{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \\n\"\n + \"\\n\",\n renderer.getTrailerHtml(\"\"));\n }\n\n /** */\n @Test\n public void testGetHeaderHtml() {\n final String keywords = \"one two three\";\n final String title = \"title\";\n final String testString = \"Content-type: text/html\\n\\n\"\n + \"\\n\"\n + \"\\n\"\n + \" \\n\"\n + \" \\n\"\n + \" \\n\"\n + \" \\n\"\n + \" \\n\"\n + \" \\n\"\n + \" \\n\"\n + \" \" + title + \"\\n\"\n + \" \\n\"\n + \" \\n\";\n assertEquals(\"Rendered string does not match expectation\",\n testString, renderer.getHeaderHtml(title, keywords));\n }\n\n /** */\n @Test\n public void testGetTrailerHtml() {\n assertEquals(\"Rendered string does not match expectation\",\n \"\\n\"\n + \"
\\n\"\n + \"
\\n\"\n + \" \\n\"\n + \" \\n\"\n + \" \\n\"\n + \" \\n\"\n + \" \\n\"\n + \"
\\n\"\n + \"

\\n\"\n + \" Maintained by \"\n + \"Richard Schoeller.
\\n\"\n + \" Created with GEDbrowser, version \"\n + GedObject.VERSION\n + \" on \" + getDateString() + \"\\n\"\n + \"

\\n\"\n + \"
\\n\"\n + \"

\\n\"\n + \"\"\n + \"\\\"[\\n\"\n + \"

\\n\"\n + \"
\\n\"\n + \"

\\n\"\n + \" \\n\"\n + \"\\n\",\n renderer.getTrailerHtml());\n }\n\n /** */\n @Test\n public void testGetTrailerHtmlIndex() {\n assertEquals(\"Rendered string does not match expectation\",\n \"\\n\"\n + \"


\\n\"\n + \"
\\n\"\n + \" \\n\"\n + \" \\n\"\n + \" \\n\"\n + \" \\n\"\n + \" \\n\"\n + \"
\\n\"\n + \"

\\n\"\n + \" Maintained by \"\n + \"Richard Schoeller.
\\n\"\n + \" Created with GEDbrowser, version \"\n + GedObject.VERSION\n + \" on \" + getDateString() + \"\\n\"\n + \"

\\n\"\n + \"
\\n\"\n + \"

\\n\"\n + \"\"\n + \"\\\"[\\n\"\n + \"

\\n\"\n + \"
\\n\"\n + \"

\\n\"\n + \" \\n\"\n + \"\\n\",\n renderer.getTrailerHtml(\"Index\"));\n }\n\n /** */\n @Test\n public void testGetHomeUrl() {\n assertEquals(\"Home URL does not match expectation\",\n homeUrl, renderer.getHomeUrl());\n }\n\n /** */\n @Test\n public void testGetName() {\n assertEquals(\"Application name does not match expectation\",\n \"gedbrowser\", renderer.getName());\n }\n\n /** */\n @Test\n public void testGetApplicationURL() {\n assertEquals(\"Application URL does not match expectation\",\n \"https://github.com/dickschoeller/gedbrowser\",\n renderer.getApplicationURL());\n }\n\n /** */\n @Test\n public void testGetMaintainerEmail() {\n assertEquals(\"Maintainer email does not match expectation\",\n \"schoeller@comcast.net\", renderer.getMaintainerEmail());\n }\n\n /** */\n @Test\n public void testGetMaintainerName() {\n assertEquals(\"Maintainer email does not match expectation\",\n \"Richard Schoeller\", renderer.getMaintainerName());\n }\n\n /** */\n @Test\n public void testGetVersion() {\n assertEquals(\"Version does not match expectation\",\n GedObject.VERSION, renderer.getVersion());\n }\n\n /**\n * Get today as a date string. This emulates what happens in the renderers.\n *\n * @return the date string.\n */\n private static String getDateString() {\n final java.util.Date javaDate = new java.util.Date();\n final String timeString = DateFormat.getDateInstance(DateFormat.LONG,\n Locale.getDefault()).format(javaDate);\n return timeString;\n }\n}\n"},"new_file":{"kind":"string","value":"gedbrowser-renderer/src/test/java/org/schoellerfamily/gedbrowser/renderer/test/ErrorRendererTest.java"},"old_contents":{"kind":"string","value":""},"message":{"kind":"string","value":"more test coverage\n"},"old_file":{"kind":"string","value":"gedbrowser-renderer/src/test/java/org/schoellerfamily/gedbrowser/renderer/test/ErrorRendererTest.java"},"subject":{"kind":"string","value":"more test coverage"},"git_diff":{"kind":"string","value":"edbrowser-renderer/src/test/java/org/schoellerfamily/gedbrowser/renderer/test/ErrorRendererTest.java\npackage org.schoellerfamily.gedbrowser.renderer.test;\n\nimport static org.junit.Assert.assertEquals;\n\nimport java.text.DateFormat;\nimport java.util.Locale;\n\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.schoellerfamily.gedbrowser.datamodel.GedObject;\nimport org.schoellerfamily.gedbrowser.renderer.ErrorRenderer;\nimport org.schoellerfamily.gedbrowser.renderer.Renderer;\n\n/**\n * @author Dick Schoeller\n */\npublic class ErrorRendererTest {\n /** */\n private String homeUrl;\n\n /**\n * Object under test.\n */\n private Renderer renderer;\n\n /** */\n @Before\n public void init() {\n homeUrl = \"http://www.schoellerfamily.org/\";\n renderer = new ErrorRenderer(new ApplicationInfoStub());\n }\n\n /** */\n @Test\n public void testGetTrailerHtmlEmpty() {\n assertEquals(\"Rendered string does not match expectation\",\n \"\\n\"\n + \"


\\n\"\n + \"
\\n\"\n + \" \\n\"\n + \" \\n\"\n + \" \\n\"\n + \" \\n\"\n + \" \\n\"\n + \"
\\n\"\n + \"

\\n\"\n + \" Maintained by \"\n + \"Richard Schoeller.
\\n\"\n + \" Created with + \"software/gedbrowser.html\\\">GEDbrowser, version \"\n + GedObject.VERSION\n + \" on \" + getDateString() + \"\\n\"\n + \"

\\n\"\n + \"
\\n\"\n + \"

\\n\"\n + \"\"\n + \" + \"class=\\\"button\\\" alt=\\\"[ Valid HTML 4.01! ]\\\" \"\n + \"height=\\\"31\\\" width=\\\"88\\\">\\n\"\n + \"

\\n\"\n + \"
\\n\"\n + \"

\\n\"\n + \" \\n\"\n + \"\\n\",\n renderer.getTrailerHtml(\"\"));\n }\n\n /** */\n @Test\n public void testGetHeaderHtml() {\n final String keywords = \"one two three\";\n final String title = \"title\";\n final String testString = \"Content-type: text/html\\n\\n\"\n + \" + \" \\\"http://www.w3.org/TR/html4/strict.dtd\\\">\\n\"\n + \"\\n\"\n + \" \\n\"\n + \" + \"content=\\\"text/html; charset=utf-8\\\">\\n\"\n + \" + \"content=\\\"gedbrowser\\\">\\n\"\n + \" + \"content=\\\"genealogy\\\">\\n\"\n + \" + \"content=\\\"genealogy gedbrowser \" + keywords + \"\\\">\\n\"\n + \" + \"content=\\\"text/css\\\">\\n\"\n + \" + \"rel=\\\"stylesheet\\\" type=\\\"text/css\\\">\\n\"\n + \" \" + title + \"\\n\"\n + \" \\n\"\n + \" \\n\";\n assertEquals(\"Rendered string does not match expectation\",\n testString, renderer.getHeaderHtml(title, keywords));\n }\n\n /** */\n @Test\n public void testGetTrailerHtml() {\n assertEquals(\"Rendered string does not match expectation\",\n \"\\n\"\n + \"


\\n\"\n + \"
\\n\"\n + \" \\n\"\n + \" \\n\"\n + \" \\n\"\n + \" \\n\"\n + \" \\n\"\n + \"
\\n\"\n + \"

\\n\"\n + \" Maintained by \"\n + \"Richard Schoeller.
\\n\"\n + \" Created with + \"software/gedbrowser.html\\\">GEDbrowser, version \"\n + GedObject.VERSION\n + \" on \" + getDateString() + \"\\n\"\n + \"

\\n\"\n + \"
\\n\"\n + \"

\\n\"\n + \"\"\n + \" + \"class=\\\"button\\\" alt=\\\"[ Valid HTML 4.01! ]\\\" \"\n + \"height=\\\"31\\\" width=\\\"88\\\">\\n\"\n + \"

\\n\"\n + \"
\\n\"\n + \"

\\n\"\n + \" \\n\"\n + \"\\n\",\n renderer.getTrailerHtml());\n }\n\n /** */\n @Test\n public void testGetTrailerHtmlIndex() {\n assertEquals(\"Rendered string does not match expectation\",\n \"\\n\"\n + \"


\\n\"\n + \"
\\n\"\n + \" \\n\"\n + \" \\n\"\n + \" \\n\"\n + \" \\n\"\n + \" \\n\"\n + \"
\\n\"\n + \"

\\n\"\n + \" Maintained by \"\n + \"Richard Schoeller.
\\n\"\n + \" Created with + \"software/gedbrowser.html\\\">GEDbrowser, version \"\n + GedObject.VERSION\n + \" on \" + getDateString() + \"\\n\"\n + \"

\\n\"\n + \"
\\n\"\n + \"

\\n\"\n + \"\"\n + \" + \"class=\\\"button\\\" alt=\\\"[ Valid HTML 4.01! ]\\\" \"\n + \"height=\\\"31\\\" width=\\\"88\\\">\\n\"\n + \"

\\n\"\n + \"
\\n\"\n + \"

\\n\"\n + \" \\n\"\n + \"\\n\",\n renderer.getTrailerHtml(\"Index\"));\n }\n\n /** */\n @Test\n public void testGetHomeUrl() {\n assertEquals(\"Home URL does not match expectation\",\n homeUrl, renderer.getHomeUrl());\n }\n\n /** */\n @Test\n public void testGetName() {\n assertEquals(\"Application name does not match expectation\",\n \"gedbrowser\", renderer.getName());\n }\n\n /** */\n @Test\n public void testGetApplicationURL() {\n assertEquals(\"Application URL does not match expectation\",\n \"https://github.com/dickschoeller/gedbrowser\",\n renderer.getApplicationURL());\n }\n\n /** */\n @Test\n public void testGetMaintainerEmail() {\n assertEquals(\"Maintainer email does not match expectation\",\n \"schoeller@comcast.net\", renderer.getMaintainerEmail());\n }\n\n /** */\n @Test\n public void testGetMaintainerName() {\n assertEquals(\"Maintainer email does not match expectation\",\n \"Richard Schoeller\", renderer.getMaintainerName());\n }\n\n /** */\n @Test\n public void testGetVersion() {\n assertEquals(\"Version does not match expectation\",\n GedObject.VERSION, renderer.getVersion());\n }\n\n /**\n * Get today as a date string. This emulates what happens in the renderers.\n *\n * @return the date string.\n */\n private static String getDateString() {\n final java.util.Date javaDate = new java.util.Date();\n final String timeString = DateFormat.getDateInstance(DateFormat.LONG,\n Locale.getDefault()).format(javaDate);\n return timeString;\n }\n}"}}},{"rowIdx":1908,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"eb809664f70f7826a3108f677995449066928aa0"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"ZuInnoTe/hadoopcryptoledger,ZuInnoTe/hadoopcryptoledger"},"new_contents":{"kind":"string","value":"/**\n * Copyright 2016 Márton Elek\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 org.zuinnote.hadoop.bitcoin.format.mapred;\n\n\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\nimport org.apache.hadoop.io.BytesWritable;\nimport org.apache.hadoop.mapred.FileSplit;\nimport org.apache.hadoop.mapred.JobConf;\nimport org.apache.hadoop.mapred.Reporter;\nimport org.zuinnote.hadoop.bitcoin.format.exception.BitcoinBlockReadException;\nimport org.zuinnote.hadoop.bitcoin.format.exception.HadoopCryptoLedgerConfigurationException;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.security.NoSuchAlgorithmException;\nimport java.util.NoSuchElementException;\n\nimport org.zuinnote.hadoop.bitcoin.format.common.*;\n\npublic class BitcoinTransactionElementRecordReader extends AbstractBitcoinRecordReader {\n\n private static final Log LOG = LogFactory.getLog(BitcoinTransactionElementRecordReader.class.getName());\n\n private int currentTransactionCounterInBlock = 0;\n\n private int currentInputCounter = 0;\n\n private int currentOutputCounter = 0;\n\n private BitcoinBlock currentBitcoinBlock;\n\n private BitcoinTransaction currentTransaction;\n\n private byte[] currentBlockHash;\n\n private byte[] currentTransactionHash;\n\n public BitcoinTransactionElementRecordReader(FileSplit split, JobConf job, Reporter reporter) throws IOException, HadoopCryptoLedgerConfigurationException, BitcoinBlockReadException {\n super(split, job, reporter);\n }\n\n /**\n * Create an empty key\n *\n * @return key\n */\n public BytesWritable createKey() {\n return new BytesWritable();\n }\n\n /**\n * Create an empty value\n *\n * @return value\n */\n public BitcoinTransactionElement createValue() {\n return new BitcoinTransactionElement();\n }\n\n\n /**\n * Read a next block.\n *\n * @param key is a 68 byte array (hashMerkleRoot, prevHashBlock, transActionCounter)\n * @param value is a deserialized Java object of class BitcoinBlock\n * @return true if next block is available, false if not\n */\n public boolean next(BytesWritable key, BitcoinTransactionElement value) throws IOException {\n // read all the blocks, if necessary a block overlapping a split´\n try {\n while (getFilePosition() <= getEnd()) { // did we already went beyond the split (remote) or do we have no further data left?\n if ((currentBitcoinBlock == null) || (currentBitcoinBlock.getTransactions().size() == currentTransactionCounterInBlock)) {\n currentBitcoinBlock = getBbr().readBlock();\n if (currentBitcoinBlock == null) return false;\n currentBlockHash = BitcoinUtil.getBlockHash(currentBitcoinBlock);\n currentTransactionCounterInBlock = 0;\n currentInputCounter = 0;\n currentOutputCounter = 0;\n readTransaction();\n }\n\n\n value.setBlockHash(currentBlockHash);\n value.setTransactionIdxInBlock(currentTransactionCounterInBlock);\n if (currentTransaction.getListOfInputs().size() > currentInputCounter) {\n value.setType(0);\n BitcoinTransactionInput input = currentTransaction.getListOfInputs().get(currentInputCounter);\n value.setIndexInTransaction(input.getPreviousTxOutIndex());\n value.setAmount(0);\n value.setTransactionHash(BitcoinUtil.reverseByteArray(input.getPrevTransactionHash()));\n value.setScript(input.getTxInScript());\n byte[] keyBytes = createUniqKey(currentTransactionHash, 0, currentInputCounter);\n key.set(keyBytes, 0, keyBytes.length);\n currentInputCounter++;\n return true;\n } else if (currentTransaction.getListOfOutputs().size() > currentOutputCounter) {\n value.setType(1);\n BitcoinTransactionOutput output = currentTransaction.getListOfOutputs().get(currentOutputCounter);\n value.setAmount(output.getValue());\n value.setIndexInTransaction(currentOutputCounter);\n value.setTransactionHash(BitcoinUtil.reverseByteArray(currentTransactionHash));\n value.setScript(output.getTxOutScript());\n byte[] keyBytes = createUniqKey(currentTransactionHash, 1, currentOutputCounter);\n key.set(keyBytes, 0, keyBytes.length);\n\n //return an output\n currentOutputCounter++;\n return true;\n } else {\n currentInputCounter = 0;\n currentOutputCounter = 0;\n currentTransactionCounterInBlock++;\n readTransaction();\n continue;\n }\n }\n return false;\n } catch (NoSuchElementException e) {\n\t LOG.error(e);\n } catch (BitcoinBlockReadException e) {\n\t LOG.error(e);\n } catch (NoSuchAlgorithmException e) {\n LOG.error(e);\n }\n }\n\n private void readTransaction() throws IOException, NoSuchAlgorithmException {\n if (currentBitcoinBlock.getTransactions().size() > currentTransactionCounterInBlock) {\n currentTransaction = currentBitcoinBlock.getTransactions().get(currentTransactionCounterInBlock);\n currentTransactionHash = BitcoinUtil.getTransactionHash(currentTransaction);\n }\n }\n\n private byte[] createUniqKey(byte[] transactionHash, int type, int counter) {\n byte[] result = new byte[transactionHash.length + 1 + 4];\n System.arraycopy(transactionHash, 0, result, 0, transactionHash.length);\n System.arraycopy(new byte[]{(byte) type}, 0, result, transactionHash.length, 1);\n System.arraycopy(ByteBuffer.allocate(4).putInt(counter).array(), 0, result, transactionHash.length + 1, 4);\n return result;\n }\n\n\n}\n"},"new_file":{"kind":"string","value":"inputformat/src/main/java/org/zuinnote/hadoop/bitcoin/format/mapred/BitcoinTransactionElementRecordReader.java"},"old_contents":{"kind":"string","value":"/**\n * Copyright 2016 Márton Elek\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 org.zuinnote.hadoop.bitcoin.format.mapred;\n\n\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\nimport org.apache.hadoop.io.BytesWritable;\nimport org.apache.hadoop.mapred.FileSplit;\nimport org.apache.hadoop.mapred.JobConf;\nimport org.apache.hadoop.mapred.Reporter;\nimport org.zuinnote.hadoop.bitcoin.format.exception.BitcoinBlockReadException;\nimport org.zuinnote.hadoop.bitcoin.format.exception.HadoopCryptoLedgerConfigurationException;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.security.NoSuchAlgorithmException;\nimport java.util.NoSuchElementException;\n\nimport org.zuinnote.hadoop.bitcoin.format.common.*;\n\npublic class BitcoinTransactionElementRecordReader extends AbstractBitcoinRecordReader {\n\n private static final Log LOG = LogFactory.getLog(BitcoinTransactionElementRecordReader.class.getName());\n\n private int currentTransactionCounterInBlock = 0;\n\n private int currentInputCounter = 0;\n\n private int currentOutputCounter = 0;\n\n private BitcoinBlock currentBitcoinBlock;\n\n private BitcoinTransaction currentTransaction;\n\n private byte[] currentBlockHash;\n\n private byte[] currentTransactionHash;\n\n public BitcoinTransactionElementRecordReader(FileSplit split, JobConf job, Reporter reporter) throws IOException, HadoopCryptoLedgerConfigurationException, BitcoinBlockReadException {\n super(split, job, reporter);\n }\n\n /**\n * Create an empty key\n *\n * @return key\n */\n public BytesWritable createKey() {\n return new BytesWritable();\n }\n\n /**\n * Create an empty value\n *\n * @return value\n */\n public BitcoinTransactionElement createValue() {\n return new BitcoinTransactionElement();\n }\n\n\n /**\n * Read a next block.\n *\n * @param key is a 68 byte array (hashMerkleRoot, prevHashBlock, transActionCounter)\n * @param value is a deserialized Java object of class BitcoinBlock\n * @return true if next block is available, false if not\n */\n public boolean next(BytesWritable key, BitcoinTransactionElement value) throws IOException {\n // read all the blocks, if necessary a block overlapping a split´\n try {\n while (getFilePosition() <= getEnd()) { // did we already went beyond the split (remote) or do we have no further data left?\n if ((currentBitcoinBlock == null) || (currentBitcoinBlock.getTransactions().size() == currentTransactionCounterInBlock)) {\n currentBitcoinBlock = getBbr().readBlock();\n if (currentBitcoinBlock == null) return false;\n currentBlockHash = BitcoinUtil.getBlockHash(currentBitcoinBlock);\n currentTransactionCounterInBlock = 0;\n currentInputCounter = 0;\n currentOutputCounter = 0;\n readTransaction();\n }\n\n\n value.setBlockHash(currentBlockHash);\n value.setTransactionIdxInBlock(currentTransactionCounterInBlock);\n if (currentTransaction.getListOfInputs().size() > currentInputCounter) {\n value.setType(0);\n BitcoinTransactionInput input = currentTransaction.getListOfInputs().get(currentInputCounter);\n value.setIndexInTransaction(input.getPreviousTxOutIndex());\n value.setAmount(0);\n value.setTransactionHash(BitcoinUtil.reverseByteArray(input.getPrevTransactionHash()));\n value.setScript(input.getTxInScript());\n byte[] keyBytes = createUniqKey(currentTransactionHash, 0, currentInputCounter);\n key.set(keyBytes, 0, keyBytes.length);\n currentInputCounter++;\n return true;\n } else if (currentTransaction.getListOfOutputs().size() > currentOutputCounter) {\n value.setType(1);\n BitcoinTransactionOutput output = currentTransaction.getListOfOutputs().get(currentOutputCounter);\n value.setAmount(output.getValue());\n value.setIndexInTransaction(currentOutputCounter);\n value.setTransactionHash(BitcoinUtil.reverseByteArray(currentTransactionHash));\n value.setScript(output.getTxOutScript());\n byte[] keyBytes = createUniqKey(currentTransactionHash, 1, currentOutputCounter);\n key.set(keyBytes, 0, keyBytes.length);\n\n //return an output\n currentOutputCounter++;\n return true;\n } else {\n currentInputCounter = 0;\n currentOutputCounter = 0;\n currentTransactionCounterInBlock++;\n readTransaction();\n continue;\n }\n }\n return false;\n } catch (NoSuchElementException e) {\n throw new RuntimeException(e);\n } catch (BitcoinBlockReadException e) {\n throw new RuntimeException(e);\n } catch (NoSuchAlgorithmException e) {\n throw new RuntimeException(e);\n }\n }\n\n private void readTransaction() throws IOException, NoSuchAlgorithmException {\n if (currentBitcoinBlock.getTransactions().size() > currentTransactionCounterInBlock) {\n currentTransaction = currentBitcoinBlock.getTransactions().get(currentTransactionCounterInBlock);\n currentTransactionHash = BitcoinUtil.getTransactionHash(currentTransaction);\n }\n }\n\n private byte[] createUniqKey(byte[] transactionHash, int type, int counter) {\n byte[] result = new byte[transactionHash.length + 1 + 4];\n System.arraycopy(transactionHash, 0, result, 0, transactionHash.length);\n System.arraycopy(new byte[]{(byte) type}, 0, result, transactionHash.length, 1);\n System.arraycopy(ByteBuffer.allocate(4).putInt(counter).array(), 0, result, transactionHash.length + 1, 4);\n return result;\n }\n\n\n}\n"},"message":{"kind":"string","value":"Fixing Sonarqube issue\n"},"old_file":{"kind":"string","value":"inputformat/src/main/java/org/zuinnote/hadoop/bitcoin/format/mapred/BitcoinTransactionElementRecordReader.java"},"subject":{"kind":"string","value":"Fixing Sonarqube issue"},"git_diff":{"kind":"string","value":"nputformat/src/main/java/org/zuinnote/hadoop/bitcoin/format/mapred/BitcoinTransactionElementRecordReader.java\n }\n return false;\n } catch (NoSuchElementException e) {\n throw new RuntimeException(e);\n\t LOG.error(e);\n } catch (BitcoinBlockReadException e) {\n throw new RuntimeException(e);\n\t LOG.error(e);\n } catch (NoSuchAlgorithmException e) {\n throw new RuntimeException(e);\n LOG.error(e);\n }\n }\n "}}},{"rowIdx":1909,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"89c35aabf87d05c2f4aa19c75a8811e866fd612f"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"OpenHFT/Chronicle-Queue,OpenHFT/Chronicle-Queue"},"new_contents":{"kind":"string","value":"/*\n * Copyright 2016-2020 Chronicle Software\n *\n * https://chronicle.software\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 net.openhft.chronicle.queue;\n\nimport net.openhft.chronicle.core.io.Closeable;\nimport net.openhft.chronicle.core.time.TimeProvider;\nimport net.openhft.chronicle.queue.impl.single.SingleChronicleQueueBuilder;\nimport net.openhft.chronicle.wire.BinaryMethodWriterInvocationHandler;\nimport net.openhft.chronicle.wire.VanillaMethodWriterBuilder;\nimport net.openhft.chronicle.wire.WireType;\nimport org.jetbrains.annotations.NotNull;\n\nimport java.io.File;\nimport java.io.OutputStream;\nimport java.io.OutputStreamWriter;\nimport java.io.Writer;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Path;\nimport java.util.stream.Stream;\n\n/**\n * Chronicle (in a generic sense) is a Java project focused on building a persisted low\n * latency messaging framework for high performance and critical applications.\n *

Using non-heap storage options Chronicle provides a processing environment where\n * applications does not suffer from GarbageCollection. GarbageCollection (GC) may\n * slow down your critical operations non-deterministically at any time.. In order to avoid\n * non-determinism and escape from GC delays off-heap memory solutions are addressed. The main idea\n * is to manage your memory manually so does not suffer from GC. Chronicle behaves like a management\n * interface over off-heap memory so you can build your own solutions over it.\n *

Chronicle uses RandomAccessFiles while managing memory and this choice brings lots of\n * possibility. Random access files permit non-sequential, or random, access to a file's contents.\n * To access a file randomly, you open the file, seek a particular location, and read from or\n * writeBytes to that file. RandomAccessFiles can be seen as \"large\" C-type byte arrays that you can\n * access any random index \"directly\" using pointers. File portions can be used as ByteBuffers if\n * the portion is mapped into memory.\n *

{@link ChronicleQueue} (now in the specific sense) is the main interface for management and\n * can be seen as the \"Collection class\" of the Chronicle environment. You will reserve a\n * portion of memory and then put/fetch/update records using the {@link ChronicleQueue}\n * interface.

\n *

{@link ExcerptCommon} is the main data container in a {@link ChronicleQueue}, each Chronicle\n * is composed of Excerpts. Putting data to a queue means starting a new Excerpt, writing data into\n * it and finishing the Excerpt at the upper.

\n *

While {@link ExcerptCommon} is a generic purpose container allowing for remote access, it also\n * has more specialized counterparts for sequential operations. See {@link ExcerptTailer} and {@link\n * ExcerptAppender}

\n *\n * @author peter.lawrey\n */\npublic interface ChronicleQueue extends Closeable {\n int TEST_BLOCK_SIZE = 64 * 1024; // smallest safe block size for Windows 8+\n\n /**\n * Creates and returns a new {@link ChronicleQueue} that will be backed by\n * files located in the directory named by the provided {@code pathName}.\n *\n * @param pathName of the directory to use for storing the queue\n * @return a new {@link ChronicleQueue} that will be stored\n * in the directory given by the provided {@code pathName}\n * @throws NullPointerException if the provided {@code pathName} is {@code null}.\n */\n static ChronicleQueue single(@NotNull String pathName) {\n return SingleChronicleQueueBuilder.single(pathName).build();\n }\n\n /**\n * Creates and returns a new {@link SingleChronicleQueueBuilder}.\n *

\n * The builder can be used to build a ChronicleQueue.\n *\n * @return a new {@link SingleChronicleQueueBuilder}\n *\n */\n static SingleChronicleQueueBuilder singleBuilder() {\n return SingleChronicleQueueBuilder.single();\n }\n\n /**\n * Creates and returns a new {@link SingleChronicleQueueBuilder} that will\n * be pre-configured to use files located in the directory named by the\n * provided {@code pathName}.\n *\n * @param pathName of the directory to pre-configure for storing the queue\n * @return a new {@link SingleChronicleQueueBuilder} that will\n * be pre-configured to use files located in the directory named by the\n * provided {@code pathName}\n * @throws NullPointerException if the provided {@code pathName} is {@code null}.\n */\n static SingleChronicleQueueBuilder singleBuilder(@NotNull String pathName) {\n return SingleChronicleQueueBuilder.binary(pathName);\n }\n\n /**\n * Creates and returns a new {@link SingleChronicleQueueBuilder} that will\n * be pre-configured to use files located in the directory of the\n * provided {@code path}.\n *\n * @param path of the directory to pre-configure for storing the queue\n * @return a new {@link SingleChronicleQueueBuilder} that will\n * be pre-configured to use files located in the directory named by the\n * provided {@code pathName}\n * @throws NullPointerException if the provided {@code path} is {@code null}.\n */\n static SingleChronicleQueueBuilder singleBuilder(@NotNull File path) {\n return SingleChronicleQueueBuilder.binary(path);\n }\n\n /**\n * Creates and returns a new {@link SingleChronicleQueueBuilder} that will\n * be pre-configured to use files located in the directory of the\n * provided {@code path}.\n *\n * @param path of the directory to pre-configure for storing the queue\n * @return a new {@link SingleChronicleQueueBuilder} that will\n * be pre-configured to use files located in the directory named by the\n * provided {@code pathName}\n * @throws NullPointerException if the provided {@code path} is {@code null}.\n */\n static SingleChronicleQueueBuilder singleBuilder(@NotNull Path path) {\n return SingleChronicleQueueBuilder.binary(path);\n }\n\n /**\n * Creates and returns a new ExcerptTailer for this ChronicleQueue.\n * \n * Tailers are NOT thread-safe. Sharing a Tailer across threads will lead to errors and unpredictable behaviour.\n * \n *\n * The tailor is created at the start, so unless you are using named tailors,\n * this method is the same as calling `net.openhft.chronicle.queue.ChronicleQueue#createTailer(java.lang.String).toStart()`\n *\n * @return a new ExcerptTailer to read sequentially.\n * @see #createTailer(String)\n */\n @NotNull\n ExcerptTailer createTailer();\n\n /**\n * Creates and returns a new ExcerptTailer for this ChronicleQueue with the given unique {@code id}.\n *

\n * The id is used to persistently store the latest index for the trailer. Any new Trailer with\n * a previously used id will continue where the old one left off.\n * \n * Tailers are NOT thread-safe. Sharing a Tailer across threads will lead to errors and unpredictable behaviour.\n * \n *

\n * If the provided {@code id} is {@code null}, the Trailer will be unnamed and this is\n * equivalent to invoking {@link #createTailer()}.\n *\n *\n * @param id unique id for a tailer which uses to track where it was up to\n * @return a new ExcerptTailer for this ChronicleQueue with the given unique {@code id}\n * @see #createTailer()\n */\n @NotNull\n default ExcerptTailer createTailer(String id) {\n throw new UnsupportedOperationException(\"not currently supported in this implementation.\");\n }\n\n /**\n * Returns a ExcerptAppender for this ChronicleQueue that is local to the current Thread.\n *

\n * An Appender can be used to store new excerpts sequentially to the queue.\n *

\n * \n * Appenders are NOT thread-safe. Sharing an Appender across threads will lead to errors and unpredictable behaviour.\n * \n *

\n * This method returns a {@link ThreadLocal} appender, so does not produce any garbage, hence it's safe to simply call\n * this method every time an appender is needed.\n *\n * @return Returns a ExcerptAppender for this ChronicleQueue that is local to the current Thread\n */\n @NotNull\n ExcerptAppender acquireAppender();\n\n /**\n * @deprecated to be remove in version 4.6 or later use {@link ChronicleQueue#acquireAppender()}\n */\n @NotNull\n @Deprecated\n default ExcerptAppender createAppender() {\n return acquireAppender();\n }\n\n /**\n * Returns the lowest valid index available for this ChronicleQueue, or {@link Long#MAX_VALUE}\n * if no such index exists.\n *\n * @return the lowest valid index available for this ChronicleQueue, or {@link Long#MAX_VALUE}\n * if no such index exists\n */\n long firstIndex();\n\n /**\n * Returns the {@link WireType} used for this ChronicleQueue.\n *

\n * For example, the WireType could be WireTypes.TEXT or WireTypes.BINARY.\n *\n * @return Returns the wire type used for this ChronicleQueue\n * @see WireType\n */\n @NotNull\n WireType wireType();\n\n /**\n * Removes all the excerpts in the current ChronicleQueue.\n */\n void clear();\n\n /**\n * Returns the base directory where ChronicleQueue stores its data.\n *\n * @return the base directory where ChronicleQueue stores its data\n */\n @NotNull\n File file();\n\n /**\n * Returns the absolute path of the base directory where ChronicleQueue stores its data.\n *

\n * This value might be cached, as getAbsolutePath is expensive\n *\n * @return the absolute path of the base directory where ChronicleQueue stores its data\n */\n @NotNull\n default String fileAbsolutePath() {\n return file().getAbsolutePath();\n }\n\n /**\n * Creates and returns a new String representation of this ChronicleQueue in YAML-format.\n *\n * @return a new String representation of this ChronicleQueue in YAML-format\n */\n @NotNull\n String dump();\n\n /**\n * Dumps a representation of this ChronicleQueue to the provided {@code writer} in YAML-format.\n * Dumping will be made from the provided (@code fromIndex) (inclusive) to the provided\n * {@code toIndex} (inclusive).\n *\n * @param writer to write to\n * @param fromIndex first index (inclusive)\n * @param toIndex last index (inclusive)\n * @throws NullPointerException if the provided {@code writer} is {@code null}\n */\n void dump(Writer writer, long fromIndex, long toIndex);\n\n /**\n * Dumps a representation of this ChronicleQueue to the provided {@code stream} in YAML-format.\n * Dumping will be made from the provided (@code fromIndex) (inclusive) to the provided\n * {@code toIndex} (inclusive).\n *\n * @param stream to write to\n * @param fromIndex first index (inclusive)\n * @param toIndex last index (inclusive)\n * @throws NullPointerException if the provided {@code writer} is {@code null}\n */\n default void dump(@NotNull OutputStream stream, long fromIndex, long toIndex) {\n dump(new OutputStreamWriter(stream, StandardCharsets.UTF_8), fromIndex, toIndex);\n }\n\n /**\n * Returns the source id.\n *

\n * The source id is non-negative.\n *\n * @return the source id\n */\n int sourceId();\n\n/**\n * Creates and returns a new writer proxy for the given interface {@code tclass} and the given {@code additional }\n * interfaces.\n *

\n * When methods are invoked on the returned T object, messages will be put in the queue.\n * \n * Writers are NOT thread-safe. Sharing a Writer across threads will lead to errors and unpredictable behaviour.\n * \n *\n * @param tClass of the main interface to be implemented\n * @param additional interfaces to be implemented\n * @param type parameter of the main interface\n * @return a new proxy for the given interface {@code tclass} and the given {@code additional }\n * interfaces\n * @throws NullPointerException if any of the provided parameters are {@code null}.\n */\n default T methodWriter(@NotNull Class tClass, Class... additional) {\n VanillaMethodWriterBuilder builder = methodWriterBuilder(tClass);\n Stream.of(additional).forEach(builder::addInterface);\n return builder.build();\n }\n /**\n * Creates and returns a new writer proxy for the given interface {@code tclass}.\n *

\n * When methods are invoked on the returned T object, messages will be put in the queue.\n *

\n * \n * Writers are NOT thread-safe. Sharing a Writer across threads will lead to errors and unpredictable behaviour.\n * \n *\n * @param tClass of the main interface to be implemented\n * @param type parameter of the main interface\n * @return a new proxy for the given interface {@code tclass}\n *\n * @throws NullPointerException if the provided parameter is {@code null}.\n */\n @NotNull\n default VanillaMethodWriterBuilder methodWriterBuilder(@NotNull Class tClass) {\n VanillaMethodWriterBuilder builder = new VanillaMethodWriterBuilder<>(tClass,\n wireType(),\n () -> new BinaryMethodWriterInvocationHandler(false, this::acquireAppender));\n builder.marshallableOut(acquireAppender());\n return builder;\n }\n\n /**\n * Returns the {@link RollCycle} for this ChronicleQueue.\n *\n * @return the {@link RollCycle} for this ChronicleQueue\n * @see RollCycle\n */\n RollCycle rollCycle();\n\n /**\n * Returns the {@link TimeProvider} for this ChronicleQueue.\n *\n * @return the {@link TimeProvider} for this ChronicleQueue\n * @see TimeProvider\n */\n TimeProvider time();\n\n /**\n * Returns the Delta Checkpoint Interval for this ChronicleQueue.\n *

\n * The value returned is always a power of two.\n *\n * @return the Delta Checkpoint Interval for this ChronicleQueue\n */\n int deltaCheckpointInterval();\n\n /**\n * Returns the last index that was replicated to a remote host. If no\n * such index exists, returns -1.\n *

\n * This method is only applicable for replicating queues.\n * @return the last index that was replicated to a remote host\n */\n long lastIndexReplicated();\n\n /**\n * Returns the last index that was replicated and acknowledged by all remote hosts. If no\n * such index exists, returns -1.\n *

\n * This method is only applicable for replicating queues.\n * @return the last index that was replicated and acknowledged by all remote hosts\n */\n long lastAcknowledgedIndexReplicated();\n\n /**\n * Sets the last index that has been sent to a remote host.\n *\n * @param lastIndex last index that has been sent to the remote host.\n * @see #lastIndexReplicated()\n */\n void lastIndexReplicated(long lastIndex);\n\n /**\n * Sets the last index that has been sent to a remote host.\n *\n * @param lastAcknowledgedIndexReplicated last acknowledged index that has been sent to the remote host(s).\n * @see #lastAcknowledgedIndexReplicated()\n */\n void lastAcknowledgedIndexReplicated(long lastAcknowledgedIndexReplicated);\n\n /**\n * Refreshed this ChronicleQueue's view of the directory used for storing files.\n *

\n * Invoke this method if you delete file from a chronicle-queue directory\n *

\n * The problem solved by this is that we cache the structure of the queue directory in order to reduce\n * file system adds latency. Calling this method, after deleting .cq4 files, will update the internal\n * caches accordingly,\n */\n void refreshDirectoryListing();\n\n /**\n * Creates and returns a new String representation of this ChronicleQueue's last header in YAML-format.\n *\n * @return a new String representation of this ChronicleQueue's last header in YAML-format\n */\n @NotNull\n String dumpLastHeader();\n}\n"},"new_file":{"kind":"string","value":"src/main/java/net/openhft/chronicle/queue/ChronicleQueue.java"},"old_contents":{"kind":"string","value":"/*\n * Copyright 2016-2020 Chronicle Software\n *\n * https://chronicle.software\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 net.openhft.chronicle.queue;\n\nimport net.openhft.chronicle.core.io.Closeable;\nimport net.openhft.chronicle.core.time.TimeProvider;\nimport net.openhft.chronicle.queue.impl.single.SingleChronicleQueueBuilder;\nimport net.openhft.chronicle.wire.BinaryMethodWriterInvocationHandler;\nimport net.openhft.chronicle.wire.VanillaMethodWriterBuilder;\nimport net.openhft.chronicle.wire.WireType;\nimport org.jetbrains.annotations.NotNull;\n\nimport java.io.File;\nimport java.io.OutputStream;\nimport java.io.OutputStreamWriter;\nimport java.io.Writer;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Path;\nimport java.util.stream.Stream;\n\n/**\n * Chronicle (in a generic sense) is a Java project focused on building a persisted low\n * latency messaging framework for high performance and critical applications.\n *

Using non-heap storage options Chronicle provides a processing environment where\n * applications does not suffer from GarbageCollection. GarbageCollection (GC) may\n * slow down your critical operations non-deterministically at any time.. In order to avoid\n * non-determinism and escape from GC delays off-heap memory solutions are addressed. The main idea\n * is to manage your memory manually so does not suffer from GC. Chronicle behaves like a management\n * interface over off-heap memory so you can build your own solutions over it.\n *

Chronicle uses RandomAccessFiles while managing memory and this choice brings lots of\n * possibility. Random access files permit non-sequential, or random, access to a file's contents.\n * To access a file randomly, you open the file, seek a particular location, and read from or\n * writeBytes to that file. RandomAccessFiles can be seen as \"large\" C-type byte arrays that you can\n * access any random index \"directly\" using pointers. File portions can be used as ByteBuffers if\n * the portion is mapped into memory.\n *

{@link ChronicleQueue} (now in the specific sense) is the main interface for management and\n * can be seen as the \"Collection class\" of the Chronicle environment. You will reserve a\n * portion of memory and then put/fetch/update records using the {@link ChronicleQueue}\n * interface.

\n *

{@link ExcerptCommon} is the main data container in a {@link ChronicleQueue}, each Chronicle\n * is composed of Excerpts. Putting data to a queue means starting a new Excerpt, writing data into\n * it and finishing the Excerpt at the upper.

\n *

While {@link ExcerptCommon} is a generic purpose container allowing for remote access, it also\n * has more specialized counterparts for sequential operations. See {@link ExcerptTailer} and {@link\n * ExcerptAppender}

\n *\n * @author peter.lawrey\n */\npublic interface ChronicleQueue extends Closeable {\n int TEST_BLOCK_SIZE = 64 * 1024; // smallest safe block size for Windows 8+\n\n /**\n * Creates and returns a new {@link ChronicleQueue} that will be backed by\n * files located in the directory named by the provided {@code pathName}.\n *\n * @param pathName of the directory to use for storing the queue\n * @return a new {@link ChronicleQueue} that will be stored\n * in the directory given by the provided {@code pathName}\n * @throws NullPointerException if the provided {@code pathName} is {@code null}.\n */\n static ChronicleQueue single(@NotNull String pathName) {\n return SingleChronicleQueueBuilder.single(pathName).build();\n }\n\n /**\n * Creates and returns a new {@link SingleChronicleQueueBuilder}.\n *

\n * The builder can be used to build a ChronicleQueue.\n *\n * @return a new {@link SingleChronicleQueueBuilder}\n *\n */\n static SingleChronicleQueueBuilder singleBuilder() {\n return SingleChronicleQueueBuilder.single();\n }\n\n /**\n * Creates and returns a new {@link SingleChronicleQueueBuilder} that will\n * be pre-configured to use files located in the directory named by the\n * provided {@code pathName}.\n *\n * @param pathName of the directory to pre-configure for storing the queue\n * @return a new {@link SingleChronicleQueueBuilder} that will\n * be pre-configured to use files located in the directory named by the\n * provided {@code pathName}\n * @throws NullPointerException if the provided {@code pathName} is {@code null}.\n */\n static SingleChronicleQueueBuilder singleBuilder(@NotNull String pathName) {\n return SingleChronicleQueueBuilder.binary(pathName);\n }\n\n /**\n * Creates and returns a new {@link SingleChronicleQueueBuilder} that will\n * be pre-configured to use files located in the directory of the\n * provided {@code path}.\n *\n * @param path of the directory to pre-configure for storing the queue\n * @return a new {@link SingleChronicleQueueBuilder} that will\n * be pre-configured to use files located in the directory named by the\n * provided {@code pathName}\n * @throws NullPointerException if the provided {@code path} is {@code null}.\n */\n static SingleChronicleQueueBuilder singleBuilder(@NotNull File path) {\n return SingleChronicleQueueBuilder.binary(path);\n }\n\n /**\n * Creates and returns a new {@link SingleChronicleQueueBuilder} that will\n * be pre-configured to use files located in the directory of the\n * provided {@code path}.\n *\n * @param path of the directory to pre-configure for storing the queue\n * @return a new {@link SingleChronicleQueueBuilder} that will\n * be pre-configured to use files located in the directory named by the\n * provided {@code pathName}\n * @throws NullPointerException if the provided {@code path} is {@code null}.\n */\n static SingleChronicleQueueBuilder singleBuilder(@NotNull Path path) {\n return SingleChronicleQueueBuilder.binary(path);\n }\n\n /**\n * Creates and returns a new ExcerptTailer for this ChronicleQueue.\n * \n * Tailers are NOT thread-safe. Sharing a Tailer across threads will lead to errors and unpredictable behaviour.\n * \n *\n * The tailor is created at the start, so unless you are using named tailors,\n * this method is the same as calling `net.openhft.chronicle.queue.ChronicleQueue#createTailer(java.lang.String).toStart()`\n *\n * @return a new ExcerptTailer to read sequentially.\n * @see #createTailer(String)\n */\n @NotNull\n ExcerptTailer createTailer();\n\n /**\n * Creates and returns a new ExcerptTailer for this ChronicleQueue with the given unique {@code id}.\n *

\n * The id is used to persistently store the latest index for the trailer. Any new Trailer with\n * a previously used id will continue where the old one left off.\n * \n * Tailers are NOT thread-safe. Sharing a Tailer across threads will lead to errors and unpredictable behaviour.\n * \n *

\n * If the provided {@code id} is {@code null}, the Trailer will be unnamed and this is\n * equivalent to invoking {@link #createTailer()}.\n *\n *\n * @param id unique id for a tailer which uses to track where it was up to\n * @return a new ExcerptTailer for this ChronicleQueue with the given unique {@code id}\n * @see #createTailer()\n */\n @NotNull\n default ExcerptTailer createTailer(String id) {\n throw new UnsupportedOperationException(\"not currently supported in this implementation.\");\n }\n\n /**\n * Returns a ExcerptAppender for this ChronicleQueue that is local to the current Thread.\n *

\n * An Appender can be used to store new excerpts sequentially to the queue.\n *

\n * \n * Appenders are NOT thread-safe. Sharing an Appender across threads will lead to errors and unpredictable behaviour.\n * \n *

\n * This method returns a {@link ThreadLocal} appender, so does not produce any garbage, hence it's safe to simply call\n * this method every time an appender is needed.\n *\n * @return Returns a ExcerptAppender for this ChronicleQueue that is local to the current Thread\n */\n @NotNull\n ExcerptAppender acquireAppender();\n\n /**\n * @deprecated to be remove in version 4.6 or later use {@link ChronicleQueue#acquireAppender()}\n */\n @NotNull\n @Deprecated\n default ExcerptAppender createAppender() {\n return acquireAppender();\n }\n\n /**\n * Returns the lowest valid index available for this ChronicleQueue, or {@link Long#MAX_VALUE}\n * if no such index exists.\n *\n * @return the lowest valid index available for this ChronicleQueue, or {@link Long#MAX_VALUE}\n * if no such index exists\n */\n long firstIndex();\n\n /**\n * Returns the {@link WireType} used for this ChronicleQueue.\n *

\n * For example, the WireType could be WireTypes.TEXT or WireTypes.BINARY.\n *\n * @return Returns the wire type used for this ChronicleQueue\n * @see WireType\n */\n @NotNull\n WireType wireType();\n\n /**\n * Removes all the excerpts in the current ChronicleQueue.\n */\n void clear();\n\n /**\n * Returns the base directory where ChronicleQueue stores its data.\n *\n * @return the base directory where ChronicleQueue stores its data\n */\n @NotNull\n File file();\n\n /**\n * Returns the absolute path of the base directory where ChronicleQueue stores its data.\n *

\n * This value might be cached, as getAbsolutePath is expensive\n *\n * @return the absolute path of the base directory where ChronicleQueue stores its data\n */\n @NotNull\n default String fileAbsolutePath() {\n return file().getAbsolutePath();\n }\n\n /**\n * Creates and returns a new String representation of this ChronicleQueue in YAML-format.\n *\n * @return a new String representation of this ChronicleQueue in YAML-format\n */\n @NotNull\n String dump();\n\n /**\n * Dumps a representation of this ChronicleQueue to the provided {@code writer} in YAML-format.\n * Dumping will be made from the provided (@code fromIndex) (inclusive) to the provided\n * {@code toIndex} (inclusive).\n *\n * @param writer to write to\n * @param fromIndex first index (inclusive)\n * @param toIndex last index (inclusive)\n * @throws NullPointerException if the provided {@code writer} is {@code null}\n */\n void dump(Writer writer, long fromIndex, long toIndex);\n\n /**\n * Dumps a representation of this ChronicleQueue to the provided {@code stream} in YAML-format.\n * Dumping will be made from the provided (@code fromIndex) (inclusive) to the provided\n * {@code toIndex} (inclusive).\n *\n * @param stream to write to\n * @param fromIndex first index (inclusive)\n * @param toIndex last index (inclusive)\n * @throws NullPointerException if the provided {@code writer} is {@code null}\n */\n default void dump(@NotNull OutputStream stream, long fromIndex, long toIndex) {\n dump(new OutputStreamWriter(stream, StandardCharsets.UTF_8), fromIndex, toIndex);\n }\n\n /**\n * Returns the source id.\n *

\n * The source id is non-negative.\n *\n * @return the source id\n */\n int sourceId();\n\n/**\n * Creates and returns a new writer proxy for the given interface {@code tclass} and the given {@code additional }\n * interfaces.\n *

\n * When methods are invoked on the returned T object, messages will be put in the queue.\n * \n * Writers are NOT thread-safe. Sharing a Writer across threads will lead to errors and unpredictable behaviour.\n * \n *\n * @param tClass of the main interface to be implemented\n * @param additional interfaces to be implemented\n * @param type parameter of the main interface\n * @return a new proxy for the given interface {@code tclass} and the given {@code additional }\n * interfaces\n * @throws NullPointerException if any of the provided parameters are {@code null}.\n */\n default T methodWriter(@NotNull Class tClass, Class... additional) {\n VanillaMethodWriterBuilder builder = methodWriterBuilder(tClass);\n Stream.of(additional).forEach(builder::addInterface);\n return builder.build();\n }\n /**\n * Creates and returns a new writer proxy for the given interface {@code tclass}.\n *

\n * When methods are invoked on the returned T object, messages will be put in the queue.\n *

\n * \n * Writers are NOT thread-safe. Sharing a Writer across threads will lead to errors and unpredictable behaviour.\n * \n *\n * @param tClass of the main interface to be implemented\n * @param type parameter of the main interface\n * @return a new proxy for the given interface {@code tclass}\n *\n * @throws NullPointerException if the provided parameter is {@code null}.\n */\n @NotNull\n default VanillaMethodWriterBuilder methodWriterBuilder(@NotNull Class tClass) {\n return new VanillaMethodWriterBuilder(tClass,\n wireType(),\n () -> new BinaryMethodWriterInvocationHandler(false, this::acquireAppender));\n }\n\n /**\n * Returns the {@link RollCycle} for this ChronicleQueue.\n *\n * @return the {@link RollCycle} for this ChronicleQueue\n * @see RollCycle\n */\n RollCycle rollCycle();\n\n /**\n * Returns the {@link TimeProvider} for this ChronicleQueue.\n *\n * @return the {@link TimeProvider} for this ChronicleQueue\n * @see TimeProvider\n */\n TimeProvider time();\n\n /**\n * Returns the Delta Checkpoint Interval for this ChronicleQueue.\n *

\n * The value returned is always a power of two.\n *\n * @return the Delta Checkpoint Interval for this ChronicleQueue\n */\n int deltaCheckpointInterval();\n\n /**\n * Returns the last index that was replicated to a remote host. If no\n * such index exists, returns -1.\n *

\n * This method is only applicable for replicating queues.\n * @return the last index that was replicated to a remote host\n */\n long lastIndexReplicated();\n\n /**\n * Returns the last index that was replicated and acknowledged by all remote hosts. If no\n * such index exists, returns -1.\n *

\n * This method is only applicable for replicating queues.\n * @return the last index that was replicated and acknowledged by all remote hosts\n */\n long lastAcknowledgedIndexReplicated();\n\n /**\n * Sets the last index that has been sent to a remote host.\n *\n * @param lastIndex last index that has been sent to the remote host.\n * @see #lastIndexReplicated()\n */\n void lastIndexReplicated(long lastIndex);\n\n /**\n * Sets the last index that has been sent to a remote host.\n *\n * @param lastAcknowledgedIndexReplicated last acknowledged index that has been sent to the remote host(s).\n * @see #lastAcknowledgedIndexReplicated()\n */\n void lastAcknowledgedIndexReplicated(long lastAcknowledgedIndexReplicated);\n\n /**\n * Refreshed this ChronicleQueue's view of the directory used for storing files.\n *

\n * Invoke this method if you delete file from a chronicle-queue directory\n *

\n * The problem solved by this is that we cache the structure of the queue directory in order to reduce\n * file system adds latency. Calling this method, after deleting .cq4 files, will update the internal\n * caches accordingly,\n */\n void refreshDirectoryListing();\n\n /**\n * Creates and returns a new String representation of this ChronicleQueue's last header in YAML-format.\n *\n * @return a new String representation of this ChronicleQueue's last header in YAML-format\n */\n @NotNull\n String dumpLastHeader();\n}\n"},"message":{"kind":"string","value":"added marshallableOut\n"},"old_file":{"kind":"string","value":"src/main/java/net/openhft/chronicle/queue/ChronicleQueue.java"},"subject":{"kind":"string","value":"added marshallableOut"},"git_diff":{"kind":"string","value":"rc/main/java/net/openhft/chronicle/queue/ChronicleQueue.java\n */\n @NotNull\n default VanillaMethodWriterBuilder methodWriterBuilder(@NotNull Class tClass) {\n return new VanillaMethodWriterBuilder(tClass,\n VanillaMethodWriterBuilder builder = new VanillaMethodWriterBuilder<>(tClass,\n wireType(),\n () -> new BinaryMethodWriterInvocationHandler(false, this::acquireAppender));\n builder.marshallableOut(acquireAppender());\n return builder;\n }\n \n /**"}}},{"rowIdx":1910,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"bsd-3-clause"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"846f911930e847d73962a9cff71699c668c46b79"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"jthrun/sdl_android,smartdevicelink/sdl_android,anildahiya/sdl_android,914802951/sdl_android,jthrun/sdl_android"},"new_contents":{"kind":"string","value":"package com.smartdevicelink.protocol;\n\nimport android.test.AndroidTestCase;\nimport android.util.Log;\n\nimport com.smartdevicelink.SdlConnection.SdlConnection;\nimport com.smartdevicelink.protocol.WiProProtocol.MessageFrameAssembler;\nimport com.smartdevicelink.protocol.enums.SessionType;\nimport com.smartdevicelink.test.SampleRpc;\nimport com.smartdevicelink.test.SdlUnitTestContants;\nimport com.smartdevicelink.transport.BaseTransportConfig;\nimport com.smartdevicelink.transport.MultiplexTransportConfig;\nimport com.smartdevicelink.transport.RouterServiceValidator;\n\nimport junit.framework.Assert;\n\nimport java.io.ByteArrayOutputStream;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\n\n/**\n * This is a unit test class for the SmartDeviceLink library project class : \n * {@link com.smartdevicelink.protocol.BinaryFrameHeader}\n */\npublic class WiProProtocolTests extends AndroidTestCase {\n\t\n\tint max_int = 2147483647;\n\tbyte[] payload;\n\tMultiplexTransportConfig config;\n\tSdlConnectionTestClass connection;\n\tWiProProtocol protocol;\n\t\n\tIProtocolListener defaultListener = new IProtocolListener(){\n\t\t@Override\n\t\tpublic void onProtocolMessageBytesToSend(SdlPacket packet) {}\n\t\t@Override\n\t\tpublic void onProtocolMessageReceived(ProtocolMessage msg) {}\n\t\t@Override\n\t\tpublic void onProtocolSessionStarted(SessionType sessionType,byte sessionID, byte version, String correlationID, int hashID,boolean isEncrypted){}\n\t\t@Override\n\t\tpublic void onProtocolSessionNACKed(SessionType sessionType,byte sessionID, byte version, String correlationID) {}\n\t\t@Override\n\t\tpublic void onProtocolSessionEnded(SessionType sessionType,byte sessionID, String correlationID) {}\n\t\t@Override\n\t\tpublic void onProtocolSessionEndedNACKed(SessionType sessionType,byte sessionID, String correlationID) {}\n\t\t@Override\n\t\tpublic void onProtocolHeartbeat(SessionType sessionType, byte sessionID) {}\n\t\t@Override\n\t\tpublic void onProtocolHeartbeatACK(SessionType sessionType,byte sessionID) {}\n\t\t@Override\n\t\tpublic void onProtocolServiceDataACK(SessionType sessionType,int dataSize, byte sessionID) {}\n\t\t@Override\n\t\tpublic void onResetOutgoingHeartbeat(SessionType sessionType,byte sessionID) {}\n\t\t@Override\n\t\tpublic void onResetIncomingHeartbeat(SessionType sessionType,byte sessionID) {}\n\t\t@Override\n\t\tpublic void onProtocolError(String info, Exception e) {}\n\t};\n\tpublic static class DidReceiveListener implements IProtocolListener{\n\t\tboolean didReceive = false;\n\t\t\n\t\tpublic void reset(){\n\t\t\tdidReceive = false;\n\t\t}\n\t\tpublic boolean didReceive(){\n\t\t\treturn didReceive;\n\t\t}\n\t\t@Override\n\t\tpublic void onProtocolMessageBytesToSend(SdlPacket packet) {}\n\t\t@Override\n\t\tpublic void onProtocolMessageReceived(ProtocolMessage msg) {\n\t\t\tdidReceive = true;\n\t\t\tLog.d(\"DidReceiveListener\", \"RPC Type: \" + msg.getRPCType());\n\t\t\tLog.d(\"DidReceiveListener\", \"Function Id: \" + msg.getFunctionID());\n\t\t\tLog.d(\"DidReceiveListener\", \"JSON Size: \" + msg.getJsonSize());\n\t\t}\n\t\t@Override\n\t\tpublic void onProtocolSessionStarted(SessionType sessionType,byte sessionID, byte version, String correlationID, int hashID,boolean isEncrypted){}\n\t\t@Override\n\t\tpublic void onProtocolSessionNACKed(SessionType sessionType,byte sessionID, byte version, String correlationID) {}\n\t\t@Override\n\t\tpublic void onProtocolSessionEnded(SessionType sessionType,byte sessionID, String correlationID) {}\n\t\t@Override\n\t\tpublic void onProtocolSessionEndedNACKed(SessionType sessionType,byte sessionID, String correlationID) {}\n\t\t@Override\n\t\tpublic void onProtocolHeartbeat(SessionType sessionType, byte sessionID) {}\n\t\t@Override\n\t\tpublic void onProtocolHeartbeatACK(SessionType sessionType,byte sessionID) {}\n\t\t@Override\n\t\tpublic void onProtocolServiceDataACK(SessionType sessionType,int dataSize, byte sessionID) {}\n\t\t@Override\n\t\tpublic void onResetOutgoingHeartbeat(SessionType sessionType,byte sessionID) {}\n\t\t@Override\n\t\tpublic void onResetIncomingHeartbeat(SessionType sessionType,byte sessionID) {}\n\t\t@Override\n\t\tpublic void onProtocolError(String info, Exception e) {}\n\t};\n\tDidReceiveListener onProtocolMessageReceivedListener = new DidReceiveListener();\n\t\n\tpublic void testBase(){\n\t\tWiProProtocol wiProProtocol = new WiProProtocol(defaultListener);\n\t\t\n\t}\n\t\n\tpublic void testVersion(){\n\t\tWiProProtocol wiProProtocol = new WiProProtocol(defaultListener);\n\t\t\n\t\twiProProtocol.setVersion((byte)0x01);\n\t\tassertEquals((byte)0x01,wiProProtocol.getVersion());\n\t\t\n\t\twiProProtocol = new WiProProtocol(defaultListener);\n\t\twiProProtocol.setVersion((byte)0x02);\n\t\tassertEquals((byte)0x02,wiProProtocol.getVersion());\n\t\t\n\t\twiProProtocol = new WiProProtocol(defaultListener);\n\t\twiProProtocol.setVersion((byte)0x03);\n\t\tassertEquals((byte)0x03,wiProProtocol.getVersion());\n\t\t\n\t\twiProProtocol = new WiProProtocol(defaultListener);\n\t\twiProProtocol.setVersion((byte)0x04);\n\t\tassertEquals((byte)0x04,wiProProtocol.getVersion());\n\n\t\twiProProtocol = new WiProProtocol(defaultListener);\n\t\twiProProtocol.setVersion((byte)0x05);\n\t\tassertEquals((byte)0x05,wiProProtocol.getVersion());\n\n\t\t//If we get newer than 5, it should fall back to 5\n\t\twiProProtocol = new WiProProtocol(defaultListener);\n\t\twiProProtocol.setVersion((byte)0x06);\n\t\tassertEquals((byte)0x05,wiProProtocol.getVersion());\n\t\t\n\t\t//Is this right?\n\t\twiProProtocol = new WiProProtocol(defaultListener);\n\t\twiProProtocol.setVersion((byte)0x00);\n\t\tassertEquals((byte)0x01,wiProProtocol.getVersion());\n\t}\n\t\n\tpublic void testMtu(){\n\t\tWiProProtocol wiProProtocol = new WiProProtocol(defaultListener);\n\t\t\n\t\twiProProtocol.setVersion((byte)0x01);\n\t\t \n\t\ttry{\n\t\t\tField field = wiProProtocol.getClass().getDeclaredField(\"MAX_DATA_SIZE\"); \n\t\t\tfield.setAccessible(true);\n\t\t\tint mtu = (Integer) field.get(wiProProtocol);\n\t\t\tassertEquals(mtu, 1500-8);\n\t\t\t//Ok our reflection works we can test the rest of the cases\n\t\t\t\n\t\t\t//Version 2\n\t\t\twiProProtocol.setVersion((byte)0x02);\n\t\t\tmtu = (Integer) field.get(wiProProtocol);\n\t\t\tassertEquals(mtu, 1500-12);\n\t\t\t\n\t\t\t//Version 3\n\t\t\twiProProtocol.setVersion((byte)0x03);\n\t\t\tmtu = (Integer) field.get(wiProProtocol);\n\t\t\tassertEquals(mtu, 131072);\n\n\t\t\t//Version 4\n\t\t\twiProProtocol.setVersion((byte)0x04);\n\t\t\tmtu = (Integer) field.get(wiProProtocol);\n\t\t\tassertEquals(mtu, 131072);\n\t\t\t\n\t\t\t//Version 4+\n\t\t\twiProProtocol.setVersion((byte)0x05);\n\t\t\tmtu = (Integer) field.get(wiProProtocol);\n\t\t\tassertEquals(mtu, 1500-12);\n\t\t\t\n\t\t}catch(Exception e){\n\t\t\tAssert.fail(\"Exceptin during reflection\");\n\t\t}\n\n\t}\n\t\n\tpublic void testHandleFrame(){\n\t\tSampleRpc sampleRpc = new SampleRpc(4);\n\t\tWiProProtocol wiProProtocol = new WiProProtocol(defaultListener);\n\t\tMessageFrameAssembler assembler = wiProProtocol.new MessageFrameAssembler();\n\t\ttry{\n\t\t\tassembler.handleFrame(sampleRpc.toSdlPacket());\n\t\t}catch(Exception e){\n\t\t\tAssert.fail(\"Exceptin during handleFrame - \" + e.toString());\n\t\t}\n\t}\n\tpublic void testHandleFrameCorrupt(){\n\t\tSampleRpc sampleRpc = new SampleRpc(4);\n\t\tBinaryFrameHeader header = sampleRpc.getBinaryFrameHeader(true);\n\t\theader.setJsonSize(Integer.MAX_VALUE);\n\t\tsampleRpc.setBinaryFrameHeader(header);\n\t\tWiProProtocol wiProProtocol = new WiProProtocol(defaultListener);\n\t\tMessageFrameAssembler assembler = wiProProtocol.new MessageFrameAssembler();\n\t\ttry{\n\t\t\tassembler.handleFrame(sampleRpc.toSdlPacket());\n\t\t}catch(Exception e){\n\t\t\tAssert.fail(\"Exceptin during handleFrame - \" + e.toString());\n\t\t}\n\t}\n\t\n\tpublic void testHandleSingleFrameMessageFrame(){\n\t\tSampleRpc sampleRpc = new SampleRpc(4);\n\t\tWiProProtocol wiProProtocol = new WiProProtocol(defaultListener);\n\t\tMessageFrameAssembler assembler = wiProProtocol.new MessageFrameAssembler();\n\n\t\t\n\t\ttry{\n\t\t\tMethod method = assembler.getClass().getDeclaredMethod (\"handleSingleFrameMessageFrame\", SdlPacket.class);\n\t\t\tmethod.setAccessible(true);\t\n\t\t\tmethod.invoke (assembler, sampleRpc.toSdlPacket());\t\n\t\t}catch(Exception e){\n\t\t\tAssert.fail(\"Exceptin during handleSingleFrameMessageFrame - \" + e.toString());\n\t\t}\t\n\t}\n\t\n\tpublic void testHandleSingleFrameMessageFrameCorruptBfh(){\n\t\tSampleRpc sampleRpc = new SampleRpc(4);\n\t\t\n\t\t//Create a corrupted header\n\t\tBinaryFrameHeader header = sampleRpc.getBinaryFrameHeader(true);\n\t\theader.setJsonSize(5);\n\t\theader.setJsonData(new byte[5]);\n\t\theader.setJsonSize(Integer.MAX_VALUE);\t\n\t\tsampleRpc.setBinaryFrameHeader(header);\n\t\t\t\n\t\tSdlPacket packet = sampleRpc.toSdlPacket();\n\t\t\t\t\n\t\tBinaryFrameHeader binFrameHeader = BinaryFrameHeader.parseBinaryHeader(packet.payload);\n\t\tassertNull(binFrameHeader);\n\t\t\n\t\tWiProProtocol wiProProtocol = new WiProProtocol(onProtocolMessageReceivedListener);\n\t\t\n\t\t\n\t\twiProProtocol.handlePacketReceived(packet);\n\t\tassertFalse(onProtocolMessageReceivedListener.didReceive());\n\t\t\n\t\tonProtocolMessageReceivedListener.reset();\n\t\tMessageFrameAssembler assembler =wiProProtocol.getFrameAssemblerForFrame(packet);// wiProProtocol.new MessageFrameAssembler();\n\t\tassertNotNull(assembler);\n\t\tassembler.handleFrame(packet);\n\t\tassertFalse(onProtocolMessageReceivedListener.didReceive());\n\t\t\n\t\ttry{\n\t\t\tMethod method = assembler.getClass().getDeclaredMethod(\"handleSingleFrameMessageFrame\", SdlPacket.class);\n\t\t\tmethod.setAccessible(true);\t\n\t\t\tmethod.invoke (assembler, sampleRpc.toSdlPacket());\t\n\t\t}catch(Exception e){\n\t\t\tAssert.fail(\"Exceptin during handleSingleFrameMessageFrame - \" + e.toString());\n\t\t}\t\n\t}\n\t\n\n\t\n\tpublic void setUp(){\n\t\tconfig = new MultiplexTransportConfig(this.mContext,SdlUnitTestContants.TEST_APP_ID);\n\t\tconnection = new SdlConnectionTestClass(config, null);\n\t\tprotocol = new WiProProtocol(connection);\n\t}\n\t\n\tpublic void testNormalCase(){\n\t\tsetUp();\n\t\tpayload = new byte[]{0x00,0x02,0x05,0x01,0x01,0x01,0x05,0x00};\n\t\tbyte sessionID = 1, version = 1;\n\t\tint messageID = 1;\n\t\tboolean encrypted = false;\n\t\tSdlPacket sdlPacket = SdlPacketFactory.createMultiSendDataFirst(SessionType.RPC, sessionID, messageID, version, payload, encrypted);\n\t\tMessageFrameAssembler assembler = protocol.getFrameAssemblerForFrame(sdlPacket);\n\t\t\n\t\tassertNotNull(assembler);\n\t\t\n\t\tOutOfMemoryError oom_error = null;\n\t\tNullPointerException np_exception = null;\n\t\ttry{\n\t\t\tassembler.handleMultiFrameMessageFrame(sdlPacket);\n\t\t}catch(OutOfMemoryError e){\n\t\t\toom_error = e;\n\t\t}catch(NullPointerException z){\n\t\t\tnp_exception = z;\n\t\t}catch(Exception e){\n\t\t\te.printStackTrace();\n\t\t\tassertNotNull(null);\n\t\t}\n\t\t\n\t\tassertNull(np_exception);\n\t\tassertNull(oom_error);\n\t\t\n\t\tpayload = new byte[23534];\n\t\tsdlPacket = SdlPacketFactory.createMultiSendDataRest(SessionType.RPC, sessionID, payload.length, (byte) 3, messageID, version, payload, 0, 1500, encrypted);\n\t\tassembler = protocol.getFrameAssemblerForFrame(sdlPacket);\n\t\ttry{\n\t\t\tassembler.handleMultiFrameMessageFrame(sdlPacket);\n\t\t}catch(OutOfMemoryError e){\n\t\t\toom_error = e;\n\t\t}catch(NullPointerException z){\n\t\t\tnp_exception = z;\n\t\t}catch(Exception e){\n\t\t\tassertNotNull(null);\n\t\t}\n\t\t\n\t\tassertNull(np_exception);\n\t\tassertNull(oom_error);\n\t}\n\t\n\tpublic void testOverallocatingAccumulator(){\n\t\tsetUp();\n\t\tByteArrayOutputStream builder = new ByteArrayOutputStream();\n\t\tfor(int i = 0; i < 8; i++){\n\t\t\tbuilder.write(0x0F);\n\t\t}\n\t\tpayload = builder.toByteArray();\n\t\tbyte sessionID = 1, version = 1;\n\t\tint messageID = 1;\n\t\tboolean encrypted = false;\n\t\tSdlPacket sdlPacket = SdlPacketFactory.createMultiSendDataFirst(SessionType.RPC, sessionID, messageID, version, payload, encrypted);\n\t\tMessageFrameAssembler assembler = protocol.getFrameAssemblerForFrame(sdlPacket);\n\t\t\n\t\tOutOfMemoryError oom_error = null;\n\t\tNullPointerException np_exception = null;\n\t\ttry{\n\t\t\tassembler.handleMultiFrameMessageFrame(sdlPacket);\n\t\t}catch(OutOfMemoryError e){\n\t\t\toom_error = e;\n\t\t}catch(NullPointerException z){\n\t\t\tnp_exception = z;\n\t\t}catch(Exception e){\n\t\t\tassertNotNull(null);\n\t\t}\n\t\t\n\t\tassertNull(np_exception);\n\t\tassertNull(oom_error);\n\n\t\tpayload = new byte[23534];\n\t\tsdlPacket = SdlPacketFactory.createMultiSendDataRest(SessionType.RPC, sessionID, payload.length, (byte) 3, messageID, version, payload, 0, 1500, encrypted);\n\t\tassembler = protocol.getFrameAssemblerForFrame(sdlPacket);\n\t\t\n\t\ttry{\n\t\t\tassembler.handleMultiFrameMessageFrame(sdlPacket);\n\t\t}catch(OutOfMemoryError e){\n\t\t\toom_error = e;\n\t\t}catch(NullPointerException z){\n\t\t\tnp_exception = z;\n\t\t}catch(Exception e){\n\t\t\tassertNotNull(null);\n\t\t}\n\t\t\n\t\tassertNull(np_exception);\n\t\tassertNull(oom_error);\n\t\t\n\t}\n\t\n\tprotected class SdlConnectionTestClass extends SdlConnection{\n\t\tprotected boolean connected = false;\n\t\tpublic SdlConnectionTestClass(BaseTransportConfig transportConfig) {\n\t\t\tsuper(transportConfig);\n\t\t}\n\n\t\tprotected SdlConnectionTestClass(BaseTransportConfig transportConfig,RouterServiceValidator rsvp){\n\t\t\tsuper(transportConfig,rsvp);\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic void onTransportConnected() {\n\t\t\tsuper.onTransportConnected();\n\t\t\tconnected = true;\n\t\t}\n\n\t\t@Override\n\t\tpublic void onTransportDisconnected(String info) {\n\t\t\tconnected = false;\n\t\t\t//Grab a currently running router service\n\t\t\tRouterServiceValidator rsvp2 = new RouterServiceValidator(mContext);\n\t\t\trsvp2.setFlags(RouterServiceValidator.FLAG_DEBUG_NONE);\n\t\t\tassertTrue(rsvp2.validate());\n\t\t\tassertNotNull(rsvp2.getService());\n\t\t\tSdlConnectionTestClass.cachedMultiConfig.setService(rsvp2.getService());\n\t\t\tsuper.onTransportDisconnected(info);\n\t\t}\n\n\t\t@Override\n\t\tpublic void onTransportError(String info, Exception e) {\n\t\t\tconnected = false;\n\t\t\tsuper.onTransportError(info, e);\n\t\t}\n\t}\n}\n"},"new_file":{"kind":"string","value":"sdl_android/src/androidTest/java/com/smartdevicelink/protocol/WiProProtocolTests.java"},"old_contents":{"kind":"string","value":"package com.smartdevicelink.protocol;\n\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\n\nimport junit.framework.Assert;\n\nimport com.smartdevicelink.protocol.IProtocolListener;\nimport com.smartdevicelink.protocol.ProtocolMessage;\nimport com.smartdevicelink.protocol.SdlPacket;\nimport com.smartdevicelink.protocol.WiProProtocol;\nimport com.smartdevicelink.protocol.WiProProtocol.MessageFrameAssembler;\nimport com.smartdevicelink.protocol.enums.MessageType;\nimport com.smartdevicelink.protocol.enums.SessionType;\nimport com.smartdevicelink.test.SampleRpc;\nimport com.smartdevicelink.util.DebugTool;\nimport java.io.ByteArrayOutputStream;\n\nimport com.smartdevicelink.SdlConnection.SdlConnection;\nimport com.smartdevicelink.test.SdlUnitTestContants;\nimport com.smartdevicelink.transport.BaseTransportConfig;\nimport com.smartdevicelink.transport.MultiplexTransportConfig;\nimport com.smartdevicelink.transport.RouterServiceValidator;\n\nimport android.test.AndroidTestCase;\nimport android.util.Log;\n\n/**\n * This is a unit test class for the SmartDeviceLink library project class : \n * {@link com.smartdevicelink.protocol.BinaryFrameHeader}\n */\npublic class WiProProtocolTests extends AndroidTestCase {\n\t\n\tint max_int = 2147483647;\n\tbyte[] payload;\n\tMultiplexTransportConfig config;\n\tSdlConnectionTestClass connection;\n\tWiProProtocol protocol;\n\t\n\tIProtocolListener defaultListener = new IProtocolListener(){\n\t\t@Override\n\t\tpublic void onProtocolMessageBytesToSend(SdlPacket packet) {}\n\t\t@Override\n\t\tpublic void onProtocolMessageReceived(ProtocolMessage msg) {}\n\t\t@Override\n\t\tpublic void onProtocolSessionStarted(SessionType sessionType,byte sessionID, byte version, String correlationID, int hashID,boolean isEncrypted){}\n\t\t@Override\n\t\tpublic void onProtocolSessionNACKed(SessionType sessionType,byte sessionID, byte version, String correlationID) {}\n\t\t@Override\n\t\tpublic void onProtocolSessionEnded(SessionType sessionType,byte sessionID, String correlationID) {}\n\t\t@Override\n\t\tpublic void onProtocolSessionEndedNACKed(SessionType sessionType,byte sessionID, String correlationID) {}\n\t\t@Override\n\t\tpublic void onProtocolHeartbeat(SessionType sessionType, byte sessionID) {}\n\t\t@Override\n\t\tpublic void onProtocolHeartbeatACK(SessionType sessionType,byte sessionID) {}\n\t\t@Override\n\t\tpublic void onProtocolServiceDataACK(SessionType sessionType,int dataSize, byte sessionID) {}\n\t\t@Override\n\t\tpublic void onResetOutgoingHeartbeat(SessionType sessionType,byte sessionID) {}\n\t\t@Override\n\t\tpublic void onResetIncomingHeartbeat(SessionType sessionType,byte sessionID) {}\n\t\t@Override\n\t\tpublic void onProtocolError(String info, Exception e) {}\n\t};\n\tpublic static class DidReceiveListener implements IProtocolListener{\n\t\tboolean didReceive = false;\n\t\t\n\t\tpublic void reset(){\n\t\t\tdidReceive = false;\n\t\t}\n\t\tpublic boolean didReceive(){\n\t\t\treturn didReceive;\n\t\t}\n\t\t@Override\n\t\tpublic void onProtocolMessageBytesToSend(SdlPacket packet) {}\n\t\t@Override\n\t\tpublic void onProtocolMessageReceived(ProtocolMessage msg) {\n\t\t\tdidReceive = true;\n\t\t\tLog.d(\"DidReceiveListener\", \"RPC Type: \" + msg.getRPCType());\n\t\t\tLog.d(\"DidReceiveListener\", \"Function Id: \" + msg.getFunctionID());\n\t\t\tLog.d(\"DidReceiveListener\", \"JSON Size: \" + msg.getJsonSize());\n\t\t}\n\t\t@Override\n\t\tpublic void onProtocolSessionStarted(SessionType sessionType,byte sessionID, byte version, String correlationID, int hashID,boolean isEncrypted){}\n\t\t@Override\n\t\tpublic void onProtocolSessionNACKed(SessionType sessionType,byte sessionID, byte version, String correlationID) {}\n\t\t@Override\n\t\tpublic void onProtocolSessionEnded(SessionType sessionType,byte sessionID, String correlationID) {}\n\t\t@Override\n\t\tpublic void onProtocolSessionEndedNACKed(SessionType sessionType,byte sessionID, String correlationID) {}\n\t\t@Override\n\t\tpublic void onProtocolHeartbeat(SessionType sessionType, byte sessionID) {}\n\t\t@Override\n\t\tpublic void onProtocolHeartbeatACK(SessionType sessionType,byte sessionID) {}\n\t\t@Override\n\t\tpublic void onProtocolServiceDataACK(SessionType sessionType,int dataSize, byte sessionID) {}\n\t\t@Override\n\t\tpublic void onResetOutgoingHeartbeat(SessionType sessionType,byte sessionID) {}\n\t\t@Override\n\t\tpublic void onResetIncomingHeartbeat(SessionType sessionType,byte sessionID) {}\n\t\t@Override\n\t\tpublic void onProtocolError(String info, Exception e) {}\n\t};\n\tDidReceiveListener onProtocolMessageReceivedListener = new DidReceiveListener();\n\t\n\tpublic void testBase(){\n\t\tWiProProtocol wiProProtocol = new WiProProtocol(defaultListener);\n\t\t\n\t}\n\t\n\tpublic void testVersion(){\n\t\tWiProProtocol wiProProtocol = new WiProProtocol(defaultListener);\n\t\t\n\t\twiProProtocol.setVersion((byte)0x01);\n\t\tassertEquals((byte)0x01,wiProProtocol.getVersion());\n\t\t\n\t\twiProProtocol = new WiProProtocol(defaultListener);\n\t\twiProProtocol.setVersion((byte)0x02);\n\t\tassertEquals((byte)0x02,wiProProtocol.getVersion());\n\t\t\n\t\twiProProtocol = new WiProProtocol(defaultListener);\n\t\twiProProtocol.setVersion((byte)0x03);\n\t\tassertEquals((byte)0x03,wiProProtocol.getVersion());\n\t\t\n\t\twiProProtocol = new WiProProtocol(defaultListener);\n\t\twiProProtocol.setVersion((byte)0x04);\n\t\tassertEquals((byte)0x04,wiProProtocol.getVersion());\n\t\t\n\t\t//If we get newer than 4, it should fall back to 4\n\t\twiProProtocol = new WiProProtocol(defaultListener);\n\t\twiProProtocol.setVersion((byte)0x05);\n\t\tassertEquals((byte)0x04,wiProProtocol.getVersion());\n\t\t\n\t\t//Is this right?\n\t\twiProProtocol = new WiProProtocol(defaultListener);\n\t\twiProProtocol.setVersion((byte)0x00);\n\t\tassertEquals((byte)0x01,wiProProtocol.getVersion());\n\t}\n\t\n\tpublic void testMtu(){\n\t\tWiProProtocol wiProProtocol = new WiProProtocol(defaultListener);\n\t\t\n\t\twiProProtocol.setVersion((byte)0x01);\n\t\t \n\t\ttry{\n\t\t\tField field = wiProProtocol.getClass().getDeclaredField(\"MAX_DATA_SIZE\"); \n\t\t\tfield.setAccessible(true);\n\t\t\tint mtu = (Integer) field.get(wiProProtocol);\n\t\t\tassertEquals(mtu, 1500-8);\n\t\t\t//Ok our reflection works we can test the rest of the cases\n\t\t\t\n\t\t\t//Version 2\n\t\t\twiProProtocol.setVersion((byte)0x02);\n\t\t\tmtu = (Integer) field.get(wiProProtocol);\n\t\t\tassertEquals(mtu, 1500-12);\n\t\t\t\n\t\t\t//Version 3\n\t\t\twiProProtocol.setVersion((byte)0x03);\n\t\t\tmtu = (Integer) field.get(wiProProtocol);\n\t\t\tassertEquals(mtu, 131072);\n\n\t\t\t//Version 4\n\t\t\twiProProtocol.setVersion((byte)0x04);\n\t\t\tmtu = (Integer) field.get(wiProProtocol);\n\t\t\tassertEquals(mtu, 131072);\n\t\t\t\n\t\t\t//Version 4+\n\t\t\twiProProtocol.setVersion((byte)0x05);\n\t\t\tmtu = (Integer) field.get(wiProProtocol);\n\t\t\tassertEquals(mtu, 1500-12);\n\t\t\t\n\t\t}catch(Exception e){\n\t\t\tAssert.fail(\"Exceptin during reflection\");\n\t\t}\n\n\t}\n\t\n\tpublic void testHandleFrame(){\n\t\tSampleRpc sampleRpc = new SampleRpc(4);\n\t\tWiProProtocol wiProProtocol = new WiProProtocol(defaultListener);\n\t\tMessageFrameAssembler assembler = wiProProtocol.new MessageFrameAssembler();\n\t\ttry{\n\t\t\tassembler.handleFrame(sampleRpc.toSdlPacket());\n\t\t}catch(Exception e){\n\t\t\tAssert.fail(\"Exceptin during handleFrame - \" + e.toString());\n\t\t}\n\t}\n\tpublic void testHandleFrameCorrupt(){\n\t\tSampleRpc sampleRpc = new SampleRpc(4);\n\t\tBinaryFrameHeader header = sampleRpc.getBinaryFrameHeader(true);\n\t\theader.setJsonSize(Integer.MAX_VALUE);\n\t\tsampleRpc.setBinaryFrameHeader(header);\n\t\tWiProProtocol wiProProtocol = new WiProProtocol(defaultListener);\n\t\tMessageFrameAssembler assembler = wiProProtocol.new MessageFrameAssembler();\n\t\ttry{\n\t\t\tassembler.handleFrame(sampleRpc.toSdlPacket());\n\t\t}catch(Exception e){\n\t\t\tAssert.fail(\"Exceptin during handleFrame - \" + e.toString());\n\t\t}\n\t}\n\t\n\tpublic void testHandleSingleFrameMessageFrame(){\n\t\tSampleRpc sampleRpc = new SampleRpc(4);\n\t\tWiProProtocol wiProProtocol = new WiProProtocol(defaultListener);\n\t\tMessageFrameAssembler assembler = wiProProtocol.new MessageFrameAssembler();\n\n\t\t\n\t\ttry{\n\t\t\tMethod method = assembler.getClass().getDeclaredMethod (\"handleSingleFrameMessageFrame\", SdlPacket.class);\n\t\t\tmethod.setAccessible(true);\t\n\t\t\tmethod.invoke (assembler, sampleRpc.toSdlPacket());\t\n\t\t}catch(Exception e){\n\t\t\tAssert.fail(\"Exceptin during handleSingleFrameMessageFrame - \" + e.toString());\n\t\t}\t\n\t}\n\t\n\tpublic void testHandleSingleFrameMessageFrameCorruptBfh(){\n\t\tSampleRpc sampleRpc = new SampleRpc(4);\n\t\t\n\t\t//Create a corrupted header\n\t\tBinaryFrameHeader header = sampleRpc.getBinaryFrameHeader(true);\n\t\theader.setJsonSize(5);\n\t\theader.setJsonData(new byte[5]);\n\t\theader.setJsonSize(Integer.MAX_VALUE);\t\n\t\tsampleRpc.setBinaryFrameHeader(header);\n\t\t\t\n\t\tSdlPacket packet = sampleRpc.toSdlPacket();\n\t\t\t\t\n\t\tBinaryFrameHeader binFrameHeader = BinaryFrameHeader.parseBinaryHeader(packet.payload);\n\t\tassertNull(binFrameHeader);\n\t\t\n\t\tWiProProtocol wiProProtocol = new WiProProtocol(onProtocolMessageReceivedListener);\n\t\t\n\t\t\n\t\twiProProtocol.handlePacketReceived(packet);\n\t\tassertFalse(onProtocolMessageReceivedListener.didReceive());\n\t\t\n\t\tonProtocolMessageReceivedListener.reset();\n\t\tMessageFrameAssembler assembler =wiProProtocol.getFrameAssemblerForFrame(packet);// wiProProtocol.new MessageFrameAssembler();\n\t\tassertNotNull(assembler);\n\t\tassembler.handleFrame(packet);\n\t\tassertFalse(onProtocolMessageReceivedListener.didReceive());\n\t\t\n\t\ttry{\n\t\t\tMethod method = assembler.getClass().getDeclaredMethod(\"handleSingleFrameMessageFrame\", SdlPacket.class);\n\t\t\tmethod.setAccessible(true);\t\n\t\t\tmethod.invoke (assembler, sampleRpc.toSdlPacket());\t\n\t\t}catch(Exception e){\n\t\t\tAssert.fail(\"Exceptin during handleSingleFrameMessageFrame - \" + e.toString());\n\t\t}\t\n\t}\n\t\n\n\t\n\tpublic void setUp(){\n\t\tconfig = new MultiplexTransportConfig(this.mContext,SdlUnitTestContants.TEST_APP_ID);\n\t\tconnection = new SdlConnectionTestClass(config, null);\n\t\tprotocol = new WiProProtocol(connection);\n\t}\n\t\n\tpublic void testNormalCase(){\n\t\tsetUp();\n\t\tpayload = new byte[]{0x00,0x02,0x05,0x01,0x01,0x01,0x05,0x00};\n\t\tbyte sessionID = 1, version = 1;\n\t\tint messageID = 1;\n\t\tboolean encrypted = false;\n\t\tSdlPacket sdlPacket = SdlPacketFactory.createMultiSendDataFirst(SessionType.RPC, sessionID, messageID, version, payload, encrypted);\n\t\tMessageFrameAssembler assembler = protocol.getFrameAssemblerForFrame(sdlPacket);\n\t\t\n\t\tassertNotNull(assembler);\n\t\t\n\t\tOutOfMemoryError oom_error = null;\n\t\tNullPointerException np_exception = null;\n\t\ttry{\n\t\t\tassembler.handleMultiFrameMessageFrame(sdlPacket);\n\t\t}catch(OutOfMemoryError e){\n\t\t\toom_error = e;\n\t\t}catch(NullPointerException z){\n\t\t\tnp_exception = z;\n\t\t}catch(Exception e){\n\t\t\te.printStackTrace();\n\t\t\tassertNotNull(null);\n\t\t}\n\t\t\n\t\tassertNull(np_exception);\n\t\tassertNull(oom_error);\n\t\t\n\t\tpayload = new byte[23534];\n\t\tsdlPacket = SdlPacketFactory.createMultiSendDataRest(SessionType.RPC, sessionID, payload.length, (byte) 3, messageID, version, payload, 0, 1500, encrypted);\n\t\tassembler = protocol.getFrameAssemblerForFrame(sdlPacket);\n\t\ttry{\n\t\t\tassembler.handleMultiFrameMessageFrame(sdlPacket);\n\t\t}catch(OutOfMemoryError e){\n\t\t\toom_error = e;\n\t\t}catch(NullPointerException z){\n\t\t\tnp_exception = z;\n\t\t}catch(Exception e){\n\t\t\tassertNotNull(null);\n\t\t}\n\t\t\n\t\tassertNull(np_exception);\n\t\tassertNull(oom_error);\n\t}\n\t\n\tpublic void testOverallocatingAccumulator(){\n\t\tsetUp();\n\t\tByteArrayOutputStream builder = new ByteArrayOutputStream();\n\t\tfor(int i = 0; i < 8; i++){\n\t\t\tbuilder.write(0x0F);\n\t\t}\n\t\tpayload = builder.toByteArray();\n\t\tbyte sessionID = 1, version = 1;\n\t\tint messageID = 1;\n\t\tboolean encrypted = false;\n\t\tSdlPacket sdlPacket = SdlPacketFactory.createMultiSendDataFirst(SessionType.RPC, sessionID, messageID, version, payload, encrypted);\n\t\tMessageFrameAssembler assembler = protocol.getFrameAssemblerForFrame(sdlPacket);\n\t\t\n\t\tOutOfMemoryError oom_error = null;\n\t\tNullPointerException np_exception = null;\n\t\ttry{\n\t\t\tassembler.handleMultiFrameMessageFrame(sdlPacket);\n\t\t}catch(OutOfMemoryError e){\n\t\t\toom_error = e;\n\t\t}catch(NullPointerException z){\n\t\t\tnp_exception = z;\n\t\t}catch(Exception e){\n\t\t\tassertNotNull(null);\n\t\t}\n\t\t\n\t\tassertNull(np_exception);\n\t\tassertNull(oom_error);\n\n\t\tpayload = new byte[23534];\n\t\tsdlPacket = SdlPacketFactory.createMultiSendDataRest(SessionType.RPC, sessionID, payload.length, (byte) 3, messageID, version, payload, 0, 1500, encrypted);\n\t\tassembler = protocol.getFrameAssemblerForFrame(sdlPacket);\n\t\t\n\t\ttry{\n\t\t\tassembler.handleMultiFrameMessageFrame(sdlPacket);\n\t\t}catch(OutOfMemoryError e){\n\t\t\toom_error = e;\n\t\t}catch(NullPointerException z){\n\t\t\tnp_exception = z;\n\t\t}catch(Exception e){\n\t\t\tassertNotNull(null);\n\t\t}\n\t\t\n\t\tassertNull(np_exception);\n\t\tassertNull(oom_error);\n\t\t\n\t}\n\t\n\tprotected class SdlConnectionTestClass extends SdlConnection{\n\t\tprotected boolean connected = false;\n\t\tpublic SdlConnectionTestClass(BaseTransportConfig transportConfig) {\n\t\t\tsuper(transportConfig);\n\t\t}\n\n\t\tprotected SdlConnectionTestClass(BaseTransportConfig transportConfig,RouterServiceValidator rsvp){\n\t\t\tsuper(transportConfig,rsvp);\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic void onTransportConnected() {\n\t\t\tsuper.onTransportConnected();\n\t\t\tconnected = true;\n\t\t}\n\n\t\t@Override\n\t\tpublic void onTransportDisconnected(String info) {\n\t\t\tconnected = false;\n\t\t\t//Grab a currently running router service\n\t\t\tRouterServiceValidator rsvp2 = new RouterServiceValidator(mContext);\n\t\t\trsvp2.setFlags(RouterServiceValidator.FLAG_DEBUG_NONE);\n\t\t\tassertTrue(rsvp2.validate());\n\t\t\tassertNotNull(rsvp2.getService());\n\t\t\tSdlConnectionTestClass.cachedMultiConfig.setService(rsvp2.getService());\n\t\t\tsuper.onTransportDisconnected(info);\n\t\t}\n\n\t\t@Override\n\t\tpublic void onTransportError(String info, Exception e) {\n\t\t\tconnected = false;\n\t\t\tsuper.onTransportError(info, e);\n\t\t}\n\t}\n}\n"},"message":{"kind":"string","value":"Fix version tests for WiProProtcol\n"},"old_file":{"kind":"string","value":"sdl_android/src/androidTest/java/com/smartdevicelink/protocol/WiProProtocolTests.java"},"subject":{"kind":"string","value":"Fix version tests for WiProProtcol"},"git_diff":{"kind":"string","value":"dl_android/src/androidTest/java/com/smartdevicelink/protocol/WiProProtocolTests.java\n package com.smartdevicelink.protocol;\n \nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\n\nimport junit.framework.Assert;\n\nimport com.smartdevicelink.protocol.IProtocolListener;\nimport com.smartdevicelink.protocol.ProtocolMessage;\nimport com.smartdevicelink.protocol.SdlPacket;\nimport com.smartdevicelink.protocol.WiProProtocol;\nimport android.test.AndroidTestCase;\nimport android.util.Log;\n\nimport com.smartdevicelink.SdlConnection.SdlConnection;\n import com.smartdevicelink.protocol.WiProProtocol.MessageFrameAssembler;\nimport com.smartdevicelink.protocol.enums.MessageType;\n import com.smartdevicelink.protocol.enums.SessionType;\n import com.smartdevicelink.test.SampleRpc;\nimport com.smartdevicelink.util.DebugTool;\nimport java.io.ByteArrayOutputStream;\n\nimport com.smartdevicelink.SdlConnection.SdlConnection;\n import com.smartdevicelink.test.SdlUnitTestContants;\n import com.smartdevicelink.transport.BaseTransportConfig;\n import com.smartdevicelink.transport.MultiplexTransportConfig;\n import com.smartdevicelink.transport.RouterServiceValidator;\n \nimport android.test.AndroidTestCase;\nimport android.util.Log;\nimport junit.framework.Assert;\n\nimport java.io.ByteArrayOutputStream;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\n \n /**\n * This is a unit test class for the SmartDeviceLink library project class : \n \t\twiProProtocol = new WiProProtocol(defaultListener);\n \t\twiProProtocol.setVersion((byte)0x04);\n \t\tassertEquals((byte)0x04,wiProProtocol.getVersion());\n\t\t\n\t\t//If we get newer than 4, it should fall back to 4\n\n \t\twiProProtocol = new WiProProtocol(defaultListener);\n \t\twiProProtocol.setVersion((byte)0x05);\n\t\tassertEquals((byte)0x04,wiProProtocol.getVersion());\n\t\tassertEquals((byte)0x05,wiProProtocol.getVersion());\n\n\t\t//If we get newer than 5, it should fall back to 5\n\t\twiProProtocol = new WiProProtocol(defaultListener);\n\t\twiProProtocol.setVersion((byte)0x06);\n\t\tassertEquals((byte)0x05,wiProProtocol.getVersion());\n \t\t\n \t\t//Is this right?\n \t\twiProProtocol = new WiProProtocol(defaultListener);"}}},{"rowIdx":1911,"cells":{"lang":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"2852604c01d0207342b833c31755dbd54279d083"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"Ricket/nodebot,Ricket/nodebot,nooitaf/nodebot,nooitaf/nodebot,ludiko/nodebot,ludiko/nodebot"},"new_contents":{"kind":"string","value":"// (c) 2011 Richard Carter\n// This code is licensed under the MIT license; see LICENSE.txt for details.\n\n// This script handles the following functions:\n// ~secret password - authenticate to become an admin\n// ~makeadmin user - make user an admin\n// ~unadmin user - demote user from admin status\n// ~admins - list admins\n// ~ignore user - the bot will no longer respond to messages from [user]\n// ~unignore user - the bot will once more respond to messages from [user]\n// ~reload - reload scripts\n\nvar db = require('./lib/listdb').getDB('admins');\n\nfunction isAdmin(username) {\n return db.hasValue(username, true);\n}\n\nfunction addAdmin(username) {\n db.add(username);\n}\n\nfunction removeAdmin(username) {\n db.remove(username, true);\n}\n\nlisten(regexFactory.startsWith(\"secret\"), function(match, data, replyTo, from) {\n if (isAdmin(from)) {\n irc.privmsg(replyTo, \"You are already an admin.\");\n } else if (match[1] === nodebot_prefs.secret) {\n addAdmin(from);\n irc.privmsg(replyTo, \"You are now an admin.\");\n }\n});\n\nlisten(regexFactory.only(\"admins\"), function(match, data, replyTo) {\n irc.privmsg(replyTo, \"Admins: \" + db.getAll().join(\",\"));\n});\n\nfunction listen_admin(regex, listener) {\n listen(regex, function(match, data, replyTo, from) {\n if (isAdmin(from)) {\n listener(match, data, replyTo, from);\n }\n });\n}\n\nlisten_admin(regexFactory.startsWith(\"makeadmin\"), function(match, data, replyTo, from) {\n if (isAdmin(match[1])) {\n irc.privmsg(replyTo, match[1] + \" is already an admin.\");\n } else {\n addAdmin(match[1]);\n irc.privmsg(replyTo, match[1] + \" is now an admin.\");\n }\n});\n\nlisten_admin(regexFactory.startsWith(\"unadmin\"), function(match, data, replyTo, from) {\n if (isAdmin(match[1])) {\n removeAdmin(match[1]);\n irc.privmsg(replyTo, match[1] + \" is no longer an admin.\");\n } else {\n irc.privmsg(replyTo, match[1] + \" isn't an admin\");\n }\n});\n\nlisten_admin(regexFactory.startsWith(\"ignore\"), function(match, data, replyTo, from) {\n if (isAdmin(match[1])) {\n irc.privmsg(replyTo, match[1] + \" is an admin, can't be ignored\");\n } else {\n irc.ignore(match[1]);\n irc.privmsg(replyTo, match[1] + \" is now ignored.\");\n }\n});\n\nlisten_admin(regexFactory.startsWith(\"unignore\"), function(match, data, replyTo, from) {\n irc.unignore(match[1]);\n irc.privmsg(replyTo, match[1] + \" unignored\");\n});\n\nlisten_admin(regexFactory.only(\"ignorelist\"), function (match, data, replyTo) {\n irc.chatignorelist(replyTo);\n});\n\nvar exec = require('child_process').exec;\nlisten_admin(regexFactory.only(\"git pull\"), function(match, data, replyTo) {\n exec('git pull', function(error, stdout, stderr) {\n var feedback, stdouts;\n stdouts = stdout.replace(/\\n$/, \"\").split(\"\\n\");\n feedback = ((error) ? \"Error: \" : \"Result: \") + stdouts[stdouts.length - 1];\n\n irc.privmsg(replyTo, feedback);\n });\n});\n\nlisten_admin(regexFactory.only('reload'), function(match, data, replyTo) {\n irc.loadScripts();\n irc.privmsg(replyTo, \"Reloaded scripts\");\n});\n\nlisten_admin(regexFactory.startsWith('raw'), function(match) {\n irc.raw(match[1]);\n});\n\n"},"new_file":{"kind":"string","value":"scripts/admin.js"},"old_contents":{"kind":"string","value":"// (c) 2011 Richard Carter\n// This code is licensed under the MIT license; see LICENSE.txt for details.\n\n// This script handles the following functions:\n// ~secret password - authenticate to become an admin\n// ~makeadmin user - make user an admin\n// ~unadmin user - demote user from admin status\n// ~admins - list admins\n// ~ignore user - the bot will no longer respond to messages from [user]\n// ~unignore user - the bot will once more respond to messages from [user]\n// ~reload - reload scripts\n\nvar db = require('./lib/listdb').getDB('admins');\n\nfunction isAdmin(username) {\n return db.hasValue(username, true);\n}\n\nfunction addAdmin(username) {\n db.add(username);\n}\n\nfunction removeAdmin(username) {\n db.remove(username, true);\n}\n\nlisten(/^:([^!]+).*~secret (.*)$/i, function(match) {\n if (isAdmin(match[1])) {\n irc.privmsg(match[1], \"You are already an admin.\");\n } else if (match[2] == nodebot_prefs.secret) {\n addAdmin(match[1]);\n irc.privmsg(match[1], \"You are now an admin.\");\n }\n});\n\nfunction listen_admin(regex, listener) {\n listen(/^:([^!]+)/i, function(match, data, replyTo) {\n if (isAdmin(match[1])) {\n match = regex.exec(data);\n if (match) {\n try {\n listener(match, data, replyTo);\n } catch(err) {\n console.log(\"caught error in admin script: \"+err);\n }\n }\n }\n });\n}\n\nlisten_admin(/^:([^!]+).*~makeadmin (.*)$/i, function(match) {\n if (isAdmin(match[2])) {\n irc.privmsg(match[1], match[2] + \" is already an admin.\");\n } else {\n addAdmin(match[2]);\n irc.privmsg(match[1], match[2] + \" is now an admin.\");\n }\n});\n\nlisten_admin(/^:([^!]+).*~unadmin (.*)$/i, function(match) {\n if (isAdmin(match[2])) {\n removeAdmin(match[2]);\n irc.privmsg(match[1], match[2] + \" is no longer an admin.\");\n } else {\n irc.privmsg(match[1], match[2] + \" isn't an admin\");\n }\n});\n\nlisten(/:([^!]+)!.*PRIVMSG (.*) :~admins/i, function(match, data, replyTo) {\n irc.privmsg(replyTo, \"Admins: \" + db.getAll().join(\",\"));\n});\n\nlisten_admin(/^:([^!]+).*~ignore (.+)$/i, function(match) {\n if (isAdmin(match[2])) {\n irc.privmsg(match[1], match[2] + \" is an admin, can't be ignored\");\n } else {\n irc.ignore(match[2]);\n irc.privmsg(match[1], match[2] + \" is now ignored.\");\n }\n});\n\nlisten_admin(/^:([^!]+)!.*~unignore (.*)$/i, function(match) {\n irc.unignore(match[2]);\n irc.privmsg(match[1], match[2] + \" unignored\");\n});\n\nlisten_admin(/~ignorelist$/i, function (match, data, replyTo) {\n irc.chatignorelist(replyTo);\n});\n\nvar exec = require('child_process').exec;\nlisten_admin(/~git pull$/i, function(match, data, replyTo) {\n exec('git pull', function(error, stdout, stderr) {\n var feedback, stdouts;\n stdouts = stdout.replace(/\\n$/, \"\").split(\"\\n\");\n feedback = ((error) ? \"Error: \" : \"Result: \") + stdouts[stdouts.length - 1];\n\n irc.privmsg(replyTo, feedback);\n });\n});\n\nlisten_admin(regexFactory.only('reload'), function(match, data, replyTo) {\n irc.loadScripts();\n irc.privmsg(replyTo, \"Reloaded scripts\");\n});\n\nlisten_admin(regexFactory.startsWith('raw'), function(match) {\n irc.raw(match[1]);\n});\n\n"},"message":{"kind":"string","value":"admin: use regexFactory\n"},"old_file":{"kind":"string","value":"scripts/admin.js"},"subject":{"kind":"string","value":"admin: use regexFactory"},"git_diff":{"kind":"string","value":"cripts/admin.js\n db.remove(username, true);\n }\n \nlisten(/^:([^!]+).*~secret (.*)$/i, function(match) {\n if (isAdmin(match[1])) {\n irc.privmsg(match[1], \"You are already an admin.\");\n } else if (match[2] == nodebot_prefs.secret) {\n addAdmin(match[1]);\n irc.privmsg(match[1], \"You are now an admin.\");\nlisten(regexFactory.startsWith(\"secret\"), function(match, data, replyTo, from) {\n if (isAdmin(from)) {\n irc.privmsg(replyTo, \"You are already an admin.\");\n } else if (match[1] === nodebot_prefs.secret) {\n addAdmin(from);\n irc.privmsg(replyTo, \"You are now an admin.\");\n }\n });\n \nlisten(regexFactory.only(\"admins\"), function(match, data, replyTo) {\n irc.privmsg(replyTo, \"Admins: \" + db.getAll().join(\",\"));\n});\n\n function listen_admin(regex, listener) {\n listen(/^:([^!]+)/i, function(match, data, replyTo) {\n if (isAdmin(match[1])) {\n match = regex.exec(data);\n if (match) {\n try {\n listener(match, data, replyTo);\n } catch(err) {\n console.log(\"caught error in admin script: \"+err);\n }\n }\n listen(regex, function(match, data, replyTo, from) {\n if (isAdmin(from)) {\n listener(match, data, replyTo, from);\n }\n });\n }\n \nlisten_admin(/^:([^!]+).*~makeadmin (.*)$/i, function(match) {\n if (isAdmin(match[2])) {\n irc.privmsg(match[1], match[2] + \" is already an admin.\");\nlisten_admin(regexFactory.startsWith(\"makeadmin\"), function(match, data, replyTo, from) {\n if (isAdmin(match[1])) {\n irc.privmsg(replyTo, match[1] + \" is already an admin.\");\n } else {\n addAdmin(match[2]);\n irc.privmsg(match[1], match[2] + \" is now an admin.\");\n addAdmin(match[1]);\n irc.privmsg(replyTo, match[1] + \" is now an admin.\");\n }\n });\n \nlisten_admin(/^:([^!]+).*~unadmin (.*)$/i, function(match) {\n if (isAdmin(match[2])) {\n removeAdmin(match[2]);\n irc.privmsg(match[1], match[2] + \" is no longer an admin.\");\nlisten_admin(regexFactory.startsWith(\"unadmin\"), function(match, data, replyTo, from) {\n if (isAdmin(match[1])) {\n removeAdmin(match[1]);\n irc.privmsg(replyTo, match[1] + \" is no longer an admin.\");\n } else {\n irc.privmsg(match[1], match[2] + \" isn't an admin\");\n irc.privmsg(replyTo, match[1] + \" isn't an admin\");\n }\n });\n \nlisten(/:([^!]+)!.*PRIVMSG (.*) :~admins/i, function(match, data, replyTo) {\n irc.privmsg(replyTo, \"Admins: \" + db.getAll().join(\",\"));\n});\n\nlisten_admin(/^:([^!]+).*~ignore (.+)$/i, function(match) {\n if (isAdmin(match[2])) {\n irc.privmsg(match[1], match[2] + \" is an admin, can't be ignored\");\nlisten_admin(regexFactory.startsWith(\"ignore\"), function(match, data, replyTo, from) {\n if (isAdmin(match[1])) {\n irc.privmsg(replyTo, match[1] + \" is an admin, can't be ignored\");\n } else {\n irc.ignore(match[2]);\n irc.privmsg(match[1], match[2] + \" is now ignored.\");\n irc.ignore(match[1]);\n irc.privmsg(replyTo, match[1] + \" is now ignored.\");\n }\n });\n \nlisten_admin(/^:([^!]+)!.*~unignore (.*)$/i, function(match) {\n irc.unignore(match[2]);\n irc.privmsg(match[1], match[2] + \" unignored\");\nlisten_admin(regexFactory.startsWith(\"unignore\"), function(match, data, replyTo, from) {\n irc.unignore(match[1]);\n irc.privmsg(replyTo, match[1] + \" unignored\");\n });\n \nlisten_admin(/~ignorelist$/i, function (match, data, replyTo) {\nlisten_admin(regexFactory.only(\"ignorelist\"), function (match, data, replyTo) {\n irc.chatignorelist(replyTo);\n });\n \n var exec = require('child_process').exec;\nlisten_admin(/~git pull$/i, function(match, data, replyTo) {\nlisten_admin(regexFactory.only(\"git pull\"), function(match, data, replyTo) {\n exec('git pull', function(error, stdout, stderr) {\n var feedback, stdouts;\n stdouts = stdout.replace(/\\n$/, \"\").split(\"\\n\");"}}},{"rowIdx":1912,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"unlicense"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"d7d22925e7828f0eb2b2c74585816acef2f89c0e"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"Samourai-Wallet/samourai-wallet-android"},"new_contents":{"kind":"string","value":"package com.samourai.wallet.home;\n\nimport android.Manifest;\nimport android.animation.Animator;\nimport android.animation.AnimatorListenerAdapter;\nimport android.app.Activity;\nimport android.app.ProgressDialog;\n\nimport androidx.appcompat.app.AlertDialog;\nimport androidx.lifecycle.Observer;\nimport androidx.lifecycle.ViewModelProviders;\nimport android.content.BroadcastReceiver;\nimport android.content.ClipData;\nimport android.content.ClipboardManager;\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.content.Intent;\nimport android.content.IntentFilter;\nimport android.content.pm.ActivityInfo;\nimport android.graphics.Typeface;\nimport android.graphics.drawable.Drawable;\nimport android.net.Uri;\nimport android.os.AsyncTask;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport androidx.annotation.Nullable;\nimport com.google.android.material.appbar.CollapsingToolbarLayout;\nimport androidx.transition.ChangeBounds;\nimport androidx.transition.TransitionManager;\nimport androidx.core.content.ContextCompat;\nimport androidx.localbroadcastmanager.content.LocalBroadcastManager;\nimport androidx.swiperefreshlayout.widget.SwipeRefreshLayout;\nimport androidx.recyclerview.widget.LinearLayoutManager;\nimport androidx.recyclerview.widget.RecyclerView;\nimport androidx.appcompat.widget.Toolbar;\n\nimport android.text.InputType;\nimport android.util.Log;\nimport android.util.TypedValue;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.widget.EditText;\nimport android.widget.ImageView;\nimport android.widget.LinearLayout;\nimport android.widget.ProgressBar;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.dm.zbar.android.scanner.ZBarConstants;\nimport com.google.android.material.dialog.MaterialAlertDialogBuilder;\nimport com.google.android.material.progressindicator.ProgressIndicator;\nimport com.samourai.wallet.R;\nimport com.samourai.wallet.ReceiveActivity;\nimport com.samourai.wallet.SamouraiActivity;\nimport com.samourai.wallet.SamouraiWallet;\nimport com.samourai.wallet.paynym.fragments.PayNymOnBoardBottomSheet;\nimport com.samourai.wallet.send.soroban.meeting.SorobanMeetingListenActivity;\nimport com.samourai.wallet.settings.SettingsActivity;\nimport com.samourai.wallet.access.AccessFactory;\nimport com.samourai.wallet.api.APIFactory;\nimport com.samourai.wallet.api.Tx;\nimport com.samourai.wallet.bip47.BIP47Meta;\nimport com.samourai.wallet.bip47.BIP47Util;\nimport com.samourai.wallet.cahoots.Cahoots;\nimport com.samourai.wallet.cahoots.psbt.PSBTUtil;\nimport com.samourai.wallet.crypto.AESUtil;\nimport com.samourai.wallet.crypto.DecryptionException;\nimport com.samourai.wallet.fragments.CameraFragmentBottomSheet;\nimport com.samourai.wallet.hd.HD_Wallet;\nimport com.samourai.wallet.hd.HD_WalletFactory;\nimport com.samourai.wallet.home.adapters.TxAdapter;\nimport com.samourai.wallet.network.NetworkDashboard;\nimport com.samourai.wallet.network.dojo.DojoUtil;\nimport com.samourai.wallet.payload.PayloadUtil;\nimport com.samourai.wallet.paynym.PayNymHome;\nimport com.samourai.wallet.permissions.PermissionsUtil;\nimport com.samourai.wallet.ricochet.RicochetMeta;\nimport com.samourai.wallet.segwit.bech32.Bech32Util;\nimport com.samourai.wallet.send.BlockedUTXO;\nimport com.samourai.wallet.send.MyTransactionOutPoint;\nimport com.samourai.wallet.send.SendActivity;\nimport com.samourai.wallet.send.SweepUtil;\nimport com.samourai.wallet.send.UTXO;\nimport com.samourai.wallet.send.cahoots.ManualCahootsActivity;\nimport com.samourai.wallet.service.JobRefreshService;\nimport com.samourai.wallet.service.WebSocketService;\nimport com.samourai.wallet.tor.TorManager;\nimport com.samourai.wallet.tx.TxDetailsActivity;\nimport com.samourai.wallet.util.AppUtil;\nimport com.samourai.wallet.util.CharSequenceX;\nimport com.samourai.wallet.util.FormatsUtil;\nimport com.samourai.wallet.util.MessageSignUtil;\nimport com.samourai.wallet.util.MonetaryUtil;\nimport com.samourai.wallet.util.PrefsUtil;\nimport com.samourai.wallet.util.PrivKeyReader;\nimport com.samourai.wallet.util.TimeOutUtil;\nimport com.samourai.wallet.utxos.UTXOSActivity;\nimport com.samourai.wallet.whirlpool.WhirlpoolMain;\nimport com.samourai.wallet.whirlpool.WhirlpoolMeta;\nimport com.samourai.wallet.whirlpool.service.WhirlpoolNotificationService;\nimport com.samourai.wallet.widgets.ItemDividerDecorator;\nimport com.squareup.picasso.Callback;\nimport com.squareup.picasso.Picasso;\n\nimport org.bitcoinj.core.Coin;\nimport org.bitcoinj.core.ECKey;\nimport org.bitcoinj.crypto.BIP38PrivateKey;\nimport org.bitcoinj.crypto.MnemonicException;\nimport org.bitcoinj.script.Script;\nimport org.bouncycastle.util.encoders.Hex;\nimport org.json.JSONArray;\nimport org.json.JSONException;\nimport org.json.JSONObject;\n\nimport java.io.IOException;\nimport java.text.DecimalFormat;\nimport java.text.DecimalFormatSymbols;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.ConcurrentModificationException;\nimport java.util.Iterator;\nimport java.util.List;\n\nimport io.matthewnelson.topl_service.TorServiceController;\nimport io.reactivex.Observable;\nimport io.reactivex.Single;\nimport io.reactivex.android.schedulers.AndroidSchedulers;\nimport io.reactivex.disposables.CompositeDisposable;\nimport io.reactivex.disposables.Disposable;\nimport io.reactivex.schedulers.Schedulers;\n\npublic class BalanceActivity extends SamouraiActivity {\n\n private final static int SCAN_COLD_STORAGE = 2011;\n private final static int SCAN_QR = 2012;\n private final static int UTXO_REQUESTCODE = 2012;\n private static final String TAG = \"BalanceActivity\";\n\n\n private List txs = null;\n private RecyclerView TxRecyclerView;\n private ProgressIndicator progressBar;\n private BalanceViewModel balanceViewModel;\n\n private RicochetQueueTask ricochetQueueTask = null;\n private com.github.clans.fab.FloatingActionMenu menuFab;\n private SwipeRefreshLayout txSwipeLayout;\n private CollapsingToolbarLayout mCollapsingToolbar;\n private CompositeDisposable compositeDisposable = new CompositeDisposable();\n private Toolbar toolbar;\n private Menu menu;\n private ImageView menuTorIcon;\n private ProgressBar progressBarMenu;\n private View whirlpoolFab, sendFab, receiveFab, paynymFab;\n\n public static final String ACTION_INTENT = \"com.samourai.wallet.BalanceFragment.REFRESH\";\n protected BroadcastReceiver receiver = new BroadcastReceiver() {\n @Override\n public void onReceive(final Context context, Intent intent) {\n\n if (ACTION_INTENT.equals(intent.getAction())) {\n if (progressBar != null) {\n showProgress();\n }\n final boolean notifTx = intent.getBooleanExtra(\"notifTx\", false);\n final boolean fetch = intent.getBooleanExtra(\"fetch\", false);\n\n final String rbfHash;\n final String blkHash;\n if (intent.hasExtra(\"rbf\")) {\n rbfHash = intent.getStringExtra(\"rbf\");\n } else {\n rbfHash = null;\n }\n if (intent.hasExtra(\"hash\")) {\n blkHash = intent.getStringExtra(\"hash\");\n } else {\n blkHash = null;\n }\n\n Handler handler = new Handler();\n handler.post(() -> {\n refreshTx(notifTx, false, false);\n\n if (BalanceActivity.this != null) {\n\n if (rbfHash != null) {\n new MaterialAlertDialogBuilder(BalanceActivity.this)\n .setTitle(R.string.app_name)\n .setMessage(rbfHash + \"\\n\\n\" + getString(R.string.rbf_incoming))\n .setCancelable(true)\n .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n\n doExplorerView(rbfHash);\n\n }\n })\n .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n ;\n }\n }).show();\n\n }\n\n }\n });\n\n }\n\n }\n };\n\n public static final String DISPLAY_INTENT = \"com.samourai.wallet.BalanceFragment.DISPLAY\";\n protected BroadcastReceiver receiverDisplay = new BroadcastReceiver() {\n @Override\n public void onReceive(final Context context, Intent intent) {\n\n if (DISPLAY_INTENT.equals(intent.getAction())) {\n\n updateDisplay(true);\n List utxos = APIFactory.getInstance(BalanceActivity.this).getUtxos(false);\n for (UTXO utxo : utxos) {\n List outpoints = utxo.getOutpoints();\n for (MyTransactionOutPoint out : outpoints) {\n\n byte[] scriptBytes = out.getScriptBytes();\n String address = null;\n try {\n if (Bech32Util.getInstance().isBech32Script(Hex.toHexString(scriptBytes))) {\n address = Bech32Util.getInstance().getAddressFromScript(Hex.toHexString(scriptBytes));\n } else {\n address = new Script(scriptBytes).getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString();\n }\n } catch (Exception e) {\n }\n String path = APIFactory.getInstance(BalanceActivity.this).getUnspentPaths().get(address);\n if (path != null && path.startsWith(\"M/1/\")) {\n continue;\n }\n\n final String hash = out.getHash().toString();\n final int idx = out.getTxOutputN();\n final long amount = out.getValue().longValue();\n boolean contains = ((BlockedUTXO.getInstance().contains(hash, idx) || BlockedUTXO.getInstance().containsNotDusted(hash, idx)));\n\n boolean containsInPostMix = (BlockedUTXO.getInstance().containsPostMix(hash, idx) || BlockedUTXO.getInstance().containsNotDustedPostMix(hash, idx));\n\n\n if (amount < BlockedUTXO.BLOCKED_UTXO_THRESHOLD && (!contains && !containsInPostMix)) {\n\n// BalanceActivity.this.runOnUiThread(new Runnable() {\n// @Override\n Handler handler = new Handler();\n handler.post(() -> {\n\n String message = BalanceActivity.this.getString(R.string.dusting_attempt);\n message += \"\\n\\n\";\n message += BalanceActivity.this.getString(R.string.dusting_attempt_amount);\n message += \" \";\n message += Coin.valueOf(amount).toPlainString();\n message += \" BTC\\n\";\n message += BalanceActivity.this.getString(R.string.dusting_attempt_id);\n message += \" \";\n message += hash + \"-\" + idx;\n\n MaterialAlertDialogBuilder dlg = new MaterialAlertDialogBuilder(BalanceActivity.this)\n .setTitle(R.string.dusting_tx)\n .setMessage(message)\n .setCancelable(false)\n .setPositiveButton(R.string.dusting_attempt_mark_unspendable, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n\n if (account == WhirlpoolMeta.getInstance(BalanceActivity.this).getWhirlpoolPostmix()) {\n BlockedUTXO.getInstance().addPostMix(hash, idx, amount);\n } else {\n BlockedUTXO.getInstance().add(hash, idx, amount);\n }\n saveState();\n }\n }).setNegativeButton(R.string.dusting_attempt_ignore, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n\n if (account == WhirlpoolMeta.getInstance(BalanceActivity.this).getWhirlpoolPostmix()) {\n BlockedUTXO.getInstance().addNotDustedPostMix(hash, idx);\n } else {\n BlockedUTXO.getInstance().addNotDusted(hash, idx);\n }\n saveState();\n }\n });\n if (!isFinishing()) {\n dlg.show();\n }\n\n });\n\n }\n\n }\n\n }\n\n }\n\n }\n };\n\n protected void onCreate(Bundle savedInstanceState) {\n\n //Switch themes based on accounts (blue theme for whirlpool account)\n setSwitchThemes(true);\n super.onCreate(savedInstanceState);\n\n setContentView(R.layout.activity_balance);\n balanceViewModel = ViewModelProviders.of(this).get(BalanceViewModel.class);\n balanceViewModel.setAccount(account);\n\n\n makePaynymAvatarcache();\n setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);\n\n TxRecyclerView = findViewById(R.id.rv_txes);\n progressBar = findViewById(R.id.progressBar);\n toolbar = findViewById(R.id.toolbar);\n mCollapsingToolbar = findViewById(R.id.toolbar_layout);\n txSwipeLayout = findViewById(R.id.tx_swipe_container);\n\n setSupportActionBar(toolbar);\n TxRecyclerView.setLayoutManager(new LinearLayoutManager(this));\n Drawable drawable = this.getResources().getDrawable(R.drawable.divider);\n TxRecyclerView.addItemDecoration(new ItemDividerDecorator(drawable));\n menuFab = findViewById(R.id.fab_menu);\n txs = new ArrayList<>();\n whirlpoolFab = findViewById(R.id.whirlpool_fab);\n sendFab = findViewById(R.id.send_fab);\n receiveFab = findViewById(R.id.receive_fab);\n paynymFab = findViewById(R.id.paynym_fab);\n\n findViewById(R.id.whirlpool_fab).setOnClickListener(view -> {\n Intent intent = new Intent(BalanceActivity.this, WhirlpoolMain.class);\n startActivity(intent);\n menuFab.toggle(true);\n });\n\n sendFab.setOnClickListener(view -> {\n Intent intent = new Intent(BalanceActivity.this, SendActivity.class);\n intent.putExtra(\"via_menu\", true);\n intent.putExtra(\"_account\", account);\n startActivity(intent);\n menuFab.toggle(true);\n });\n\n JSONObject payload = null;\n try {\n payload = PayloadUtil.getInstance(BalanceActivity.this).getPayload();\n } catch (Exception e) {\n AppUtil.getInstance(getApplicationContext()).restartApp();\n e.printStackTrace();\n return;\n }\n if(account == 0 && payload != null && payload.has(\"prev_balance\")) {\n try {\n setBalance(payload.getLong(\"prev_balance\"), false);\n }\n catch(Exception e) {\n setBalance(0L, false);\n }\n }\n else {\n setBalance(0L, false);\n }\n\n receiveFab.setOnClickListener(view -> {\n menuFab.toggle(true);\n\n HD_Wallet hdw = HD_WalletFactory.getInstance(BalanceActivity.this).get();\n\n if (hdw != null) {\n Intent intent = new Intent(BalanceActivity.this, ReceiveActivity.class);\n startActivity(intent);\n }\n });\n paynymFab.setOnClickListener(view -> {\n menuFab.toggle(true);\n Intent intent = new Intent(BalanceActivity.this, PayNymHome.class);\n startActivity(intent);\n });\n txSwipeLayout.setOnRefreshListener(() -> {\n refreshTx(false, true, false);\n txSwipeLayout.setRefreshing(false);\n showProgress();\n });\n\n IntentFilter filter = new IntentFilter(ACTION_INTENT);\n LocalBroadcastManager.getInstance(BalanceActivity.this).registerReceiver(receiver, filter);\n IntentFilter filterDisplay = new IntentFilter(DISPLAY_INTENT);\n LocalBroadcastManager.getInstance(BalanceActivity.this).registerReceiver(receiverDisplay, filterDisplay);\n\n if (!PermissionsUtil.getInstance(BalanceActivity.this).hasPermission(Manifest.permission.READ_EXTERNAL_STORAGE) || !PermissionsUtil.getInstance(BalanceActivity.this).hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {\n PermissionsUtil.getInstance(BalanceActivity.this).showRequestPermissionsInfoAlertDialog(PermissionsUtil.READ_WRITE_EXTERNAL_PERMISSION_CODE);\n }\n if (!PermissionsUtil.getInstance(BalanceActivity.this).hasPermission(Manifest.permission.CAMERA)) {\n PermissionsUtil.getInstance(BalanceActivity.this).showRequestPermissionsInfoAlertDialog(PermissionsUtil.CAMERA_PERMISSION_CODE);\n }\n if (PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.PAYNYM_CLAIMED, false) && !PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.PAYNYM_FEATURED_SEGWIT, false)) {\n doFeaturePayNymUpdate();\n } else if (!PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.PAYNYM_CLAIMED, false) &&\n !PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.PAYNYM_REFUSED, false)) {\n PayNymOnBoardBottomSheet payNymOnBoardBottomSheet = new PayNymOnBoardBottomSheet();\n payNymOnBoardBottomSheet.show(getSupportFragmentManager(),payNymOnBoardBottomSheet.getTag());\n }\n Log.i(TAG, \"onCreate:PAYNYM_REFUSED \".concat(String.valueOf(PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.PAYNYM_REFUSED, false))));\n\n if (RicochetMeta.getInstance(BalanceActivity.this).getQueue().size() > 0) {\n if (ricochetQueueTask == null || ricochetQueueTask.getStatus().equals(AsyncTask.Status.FINISHED)) {\n ricochetQueueTask = new RicochetQueueTask();\n ricochetQueueTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);\n }\n }\n\n if (!AppUtil.getInstance(BalanceActivity.this).isClipboardSeen()) {\n doClipboardCheck();\n }\n\n\n if (!AppUtil.getInstance(BalanceActivity.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) {\n startService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class));\n }\n setUpTor();\n initViewModel();\n showProgress();\n\n if (account == 0) {\n final Handler delayedHandler = new Handler();\n delayedHandler.postDelayed(() -> {\n\n boolean notifTx = false;\n Bundle extras = getIntent().getExtras();\n if (extras != null && extras.containsKey(\"notifTx\")) {\n notifTx = extras.getBoolean(\"notifTx\");\n }\n\n refreshTx(notifTx, false, true);\n\n updateDisplay(false);\n }, 100L);\n\n getSupportActionBar().setIcon(R.drawable.ic_samourai_logo);\n\n }\n else {\n getSupportActionBar().setIcon(R.drawable.ic_whirlpool);\n receiveFab.setVisibility(View.GONE);\n whirlpoolFab.setVisibility(View.GONE);\n paynymFab.setVisibility(View.GONE);\n new Handler().postDelayed(() -> updateDisplay(true), 600L);\n }\n balanceViewModel.loadOfflineData();\n\n boolean hadContentDescription = android.text.TextUtils.isEmpty(toolbar.getLogoDescription());\n String contentDescription = String.valueOf(!hadContentDescription ? toolbar.getLogoDescription() : \"logoContentDescription\");\n toolbar.setLogoDescription(contentDescription);\n ArrayList potentialViews = new ArrayList();\n toolbar.findViewsWithText(potentialViews,contentDescription, View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION);\n View logoView = null;\n if(potentialViews.size() > 0){\n logoView = potentialViews.get(0);\n if (account == 0) {\n logoView.setOnClickListener(new View.OnClickListener() {\n @Override public void onClick(View v) {\n Intent _intent = new Intent(BalanceActivity.this, BalanceActivity.class);\n _intent.putExtra(\"_account\", WhirlpoolMeta.getInstance(BalanceActivity.this).getWhirlpoolPostmix());\n startActivity(_intent);\n } });\n } else {\n logoView.setOnClickListener(new View.OnClickListener() {\n @Override public void onClick(View v) {\n Intent _intent = new Intent(BalanceActivity.this, BalanceActivity.class);\n _intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);\n startActivity(_intent);\n } });\n }\n }\n\n updateDisplay(false);\n checkDeepLinks();\n }\n\n private void hideProgress() {\n progressBar.hide();\n }\n\n private void showProgress() {\n progressBar.setIndeterminate(true);\n progressBar.show();\n }\n\n private void checkDeepLinks() {\n Bundle bundle = getIntent().getExtras();\n if (bundle == null) {\n return;\n }\n if (bundle.containsKey(\"pcode\") || bundle.containsKey(\"uri\") || bundle.containsKey(\"amount\")) {\n if (balanceViewModel.getBalance().getValue() != null)\n bundle.putLong(\"balance\", balanceViewModel.getBalance().getValue());\n Intent intent = new Intent(this, SendActivity.class);\n intent.putExtra(\"_account\",account);\n intent.putExtras(bundle);\n startActivity(intent);\n }\n\n }\n\n @Override\n protected void onNewIntent(Intent intent) {\n super.onNewIntent(intent);\n setIntent(intent);\n }\n\n private void initViewModel() {\n TxAdapter adapter = new TxAdapter(getApplicationContext(), new ArrayList<>(), account);\n adapter.setHasStableIds(true);\n adapter.setClickListener((position, tx) -> txDetails(tx));\n\n TxRecyclerView.setAdapter(adapter);\n\n balanceViewModel.getBalance().observe(this, balance -> {\n if (balance < 0) {\n return;\n }\n if (balanceViewModel.getSatState().getValue() != null) {\n setBalance(balance, balanceViewModel.getSatState().getValue());\n } else {\n setBalance(balance, false);\n }\n });\n adapter.setTxes(balanceViewModel.getTxs().getValue());\n setBalance(balanceViewModel.getBalance().getValue(), false);\n\n balanceViewModel.getSatState().observe(this, state -> {\n if (state == null) {\n state = false;\n }\n setBalance(balanceViewModel.getBalance().getValue(), state);\n adapter.toggleDisplayUnit(state);\n });\n balanceViewModel.getTxs().observe(this, new Observer>() {\n @Override\n public void onChanged(@Nullable List list) {\n adapter.setTxes(list);\n }\n });\n mCollapsingToolbar.setOnClickListener(view -> balanceViewModel.toggleSat());\n\n mCollapsingToolbar.setOnLongClickListener(view -> {\n Intent intent = new Intent(BalanceActivity.this, UTXOSActivity.class);\n intent.putExtra(\"_account\", account);\n startActivityForResult(intent,UTXO_REQUESTCODE);\n\n return false;\n });\n }\n\n private void setBalance(Long balance, boolean isSat) {\n if (balance == null) {\n return;\n }\n\n if (getSupportActionBar() != null) {\n TransitionManager.beginDelayedTransition(mCollapsingToolbar, new ChangeBounds());\n\n String displayAmount = \"\".concat(isSat ? getSatoshiDisplayAmount(balance) : getBTCDisplayAmount(balance));\n String Unit = isSat ? getSatoshiDisplayUnits() : getBTCDisplayUnits();\n\n displayAmount = displayAmount.concat(\" \").concat(Unit);\n toolbar.setTitle(displayAmount);\n setTitle(displayAmount);\n mCollapsingToolbar.setTitle(displayAmount);\n\n }\n\n\n Log.i(TAG, \"setBalance: \".concat(getBTCDisplayAmount(balance)));\n\n }\n\n @Override\n public void onResume() {\n super.onResume();\n\n// IntentFilter filter = new IntentFilter(ACTION_INTENT);\n// LocalBroadcastManager.getInstance(BalanceActivity.this).registerReceiver(receiver, filter);\n\n AppUtil.getInstance(BalanceActivity.this).checkTimeOut();\n//\n// Intent intent = new Intent(\"com.samourai.wallet.MainActivity2.RESTART_SERVICE\");\n// LocalBroadcastManager.getInstance(BalanceActivity.this).sendBroadcast(intent);\n\n }\n\n public View createTag(String text){\n float scale = getResources().getDisplayMetrics().density;\n LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(\n LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);\n TextView textView = new TextView(getApplicationContext());\n textView.setText(text);\n textView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.white));\n textView.setLayoutParams(lparams);\n textView.setBackgroundResource(R.drawable.tag_round_shape);\n textView.setPadding((int) (8 * scale + 0.5f), (int) (6 * scale + 0.5f), (int) (8 * scale + 0.5f), (int) (6 * scale + 0.5f));\n textView.setTypeface(Typeface.DEFAULT_BOLD);\n textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 11);\n return textView;\n }\n\n @Override\n public void onPause() {\n super.onPause();\n\n// ibQuickSend.collapse();\n\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && AppUtil.getInstance(BalanceActivity.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) {\n stopService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class));\n }\n\n }\n\n\n private void makePaynymAvatarcache() {\n try {\n\n ArrayList paymentCodes = new ArrayList<>(BIP47Meta.getInstance().getSortedByLabels(false, true));\n for (String code : paymentCodes) {\n Picasso.get()\n .load(com.samourai.wallet.bip47.paynym.WebUtil.PAYNYM_API + code + \"/avatar\").fetch(new Callback() {\n @Override\n public void onSuccess() {\n /*NO OP*/\n }\n\n @Override\n public void onError(Exception e) {\n /*NO OP*/\n }\n });\n }\n\n } catch (Exception ignored) {\n\n }\n }\n\n @Override\n public void onDestroy() {\n\n LocalBroadcastManager.getInstance(BalanceActivity.this).unregisterReceiver(receiver);\n LocalBroadcastManager.getInstance(BalanceActivity.this).unregisterReceiver(receiverDisplay);\n\n if(account == 0) {\n if (AppUtil.getInstance(BalanceActivity.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) {\n stopService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class));\n }\n }\n\n super.onDestroy();\n\n if(compositeDisposable != null && !compositeDisposable.isDisposed()) {\n compositeDisposable.dispose();\n }\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n getMenuInflater().inflate(R.menu.main, menu);\n\n menu.findItem(R.id.action_refresh).setVisible(false);\n menu.findItem(R.id.action_share_receive).setVisible(false);\n menu.findItem(R.id.action_ricochet).setVisible(false);\n menu.findItem(R.id.action_empty_ricochet).setVisible(false);\n menu.findItem(R.id.action_sign).setVisible(false);\n menu.findItem(R.id.action_fees).setVisible(false);\n menu.findItem(R.id.action_batch).setVisible(false);\n\n WhirlpoolMeta.getInstance(getApplicationContext());\n if (account == WhirlpoolMeta.getInstance(getApplicationContext()).getWhirlpoolPostmix()) {\n\n menu.findItem(R.id.action_sweep).setVisible(false);\n menu.findItem(R.id.action_backup).setVisible(false);\n menu.findItem(R.id.action_postmix).setVisible(false);\n\n menu.findItem(R.id.action_network_dashboard).setVisible(false);\n MenuItem item = menu.findItem(R.id.action_menu_account);\n item.setActionView(createTag(\" POST-MIX \"));\n item.setVisible(true);\n item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);\n\n }\n else {\n menu.findItem(R.id.action_soroban_collab).setVisible(false);\n }\n this.menu = menu;\n\n return super.onCreateOptionsMenu(menu);\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n // Handle action bar item clicks here. The action bar will\n // automatically handle clicks on the Home/Up button, so long\n // as you specify a parent activity in AndroidManifest.xml.\n int id = item.getItemId();\n\n if(id == android.R.id.home){\n this.finish();\n return super.onOptionsItemSelected(item);\n }\n // noinspection SimplifiableIfStatement\n if (id == R.id.action_network_dashboard) {\n startActivity(new Intent(this, NetworkDashboard.class));\n } // noinspection SimplifiableIfStatement\n if (id == R.id.action_copy_cahoots) {\n ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);\n if(clipboard.hasPrimaryClip()) {\n ClipData.Item clipItem = clipboard.getPrimaryClip().getItemAt(0);\n\n if(Cahoots.isCahoots(clipItem.getText().toString().trim())){\n try {\n Intent cahootIntent = ManualCahootsActivity.createIntentResume(this, account, clipItem.getText().toString().trim());\n startActivity(cahootIntent);\n }\n catch (Exception e) {\n Toast.makeText(this,R.string.cannot_process_cahoots,Toast.LENGTH_SHORT).show();\n e.printStackTrace();\n }\n }\n else {\n Toast.makeText(this,R.string.cannot_process_cahoots,Toast.LENGTH_SHORT).show();\n }\n }\n else {\n Toast.makeText(this,R.string.clipboard_empty,Toast.LENGTH_SHORT).show();\n }\n }\n if (id == R.id.action_settings) {\n doSettings();\n }\n else if (id == R.id.action_support) {\n doSupport();\n }\n else if (id == R.id.action_sweep) {\n if (!AppUtil.getInstance(BalanceActivity.this).isOfflineMode()) {\n doSweep();\n }\n else {\n Toast.makeText(BalanceActivity.this, R.string.in_offline_mode, Toast.LENGTH_SHORT).show();\n }\n }\n else if (id == R.id.action_utxo) {\n doUTXO();\n }\n else if (id == R.id.action_backup) {\n\n if (SamouraiWallet.getInstance().hasPassphrase(BalanceActivity.this)) {\n if (HD_WalletFactory.getInstance(BalanceActivity.this).get() != null && SamouraiWallet.getInstance().hasPassphrase(BalanceActivity.this)) {\n doBackup();\n }\n else {\n\n MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);\n builder.setMessage(R.string.passphrase_needed_for_backup).setCancelable(false);\n AlertDialog alert = builder.create();\n\n alert.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.ok), new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int id) {\n dialog.dismiss();\n }\n });\n\n if (!isFinishing()) {\n alert.show();\n }\n\n }\n }\n else {\n Toast.makeText(BalanceActivity.this, R.string.passphrase_required, Toast.LENGTH_SHORT).show();\n }\n\n }\n else if (id == R.id.action_scan_qr) {\n doScan();\n }\n else if (id == R.id.action_postmix) {\n\n Intent intent = new Intent(BalanceActivity.this, SendActivity.class);\n intent.putExtra(\"_account\", WhirlpoolMeta.getInstance(BalanceActivity.this).getWhirlpoolPostmix());\n startActivity(intent);\n\n }\n else if(id == R.id.action_soroban_collab) {\n Intent intent = new Intent(this, SorobanMeetingListenActivity.class);\n intent.putExtra(\"_account\", WhirlpoolMeta.getInstance(BalanceActivity.this).getWhirlpoolPostmix());\n startActivity(intent);\n }\n else {\n ;\n }\n return super.onOptionsItemSelected(item);\n }\n\n\n private void setUpTor() {\n TorManager.INSTANCE.getTorStateLiveData().observe(this,torState -> {\n if (torState == TorManager.TorState.ON) {\n PrefsUtil.getInstance(this).setValue(PrefsUtil.ENABLE_TOR, true);\n if (this.progressBarMenu != null) {\n this.progressBarMenu.setVisibility(View.INVISIBLE);\n this.menuTorIcon.setImageResource(R.drawable.tor_on);\n }\n\n } else if (torState == TorManager.TorState.WAITING) {\n if (this.progressBarMenu != null) {\n this.progressBarMenu.setVisibility(View.VISIBLE);\n this.menuTorIcon.setImageResource(R.drawable.tor_on);\n }\n } else {\n if (this.progressBarMenu != null) {\n this.progressBarMenu.setVisibility(View.INVISIBLE);\n this.menuTorIcon.setImageResource(R.drawable.tor_off);\n }\n\n }\n });\n }\n\n\n @Override\n public void onActivityResult(int requestCode, int resultCode, Intent data) {\n\n super.onActivityResult(requestCode, resultCode, data);\n if (resultCode == Activity.RESULT_OK && requestCode == SCAN_COLD_STORAGE) {\n\n if (data != null && data.getStringExtra(ZBarConstants.SCAN_RESULT) != null) {\n\n final String strResult = data.getStringExtra(ZBarConstants.SCAN_RESULT);\n\n doPrivKey(strResult);\n\n }\n } else if (resultCode == Activity.RESULT_CANCELED && requestCode == SCAN_COLD_STORAGE) {\n } else if (resultCode == Activity.RESULT_OK && requestCode == SCAN_QR) {\n\n if (data != null && data.getStringExtra(ZBarConstants.SCAN_RESULT) != null) {\n\n final String strResult = data.getStringExtra(ZBarConstants.SCAN_RESULT);\n\n PrivKeyReader privKeyReader = new PrivKeyReader(new CharSequenceX(strResult.trim()));\n try {\n if (privKeyReader.getFormat() != null) {\n doPrivKey(strResult.trim());\n } else if (Cahoots.isCahoots(strResult.trim())) {\n Intent cahootIntent = ManualCahootsActivity.createIntentResume(this, account, strResult.trim());\n startActivity(cahootIntent);\n } else if (FormatsUtil.getInstance().isPSBT(strResult.trim())) {\n PSBTUtil.getInstance(BalanceActivity.this).doPSBT(strResult.trim());\n } else if (DojoUtil.getInstance(BalanceActivity.this).isValidPairingPayload(strResult.trim())) {\n\n Intent intent = new Intent(BalanceActivity.this, NetworkDashboard.class);\n intent.putExtra(\"params\", strResult.trim());\n startActivity(intent);\n\n } else {\n Intent intent = new Intent(BalanceActivity.this, SendActivity.class);\n intent.putExtra(\"uri\", strResult.trim());\n intent.putExtra(\"_account\", account);\n startActivity(intent);\n }\n } catch (Exception e) {\n }\n\n }\n }\n if (resultCode == Activity.RESULT_OK && requestCode == UTXO_REQUESTCODE) {\n refreshTx(false, false, false);\n showProgress();\n } else {\n ;\n }\n\n }\n\n\n @Override\n public void onBackPressed() {\n\n\n if (account == 0) {\n\n MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);\n builder.setMessage(R.string.ask_you_sure_exit);\n AlertDialog alert = builder.create();\n\n alert.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.yes), (dialog, id) -> {\n\n try {\n PayloadUtil.getInstance(BalanceActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BalanceActivity.this).getGUID() + AccessFactory.getInstance(BalanceActivity.this).getPIN()));\n } catch (MnemonicException.MnemonicLengthException mle) {\n } catch (JSONException je) {\n } catch (IOException ioe) {\n } catch (DecryptionException de) {\n }\n\n // disconnect Whirlpool on app back key exit\n if (WhirlpoolNotificationService.isRunning(getApplicationContext()))\n WhirlpoolNotificationService.stopService(getApplicationContext());\n\n if (TorManager.INSTANCE.isConnected()) {\n TorServiceController.stopTor();\n }\n TimeOutUtil.getInstance().reset();\n finishAffinity();\n finish();\n super.onBackPressed();\n });\n\n alert.setButton(AlertDialog.BUTTON_NEGATIVE, getString(R.string.no), (dialog, id) -> dialog.dismiss());\n alert.show();\n\n } else {\n super.onBackPressed();\n }\n }\n\n private void updateDisplay(boolean fromRefreshService) {\n Disposable txDisposable = loadTxes(account)\n .subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread())\n .subscribe((txes, throwable) -> {\n if (throwable != null)\n throwable.printStackTrace();\n\n\n if (txes != null) {\n if (txes.size() != 0) {\n balanceViewModel.setTx(txes);\n } else {\n if (balanceViewModel.getTxs().getValue() != null && balanceViewModel.getTxs().getValue().size() == 0) {\n balanceViewModel.setTx(txes);\n }\n }\n\n Collections.sort(txes, new APIFactory.TxMostRecentDateComparator());\n txs.clear();\n txs.addAll(txes);\n }\n\n if (progressBar.getVisibility() == View.VISIBLE && fromRefreshService) {\n hideProgress();\n }\n });\n\n Disposable balanceDisposable = loadBalance(account)\n .subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread())\n .subscribe((balance, throwable) -> {\n if (throwable != null)\n throwable.printStackTrace();\n\n if (balanceViewModel.getBalance().getValue() != null) {\n balanceViewModel.setBalance(balance);\n } else {\n balanceViewModel.setBalance(balance);\n }\n });\n compositeDisposable.add(balanceDisposable);\n compositeDisposable.add(txDisposable);\n// displayBalance();\n// txAdapter.notifyDataSetChanged();\n\n\n }\n\n private Single> loadTxes(int account) {\n return Single.fromCallable(() -> {\n List loadedTxes = new ArrayList<>();\n if (account == 0) {\n loadedTxes = APIFactory.getInstance(BalanceActivity.this).getAllXpubTxs();\n } else if (account == WhirlpoolMeta.getInstance(getApplicationContext()).getWhirlpoolPostmix()) {\n loadedTxes = APIFactory.getInstance(BalanceActivity.this).getAllPostMixTxs();\n }\n return loadedTxes;\n });\n }\n\n private Single loadBalance(int account) {\n return Single.fromCallable(() -> {\n long loadedBalance = 0L;\n if (account == 0) {\n loadedBalance = APIFactory.getInstance(BalanceActivity.this).getXpubBalance();\n } else if (account == WhirlpoolMeta.getInstance(getApplicationContext()).getWhirlpoolPostmix()) {\n loadedBalance = APIFactory.getInstance(BalanceActivity.this).getXpubPostMixBalance();\n }\n return loadedBalance;\n });\n }\n\n\n private void doSettings() {\n TimeOutUtil.getInstance().updatePin();\n Intent intent = new Intent(BalanceActivity.this, SettingsActivity.class);\n startActivity(intent);\n }\n\n private void doSupport() {\n Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"https://support.samourai.io/\"));\n startActivity(intent);\n }\n\n private void doUTXO() {\n Intent intent = new Intent(BalanceActivity.this, UTXOSActivity.class);\n intent.putExtra(\"_account\", account);\n startActivityForResult(intent,UTXO_REQUESTCODE);\n }\n\n private void doScan() {\n\n CameraFragmentBottomSheet cameraFragmentBottomSheet = new CameraFragmentBottomSheet();\n cameraFragmentBottomSheet.show(getSupportFragmentManager(), cameraFragmentBottomSheet.getTag());\n\n cameraFragmentBottomSheet.setQrCodeScanLisenter(code -> {\n cameraFragmentBottomSheet.dismissAllowingStateLoss();\n PrivKeyReader privKeyReader = new PrivKeyReader(new CharSequenceX(code.trim()));\n try {\n if (privKeyReader.getFormat() != null) {\n doPrivKey(code.trim());\n } else if (Cahoots.isCahoots(code.trim())) {\n Intent cahootIntent = ManualCahootsActivity.createIntentResume(this, account, code.trim());\n startActivity(cahootIntent);\n\n } else if (FormatsUtil.getInstance().isPSBT(code.trim())) {\n PSBTUtil.getInstance(BalanceActivity.this).doPSBT(code.trim());\n } else if (DojoUtil.getInstance(BalanceActivity.this).isValidPairingPayload(code.trim())) {\n Intent intent = new Intent(BalanceActivity.this, NetworkDashboard.class);\n intent.putExtra(\"params\", code.trim());\n startActivity(intent);\n } else {\n Intent intent = new Intent(BalanceActivity.this, SendActivity.class);\n intent.putExtra(\"uri\", code.trim());\n intent.putExtra(\"_account\", account);\n startActivity(intent);\n }\n } catch (Exception e) {\n }\n });\n }\n\n private void doSweepViaScan() {\n\n CameraFragmentBottomSheet cameraFragmentBottomSheet = new CameraFragmentBottomSheet();\n cameraFragmentBottomSheet.show(getSupportFragmentManager(), cameraFragmentBottomSheet.getTag());\n cameraFragmentBottomSheet.setQrCodeScanLisenter(code -> {\n cameraFragmentBottomSheet.dismissAllowingStateLoss();\n PrivKeyReader privKeyReader = new PrivKeyReader(new CharSequenceX(code.trim()));\n try {\n if (privKeyReader.getFormat() != null) {\n doPrivKey(code.trim());\n } else if (Cahoots.isCahoots(code.trim())) {\n Intent cahootIntent = ManualCahootsActivity.createIntentResume(this, account, code.trim());\n startActivity(cahootIntent);\n } else if (FormatsUtil.getInstance().isPSBT(code.trim())) {\n PSBTUtil.getInstance(BalanceActivity.this).doPSBT(code.trim());\n } else if (DojoUtil.getInstance(BalanceActivity.this).isValidPairingPayload(code.trim())) {\n Toast.makeText(BalanceActivity.this, \"Samourai Dojo full node coming soon.\", Toast.LENGTH_SHORT).show();\n } else {\n Intent intent = new Intent(BalanceActivity.this, SendActivity.class);\n intent.putExtra(\"uri\", code.trim());\n intent.putExtra(\"_account\", account);\n startActivity(intent);\n }\n } catch (Exception e) {\n }\n });\n }\n\n private void doSweep() {\n\n MaterialAlertDialogBuilder dlg = new MaterialAlertDialogBuilder(BalanceActivity.this)\n .setTitle(R.string.app_name)\n .setMessage(R.string.action_sweep)\n .setCancelable(true)\n .setPositiveButton(R.string.enter_privkey, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n\n final EditText privkey = new EditText(BalanceActivity.this);\n privkey.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);\n\n MaterialAlertDialogBuilder dlg = new MaterialAlertDialogBuilder(BalanceActivity.this)\n .setTitle(R.string.app_name)\n .setMessage(R.string.enter_privkey)\n .setView(privkey)\n .setCancelable(false)\n .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n\n final String strPrivKey = privkey.getText().toString();\n\n if (strPrivKey != null && strPrivKey.length() > 0) {\n doPrivKey(strPrivKey);\n }\n\n }\n }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n\n dialog.dismiss();\n\n }\n });\n if (!isFinishing()) {\n dlg.show();\n }\n\n }\n\n }).setNegativeButton(R.string.scan, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n\n doSweepViaScan();\n\n }\n });\n if (!isFinishing()) {\n dlg.show();\n }\n\n }\n\n private void doPrivKey(final String data) {\n\n PrivKeyReader privKeyReader = null;\n\n String format = null;\n try {\n privKeyReader = new PrivKeyReader(new CharSequenceX(data), null);\n format = privKeyReader.getFormat();\n } catch (Exception e) {\n Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();\n return;\n }\n\n if (format != null) {\n\n if (format.equals(PrivKeyReader.BIP38)) {\n\n final PrivKeyReader pvr = privKeyReader;\n\n final EditText password38 = new EditText(BalanceActivity.this);\n password38.setSingleLine(true);\n password38.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);\n\n MaterialAlertDialogBuilder dlg = new MaterialAlertDialogBuilder(BalanceActivity.this)\n .setTitle(R.string.app_name)\n .setMessage(R.string.bip38_pw)\n .setView(password38)\n .setCancelable(false)\n .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n\n String password = password38.getText().toString();\n\n ProgressDialog progress = new ProgressDialog(BalanceActivity.this);\n progress.setCancelable(false);\n progress.setTitle(R.string.app_name);\n progress.setMessage(getString(R.string.decrypting_bip38));\n progress.show();\n\n boolean keyDecoded = false;\n\n try {\n BIP38PrivateKey bip38 = new BIP38PrivateKey(SamouraiWallet.getInstance().getCurrentNetworkParams(), data);\n final ECKey ecKey = bip38.decrypt(password);\n if (ecKey != null && ecKey.hasPrivKey()) {\n\n if (progress != null && progress.isShowing()) {\n progress.cancel();\n }\n\n pvr.setPassword(new CharSequenceX(password));\n keyDecoded = true;\n\n Toast.makeText(BalanceActivity.this, pvr.getFormat(), Toast.LENGTH_SHORT).show();\n Toast.makeText(BalanceActivity.this, pvr.getKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(), Toast.LENGTH_SHORT).show();\n\n }\n } catch (Exception e) {\n e.printStackTrace();\n Toast.makeText(BalanceActivity.this, R.string.bip38_pw_error, Toast.LENGTH_SHORT).show();\n }\n\n if (progress != null && progress.isShowing()) {\n progress.cancel();\n }\n\n if (keyDecoded) {\n SweepUtil.getInstance(BalanceActivity.this).sweep(pvr, SweepUtil.TYPE_P2PKH);\n }\n\n }\n }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n\n Toast.makeText(BalanceActivity.this, R.string.bip38_pw_error, Toast.LENGTH_SHORT).show();\n\n }\n });\n if (!isFinishing()) {\n dlg.show();\n }\n\n } else if (privKeyReader != null) {\n SweepUtil.getInstance(BalanceActivity.this).sweep(privKeyReader, SweepUtil.TYPE_P2PKH);\n } else {\n ;\n }\n\n } else {\n Toast.makeText(BalanceActivity.this, R.string.cannot_recognize_privkey, Toast.LENGTH_SHORT).show();\n }\n\n }\n\n private void doBackup() {\n\n final String passphrase = HD_WalletFactory.getInstance(BalanceActivity.this).get().getPassphrase();\n\n final String[] export_methods = new String[2];\n export_methods[0] = getString(R.string.export_to_clipboard);\n export_methods[1] = getString(R.string.export_to_email);\n\n new MaterialAlertDialogBuilder(BalanceActivity.this)\n .setTitle(R.string.options_export)\n .setSingleChoiceItems(export_methods, 0, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int which) {\n\n try {\n PayloadUtil.getInstance(BalanceActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BalanceActivity.this).getGUID() + AccessFactory.getInstance(BalanceActivity.this).getPIN()));\n } catch (IOException ioe) {\n ;\n } catch (JSONException je) {\n ;\n } catch (DecryptionException de) {\n ;\n } catch (MnemonicException.MnemonicLengthException mle) {\n ;\n }\n\n String encrypted = null;\n try {\n encrypted = AESUtil.encrypt(PayloadUtil.getInstance(BalanceActivity.this).getPayload().toString(), new CharSequenceX(passphrase), AESUtil.DefaultPBKDF2Iterations);\n } catch (Exception e) {\n Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();\n } finally {\n if (encrypted == null) {\n Toast.makeText(BalanceActivity.this, R.string.encryption_error, Toast.LENGTH_SHORT).show();\n return;\n }\n }\n\n JSONObject obj = PayloadUtil.getInstance(BalanceActivity.this).putPayload(encrypted, true);\n\n if (which == 0) {\n android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(android.content.Context.CLIPBOARD_SERVICE);\n android.content.ClipData clip = null;\n clip = android.content.ClipData.newPlainText(\"Wallet backup\", obj.toString());\n clipboard.setPrimaryClip(clip);\n Toast.makeText(BalanceActivity.this, R.string.copied_to_clipboard, Toast.LENGTH_SHORT).show();\n } else {\n Intent email = new Intent(Intent.ACTION_SEND);\n email.putExtra(Intent.EXTRA_SUBJECT, \"Samourai Wallet backup\");\n email.putExtra(Intent.EXTRA_TEXT, obj.toString());\n email.setType(\"message/rfc822\");\n startActivity(Intent.createChooser(email, BalanceActivity.this.getText(R.string.choose_email_client)));\n }\n\n dialog.dismiss();\n }\n }\n ).show();\n\n }\n\n private void doClipboardCheck() {\n\n final android.content.ClipboardManager clipboard = (android.content.ClipboardManager) BalanceActivity.this.getSystemService(android.content.Context.CLIPBOARD_SERVICE);\n if (clipboard.hasPrimaryClip()) {\n final ClipData clip = clipboard.getPrimaryClip();\n ClipData.Item item = clip.getItemAt(0);\n if (item.getText() != null) {\n String text = item.getText().toString();\n String[] s = text.split(\"\\\\s+\");\n\n try {\n for (int i = 0; i < s.length; i++) {\n PrivKeyReader privKeyReader = new PrivKeyReader(new CharSequenceX(s[i]));\n if (privKeyReader.getFormat() != null &&\n (privKeyReader.getFormat().equals(PrivKeyReader.WIF_COMPRESSED) ||\n privKeyReader.getFormat().equals(PrivKeyReader.WIF_UNCOMPRESSED) ||\n privKeyReader.getFormat().equals(PrivKeyReader.BIP38) ||\n FormatsUtil.getInstance().isValidXprv(s[i])\n )\n ) {\n\n new MaterialAlertDialogBuilder(BalanceActivity.this)\n .setTitle(R.string.app_name)\n .setMessage(R.string.privkey_clipboard)\n .setCancelable(false)\n .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {\n\n public void onClick(DialogInterface dialog, int whichButton) {\n\n clipboard.setPrimaryClip(ClipData.newPlainText(\"\", \"\"));\n\n }\n\n }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {\n\n public void onClick(DialogInterface dialog, int whichButton) {\n ;\n }\n }).show();\n\n }\n }\n } catch (Exception e) {\n ;\n }\n }\n }\n\n }\n\n private void refreshTx(final boolean notifTx, final boolean dragged, final boolean launch) {\n\n if (AppUtil.getInstance(BalanceActivity.this).isOfflineMode()) {\n Toast.makeText(BalanceActivity.this, R.string.in_offline_mode, Toast.LENGTH_SHORT).show();\n /*\n CoordinatorLayout coordinatorLayout = new CoordinatorLayout(BalanceActivity.this);\n Snackbar snackbar = Snackbar.make(coordinatorLayout, R.string.in_offline_mode, Snackbar.LENGTH_LONG);\n snackbar.show();\n */\n }\n\n\n Intent intent = new Intent(this, JobRefreshService.class);\n intent.putExtra(\"notifTx\", notifTx);\n intent.putExtra(\"dragged\", dragged);\n intent.putExtra(\"launch\", launch);\n JobRefreshService.enqueueWork(getApplicationContext(), intent);\n//\n//\n// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {\n// startForegroundService(intent);\n// } else {\n// startService(intent);\n// }\n\n }\n\n private String getBTCDisplayAmount(long value) {\n return Coin.valueOf(value).toPlainString();\n }\n\n private String getSatoshiDisplayAmount(long value) {\n DecimalFormatSymbols symbols = new DecimalFormatSymbols();\n symbols.setGroupingSeparator(' ');\n DecimalFormat df = new DecimalFormat(\"#\", symbols);\n df.setMinimumIntegerDigits(1);\n df.setMaximumIntegerDigits(16);\n df.setGroupingUsed(true);\n df.setGroupingSize(3);\n return df.format(value);\n }\n\n private String getBTCDisplayUnits() {\n\n return MonetaryUtil.getInstance().getBTCUnits();\n\n }\n\n private String getSatoshiDisplayUnits() {\n\n return MonetaryUtil.getInstance().getSatoshiUnits();\n\n }\n\n\n private void doExplorerView(String strHash) {\n\n if (strHash != null) {\n\n String blockExplorer = \"https://m.oxt.me/transaction/\";\n if (SamouraiWallet.getInstance().isTestNet()) {\n blockExplorer = \"https://blockstream.info/testnet/\";\n }\n Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(blockExplorer + strHash));\n startActivity(browserIntent);\n }\n\n }\n\n private void txDetails(Tx tx) {\n if(account == WhirlpoolMeta.getInstance(getApplicationContext()).getWhirlpoolPostmix() && tx.getAmount() == 0){\n return;\n }\n Intent txIntent = new Intent(this, TxDetailsActivity.class);\n txIntent.putExtra(\"TX\", tx.toJSON().toString());\n startActivity(txIntent);\n }\n\n private class RicochetQueueTask extends AsyncTask {\n\n @Override\n protected String doInBackground(String... params) {\n\n if (RicochetMeta.getInstance(BalanceActivity.this).getQueue().size() > 0) {\n\n int count = 0;\n\n final Iterator itr = RicochetMeta.getInstance(BalanceActivity.this).getIterator();\n\n while (itr.hasNext()) {\n\n if (count == 3) {\n break;\n }\n\n try {\n JSONObject jObj = itr.next();\n JSONArray jHops = jObj.getJSONArray(\"hops\");\n if (jHops.length() > 0) {\n\n JSONObject jHop = jHops.getJSONObject(jHops.length() - 1);\n String txHash = jHop.getString(\"hash\");\n\n JSONObject txObj = APIFactory.getInstance(BalanceActivity.this).getTxInfo(txHash);\n if (txObj != null && txObj.has(\"block_height\") && txObj.getInt(\"block_height\") != -1) {\n itr.remove();\n count++;\n }\n\n }\n } catch (JSONException je) {\n ;\n }\n }\n\n }\n\n if (RicochetMeta.getInstance(BalanceActivity.this).getStaggered().size() > 0) {\n\n int count = 0;\n\n List staggered = RicochetMeta.getInstance(BalanceActivity.this).getStaggered();\n List _staggered = new ArrayList();\n\n for (JSONObject jObj : staggered) {\n\n if (count == 3) {\n break;\n }\n\n try {\n JSONArray jHops = jObj.getJSONArray(\"script\");\n if (jHops.length() > 0) {\n\n JSONObject jHop = jHops.getJSONObject(jHops.length() - 1);\n String txHash = jHop.getString(\"tx\");\n\n JSONObject txObj = APIFactory.getInstance(BalanceActivity.this).getTxInfo(txHash);\n if (txObj != null && txObj.has(\"block_height\") && txObj.getInt(\"block_height\") != -1) {\n count++;\n } else {\n _staggered.add(jObj);\n }\n\n }\n } catch (JSONException je) {\n ;\n } catch (ConcurrentModificationException cme) {\n ;\n }\n }\n\n }\n\n return \"OK\";\n }\n\n @Override\n protected void onPostExecute(String result) {\n ;\n }\n\n @Override\n protected void onPreExecute() {\n ;\n }\n\n }\n\n private void doFeaturePayNymUpdate() {\n\n Disposable disposable = Observable.fromCallable(() -> {\n JSONObject obj = new JSONObject();\n obj.put(\"code\", BIP47Util.getInstance(BalanceActivity.this).getPaymentCode().toString());\n// Log.d(\"BalanceActivity\", obj.toString());\n String res = com.samourai.wallet.bip47.paynym.WebUtil.getInstance(BalanceActivity.this).postURL(\"application/json\", null, com.samourai.wallet.bip47.paynym.WebUtil.PAYNYM_API + \"api/v1/token\", obj.toString());\n// Log.d(\"BalanceActivity\", res);\n\n JSONObject responseObj = new JSONObject(res);\n if (responseObj.has(\"token\")) {\n String token = responseObj.getString(\"token\");\n\n String sig = MessageSignUtil.getInstance(BalanceActivity.this).signMessage(BIP47Util.getInstance(BalanceActivity.this).getNotificationAddress().getECKey(), token);\n// Log.d(\"BalanceActivity\", sig);\n\n obj = new JSONObject();\n obj.put(\"nym\", BIP47Util.getInstance(BalanceActivity.this).getPaymentCode().toString());\n obj.put(\"code\", BIP47Util.getInstance(BalanceActivity.this).getFeaturePaymentCode().toString());\n obj.put(\"signature\", sig);\n\n// Log.d(\"BalanceActivity\", \"nym/add:\" + obj.toString());\n res = com.samourai.wallet.bip47.paynym.WebUtil.getInstance(BalanceActivity.this).postURL(\"application/json\", token, com.samourai.wallet.bip47.paynym.WebUtil.PAYNYM_API + \"api/v1/nym/add\", obj.toString());\n// Log.d(\"BalanceActivity\", res);\n\n responseObj = new JSONObject(res);\n if (responseObj.has(\"segwit\") && responseObj.has(\"token\")) {\n PrefsUtil.getInstance(BalanceActivity.this).setValue(PrefsUtil.PAYNYM_FEATURED_SEGWIT, true);\n } else if (responseObj.has(\"claimed\") && responseObj.getBoolean(\"claimed\") == true) {\n PrefsUtil.getInstance(BalanceActivity.this).setValue(PrefsUtil.PAYNYM_FEATURED_SEGWIT, true);\n }\n\n }\n return true;\n }).subscribeOn(Schedulers.newThread())\n .observeOn(AndroidSchedulers.mainThread())\n .subscribe(aBoolean -> {\n Log.i(TAG, \"doFeaturePayNymUpdate: Feature update complete\");\n }, error -> {\n Log.i(TAG, \"doFeaturePayNymUpdate: Feature update Fail\");\n });\n compositeDisposable.add(disposable);\n\n\n }\n\n\n}\n"},"new_file":{"kind":"string","value":"app/src/main/java/com/samourai/wallet/home/BalanceActivity.java"},"old_contents":{"kind":"string","value":"package com.samourai.wallet.home;\n\nimport android.Manifest;\nimport android.animation.Animator;\nimport android.animation.AnimatorListenerAdapter;\nimport android.app.Activity;\nimport android.app.ProgressDialog;\n\nimport androidx.appcompat.app.AlertDialog;\nimport androidx.lifecycle.Observer;\nimport androidx.lifecycle.ViewModelProviders;\nimport android.content.BroadcastReceiver;\nimport android.content.ClipData;\nimport android.content.ClipboardManager;\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.content.Intent;\nimport android.content.IntentFilter;\nimport android.content.pm.ActivityInfo;\nimport android.graphics.Typeface;\nimport android.graphics.drawable.Drawable;\nimport android.net.Uri;\nimport android.os.AsyncTask;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport androidx.annotation.Nullable;\nimport com.google.android.material.appbar.CollapsingToolbarLayout;\nimport androidx.transition.ChangeBounds;\nimport androidx.transition.TransitionManager;\nimport androidx.core.content.ContextCompat;\nimport androidx.localbroadcastmanager.content.LocalBroadcastManager;\nimport androidx.swiperefreshlayout.widget.SwipeRefreshLayout;\nimport androidx.recyclerview.widget.LinearLayoutManager;\nimport androidx.recyclerview.widget.RecyclerView;\nimport androidx.appcompat.widget.Toolbar;\nimport android.text.InputType;\nimport android.util.Log;\nimport android.util.TypedValue;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.widget.EditText;\nimport android.widget.ImageView;\nimport android.widget.LinearLayout;\nimport android.widget.ProgressBar;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.dm.zbar.android.scanner.ZBarConstants;\nimport com.google.android.material.dialog.MaterialAlertDialogBuilder;\nimport com.google.android.material.progressindicator.ProgressIndicator;\nimport com.samourai.wallet.R;\nimport com.samourai.wallet.ReceiveActivity;\nimport com.samourai.wallet.SamouraiActivity;\nimport com.samourai.wallet.SamouraiWallet;\nimport com.samourai.wallet.paynym.fragments.PayNymOnBoardBottomSheet;\nimport com.samourai.wallet.send.soroban.meeting.SorobanMeetingListenActivity;\nimport com.samourai.wallet.settings.SettingsActivity;\nimport com.samourai.wallet.access.AccessFactory;\nimport com.samourai.wallet.api.APIFactory;\nimport com.samourai.wallet.api.Tx;\nimport com.samourai.wallet.bip47.BIP47Meta;\nimport com.samourai.wallet.bip47.BIP47Util;\nimport com.samourai.wallet.cahoots.Cahoots;\nimport com.samourai.wallet.cahoots.psbt.PSBTUtil;\nimport com.samourai.wallet.crypto.AESUtil;\nimport com.samourai.wallet.crypto.DecryptionException;\nimport com.samourai.wallet.fragments.CameraFragmentBottomSheet;\nimport com.samourai.wallet.hd.HD_Wallet;\nimport com.samourai.wallet.hd.HD_WalletFactory;\nimport com.samourai.wallet.home.adapters.TxAdapter;\nimport com.samourai.wallet.network.NetworkDashboard;\nimport com.samourai.wallet.network.dojo.DojoUtil;\nimport com.samourai.wallet.payload.PayloadUtil;\nimport com.samourai.wallet.paynym.PayNymHome;\nimport com.samourai.wallet.permissions.PermissionsUtil;\nimport com.samourai.wallet.ricochet.RicochetMeta;\nimport com.samourai.wallet.segwit.bech32.Bech32Util;\nimport com.samourai.wallet.send.BlockedUTXO;\nimport com.samourai.wallet.send.MyTransactionOutPoint;\nimport com.samourai.wallet.send.SendActivity;\nimport com.samourai.wallet.send.SweepUtil;\nimport com.samourai.wallet.send.UTXO;\nimport com.samourai.wallet.send.cahoots.ManualCahootsActivity;\nimport com.samourai.wallet.service.JobRefreshService;\nimport com.samourai.wallet.service.WebSocketService;\nimport com.samourai.wallet.tor.TorManager;\nimport com.samourai.wallet.tx.TxDetailsActivity;\nimport com.samourai.wallet.util.AppUtil;\nimport com.samourai.wallet.util.CharSequenceX;\nimport com.samourai.wallet.util.FormatsUtil;\nimport com.samourai.wallet.util.MessageSignUtil;\nimport com.samourai.wallet.util.MonetaryUtil;\nimport com.samourai.wallet.util.PrefsUtil;\nimport com.samourai.wallet.util.PrivKeyReader;\nimport com.samourai.wallet.util.TimeOutUtil;\nimport com.samourai.wallet.utxos.UTXOSActivity;\nimport com.samourai.wallet.whirlpool.WhirlpoolMain;\nimport com.samourai.wallet.whirlpool.WhirlpoolMeta;\nimport com.samourai.wallet.whirlpool.service.WhirlpoolNotificationService;\nimport com.samourai.wallet.widgets.ItemDividerDecorator;\nimport com.squareup.picasso.Callback;\nimport com.squareup.picasso.Picasso;\n\nimport org.bitcoinj.core.Coin;\nimport org.bitcoinj.core.ECKey;\nimport org.bitcoinj.crypto.BIP38PrivateKey;\nimport org.bitcoinj.crypto.MnemonicException;\nimport org.bitcoinj.script.Script;\nimport org.bouncycastle.util.encoders.Hex;\nimport org.json.JSONArray;\nimport org.json.JSONException;\nimport org.json.JSONObject;\n\nimport java.io.IOException;\nimport java.text.DecimalFormat;\nimport java.text.DecimalFormatSymbols;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.ConcurrentModificationException;\nimport java.util.Iterator;\nimport java.util.List;\n\nimport io.matthewnelson.topl_service.TorServiceController;\nimport io.reactivex.Observable;\nimport io.reactivex.Single;\nimport io.reactivex.android.schedulers.AndroidSchedulers;\nimport io.reactivex.disposables.CompositeDisposable;\nimport io.reactivex.disposables.Disposable;\nimport io.reactivex.schedulers.Schedulers;\n\npublic class BalanceActivity extends SamouraiActivity {\n\n private final static int SCAN_COLD_STORAGE = 2011;\n private final static int SCAN_QR = 2012;\n private final static int UTXO_REQUESTCODE = 2012;\n private static final String TAG = \"BalanceActivity\";\n\n\n private List txs = null;\n private RecyclerView TxRecyclerView;\n private ProgressIndicator progressBar;\n private BalanceViewModel balanceViewModel;\n\n private RicochetQueueTask ricochetQueueTask = null;\n private com.github.clans.fab.FloatingActionMenu menuFab;\n private SwipeRefreshLayout txSwipeLayout;\n private CollapsingToolbarLayout mCollapsingToolbar;\n private CompositeDisposable compositeDisposable = new CompositeDisposable();\n private Toolbar toolbar;\n private Menu menu;\n private ImageView menuTorIcon;\n private ProgressBar progressBarMenu;\n private View whirlpoolFab, sendFab, receiveFab, paynymFab;\n\n public static final String ACTION_INTENT = \"com.samourai.wallet.BalanceFragment.REFRESH\";\n protected BroadcastReceiver receiver = new BroadcastReceiver() {\n @Override\n public void onReceive(final Context context, Intent intent) {\n\n if (ACTION_INTENT.equals(intent.getAction())) {\n if (progressBar != null) {\n showProgress();\n }\n final boolean notifTx = intent.getBooleanExtra(\"notifTx\", false);\n final boolean fetch = intent.getBooleanExtra(\"fetch\", false);\n\n final String rbfHash;\n final String blkHash;\n if (intent.hasExtra(\"rbf\")) {\n rbfHash = intent.getStringExtra(\"rbf\");\n } else {\n rbfHash = null;\n }\n if (intent.hasExtra(\"hash\")) {\n blkHash = intent.getStringExtra(\"hash\");\n } else {\n blkHash = null;\n }\n\n Handler handler = new Handler();\n handler.post(() -> {\n refreshTx(notifTx, false, false);\n\n if (BalanceActivity.this != null) {\n\n if (rbfHash != null) {\n new MaterialAlertDialogBuilder(BalanceActivity.this)\n .setTitle(R.string.app_name)\n .setMessage(rbfHash + \"\\n\\n\" + getString(R.string.rbf_incoming))\n .setCancelable(true)\n .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n\n doExplorerView(rbfHash);\n\n }\n })\n .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n ;\n }\n }).show();\n\n }\n\n }\n });\n\n }\n\n }\n };\n\n public static final String DISPLAY_INTENT = \"com.samourai.wallet.BalanceFragment.DISPLAY\";\n protected BroadcastReceiver receiverDisplay = new BroadcastReceiver() {\n @Override\n public void onReceive(final Context context, Intent intent) {\n\n if (DISPLAY_INTENT.equals(intent.getAction())) {\n\n updateDisplay(true);\n List utxos = APIFactory.getInstance(BalanceActivity.this).getUtxos(false);\n for (UTXO utxo : utxos) {\n List outpoints = utxo.getOutpoints();\n for (MyTransactionOutPoint out : outpoints) {\n\n byte[] scriptBytes = out.getScriptBytes();\n String address = null;\n try {\n if (Bech32Util.getInstance().isBech32Script(Hex.toHexString(scriptBytes))) {\n address = Bech32Util.getInstance().getAddressFromScript(Hex.toHexString(scriptBytes));\n } else {\n address = new Script(scriptBytes).getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString();\n }\n } catch (Exception e) {\n }\n String path = APIFactory.getInstance(BalanceActivity.this).getUnspentPaths().get(address);\n if (path != null && path.startsWith(\"M/1/\")) {\n continue;\n }\n\n final String hash = out.getHash().toString();\n final int idx = out.getTxOutputN();\n final long amount = out.getValue().longValue();\n\n if (amount < BlockedUTXO.BLOCKED_UTXO_THRESHOLD &&\n ((!BlockedUTXO.getInstance().contains(hash, idx) &&\n !BlockedUTXO.getInstance().containsNotDusted(hash, idx))\n ||\n (!BlockedUTXO.getInstance().containsPostMix(hash, idx) &&\n !BlockedUTXO.getInstance().containsNotDustedPostMix(hash, idx)))\n ){\n\n// BalanceActivity.this.runOnUiThread(new Runnable() {\n// @Override\n Handler handler = new Handler();\n handler.post(new Runnable() {\n public void run() {\n\n String message = BalanceActivity.this.getString(R.string.dusting_attempt);\n message += \"\\n\\n\";\n message += BalanceActivity.this.getString(R.string.dusting_attempt_amount);\n message += \" \";\n message += Coin.valueOf(amount).toPlainString();\n message += \" BTC\\n\";\n message += BalanceActivity.this.getString(R.string.dusting_attempt_id);\n message += \" \";\n message += hash + \"-\" + idx;\n\n MaterialAlertDialogBuilder dlg = new MaterialAlertDialogBuilder(BalanceActivity.this)\n .setTitle(R.string.dusting_tx)\n .setMessage(message)\n .setCancelable(false)\n .setPositiveButton(R.string.dusting_attempt_mark_unspendable, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n\n if(account == WhirlpoolMeta.getInstance(BalanceActivity.this).getWhirlpoolPostmix()) {\n BlockedUTXO.getInstance().addPostMix(hash, idx, amount);\n }\n else {\n BlockedUTXO.getInstance().add(hash, idx, amount);\n }\n saveState();\n }\n }).setNegativeButton(R.string.dusting_attempt_ignore, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n\n if(account == WhirlpoolMeta.getInstance(BalanceActivity.this).getWhirlpoolPostmix()) {\n BlockedUTXO.getInstance().addNotDustedPostMix(hash, idx);\n }\n else {\n BlockedUTXO.getInstance().addNotDusted(hash, idx);\n }\n\n }\n });\n if (!isFinishing()) {\n dlg.show();\n }\n\n }\n });\n\n }\n\n }\n\n }\n\n }\n\n }\n };\n\n protected void onCreate(Bundle savedInstanceState) {\n\n //Switch themes based on accounts (blue theme for whirlpool account)\n setSwitchThemes(true);\n super.onCreate(savedInstanceState);\n\n setContentView(R.layout.activity_balance);\n balanceViewModel = ViewModelProviders.of(this).get(BalanceViewModel.class);\n balanceViewModel.setAccount(account);\n\n\n makePaynymAvatarcache();\n setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);\n\n TxRecyclerView = findViewById(R.id.rv_txes);\n progressBar = findViewById(R.id.progressBar);\n toolbar = findViewById(R.id.toolbar);\n mCollapsingToolbar = findViewById(R.id.toolbar_layout);\n txSwipeLayout = findViewById(R.id.tx_swipe_container);\n\n setSupportActionBar(toolbar);\n TxRecyclerView.setLayoutManager(new LinearLayoutManager(this));\n Drawable drawable = this.getResources().getDrawable(R.drawable.divider);\n TxRecyclerView.addItemDecoration(new ItemDividerDecorator(drawable));\n menuFab = findViewById(R.id.fab_menu);\n txs = new ArrayList<>();\n whirlpoolFab = findViewById(R.id.whirlpool_fab);\n sendFab = findViewById(R.id.send_fab);\n receiveFab = findViewById(R.id.receive_fab);\n paynymFab = findViewById(R.id.paynym_fab);\n\n findViewById(R.id.whirlpool_fab).setOnClickListener(view -> {\n Intent intent = new Intent(BalanceActivity.this, WhirlpoolMain.class);\n startActivity(intent);\n menuFab.toggle(true);\n });\n\n sendFab.setOnClickListener(view -> {\n Intent intent = new Intent(BalanceActivity.this, SendActivity.class);\n intent.putExtra(\"via_menu\", true);\n intent.putExtra(\"_account\", account);\n startActivity(intent);\n menuFab.toggle(true);\n });\n\n JSONObject payload = null;\n try {\n payload = PayloadUtil.getInstance(BalanceActivity.this).getPayload();\n } catch (Exception e) {\n AppUtil.getInstance(getApplicationContext()).restartApp();\n e.printStackTrace();\n return;\n }\n if(account == 0 && payload != null && payload.has(\"prev_balance\")) {\n try {\n setBalance(payload.getLong(\"prev_balance\"), false);\n }\n catch(Exception e) {\n setBalance(0L, false);\n }\n }\n else {\n setBalance(0L, false);\n }\n\n receiveFab.setOnClickListener(view -> {\n menuFab.toggle(true);\n\n HD_Wallet hdw = HD_WalletFactory.getInstance(BalanceActivity.this).get();\n\n if (hdw != null) {\n Intent intent = new Intent(BalanceActivity.this, ReceiveActivity.class);\n startActivity(intent);\n }\n });\n paynymFab.setOnClickListener(view -> {\n menuFab.toggle(true);\n Intent intent = new Intent(BalanceActivity.this, PayNymHome.class);\n startActivity(intent);\n });\n txSwipeLayout.setOnRefreshListener(() -> {\n refreshTx(false, true, false);\n txSwipeLayout.setRefreshing(false);\n showProgress();\n });\n\n IntentFilter filter = new IntentFilter(ACTION_INTENT);\n LocalBroadcastManager.getInstance(BalanceActivity.this).registerReceiver(receiver, filter);\n IntentFilter filterDisplay = new IntentFilter(DISPLAY_INTENT);\n LocalBroadcastManager.getInstance(BalanceActivity.this).registerReceiver(receiverDisplay, filterDisplay);\n\n if (!PermissionsUtil.getInstance(BalanceActivity.this).hasPermission(Manifest.permission.READ_EXTERNAL_STORAGE) || !PermissionsUtil.getInstance(BalanceActivity.this).hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {\n PermissionsUtil.getInstance(BalanceActivity.this).showRequestPermissionsInfoAlertDialog(PermissionsUtil.READ_WRITE_EXTERNAL_PERMISSION_CODE);\n }\n if (!PermissionsUtil.getInstance(BalanceActivity.this).hasPermission(Manifest.permission.CAMERA)) {\n PermissionsUtil.getInstance(BalanceActivity.this).showRequestPermissionsInfoAlertDialog(PermissionsUtil.CAMERA_PERMISSION_CODE);\n }\n if (PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.PAYNYM_CLAIMED, false) && !PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.PAYNYM_FEATURED_SEGWIT, false)) {\n doFeaturePayNymUpdate();\n } else if (!PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.PAYNYM_CLAIMED, false) &&\n !PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.PAYNYM_REFUSED, false)) {\n PayNymOnBoardBottomSheet payNymOnBoardBottomSheet = new PayNymOnBoardBottomSheet();\n payNymOnBoardBottomSheet.show(getSupportFragmentManager(),payNymOnBoardBottomSheet.getTag());\n }\n Log.i(TAG, \"onCreate:PAYNYM_REFUSED \".concat(String.valueOf(PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.PAYNYM_REFUSED, false))));\n\n if (RicochetMeta.getInstance(BalanceActivity.this).getQueue().size() > 0) {\n if (ricochetQueueTask == null || ricochetQueueTask.getStatus().equals(AsyncTask.Status.FINISHED)) {\n ricochetQueueTask = new RicochetQueueTask();\n ricochetQueueTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);\n }\n }\n\n if (!AppUtil.getInstance(BalanceActivity.this).isClipboardSeen()) {\n doClipboardCheck();\n }\n\n\n if (!AppUtil.getInstance(BalanceActivity.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) {\n startService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class));\n }\n setUpTor();\n initViewModel();\n showProgress();\n\n if (account == 0) {\n final Handler delayedHandler = new Handler();\n delayedHandler.postDelayed(() -> {\n\n boolean notifTx = false;\n Bundle extras = getIntent().getExtras();\n if (extras != null && extras.containsKey(\"notifTx\")) {\n notifTx = extras.getBoolean(\"notifTx\");\n }\n\n refreshTx(notifTx, false, true);\n\n updateDisplay(false);\n }, 100L);\n\n getSupportActionBar().setIcon(R.drawable.ic_samourai_logo);\n\n }\n else {\n getSupportActionBar().setIcon(R.drawable.ic_whirlpool);\n receiveFab.setVisibility(View.GONE);\n whirlpoolFab.setVisibility(View.GONE);\n paynymFab.setVisibility(View.GONE);\n new Handler().postDelayed(() -> updateDisplay(true), 600L);\n }\n balanceViewModel.loadOfflineData();\n\n boolean hadContentDescription = android.text.TextUtils.isEmpty(toolbar.getLogoDescription());\n String contentDescription = String.valueOf(!hadContentDescription ? toolbar.getLogoDescription() : \"logoContentDescription\");\n toolbar.setLogoDescription(contentDescription);\n ArrayList potentialViews = new ArrayList();\n toolbar.findViewsWithText(potentialViews,contentDescription, View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION);\n View logoView = null;\n if(potentialViews.size() > 0){\n logoView = potentialViews.get(0);\n if (account == 0) {\n logoView.setOnClickListener(new View.OnClickListener() {\n @Override public void onClick(View v) {\n Intent _intent = new Intent(BalanceActivity.this, BalanceActivity.class);\n _intent.putExtra(\"_account\", WhirlpoolMeta.getInstance(BalanceActivity.this).getWhirlpoolPostmix());\n startActivity(_intent);\n } });\n } else {\n logoView.setOnClickListener(new View.OnClickListener() {\n @Override public void onClick(View v) {\n Intent _intent = new Intent(BalanceActivity.this, BalanceActivity.class);\n _intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);\n startActivity(_intent);\n } });\n }\n }\n\n updateDisplay(false);\n checkDeepLinks();\n }\n\n private void hideProgress() {\n progressBar.hide();\n }\n\n private void showProgress() {\n progressBar.setIndeterminate(true);\n progressBar.show();\n }\n\n private void checkDeepLinks() {\n Bundle bundle = getIntent().getExtras();\n if (bundle == null) {\n return;\n }\n if (bundle.containsKey(\"pcode\") || bundle.containsKey(\"uri\") || bundle.containsKey(\"amount\")) {\n if (balanceViewModel.getBalance().getValue() != null)\n bundle.putLong(\"balance\", balanceViewModel.getBalance().getValue());\n Intent intent = new Intent(this, SendActivity.class);\n intent.putExtra(\"_account\",account);\n intent.putExtras(bundle);\n startActivity(intent);\n }\n\n }\n\n @Override\n protected void onNewIntent(Intent intent) {\n super.onNewIntent(intent);\n setIntent(intent);\n }\n\n private void initViewModel() {\n TxAdapter adapter = new TxAdapter(getApplicationContext(), new ArrayList<>(), account);\n adapter.setHasStableIds(true);\n adapter.setClickListener((position, tx) -> txDetails(tx));\n\n TxRecyclerView.setAdapter(adapter);\n\n balanceViewModel.getBalance().observe(this, balance -> {\n if (balance < 0) {\n return;\n }\n if (balanceViewModel.getSatState().getValue() != null) {\n setBalance(balance, balanceViewModel.getSatState().getValue());\n } else {\n setBalance(balance, false);\n }\n });\n adapter.setTxes(balanceViewModel.getTxs().getValue());\n setBalance(balanceViewModel.getBalance().getValue(), false);\n\n balanceViewModel.getSatState().observe(this, state -> {\n if (state == null) {\n state = false;\n }\n setBalance(balanceViewModel.getBalance().getValue(), state);\n adapter.toggleDisplayUnit(state);\n });\n balanceViewModel.getTxs().observe(this, new Observer>() {\n @Override\n public void onChanged(@Nullable List list) {\n adapter.setTxes(list);\n }\n });\n mCollapsingToolbar.setOnClickListener(view -> balanceViewModel.toggleSat());\n\n mCollapsingToolbar.setOnLongClickListener(view -> {\n Intent intent = new Intent(BalanceActivity.this, UTXOSActivity.class);\n intent.putExtra(\"_account\", account);\n startActivityForResult(intent,UTXO_REQUESTCODE);\n\n return false;\n });\n }\n\n private void setBalance(Long balance, boolean isSat) {\n if (balance == null) {\n return;\n }\n\n if (getSupportActionBar() != null) {\n TransitionManager.beginDelayedTransition(mCollapsingToolbar, new ChangeBounds());\n\n String displayAmount = \"\".concat(isSat ? getSatoshiDisplayAmount(balance) : getBTCDisplayAmount(balance));\n String Unit = isSat ? getSatoshiDisplayUnits() : getBTCDisplayUnits();\n\n displayAmount = displayAmount.concat(\" \").concat(Unit);\n toolbar.setTitle(displayAmount);\n setTitle(displayAmount);\n mCollapsingToolbar.setTitle(displayAmount);\n\n }\n\n\n Log.i(TAG, \"setBalance: \".concat(getBTCDisplayAmount(balance)));\n\n }\n\n @Override\n public void onResume() {\n super.onResume();\n\n// IntentFilter filter = new IntentFilter(ACTION_INTENT);\n// LocalBroadcastManager.getInstance(BalanceActivity.this).registerReceiver(receiver, filter);\n\n AppUtil.getInstance(BalanceActivity.this).checkTimeOut();\n//\n// Intent intent = new Intent(\"com.samourai.wallet.MainActivity2.RESTART_SERVICE\");\n// LocalBroadcastManager.getInstance(BalanceActivity.this).sendBroadcast(intent);\n\n }\n\n public View createTag(String text){\n float scale = getResources().getDisplayMetrics().density;\n LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(\n LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);\n TextView textView = new TextView(getApplicationContext());\n textView.setText(text);\n textView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.white));\n textView.setLayoutParams(lparams);\n textView.setBackgroundResource(R.drawable.tag_round_shape);\n textView.setPadding((int) (8 * scale + 0.5f), (int) (6 * scale + 0.5f), (int) (8 * scale + 0.5f), (int) (6 * scale + 0.5f));\n textView.setTypeface(Typeface.DEFAULT_BOLD);\n textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 11);\n return textView;\n }\n\n @Override\n public void onPause() {\n super.onPause();\n\n// ibQuickSend.collapse();\n\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && AppUtil.getInstance(BalanceActivity.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) {\n stopService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class));\n }\n\n }\n\n\n private void makePaynymAvatarcache() {\n try {\n\n ArrayList paymentCodes = new ArrayList<>(BIP47Meta.getInstance().getSortedByLabels(false, true));\n for (String code : paymentCodes) {\n Picasso.get()\n .load(com.samourai.wallet.bip47.paynym.WebUtil.PAYNYM_API + code + \"/avatar\").fetch(new Callback() {\n @Override\n public void onSuccess() {\n /*NO OP*/\n }\n\n @Override\n public void onError(Exception e) {\n /*NO OP*/\n }\n });\n }\n\n } catch (Exception ignored) {\n\n }\n }\n\n @Override\n public void onDestroy() {\n\n LocalBroadcastManager.getInstance(BalanceActivity.this).unregisterReceiver(receiver);\n LocalBroadcastManager.getInstance(BalanceActivity.this).unregisterReceiver(receiverDisplay);\n\n if(account == 0) {\n if (AppUtil.getInstance(BalanceActivity.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) {\n stopService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class));\n }\n }\n\n super.onDestroy();\n\n if(compositeDisposable != null && !compositeDisposable.isDisposed()) {\n compositeDisposable.dispose();\n }\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n getMenuInflater().inflate(R.menu.main, menu);\n\n menu.findItem(R.id.action_refresh).setVisible(false);\n menu.findItem(R.id.action_share_receive).setVisible(false);\n menu.findItem(R.id.action_ricochet).setVisible(false);\n menu.findItem(R.id.action_empty_ricochet).setVisible(false);\n menu.findItem(R.id.action_sign).setVisible(false);\n menu.findItem(R.id.action_fees).setVisible(false);\n menu.findItem(R.id.action_batch).setVisible(false);\n\n WhirlpoolMeta.getInstance(getApplicationContext());\n if (account == WhirlpoolMeta.getInstance(getApplicationContext()).getWhirlpoolPostmix()) {\n\n menu.findItem(R.id.action_sweep).setVisible(false);\n menu.findItem(R.id.action_backup).setVisible(false);\n menu.findItem(R.id.action_postmix).setVisible(false);\n\n menu.findItem(R.id.action_network_dashboard).setVisible(false);\n MenuItem item = menu.findItem(R.id.action_menu_account);\n item.setActionView(createTag(\" POST-MIX \"));\n item.setVisible(true);\n item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);\n\n }\n else {\n menu.findItem(R.id.action_soroban_collab).setVisible(false);\n }\n this.menu = menu;\n\n return super.onCreateOptionsMenu(menu);\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n // Handle action bar item clicks here. The action bar will\n // automatically handle clicks on the Home/Up button, so long\n // as you specify a parent activity in AndroidManifest.xml.\n int id = item.getItemId();\n\n if(id == android.R.id.home){\n this.finish();\n return super.onOptionsItemSelected(item);\n }\n // noinspection SimplifiableIfStatement\n if (id == R.id.action_network_dashboard) {\n startActivity(new Intent(this, NetworkDashboard.class));\n } // noinspection SimplifiableIfStatement\n if (id == R.id.action_copy_cahoots) {\n ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);\n if(clipboard.hasPrimaryClip()) {\n ClipData.Item clipItem = clipboard.getPrimaryClip().getItemAt(0);\n\n if(Cahoots.isCahoots(clipItem.getText().toString().trim())){\n try {\n Intent cahootIntent = ManualCahootsActivity.createIntentResume(this, account, clipItem.getText().toString().trim());\n startActivity(cahootIntent);\n }\n catch (Exception e) {\n Toast.makeText(this,R.string.cannot_process_cahoots,Toast.LENGTH_SHORT).show();\n e.printStackTrace();\n }\n }\n else {\n Toast.makeText(this,R.string.cannot_process_cahoots,Toast.LENGTH_SHORT).show();\n }\n }\n else {\n Toast.makeText(this,R.string.clipboard_empty,Toast.LENGTH_SHORT).show();\n }\n }\n if (id == R.id.action_settings) {\n doSettings();\n }\n else if (id == R.id.action_support) {\n doSupport();\n }\n else if (id == R.id.action_sweep) {\n if (!AppUtil.getInstance(BalanceActivity.this).isOfflineMode()) {\n doSweep();\n }\n else {\n Toast.makeText(BalanceActivity.this, R.string.in_offline_mode, Toast.LENGTH_SHORT).show();\n }\n }\n else if (id == R.id.action_utxo) {\n doUTXO();\n }\n else if (id == R.id.action_backup) {\n\n if (SamouraiWallet.getInstance().hasPassphrase(BalanceActivity.this)) {\n if (HD_WalletFactory.getInstance(BalanceActivity.this).get() != null && SamouraiWallet.getInstance().hasPassphrase(BalanceActivity.this)) {\n doBackup();\n }\n else {\n\n MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);\n builder.setMessage(R.string.passphrase_needed_for_backup).setCancelable(false);\n AlertDialog alert = builder.create();\n\n alert.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.ok), new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int id) {\n dialog.dismiss();\n }\n });\n\n if (!isFinishing()) {\n alert.show();\n }\n\n }\n }\n else {\n Toast.makeText(BalanceActivity.this, R.string.passphrase_required, Toast.LENGTH_SHORT).show();\n }\n\n }\n else if (id == R.id.action_scan_qr) {\n doScan();\n }\n else if (id == R.id.action_postmix) {\n\n Intent intent = new Intent(BalanceActivity.this, SendActivity.class);\n intent.putExtra(\"_account\", WhirlpoolMeta.getInstance(BalanceActivity.this).getWhirlpoolPostmix());\n startActivity(intent);\n\n }\n else if(id == R.id.action_soroban_collab) {\n Intent intent = new Intent(this, SorobanMeetingListenActivity.class);\n intent.putExtra(\"_account\", WhirlpoolMeta.getInstance(BalanceActivity.this).getWhirlpoolPostmix());\n startActivity(intent);\n }\n else {\n ;\n }\n return super.onOptionsItemSelected(item);\n }\n\n\n private void setUpTor() {\n TorManager.INSTANCE.getTorStateLiveData().observe(this,torState -> {\n if (torState == TorManager.TorState.ON) {\n PrefsUtil.getInstance(this).setValue(PrefsUtil.ENABLE_TOR, true);\n if (this.progressBarMenu != null) {\n this.progressBarMenu.setVisibility(View.INVISIBLE);\n this.menuTorIcon.setImageResource(R.drawable.tor_on);\n }\n\n } else if (torState == TorManager.TorState.WAITING) {\n if (this.progressBarMenu != null) {\n this.progressBarMenu.setVisibility(View.VISIBLE);\n this.menuTorIcon.setImageResource(R.drawable.tor_on);\n }\n } else {\n if (this.progressBarMenu != null) {\n this.progressBarMenu.setVisibility(View.INVISIBLE);\n this.menuTorIcon.setImageResource(R.drawable.tor_off);\n }\n\n }\n });\n }\n\n\n @Override\n public void onActivityResult(int requestCode, int resultCode, Intent data) {\n\n super.onActivityResult(requestCode, resultCode, data);\n if (resultCode == Activity.RESULT_OK && requestCode == SCAN_COLD_STORAGE) {\n\n if (data != null && data.getStringExtra(ZBarConstants.SCAN_RESULT) != null) {\n\n final String strResult = data.getStringExtra(ZBarConstants.SCAN_RESULT);\n\n doPrivKey(strResult);\n\n }\n } else if (resultCode == Activity.RESULT_CANCELED && requestCode == SCAN_COLD_STORAGE) {\n } else if (resultCode == Activity.RESULT_OK && requestCode == SCAN_QR) {\n\n if (data != null && data.getStringExtra(ZBarConstants.SCAN_RESULT) != null) {\n\n final String strResult = data.getStringExtra(ZBarConstants.SCAN_RESULT);\n\n PrivKeyReader privKeyReader = new PrivKeyReader(new CharSequenceX(strResult.trim()));\n try {\n if (privKeyReader.getFormat() != null) {\n doPrivKey(strResult.trim());\n } else if (Cahoots.isCahoots(strResult.trim())) {\n Intent cahootIntent = ManualCahootsActivity.createIntentResume(this, account, strResult.trim());\n startActivity(cahootIntent);\n } else if (FormatsUtil.getInstance().isPSBT(strResult.trim())) {\n PSBTUtil.getInstance(BalanceActivity.this).doPSBT(strResult.trim());\n } else if (DojoUtil.getInstance(BalanceActivity.this).isValidPairingPayload(strResult.trim())) {\n\n Intent intent = new Intent(BalanceActivity.this, NetworkDashboard.class);\n intent.putExtra(\"params\", strResult.trim());\n startActivity(intent);\n\n } else {\n Intent intent = new Intent(BalanceActivity.this, SendActivity.class);\n intent.putExtra(\"uri\", strResult.trim());\n intent.putExtra(\"_account\", account);\n startActivity(intent);\n }\n } catch (Exception e) {\n }\n\n }\n }\n if (resultCode == Activity.RESULT_OK && requestCode == UTXO_REQUESTCODE) {\n refreshTx(false, false, false);\n showProgress();\n } else {\n ;\n }\n\n }\n\n\n @Override\n public void onBackPressed() {\n\n\n if (account == 0) {\n\n MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);\n builder.setMessage(R.string.ask_you_sure_exit);\n AlertDialog alert = builder.create();\n\n alert.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.yes), (dialog, id) -> {\n\n try {\n PayloadUtil.getInstance(BalanceActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BalanceActivity.this).getGUID() + AccessFactory.getInstance(BalanceActivity.this).getPIN()));\n } catch (MnemonicException.MnemonicLengthException mle) {\n } catch (JSONException je) {\n } catch (IOException ioe) {\n } catch (DecryptionException de) {\n }\n\n // disconnect Whirlpool on app back key exit\n if (WhirlpoolNotificationService.isRunning(getApplicationContext()))\n WhirlpoolNotificationService.stopService(getApplicationContext());\n\n if (TorManager.INSTANCE.isConnected()) {\n TorServiceController.stopTor();\n }\n TimeOutUtil.getInstance().reset();\n finishAffinity();\n finish();\n super.onBackPressed();\n });\n\n alert.setButton(AlertDialog.BUTTON_NEGATIVE, getString(R.string.no), (dialog, id) -> dialog.dismiss());\n alert.show();\n\n } else {\n super.onBackPressed();\n }\n }\n\n private void updateDisplay(boolean fromRefreshService) {\n Disposable txDisposable = loadTxes(account)\n .subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread())\n .subscribe((txes, throwable) -> {\n if (throwable != null)\n throwable.printStackTrace();\n\n\n if (txes != null) {\n if (txes.size() != 0) {\n balanceViewModel.setTx(txes);\n } else {\n if (balanceViewModel.getTxs().getValue() != null && balanceViewModel.getTxs().getValue().size() == 0) {\n balanceViewModel.setTx(txes);\n }\n }\n\n Collections.sort(txes, new APIFactory.TxMostRecentDateComparator());\n txs.clear();\n txs.addAll(txes);\n }\n\n if (progressBar.getVisibility() == View.VISIBLE && fromRefreshService) {\n hideProgress();\n }\n });\n\n Disposable balanceDisposable = loadBalance(account)\n .subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread())\n .subscribe((balance, throwable) -> {\n if (throwable != null)\n throwable.printStackTrace();\n\n if (balanceViewModel.getBalance().getValue() != null) {\n balanceViewModel.setBalance(balance);\n } else {\n balanceViewModel.setBalance(balance);\n }\n });\n compositeDisposable.add(balanceDisposable);\n compositeDisposable.add(txDisposable);\n// displayBalance();\n// txAdapter.notifyDataSetChanged();\n\n\n }\n\n private Single> loadTxes(int account) {\n return Single.fromCallable(() -> {\n List loadedTxes = new ArrayList<>();\n if (account == 0) {\n loadedTxes = APIFactory.getInstance(BalanceActivity.this).getAllXpubTxs();\n } else if (account == WhirlpoolMeta.getInstance(getApplicationContext()).getWhirlpoolPostmix()) {\n loadedTxes = APIFactory.getInstance(BalanceActivity.this).getAllPostMixTxs();\n }\n return loadedTxes;\n });\n }\n\n private Single loadBalance(int account) {\n return Single.fromCallable(() -> {\n long loadedBalance = 0L;\n if (account == 0) {\n loadedBalance = APIFactory.getInstance(BalanceActivity.this).getXpubBalance();\n } else if (account == WhirlpoolMeta.getInstance(getApplicationContext()).getWhirlpoolPostmix()) {\n loadedBalance = APIFactory.getInstance(BalanceActivity.this).getXpubPostMixBalance();\n }\n return loadedBalance;\n });\n }\n\n\n private void doSettings() {\n TimeOutUtil.getInstance().updatePin();\n Intent intent = new Intent(BalanceActivity.this, SettingsActivity.class);\n startActivity(intent);\n }\n\n private void doSupport() {\n Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"https://support.samourai.io/\"));\n startActivity(intent);\n }\n\n private void doUTXO() {\n Intent intent = new Intent(BalanceActivity.this, UTXOSActivity.class);\n intent.putExtra(\"_account\", account);\n startActivityForResult(intent,UTXO_REQUESTCODE);\n }\n\n private void doScan() {\n\n CameraFragmentBottomSheet cameraFragmentBottomSheet = new CameraFragmentBottomSheet();\n cameraFragmentBottomSheet.show(getSupportFragmentManager(), cameraFragmentBottomSheet.getTag());\n\n cameraFragmentBottomSheet.setQrCodeScanLisenter(code -> {\n cameraFragmentBottomSheet.dismissAllowingStateLoss();\n PrivKeyReader privKeyReader = new PrivKeyReader(new CharSequenceX(code.trim()));\n try {\n if (privKeyReader.getFormat() != null) {\n doPrivKey(code.trim());\n } else if (Cahoots.isCahoots(code.trim())) {\n Intent cahootIntent = ManualCahootsActivity.createIntentResume(this, account, code.trim());\n startActivity(cahootIntent);\n\n } else if (FormatsUtil.getInstance().isPSBT(code.trim())) {\n PSBTUtil.getInstance(BalanceActivity.this).doPSBT(code.trim());\n } else if (DojoUtil.getInstance(BalanceActivity.this).isValidPairingPayload(code.trim())) {\n Intent intent = new Intent(BalanceActivity.this, NetworkDashboard.class);\n intent.putExtra(\"params\", code.trim());\n startActivity(intent);\n } else {\n Intent intent = new Intent(BalanceActivity.this, SendActivity.class);\n intent.putExtra(\"uri\", code.trim());\n intent.putExtra(\"_account\", account);\n startActivity(intent);\n }\n } catch (Exception e) {\n }\n });\n }\n\n private void doSweepViaScan() {\n\n CameraFragmentBottomSheet cameraFragmentBottomSheet = new CameraFragmentBottomSheet();\n cameraFragmentBottomSheet.show(getSupportFragmentManager(), cameraFragmentBottomSheet.getTag());\n cameraFragmentBottomSheet.setQrCodeScanLisenter(code -> {\n cameraFragmentBottomSheet.dismissAllowingStateLoss();\n PrivKeyReader privKeyReader = new PrivKeyReader(new CharSequenceX(code.trim()));\n try {\n if (privKeyReader.getFormat() != null) {\n doPrivKey(code.trim());\n } else if (Cahoots.isCahoots(code.trim())) {\n Intent cahootIntent = ManualCahootsActivity.createIntentResume(this, account, code.trim());\n startActivity(cahootIntent);\n } else if (FormatsUtil.getInstance().isPSBT(code.trim())) {\n PSBTUtil.getInstance(BalanceActivity.this).doPSBT(code.trim());\n } else if (DojoUtil.getInstance(BalanceActivity.this).isValidPairingPayload(code.trim())) {\n Toast.makeText(BalanceActivity.this, \"Samourai Dojo full node coming soon.\", Toast.LENGTH_SHORT).show();\n } else {\n Intent intent = new Intent(BalanceActivity.this, SendActivity.class);\n intent.putExtra(\"uri\", code.trim());\n intent.putExtra(\"_account\", account);\n startActivity(intent);\n }\n } catch (Exception e) {\n }\n });\n }\n\n private void doSweep() {\n\n MaterialAlertDialogBuilder dlg = new MaterialAlertDialogBuilder(BalanceActivity.this)\n .setTitle(R.string.app_name)\n .setMessage(R.string.action_sweep)\n .setCancelable(true)\n .setPositiveButton(R.string.enter_privkey, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n\n final EditText privkey = new EditText(BalanceActivity.this);\n privkey.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);\n\n MaterialAlertDialogBuilder dlg = new MaterialAlertDialogBuilder(BalanceActivity.this)\n .setTitle(R.string.app_name)\n .setMessage(R.string.enter_privkey)\n .setView(privkey)\n .setCancelable(false)\n .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n\n final String strPrivKey = privkey.getText().toString();\n\n if (strPrivKey != null && strPrivKey.length() > 0) {\n doPrivKey(strPrivKey);\n }\n\n }\n }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n\n dialog.dismiss();\n\n }\n });\n if (!isFinishing()) {\n dlg.show();\n }\n\n }\n\n }).setNegativeButton(R.string.scan, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n\n doSweepViaScan();\n\n }\n });\n if (!isFinishing()) {\n dlg.show();\n }\n\n }\n\n private void doPrivKey(final String data) {\n\n PrivKeyReader privKeyReader = null;\n\n String format = null;\n try {\n privKeyReader = new PrivKeyReader(new CharSequenceX(data), null);\n format = privKeyReader.getFormat();\n } catch (Exception e) {\n Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();\n return;\n }\n\n if (format != null) {\n\n if (format.equals(PrivKeyReader.BIP38)) {\n\n final PrivKeyReader pvr = privKeyReader;\n\n final EditText password38 = new EditText(BalanceActivity.this);\n password38.setSingleLine(true);\n password38.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);\n\n MaterialAlertDialogBuilder dlg = new MaterialAlertDialogBuilder(BalanceActivity.this)\n .setTitle(R.string.app_name)\n .setMessage(R.string.bip38_pw)\n .setView(password38)\n .setCancelable(false)\n .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n\n String password = password38.getText().toString();\n\n ProgressDialog progress = new ProgressDialog(BalanceActivity.this);\n progress.setCancelable(false);\n progress.setTitle(R.string.app_name);\n progress.setMessage(getString(R.string.decrypting_bip38));\n progress.show();\n\n boolean keyDecoded = false;\n\n try {\n BIP38PrivateKey bip38 = new BIP38PrivateKey(SamouraiWallet.getInstance().getCurrentNetworkParams(), data);\n final ECKey ecKey = bip38.decrypt(password);\n if (ecKey != null && ecKey.hasPrivKey()) {\n\n if (progress != null && progress.isShowing()) {\n progress.cancel();\n }\n\n pvr.setPassword(new CharSequenceX(password));\n keyDecoded = true;\n\n Toast.makeText(BalanceActivity.this, pvr.getFormat(), Toast.LENGTH_SHORT).show();\n Toast.makeText(BalanceActivity.this, pvr.getKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(), Toast.LENGTH_SHORT).show();\n\n }\n } catch (Exception e) {\n e.printStackTrace();\n Toast.makeText(BalanceActivity.this, R.string.bip38_pw_error, Toast.LENGTH_SHORT).show();\n }\n\n if (progress != null && progress.isShowing()) {\n progress.cancel();\n }\n\n if (keyDecoded) {\n SweepUtil.getInstance(BalanceActivity.this).sweep(pvr, SweepUtil.TYPE_P2PKH);\n }\n\n }\n }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n\n Toast.makeText(BalanceActivity.this, R.string.bip38_pw_error, Toast.LENGTH_SHORT).show();\n\n }\n });\n if (!isFinishing()) {\n dlg.show();\n }\n\n } else if (privKeyReader != null) {\n SweepUtil.getInstance(BalanceActivity.this).sweep(privKeyReader, SweepUtil.TYPE_P2PKH);\n } else {\n ;\n }\n\n } else {\n Toast.makeText(BalanceActivity.this, R.string.cannot_recognize_privkey, Toast.LENGTH_SHORT).show();\n }\n\n }\n\n private void doBackup() {\n\n final String passphrase = HD_WalletFactory.getInstance(BalanceActivity.this).get().getPassphrase();\n\n final String[] export_methods = new String[2];\n export_methods[0] = getString(R.string.export_to_clipboard);\n export_methods[1] = getString(R.string.export_to_email);\n\n new MaterialAlertDialogBuilder(BalanceActivity.this)\n .setTitle(R.string.options_export)\n .setSingleChoiceItems(export_methods, 0, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int which) {\n\n try {\n PayloadUtil.getInstance(BalanceActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BalanceActivity.this).getGUID() + AccessFactory.getInstance(BalanceActivity.this).getPIN()));\n } catch (IOException ioe) {\n ;\n } catch (JSONException je) {\n ;\n } catch (DecryptionException de) {\n ;\n } catch (MnemonicException.MnemonicLengthException mle) {\n ;\n }\n\n String encrypted = null;\n try {\n encrypted = AESUtil.encrypt(PayloadUtil.getInstance(BalanceActivity.this).getPayload().toString(), new CharSequenceX(passphrase), AESUtil.DefaultPBKDF2Iterations);\n } catch (Exception e) {\n Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();\n } finally {\n if (encrypted == null) {\n Toast.makeText(BalanceActivity.this, R.string.encryption_error, Toast.LENGTH_SHORT).show();\n return;\n }\n }\n\n JSONObject obj = PayloadUtil.getInstance(BalanceActivity.this).putPayload(encrypted, true);\n\n if (which == 0) {\n android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(android.content.Context.CLIPBOARD_SERVICE);\n android.content.ClipData clip = null;\n clip = android.content.ClipData.newPlainText(\"Wallet backup\", obj.toString());\n clipboard.setPrimaryClip(clip);\n Toast.makeText(BalanceActivity.this, R.string.copied_to_clipboard, Toast.LENGTH_SHORT).show();\n } else {\n Intent email = new Intent(Intent.ACTION_SEND);\n email.putExtra(Intent.EXTRA_SUBJECT, \"Samourai Wallet backup\");\n email.putExtra(Intent.EXTRA_TEXT, obj.toString());\n email.setType(\"message/rfc822\");\n startActivity(Intent.createChooser(email, BalanceActivity.this.getText(R.string.choose_email_client)));\n }\n\n dialog.dismiss();\n }\n }\n ).show();\n\n }\n\n private void doClipboardCheck() {\n\n final android.content.ClipboardManager clipboard = (android.content.ClipboardManager) BalanceActivity.this.getSystemService(android.content.Context.CLIPBOARD_SERVICE);\n if (clipboard.hasPrimaryClip()) {\n final ClipData clip = clipboard.getPrimaryClip();\n ClipData.Item item = clip.getItemAt(0);\n if (item.getText() != null) {\n String text = item.getText().toString();\n String[] s = text.split(\"\\\\s+\");\n\n try {\n for (int i = 0; i < s.length; i++) {\n PrivKeyReader privKeyReader = new PrivKeyReader(new CharSequenceX(s[i]));\n if (privKeyReader.getFormat() != null &&\n (privKeyReader.getFormat().equals(PrivKeyReader.WIF_COMPRESSED) ||\n privKeyReader.getFormat().equals(PrivKeyReader.WIF_UNCOMPRESSED) ||\n privKeyReader.getFormat().equals(PrivKeyReader.BIP38) ||\n FormatsUtil.getInstance().isValidXprv(s[i])\n )\n ) {\n\n new MaterialAlertDialogBuilder(BalanceActivity.this)\n .setTitle(R.string.app_name)\n .setMessage(R.string.privkey_clipboard)\n .setCancelable(false)\n .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {\n\n public void onClick(DialogInterface dialog, int whichButton) {\n\n clipboard.setPrimaryClip(ClipData.newPlainText(\"\", \"\"));\n\n }\n\n }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {\n\n public void onClick(DialogInterface dialog, int whichButton) {\n ;\n }\n }).show();\n\n }\n }\n } catch (Exception e) {\n ;\n }\n }\n }\n\n }\n\n private void refreshTx(final boolean notifTx, final boolean dragged, final boolean launch) {\n\n if (AppUtil.getInstance(BalanceActivity.this).isOfflineMode()) {\n Toast.makeText(BalanceActivity.this, R.string.in_offline_mode, Toast.LENGTH_SHORT).show();\n /*\n CoordinatorLayout coordinatorLayout = new CoordinatorLayout(BalanceActivity.this);\n Snackbar snackbar = Snackbar.make(coordinatorLayout, R.string.in_offline_mode, Snackbar.LENGTH_LONG);\n snackbar.show();\n */\n }\n\n\n Intent intent = new Intent(this, JobRefreshService.class);\n intent.putExtra(\"notifTx\", notifTx);\n intent.putExtra(\"dragged\", dragged);\n intent.putExtra(\"launch\", launch);\n JobRefreshService.enqueueWork(getApplicationContext(), intent);\n//\n//\n// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {\n// startForegroundService(intent);\n// } else {\n// startService(intent);\n// }\n\n }\n\n private String getBTCDisplayAmount(long value) {\n return Coin.valueOf(value).toPlainString();\n }\n\n private String getSatoshiDisplayAmount(long value) {\n DecimalFormatSymbols symbols = new DecimalFormatSymbols();\n symbols.setGroupingSeparator(' ');\n DecimalFormat df = new DecimalFormat(\"#\", symbols);\n df.setMinimumIntegerDigits(1);\n df.setMaximumIntegerDigits(16);\n df.setGroupingUsed(true);\n df.setGroupingSize(3);\n return df.format(value);\n }\n\n private String getBTCDisplayUnits() {\n\n return MonetaryUtil.getInstance().getBTCUnits();\n\n }\n\n private String getSatoshiDisplayUnits() {\n\n return MonetaryUtil.getInstance().getSatoshiUnits();\n\n }\n\n\n private void doExplorerView(String strHash) {\n\n if (strHash != null) {\n\n String blockExplorer = \"https://m.oxt.me/transaction/\";\n if (SamouraiWallet.getInstance().isTestNet()) {\n blockExplorer = \"https://blockstream.info/testnet/\";\n }\n Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(blockExplorer + strHash));\n startActivity(browserIntent);\n }\n\n }\n\n private void txDetails(Tx tx) {\n if(account == WhirlpoolMeta.getInstance(getApplicationContext()).getWhirlpoolPostmix() && tx.getAmount() == 0){\n return;\n }\n Intent txIntent = new Intent(this, TxDetailsActivity.class);\n txIntent.putExtra(\"TX\", tx.toJSON().toString());\n startActivity(txIntent);\n }\n\n private class RicochetQueueTask extends AsyncTask {\n\n @Override\n protected String doInBackground(String... params) {\n\n if (RicochetMeta.getInstance(BalanceActivity.this).getQueue().size() > 0) {\n\n int count = 0;\n\n final Iterator itr = RicochetMeta.getInstance(BalanceActivity.this).getIterator();\n\n while (itr.hasNext()) {\n\n if (count == 3) {\n break;\n }\n\n try {\n JSONObject jObj = itr.next();\n JSONArray jHops = jObj.getJSONArray(\"hops\");\n if (jHops.length() > 0) {\n\n JSONObject jHop = jHops.getJSONObject(jHops.length() - 1);\n String txHash = jHop.getString(\"hash\");\n\n JSONObject txObj = APIFactory.getInstance(BalanceActivity.this).getTxInfo(txHash);\n if (txObj != null && txObj.has(\"block_height\") && txObj.getInt(\"block_height\") != -1) {\n itr.remove();\n count++;\n }\n\n }\n } catch (JSONException je) {\n ;\n }\n }\n\n }\n\n if (RicochetMeta.getInstance(BalanceActivity.this).getStaggered().size() > 0) {\n\n int count = 0;\n\n List staggered = RicochetMeta.getInstance(BalanceActivity.this).getStaggered();\n List _staggered = new ArrayList();\n\n for (JSONObject jObj : staggered) {\n\n if (count == 3) {\n break;\n }\n\n try {\n JSONArray jHops = jObj.getJSONArray(\"script\");\n if (jHops.length() > 0) {\n\n JSONObject jHop = jHops.getJSONObject(jHops.length() - 1);\n String txHash = jHop.getString(\"tx\");\n\n JSONObject txObj = APIFactory.getInstance(BalanceActivity.this).getTxInfo(txHash);\n if (txObj != null && txObj.has(\"block_height\") && txObj.getInt(\"block_height\") != -1) {\n count++;\n } else {\n _staggered.add(jObj);\n }\n\n }\n } catch (JSONException je) {\n ;\n } catch (ConcurrentModificationException cme) {\n ;\n }\n }\n\n }\n\n return \"OK\";\n }\n\n @Override\n protected void onPostExecute(String result) {\n ;\n }\n\n @Override\n protected void onPreExecute() {\n ;\n }\n\n }\n\n private void doFeaturePayNymUpdate() {\n\n Disposable disposable = Observable.fromCallable(() -> {\n JSONObject obj = new JSONObject();\n obj.put(\"code\", BIP47Util.getInstance(BalanceActivity.this).getPaymentCode().toString());\n// Log.d(\"BalanceActivity\", obj.toString());\n String res = com.samourai.wallet.bip47.paynym.WebUtil.getInstance(BalanceActivity.this).postURL(\"application/json\", null, com.samourai.wallet.bip47.paynym.WebUtil.PAYNYM_API + \"api/v1/token\", obj.toString());\n// Log.d(\"BalanceActivity\", res);\n\n JSONObject responseObj = new JSONObject(res);\n if (responseObj.has(\"token\")) {\n String token = responseObj.getString(\"token\");\n\n String sig = MessageSignUtil.getInstance(BalanceActivity.this).signMessage(BIP47Util.getInstance(BalanceActivity.this).getNotificationAddress().getECKey(), token);\n// Log.d(\"BalanceActivity\", sig);\n\n obj = new JSONObject();\n obj.put(\"nym\", BIP47Util.getInstance(BalanceActivity.this).getPaymentCode().toString());\n obj.put(\"code\", BIP47Util.getInstance(BalanceActivity.this).getFeaturePaymentCode().toString());\n obj.put(\"signature\", sig);\n\n// Log.d(\"BalanceActivity\", \"nym/add:\" + obj.toString());\n res = com.samourai.wallet.bip47.paynym.WebUtil.getInstance(BalanceActivity.this).postURL(\"application/json\", token, com.samourai.wallet.bip47.paynym.WebUtil.PAYNYM_API + \"api/v1/nym/add\", obj.toString());\n// Log.d(\"BalanceActivity\", res);\n\n responseObj = new JSONObject(res);\n if (responseObj.has(\"segwit\") && responseObj.has(\"token\")) {\n PrefsUtil.getInstance(BalanceActivity.this).setValue(PrefsUtil.PAYNYM_FEATURED_SEGWIT, true);\n } else if (responseObj.has(\"claimed\") && responseObj.getBoolean(\"claimed\") == true) {\n PrefsUtil.getInstance(BalanceActivity.this).setValue(PrefsUtil.PAYNYM_FEATURED_SEGWIT, true);\n }\n\n }\n return true;\n }).subscribeOn(Schedulers.newThread())\n .observeOn(AndroidSchedulers.mainThread())\n .subscribe(aBoolean -> {\n Log.i(TAG, \"doFeaturePayNymUpdate: Feature update complete\");\n }, error -> {\n Log.i(TAG, \"doFeaturePayNymUpdate: Feature update Fail\");\n });\n compositeDisposable.add(disposable);\n\n\n }\n\n\n}\n"},"message":{"kind":"string","value":"Fix re-appearing dust warnings \n\n"},"old_file":{"kind":"string","value":"app/src/main/java/com/samourai/wallet/home/BalanceActivity.java"},"subject":{"kind":"string","value":"Fix re-appearing dust warnings "},"git_diff":{"kind":"string","value":"pp/src/main/java/com/samourai/wallet/home/BalanceActivity.java\n import androidx.recyclerview.widget.LinearLayoutManager;\n import androidx.recyclerview.widget.RecyclerView;\n import androidx.appcompat.widget.Toolbar;\n\n import android.text.InputType;\n import android.util.Log;\n import android.util.TypedValue;\n final String hash = out.getHash().toString();\n final int idx = out.getTxOutputN();\n final long amount = out.getValue().longValue();\n\n if (amount < BlockedUTXO.BLOCKED_UTXO_THRESHOLD &&\n ((!BlockedUTXO.getInstance().contains(hash, idx) &&\n !BlockedUTXO.getInstance().containsNotDusted(hash, idx))\n ||\n (!BlockedUTXO.getInstance().containsPostMix(hash, idx) &&\n !BlockedUTXO.getInstance().containsNotDustedPostMix(hash, idx)))\n ){\n boolean contains = ((BlockedUTXO.getInstance().contains(hash, idx) || BlockedUTXO.getInstance().containsNotDusted(hash, idx)));\n\n boolean containsInPostMix = (BlockedUTXO.getInstance().containsPostMix(hash, idx) || BlockedUTXO.getInstance().containsNotDustedPostMix(hash, idx));\n\n\n if (amount < BlockedUTXO.BLOCKED_UTXO_THRESHOLD && (!contains && !containsInPostMix)) {\n \n // BalanceActivity.this.runOnUiThread(new Runnable() {\n // @Override\n Handler handler = new Handler();\n handler.post(new Runnable() {\n public void run() {\n\n String message = BalanceActivity.this.getString(R.string.dusting_attempt);\n message += \"\\n\\n\";\n message += BalanceActivity.this.getString(R.string.dusting_attempt_amount);\n message += \" \";\n message += Coin.valueOf(amount).toPlainString();\n message += \" BTC\\n\";\n message += BalanceActivity.this.getString(R.string.dusting_attempt_id);\n message += \" \";\n message += hash + \"-\" + idx;\n\n MaterialAlertDialogBuilder dlg = new MaterialAlertDialogBuilder(BalanceActivity.this)\n .setTitle(R.string.dusting_tx)\n .setMessage(message)\n .setCancelable(false)\n .setPositiveButton(R.string.dusting_attempt_mark_unspendable, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n\n if(account == WhirlpoolMeta.getInstance(BalanceActivity.this).getWhirlpoolPostmix()) {\n BlockedUTXO.getInstance().addPostMix(hash, idx, amount);\n }\n else {\n BlockedUTXO.getInstance().add(hash, idx, amount);\n }\n saveState();\n handler.post(() -> {\n\n String message = BalanceActivity.this.getString(R.string.dusting_attempt);\n message += \"\\n\\n\";\n message += BalanceActivity.this.getString(R.string.dusting_attempt_amount);\n message += \" \";\n message += Coin.valueOf(amount).toPlainString();\n message += \" BTC\\n\";\n message += BalanceActivity.this.getString(R.string.dusting_attempt_id);\n message += \" \";\n message += hash + \"-\" + idx;\n\n MaterialAlertDialogBuilder dlg = new MaterialAlertDialogBuilder(BalanceActivity.this)\n .setTitle(R.string.dusting_tx)\n .setMessage(message)\n .setCancelable(false)\n .setPositiveButton(R.string.dusting_attempt_mark_unspendable, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n\n if (account == WhirlpoolMeta.getInstance(BalanceActivity.this).getWhirlpoolPostmix()) {\n BlockedUTXO.getInstance().addPostMix(hash, idx, amount);\n } else {\n BlockedUTXO.getInstance().add(hash, idx, amount);\n }\n }).setNegativeButton(R.string.dusting_attempt_ignore, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n\n if(account == WhirlpoolMeta.getInstance(BalanceActivity.this).getWhirlpoolPostmix()) {\n BlockedUTXO.getInstance().addNotDustedPostMix(hash, idx);\n }\n else {\n BlockedUTXO.getInstance().addNotDusted(hash, idx);\n }\n\n saveState();\n }\n }).setNegativeButton(R.string.dusting_attempt_ignore, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n\n if (account == WhirlpoolMeta.getInstance(BalanceActivity.this).getWhirlpoolPostmix()) {\n BlockedUTXO.getInstance().addNotDustedPostMix(hash, idx);\n } else {\n BlockedUTXO.getInstance().addNotDusted(hash, idx);\n }\n });\n if (!isFinishing()) {\n dlg.show();\n }\n\n saveState();\n }\n });\n if (!isFinishing()) {\n dlg.show();\n }\n\n });\n \n }\n if (!PermissionsUtil.getInstance(BalanceActivity.this).hasPermission(Manifest.permission.CAMERA)) {\n PermissionsUtil.getInstance(BalanceActivity.this).showRequestPermissionsInfoAlertDialog(PermissionsUtil.CAMERA_PERMISSION_CODE);\n }\n if (PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.PAYNYM_CLAIMED, false) && !PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.PAYNYM_FEATURED_SEGWIT, false)) {\n if (PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.PAYNYM_CLAIMED, false) && !PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.PAYNYM_FEATURED_SEGWIT, false)) {\n doFeaturePayNymUpdate();\n } else if (!PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.PAYNYM_CLAIMED, false) &&\n !PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.PAYNYM_REFUSED, false)) {\n }\n \n private void showProgress() {\n progressBar.setIndeterminate(true);\n progressBar.show();\n progressBar.setIndeterminate(true);\n progressBar.show();\n }\n \n private void checkDeepLinks() {\n throwable.printStackTrace();\n \n if (balanceViewModel.getBalance().getValue() != null) {\n balanceViewModel.setBalance(balance);\n balanceViewModel.setBalance(balance);\n } else {\n balanceViewModel.setBalance(balance);\n }\n PrivKeyReader privKeyReader = new PrivKeyReader(new CharSequenceX(code.trim()));\n try {\n if (privKeyReader.getFormat() != null) {\n doPrivKey(code.trim());\n } else if (Cahoots.isCahoots(code.trim())) {\n Intent cahootIntent = ManualCahootsActivity.createIntentResume(this, account, code.trim());\n startActivity(cahootIntent);\n } else if (FormatsUtil.getInstance().isPSBT(code.trim())) {\n PSBTUtil.getInstance(BalanceActivity.this).doPSBT(code.trim());\n doPrivKey(code.trim());\n } else if (Cahoots.isCahoots(code.trim())) {\n Intent cahootIntent = ManualCahootsActivity.createIntentResume(this, account, code.trim());\n startActivity(cahootIntent);\n } else if (FormatsUtil.getInstance().isPSBT(code.trim())) {\n PSBTUtil.getInstance(BalanceActivity.this).doPSBT(code.trim());\n } else if (DojoUtil.getInstance(BalanceActivity.this).isValidPairingPayload(code.trim())) {\n Toast.makeText(BalanceActivity.this, \"Samourai Dojo full node coming soon.\", Toast.LENGTH_SHORT).show();\n } else {"}}},{"rowIdx":1913,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"cd7ccb62d11c469f7f7d99807008a62205e60096"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"leandrocgsi/erudio-api-oauth2,leandrocgsi/erudio-api-oauth2"},"new_contents":{"kind":"string","value":"package br.com.erudio.entrypoint.v1;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\nimport org.junit.Test;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.security.access.annotation.Secured;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\nimport org.springframework.web.bind.annotation.ResponseBody;\nimport org.springframework.web.bind.annotation.ResponseStatus;\n\nimport com.wordnik.swagger.annotations.Api;\nimport com.wordnik.swagger.annotations.ApiOperation;\n\nimport br.com.erudio.model.Country;\nimport br.com.erudio.repository.interfaces.ICountryRepository;\nimport br.com.erudio.vo.CountryVO;\n\n@Controller\n@Secured(\"ROLE_USER\")\n@Api(value = \"city\", description = \"Exposes endpoints of service City.\")\n@RequestMapping(\"/api/v1/country\")\npublic class CountryEntryPoint {\n\n\t@Autowired\n private ICountryRepository countryRepository;\n \n\t/*@RequestMapping(method = RequestMethod.POST)\n @ResponseStatus(value = HttpStatus.OK)\n\t@ApiOperation(httpMethod = \"POST\", value = \"Saving a country\")\n\tpublic @ResponseBody CountryVO save(@RequestBody CountryVO country) {\n\t\tcountry.setInsertDate(new Date());\n\t\tcountry.setIdUserInsert(0);\n\t\tcountry.setActive(true);\n\t\tCountry savedCountry = countryRepository.save(ObjectParser.parseObjectInputToObjectOutput(country, Country.class));\n\t\tCountryVO countryVO = ObjectParser.parseObjectInputToObjectOutput(savedCountry, CountryVO.class);\n\t\taddHATEOASSupport(countryVO);\n\t\treturn countryVO;\n\t}\n\n\t@RequestMapping(method = RequestMethod.PUT)\n @ResponseStatus(value = HttpStatus.OK)\n\t@ApiOperation(httpMethod = \"PUT\", value = \"Updating a country\")\n\tpublic @ResponseBody CountryVO update(@RequestBody CountryVO country) {\n\t\tcountry.setUpdatedDate(new Date());\n\t\tcountry.setIdUserUpdate(0);\n\t\tCountry updatedCountry = countryRepository.update(ObjectParser.parseObjectInputToObjectOutput(country, Country.class));\n\t\tCountryVO countryVO = ObjectParser.parseObjectInputToObjectOutput(updatedCountry, CountryVO.class);\n\t\taddHATEOASSupport(countryVO);\n\t\treturn cityVO;\n\t}\n \n\t@RequestMapping(value = \"/{id}\", method = RequestMethod.DELETE)\n @ResponseStatus(value = HttpStatus.OK)\n\t@ApiOperation(httpMethod = \"DELETE\", value = \"Deleting a country by id\")\n public @ResponseBody ResponseEntity delete(@PathVariable Integer id) {\n\t\tcountryReposiountryy.deleteById(id);\n\t\treturn new ResponseEntity(HttpStatus.OK);\n\t}\n\n\t@RequestMapping(value = \"/{id}\", method = RequestMethod.GET)\n\t@ResponseStatus(value = HttpStatus.OK)\n\t@ApiOperation(httpMethod = \"GET\", value = \"Find a country by id\")\n\tpublic @ResponseBody CountryVO findById(@PathVariable Integer id) {\n\t\tCountry country = countryRepository.findById(id);\n\t\tCountryVO countryVO = ObjectParser.parseObjectInputToObjectOutput(country, CountryVO.class);\n\t\taddHATEOASSupport(countryVO);\n\t\treturn countryVO;\n\t}\n\t\n\t@RequestMapping(value = \"/findByName/{name}\", method = RequestMethod.GET)\n @ResponseStatus(value = HttpStatus.OK)\n\t@ApiOperation(httpMethod = \"GET\", value = \"Find a country by name\")\n public @ResponseBody CountryVO findCountryVOByName(@PathVariable String name) {\n Country country = countryRepository.findByName(name);\n\t\tCountryVO countryVO = ObjectParser.parseObjectInputToObjectOutput(country, CountryVO.class);\n\t\taddHATEOASSupport(countryVO);\n\t\treturn countryVO;\n }*/\n \n\t@RequestMapping(value = \"/findAll\", method = RequestMethod.GET)\n @ResponseStatus(value = HttpStatus.OK)\n\t@ApiOperation(httpMethod = \"GET\", value = \"Find all cities\")\n public @ResponseBody List findAll() {\n List allCountries = countryRepository.findAll();\n\t\tList citiesVO = parseCountries(allCountries);\n//\t\tfor (CountryVO countryVO : citiesVO) addHATEOASSupport(countryVO);\n\t\treturn citiesVO;\n }\n\n\tprivate List parseCountries(List allCountries) {\n\t\tArrayList countries = new ArrayList<>();\n\t\tfor (Country country : allCountries) {\n\t\t\tCountryVO countryVO = new CountryVO();\n\t\t\tcountryVO.setIdCountry(country.getIdCountry());\n\t\t\tcountryVO.setLocaleMessageKey(country.getLocaleMessageKey());\n\t\t\tcountryVO.setName(country.getName());\n\t\t\tcountryVO.setStates(country.getStates());\n\t\t}\n\t\treturn countries;\n\t}\n\n\t\t@Test\n\t\tpublic void test(){\n\t\t\tString[] ary = \"Andorra la Vella|Bengo|Benguela|Bie|Cabinda|Canillo|Cuando Cubango|Cuanza Norte|Cuanza Sul|Cunene|Encamp|Escaldes-Engordany|Huambo|Huila|La Massana|Luanda|Lunda Norte|Lunda Sul|Malanje|Moxico|Namibe|Ordino|Sant Julia de Loria|Uige|Zaire\".split(\"\\\\|\");\n\t\t\tfor (String string : ary) {\n\t\t\t\tSystem.out.println(string);\n\t\t\t}\n\t\t\tList myList = new ArrayList(Arrays.asList(ary));\n\t\t}\n\t/*private void addHATEOASSupport(CountryVO countryVO) {\n\t\tcountryVO.add(linkTo(methodOn(CountryEntryPoint.class).findById(countryVO.getIdCountry())).withSelfRel());\n\t}*/\n}"},"new_file":{"kind":"string","value":"src/main/java/br/com/erudio/entrypoint/v1/CountryEntryPoint.java"},"old_contents":{"kind":"string","value":"package br.com.erudio.entrypoint.v1;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\nimport org.junit.Test;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.security.access.annotation.Secured;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\nimport org.springframework.web.bind.annotation.ResponseBody;\nimport org.springframework.web.bind.annotation.ResponseStatus;\n\nimport com.wordnik.swagger.annotations.Api;\nimport com.wordnik.swagger.annotations.ApiOperation;\n\nimport br.com.erudio.model.Country;\nimport br.com.erudio.repository.interfaces.ICountryRepository;\nimport br.com.erudio.vo.CountryVO;\n\n@Controller\n@Secured(\"ROLE_USER\")\n@Api(value = \"city\", description = \"Exposes endpoints of service City.\")\n@RequestMapping(\"/api/v1/country\")\npublic class CountryEntryPoint {\n\n\t@Autowired\n private ICountryRepository countryRepository;\n \n\t/*@RequestMapping(method = RequestMethod.POST)\n @ResponseStatus(value = HttpStatus.OK)\n\t@ApiOperation(httpMethod = \"POST\", value = \"Saving a country\")\n\tpublic @ResponseBody CountryVO save(@RequestBody CountryVO country) {\n\t\tcountry.setInsertDate(new Date());\n\t\tcountry.setIdUserInsert(0);\n\t\tcountry.setActive(true);\n\t\tCountry savedCountry = countryRepository.save(ObjectParser.parseObjectInputToObjectOutput(country, Country.class));\n\t\tCountryVO countryVO = ObjectParser.parseObjectInputToObjectOutput(savedCountry, CountryVO.class);\n\t\taddHATEOASSupport(countryVO);\n\t\treturn countryVO;\n\t}\n\n\t@RequestMapping(method = RequestMethod.PUT)\n @ResponseStatus(value = HttpStatus.OK)\n\t@ApiOperation(httpMethod = \"PUT\", value = \"Updating a country\")\n\tpublic @ResponseBody CountryVO update(@RequestBody CountryVO country) {\n\t\tcountry.setUpdatedDate(new Date());\n\t\tcountry.setIdUserUpdate(0);\n\t\tCountry updatedCountry = countryRepository.update(ObjectParser.parseObjectInputToObjectOutput(country, Country.class));\n\t\tCountryVO countryVO = ObjectParser.parseObjectInputToObjectOutput(updatedCountry, CountryVO.class);\n\t\taddHATEOASSupport(countryVO);\n\t\treturn cityVO;\n\t}\n \n\t@RequestMapping(value = \"/{id}\", method = RequestMethod.DELETE)\n @ResponseStatus(value = HttpStatus.OK)\n\t@ApiOperation(httpMethod = \"DELETE\", value = \"Deleting a country by id\")\n public @ResponseBody ResponseEntity delete(@PathVariable Integer id) {\n\t\tcountryReposiountryy.deleteById(id);\n\t\treturn new ResponseEntity(HttpStatus.OK);\n\t}\n\n\t@RequestMapping(value = \"/{id}\", method = RequestMethod.GET)\n\t@ResponseStatus(value = HttpStatus.OK)\n\t@ApiOperation(httpMethod = \"GET\", value = \"Find a country by id\")\n\tpublic @ResponseBody CountryVO findById(@PathVariable Integer id) {\n\t\tCountry country = countryRepository.findById(id);\n\t\tCountryVO countryVO = ObjectParser.parseObjectInputToObjectOutput(country, CountryVO.class);\n\t\taddHATEOASSupport(countryVO);\n\t\treturn countryVO;\n\t}\n\t\n\t@RequestMapping(value = \"/findByName/{name}\", method = RequestMethod.GET)\n @ResponseStatus(value = HttpStatus.OK)\n\t@ApiOperation(httpMethod = \"GET\", value = \"Find a country by name\")\n public @ResponseBody CountryVO findCountryVOByName(@PathVariable String name) {\n Country country = countryRepository.findByName(name);\n\t\tCountryVO countryVO = ObjectParser.parseObjectInputToObjectOutput(country, CountryVO.class);\n\t\taddHATEOASSupport(countryVO);\n\t\treturn countryVO;\n }*/\n \n\t@RequestMapping(value = \"/findAll\", method = RequestMethod.GET)\n @ResponseStatus(value = HttpStatus.OK)\n\t@ApiOperation(httpMethod = \"GET\", value = \"Find all cities\")\n public @ResponseBody List findAll() {\n List allCountries = countryRepository.findAll();\n\t\tList citiesVO = parseCountries(allCountries);\n//\t\tfor (CountryVO countryVO : citiesVO) addHATEOASSupport(countryVO);\n\t\treturn citiesVO;\n }\n\n\tprivate List parseCountries(List allCountries) {\n\t\tArrayList countries = new ArrayList<>();\n\t\tfor (Country country : allCountries) {\n\t\t\tCountryVO countryVO = new CountryVO();\n\t\t\tcountryVO.setIdCountry(country.getIdCountry());\n\t\t\tcountryVO.setLocaleMessageKey(country.getLocaleMessageKey());\n\t\t\tcountryVO.setName(country.getName());\n\t\t\tcountryVO.setStates(country.getStates());\n\t\t}\n\t\treturn countries;\n\t}\n\n\t\t@Test\n\t\tpublic void test(){\n\t\t\tList myList = new ArrayList(Arrays.asList(\"Andorra la Vella|Bengo|Benguela|Bie|Cabinda|Canillo|Cuando Cubango|Cuanza Norte|Cuanza Sul|Cunene|Encamp|Escaldes-Engordany|Huambo|Huila|La Massana|Luanda|Lunda Norte|Lunda Sul|Malanje|Moxico|Namibe|Ordino|Sant Julia de Loria|Uige|Zaire\".split(\"|\")));\n\t\t\tSystem.out.println(myList);;\n\t\t}\n\t/*private void addHATEOASSupport(CountryVO countryVO) {\n\t\tcountryVO.add(linkTo(methodOn(CountryEntryPoint.class).findById(countryVO.getIdCountry())).withSelfRel());\n\t}*/\n}"},"message":{"kind":"string","value":"Adding Country entry point\n"},"old_file":{"kind":"string","value":"src/main/java/br/com/erudio/entrypoint/v1/CountryEntryPoint.java"},"subject":{"kind":"string","value":"Adding Country entry point"},"git_diff":{"kind":"string","value":"rc/main/java/br/com/erudio/entrypoint/v1/CountryEntryPoint.java\n \n \t\t@Test\n \t\tpublic void test(){\n\t\t\tList myList = new ArrayList(Arrays.asList(\"Andorra la Vella|Bengo|Benguela|Bie|Cabinda|Canillo|Cuando Cubango|Cuanza Norte|Cuanza Sul|Cunene|Encamp|Escaldes-Engordany|Huambo|Huila|La Massana|Luanda|Lunda Norte|Lunda Sul|Malanje|Moxico|Namibe|Ordino|Sant Julia de Loria|Uige|Zaire\".split(\"|\")));\n\t\t\tSystem.out.println(myList);;\n\t\t\tString[] ary = \"Andorra la Vella|Bengo|Benguela|Bie|Cabinda|Canillo|Cuando Cubango|Cuanza Norte|Cuanza Sul|Cunene|Encamp|Escaldes-Engordany|Huambo|Huila|La Massana|Luanda|Lunda Norte|Lunda Sul|Malanje|Moxico|Namibe|Ordino|Sant Julia de Loria|Uige|Zaire\".split(\"\\\\|\");\n\t\t\tfor (String string : ary) {\n\t\t\t\tSystem.out.println(string);\n\t\t\t}\n\t\t\tList myList = new ArrayList(Arrays.asList(ary));\n \t\t}\n \t/*private void addHATEOASSupport(CountryVO countryVO) {\n \t\tcountryVO.add(linkTo(methodOn(CountryEntryPoint.class).findById(countryVO.getIdCountry())).withSelfRel());"}}},{"rowIdx":1914,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"2af508ef838daf87bad66a9db129e499194ed486"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable"},"new_contents":{"kind":"string","value":"/*\n * Copyright (c) 2010 The Broad Institute\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use,\n * copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following\n * conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR\n * THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\npackage org.broadinstitute.sting.commandline;\n\nimport org.broadinstitute.sting.utils.exceptions.ReviewedStingException;\n\nimport java.util.*;\nimport java.lang.annotation.Annotation;\n\n/**\n * Static utility methods for working with command-line arguments.\n *\n * @author mhanna\n * @version 0.1\n */\npublic class CommandLineUtils {\n\n /**\n * Returns a key-value mapping of the command-line arguments passed into the GATK.\n * Will be approximate; this class doesn't have all the required data to completely\n * reconstruct the list of command-line arguments from the given objects.\n *\n * @param parsingEngine The parsing engine\n * @param argumentProviders The providers of command-line arguments.\n * @return A key-value mapping of argument full names to argument values. Produces best string representation\n * possible given the information available.\n */\n public static Map getApproximateCommandLineArguments(ParsingEngine parsingEngine, Object... argumentProviders) {\n return getApproximateCommandLineArguments(parsingEngine, false, argumentProviders);\n }\n\n /**\n * Returns a key-value mapping of the command-line arguments passed into the GATK.\n * Will be approximate; this class doesn't have all the required data to completely\n * reconstruct the list of command-line arguments from the given objects.\n * \n * @param parsingEngine The parsing engine\n * @param skipObjectPointers Should we skip arguments whose values are pointers (and don't print nicely)?\n * @param argumentProviders The providers of command-line arguments.\n * @return A key-value mapping of argument full names to argument values. Produces best string representation\n * possible given the information available.\n */\n public static Map getApproximateCommandLineArguments(ParsingEngine parsingEngine, boolean skipObjectPointers, Object... argumentProviders) {\n Map commandLineArguments = new LinkedHashMap();\n\n for(Object argumentProvider: argumentProviders) {\n Map argBindings = parsingEngine.extractArgumentBindings(argumentProvider);\n for(Map.Entry elt: argBindings.entrySet()) {\n Object argumentValue = elt.getValue();\n\n String argumentValueString = argumentValue != null ? argumentValue.toString() : null;\n if ( skipObjectPointers && isObjectPointer(argumentValueString) )\n continue;\n\n for(ArgumentDefinition definition: elt.getKey().createArgumentDefinitions()) {\n String argumentName = definition.fullName;\n commandLineArguments.put(argumentName,argumentValueString);\n }\n }\n }\n\n return commandLineArguments;\n }\n\n /**\n * Create an approximate list of command-line arguments based on the given argument providers.\n * @param parsingEngine The parsing engine\n * @param argumentProviders Argument providers to inspect.\n * @return A string representing the given command-line arguments.\n */\n public static String createApproximateCommandLineArgumentString(ParsingEngine parsingEngine, Object... argumentProviders) {\n return createApproximateCommandLineArgumentString(parsingEngine, true, argumentProviders);\n }\n\n /**\n * Create an approximate list of command-line arguments based on the given argument providers.\n * @param parsingEngine The parsing engine\n * @param skipObjectPointers Should we skip arguments whose values are pointers (and don't print nicely)?\n * @param argumentProviders Argument providers to inspect.\n * @return A string representing the given command-line arguments.\n */\n public static String createApproximateCommandLineArgumentString(ParsingEngine parsingEngine, boolean skipObjectPointers, Object... argumentProviders) {\n Map commandLineArgs = getApproximateCommandLineArguments(parsingEngine, skipObjectPointers, argumentProviders);\n StringBuffer sb = new StringBuffer();\n\n boolean first = true;\n for ( Map.Entry commandLineArg : commandLineArgs.entrySet() ) {\n if ( !first )\n sb.append(\" \");\n sb.append(commandLineArg.getKey());\n sb.append(\"=\");\n sb.append(commandLineArg.getValue());\n first = false;\n }\n\n return sb.toString();\n }\n\n /**\n * A hack to get around the fact that Java doesn't like inheritance in Annotations.\n * @param annotation to run the method on\n * @param method the method to invoke\n * @return the return value of the method\n */\n public static Object getValue(Annotation annotation, String method) {\n try {\n return annotation.getClass().getMethod(method).invoke(annotation);\n } catch (Exception e) {\n throw new ReviewedStingException(\"Unable to access method \" + method + \" on annotation \" + annotation.getClass(), e);\n }\n }\n\n // The problem here is that some of the fields being output are Objects - and those\n // Objects don't overload toString() so that the output is just the memory pointer\n // to the Object. Because those values are non-deterministic, they don't merge well\n // into BAM/VCF headers (plus, it's just damn ugly). Perhaps there's a better way to\n // do this, but at least this one works for the moment.\n private static final String pointerRegexp = \".+@[0-9a-fA-F]+$\";\n private static boolean isObjectPointer(String s) {\n return s != null && s.matches(pointerRegexp);\n }\n}\n"},"new_file":{"kind":"string","value":"java/src/org/broadinstitute/sting/commandline/CommandLineUtils.java"},"old_contents":{"kind":"string","value":"/*\n * Copyright (c) 2010 The Broad Institute\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use,\n * copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following\n * conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR\n * THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\npackage org.broadinstitute.sting.commandline;\n\nimport org.broadinstitute.sting.utils.exceptions.ReviewedStingException;\n\nimport java.util.*;\nimport java.lang.annotation.Annotation;\n\n/**\n * Static utility methods for working with command-line arguments.\n *\n * @author mhanna\n * @version 0.1\n */\npublic class CommandLineUtils {\n\n /**\n * Returns a key-value mapping of the command-line arguments passed into the GATK.\n * Will be approximate; this class doesn't have all the required data to completely\n * reconstruct the list of command-line arguments from the given objects.\n *\n * @param parsingEngine The parsing engine\n * @param argumentProviders The providers of command-line arguments.\n * @return A key-value mapping of argument full names to argument values. Produces best string representation\n * possible given the information available.\n */\n public static Map getApproximateCommandLineArguments(ParsingEngine parsingEngine, Object... argumentProviders) {\n return getApproximateCommandLineArguments(parsingEngine, false, argumentProviders);\n }\n\n /**\n * Returns a key-value mapping of the command-line arguments passed into the GATK.\n * Will be approximate; this class doesn't have all the required data to completely\n * reconstruct the list of command-line arguments from the given objects.\n * \n * @param parsingEngine The parsing engine\n * @param skipObjectPointers Should we skip arguments whose values are pointers (and don't print nicely)?\n * @param argumentProviders The providers of command-line arguments.\n * @return A key-value mapping of argument full names to argument values. Produces best string representation\n * possible given the information available.\n */\n public static Map getApproximateCommandLineArguments(ParsingEngine parsingEngine, boolean skipObjectPointers, Object... argumentProviders) {\n Map commandLineArguments = new LinkedHashMap();\n\n for(Object argumentProvider: argumentProviders) {\n Map argBindings = parsingEngine.extractArgumentBindings(argumentProvider);\n for(Map.Entry elt: argBindings.entrySet()) {\n Object argumentValue = elt.getValue();\n\n String argumentValueString = argumentValue != null ? argumentValue.toString() : null;\n if ( skipObjectPointers && isObjectPointer(argumentValueString) )\n continue;\n\n for(ArgumentDefinition definition: elt.getKey().createArgumentDefinitions()) {\n String argumentName = definition.fullName;\n commandLineArguments.put(argumentName,argumentValueString);\n }\n }\n }\n\n return commandLineArguments;\n }\n\n /**\n * Create an approximate list of command-line arguments based on the given argument providers.\n * @param parsingEngine The parsing engine\n * @param argumentProviders Argument providers to inspect.\n * @return A string representing the given command-line arguments.\n */\n public static String createApproximateCommandLineArgumentString(ParsingEngine parsingEngine, Object... argumentProviders) {\n return createApproximateCommandLineArgumentString(parsingEngine, true, argumentProviders);\n }\n\n /**\n * Create an approximate list of command-line arguments based on the given argument providers.\n * @param parsingEngine The parsing engine\n * @param skipObjectPointers Should we skip arguments whose values are pointers (and don't print nicely)?\n * @param argumentProviders Argument providers to inspect.\n * @return A string representing the given command-line arguments.\n */\n public static String createApproximateCommandLineArgumentString(ParsingEngine parsingEngine, boolean skipObjectPointers, Object... argumentProviders) {\n Map commandLineArgs = getApproximateCommandLineArguments(parsingEngine, skipObjectPointers, argumentProviders);\n StringBuffer sb = new StringBuffer();\n\n boolean first = true;\n for ( Map.Entry commandLineArg : commandLineArgs.entrySet() ) {\n if ( !first )\n sb.append(\" \");\n sb.append(commandLineArg.getKey());\n sb.append(\"=\");\n sb.append(commandLineArg.getValue());\n first = false;\n }\n\n return sb.toString();\n }\n\n /**\n * A hack to get around the fact that Java doesn't like inheritance in Annotations.\n * @param annotation to run the method on\n * @param method the method to invoke\n * @return the return value of the method\n */\n public static Object getValue(Annotation annotation, String method) {\n try {\n return annotation.getClass().getMethod(method).invoke(annotation);\n } catch (Exception e) {\n throw new ReviewedStingException(\"Unable to access method \" + method + \" on annotation \" + annotation.getClass(), e);\n }\n }\n\n // TODO -- is there a better way to do this?\n private static final String pointerRegexp = \".+@[0-9a-fA-F]+$\";\n private static boolean isObjectPointer(String s) {\n return s != null && s.matches(pointerRegexp);\n }\n}\n"},"message":{"kind":"string","value":"Better docs, as requested by Matt\n\ngit-svn-id: 4561c0a8f080806b19201efb9525134c00b76d40@4681 348d0f76-0448-11de-a6fe-93d51630548a\n"},"old_file":{"kind":"string","value":"java/src/org/broadinstitute/sting/commandline/CommandLineUtils.java"},"subject":{"kind":"string","value":"Better docs, as requested by Matt"},"git_diff":{"kind":"string","value":"ava/src/org/broadinstitute/sting/commandline/CommandLineUtils.java\n }\n }\n \n // TODO -- is there a better way to do this?\n // The problem here is that some of the fields being output are Objects - and those\n // Objects don't overload toString() so that the output is just the memory pointer\n // to the Object. Because those values are non-deterministic, they don't merge well\n // into BAM/VCF headers (plus, it's just damn ugly). Perhaps there's a better way to\n // do this, but at least this one works for the moment.\n private static final String pointerRegexp = \".+@[0-9a-fA-F]+$\";\n private static boolean isObjectPointer(String s) {\n return s != null && s.matches(pointerRegexp);"}}},{"rowIdx":1915,"cells":{"lang":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"e8eed83f58d7a887836d6cbde55313fb42eaa7ea"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"TheFive/osmbc,fredao/osmbc,TheFive/osmbc,fredao/osmbc,fredao/osmbc,TheFive/osmbc"},"new_contents":{"kind":"string","value":"exports.osmbc_version = \"0.3.12a\";\n\n\n\n"},"new_file":{"kind":"string","value":"version.js"},"old_contents":{"kind":"string","value":"exports.osmbc_version = \"0.3.12\";\n\n\n\n"},"message":{"kind":"string","value":"Version\n"},"old_file":{"kind":"string","value":"version.js"},"subject":{"kind":"string","value":"Version"},"git_diff":{"kind":"string","value":"ersion.js\nexports.osmbc_version = \"0.3.12\";\nexports.osmbc_version = \"0.3.12a\";\n \n \n "}}},{"rowIdx":1916,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"bc8f5a2b18d271080d2311db08bf9fd93fcbbd01"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"cn-cerc/summer-mis,cn-cerc/summer-mis"},"new_contents":{"kind":"string","value":"package cn.cerc.ui.parts;\n\nimport cn.cerc.core.Utils;\nimport cn.cerc.ui.core.HtmlWriter;\nimport cn.cerc.ui.core.UrlRecord;\nimport cn.cerc.ui.vcl.UIButton;\nimport cn.cerc.ui.vcl.UIImage;\nimport cn.cerc.ui.vcl.ext.UISpan;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class UISheetMenu extends UISheet {\n private List menus = new ArrayList<>();\n private UIImage icon; // 显示icon\n private UISpan caption; // 标题\n private UIButton opera; // 操作\n\n public UISheetMenu(UIToolbar owner) {\n super(owner);\n this.setCssClass(\"menuList\");\n }\n\n @Override\n public void output(HtmlWriter html) {\n if (menus.size() == 0) {\n return;\n }\n\n html.println(\"

\", this.cssClass);\n if (caption != null) {\n html.println(\"
\");\n icon.output(html);\n caption.output(html);\n if (opera != null) {\n opera.output(html);\n }\n html.println(\"
\");\n }\n html.println(\"
\");\n html.println(\"
    \");\n for (UrlRecord url : menus) {\n html.println(\"
  • \");\n html.print(\"\", url.getImgage());\n\n html.print(\"%s\", url.getName());\n if (url.isWindow()) {\n String hrip = \"hrip:\" + url.getUrl();\n html.print(\" \", hrip, \"images/menu/erp-blue.png\");\n }\n if (Utils.isNotEmpty(url.getArrow())) {\n html.println(\"\", url.getArrow());\n }\n html.println(\"
  • \");\n }\n html.println(\"
\");\n html.println(\"
\");\n html.println(\"
\");\n }\n\n public UrlRecord addMenu() {\n UrlRecord menu = new UrlRecord();\n menus.add(menu);\n return menu;\n }\n\n public UrlRecord addMenus(UrlRecord menu) {\n menus.add(menu);\n return menu;\n }\n\n public void setIconAndCaption(String logoUrl, String caption) {\n this.icon = new UIImage();\n this.icon.setSrc(logoUrl);\n this.caption = new UISpan();\n this.caption.setText(caption);\n }\n\n public void setIconAndCaption(String logoUrl, String caption, UIButton opera) {\n this.icon = new UIImage();\n this.icon.setSrc(logoUrl);\n this.caption = new UISpan();\n this.caption.setText(caption);\n this.opera = opera;\n }\n}\n"},"new_file":{"kind":"string","value":"summer-mis/src/main/java/cn/cerc/ui/parts/UISheetMenu.java"},"old_contents":{"kind":"string","value":"package cn.cerc.ui.parts;\n\nimport cn.cerc.core.Utils;\nimport cn.cerc.ui.core.HtmlWriter;\nimport cn.cerc.ui.core.UrlRecord;\nimport cn.cerc.ui.vcl.UIButton;\nimport cn.cerc.ui.vcl.UIImage;\nimport cn.cerc.ui.vcl.ext.UISpan;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class UISheetMenu extends UISheet {\n private List menus = new ArrayList<>();\n private UIImage icon; // 显示icon\n private UISpan caption; // 标题\n private UIButton opera; // 操作\n\n public UISheetMenu(UIToolbar owner) {\n super(owner);\n this.setCssClass(\"menuList\");\n }\n\n @Override\n public void output(HtmlWriter html) {\n if (menus.size() == 0) {\n return;\n }\n\n html.println(\"
\", this.cssClass);\n if (caption != null) {\n html.println(\"
\");\n icon.output(html);\n caption.output(html);\n if (opera != null) {\n opera.output(html);\n }\n html.println(\"
\");\n }\n html.println(\"
\");\n html.println(\"
    \");\n for (UrlRecord url : menus) {\n html.println(\"
  • \");\n html.print(\"\", url.getImgage());\n\n html.print(\"%s\", url.getName());\n if (url.isWindow()) {\n String hrip = \"hrip:\" + url.getUrl();\n html.print(\" \",hrip,\"images/menu/erp-blue.png\");\n //html.print(\"\",hrip);\n }\n if (Utils.isNotEmpty(url.getArrow())) {\n html.println(\"\", url.getArrow());\n }\n html.println(\"
  • \");\n }\n html.println(\"
\");\n html.println(\"
\");\n html.println(\"
\");\n }\n\n public UrlRecord addMenu() {\n UrlRecord menu = new UrlRecord();\n menus.add(menu);\n return menu;\n }\n\n public UrlRecord addMenus(UrlRecord menu) {\n menus.add(menu);\n return menu;\n }\n\n public void setIconAndCaption(String logoUrl, String caption) {\n this.icon = new UIImage();\n this.icon.setSrc(logoUrl);\n this.caption = new UISpan();\n this.caption.setText(caption);\n }\n\n public void setIconAndCaption(String logoUrl, String caption, UIButton opera) {\n this.icon = new UIImage();\n this.icon.setSrc(logoUrl);\n this.caption = new UISpan();\n this.caption.setText(caption);\n this.opera = opera;\n }\n}\n"},"message":{"kind":"string","value":"给闪电版图标增加class\n"},"old_file":{"kind":"string","value":"summer-mis/src/main/java/cn/cerc/ui/parts/UISheetMenu.java"},"subject":{"kind":"string","value":"给闪电版图标增加class"},"git_diff":{"kind":"string","value":"ummer-mis/src/main/java/cn/cerc/ui/parts/UISheetMenu.java\n html.print(\">%s\", url.getName());\n if (url.isWindow()) {\n String hrip = \"hrip:\" + url.getUrl();\n html.print(\" \",hrip,\"images/menu/erp-blue.png\");\n //html.print(\"\",hrip);\n html.print(\" \", hrip, \"images/menu/erp-blue.png\");\n }\n if (Utils.isNotEmpty(url.getArrow())) {\n html.println(\"\", url.getArrow());"}}},{"rowIdx":1917,"cells":{"lang":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"82c5c763357c401135675a39bfabf9b7f6805815"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"tiemevanveen/markerclustererpluspatch,tiemevanveen/markerclustererpluspatch,tiemevanveen/markerclustererpluspatch"},"new_contents":{"kind":"string","value":"/**\n * @name MarkerClustererPlus for Google Maps V3\n * @version 2.1.2 [May 28, 2014]\n * @author Gary Little\n * @fileoverview\n * The library creates and manages per-zoom-level clusters for large amounts of markers.\n *

\n * This is an enhanced V3 implementation of the\n * V2 MarkerClusterer by Xiaoxi Wu. It is based on the\n * V3 MarkerClusterer port by Luke Mahe. MarkerClustererPlus was created by Gary Little.\n *

\n * v2.0 release: MarkerClustererPlus v2.0 is backward compatible with MarkerClusterer v1.0. It\n * adds support for the ignoreHidden, title, batchSizeIE,\n * and calculator properties as well as support for four more events. It also allows\n * greater control over the styling of the text that appears on the cluster marker. The\n * documentation has been significantly improved and the overall code has been simplified and\n * polished. Very large numbers of markers can now be managed without causing Javascript timeout\n * errors on Internet Explorer. Note that the name of the clusterclick event has been\n * deprecated. The new name is click, so please change your application code now.\n */\n\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\n\n/**\n * @name ClusterIconStyle\n * @class This class represents the object for values in the styles array passed\n * to the {@link MarkerClusterer} constructor. The element in this array that is used to\n * style the cluster icon is determined by calling the calculator function.\n *\n * @property {string} url The URL of the cluster icon image file. Required.\n * @property {number} height The display height (in pixels) of the cluster icon. Required.\n * @property {number} width The display width (in pixels) of the cluster icon. Required.\n * @property {Array} [anchorText] The position (in pixels) from the center of the cluster icon to\n * where the text label is to be centered and drawn. The format is [yoffset, xoffset]\n * where yoffset increases as you go down from center and xoffset\n * increases to the right of center. The default is [0, 0].\n * @property {Array} [anchorIcon] The anchor position (in pixels) of the cluster icon. This is the\n * spot on the cluster icon that is to be aligned with the cluster position. The format is\n * [yoffset, xoffset] where yoffset increases as you go down and\n * xoffset increases to the right of the top-left corner of the icon. The default\n * anchor position is the center of the cluster icon.\n * @property {string} [textColor=\"black\"] The color of the label text shown on the\n * cluster icon.\n * @property {number} [textSize=11] The size (in pixels) of the label text shown on the\n * cluster icon.\n * @property {string} [textDecoration=\"none\"] The value of the CSS text-decoration\n * property for the label text shown on the cluster icon.\n * @property {string} [fontWeight=\"bold\"] The value of the CSS font-weight\n * property for the label text shown on the cluster icon.\n * @property {string} [fontStyle=\"normal\"] The value of the CSS font-style\n * property for the label text shown on the cluster icon.\n * @property {string} [fontFamily=\"Arial,sans-serif\"] The value of the CSS font-family\n * property for the label text shown on the cluster icon.\n * @property {string} [backgroundPosition=\"0 0\"] The position of the cluster icon image\n * within the image defined by url. The format is \"xpos ypos\"\n * (the same format as for the CSS background-position property). You must set\n * this property appropriately when the image defined by url represents a sprite\n * containing multiple images. Note that the position must be specified in px units.\n */\n/**\n * @name ClusterIconInfo\n * @class This class is an object containing general information about a cluster icon. This is\n * the object that a calculator function returns.\n *\n * @property {string} text The text of the label to be shown on the cluster icon.\n * @property {number} index The index plus 1 of the element in the styles\n * array to be used to style the cluster icon.\n * @property {string} title The tooltip to display when the mouse moves over the cluster icon.\n * If this value is undefined or \"\", title is set to the\n * value of the title property passed to the MarkerClusterer.\n */\n/**\n * A cluster icon.\n *\n * @constructor\n * @extends google.maps.OverlayView\n * @param {Cluster} cluster The cluster with which the icon is to be associated.\n * @param {Array} [styles] An array of {@link ClusterIconStyle} defining the cluster icons\n * to use for various cluster sizes.\n * @private\n */\nfunction ClusterIcon(cluster, styles) {\n cluster.getMarkerClusterer().extend(ClusterIcon, google.maps.OverlayView);\n\n this.cluster_ = cluster;\n this.className_ = cluster.getMarkerClusterer().getClusterClass();\n this.styles_ = styles;\n this.center_ = null;\n this.div_ = null;\n this.sums_ = null;\n this.visible_ = false;\n\n this.setMap(cluster.getMap()); // Note: this causes onAdd to be called\n}\n\n\n/**\n * Adds the icon to the DOM.\n */\nClusterIcon.prototype.onAdd = function () {\n var cClusterIcon = this;\n var cMouseDownInCluster;\n var cDraggingMapByCluster;\n\n this.div_ = document.createElement(\"div\");\n this.div_.className = this.className_;\n if (this.visible_) {\n this.show();\n }\n\n this.getPanes().overlayMouseTarget.appendChild(this.div_);\n\n // Fix for Issue 157\n this.boundsChangedListener_ = google.maps.event.addListener(this.getMap(), \"bounds_changed\", function () {\n cDraggingMapByCluster = cMouseDownInCluster;\n });\n\n google.maps.event.addDomListener(this.div_, \"mousedown\", function () {\n cMouseDownInCluster = true;\n cDraggingMapByCluster = false;\n });\n\n google.maps.event.addDomListener(this.div_, \"click\", function (e) {\n cMouseDownInCluster = false;\n if (!cDraggingMapByCluster) {\n var theBounds;\n var mz;\n var mc = cClusterIcon.cluster_.getMarkerClusterer();\n /**\n * This event is fired when a cluster marker is clicked.\n * @name MarkerClusterer#click\n * @param {Cluster} c The cluster that was clicked.\n * @event\n */\n google.maps.event.trigger(mc, \"click\", cClusterIcon.cluster_);\n google.maps.event.trigger(mc, \"clusterclick\", cClusterIcon.cluster_); // deprecated name\n\n // The default click handler follows. Disable it by setting\n // the zoomOnClick property to false.\n if (mc.getZoomOnClick()) {\n // Zoom into the cluster.\n mz = mc.getMaxZoom();\n theBounds = cClusterIcon.cluster_.getBounds();\n mc.getMap().fitBounds(theBounds);\n // There is a fix for Issue 170 here:\n setTimeout(function () {\n mc.getMap().fitBounds(theBounds);\n // Don't zoom beyond the max zoom level\n if (mz !== null && (mc.getMap().getZoom() > mz)) {\n mc.getMap().setZoom(mz + 1);\n }\n }, 100);\n }\n\n // Prevent event propagation to the map:\n e.cancelBubble = true;\n if (e.stopPropagation) {\n e.stopPropagation();\n }\n }\n });\n\n google.maps.event.addDomListener(this.div_, \"mouseover\", function () {\n var mc = cClusterIcon.cluster_.getMarkerClusterer();\n /**\n * This event is fired when the mouse moves over a cluster marker.\n * @name MarkerClusterer#mouseover\n * @param {Cluster} c The cluster that the mouse moved over.\n * @event\n */\n google.maps.event.trigger(mc, \"mouseover\", cClusterIcon.cluster_);\n });\n\n google.maps.event.addDomListener(this.div_, \"mouseout\", function () {\n var mc = cClusterIcon.cluster_.getMarkerClusterer();\n /**\n * This event is fired when the mouse moves out of a cluster marker.\n * @name MarkerClusterer#mouseout\n * @param {Cluster} c The cluster that the mouse moved out of.\n * @event\n */\n google.maps.event.trigger(mc, \"mouseout\", cClusterIcon.cluster_);\n });\n};\n\n\n/**\n * Removes the icon from the DOM.\n */\nClusterIcon.prototype.onRemove = function () {\n if (this.div_ && this.div_.parentNode) {\n this.hide();\n google.maps.event.removeListener(this.boundsChangedListener_);\n google.maps.event.clearInstanceListeners(this.div_);\n this.div_.parentNode.removeChild(this.div_);\n this.div_ = null;\n }\n};\n\n\n/**\n * Draws the icon.\n */\nClusterIcon.prototype.draw = function () {\n if (this.visible_) {\n var pos = this.getPosFromLatLng_(this.center_);\n this.div_.style.top = pos.y + \"px\";\n this.div_.style.left = pos.x + \"px\";\n }\n};\n\n\n/**\n * Hides the icon.\n */\nClusterIcon.prototype.hide = function () {\n if (this.div_) {\n this.div_.style.display = \"none\";\n }\n this.visible_ = false;\n};\n\n\n/**\n * Positions and shows the icon.\n */\nClusterIcon.prototype.show = function () {\n if (this.div_) {\n var img = \"\";\n // NOTE: values must be specified in px units\n var bp = this.backgroundPosition_.split(\" \");\n var spriteH = parseInt(bp[0].replace(/^\\s+|\\s+$/g, \"\"), 10);\n var spriteV = parseInt(bp[1].replace(/^\\s+|\\s+$/g, \"\"), 10);\n var pos = this.getPosFromLatLng_(this.center_);\n this.div_.style.cssText = this.createCss(pos);\n img = \"\";\n this.div_.innerHTML = img + \"

\" + this.sums_.text + \"
\";\n if (typeof this.sums_.title === \"undefined\" || this.sums_.title === \"\") {\n this.div_.title = this.cluster_.getMarkerClusterer().getTitle();\n } else {\n this.div_.title = this.sums_.title;\n }\n this.div_.style.display = \"\";\n }\n this.visible_ = true;\n};\n\n\n/**\n * Sets the icon styles to the appropriate element in the styles array.\n *\n * @param {ClusterIconInfo} sums The icon label text and styles index.\n */\nClusterIcon.prototype.useStyle = function (sums) {\n this.sums_ = sums;\n var index = Math.max(0, sums.index - 1);\n index = Math.min(this.styles_.length - 1, index);\n var style = this.styles_[index];\n this.url_ = style.url;\n this.height_ = style.height;\n this.width_ = style.width;\n this.anchorText_ = style.anchorText || [0, 0];\n this.anchorIcon_ = style.anchorIcon || [parseInt(this.height_ / 2, 10), parseInt(this.width_ / 2, 10)];\n this.textColor_ = style.textColor || \"black\";\n this.textSize_ = style.textSize || 11;\n this.textDecoration_ = style.textDecoration || \"none\";\n this.fontWeight_ = style.fontWeight || \"bold\";\n this.fontStyle_ = style.fontStyle || \"normal\";\n this.fontFamily_ = style.fontFamily || \"Arial,sans-serif\";\n this.backgroundPosition_ = style.backgroundPosition || \"0 0\";\n};\n\n\n/**\n * Sets the position at which to center the icon.\n *\n * @param {google.maps.LatLng} center The latlng to set as the center.\n */\nClusterIcon.prototype.setCenter = function (center) {\n this.center_ = center;\n};\n\n\n/**\n * Creates the cssText style parameter based on the position of the icon.\n *\n * @param {google.maps.Point} pos The position of the icon.\n * @return {string} The CSS style text.\n */\nClusterIcon.prototype.createCss = function (pos) {\n var style = [];\n style.push(\"cursor: pointer;\");\n style.push(\"position: absolute; top: \" + pos.y + \"px; left: \" + pos.x + \"px;\");\n style.push(\"width: \" + this.width_ + \"px; height: \" + this.height_ + \"px;\");\n return style.join(\"\");\n};\n\n\n/**\n * Returns the position at which to place the DIV depending on the latlng.\n *\n * @param {google.maps.LatLng} latlng The position in latlng.\n * @return {google.maps.Point} The position in pixels.\n */\nClusterIcon.prototype.getPosFromLatLng_ = function (latlng) {\n var pos = this.getProjection().fromLatLngToDivPixel(latlng);\n pos.x -= this.anchorIcon_[1];\n pos.y -= this.anchorIcon_[0];\n pos.x = parseInt(pos.x, 10);\n pos.y = parseInt(pos.y, 10);\n return pos;\n};\n\n\n/**\n * Creates a single cluster that manages a group of proximate markers.\n * Used internally, do not call this constructor directly.\n * @constructor\n * @param {MarkerClusterer} mc The MarkerClusterer object with which this\n * cluster is associated.\n */\nfunction Cluster(mc) {\n this.markerClusterer_ = mc;\n this.map_ = mc.getMap();\n this.gridSize_ = mc.getGridSize();\n this.minClusterSize_ = mc.getMinimumClusterSize();\n this.averageCenter_ = mc.getAverageCenter();\n this.markers_ = [];\n this.center_ = null;\n this.bounds_ = null;\n this.clusterIcon_ = new ClusterIcon(this, mc.getStyles());\n}\n\n\n/**\n * Returns the number of markers managed by the cluster. You can call this from\n * a click, mouseover, or mouseout event handler\n * for the MarkerClusterer object.\n *\n * @return {number} The number of markers in the cluster.\n */\nCluster.prototype.getSize = function () {\n return this.markers_.length;\n};\n\n\n/**\n * Returns the array of markers managed by the cluster. You can call this from\n * a click, mouseover, or mouseout event handler\n * for the MarkerClusterer object.\n *\n * @return {Array} The array of markers in the cluster.\n */\nCluster.prototype.getMarkers = function () {\n return this.markers_;\n};\n\n\n/**\n * Returns the center of the cluster. You can call this from\n * a click, mouseover, or mouseout event handler\n * for the MarkerClusterer object.\n *\n * @return {google.maps.LatLng} The center of the cluster.\n */\nCluster.prototype.getCenter = function () {\n return this.center_;\n};\n\n\n/**\n * Returns the map with which the cluster is associated.\n *\n * @return {google.maps.Map} The map.\n * @ignore\n */\nCluster.prototype.getMap = function () {\n return this.map_;\n};\n\n\n/**\n * Returns the MarkerClusterer object with which the cluster is associated.\n *\n * @return {MarkerClusterer} The associated marker clusterer.\n * @ignore\n */\nCluster.prototype.getMarkerClusterer = function () {\n return this.markerClusterer_;\n};\n\n\n/**\n * Returns the bounds of the cluster.\n *\n * @return {google.maps.LatLngBounds} the cluster bounds.\n * @ignore\n */\nCluster.prototype.getBounds = function () {\n var i;\n var bounds = new google.maps.LatLngBounds(this.center_, this.center_);\n var markers = this.getMarkers();\n for (i = 0; i < markers.length; i++) {\n bounds.extend(markers[i].getPosition());\n }\n return bounds;\n};\n\n\n/**\n * Removes the cluster from the map.\n *\n * @ignore\n */\nCluster.prototype.remove = function () {\n this.clusterIcon_.setMap(null);\n this.markers_ = [];\n delete this.markers_;\n};\n\n\n/**\n * Adds a marker to the cluster.\n *\n * @param {google.maps.Marker} marker The marker to be added.\n * @return {boolean} True if the marker was added.\n * @ignore\n */\nCluster.prototype.addMarker = function (marker) {\n var i;\n var mCount;\n var mz;\n\n if (this.isMarkerAlreadyAdded_(marker)) {\n return false;\n }\n\n if (!this.center_) {\n this.center_ = marker.getPosition();\n this.calculateBounds_();\n } else {\n if (this.averageCenter_) {\n var l = this.markers_.length + 1;\n var lat = (this.center_.lat() * (l - 1) + marker.getPosition().lat()) / l;\n var lng = (this.center_.lng() * (l - 1) + marker.getPosition().lng()) / l;\n this.center_ = new google.maps.LatLng(lat, lng);\n this.calculateBounds_();\n }\n }\n\n marker.isAdded = true;\n this.markers_.push(marker);\n\n mCount = this.markers_.length;\n mz = this.markerClusterer_.getMaxZoom();\n if (mz !== null && this.map_.getZoom() > mz) {\n // Zoomed in past max zoom, so show the marker.\n if (marker.getMap() !== this.map_) {\n marker.setMap(this.map_);\n }\n } else if (mCount < this.minClusterSize_) {\n // Min cluster size not reached so show the marker.\n if (marker.getMap() !== this.map_) {\n marker.setMap(this.map_);\n }\n } else if (mCount === this.minClusterSize_) {\n // Hide the markers that were showing.\n for (i = 0; i < mCount; i++) {\n this.markers_[i].setMap(null);\n }\n } else {\n marker.setMap(null);\n }\n\n this.updateIcon_();\n return true;\n};\n\n\n/**\n * Determines if a marker lies within the cluster's bounds.\n *\n * @param {google.maps.Marker} marker The marker to check.\n * @return {boolean} True if the marker lies in the bounds.\n * @ignore\n */\nCluster.prototype.isMarkerInClusterBounds = function (marker) {\n return this.bounds_.contains(marker.getPosition());\n};\n\n\n/**\n * Calculates the extended bounds of the cluster with the grid.\n */\nCluster.prototype.calculateBounds_ = function () {\n var bounds = new google.maps.LatLngBounds(this.center_, this.center_);\n this.bounds_ = this.markerClusterer_.getExtendedBounds(bounds);\n};\n\n\n/**\n * Updates the cluster icon.\n */\nCluster.prototype.updateIcon_ = function () {\n var mCount = this.markers_.length;\n var mz = this.markerClusterer_.getMaxZoom();\n\n if (mz !== null && this.map_.getZoom() > mz) {\n this.clusterIcon_.hide();\n return;\n }\n\n if (mCount < this.minClusterSize_) {\n // Min cluster size not yet reached.\n this.clusterIcon_.hide();\n return;\n }\n\n var numStyles = this.markerClusterer_.getStyles().length;\n var sums = this.markerClusterer_.getCalculator()(this.markers_, numStyles);\n this.clusterIcon_.setCenter(this.center_);\n this.clusterIcon_.useStyle(sums);\n this.clusterIcon_.show();\n};\n\n\n/**\n * Determines if a marker has already been added to the cluster.\n *\n * @param {google.maps.Marker} marker The marker to check.\n * @return {boolean} True if the marker has already been added.\n */\nCluster.prototype.isMarkerAlreadyAdded_ = function (marker) {\n var i;\n if (this.markers_.indexOf) {\n return this.markers_.indexOf(marker) !== -1;\n } else {\n for (i = 0; i < this.markers_.length; i++) {\n if (marker === this.markers_[i]) {\n return true;\n }\n }\n }\n return false;\n};\n\n\n/**\n * @name MarkerClustererOptions\n * @class This class represents the optional parameter passed to\n * the {@link MarkerClusterer} constructor.\n * @property {number} [gridSize=60] The grid size of a cluster in pixels. The grid is a square.\n * @property {number} [maxZoom=null] The maximum zoom level at which clustering is enabled or\n * null if clustering is to be enabled at all zoom levels.\n * @property {boolean} [zoomOnClick=true] Whether to zoom the map when a cluster marker is\n * clicked. You may want to set this to false if you have installed a handler\n * for the click event and it deals with zooming on its own.\n * @property {boolean} [averageCenter=false] Whether the position of a cluster marker should be\n * the average position of all markers in the cluster. If set to false, the\n * cluster marker is positioned at the location of the first marker added to the cluster.\n * @property {number} [minimumClusterSize=2] The minimum number of markers needed in a cluster\n * before the markers are hidden and a cluster marker appears.\n * @property {boolean} [ignoreHidden=false] Whether to ignore hidden markers in clusters. You\n * may want to set this to true to ensure that hidden markers are not included\n * in the marker count that appears on a cluster marker (this count is the value of the\n * text property of the result returned by the default calculator).\n * If set to true and you change the visibility of a marker being clustered, be\n * sure to also call MarkerClusterer.repaint().\n * @property {string} [title=\"\"] The tooltip to display when the mouse moves over a cluster\n * marker. (Alternatively, you can use a custom calculator function to specify a\n * different tooltip for each cluster marker.)\n * @property {function} [calculator=MarkerClusterer.CALCULATOR] The function used to determine\n * the text to be displayed on a cluster marker and the index indicating which style to use\n * for the cluster marker. The input parameters for the function are (1) the array of markers\n * represented by a cluster marker and (2) the number of cluster icon styles. It returns a\n * {@link ClusterIconInfo} object. The default calculator returns a\n * text property which is the number of markers in the cluster and an\n * index property which is one higher than the lowest integer such that\n * 10^i exceeds the number of markers in the cluster, or the size of the styles\n * array, whichever is less. The styles array element used has an index of\n * index minus 1. For example, the default calculator returns a\n * text value of \"125\" and an index of 3\n * for a cluster icon representing 125 markers so the element used in the styles\n * array is 2. A calculator may also return a title\n * property that contains the text of the tooltip to be used for the cluster marker. If\n * title is not defined, the tooltip is set to the value of the title\n * property for the MarkerClusterer.\n * @property {string} [clusterClass=\"cluster\"] The name of the CSS class defining general styles\n * for the cluster markers. Use this class to define CSS styles that are not set up by the code\n * that processes the styles array.\n * @property {Array} [styles] An array of {@link ClusterIconStyle} elements defining the styles\n * of the cluster markers to be used. The element to be used to style a given cluster marker\n * is determined by the function defined by the calculator property.\n * The default is an array of {@link ClusterIconStyle} elements whose properties are derived\n * from the values for imagePath, imageExtension, and\n * imageSizes.\n * @property {boolean} [enableRetinaIcons=false] Whether to allow the use of cluster icons that\n * have sizes that are some multiple (typically double) of their actual display size. Icons such\n * as these look better when viewed on high-resolution monitors such as Apple's Retina displays.\n * Note: if this property is true, sprites cannot be used as cluster icons.\n * @property {number} [batchSize=MarkerClusterer.BATCH_SIZE] Set this property to the\n * number of markers to be processed in a single batch when using a browser other than\n * Internet Explorer (for Internet Explorer, use the batchSizeIE property instead).\n * @property {number} [batchSizeIE=MarkerClusterer.BATCH_SIZE_IE] When Internet Explorer is\n * being used, markers are processed in several batches with a small delay inserted between\n * each batch in an attempt to avoid Javascript timeout errors. Set this property to the\n * number of markers to be processed in a single batch; select as high a number as you can\n * without causing a timeout error in the browser. This number might need to be as low as 100\n * if 15,000 markers are being managed, for example.\n * @property {string} [imagePath=MarkerClusterer.IMAGE_PATH]\n * The full URL of the root name of the group of image files to use for cluster icons.\n * The complete file name is of the form imagePathn.imageExtension\n * where n is the image file number (1, 2, etc.).\n * @property {string} [imageExtension=MarkerClusterer.IMAGE_EXTENSION]\n * The extension name for the cluster icon image files (e.g., \"png\" or\n * \"jpg\").\n * @property {Array} [imageSizes=MarkerClusterer.IMAGE_SIZES]\n * An array of numbers containing the widths of the group of\n * imagePathn.imageExtension image files.\n * (The images are assumed to be square.)\n */\n/**\n * Creates a MarkerClusterer object with the options specified in {@link MarkerClustererOptions}.\n * @constructor\n * @extends google.maps.OverlayView\n * @param {google.maps.Map} map The Google map to attach to.\n * @param {Array.} [opt_markers] The markers to be added to the cluster.\n * @param {MarkerClustererOptions} [opt_options] The optional parameters.\n */\nfunction MarkerClusterer(map, opt_markers, opt_options) {\n // MarkerClusterer implements google.maps.OverlayView interface. We use the\n // extend function to extend MarkerClusterer with google.maps.OverlayView\n // because it might not always be available when the code is defined so we\n // look for it at the last possible moment. If it doesn't exist now then\n // there is no point going ahead :)\n this.extend(MarkerClusterer, google.maps.OverlayView);\n\n opt_markers = opt_markers || [];\n opt_options = opt_options || {};\n\n this.markers_ = [];\n this.clusters_ = [];\n this.listeners_ = [];\n this.activeMap_ = null;\n this.ready_ = false;\n\n this.gridSize_ = opt_options.gridSize || 60;\n this.minClusterSize_ = opt_options.minimumClusterSize || 2;\n this.maxZoom_ = opt_options.maxZoom || null;\n this.styles_ = opt_options.styles || [];\n this.title_ = opt_options.title || \"\";\n this.zoomOnClick_ = true;\n if (opt_options.zoomOnClick !== undefined) {\n this.zoomOnClick_ = opt_options.zoomOnClick;\n }\n this.averageCenter_ = false;\n if (opt_options.averageCenter !== undefined) {\n this.averageCenter_ = opt_options.averageCenter;\n }\n this.ignoreHidden_ = false;\n if (opt_options.ignoreHidden !== undefined) {\n this.ignoreHidden_ = opt_options.ignoreHidden;\n }\n this.enableRetinaIcons_ = false;\n if (opt_options.enableRetinaIcons !== undefined) {\n this.enableRetinaIcons_ = opt_options.enableRetinaIcons;\n }\n this.imagePath_ = opt_options.imagePath || MarkerClusterer.IMAGE_PATH;\n this.imageExtension_ = opt_options.imageExtension || MarkerClusterer.IMAGE_EXTENSION;\n this.imageSizes_ = opt_options.imageSizes || MarkerClusterer.IMAGE_SIZES;\n this.calculator_ = opt_options.calculator || MarkerClusterer.CALCULATOR;\n this.batchSize_ = opt_options.batchSize || MarkerClusterer.BATCH_SIZE;\n this.batchSizeIE_ = opt_options.batchSizeIE || MarkerClusterer.BATCH_SIZE_IE;\n this.clusterClass_ = opt_options.clusterClass || \"cluster\";\n\n if (navigator.userAgent.toLowerCase().indexOf(\"msie\") !== -1) {\n // Try to avoid IE timeout when processing a huge number of markers:\n this.batchSize_ = this.batchSizeIE_;\n }\n\n this.setupStyles_();\n\n this.addMarkers(opt_markers, true);\n this.setMap(map); // Note: this causes onAdd to be called\n}\n\n\n/**\n * Implementation of the onAdd interface method.\n * @ignore\n */\nMarkerClusterer.prototype.onAdd = function () {\n var cMarkerClusterer = this;\n\n this.activeMap_ = this.getMap();\n this.ready_ = true;\n\n this.repaint();\n\n // Add the map event listeners\n this.listeners_ = [\n google.maps.event.addListener(this.getMap(), \"zoom_changed\", function () {\n cMarkerClusterer.resetViewport_(false);\n // Workaround for this Google bug: when map is at level 0 and \"-\" of\n // zoom slider is clicked, a \"zoom_changed\" event is fired even though\n // the map doesn't zoom out any further. In this situation, no \"idle\"\n // event is triggered so the cluster markers that have been removed\n // do not get redrawn. Same goes for a zoom in at maxZoom.\n if (this.getZoom() === (this.get(\"minZoom\") || 0) || this.getZoom() === this.get(\"maxZoom\")) {\n google.maps.event.trigger(this, \"idle\");\n }\n }),\n google.maps.event.addListener(this.getMap(), \"idle\", function () {\n cMarkerClusterer.redraw_();\n })\n ];\n};\n\n\n/**\n * Implementation of the onRemove interface method.\n * Removes map event listeners and all cluster icons from the DOM.\n * All managed markers are also put back on the map.\n * @ignore\n */\nMarkerClusterer.prototype.onRemove = function () {\n var i;\n\n // Put all the managed markers back on the map:\n for (i = 0; i < this.markers_.length; i++) {\n if (this.markers_[i].getMap() !== this.activeMap_) {\n this.markers_[i].setMap(this.activeMap_);\n }\n }\n\n // Remove all clusters:\n for (i = 0; i < this.clusters_.length; i++) {\n this.clusters_[i].remove();\n }\n this.clusters_ = [];\n\n // Remove map event listeners:\n for (i = 0; i < this.listeners_.length; i++) {\n google.maps.event.removeListener(this.listeners_[i]);\n }\n this.listeners_ = [];\n\n this.activeMap_ = null;\n this.ready_ = false;\n};\n\n\n/**\n * Implementation of the draw interface method.\n * @ignore\n */\nMarkerClusterer.prototype.draw = function () {};\n\n\n/**\n * Sets up the styles object.\n */\nMarkerClusterer.prototype.setupStyles_ = function () {\n var i, size;\n if (this.styles_.length > 0) {\n return;\n }\n\n for (i = 0; i < this.imageSizes_.length; i++) {\n size = this.imageSizes_[i];\n this.styles_.push({\n url: this.imagePath_ + (i + 1) + \".\" + this.imageExtension_,\n height: size,\n width: size\n });\n }\n};\n\n\n/**\n * Fits the map to the bounds of the markers managed by the clusterer.\n */\nMarkerClusterer.prototype.fitMapToMarkers = function () {\n var i;\n var markers = this.getMarkers();\n var bounds = new google.maps.LatLngBounds();\n for (i = 0; i < markers.length; i++) {\n bounds.extend(markers[i].getPosition());\n }\n\n this.getMap().fitBounds(bounds);\n};\n\n\n/**\n * Returns the value of the gridSize property.\n *\n * @return {number} The grid size.\n */\nMarkerClusterer.prototype.getGridSize = function () {\n return this.gridSize_;\n};\n\n\n/**\n * Sets the value of the gridSize property.\n *\n * @param {number} gridSize The grid size.\n */\nMarkerClusterer.prototype.setGridSize = function (gridSize) {\n this.gridSize_ = gridSize;\n};\n\n\n/**\n * Returns the value of the minimumClusterSize property.\n *\n * @return {number} The minimum cluster size.\n */\nMarkerClusterer.prototype.getMinimumClusterSize = function () {\n return this.minClusterSize_;\n};\n\n/**\n * Sets the value of the minimumClusterSize property.\n *\n * @param {number} minimumClusterSize The minimum cluster size.\n */\nMarkerClusterer.prototype.setMinimumClusterSize = function (minimumClusterSize) {\n this.minClusterSize_ = minimumClusterSize;\n};\n\n\n/**\n * Returns the value of the maxZoom property.\n *\n * @return {number} The maximum zoom level.\n */\nMarkerClusterer.prototype.getMaxZoom = function () {\n return this.maxZoom_;\n};\n\n\n/**\n * Sets the value of the maxZoom property.\n *\n * @param {number} maxZoom The maximum zoom level.\n */\nMarkerClusterer.prototype.setMaxZoom = function (maxZoom) {\n this.maxZoom_ = maxZoom;\n};\n\n\n/**\n * Returns the value of the styles property.\n *\n * @return {Array} The array of styles defining the cluster markers to be used.\n */\nMarkerClusterer.prototype.getStyles = function () {\n return this.styles_;\n};\n\n\n/**\n * Sets the value of the styles property.\n *\n * @param {Array.} styles The array of styles to use.\n */\nMarkerClusterer.prototype.setStyles = function (styles) {\n this.styles_ = styles;\n};\n\n\n/**\n * Returns the value of the title property.\n *\n * @return {string} The content of the title text.\n */\nMarkerClusterer.prototype.getTitle = function () {\n return this.title_;\n};\n\n\n/**\n * Sets the value of the title property.\n *\n * @param {string} title The value of the title property.\n */\nMarkerClusterer.prototype.setTitle = function (title) {\n this.title_ = title;\n};\n\n\n/**\n * Returns the value of the zoomOnClick property.\n *\n * @return {boolean} True if zoomOnClick property is set.\n */\nMarkerClusterer.prototype.getZoomOnClick = function () {\n return this.zoomOnClick_;\n};\n\n\n/**\n * Sets the value of the zoomOnClick property.\n *\n * @param {boolean} zoomOnClick The value of the zoomOnClick property.\n */\nMarkerClusterer.prototype.setZoomOnClick = function (zoomOnClick) {\n this.zoomOnClick_ = zoomOnClick;\n};\n\n\n/**\n * Returns the value of the averageCenter property.\n *\n * @return {boolean} True if averageCenter property is set.\n */\nMarkerClusterer.prototype.getAverageCenter = function () {\n return this.averageCenter_;\n};\n\n\n/**\n * Sets the value of the averageCenter property.\n *\n * @param {boolean} averageCenter The value of the averageCenter property.\n */\nMarkerClusterer.prototype.setAverageCenter = function (averageCenter) {\n this.averageCenter_ = averageCenter;\n};\n\n\n/**\n * Returns the value of the ignoreHidden property.\n *\n * @return {boolean} True if ignoreHidden property is set.\n */\nMarkerClusterer.prototype.getIgnoreHidden = function () {\n return this.ignoreHidden_;\n};\n\n\n/**\n * Sets the value of the ignoreHidden property.\n *\n * @param {boolean} ignoreHidden The value of the ignoreHidden property.\n */\nMarkerClusterer.prototype.setIgnoreHidden = function (ignoreHidden) {\n this.ignoreHidden_ = ignoreHidden;\n};\n\n\n/**\n * Returns the value of the enableRetinaIcons property.\n *\n * @return {boolean} True if enableRetinaIcons property is set.\n */\nMarkerClusterer.prototype.getEnableRetinaIcons = function () {\n return this.enableRetinaIcons_;\n};\n\n\n/**\n * Sets the value of the enableRetinaIcons property.\n *\n * @param {boolean} enableRetinaIcons The value of the enableRetinaIcons property.\n */\nMarkerClusterer.prototype.setEnableRetinaIcons = function (enableRetinaIcons) {\n this.enableRetinaIcons_ = enableRetinaIcons;\n};\n\n\n/**\n * Returns the value of the imageExtension property.\n *\n * @return {string} The value of the imageExtension property.\n */\nMarkerClusterer.prototype.getImageExtension = function () {\n return this.imageExtension_;\n};\n\n\n/**\n * Sets the value of the imageExtension property.\n *\n * @param {string} imageExtension The value of the imageExtension property.\n */\nMarkerClusterer.prototype.setImageExtension = function (imageExtension) {\n this.imageExtension_ = imageExtension;\n};\n\n\n/**\n * Returns the value of the imagePath property.\n *\n * @return {string} The value of the imagePath property.\n */\nMarkerClusterer.prototype.getImagePath = function () {\n return this.imagePath_;\n};\n\n\n/**\n * Sets the value of the imagePath property.\n *\n * @param {string} imagePath The value of the imagePath property.\n */\nMarkerClusterer.prototype.setImagePath = function (imagePath) {\n this.imagePath_ = imagePath;\n};\n\n\n/**\n * Returns the value of the imageSizes property.\n *\n * @return {Array} The value of the imageSizes property.\n */\nMarkerClusterer.prototype.getImageSizes = function () {\n return this.imageSizes_;\n};\n\n\n/**\n * Sets the value of the imageSizes property.\n *\n * @param {Array} imageSizes The value of the imageSizes property.\n */\nMarkerClusterer.prototype.setImageSizes = function (imageSizes) {\n this.imageSizes_ = imageSizes;\n};\n\n\n/**\n * Returns the value of the calculator property.\n *\n * @return {function} the value of the calculator property.\n */\nMarkerClusterer.prototype.getCalculator = function () {\n return this.calculator_;\n};\n\n\n/**\n * Sets the value of the calculator property.\n *\n * @param {function(Array., number)} calculator The value\n * of the calculator property.\n */\nMarkerClusterer.prototype.setCalculator = function (calculator) {\n this.calculator_ = calculator;\n};\n\n\n/**\n * Returns the value of the batchSizeIE property.\n *\n * @return {number} the value of the batchSizeIE property.\n */\nMarkerClusterer.prototype.getBatchSizeIE = function () {\n return this.batchSizeIE_;\n};\n\n\n/**\n * Sets the value of the batchSizeIE property.\n *\n * @param {number} batchSizeIE The value of the batchSizeIE property.\n */\nMarkerClusterer.prototype.setBatchSizeIE = function (batchSizeIE) {\n this.batchSizeIE_ = batchSizeIE;\n};\n\n\n/**\n * Returns the value of the clusterClass property.\n *\n * @return {string} the value of the clusterClass property.\n */\nMarkerClusterer.prototype.getClusterClass = function () {\n return this.clusterClass_;\n};\n\n\n/**\n * Sets the value of the clusterClass property.\n *\n * @param {string} clusterClass The value of the clusterClass property.\n */\nMarkerClusterer.prototype.setClusterClass = function (clusterClass) {\n this.clusterClass_ = clusterClass;\n};\n\n\n/**\n * Returns the array of markers managed by the clusterer.\n *\n * @return {Array} The array of markers managed by the clusterer.\n */\nMarkerClusterer.prototype.getMarkers = function () {\n return this.markers_;\n};\n\n\n/**\n * Returns the number of markers managed by the clusterer.\n *\n * @return {number} The number of markers.\n */\nMarkerClusterer.prototype.getTotalMarkers = function () {\n return this.markers_.length;\n};\n\n\n/**\n * Returns the current array of clusters formed by the clusterer.\n *\n * @return {Array} The array of clusters formed by the clusterer.\n */\nMarkerClusterer.prototype.getClusters = function () {\n return this.clusters_;\n};\n\n\n/**\n * Returns the number of clusters formed by the clusterer.\n *\n * @return {number} The number of clusters formed by the clusterer.\n */\nMarkerClusterer.prototype.getTotalClusters = function () {\n return this.clusters_.length;\n};\n\n\n/**\n * Adds a marker to the clusterer. The clusters are redrawn unless\n * opt_nodraw is set to true.\n *\n * @param {google.maps.Marker} marker The marker to add.\n * @param {boolean} [opt_nodraw] Set to true to prevent redrawing.\n */\nMarkerClusterer.prototype.addMarker = function (marker, opt_nodraw) {\n this.pushMarkerTo_(marker);\n if (!opt_nodraw) {\n this.redraw_();\n }\n};\n\n\n/**\n * Adds an array of markers to the clusterer. The clusters are redrawn unless\n * opt_nodraw is set to true.\n *\n * @param {Array.} markers The markers to add.\n * @param {boolean} [opt_nodraw] Set to true to prevent redrawing.\n */\nMarkerClusterer.prototype.addMarkers = function (markers, opt_nodraw) {\n var key;\n for (key in markers) {\n if (markers.hasOwnProperty(key)) {\n this.pushMarkerTo_(markers[key]);\n }\n } \n if (!opt_nodraw) {\n this.redraw_();\n }\n};\n\n\n/**\n * Pushes a marker to the clusterer.\n *\n * @param {google.maps.Marker} marker The marker to add.\n */\nMarkerClusterer.prototype.pushMarkerTo_ = function (marker) {\n // If the marker is draggable add a listener so we can update the clusters on the dragend:\n if (marker.getDraggable()) {\n var cMarkerClusterer = this;\n google.maps.event.addListener(marker, \"dragend\", function () {\n if (cMarkerClusterer.ready_) {\n this.isAdded = false;\n cMarkerClusterer.repaint();\n }\n });\n }\n marker.isAdded = false;\n this.markers_.push(marker);\n};\n\n\n/**\n * Removes a marker from the cluster. The clusters are redrawn unless\n * opt_nodraw is set to true. Returns true if the\n * marker was removed from the clusterer.\n *\n * @param {google.maps.Marker} marker The marker to remove.\n * @param {boolean} [opt_nodraw] Set to true to prevent redrawing.\n * @return {boolean} True if the marker was removed from the clusterer.\n */\nMarkerClusterer.prototype.removeMarker = function (marker, opt_nodraw) {\n var removed = this.removeMarker_(marker);\n\n if (!opt_nodraw && removed) {\n this.repaint();\n }\n\n return removed;\n};\n\n\n/**\n * Removes an array of markers from the cluster. The clusters are redrawn unless\n * opt_nodraw is set to true. Returns true if markers\n * were removed from the clusterer.\n *\n * @param {Array.} markers The markers to remove.\n * @param {boolean} [opt_nodraw] Set to true to prevent redrawing.\n * @return {boolean} True if markers were removed from the clusterer.\n */\nMarkerClusterer.prototype.removeMarkers = function (markers, opt_nodraw) {\n var i, r;\n var removed = false;\n\n for (i = 0; i < markers.length; i++) {\n r = this.removeMarker_(markers[i]);\n removed = removed || r;\n }\n\n if (!opt_nodraw && removed) {\n this.repaint();\n }\n\n return removed;\n};\n\n\n/**\n * Removes a marker and returns true if removed, false if not.\n *\n * @param {google.maps.Marker} marker The marker to remove\n * @return {boolean} Whether the marker was removed or not\n */\nMarkerClusterer.prototype.removeMarker_ = function (marker) {\n var i;\n var index = -1;\n if (this.markers_.indexOf) {\n index = this.markers_.indexOf(marker);\n } else {\n for (i = 0; i < this.markers_.length; i++) {\n if (marker === this.markers_[i]) {\n index = i;\n break;\n }\n }\n }\n\n if (index === -1) {\n // Marker is not in our list of markers, so do nothing:\n return false;\n }\n\n marker.setMap(null);\n this.markers_.splice(index, 1); // Remove the marker from the list of managed markers\n return true;\n};\n\n\n/**\n * Removes all clusters and markers from the map and also removes all markers\n * managed by the clusterer.\n */\nMarkerClusterer.prototype.clearMarkers = function () {\n this.resetViewport_(true);\n this.markers_ = [];\n};\n\n\n/**\n * Recalculates and redraws all the marker clusters from scratch.\n * Call this after changing any properties.\n */\nMarkerClusterer.prototype.repaint = function () {\n var oldClusters = this.clusters_.slice();\n this.clusters_ = [];\n this.resetViewport_(false);\n this.redraw_();\n\n // Remove the old clusters.\n // Do it in a timeout to prevent blinking effect.\n setTimeout(function () {\n var i;\n for (i = 0; i < oldClusters.length; i++) {\n oldClusters[i].remove();\n }\n }, 0);\n};\n\n\n/**\n * Returns the current bounds extended by the grid size.\n *\n * @param {google.maps.LatLngBounds} bounds The bounds to extend.\n * @return {google.maps.LatLngBounds} The extended bounds.\n * @ignore\n */\nMarkerClusterer.prototype.getExtendedBounds = function (bounds) {\n var projection = this.getProjection();\n\n // Turn the bounds into latlng.\n var tr = new google.maps.LatLng(bounds.getNorthEast().lat(),\n bounds.getNorthEast().lng());\n var bl = new google.maps.LatLng(bounds.getSouthWest().lat(),\n bounds.getSouthWest().lng());\n\n // Convert the points to pixels and the extend out by the grid size.\n var trPix = projection.fromLatLngToDivPixel(tr);\n trPix.x += this.gridSize_;\n trPix.y -= this.gridSize_;\n\n var blPix = projection.fromLatLngToDivPixel(bl);\n blPix.x -= this.gridSize_;\n blPix.y += this.gridSize_;\n\n // Convert the pixel points back to LatLng\n var ne = projection.fromDivPixelToLatLng(trPix);\n var sw = projection.fromDivPixelToLatLng(blPix);\n\n // Extend the bounds to contain the new bounds.\n bounds.extend(ne);\n bounds.extend(sw);\n\n return bounds;\n};\n\n\n/**\n * Redraws all the clusters.\n */\nMarkerClusterer.prototype.redraw_ = function () {\n this.createClusters_(0);\n};\n\n\n/**\n * Removes all clusters from the map. The markers are also removed from the map\n * if opt_hide is set to true.\n *\n * @param {boolean} [opt_hide] Set to true to also remove the markers\n * from the map.\n */\nMarkerClusterer.prototype.resetViewport_ = function (opt_hide) {\n var i, marker;\n // Remove all the clusters\n for (i = 0; i < this.clusters_.length; i++) {\n this.clusters_[i].remove();\n }\n this.clusters_ = [];\n\n // Reset the markers to not be added and to be removed from the map.\n for (i = 0; i < this.markers_.length; i++) {\n marker = this.markers_[i];\n marker.isAdded = false;\n if (opt_hide) {\n marker.setMap(null);\n }\n }\n};\n\n\n/**\n * Calculates the distance between two latlng locations in km.\n *\n * @param {google.maps.LatLng} p1 The first lat lng point.\n * @param {google.maps.LatLng} p2 The second lat lng point.\n * @return {number} The distance between the two points in km.\n * @see http://www.movable-type.co.uk/scripts/latlong.html\n*/\nMarkerClusterer.prototype.distanceBetweenPoints_ = function (p1, p2) {\n var R = 6371; // Radius of the Earth in km\n var dLat = (p2.lat() - p1.lat()) * Math.PI / 180;\n var dLon = (p2.lng() - p1.lng()) * Math.PI / 180;\n var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +\n Math.cos(p1.lat() * Math.PI / 180) * Math.cos(p2.lat() * Math.PI / 180) *\n Math.sin(dLon / 2) * Math.sin(dLon / 2);\n var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n var d = R * c;\n return d;\n};\n\n\n/**\n * Determines if a marker is contained in a bounds.\n *\n * @param {google.maps.Marker} marker The marker to check.\n * @param {google.maps.LatLngBounds} bounds The bounds to check against.\n * @return {boolean} True if the marker is in the bounds.\n */\nMarkerClusterer.prototype.isMarkerInBounds_ = function (marker, bounds) {\n return bounds.contains(marker.getPosition());\n};\n\n\n/**\n * Adds a marker to a cluster, or creates a new cluster.\n *\n * @param {google.maps.Marker} marker The marker to add.\n */\nMarkerClusterer.prototype.addToClosestCluster_ = function (marker) {\n var i, d, cluster, center;\n var distance = 40000; // Some large number\n var clusterToAddTo = null;\n for (i = 0; i < this.clusters_.length; i++) {\n cluster = this.clusters_[i];\n center = cluster.getCenter();\n if (center) {\n d = this.distanceBetweenPoints_(center, marker.getPosition());\n if (d < distance) {\n distance = d;\n clusterToAddTo = cluster;\n }\n }\n }\n\n if (clusterToAddTo && clusterToAddTo.isMarkerInClusterBounds(marker)) {\n clusterToAddTo.addMarker(marker);\n } else {\n cluster = new Cluster(this);\n cluster.addMarker(marker);\n this.clusters_.push(cluster);\n }\n};\n\n\n/**\n * Creates the clusters. This is done in batches to avoid timeout errors\n * in some browsers when there is a huge number of markers.\n *\n * @param {number} iFirst The index of the first marker in the batch of\n * markers to be added to clusters.\n */\nMarkerClusterer.prototype.createClusters_ = function (iFirst) {\n var i, marker;\n var mapBounds;\n var cMarkerClusterer = this;\n if (!this.ready_) {\n return;\n }\n\n // Cancel previous batch processing if we're working on the first batch:\n if (iFirst === 0) {\n /**\n * This event is fired when the MarkerClusterer begins\n * clustering markers.\n * @name MarkerClusterer#clusteringbegin\n * @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered.\n * @event\n */\n google.maps.event.trigger(this, \"clusteringbegin\", this);\n\n if (typeof this.timerRefStatic !== \"undefined\") {\n clearTimeout(this.timerRefStatic);\n delete this.timerRefStatic;\n }\n }\n\n // Get our current map view bounds.\n // Create a new bounds object so we don't affect the map.\n //\n // See Comments 9 & 11 on Issue 3651 relating to this workaround for a Google Maps bug:\n if (this.getMap().getZoom() > 3) {\n mapBounds = new google.maps.LatLngBounds(this.getMap().getBounds().getSouthWest(),\n this.getMap().getBounds().getNorthEast());\n } else {\n mapBounds = new google.maps.LatLngBounds(new google.maps.LatLng(85.02070771743472, -178.48388434375), new google.maps.LatLng(-85.08136444384544, 178.00048865625));\n }\n var bounds = this.getExtendedBounds(mapBounds);\n\n var iLast = Math.min(iFirst + this.batchSize_, this.markers_.length);\n\n for (i = iFirst; i < iLast; i++) {\n marker = this.markers_[i];\n if (!marker.isAdded && this.isMarkerInBounds_(marker, bounds)) {\n if (!this.ignoreHidden_ || (this.ignoreHidden_ && marker.getVisible())) {\n this.addToClosestCluster_(marker);\n }\n }\n }\n\n if (iLast < this.markers_.length) {\n this.timerRefStatic = setTimeout(function () {\n cMarkerClusterer.createClusters_(iLast);\n }, 0);\n } else {\n delete this.timerRefStatic;\n\n /**\n * This event is fired when the MarkerClusterer stops\n * clustering markers.\n * @name MarkerClusterer#clusteringend\n * @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered.\n * @event\n */\n google.maps.event.trigger(this, \"clusteringend\", this);\n }\n};\n\n\n/**\n * Extends an object's prototype by another's.\n *\n * @param {Object} obj1 The object to be extended.\n * @param {Object} obj2 The object to extend with.\n * @return {Object} The new extended object.\n * @ignore\n */\nMarkerClusterer.prototype.extend = function (obj1, obj2) {\n return (function (object) {\n var property;\n for (property in object.prototype) {\n this.prototype[property] = object.prototype[property];\n }\n return this;\n }).apply(obj1, [obj2]);\n};\n\n\n/**\n * The default function for determining the label text and style\n * for a cluster icon.\n *\n * @param {Array.} markers The array of markers represented by the cluster.\n * @param {number} numStyles The number of marker styles available.\n * @return {ClusterIconInfo} The information resource for the cluster.\n * @constant\n * @ignore\n */\nMarkerClusterer.CALCULATOR = function (markers, numStyles) {\n var index = 0;\n var title = \"\";\n var count = markers.length.toString();\n\n var dv = count;\n while (dv !== 0) {\n dv = parseInt(dv / 10, 10);\n index++;\n }\n\n index = Math.min(index, numStyles);\n return {\n text: count,\n index: index,\n title: title\n };\n};\n\n\n/**\n * The number of markers to process in one batch.\n *\n * @type {number}\n * @constant\n */\nMarkerClusterer.BATCH_SIZE = 2000;\n\n\n/**\n * The number of markers to process in one batch (IE only).\n *\n * @type {number}\n * @constant\n */\nMarkerClusterer.BATCH_SIZE_IE = 500;\n\n\n/**\n * The default root name for the marker cluster images.\n *\n * @type {string}\n * @constant\n */\nMarkerClusterer.IMAGE_PATH = \"http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclustererplus/images/m\";\n\n\n/**\n * The default extension name for the marker cluster images.\n *\n * @type {string}\n * @constant\n */\nMarkerClusterer.IMAGE_EXTENSION = \"png\";\n\n\n/**\n * The default array of sizes for the marker cluster images.\n *\n * @type {Array.}\n * @constant\n */\nMarkerClusterer.IMAGE_SIZES = [53, 56, 66, 78, 90];\n"},"new_file":{"kind":"string","value":"markerclustererplus/src/markerclusterer.js"},"old_contents":{"kind":"string","value":"/**\n * @name MarkerClustererPlus for Google Maps V3\n * @version 2.1.2 [May 28, 2014]\n * @author Gary Little\n * @fileoverview\n * The library creates and manages per-zoom-level clusters for large amounts of markers.\n *

\n * This is an enhanced V3 implementation of the\n * V2 MarkerClusterer by Xiaoxi Wu. It is based on the\n * V3 MarkerClusterer port by Luke Mahe. MarkerClustererPlus was created by Gary Little.\n *

\n * v2.0 release: MarkerClustererPlus v2.0 is backward compatible with MarkerClusterer v1.0. It\n * adds support for the ignoreHidden, title, batchSizeIE,\n * and calculator properties as well as support for four more events. It also allows\n * greater control over the styling of the text that appears on the cluster marker. The\n * documentation has been significantly improved and the overall code has been simplified and\n * polished. Very large numbers of markers can now be managed without causing Javascript timeout\n * errors on Internet Explorer. Note that the name of the clusterclick event has been\n * deprecated. The new name is click, so please change your application code now.\n */\n\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\n\n/**\n * @name ClusterIconStyle\n * @class This class represents the object for values in the styles array passed\n * to the {@link MarkerClusterer} constructor. The element in this array that is used to\n * style the cluster icon is determined by calling the calculator function.\n *\n * @property {string} url The URL of the cluster icon image file. Required.\n * @property {number} height The display height (in pixels) of the cluster icon. Required.\n * @property {number} width The display width (in pixels) of the cluster icon. Required.\n * @property {Array} [anchorText] The position (in pixels) from the center of the cluster icon to\n * where the text label is to be centered and drawn. The format is [yoffset, xoffset]\n * where yoffset increases as you go down from center and xoffset\n * increases to the right of center. The default is [0, 0].\n * @property {Array} [anchorIcon] The anchor position (in pixels) of the cluster icon. This is the\n * spot on the cluster icon that is to be aligned with the cluster position. The format is\n * [yoffset, xoffset] where yoffset increases as you go down and\n * xoffset increases to the right of the top-left corner of the icon. The default\n * anchor position is the center of the cluster icon.\n * @property {string} [textColor=\"black\"] The color of the label text shown on the\n * cluster icon.\n * @property {number} [textSize=11] The size (in pixels) of the label text shown on the\n * cluster icon.\n * @property {string} [textDecoration=\"none\"] The value of the CSS text-decoration\n * property for the label text shown on the cluster icon.\n * @property {string} [fontWeight=\"bold\"] The value of the CSS font-weight\n * property for the label text shown on the cluster icon.\n * @property {string} [fontStyle=\"normal\"] The value of the CSS font-style\n * property for the label text shown on the cluster icon.\n * @property {string} [fontFamily=\"Arial,sans-serif\"] The value of the CSS font-family\n * property for the label text shown on the cluster icon.\n * @property {string} [backgroundPosition=\"0 0\"] The position of the cluster icon image\n * within the image defined by url. The format is \"xpos ypos\"\n * (the same format as for the CSS background-position property). You must set\n * this property appropriately when the image defined by url represents a sprite\n * containing multiple images. Note that the position must be specified in px units.\n */\n/**\n * @name ClusterIconInfo\n * @class This class is an object containing general information about a cluster icon. This is\n * the object that a calculator function returns.\n *\n * @property {string} text The text of the label to be shown on the cluster icon.\n * @property {number} index The index plus 1 of the element in the styles\n * array to be used to style the cluster icon.\n * @property {string} title The tooltip to display when the mouse moves over the cluster icon.\n * If this value is undefined or \"\", title is set to the\n * value of the title property passed to the MarkerClusterer.\n */\n/**\n * A cluster icon.\n *\n * @constructor\n * @extends google.maps.OverlayView\n * @param {Cluster} cluster The cluster with which the icon is to be associated.\n * @param {Array} [styles] An array of {@link ClusterIconStyle} defining the cluster icons\n * to use for various cluster sizes.\n * @private\n */\nfunction ClusterIcon(cluster, styles) {\n cluster.getMarkerClusterer().extend(ClusterIcon, google.maps.OverlayView);\n\n this.cluster_ = cluster;\n this.className_ = cluster.getMarkerClusterer().getClusterClass();\n this.styles_ = styles;\n this.center_ = null;\n this.div_ = null;\n this.sums_ = null;\n this.visible_ = false;\n\n this.setMap(cluster.getMap()); // Note: this causes onAdd to be called\n}\n\n\n/**\n * Adds the icon to the DOM.\n */\nClusterIcon.prototype.onAdd = function () {\n var cClusterIcon = this;\n var cMouseDownInCluster;\n var cDraggingMapByCluster;\n\n this.div_ = document.createElement(\"div\");\n this.div_.className = this.className_;\n if (this.visible_) {\n this.show();\n }\n\n this.getPanes().overlayMouseTarget.appendChild(this.div_);\n\n // Fix for Issue 157\n this.boundsChangedListener_ = google.maps.event.addListener(this.getMap(), \"bounds_changed\", function () {\n cDraggingMapByCluster = cMouseDownInCluster;\n });\n\n google.maps.event.addDomListener(this.div_, \"mousedown\", function () {\n cMouseDownInCluster = true;\n cDraggingMapByCluster = false;\n });\n\n google.maps.event.addDomListener(this.div_, \"click\", function (e) {\n cMouseDownInCluster = false;\n if (!cDraggingMapByCluster) {\n var theBounds;\n var mz;\n var mc = cClusterIcon.cluster_.getMarkerClusterer();\n /**\n * This event is fired when a cluster marker is clicked.\n * @name MarkerClusterer#click\n * @param {Cluster} c The cluster that was clicked.\n * @event\n */\n google.maps.event.trigger(mc, \"click\", cClusterIcon.cluster_);\n google.maps.event.trigger(mc, \"clusterclick\", cClusterIcon.cluster_); // deprecated name\n\n // The default click handler follows. Disable it by setting\n // the zoomOnClick property to false.\n if (mc.getZoomOnClick()) {\n // Zoom into the cluster.\n mz = mc.getMaxZoom();\n theBounds = cClusterIcon.cluster_.getBounds();\n mc.getMap().fitBounds(theBounds);\n // There is a fix for Issue 170 here:\n setTimeout(function () {\n mc.getMap().fitBounds(theBounds);\n // Don't zoom beyond the max zoom level\n if (mz !== null && (mc.getMap().getZoom() > mz)) {\n mc.getMap().setZoom(mz + 1);\n }\n }, 100);\n }\n\n // Prevent event propagation to the map:\n e.cancelBubble = true;\n if (e.stopPropagation) {\n e.stopPropagation();\n }\n }\n });\n\n google.maps.event.addDomListener(this.div_, \"mouseover\", function () {\n var mc = cClusterIcon.cluster_.getMarkerClusterer();\n /**\n * This event is fired when the mouse moves over a cluster marker.\n * @name MarkerClusterer#mouseover\n * @param {Cluster} c The cluster that the mouse moved over.\n * @event\n */\n google.maps.event.trigger(mc, \"mouseover\", cClusterIcon.cluster_);\n });\n\n google.maps.event.addDomListener(this.div_, \"mouseout\", function () {\n var mc = cClusterIcon.cluster_.getMarkerClusterer();\n /**\n * This event is fired when the mouse moves out of a cluster marker.\n * @name MarkerClusterer#mouseout\n * @param {Cluster} c The cluster that the mouse moved out of.\n * @event\n */\n google.maps.event.trigger(mc, \"mouseout\", cClusterIcon.cluster_);\n });\n};\n\n\n/**\n * Removes the icon from the DOM.\n */\nClusterIcon.prototype.onRemove = function () {\n if (this.div_ && this.div_.parentNode) {\n this.hide();\n google.maps.event.removeListener(this.boundsChangedListener_);\n google.maps.event.clearInstanceListeners(this.div_);\n this.div_.parentNode.removeChild(this.div_);\n this.div_ = null;\n }\n};\n\n\n/**\n * Draws the icon.\n */\nClusterIcon.prototype.draw = function () {\n if (this.visible_) {\n var pos = this.getPosFromLatLng_(this.center_);\n this.div_.style.top = pos.y + \"px\";\n this.div_.style.left = pos.x + \"px\";\n }\n};\n\n\n/**\n * Hides the icon.\n */\nClusterIcon.prototype.hide = function () {\n if (this.div_) {\n this.div_.style.display = \"none\";\n }\n this.visible_ = false;\n};\n\n\n/**\n * Positions and shows the icon.\n */\nClusterIcon.prototype.show = function () {\n if (this.div_) {\n var img = \"\";\n // NOTE: values must be specified in px units\n var bp = this.backgroundPosition_.split(\" \");\n var spriteH = parseInt(bp[0].replace(/^\\s+|\\s+$/g, \"\"), 10);\n var spriteV = parseInt(bp[1].replace(/^\\s+|\\s+$/g, \"\"), 10);\n var pos = this.getPosFromLatLng_(this.center_);\n this.div_.style.cssText = this.createCss(pos);\n img = \"\";\n this.div_.innerHTML = img + \"

\" + this.sums_.text + \"
\";\n if (typeof this.sums_.title === \"undefined\" || this.sums_.title === \"\") {\n this.div_.title = this.cluster_.getMarkerClusterer().getTitle();\n } else {\n this.div_.title = this.sums_.title;\n }\n this.div_.style.display = \"\";\n }\n this.visible_ = true;\n};\n\n\n/**\n * Sets the icon styles to the appropriate element in the styles array.\n *\n * @param {ClusterIconInfo} sums The icon label text and styles index.\n */\nClusterIcon.prototype.useStyle = function (sums) {\n this.sums_ = sums;\n var index = Math.max(0, sums.index - 1);\n index = Math.min(this.styles_.length - 1, index);\n var style = this.styles_[index];\n this.url_ = style.url;\n this.height_ = style.height;\n this.width_ = style.width;\n this.anchorText_ = style.anchorText || [0, 0];\n this.anchorIcon_ = style.anchorIcon || [parseInt(this.height_ / 2, 10), parseInt(this.width_ / 2, 10)];\n this.textColor_ = style.textColor || \"black\";\n this.textSize_ = style.textSize || 11;\n this.textDecoration_ = style.textDecoration || \"none\";\n this.fontWeight_ = style.fontWeight || \"bold\";\n this.fontStyle_ = style.fontStyle || \"normal\";\n this.fontFamily_ = style.fontFamily || \"Arial,sans-serif\";\n this.backgroundPosition_ = style.backgroundPosition || \"0 0\";\n};\n\n\n/**\n * Sets the position at which to center the icon.\n *\n * @param {google.maps.LatLng} center The latlng to set as the center.\n */\nClusterIcon.prototype.setCenter = function (center) {\n this.center_ = center;\n};\n\n\n/**\n * Creates the cssText style parameter based on the position of the icon.\n *\n * @param {google.maps.Point} pos The position of the icon.\n * @return {string} The CSS style text.\n */\nClusterIcon.prototype.createCss = function (pos) {\n var style = [];\n style.push(\"cursor: pointer;\");\n style.push(\"position: absolute; top: \" + pos.y + \"px; left: \" + pos.x + \"px;\");\n style.push(\"width: \" + this.width_ + \"px; height: \" + this.height_ + \"px;\");\n return style.join(\"\");\n};\n\n\n/**\n * Returns the position at which to place the DIV depending on the latlng.\n *\n * @param {google.maps.LatLng} latlng The position in latlng.\n * @return {google.maps.Point} The position in pixels.\n */\nClusterIcon.prototype.getPosFromLatLng_ = function (latlng) {\n var pos = this.getProjection().fromLatLngToDivPixel(latlng);\n pos.x -= this.anchorIcon_[1];\n pos.y -= this.anchorIcon_[0];\n pos.x = parseInt(pos.x, 10);\n pos.y = parseInt(pos.y, 10);\n return pos;\n};\n\n\n/**\n * Creates a single cluster that manages a group of proximate markers.\n * Used internally, do not call this constructor directly.\n * @constructor\n * @param {MarkerClusterer} mc The MarkerClusterer object with which this\n * cluster is associated.\n */\nfunction Cluster(mc) {\n this.markerClusterer_ = mc;\n this.map_ = mc.getMap();\n this.gridSize_ = mc.getGridSize();\n this.minClusterSize_ = mc.getMinimumClusterSize();\n this.averageCenter_ = mc.getAverageCenter();\n this.markers_ = [];\n this.center_ = null;\n this.bounds_ = null;\n this.clusterIcon_ = new ClusterIcon(this, mc.getStyles());\n}\n\n\n/**\n * Returns the number of markers managed by the cluster. You can call this from\n * a click, mouseover, or mouseout event handler\n * for the MarkerClusterer object.\n *\n * @return {number} The number of markers in the cluster.\n */\nCluster.prototype.getSize = function () {\n return this.markers_.length;\n};\n\n\n/**\n * Returns the array of markers managed by the cluster. You can call this from\n * a click, mouseover, or mouseout event handler\n * for the MarkerClusterer object.\n *\n * @return {Array} The array of markers in the cluster.\n */\nCluster.prototype.getMarkers = function () {\n return this.markers_;\n};\n\n\n/**\n * Returns the center of the cluster. You can call this from\n * a click, mouseover, or mouseout event handler\n * for the MarkerClusterer object.\n *\n * @return {google.maps.LatLng} The center of the cluster.\n */\nCluster.prototype.getCenter = function () {\n return this.center_;\n};\n\n\n/**\n * Returns the map with which the cluster is associated.\n *\n * @return {google.maps.Map} The map.\n * @ignore\n */\nCluster.prototype.getMap = function () {\n return this.map_;\n};\n\n\n/**\n * Returns the MarkerClusterer object with which the cluster is associated.\n *\n * @return {MarkerClusterer} The associated marker clusterer.\n * @ignore\n */\nCluster.prototype.getMarkerClusterer = function () {\n return this.markerClusterer_;\n};\n\n\n/**\n * Returns the bounds of the cluster.\n *\n * @return {google.maps.LatLngBounds} the cluster bounds.\n * @ignore\n */\nCluster.prototype.getBounds = function () {\n var i;\n var bounds = new google.maps.LatLngBounds(this.center_, this.center_);\n var markers = this.getMarkers();\n for (i = 0; i < markers.length; i++) {\n bounds.extend(markers[i].getPosition());\n }\n return bounds;\n};\n\n\n/**\n * Removes the cluster from the map.\n *\n * @ignore\n */\nCluster.prototype.remove = function () {\n this.clusterIcon_.setMap(null);\n this.markers_ = [];\n delete this.markers_;\n};\n\n\n/**\n * Adds a marker to the cluster.\n *\n * @param {google.maps.Marker} marker The marker to be added.\n * @return {boolean} True if the marker was added.\n * @ignore\n */\nCluster.prototype.addMarker = function (marker) {\n var i;\n var mCount;\n var mz;\n\n if (this.isMarkerAlreadyAdded_(marker)) {\n return false;\n }\n\n if (!this.center_) {\n this.center_ = marker.getPosition();\n this.calculateBounds_();\n } else {\n if (this.averageCenter_) {\n var l = this.markers_.length + 1;\n var lat = (this.center_.lat() * (l - 1) + marker.getPosition().lat()) / l;\n var lng = (this.center_.lng() * (l - 1) + marker.getPosition().lng()) / l;\n this.center_ = new google.maps.LatLng(lat, lng);\n this.calculateBounds_();\n }\n }\n\n marker.isAdded = true;\n this.markers_.push(marker);\n\n mCount = this.markers_.length;\n mz = this.markerClusterer_.getMaxZoom();\n if (mz !== null && this.map_.getZoom() > mz) {\n // Zoomed in past max zoom, so show the marker.\n if (marker.getMap() !== this.map_) {\n marker.setMap(this.map_);\n }\n } else if (mCount < this.minClusterSize_) {\n // Min cluster size not reached so show the marker.\n if (marker.getMap() !== this.map_) {\n marker.setMap(this.map_);\n }\n } else if (mCount === this.minClusterSize_) {\n // Hide the markers that were showing.\n for (i = 0; i < mCount; i++) {\n this.markers_[i].setMap(null);\n }\n } else {\n marker.setMap(null);\n }\n\n this.updateIcon_();\n return true;\n};\n\n\n/**\n * Determines if a marker lies within the cluster's bounds.\n *\n * @param {google.maps.Marker} marker The marker to check.\n * @return {boolean} True if the marker lies in the bounds.\n * @ignore\n */\nCluster.prototype.isMarkerInClusterBounds = function (marker) {\n return this.bounds_.contains(marker.getPosition());\n};\n\n\n/**\n * Calculates the extended bounds of the cluster with the grid.\n */\nCluster.prototype.calculateBounds_ = function () {\n var bounds = new google.maps.LatLngBounds(this.center_, this.center_);\n this.bounds_ = this.markerClusterer_.getExtendedBounds(bounds);\n};\n\n\n/**\n * Updates the cluster icon.\n */\nCluster.prototype.updateIcon_ = function () {\n var mCount = this.markers_.length;\n var mz = this.markerClusterer_.getMaxZoom();\n\n if (mz !== null && this.map_.getZoom() > mz) {\n this.clusterIcon_.hide();\n return;\n }\n\n if (mCount < this.minClusterSize_) {\n // Min cluster size not yet reached.\n this.clusterIcon_.hide();\n return;\n }\n\n var numStyles = this.markerClusterer_.getStyles().length;\n var sums = this.markerClusterer_.getCalculator()(this.markers_, numStyles);\n this.clusterIcon_.setCenter(this.center_);\n this.clusterIcon_.useStyle(sums);\n this.clusterIcon_.show();\n};\n\n\n/**\n * Determines if a marker has already been added to the cluster.\n *\n * @param {google.maps.Marker} marker The marker to check.\n * @return {boolean} True if the marker has already been added.\n */\nCluster.prototype.isMarkerAlreadyAdded_ = function (marker) {\n var i;\n if (this.markers_.indexOf) {\n return this.markers_.indexOf(marker) !== -1;\n } else {\n for (i = 0; i < this.markers_.length; i++) {\n if (marker === this.markers_[i]) {\n return true;\n }\n }\n }\n return false;\n};\n\n\n/**\n * @name MarkerClustererOptions\n * @class This class represents the optional parameter passed to\n * the {@link MarkerClusterer} constructor.\n * @property {number} [gridSize=60] The grid size of a cluster in pixels. The grid is a square.\n * @property {number} [maxZoom=null] The maximum zoom level at which clustering is enabled or\n * null if clustering is to be enabled at all zoom levels.\n * @property {boolean} [zoomOnClick=true] Whether to zoom the map when a cluster marker is\n * clicked. You may want to set this to false if you have installed a handler\n * for the click event and it deals with zooming on its own.\n * @property {boolean} [averageCenter=false] Whether the position of a cluster marker should be\n * the average position of all markers in the cluster. If set to false, the\n * cluster marker is positioned at the location of the first marker added to the cluster.\n * @property {number} [minimumClusterSize=2] The minimum number of markers needed in a cluster\n * before the markers are hidden and a cluster marker appears.\n * @property {boolean} [ignoreHidden=false] Whether to ignore hidden markers in clusters. You\n * may want to set this to true to ensure that hidden markers are not included\n * in the marker count that appears on a cluster marker (this count is the value of the\n * text property of the result returned by the default calculator).\n * If set to true and you change the visibility of a marker being clustered, be\n * sure to also call MarkerClusterer.repaint().\n * @property {string} [title=\"\"] The tooltip to display when the mouse moves over a cluster\n * marker. (Alternatively, you can use a custom calculator function to specify a\n * different tooltip for each cluster marker.)\n * @property {function} [calculator=MarkerClusterer.CALCULATOR] The function used to determine\n * the text to be displayed on a cluster marker and the index indicating which style to use\n * for the cluster marker. The input parameters for the function are (1) the array of markers\n * represented by a cluster marker and (2) the number of cluster icon styles. It returns a\n * {@link ClusterIconInfo} object. The default calculator returns a\n * text property which is the number of markers in the cluster and an\n * index property which is one higher than the lowest integer such that\n * 10^i exceeds the number of markers in the cluster, or the size of the styles\n * array, whichever is less. The styles array element used has an index of\n * index minus 1. For example, the default calculator returns a\n * text value of \"125\" and an index of 3\n * for a cluster icon representing 125 markers so the element used in the styles\n * array is 2. A calculator may also return a title\n * property that contains the text of the tooltip to be used for the cluster marker. If\n * title is not defined, the tooltip is set to the value of the title\n * property for the MarkerClusterer.\n * @property {string} [clusterClass=\"cluster\"] The name of the CSS class defining general styles\n * for the cluster markers. Use this class to define CSS styles that are not set up by the code\n * that processes the styles array.\n * @property {Array} [styles] An array of {@link ClusterIconStyle} elements defining the styles\n * of the cluster markers to be used. The element to be used to style a given cluster marker\n * is determined by the function defined by the calculator property.\n * The default is an array of {@link ClusterIconStyle} elements whose properties are derived\n * from the values for imagePath, imageExtension, and\n * imageSizes.\n * @property {boolean} [enableRetinaIcons=false] Whether to allow the use of cluster icons that\n * have sizes that are some multiple (typically double) of their actual display size. Icons such\n * as these look better when viewed on high-resolution monitors such as Apple's Retina displays.\n * Note: if this property is true, sprites cannot be used as cluster icons.\n * @property {number} [batchSize=MarkerClusterer.BATCH_SIZE] Set this property to the\n * number of markers to be processed in a single batch when using a browser other than\n * Internet Explorer (for Internet Explorer, use the batchSizeIE property instead).\n * @property {number} [batchSizeIE=MarkerClusterer.BATCH_SIZE_IE] When Internet Explorer is\n * being used, markers are processed in several batches with a small delay inserted between\n * each batch in an attempt to avoid Javascript timeout errors. Set this property to the\n * number of markers to be processed in a single batch; select as high a number as you can\n * without causing a timeout error in the browser. This number might need to be as low as 100\n * if 15,000 markers are being managed, for example.\n * @property {string} [imagePath=MarkerClusterer.IMAGE_PATH]\n * The full URL of the root name of the group of image files to use for cluster icons.\n * The complete file name is of the form imagePathn.imageExtension\n * where n is the image file number (1, 2, etc.).\n * @property {string} [imageExtension=MarkerClusterer.IMAGE_EXTENSION]\n * The extension name for the cluster icon image files (e.g., \"png\" or\n * \"jpg\").\n * @property {Array} [imageSizes=MarkerClusterer.IMAGE_SIZES]\n * An array of numbers containing the widths of the group of\n * imagePathn.imageExtension image files.\n * (The images are assumed to be square.)\n */\n/**\n * Creates a MarkerClusterer object with the options specified in {@link MarkerClustererOptions}.\n * @constructor\n * @extends google.maps.OverlayView\n * @param {google.maps.Map} map The Google map to attach to.\n * @param {Array.} [opt_markers] The markers to be added to the cluster.\n * @param {MarkerClustererOptions} [opt_options] The optional parameters.\n */\nfunction MarkerClusterer(map, opt_markers, opt_options) {\n // MarkerClusterer implements google.maps.OverlayView interface. We use the\n // extend function to extend MarkerClusterer with google.maps.OverlayView\n // because it might not always be available when the code is defined so we\n // look for it at the last possible moment. If it doesn't exist now then\n // there is no point going ahead :)\n this.extend(MarkerClusterer, google.maps.OverlayView);\n\n opt_markers = opt_markers || [];\n opt_options = opt_options || {};\n\n this.markers_ = [];\n this.clusters_ = [];\n this.listeners_ = [];\n this.activeMap_ = null;\n this.ready_ = false;\n\n this.gridSize_ = opt_options.gridSize || 60;\n this.minClusterSize_ = opt_options.minimumClusterSize || 2;\n this.maxZoom_ = opt_options.maxZoom || null;\n this.styles_ = opt_options.styles || [];\n this.title_ = opt_options.title || \"\";\n this.zoomOnClick_ = true;\n if (opt_options.zoomOnClick !== undefined) {\n this.zoomOnClick_ = opt_options.zoomOnClick;\n }\n this.averageCenter_ = false;\n if (opt_options.averageCenter !== undefined) {\n this.averageCenter_ = opt_options.averageCenter;\n }\n this.ignoreHidden_ = false;\n if (opt_options.ignoreHidden !== undefined) {\n this.ignoreHidden_ = opt_options.ignoreHidden;\n }\n this.enableRetinaIcons_ = false;\n if (opt_options.enableRetinaIcons !== undefined) {\n this.enableRetinaIcons_ = opt_options.enableRetinaIcons;\n }\n this.imagePath_ = opt_options.imagePath || MarkerClusterer.IMAGE_PATH;\n this.imageExtension_ = opt_options.imageExtension || MarkerClusterer.IMAGE_EXTENSION;\n this.imageSizes_ = opt_options.imageSizes || MarkerClusterer.IMAGE_SIZES;\n this.calculator_ = opt_options.calculator || MarkerClusterer.CALCULATOR;\n this.batchSize_ = opt_options.batchSize || MarkerClusterer.BATCH_SIZE;\n this.batchSizeIE_ = opt_options.batchSizeIE || MarkerClusterer.BATCH_SIZE_IE;\n this.clusterClass_ = opt_options.clusterClass || \"cluster\";\n\n if (navigator.userAgent.toLowerCase().indexOf(\"msie\") !== -1) {\n // Try to avoid IE timeout when processing a huge number of markers:\n this.batchSize_ = this.batchSizeIE_;\n }\n\n this.setupStyles_();\n\n this.addMarkers(opt_markers, true);\n this.setMap(map); // Note: this causes onAdd to be called\n}\n\n\n/**\n * Implementation of the onAdd interface method.\n * @ignore\n */\nMarkerClusterer.prototype.onAdd = function () {\n var cMarkerClusterer = this;\n\n this.activeMap_ = this.getMap();\n this.ready_ = true;\n\n this.repaint();\n\n // Add the map event listeners\n this.listeners_ = [\n google.maps.event.addListener(this.getMap(), \"zoom_changed\", function () {\n cMarkerClusterer.resetViewport_(false);\n // Workaround for this Google bug: when map is at level 0 and \"-\" of\n // zoom slider is clicked, a \"zoom_changed\" event is fired even though\n // the map doesn't zoom out any further. In this situation, no \"idle\"\n // event is triggered so the cluster markers that have been removed\n // do not get redrawn. Same goes for a zoom in at maxZoom.\n if (this.getZoom() === (this.get(\"minZoom\") || 0) || this.getZoom() === this.get(\"maxZoom\")) {\n google.maps.event.trigger(this, \"idle\");\n }\n }),\n google.maps.event.addListener(this.getMap(), \"idle\", function () {\n cMarkerClusterer.redraw_();\n })\n ];\n};\n\n\n/**\n * Implementation of the onRemove interface method.\n * Removes map event listeners and all cluster icons from the DOM.\n * All managed markers are also put back on the map.\n * @ignore\n */\nMarkerClusterer.prototype.onRemove = function () {\n var i;\n\n // Put all the managed markers back on the map:\n for (i = 0; i < this.markers_.length; i++) {\n if (this.markers_[i].getMap() !== this.activeMap_) {\n this.markers_[i].setMap(this.activeMap_);\n }\n }\n\n // Remove all clusters:\n for (i = 0; i < this.clusters_.length; i++) {\n this.clusters_[i].remove();\n }\n this.clusters_ = [];\n\n // Remove map event listeners:\n for (i = 0; i < this.listeners_.length; i++) {\n google.maps.event.removeListener(this.listeners_[i]);\n }\n this.listeners_ = [];\n\n this.activeMap_ = null;\n this.ready_ = false;\n};\n\n\n/**\n * Implementation of the draw interface method.\n * @ignore\n */\nMarkerClusterer.prototype.draw = function () {};\n\n\n/**\n * Sets up the styles object.\n */\nMarkerClusterer.prototype.setupStyles_ = function () {\n var i, size;\n if (this.styles_.length > 0) {\n return;\n }\n\n for (i = 0; i < this.imageSizes_.length; i++) {\n size = this.imageSizes_[i];\n this.styles_.push({\n url: this.imagePath_ + (i + 1) + \".\" + this.imageExtension_,\n height: size,\n width: size\n });\n }\n};\n\n\n/**\n * Fits the map to the bounds of the markers managed by the clusterer.\n */\nMarkerClusterer.prototype.fitMapToMarkers = function () {\n var i;\n var markers = this.getMarkers();\n var bounds = new google.maps.LatLngBounds();\n for (i = 0; i < markers.length; i++) {\n bounds.extend(markers[i].getPosition());\n }\n\n this.getMap().fitBounds(bounds);\n};\n\n\n/**\n * Returns the value of the gridSize property.\n *\n * @return {number} The grid size.\n */\nMarkerClusterer.prototype.getGridSize = function () {\n return this.gridSize_;\n};\n\n\n/**\n * Sets the value of the gridSize property.\n *\n * @param {number} gridSize The grid size.\n */\nMarkerClusterer.prototype.setGridSize = function (gridSize) {\n this.gridSize_ = gridSize;\n};\n\n\n/**\n * Returns the value of the minimumClusterSize property.\n *\n * @return {number} The minimum cluster size.\n */\nMarkerClusterer.prototype.getMinimumClusterSize = function () {\n return this.minClusterSize_;\n};\n\n/**\n * Sets the value of the minimumClusterSize property.\n *\n * @param {number} minimumClusterSize The minimum cluster size.\n */\nMarkerClusterer.prototype.setMinimumClusterSize = function (minimumClusterSize) {\n this.minClusterSize_ = minimumClusterSize;\n};\n\n\n/**\n * Returns the value of the maxZoom property.\n *\n * @return {number} The maximum zoom level.\n */\nMarkerClusterer.prototype.getMaxZoom = function () {\n return this.maxZoom_;\n};\n\n\n/**\n * Sets the value of the maxZoom property.\n *\n * @param {number} maxZoom The maximum zoom level.\n */\nMarkerClusterer.prototype.setMaxZoom = function (maxZoom) {\n this.maxZoom_ = maxZoom;\n};\n\n\n/**\n * Returns the value of the styles property.\n *\n * @return {Array} The array of styles defining the cluster markers to be used.\n */\nMarkerClusterer.prototype.getStyles = function () {\n return this.styles_;\n};\n\n\n/**\n * Sets the value of the styles property.\n *\n * @param {Array.} styles The array of styles to use.\n */\nMarkerClusterer.prototype.setStyles = function (styles) {\n this.styles_ = styles;\n};\n\n\n/**\n * Returns the value of the title property.\n *\n * @return {string} The content of the title text.\n */\nMarkerClusterer.prototype.getTitle = function () {\n return this.title_;\n};\n\n\n/**\n * Sets the value of the title property.\n *\n * @param {string} title The value of the title property.\n */\nMarkerClusterer.prototype.setTitle = function (title) {\n this.title_ = title;\n};\n\n\n/**\n * Returns the value of the zoomOnClick property.\n *\n * @return {boolean} True if zoomOnClick property is set.\n */\nMarkerClusterer.prototype.getZoomOnClick = function () {\n return this.zoomOnClick_;\n};\n\n\n/**\n * Sets the value of the zoomOnClick property.\n *\n * @param {boolean} zoomOnClick The value of the zoomOnClick property.\n */\nMarkerClusterer.prototype.setZoomOnClick = function (zoomOnClick) {\n this.zoomOnClick_ = zoomOnClick;\n};\n\n\n/**\n * Returns the value of the averageCenter property.\n *\n * @return {boolean} True if averageCenter property is set.\n */\nMarkerClusterer.prototype.getAverageCenter = function () {\n return this.averageCenter_;\n};\n\n\n/**\n * Sets the value of the averageCenter property.\n *\n * @param {boolean} averageCenter The value of the averageCenter property.\n */\nMarkerClusterer.prototype.setAverageCenter = function (averageCenter) {\n this.averageCenter_ = averageCenter;\n};\n\n\n/**\n * Returns the value of the ignoreHidden property.\n *\n * @return {boolean} True if ignoreHidden property is set.\n */\nMarkerClusterer.prototype.getIgnoreHidden = function () {\n return this.ignoreHidden_;\n};\n\n\n/**\n * Sets the value of the ignoreHidden property.\n *\n * @param {boolean} ignoreHidden The value of the ignoreHidden property.\n */\nMarkerClusterer.prototype.setIgnoreHidden = function (ignoreHidden) {\n this.ignoreHidden_ = ignoreHidden;\n};\n\n\n/**\n * Returns the value of the enableRetinaIcons property.\n *\n * @return {boolean} True if enableRetinaIcons property is set.\n */\nMarkerClusterer.prototype.getEnableRetinaIcons = function () {\n return this.enableRetinaIcons_;\n};\n\n\n/**\n * Sets the value of the enableRetinaIcons property.\n *\n * @param {boolean} enableRetinaIcons The value of the enableRetinaIcons property.\n */\nMarkerClusterer.prototype.setEnableRetinaIcons = function (enableRetinaIcons) {\n this.enableRetinaIcons_ = enableRetinaIcons;\n};\n\n\n/**\n * Returns the value of the imageExtension property.\n *\n * @return {string} The value of the imageExtension property.\n */\nMarkerClusterer.prototype.getImageExtension = function () {\n return this.imageExtension_;\n};\n\n\n/**\n * Sets the value of the imageExtension property.\n *\n * @param {string} imageExtension The value of the imageExtension property.\n */\nMarkerClusterer.prototype.setImageExtension = function (imageExtension) {\n this.imageExtension_ = imageExtension;\n};\n\n\n/**\n * Returns the value of the imagePath property.\n *\n * @return {string} The value of the imagePath property.\n */\nMarkerClusterer.prototype.getImagePath = function () {\n return this.imagePath_;\n};\n\n\n/**\n * Sets the value of the imagePath property.\n *\n * @param {string} imagePath The value of the imagePath property.\n */\nMarkerClusterer.prototype.setImagePath = function (imagePath) {\n this.imagePath_ = imagePath;\n};\n\n\n/**\n * Returns the value of the imageSizes property.\n *\n * @return {Array} The value of the imageSizes property.\n */\nMarkerClusterer.prototype.getImageSizes = function () {\n return this.imageSizes_;\n};\n\n\n/**\n * Sets the value of the imageSizes property.\n *\n * @param {Array} imageSizes The value of the imageSizes property.\n */\nMarkerClusterer.prototype.setImageSizes = function (imageSizes) {\n this.imageSizes_ = imageSizes;\n};\n\n\n/**\n * Returns the value of the calculator property.\n *\n * @return {function} the value of the calculator property.\n */\nMarkerClusterer.prototype.getCalculator = function () {\n return this.calculator_;\n};\n\n\n/**\n * Sets the value of the calculator property.\n *\n * @param {function(Array., number)} calculator The value\n * of the calculator property.\n */\nMarkerClusterer.prototype.setCalculator = function (calculator) {\n this.calculator_ = calculator;\n};\n\n\n/**\n * Returns the value of the batchSizeIE property.\n *\n * @return {number} the value of the batchSizeIE property.\n */\nMarkerClusterer.prototype.getBatchSizeIE = function () {\n return this.batchSizeIE_;\n};\n\n\n/**\n * Sets the value of the batchSizeIE property.\n *\n * @param {number} batchSizeIE The value of the batchSizeIE property.\n */\nMarkerClusterer.prototype.setBatchSizeIE = function (batchSizeIE) {\n this.batchSizeIE_ = batchSizeIE;\n};\n\n\n/**\n * Returns the value of the clusterClass property.\n *\n * @return {string} the value of the clusterClass property.\n */\nMarkerClusterer.prototype.getClusterClass = function () {\n return this.clusterClass_;\n};\n\n\n/**\n * Sets the value of the clusterClass property.\n *\n * @param {string} clusterClass The value of the clusterClass property.\n */\nMarkerClusterer.prototype.setClusterClass = function (clusterClass) {\n this.clusterClass_ = clusterClass;\n};\n\n\n/**\n * Returns the array of markers managed by the clusterer.\n *\n * @return {Array} The array of markers managed by the clusterer.\n */\nMarkerClusterer.prototype.getMarkers = function () {\n return this.markers_;\n};\n\n\n/**\n * Returns the number of markers managed by the clusterer.\n *\n * @return {number} The number of markers.\n */\nMarkerClusterer.prototype.getTotalMarkers = function () {\n return this.markers_.length;\n};\n\n\n/**\n * Returns the current array of clusters formed by the clusterer.\n *\n * @return {Array} The array of clusters formed by the clusterer.\n */\nMarkerClusterer.prototype.getClusters = function () {\n return this.clusters_;\n};\n\n\n/**\n * Returns the number of clusters formed by the clusterer.\n *\n * @return {number} The number of clusters formed by the clusterer.\n */\nMarkerClusterer.prototype.getTotalClusters = function () {\n return this.clusters_.length;\n};\n\n\n/**\n * Adds a marker to the clusterer. The clusters are redrawn unless\n * opt_nodraw is set to true.\n *\n * @param {google.maps.Marker} marker The marker to add.\n * @param {boolean} [opt_nodraw] Set to true to prevent redrawing.\n */\nMarkerClusterer.prototype.addMarker = function (marker, opt_nodraw) {\n this.pushMarkerTo_(marker);\n if (!opt_nodraw) {\n this.redraw_();\n }\n};\n\n\n/**\n * Adds an array of markers to the clusterer. The clusters are redrawn unless\n * opt_nodraw is set to true.\n *\n * @param {Array.} markers The markers to add.\n * @param {boolean} [opt_nodraw] Set to true to prevent redrawing.\n */\nMarkerClusterer.prototype.addMarkers = function (markers, opt_nodraw) {\n var key;\n for (key in markers) {\n if (markers.hasOwnProperty(key)) {\n this.pushMarkerTo_(markers[key]);\n }\n } \n if (!opt_nodraw) {\n this.redraw_();\n }\n};\n\n\n/**\n * Pushes a marker to the clusterer.\n *\n * @param {google.maps.Marker} marker The marker to add.\n */\nMarkerClusterer.prototype.pushMarkerTo_ = function (marker) {\n // If the marker is draggable add a listener so we can update the clusters on the dragend:\n if (marker.getDraggable()) {\n var cMarkerClusterer = this;\n google.maps.event.addListener(marker, \"dragend\", function () {\n if (cMarkerClusterer.ready_) {\n this.isAdded = false;\n cMarkerClusterer.repaint();\n }\n });\n }\n marker.isAdded = false;\n this.markers_.push(marker);\n};\n\n\n/**\n * Removes a marker from the cluster. The clusters are redrawn unless\n * opt_nodraw is set to true. Returns true if the\n * marker was removed from the clusterer.\n *\n * @param {google.maps.Marker} marker The marker to remove.\n * @param {boolean} [opt_nodraw] Set to true to prevent redrawing.\n * @return {boolean} True if the marker was removed from the clusterer.\n */\nMarkerClusterer.prototype.removeMarker = function (marker, opt_nodraw) {\n var removed = this.removeMarker_(marker);\n\n if (!opt_nodraw && removed) {\n this.repaint();\n }\n\n return removed;\n};\n\n\n/**\n * Removes an array of markers from the cluster. The clusters are redrawn unless\n * opt_nodraw is set to true. Returns true if markers\n * were removed from the clusterer.\n *\n * @param {Array.} markers The markers to remove.\n * @param {boolean} [opt_nodraw] Set to true to prevent redrawing.\n * @return {boolean} True if markers were removed from the clusterer.\n */\nMarkerClusterer.prototype.removeMarkers = function (markers, opt_nodraw) {\n var i, r;\n var removed = false;\n\n for (i = 0; i < markers.length; i++) {\n r = this.removeMarker_(markers[i]);\n removed = removed || r;\n }\n\n if (!opt_nodraw && removed) {\n this.repaint();\n }\n\n return removed;\n};\n\n\n/**\n * Removes a marker and returns true if removed, false if not.\n *\n * @param {google.maps.Marker} marker The marker to remove\n * @return {boolean} Whether the marker was removed or not\n */\nMarkerClusterer.prototype.removeMarker_ = function (marker) {\n var i;\n var index = -1;\n if (this.markers_.indexOf) {\n index = this.markers_.indexOf(marker);\n } else {\n for (i = 0; i < this.markers_.length; i++) {\n if (marker === this.markers_[i]) {\n index = i;\n break;\n }\n }\n }\n\n if (index === -1) {\n // Marker is not in our list of markers, so do nothing:\n return false;\n }\n\n marker.setMap(null);\n this.markers_.splice(index, 1); // Remove the marker from the list of managed markers\n return true;\n};\n\n\n/**\n * Removes all clusters and markers from the map and also removes all markers\n * managed by the clusterer.\n */\nMarkerClusterer.prototype.clearMarkers = function () {\n this.resetViewport_(true);\n this.markers_ = [];\n};\n\n\n/**\n * Recalculates and redraws all the marker clusters from scratch.\n * Call this after changing any properties.\n */\nMarkerClusterer.prototype.repaint = function () {\n var oldClusters = this.clusters_.slice();\n this.clusters_ = [];\n this.resetViewport_(false);\n this.redraw_();\n\n // Remove the old clusters.\n // Do it in a timeout to prevent blinking effect.\n setTimeout(function () {\n var i;\n for (i = 0; i < oldClusters.length; i++) {\n oldClusters[i].remove();\n }\n }, 0);\n};\n\n\n/**\n * Returns the current bounds extended by the grid size.\n *\n * @param {google.maps.LatLngBounds} bounds The bounds to extend.\n * @return {google.maps.LatLngBounds} The extended bounds.\n * @ignore\n */\nMarkerClusterer.prototype.getExtendedBounds = function (bounds) {\n var projection = this.getProjection();\n\n // Turn the bounds into latlng.\n var tr = new google.maps.LatLng(bounds.getNorthEast().lat(),\n bounds.getNorthEast().lng());\n var bl = new google.maps.LatLng(bounds.getSouthWest().lat(),\n bounds.getSouthWest().lng());\n\n // Convert the points to pixels and the extend out by the grid size.\n var trPix = projection.fromLatLngToDivPixel(tr);\n trPix.x += this.gridSize_;\n trPix.y -= this.gridSize_;\n\n var blPix = projection.fromLatLngToDivPixel(bl);\n blPix.x -= this.gridSize_;\n blPix.y += this.gridSize_;\n\n // Convert the pixel points back to LatLng\n var ne = projection.fromDivPixelToLatLng(trPix);\n var sw = projection.fromDivPixelToLatLng(blPix);\n\n // Extend the bounds to contain the new bounds.\n bounds.extend(ne);\n bounds.extend(sw);\n\n return bounds;\n};\n\n\n/**\n * Redraws all the clusters.\n */\nMarkerClusterer.prototype.redraw_ = function () {\n this.createClusters_(0);\n};\n\n\n/**\n * Removes all clusters from the map. The markers are also removed from the map\n * if opt_hide is set to true.\n *\n * @param {boolean} [opt_hide] Set to true to also remove the markers\n * from the map.\n */\nMarkerClusterer.prototype.resetViewport_ = function (opt_hide) {\n var i, marker;\n // Remove all the clusters\n for (i = 0; i < this.clusters_.length; i++) {\n this.clusters_[i].remove();\n }\n this.clusters_ = [];\n\n // Reset the markers to not be added and to be removed from the map.\n for (i = 0; i < this.markers_.length; i++) {\n marker = this.markers_[i];\n marker.isAdded = false;\n if (opt_hide) {\n marker.setMap(null);\n }\n }\n};\n\n\n/**\n * Calculates the distance between two latlng locations in km.\n *\n * @param {google.maps.LatLng} p1 The first lat lng point.\n * @param {google.maps.LatLng} p2 The second lat lng point.\n * @return {number} The distance between the two points in km.\n * @see http://www.movable-type.co.uk/scripts/latlong.html\n*/\nMarkerClusterer.prototype.distanceBetweenPoints_ = function (p1, p2) {\n var R = 6371; // Radius of the Earth in km\n var dLat = (p2.lat() - p1.lat()) * Math.PI / 180;\n var dLon = (p2.lng() - p1.lng()) * Math.PI / 180;\n var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +\n Math.cos(p1.lat() * Math.PI / 180) * Math.cos(p2.lat() * Math.PI / 180) *\n Math.sin(dLon / 2) * Math.sin(dLon / 2);\n var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n var d = R * c;\n return d;\n};\n\n\n/**\n * Determines if a marker is contained in a bounds.\n *\n * @param {google.maps.Marker} marker The marker to check.\n * @param {google.maps.LatLngBounds} bounds The bounds to check against.\n * @return {boolean} True if the marker is in the bounds.\n */\nMarkerClusterer.prototype.isMarkerInBounds_ = function (marker, bounds) {\n return bounds.contains(marker.getPosition());\n};\n\n\n/**\n * Adds a marker to a cluster, or creates a new cluster.\n *\n * @param {google.maps.Marker} marker The marker to add.\n */\nMarkerClusterer.prototype.addToClosestCluster_ = function (marker) {\n var i, d, cluster, center;\n var distance = 40000; // Some large number\n var clusterToAddTo = null;\n for (i = 0; i < this.clusters_.length; i++) {\n cluster = this.clusters_[i];\n center = cluster.getCenter();\n if (center) {\n d = this.distanceBetweenPoints_(center, marker.getPosition());\n if (d < distance) {\n distance = d;\n clusterToAddTo = cluster;\n }\n }\n }\n\n if (clusterToAddTo && clusterToAddTo.isMarkerInClusterBounds(marker)) {\n clusterToAddTo.addMarker(marker);\n } else {\n cluster = new Cluster(this);\n cluster.addMarker(marker);\n this.clusters_.push(cluster);\n }\n};\n\n\n/**\n * Creates the clusters. This is done in batches to avoid timeout errors\n * in some browsers when there is a huge number of markers.\n *\n * @param {number} iFirst The index of the first marker in the batch of\n * markers to be added to clusters.\n */\nMarkerClusterer.prototype.createClusters_ = function (iFirst) {\n var i, marker;\n var mapBounds;\n var cMarkerClusterer = this;\n if (!this.ready_) {\n return;\n }\n\n // Cancel previous batch processing if we're working on the first batch:\n if (iFirst === 0) {\n /**\n * This event is fired when the MarkerClusterer begins\n * clustering markers.\n * @name MarkerClusterer#clusteringbegin\n * @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered.\n * @event\n */\n google.maps.event.trigger(this, \"clusteringbegin\", this);\n\n if (typeof this.timerRefStatic !== \"undefined\") {\n clearTimeout(this.timerRefStatic);\n delete this.timerRefStatic;\n }\n }\n\n // Get our current map view bounds.\n // Create a new bounds object so we don't affect the map.\n //\n // See Comments 9 & 11 on Issue 3651 relating to this workaround for a Google Maps bug:\n if (this.getMap().getZoom() > 3) {\n mapBounds = new google.maps.LatLngBounds(this.getMap().getBounds().getSouthWest(),\n this.getMap().getBounds().getNorthEast());\n } else {\n mapBounds = new google.maps.LatLngBounds(new google.maps.LatLng(85.02070771743472, -178.48388434375), new google.maps.LatLng(-85.08136444384544, 178.00048865625));\n }\n var bounds = this.getExtendedBounds(mapBounds);\n\n var iLast = Math.min(iFirst + this.batchSize_, this.markers_.length);\n\n for (i = iFirst; i < iLast; i++) {\n marker = this.markers_[i];\n if (!marker.isAdded && this.isMarkerInBounds_(marker, bounds)) {\n if (!this.ignoreHidden_ || (this.ignoreHidden_ && marker.getVisible())) {\n this.addToClosestCluster_(marker);\n }\n }\n }\n\n if (iLast < this.markers_.length) {\n this.timerRefStatic = setTimeout(function () {\n cMarkerClusterer.createClusters_(iLast);\n }, 0);\n } else {\n delete this.timerRefStatic;\n\n /**\n * This event is fired when the MarkerClusterer stops\n * clustering markers.\n * @name MarkerClusterer#clusteringend\n * @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered.\n * @event\n */\n google.maps.event.trigger(this, \"clusteringend\", this);\n }\n};\n\n\n/**\n * Extends an object's prototype by another's.\n *\n * @param {Object} obj1 The object to be extended.\n * @param {Object} obj2 The object to extend with.\n * @return {Object} The new extended object.\n * @ignore\n */\nMarkerClusterer.prototype.extend = function (obj1, obj2) {\n return (function (object) {\n var property;\n for (property in object.prototype) {\n this.prototype[property] = object.prototype[property];\n }\n return this;\n }).apply(obj1, [obj2]);\n};\n\n\n/**\n * The default function for determining the label text and style\n * for a cluster icon.\n *\n * @param {Array.} markers The array of markers represented by the cluster.\n * @param {number} numStyles The number of marker styles available.\n * @return {ClusterIconInfo} The information resource for the cluster.\n * @constant\n * @ignore\n */\nMarkerClusterer.CALCULATOR = function (markers, numStyles) {\n var index = 0;\n var title = \"\";\n var count = markers.length.toString();\n\n var dv = count;\n while (dv !== 0) {\n dv = parseInt(dv / 10, 10);\n index++;\n }\n\n index = Math.min(index, numStyles);\n return {\n text: count,\n index: index,\n title: title\n };\n};\n\n\n/**\n * The number of markers to process in one batch.\n *\n * @type {number}\n * @constant\n */\nMarkerClusterer.BATCH_SIZE = 2000;\n\n\n/**\n * The number of markers to process in one batch (IE only).\n *\n * @type {number}\n * @constant\n */\nMarkerClusterer.BATCH_SIZE_IE = 500;\n\n\n/**\n * The default root name for the marker cluster images.\n *\n * @type {string}\n * @constant\n */\nMarkerClusterer.IMAGE_PATH = \"http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclustererplus/images/m\";\n\n\n/**\n * The default extension name for the marker cluster images.\n *\n * @type {string}\n * @constant\n */\nMarkerClusterer.IMAGE_EXTENSION = \"png\";\n\n\n/**\n * The default array of sizes for the marker cluster images.\n *\n * @type {Array.}\n * @constant\n */\nMarkerClusterer.IMAGE_SIZES = [53, 56, 66, 78, 90];\n"},"message":{"kind":"string","value":"MasterClurstererPlus - Patch for marker on retina display\n"},"old_file":{"kind":"string","value":"markerclustererplus/src/markerclusterer.js"},"subject":{"kind":"string","value":"MasterClurstererPlus - Patch for marker on retina display"},"git_diff":{"kind":"string","value":"arkerclustererplus/src/markerclusterer.js\n if (!this.cluster_.getMarkerClusterer().enableRetinaIcons_) {\n img += \"clip: rect(\" + (-1 * spriteV) + \"px, \" + ((-1 * spriteH) + this.width_) + \"px, \" +\n ((-1 * spriteV) + this.height_) + \"px, \" + (-1 * spriteH) + \"px);\";\n }\n else {\n \timg += \"width: \" + this.width_ + \"px;\" + \"height: \" + this.height_ + \"px;\";\n }\n img += \"'>\";\n this.div_.innerHTML = img + \"
= 0;\n\t}\n\n\tpublic IntSet minus(int i) {\n\t\tint idx = Arrays.binarySearch(values, i);\n\t\tif (idx >= 0) {\n\t\t\tint[] newValues = new int[values.length - 1];\n\t\t\tSystem.arraycopy(values, 0, newValues, 0, idx); // x < i\n\t\t\tSystem.arraycopy(values, idx + 1, newValues, idx, values.length - idx - 1); // x > i\n\t\t\treturn new IntSet(newValues);\n\t\t}\n\t\telse {\n\t\t\treturn this;\n\t\t}\n\t}\n\n\tpublic IntSet minus(IntContainer that) {\n\t\tCheck.notNull(that);\n\n\t\tIntSet result = this;\n\t\tfor (int i = 0; i < that.length(); i++) {\n\t\t\t// FIXME: this is very inefficient for IntSets -- that can be specialised\n\t\t\tresult = result.minus(that.get(i));\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic IntSet plus(int i) {\n\t\tint idx = Arrays.binarySearch(values, i);\n\t\tif (idx < 0) {\n\t\t\tint[] newValues = new int[values.length + 1];\n\n\t\t\tint insIdx = -idx - 1;\n\t\t\tSystem.arraycopy(values, 0, newValues, 0, insIdx); // x < i\n\t\t\tSystem.arraycopy(values, insIdx, newValues, insIdx + 1, values.length - insIdx); // x > i\n\t\t\tnewValues[insIdx] = i;\n\n\t\t\treturn new IntSet(newValues);\n\t\t}\n\t\telse {\n\t\t\treturn this;\n\t\t}\n\t}\n\n\tpublic IntSet plus(IntContainer that) {\n\t\tCheck.notNull(that);\n\n\t\tIntSet result = this;\n\t\tfor (int i = 0; i < that.length(); i++) {\n\t\t\t// FIXME: this is very inefficient for IntSets -- that can be specialised\n\t\t\tresult = result.plus(that.get(i));\n\t\t}\n\t\treturn result;\n\t}\n\n}\n"},"new_file":{"kind":"string","value":"rembulan-util/src/main/java/net/sandius/rembulan/util/IntSet.java"},"old_contents":{"kind":"string","value":""},"message":{"kind":"string","value":"Adding an implementation of integer sets.\n"},"old_file":{"kind":"string","value":"rembulan-util/src/main/java/net/sandius/rembulan/util/IntSet.java"},"subject":{"kind":"string","value":"Adding an implementation of integer sets."},"git_diff":{"kind":"string","value":"embulan-util/src/main/java/net/sandius/rembulan/util/IntSet.java\npackage net.sandius.rembulan.util;\n\nimport java.util.Arrays;\n\npublic class IntSet extends IntContainer {\n\n\tprivate final int[] values;\n\n\tprivate IntSet(int[] values) {\n\t\tCheck.notNull(values);\n\t\t// values must be sorted\n\t\tthis.values = values;\n\t}\n\n//\tpublic static IntSet from(int[] values) {\n//\t\tCheck.notNull(values);\n//\t\tint[] sorted = Arrays.copyOf(values, values.length);\n//\t\tArrays.sort(sorted);\n//\n//\t\t// remove duplicates\n//\n//\t\treturn new IntSet(copy);\n//\t}\n\n\tpublic static IntSet empty() {\n\t\treturn new IntSet(new int[0]);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (this == o) return true;\n\t\tif (o == null || getClass() != o.getClass()) return false;\n\t\tIntSet intSet = (IntSet) o;\n\t\treturn Arrays.equals(values, intSet.values);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Arrays.hashCode(values);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn toString(\",\");\n\t}\n\n\tpublic String toString(String separator) {\n\t\tStringBuilder bld = new StringBuilder();\n\t\tfor (int i = 0; i < values.length; i++) {\n\t\t\tbld.append(values[i]);\n\t\t\tif (i + 1 < values.length) {\n\t\t\t\tbld.append(separator);\n\t\t\t}\n\t\t}\n\t\treturn bld.toString();\n\t}\n\n\t@Override\n\tpublic int length() {\n\t\treturn size();\n\t}\n\n\t@Override\n\tpublic int get(int index) {\n\t\treturn values[index];\n\t}\n\n\tpublic int size() {\n\t\treturn values.length;\n\t}\n\n\t@Override\n\tpublic boolean contains(int i) {\n\t\treturn Arrays.binarySearch(values, i) >= 0;\n\t}\n\n\tpublic IntSet minus(int i) {\n\t\tint idx = Arrays.binarySearch(values, i);\n\t\tif (idx >= 0) {\n\t\t\tint[] newValues = new int[values.length - 1];\n\t\t\tSystem.arraycopy(values, 0, newValues, 0, idx); // x < i\n\t\t\tSystem.arraycopy(values, idx + 1, newValues, idx, values.length - idx - 1); // x > i\n\t\t\treturn new IntSet(newValues);\n\t\t}\n\t\telse {\n\t\t\treturn this;\n\t\t}\n\t}\n\n\tpublic IntSet minus(IntContainer that) {\n\t\tCheck.notNull(that);\n\n\t\tIntSet result = this;\n\t\tfor (int i = 0; i < that.length(); i++) {\n\t\t\t// FIXME: this is very inefficient for IntSets -- that can be specialised\n\t\t\tresult = result.minus(that.get(i));\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic IntSet plus(int i) {\n\t\tint idx = Arrays.binarySearch(values, i);\n\t\tif (idx < 0) {\n\t\t\tint[] newValues = new int[values.length + 1];\n\n\t\t\tint insIdx = -idx - 1;\n\t\t\tSystem.arraycopy(values, 0, newValues, 0, insIdx); // x < i\n\t\t\tSystem.arraycopy(values, insIdx, newValues, insIdx + 1, values.length - insIdx); // x > i\n\t\t\tnewValues[insIdx] = i;\n\n\t\t\treturn new IntSet(newValues);\n\t\t}\n\t\telse {\n\t\t\treturn this;\n\t\t}\n\t}\n\n\tpublic IntSet plus(IntContainer that) {\n\t\tCheck.notNull(that);\n\n\t\tIntSet result = this;\n\t\tfor (int i = 0; i < that.length(); i++) {\n\t\t\t// FIXME: this is very inefficient for IntSets -- that can be specialised\n\t\t\tresult = result.plus(that.get(i));\n\t\t}\n\t\treturn result;\n\t}\n\n}"}}},{"rowIdx":1919,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"epl-1.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"6820adba4e2784419ca57386f3a1e6f82bad41ea"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"inevo/mondrian,inevo/mondrian"},"new_contents":{"kind":"string","value":"/*\n// $Id$\n// This software is subject to the terms of the Common Public License\n// Agreement, available at the following URL:\n// http://www.opensource.org/licenses/cpl.html.\n// (C) Copyright 2004-2005 Julian Hyde\n// All Rights Reserved.\n// You must accept the terms of that agreement to use this software.\n*/\npackage mondrian.test.loader;\n\nimport mondrian.olap.MondrianResource;\nimport mondrian.rolap.RolapUtil;\nimport mondrian.rolap.sql.SqlQuery;\n\nimport java.io.*;\nimport java.math.BigDecimal;\n//import java.math.BigDecimal;\nimport java.sql.*;\nimport java.text.DateFormat;\nimport java.text.DecimalFormat;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.Map;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport java.util.zip.ZipEntry;\nimport java.util.zip.ZipFile;\n\n/**\n * Utility to load the FoodMart dataset into an arbitrary JDBC database.\n *\n *

This is known to create test data for the following databases:

\n *
    \n *\n *
  • MySQL 3.23 using MySQL-connector/J 3.0.16
  • \n *\n *
  • MySQL 4.15 using MySQL-connector/J 3.0.16
  • \n *\n *
  • Postgres 8.0 beta using postgresql-driver-jdbc3-74-214.jar
  • \n *\n *
  • Oracle 10g using ojdbc14.jar
  • \n *\n *
\n *\n *

Output can be to a set of files with create table, insert and create index\n * statements, or directly to a JDBC connection with JDBC batches (lots faster!)

\n *\n *

On the command line:

\n *\n *
MySQL example\n * $ mysqladmin create foodmart
\n * $ java -cp 'classes;testclasses' mondrian.test.loader.MondrianFoodMartLoader\n * -verbose -tables -data -indexes -jdbcDrivers=com.mysql.jdbc.Driver\n * -inputJdbcURL=jdbc:odbc:MondrianFoodMart -outputJdbcURL=jdbc:mysql://localhost/foodmart\n *
\n *\n * @author jhyde\n * @since 23 December, 2004\n * @version $Id$\n */\npublic class MondrianFoodMartLoader {\n final Pattern decimalDataTypeRegex = Pattern.compile(\"DECIMAL\\\\((.*),(.*)\\\\)\");\n final DecimalFormat integerFormatter = new DecimalFormat(decimalFormat(15, 0));\n final String dateFormatString = \"yyyy-MM-dd\";\n final String oracleDateFormatString = \"YYYY-MM-DD\";\n final DateFormat dateFormatter = new SimpleDateFormat(dateFormatString);\n private String jdbcDrivers;\n private String jdbcURL;\n private String userName;\n private String password;\n private String inputJdbcURL;\n private String inputUserName;\n private String inputPassword;\n private String inputFile;\n private String outputDirectory;\n private boolean tables = false;\n private boolean indexes = false;\n private boolean data = false;\n private static final String nl = System.getProperty(\"line.separator\");\n private boolean verbose = false;\n private boolean jdbcInput = false;\n private boolean jdbcOutput = false;\n private int inputBatchSize = 50;\n private Connection connection;\n private Connection inputConnection;\n\n private FileWriter fileOutput = null;\n\n private SqlQuery sqlQuery;\n private String booleanColumnType;\n private String bigIntColumnType;\n private final HashMap mapTableNameToColumns = new HashMap();\n\n public MondrianFoodMartLoader(String[] args) {\n\n StringBuffer errorMessage = new StringBuffer();\n\n for ( int i=0; i 0) {\n usage();\n throw MondrianResource.instance().newMissingArg(errorMessage.toString());\n }\n }\n\n public void usage() {\n System.out.println(\"Usage: MondrianFoodMartLoader [-verbose] [-tables] [-data] [-indexes] \" +\n \"-jdbcDrivers= \" +\n \"-outputJdbcURL= [-outputJdbcUser=user] [-outputJdbcPassword=password]\" +\n \"[-outputJdbcBatchSize=] \" +\n \"| \" +\n \"[-outputDirectory=] \" +\n \"[\" +\n \" [-inputJdbcURL= [-inputJdbcUser=user] [-inputJdbcPassword=password]]\" +\n \" | \" +\n \" [-inputfile=]\" +\n \"]\");\n System.out.println(\"\");\n System.out.println(\" JDBC connect string for DB\");\n System.out.println(\" [user] JDBC user name for DB\");\n System.out.println(\" [password] JDBC password for user for DB\");\n System.out.println(\" If no source DB parameters are given, assumes data comes from file\");\n System.out.println(\" [file name] file containing test data - INSERT statements in MySQL format\");\n System.out.println(\" If no input file name or input JDBC parameters are given, assume insert statements come from demo/FoodMartCreateData.zip file\");\n System.out.println(\" [outputDirectory] Where FoodMartCreateTables.sql, FoodMartCreateData.sql and FoodMartCreateIndexes.sql will be created\");\n\n System.out.println(\" size of JDBC batch updates - default to 50 inserts\");\n System.out.println(\" Comma-separated list of JDBC drivers.\");\n System.out.println(\" They must be on the classpath.\");\n System.out.println(\" -verbose Verbose mode.\");\n System.out.println(\" -tables If specified, drop and create the tables.\");\n System.out.println(\" -data If specified, load the data.\");\n System.out.println(\" -indexes If specified, drop and create the tables.\");\n }\n\n public static void main(String[] args) {\n System.out.println(\"Starting load at: \" + (new Date()));\n try {\n new MondrianFoodMartLoader(args).load();\n } catch (Throwable e) {\n e.printStackTrace();\n }\n System.out.println(\"Finished load at: \" + (new Date()));\n }\n\n /**\n * Load output from the input, optionally creating tables,\n * populating tables and creating indexes\n *\n * @throws Exception\n */\n private void load() throws Exception {\n RolapUtil.loadDrivers(jdbcDrivers);\n\n if (userName == null) {\n connection = DriverManager.getConnection(jdbcURL);\n } else {\n connection = DriverManager.getConnection(jdbcURL, userName, password);\n }\n\n if (jdbcInput) {\n if (inputUserName == null) {\n inputConnection = DriverManager.getConnection(inputJdbcURL);\n } else {\n inputConnection = DriverManager.getConnection(inputJdbcURL, inputUserName, inputPassword);\n }\n }\n final DatabaseMetaData metaData = connection.getMetaData();\n\n String productName = metaData.getDatabaseProductName();\n String version = metaData.getDatabaseProductVersion();\n\n System.out.println(\"Output connection is \" + productName + \", \" + version);\n\n sqlQuery = new SqlQuery(metaData);\n booleanColumnType = \"SMALLINT\";\n if (sqlQuery.isPostgres()) {\n booleanColumnType = \"BOOLEAN\";\n } else if (sqlQuery.isMySQL()) {\n booleanColumnType = \"BIT\";\n }\n\n bigIntColumnType = \"BIGINT\";\n if (sqlQuery.isOracle()) {\n bigIntColumnType = \"DECIMAL(15,0)\";\n }\n\n try {\n createTables(); // This also initializes mapTableNameToColumns\n if (data) {\n if (jdbcInput) {\n loadDataFromJdbcInput();\n } else {\n loadDataFromFile();\n }\n }\n if (indexes) {\n createIndexes();\n }\n } finally {\n if (connection != null) {\n connection.close();\n connection = null;\n }\n if (inputConnection != null) {\n inputConnection.close();\n inputConnection = null;\n }\n if (fileOutput != null) {\n fileOutput.close();\n fileOutput = null;\n }\n }\n }\n\n /**\n * Parse a file of INSERT statements and output to the configured JDBC\n * connection or another file in the dialect of the target data source.\n *\n * The assumption is that the input INSERT statements are generated\n * by this loader by something like:\n *\n * MondrianFoodLoader\n * -verbose -tables -data -indexes\n * -jdbcDrivers=sun.jdbc.odbc.JdbcOdbcDriver,com.mysql.jdbc.Driver\n * -inputJdbcURL=jdbc:odbc:MondrianFoodMart\n * -outputJdbcURL=jdbc:mysql://localhost/textload?user=root&password=myAdmin\n * -outputDirectory=C:\\Temp\\wip\\Loader-Output\n *\n * @throws Exception\n */\n private void loadDataFromFile() throws Exception {\n InputStream is = openInputStream();\n\n if (is == null) {\n throw new Exception(\"No data file to process\");\n }\n\n try {\n final InputStreamReader reader = new InputStreamReader(is);\n final BufferedReader bufferedReader = new BufferedReader(reader);\n final Pattern mySQLRegex = Pattern.compile(\"INSERT INTO `([^ ]+)` \\\\((.*)\\\\) VALUES\\\\((.*)\\\\);\");\n final Pattern doubleQuoteRegex = Pattern.compile(\"INSERT INTO \\\"([^ ]+)\\\" \\\\((.*)\\\\) VALUES\\\\((.*)\\\\);\");\n String line;\n int lineNumber = 0;\n int tableRowCount = 0;\n String prevTable = \"\";\n String quotedTableName = null;\n String quotedColumnNames = null;\n Column[] orderedColumns = null;\n\n String[] batch = new String[inputBatchSize];\n int batchSize = 0;\n\n Pattern regex = null;\n String quoteChar = null;\n \n while ((line = bufferedReader.readLine()) != null) {\n ++lineNumber;\n if (line.startsWith(\"#\")) {\n continue;\n }\n if (regex == null) {\n \tMatcher m1 = mySQLRegex.matcher(line);\n \tif (m1.matches()) {\n \t\tregex = mySQLRegex;\n \t\tquoteChar = \"`\";\n \t} else {\n \t\tregex = doubleQuoteRegex;\n \t\tquoteChar = \"\\\"\";\n \t}\n }\n // Split the up the line. For example,\n // INSERT INTO `foo` ( `column1`,`column2` ) VALUES (1, 'bar');\n // would yield\n // tableName = \"foo\"\n // columnNames = \" `column1`,`column2` \"\n // values = \"1, 'bar'\"\n final Matcher matcher = regex.matcher(line);\n if (!matcher.matches()) {\n throw MondrianResource.instance().newInvalidInsertLine(\n new Integer(lineNumber), line);\n }\n String tableName = matcher.group(1); // e.g. \"foo\"\n String columnNames = matcher.group(2);\n String values = matcher.group(3);\n\n // If table just changed, flush the previous batch.\n if (!tableName.equals(prevTable)) {\n if (!prevTable.equals(\"\")) {\n System.out.println(\"Table \" + prevTable +\n \": loaded \" + tableRowCount + \" rows.\");\n }\n tableRowCount = 0;\n writeBatch(batch, batchSize);\n batchSize = 0;\n prevTable = tableName;\n quotedTableName = quoteId(tableName);\n quotedColumnNames = columnNames.replaceAll(quoteChar, \n \t\t\t\t\t\t\t\t\tsqlQuery.getQuoteIdentifierString());\n String[] splitColumnNames = columnNames.replaceAll(quoteChar, \"\")\n \t\t\t\t\t\t.replaceAll(\" \", \"\").split(\",\");\n Column[] columns = (Column[]) mapTableNameToColumns.get(tableName);\n\n orderedColumns = new Column[columns.length];\n\n for (int i = 0; i < splitColumnNames.length; i++) {\n Column thisColumn = null;\n for (int j = 0; j < columns.length && thisColumn == null; j++) {\n if (columns[j].name.equalsIgnoreCase(splitColumnNames[i])) {\n thisColumn = columns[j];\n }\n }\n if (thisColumn == null) {\n throw new Exception(\"Unknown column in INSERT statement from file: \" + splitColumnNames[i]);\n } else {\n orderedColumns[i] = thisColumn;\n }\n }\n\n\n }\n\n StringBuffer massagedLine = new StringBuffer();\n\n massagedLine\n .append(\"INSERT INTO \")\n .append(quotedTableName)\n .append(\" (\")\n .append(quotedColumnNames)\n .append(\" ) VALUES(\")\n .append(getMassagedValues(orderedColumns, values))\n .append(\" )\");\n\n line = massagedLine.toString();\n\n ++tableRowCount;\n\n batch[batchSize++] = line;\n if (batchSize >= inputBatchSize) {\n writeBatch(batch, batchSize);\n batchSize = 0;\n }\n }\n // Print summary of the final table.\n if (!prevTable.equals(\"\")) {\n System.out.println(\"Table \" + prevTable +\n \": loaded \" + tableRowCount + \" rows.\");\n tableRowCount = 0;\n writeBatch(batch, batchSize);\n batchSize = 0;\n }\n } finally {\n if (is != null) {\n is.close();\n }\n }\n }\n\n /**\n * @param splitColumnNames the individual column names in the same order as the values\n * @param columns column metadata for the table\n * @param values the contents of the INSERT VALUES clause ie. \"34,67.89,'GHt''ab'\". These are in MySQL form.\n * @return String values for the destination dialect\n * @throws Exception\n */\n private String getMassagedValues(Column[] columns, String values) throws Exception {\n StringBuffer sb = new StringBuffer();\n\n // Get the values out as individual elements\n // Split the string at commas, and cope with embedded commas\n String[] individualValues = new String[columns.length];\n\n String[] splitValues = values.split(\",\");\n\n // If these 2 are the same length, then there are no embedded commas\n\n if (splitValues.length == columns.length) {\n individualValues = splitValues;\n } else {\n // \"34,67.89,'GH,t''a,b'\" => { \"34\", \"67.89\", \"'GH\", \"t''a\", \"b'\"\n int valuesPos = 0;\n boolean inQuote = false;\n for (int i = 0; i < splitValues.length; i++) {\n if (i == 0) {\n individualValues[valuesPos] = splitValues[i];\n inQuote = inQuote(splitValues[i], inQuote);\n } else {\n // at end\n if (inQuote) {\n individualValues[valuesPos] = individualValues[valuesPos] + \",\" + splitValues[i];\n inQuote = inQuote(splitValues[i], inQuote);\n } else {\n valuesPos++;\n individualValues[valuesPos] = splitValues[i];\n inQuote = inQuote(splitValues[i], inQuote);\n }\n }\n }\n\n assert(valuesPos + 1 == columns.length);\n }\n\n for (int i = 0; i < columns.length; i++) {\n if (i > 0) {\n sb.append(\",\");\n }\n String value = individualValues[i];\n if (value != null && value.trim().equals(\"NULL\")) {\n value = null;\n }\n sb.append(columnValue(value, columns[i]));\n }\n return sb.toString();\n\n }\n\n private boolean inQuote(String str, boolean nowInQuote) {\n if (str.indexOf('\\'') == -1) {\n // No quote, so stay the same\n return nowInQuote;\n }\n int lastPos = 0;\n while (lastPos <= str.length() && str.indexOf('\\'', lastPos) != -1) {\n int pos = str.indexOf('\\'', lastPos);\n nowInQuote = !nowInQuote;\n lastPos = pos + 1;\n }\n return nowInQuote;\n }\n\n private void loadDataFromJdbcInput() throws Exception {\n if (outputDirectory != null) {\n fileOutput = new FileWriter(new File(outputDirectory, \"createData.sql\"));\n }\n\n /*\n * For each input table,\n * read specified columns for all rows in the input connection\n *\n * For each row, insert a row\n */\n\n for (Iterator it = mapTableNameToColumns.entrySet().iterator(); it.hasNext(); ) {\n Map.Entry tableEntry = (Map.Entry) it.next();\n int rowsAdded = loadTable((String) tableEntry.getKey(), (Column[]) tableEntry.getValue());\n System.out.println(\"Table \" + (String) tableEntry.getKey() +\n \": loaded \" + rowsAdded + \" rows.\");\n }\n\n if (outputDirectory != null) {\n fileOutput.close();\n }\n }\n\n /**\n * Read the given table from the input RDBMS and output to destination\n * RDBMS or file\n *\n * @param name name of table\n * @param columns columns to be read/output\n * @return #rows inserted\n * @throws Exception\n */\n private int loadTable(String name, Column[] columns) throws Exception {\n int rowsAdded = 0;\n StringBuffer buf = new StringBuffer();\n\n buf.append(\"select \");\n for (int i = 0; i < columns.length; i++) {\n Column column = columns[i];\n if (i > 0) {\n buf.append(\",\");\n }\n buf.append(quoteId(column.name));\n }\n buf.append(\" from \")\n .append(quoteId(name));\n String ddl = buf.toString();\n Statement statement = inputConnection.createStatement();\n if (verbose) {\n System.out.println(\"Input table SQL: \" + ddl);\n }\n ResultSet rs = statement.executeQuery(ddl);\n\n String[] batch = new String[inputBatchSize];\n int batchSize = 0;\n boolean displayedInsert = false;\n\n while (rs.next()) {\n /*\n * Get a batch of insert statements, then save a batch\n */\n\n String insertStatement = createInsertStatement(rs, name, columns);\n if (!displayedInsert && verbose) {\n System.out.println(\"Example Insert statement: \" + insertStatement);\n displayedInsert = true;\n }\n batch[batchSize++] = insertStatement;\n if (batchSize >= inputBatchSize) {\n rowsAdded += writeBatch(batch, batchSize);\n batchSize = 0;\n }\n }\n\n if (batchSize > 0) {\n rowsAdded += writeBatch(batch, batchSize);\n }\n\n return rowsAdded;\n }\n\n /**\n * Create a SQL INSERT statement in the dialect of the output RDBMS.\n *\n * @param rs ResultSet of input RDBMS\n * @param name name of table\n * @param columns column definitions for INSERT statement\n * @return String the INSERT statement\n * @throws Exception\n */\n private String createInsertStatement(ResultSet rs, String name, Column[] columns) throws Exception {\n StringBuffer buf = new StringBuffer();\n\n buf.append(\"INSERT INTO \")\n .append(quoteId(name))\n .append(\" ( \");\n for (int i = 0; i < columns.length; i++) {\n Column column = columns[i];\n if (i > 0) {\n buf.append(\",\");\n }\n buf.append(quoteId(column.name));\n }\n buf.append(\" ) VALUES(\");\n for (int i = 0; i < columns.length; i++) {\n Column column = columns[i];\n if (i > 0) {\n buf.append(\",\");\n }\n buf.append(columnValue(rs, column));\n }\n buf.append(\" )\");\n return buf.toString();\n }\n\n /**\n * If we are outputting to JDBC,\n * Execute the given set of SQL statements\n *\n * Otherwise,\n * output the statements to a file.\n *\n * @param batch SQL statements to execute\n * @param batchSize # SQL statements to execute\n * @return # SQL statements executed\n * @throws IOException\n * @throws SQLException\n */\n private int writeBatch(String[] batch, int batchSize) throws IOException, SQLException {\n if (outputDirectory != null) {\n for (int i = 0; i < batchSize; i++) {\n fileOutput.write(batch[i]);\n fileOutput.write(\";\\n\");\n }\n } else {\n connection.setAutoCommit(false);\n Statement stmt = connection.createStatement();\n if (batchSize == 1) {\n // Don't use batching if there's only one item. This allows\n // us to work around bugs in the JDBC driver by setting\n // outputJdbcBatchSize=1.\n stmt.execute(batch[0]);\n } else {\n for (int i = 0; i < batchSize; i++) {\n stmt.addBatch(batch[i]);\n }\n int [] updateCounts = null;\n\n try {\n updateCounts = stmt.executeBatch();\n } catch (SQLException e) {\n for (int i = 0; i < batchSize; i++) {\n System.out.println(\"Error in SQL batch: \" + batch[i]);\n }\n throw e;\n }\n int updates = 0;\n for (int i = 0; i < updateCounts.length; updates += updateCounts[i], i++) {\n if (updateCounts[i] == 0) {\n System.out.println(\"Error in SQL: \" + batch[i]);\n }\n }\n if (updates < batchSize) {\n throw new RuntimeException(\"Failed to execute batch: \" + batchSize + \" versus \" + updates);\n }\n }\n stmt.close();\n connection.setAutoCommit(true);\n }\n return batchSize;\n }\n\n /**\n * Open the file of INSERT statements to load the data. Default\n * file name is ./demo/FoodMartCreateData.zip\n *\n * @return FileInputStream\n */\n private InputStream openInputStream() throws Exception {\n final String defaultZipFileName = \"FoodMartCreateData.zip\";\n final String defaultDataFileName = \"FoodMartCreateData.sql\";\n final File file = (inputFile != null) ? new File(inputFile) : new File(\"demo\", defaultZipFileName);\n if (!file.exists()) {\n System.out.println(\"No input file: \" + file);\n return null;\n }\n if (file.getName().toLowerCase().endsWith(\".zip\")) {\n ZipFile zippedData = new ZipFile(file);\n ZipEntry entry = zippedData.getEntry(defaultDataFileName);\n return zippedData.getInputStream(entry);\n } else {\n return new FileInputStream(file);\n }\n }\n\n /**\n * Create all indexes for the FoodMart database\n *\n * @throws Exception\n */\n private void createIndexes() throws Exception {\n if (outputDirectory != null) {\n fileOutput = new FileWriter(new File(outputDirectory, \"createIndexes.sql\"));\n }\n\n createIndex(true, \"account\", \"i_account_id\", new String[] {\"account_id\"});\n createIndex(false, \"account\", \"i_account_parent\", new String[] {\"account_parent\"});\n createIndex(true, \"category\", \"i_category_id\", new String[] {\"category_id\"});\n createIndex(false, \"category\", \"i_category_parent\", new String[] {\"category_parent\"});\n createIndex(true, \"currency\", \"i_currency\", new String[] {\"currency_id\", \"date\"});\n createIndex(false, \"customer\", \"i_cust_acct_num\", new String[] {\"account_num\"});\n createIndex(false, \"customer\", \"i_customer_fname\", new String[] {\"fname\"});\n createIndex(false, \"customer\", \"i_customer_lname\", new String[] {\"lname\"});\n createIndex(false, \"customer\", \"i_cust_child_home\", new String[] {\"num_children_at_home\"});\n createIndex(true, \"customer\", \"i_customer_id\", new String[] {\"customer_id\"});\n createIndex(false, \"customer\", \"i_cust_postal_code\", new String[] {\"postal_code\"});\n createIndex(false, \"customer\", \"i_cust_region_id\", new String[] {\"customer_region_id\"});\n createIndex(true, \"department\", \"i_department_id\", new String[] {\"department_id\"});\n createIndex(true, \"employee\", \"i_employee_id\", new String[] {\"employee_id\"});\n createIndex(false, \"employee\", \"i_empl_dept_id\", new String[] {\"department_id\"});\n createIndex(false, \"employee\", \"i_empl_store_id\", new String[] {\"store_id\"});\n createIndex(false, \"employee\", \"i_empl_super_id\", new String[] {\"supervisor_id\"});\n createIndex(true, \"employee_closure\", \"i_empl_closure\", new String[] {\"supervisor_id\", \"employee_id\"});\n createIndex(false, \"employee_closure\", \"i_empl_closure_emp\", new String[] {\"employee_id\"});\n createIndex(false, \"expense_fact\", \"i_expense_store_id\", new String[] {\"store_id\"});\n createIndex(false, \"expense_fact\", \"i_expense_acct_id\", new String[] {\"account_id\"});\n createIndex(false, \"expense_fact\", \"i_expense_time_id\", new String[] {\"time_id\"});\n createIndex(false, \"inventory_fact_1997\", \"i_inv_97_prod_id\", new String[] {\"product_id\"});\n createIndex(false, \"inventory_fact_1997\", \"i_inv_97_store_id\", new String[] {\"store_id\"});\n createIndex(false, \"inventory_fact_1997\", \"i_inv_97_time_id\", new String[] {\"time_id\"});\n createIndex(false, \"inventory_fact_1997\", \"i_inv_97_wrhse_id\", new String[] {\"warehouse_id\"});\n createIndex(false, \"inventory_fact_1998\", \"i_inv_98_prod_id\", new String[] {\"product_id\"});\n createIndex(false, \"inventory_fact_1998\", \"i_inv_98_store_id\", new String[] {\"store_id\"});\n createIndex(false, \"inventory_fact_1998\", \"i_inv_98_time_id\", new String[] {\"time_id\"});\n createIndex(false, \"inventory_fact_1998\", \"i_inv_98_wrhse_id\", new String[] {\"warehouse_id\"});\n createIndex(true, \"position\", \"i_position_id\", new String[] {\"position_id\"});\n createIndex(false, \"product\", \"i_prod_brand_name\", new String[] {\"brand_name\"});\n createIndex(true, \"product\", \"i_product_id\", new String[] {\"product_id\"});\n createIndex(false, \"product\", \"i_prod_class_id\", new String[] {\"product_class_id\"});\n createIndex(false, \"product\", \"i_product_name\", new String[] {\"product_name\"});\n createIndex(false, \"product\", \"i_product_SKU\", new String[] {\"SKU\"});\n createIndex(true, \"promotion\", \"i_promotion_id\", new String[] {\"promotion_id\"});\n createIndex(false, \"promotion\", \"i_promo_dist_id\", new String[] {\"promotion_district_id\"});\n createIndex(true, \"reserve_employee\", \"i_rsrv_empl_id\", new String[] {\"employee_id\"});\n createIndex(false, \"reserve_employee\", \"i_rsrv_empl_dept\", new String[] {\"department_id\"});\n createIndex(false, \"reserve_employee\", \"i_rsrv_empl_store\", new String[] {\"store_id\"});\n createIndex(false, \"reserve_employee\", \"i_rsrv_empl_sup\", new String[] {\"supervisor_id\"});\n createIndex(false, \"salary\", \"i_salary_pay_date\", new String[] {\"pay_date\"});\n createIndex(false, \"salary\", \"i_salary_employee\", new String[] {\"employee_id\"});\n createIndex(false, \"sales_fact_1997\", \"i_sls_97_cust_id\", new String[] {\"customer_id\"});\n createIndex(false, \"sales_fact_1997\", \"i_sls_97_prod_id\", new String[] {\"product_id\"});\n createIndex(false, \"sales_fact_1997\", \"i_sls_97_promo_id\", new String[] {\"promotion_id\"});\n createIndex(false, \"sales_fact_1997\", \"i_sls_97_store_id\", new String[] {\"store_id\"});\n createIndex(false, \"sales_fact_1997\", \"i_sls_97_time_id\", new String[] {\"time_id\"});\n createIndex(false, \"sales_fact_dec_1998\", \"i_sls_dec98_cust\", new String[] {\"customer_id\"});\n createIndex(false, \"sales_fact_dec_1998\", \"i_sls_dec98_prod\", new String[] {\"product_id\"});\n createIndex(false, \"sales_fact_dec_1998\", \"i_sls_dec98_promo\", new String[] {\"promotion_id\"});\n createIndex(false, \"sales_fact_dec_1998\", \"i_sls_dec98_store\", new String[] {\"store_id\"});\n createIndex(false, \"sales_fact_dec_1998\", \"i_sls_dec98_time\", new String[] {\"time_id\"});\n createIndex(false, \"sales_fact_1998\", \"i_sls_98_cust_id\", new String[] {\"customer_id\"});\n createIndex(false, \"sales_fact_1998\", \"i_sls_1998_prod_id\", new String[] {\"product_id\"});\n createIndex(false, \"sales_fact_1998\", \"i_sls_1998_promo\", new String[] {\"promotion_id\"});\n createIndex(false, \"sales_fact_1998\", \"i_sls_1998_store\", new String[] {\"store_id\"});\n createIndex(false, \"sales_fact_1998\", \"i_sls_1998_time_id\", new String[] {\"time_id\"});\n createIndex(true, \"store\", \"i_store_id\", new String[] {\"store_id\"});\n createIndex(false, \"store\", \"i_store_region_id\", new String[] {\"region_id\"});\n createIndex(true, \"store_ragged\", \"i_store_raggd_id\", new String[] {\"store_id\"});\n createIndex(false, \"store_ragged\", \"i_store_rggd_reg\", new String[] {\"region_id\"});\n createIndex(true, \"time_by_day\", \"i_time_id\", new String[] {\"time_id\"});\n createIndex(true, \"time_by_day\", \"i_time_day\", new String[] {\"the_date\"});\n createIndex(false, \"time_by_day\", \"i_time_year\", new String[] {\"the_year\"});\n createIndex(false, \"time_by_day\", \"i_time_quarter\", new String[] {\"quarter\"});\n createIndex(false, \"time_by_day\", \"i_time_month\", new String[] {\"month_of_year\"});\n\n if (outputDirectory != null) {\n fileOutput.close();\n }\n }\n\n /**\n *\n * If we are outputting to JDBC,\n * Execute the CREATE INDEX statement\n *\n * Otherwise,\n * output the statement to a file.\n *\n * @param isUnique\n * @param tableName\n * @param indexName\n * @param columnNames\n */\n private void createIndex(\n boolean isUnique,\n String tableName,\n String indexName,\n String[] columnNames)\n {\n try {\n StringBuffer buf = new StringBuffer();\n if (jdbcOutput) {\n try {\n buf.append(\"DROP INDEX \")\n .append(quoteId(indexName));\n if (sqlQuery.isMySQL()) {\n buf.append(\" ON \")\n .append(quoteId(tableName));\n }\n final String deleteDDL = buf.toString();\n executeDDL(deleteDDL);\n } catch (Exception e1) {\n System.out.println(\"Drop failed: but continue\");\n }\n }\n\n buf = new StringBuffer();\n buf.append(isUnique ? \"CREATE UNIQUE INDEX \" : \"CREATE INDEX \")\n .append(quoteId(indexName)).append(\" ON \")\n .append(quoteId(tableName)).append(\" (\");\n for (int i = 0; i < columnNames.length; i++) {\n String columnName = columnNames[i];\n if (i > 0) {\n buf.append(\", \");\n }\n buf.append(quoteId(columnName));\n }\n buf.append(\")\");\n final String createDDL = buf.toString();\n executeDDL(createDDL);\n } catch (Exception e) {\n throw MondrianResource.instance().newCreateIndexFailed(indexName,\n tableName, e);\n }\n }\n\n /**\n * Define all tables for the FoodMart database.\n *\n * Also initializes mapTableNameToColumns\n *\n * @throws Exception\n */\n private void createTables() throws Exception {\n if (outputDirectory != null) {\n fileOutput = new FileWriter(new File(outputDirectory, \"createTables.sql\"));\n }\n\n createTable(\"sales_fact_1997\", new Column[] {\n new Column(\"product_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"time_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"customer_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"promotion_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"store_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"store_sales\", \"DECIMAL(10,4)\", \"NOT NULL\"),\n new Column(\"store_cost\", \"DECIMAL(10,4)\", \"NOT NULL\"),\n new Column(\"unit_sales\", \"DECIMAL(10,4)\", \"NOT NULL\"),\n });\n createTable(\"sales_fact_1998\", new Column[] {\n new Column(\"product_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"time_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"customer_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"promotion_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"store_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"store_sales\", \"DECIMAL(10,4)\", \"NOT NULL\"),\n new Column(\"store_cost\", \"DECIMAL(10,4)\", \"NOT NULL\"),\n new Column(\"unit_sales\", \"DECIMAL(10,4)\", \"NOT NULL\"),\n });\n createTable(\"sales_fact_dec_1998\", new Column[] {\n new Column(\"product_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"time_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"customer_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"promotion_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"store_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"store_sales\", \"DECIMAL(10,4)\", \"NOT NULL\"),\n new Column(\"store_cost\", \"DECIMAL(10,4)\", \"NOT NULL\"),\n new Column(\"unit_sales\", \"DECIMAL(10,4)\", \"NOT NULL\"),\n });\n createTable(\"inventory_fact_1997\", new Column[] {\n new Column(\"product_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"time_id\", \"INTEGER\", \"\"),\n new Column(\"warehouse_id\", \"INTEGER\", \"\"),\n new Column(\"store_id\", \"INTEGER\", \"\"),\n new Column(\"units_ordered\", \"INTEGER\", \"\"),\n new Column(\"units_shipped\", \"INTEGER\", \"\"),\n new Column(\"warehouse_sales\", \"DECIMAL(10,4)\", \"\"),\n new Column(\"warehouse_cost\", \"DECIMAL(10,4)\", \"\"),\n new Column(\"supply_time\", \"SMALLINT\", \"\"),\n new Column(\"store_invoice\", \"DECIMAL(10,4)\", \"\"),\n });\n createTable(\"inventory_fact_1998\", new Column[] {\n new Column(\"product_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"time_id\", \"INTEGER\", \"\"),\n new Column(\"warehouse_id\", \"INTEGER\", \"\"),\n new Column(\"store_id\", \"INTEGER\", \"\"),\n new Column(\"units_ordered\", \"INTEGER\", \"\"),\n new Column(\"units_shipped\", \"INTEGER\", \"\"),\n new Column(\"warehouse_sales\", \"DECIMAL(10,4)\", \"\"),\n new Column(\"warehouse_cost\", \"DECIMAL(10,4)\", \"\"),\n new Column(\"supply_time\", \"SMALLINT\", \"\"),\n new Column(\"store_invoice\", \"DECIMAL(10,4)\", \"\"),\n });\n createTable(\"currency\", new Column[] {\n new Column(\"currency_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"date\", \"DATE\", \"NOT NULL\"),\n new Column(\"currency\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"conversion_ratio\", \"DECIMAL(10,4)\", \"NOT NULL\"),\n });\n createTable(\"account\", new Column[] {\n new Column(\"account_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"account_parent\", \"INTEGER\", \"\"),\n new Column(\"account_description\", \"VARCHAR(30)\", \"\"),\n new Column(\"account_type\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"account_rollup\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"Custom_Members\", \"VARCHAR(255)\", \"\"),\n });\n createTable(\"category\", new Column[] {\n new Column(\"category_id\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"category_parent\", \"VARCHAR(30)\", \"\"),\n new Column(\"category_description\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"category_rollup\", \"VARCHAR(30)\", \"\"),\n });\n createTable(\"customer\", new Column[] {\n new Column(\"customer_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"account_num\", bigIntColumnType, \"NOT NULL\"),\n new Column(\"lname\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"fname\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"mi\", \"VARCHAR(30)\", \"\"),\n new Column(\"address1\", \"VARCHAR(30)\", \"\"),\n new Column(\"address2\", \"VARCHAR(30)\", \"\"),\n new Column(\"address3\", \"VARCHAR(30)\", \"\"),\n new Column(\"address4\", \"VARCHAR(30)\", \"\"),\n new Column(\"city\", \"VARCHAR(30)\", \"\"),\n new Column(\"state_province\", \"VARCHAR(30)\", \"\"),\n new Column(\"postal_code\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"country\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"customer_region_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"phone1\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"phone2\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"birthdate\", \"DATE\", \"NOT NULL\"),\n new Column(\"marital_status\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"yearly_income\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"gender\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"total_children\", \"SMALLINT\", \"NOT NULL\"),\n new Column(\"num_children_at_home\", \"SMALLINT\", \"NOT NULL\"),\n new Column(\"education\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"date_accnt_opened\", \"DATE\", \"NOT NULL\"),\n new Column(\"member_card\", \"VARCHAR(30)\", \"\"),\n new Column(\"occupation\", \"VARCHAR(30)\", \"\"),\n new Column(\"houseowner\", \"VARCHAR(30)\", \"\"),\n new Column(\"num_cars_owned\", \"INTEGER\", \"\"),\n new Column(\"fullname\", \"VARCHAR(60)\", \"NOT NULL\"),\n });\n createTable(\"days\", new Column[] {\n new Column(\"day\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"week_day\", \"VARCHAR(30)\", \"NOT NULL\"),\n });\n createTable(\"department\", new Column[] {\n new Column(\"department_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"department_description\", \"VARCHAR(30)\", \"NOT NULL\"),\n });\n createTable(\"employee\", new Column[] {\n new Column(\"employee_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"full_name\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"first_name\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"last_name\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"position_id\", \"INTEGER\", \"\"),\n new Column(\"position_title\", \"VARCHAR(30)\", \"\"),\n new Column(\"store_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"department_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"birth_date\", \"DATE\", \"NOT NULL\"),\n new Column(\"hire_date\", \"TIMESTAMP\", \"\"),\n new Column(\"end_date\", \"TIMESTAMP\", \"\"),\n new Column(\"salary\", \"DECIMAL(10,4)\", \"NOT NULL\"),\n new Column(\"supervisor_id\", \"INTEGER\", \"\"),\n new Column(\"education_level\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"marital_status\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"gender\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"management_role\", \"VARCHAR(30)\", \"\"),\n });\n createTable(\"employee_closure\", new Column[] {\n new Column(\"employee_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"supervisor_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"distance\", \"INTEGER\", \"\"),\n });\n createTable(\"expense_fact\", new Column[] {\n new Column(\"store_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"account_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"exp_date\", \"TIMESTAMP\", \"NOT NULL\"),\n new Column(\"time_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"category_id\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"currency_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"amount\", \"DECIMAL(10,4)\", \"NOT NULL\"),\n });\n createTable(\"position\", new Column[] {\n new Column(\"position_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"position_title\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"pay_type\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"min_scale\", \"DECIMAL(10,4)\", \"NOT NULL\"),\n new Column(\"max_scale\", \"DECIMAL(10,4)\", \"NOT NULL\"),\n new Column(\"management_role\", \"VARCHAR(30)\", \"NOT NULL\"),\n });\n createTable(\"product\", new Column[] {\n new Column(\"product_class_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"product_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"brand_name\", \"VARCHAR(60)\", \"\"),\n new Column(\"product_name\", \"VARCHAR(60)\", \"NOT NULL\"),\n new Column(\"SKU\", bigIntColumnType, \"NOT NULL\"),\n new Column(\"SRP\", \"DECIMAL(10,4)\", \"\"),\n new Column(\"gross_weight\", \"REAL\", \"\"),\n new Column(\"net_weight\", \"REAL\", \"\"),\n new Column(\"recyclable_package\", booleanColumnType, \"\"),\n new Column(\"low_fat\", booleanColumnType, \"\"),\n new Column(\"units_per_case\", \"SMALLINT\", \"\"),\n new Column(\"cases_per_pallet\", \"SMALLINT\", \"\"),\n new Column(\"shelf_width\", \"REAL\", \"\"),\n new Column(\"shelf_height\", \"REAL\", \"\"),\n new Column(\"shelf_depth\", \"REAL\", \"\"),\n });\n createTable(\"product_class\", new Column[] {\n new Column(\"product_class_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"product_subcategory\", \"VARCHAR(30)\", \"\"),\n new Column(\"product_category\", \"VARCHAR(30)\", \"\"),\n new Column(\"product_department\", \"VARCHAR(30)\", \"\"),\n new Column(\"product_family\", \"VARCHAR(30)\", \"\"),\n });\n createTable(\"promotion\", new Column[] {\n new Column(\"promotion_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"promotion_district_id\", \"INTEGER\", \"\"),\n new Column(\"promotion_name\", \"VARCHAR(30)\", \"\"),\n new Column(\"media_type\", \"VARCHAR(30)\", \"\"),\n new Column(\"cost\", \"DECIMAL(10,4)\", \"\"),\n new Column(\"start_date\", \"TIMESTAMP\", \"\"),\n new Column(\"end_date\", \"TIMESTAMP\", \"\"),\n });\n createTable(\"region\", new Column[] {\n new Column(\"region_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"sales_city\", \"VARCHAR(30)\", \"\"),\n new Column(\"sales_state_province\", \"VARCHAR(30)\", \"\"),\n new Column(\"sales_district\", \"VARCHAR(30)\", \"\"),\n new Column(\"sales_region\", \"VARCHAR(30)\", \"\"),\n new Column(\"sales_country\", \"VARCHAR(30)\", \"\"),\n new Column(\"sales_district_id\", \"INTEGER\", \"\"),\n });\n createTable(\"reserve_employee\", new Column[] {\n new Column(\"employee_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"full_name\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"first_name\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"last_name\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"position_id\", \"INTEGER\", \"\"),\n new Column(\"position_title\", \"VARCHAR(30)\", \"\"),\n new Column(\"store_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"department_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"birth_date\", \"TIMESTAMP\", \"NOT NULL\"),\n new Column(\"hire_date\", \"TIMESTAMP\", \"\"),\n new Column(\"end_date\", \"TIMESTAMP\", \"\"),\n new Column(\"salary\", \"DECIMAL(10,4)\", \"NOT NULL\"),\n new Column(\"supervisor_id\", \"INTEGER\", \"\"),\n new Column(\"education_level\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"marital_status\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"gender\", \"VARCHAR(30)\", \"NOT NULL\"),\n });\n createTable(\"salary\", new Column[] {\n new Column(\"pay_date\", \"TIMESTAMP\", \"NOT NULL\"),\n new Column(\"employee_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"department_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"currency_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"salary_paid\", \"DECIMAL(10,4)\", \"NOT NULL\"),\n new Column(\"overtime_paid\", \"DECIMAL(10,4)\", \"NOT NULL\"),\n new Column(\"vacation_accrued\", \"REAL\", \"NOT NULL\"),\n new Column(\"vacation_used\", \"REAL\", \"NOT NULL\"),\n });\n createTable(\"store\", new Column[] {\n new Column(\"store_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"store_type\", \"VARCHAR(30)\", \"\"),\n new Column(\"region_id\", \"INTEGER\", \"\"),\n new Column(\"store_name\", \"VARCHAR(30)\", \"\"),\n new Column(\"store_number\", \"INTEGER\", \"\"),\n new Column(\"store_street_address\", \"VARCHAR(30)\", \"\"),\n new Column(\"store_city\", \"VARCHAR(30)\", \"\"),\n new Column(\"store_state\", \"VARCHAR(30)\", \"\"),\n new Column(\"store_postal_code\", \"VARCHAR(30)\", \"\"),\n new Column(\"store_country\", \"VARCHAR(30)\", \"\"),\n new Column(\"store_manager\", \"VARCHAR(30)\", \"\"),\n new Column(\"store_phone\", \"VARCHAR(30)\", \"\"),\n new Column(\"store_fax\", \"VARCHAR(30)\", \"\"),\n new Column(\"first_opened_date\", \"TIMESTAMP\", \"\"),\n new Column(\"last_remodel_date\", \"TIMESTAMP\", \"\"),\n new Column(\"store_sqft\", \"INTEGER\", \"\"),\n new Column(\"grocery_sqft\", \"INTEGER\", \"\"),\n new Column(\"frozen_sqft\", \"INTEGER\", \"\"),\n new Column(\"meat_sqft\", \"INTEGER\", \"\"),\n new Column(\"coffee_bar\", booleanColumnType, \"\"),\n new Column(\"video_store\", booleanColumnType, \"\"),\n new Column(\"salad_bar\", booleanColumnType, \"\"),\n new Column(\"prepared_food\", booleanColumnType, \"\"),\n new Column(\"florist\", booleanColumnType, \"\"),\n });\n createTable(\"store_ragged\", new Column[] {\n new Column(\"store_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"store_type\", \"VARCHAR(30)\", \"\"),\n new Column(\"region_id\", \"INTEGER\", \"\"),\n new Column(\"store_name\", \"VARCHAR(30)\", \"\"),\n new Column(\"store_number\", \"INTEGER\", \"\"),\n new Column(\"store_street_address\", \"VARCHAR(30)\", \"\"),\n new Column(\"store_city\", \"VARCHAR(30)\", \"\"),\n new Column(\"store_state\", \"VARCHAR(30)\", \"\"),\n new Column(\"store_postal_code\", \"VARCHAR(30)\", \"\"),\n new Column(\"store_country\", \"VARCHAR(30)\", \"\"),\n new Column(\"store_manager\", \"VARCHAR(30)\", \"\"),\n new Column(\"store_phone\", \"VARCHAR(30)\", \"\"),\n new Column(\"store_fax\", \"VARCHAR(30)\", \"\"),\n new Column(\"first_opened_date\", \"TIMESTAMP\", \"\"),\n new Column(\"last_remodel_date\", \"TIMESTAMP\", \"\"),\n new Column(\"store_sqft\", \"INTEGER\", \"\"),\n new Column(\"grocery_sqft\", \"INTEGER\", \"\"),\n new Column(\"frozen_sqft\", \"INTEGER\", \"\"),\n new Column(\"meat_sqft\", \"INTEGER\", \"\"),\n new Column(\"coffee_bar\", booleanColumnType, \"\"),\n new Column(\"video_store\", booleanColumnType, \"\"),\n new Column(\"salad_bar\", booleanColumnType, \"\"),\n new Column(\"prepared_food\", booleanColumnType, \"\"),\n new Column(\"florist\", booleanColumnType, \"\"),\n });\n createTable(\"time_by_day\", new Column[] {\n new Column(\"time_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"the_date\", \"TIMESTAMP\", \"\"),\n new Column(\"the_day\", \"VARCHAR(30)\", \"\"),\n new Column(\"the_month\", \"VARCHAR(30)\", \"\"),\n new Column(\"the_year\", \"SMALLINT\", \"\"),\n new Column(\"day_of_month\", \"SMALLINT\", \"\"),\n new Column(\"week_of_year\", \"INTEGER\", \"\"),\n new Column(\"month_of_year\", \"SMALLINT\", \"\"),\n new Column(\"quarter\", \"VARCHAR(30)\", \"\"),\n new Column(\"fiscal_period\", \"VARCHAR(30)\", \"\"),\n });\n createTable(\"warehouse\", new Column[] {\n new Column(\"warehouse_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"warehouse_class_id\", \"INTEGER\", \"\"),\n new Column(\"stores_id\", \"INTEGER\", \"\"),\n new Column(\"warehouse_name\", \"VARCHAR(60)\", \"\"),\n new Column(\"wa_address1\", \"VARCHAR(30)\", \"\"),\n new Column(\"wa_address2\", \"VARCHAR(30)\", \"\"),\n new Column(\"wa_address3\", \"VARCHAR(30)\", \"\"),\n new Column(\"wa_address4\", \"VARCHAR(30)\", \"\"),\n new Column(\"warehouse_city\", \"VARCHAR(30)\", \"\"),\n new Column(\"warehouse_state_province\", \"VARCHAR(30)\", \"\"),\n new Column(\"warehouse_postal_code\", \"VARCHAR(30)\", \"\"),\n new Column(\"warehouse_country\", \"VARCHAR(30)\", \"\"),\n new Column(\"warehouse_owner_name\", \"VARCHAR(30)\", \"\"),\n new Column(\"warehouse_phone\", \"VARCHAR(30)\", \"\"),\n new Column(\"warehouse_fax\", \"VARCHAR(30)\", \"\"),\n });\n createTable(\"warehouse_class\", new Column[] {\n new Column(\"warehouse_class_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"description\", \"VARCHAR(30)\", \"\"),\n });\n if (outputDirectory != null) {\n fileOutput.close();\n }\n }\n\n /**\n * If we are outputting to JDBC, and not creating tables, delete all rows.\n *\n * Otherwise:\n *\n * Generate the SQL CREATE TABLE statement.\n *\n * If we are outputting to JDBC,\n * Execute a DROP TABLE statement\n * Execute the CREATE TABLE statement\n *\n * Otherwise,\n * output the statement to a file.\n *\n * @param name\n * @param columns\n */\n private void createTable(String name, Column[] columns) {\n try {\n // Define the table.\n mapTableNameToColumns.put(name, columns);\n if (!tables) {\n if (data && jdbcOutput) {\n // We're going to load the data without [re]creating\n // the table, so let's remove the data.\n try {\n executeDDL(\"DELETE FROM \" + quoteId(name));\n } catch (SQLException e) {\n throw MondrianResource.instance().newCreateTableFailed(name, e);\n }\n }\n return;\n }\n // If table does not exist, that is OK\n try {\n \texecuteDDL(\"DROP TABLE \" + quoteId(name));\n } catch (Exception e) {\n \tif (verbose) {\n \t\tSystem.out.println(\"Drop of \" + name + \" failed. Ignored\");\n \t}\n }\n StringBuffer buf = new StringBuffer();\n buf.append(\"CREATE TABLE \").append(quoteId(name)).append(\"(\");\n for (int i = 0; i < columns.length; i++) {\n Column column = columns[i];\n if (i > 0) {\n buf.append(\",\");\n }\n buf.append(nl);\n buf.append(\" \").append(quoteId(column.name)).append(\" \")\n .append(column.type);\n if (!column.constraint.equals(\"\")) {\n buf.append(\" \").append(column.constraint);\n }\n }\n buf.append(\")\");\n final String ddl = buf.toString();\n executeDDL(ddl);\n } catch (Exception e) {\n throw MondrianResource.instance().newCreateTableFailed(name, e);\n }\n }\n \n private void executeDDL(String ddl) throws Exception {\n if (verbose) {\n System.out.println(ddl);\n }\n if (jdbcOutput) {\n final Statement statement = connection.createStatement();\n statement.execute(ddl);\n } else {\n fileOutput.write(ddl);\n fileOutput.write(\";\\n\");\n }\n\n }\n\n /**\n * Quote the given SQL identifier suitable for the output DBMS.\n * @param name\n * @return\n */\n private String quoteId(String name) {\n return sqlQuery.quoteIdentifier(name);\n }\n\n /**\n * String representation of the column in the result set, suitable for\n * inclusion in a SQL insert statement.\n *\n * The column in the result set is transformed according to the type in\n * the column parameter.\n *\n * Different DBMSs return different Java types for a given column.\n * ClassCastExceptions may occur.\n *\n * @param rs ResultSet row to process\n * @param column Column to process\n * @return String representation of column value\n * @throws Exception\n */\n private String columnValue(ResultSet rs, Column column) throws Exception {\n\n Object obj = rs.getObject(column.name);\n String columnType = column.type;\n\n if (obj == null) {\n return \"NULL\";\n }\n\n /*\n * Output for an INTEGER column, handling Doubles and Integers\n * in the result set\n */\n if (columnType.startsWith(\"INTEGER\")) {\n if (obj.getClass() == Double.class) {\n try {\n Double result = (Double) obj;\n return integerFormatter.format(result.doubleValue());\n } catch (ClassCastException cce) {\n System.out.println(\"CCE: \" + column.name + \" to Long from: \" + obj.getClass().getName() + \" - \" + obj.toString());\n throw cce;\n }\n } else {\n try {\n Integer result = (Integer) obj;\n return result.toString();\n } catch (ClassCastException cce) {\n System.out.println(\"CCE: \" + column.name + \" to Integer from: \" + obj.getClass().getName() + \" - \" + obj.toString());\n throw cce;\n }\n }\n\n /*\n * Output for an SMALLINT column, handling Integers\n * in the result set\n */\n } else if (columnType.startsWith(\"SMALLINT\")) {\n if (obj.getClass() == Boolean.class) {\n Boolean result = (Boolean) obj;\n if (result.booleanValue()) {\n return \"1\";\n } else {\n return \"0\";\n }\n } else {\n try {\n Integer result = (Integer) obj;\n return result.toString();\n } catch (ClassCastException cce) {\n System.out.println(\"CCE: \" + column.name + \" to Integer from: \" + obj.getClass().getName() + \" - \" + obj.toString());\n throw cce;\n }\n }\n /*\n * Output for an BIGINT column, handling Doubles and Longs\n * in the result set\n */\n } else if (columnType.startsWith(\"BIGINT\")) {\n if (obj.getClass() == Double.class) {\n try {\n Double result = (Double) obj;\n return integerFormatter.format(result.doubleValue());\n } catch (ClassCastException cce) {\n System.out.println(\"CCE: \" + column.name + \" to Double from: \" + obj.getClass().getName() + \" - \" + obj.toString());\n throw cce;\n }\n } else {\n try {\n Long result = (Long) obj;\n return result.toString();\n } catch (ClassCastException cce) {\n System.out.println(\"CCE: \" + column.name + \" to Long from: \" + obj.getClass().getName() + \" - \" + obj.toString());\n throw cce;\n }\n }\n\n /*\n * Output for a String, managing embedded quotes\n */\n } else if (columnType.startsWith(\"VARCHAR\")) {\n return embedQuotes((String) obj);\n\n /*\n * Output for a TIMESTAMP\n */\n } else if (columnType.startsWith(\"TIMESTAMP\")) {\n Timestamp ts = (Timestamp) obj;\n if (sqlQuery.isOracle()) {\n return \"TIMESTAMP '\" + ts + \"'\";\n } else {\n return \"'\" + ts + \"'\";\n }\n //return \"'\" + ts + \"'\" ;\n\n /*\n * Output for a DATE\n */\n } else if (columnType.startsWith(\"DATE\")) {\n Date dt = (Date) obj;\n if (sqlQuery.isOracle()) {\n return \"DATE '\" + dateFormatter.format(dt) + \"'\";\n } else {\n return \"'\" + dateFormatter.format(dt) + \"'\";\n }\n\n /*\n * Output for a FLOAT\n */\n } else if (columnType.startsWith(\"REAL\")) {\n Float result = (Float) obj;\n return result.toString();\n\n /*\n * Output for a DECIMAL(length, places)\n */\n } else if (columnType.startsWith(\"DECIMAL\")) {\n final Matcher matcher = decimalDataTypeRegex.matcher(columnType);\n if (!matcher.matches()) {\n throw new Exception(\"Bad DECIMAL column type for \" + columnType);\n }\n DecimalFormat formatter = new DecimalFormat(decimalFormat(matcher.group(1), matcher.group(2)));\n if (obj.getClass() == Double.class) {\n try {\n Double result = (Double) obj;\n return formatter.format(result.doubleValue());\n } catch (ClassCastException cce) {\n System.out.println(\"CCE: \" + column.name + \" to Double from: \" + obj.getClass().getName() + \" - \" + obj.toString());\n throw cce;\n }\n } else {\n // should be (obj.getClass() == BigDecimal.class)\n try {\n BigDecimal result = (BigDecimal) obj;\n return formatter.format(result);\n } catch (ClassCastException cce) {\n System.out.println(\"CCE: \" + column.name + \" to BigDecimal from: \" + obj.getClass().getName() + \" - \" + obj.toString());\n throw cce;\n }\n }\n\n /*\n * Output for a BOOLEAN (Postgres) or BIT (other DBMSs)\n */\n } else if (columnType.startsWith(\"BOOLEAN\") || columnType.startsWith(\"BIT\")) {\n Boolean result = (Boolean) obj;\n return result.toString();\n }\n throw new Exception(\"Unknown column type: \" + columnType + \" for column: \" + column.name);\n }\n\n private String columnValue(String columnValue, Column column) throws Exception {\n String columnType = column.type;\n\n if (columnValue == null) {\n return \"NULL\";\n }\n\n /*\n * Output for a TIMESTAMP\n */\n if (columnType.startsWith(\"TIMESTAMP\")) {\n if (sqlQuery.isOracle()) {\n return \"TIMESTAMP \" + columnValue;\n }\n\n /*\n * Output for a DATE\n */\n } else if (columnType.startsWith(\"DATE\")) {\n if (sqlQuery.isOracle()) {\n return \"DATE \" + columnValue;\n }\n\n /*\n * Output for a BOOLEAN (Postgres) or BIT (other DBMSs)\n *\n * FIXME This code assumes that only a boolean column would\n * map onto booleanColumnType. It would be better if we had a\n * logical and physical type for each column.\n */\n } else if (columnType.equals(booleanColumnType)) {\n String trimmedValue = columnValue.trim();\n if (!sqlQuery.isMySQL() &&\n !sqlQuery.isOracle()) {\n if (trimmedValue.equals(\"1\")) {\n return \"true\";\n } else if (trimmedValue.equals(\"0\")) {\n return \"false\";\n }\n } else {\n if (trimmedValue.equals(\"true\")) {\n return \"1\";\n } else if (trimmedValue.equals(\"false\")) {\n return \"0\";\n }\n }\n }\n return columnValue;\n //throw new Exception(\"Unknown column type: \" + columnType + \" for column: \" + column.name);\n }\n\n /**\n * Generate an appropriate string to use in an SQL insert statement for\n * a VARCHAR colummn, taking into account NULL strings and strings with embedded\n * quotes\n *\n * @param original String to transform\n * @return NULL if null string, otherwise massaged string with doubled quotes\n * for SQL\n */\n private String embedQuotes(String original) {\n if (original == null) {\n return \"NULL\";\n }\n StringBuffer sb = new StringBuffer();\n\n sb.append(\"'\");\n for (int i = 0; i < original.length(); i++) {\n char ch = original.charAt(i);\n sb.append(ch);\n if (ch == '\\'') {\n sb.append('\\'');\n }\n }\n sb.append(\"'\");\n return sb.toString();\n }\n\n /**\n * Generate an appropriate number format string for doubles etc\n * to be used to include a number in an SQL insert statement.\n *\n * Calls decimalFormat(int length, int places) to do the work.\n *\n * @param lengthStr String representing integer: number of digits to format\n * @param placesStr String representing integer: number of decimal places\n * @return number format, ie. length = 6, places = 2 => \"####.##\"\n */\n private static String decimalFormat(String lengthStr, String placesStr) {\n\n int length = Integer.parseInt(lengthStr);\n int places = Integer.parseInt(placesStr);\n return decimalFormat(length, places);\n }\n\n /**\n * Generate an appropriate number format string for doubles etc\n * to be used to include a number in an SQL insert statement.\n *\n * @param length int: number of digits to format\n * @param places int: number of decimal places\n * @return number format, ie. length = 6, places = 2 => \"###0.00\"\n */\n private static String decimalFormat(int length, int places) {\n StringBuffer sb = new StringBuffer();\n for (int i = 0; i < length; i++) {\n if ((length - i) == places) {\n sb.append('.');\n }\n if ((length - i) <= (places + 1)) {\n sb.append(\"0\");\n } else {\n sb.append(\"#\");\n }\n }\n return sb.toString();\n }\n\n private static class Column {\n private final String name;\n private final String type;\n private final String constraint;\n\n public Column(String name, String type, String constraint) {\n this.name = name;\n this.type = type;\n this.constraint = constraint;\n }\n }\n}\n\n\n// End MondrianFoodMartLoader.java\n"},"new_file":{"kind":"string","value":"testsrc/main/mondrian/test/loader/MondrianFoodMartLoader.java"},"old_contents":{"kind":"string","value":"/*\n// $Id$\n// This software is subject to the terms of the Common Public License\n// Agreement, available at the following URL:\n// http://www.opensource.org/licenses/cpl.html.\n// (C) Copyright 2004-2005 Julian Hyde\n// All Rights Reserved.\n// You must accept the terms of that agreement to use this software.\n*/\npackage mondrian.test.loader;\n\nimport mondrian.olap.MondrianResource;\nimport mondrian.rolap.RolapUtil;\nimport mondrian.rolap.sql.SqlQuery;\n\nimport java.io.*;\nimport java.math.BigDecimal;\n//import java.math.BigDecimal;\nimport java.sql.*;\nimport java.text.DateFormat;\nimport java.text.DecimalFormat;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.Map;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport java.util.zip.ZipEntry;\nimport java.util.zip.ZipFile;\n\n/**\n * Utility to load the FoodMart dataset into an arbitrary JDBC database.\n *\n *

This is known to create test data for the following databases:

\n *
    \n *\n *
  • MySQL 3.23 using MySQL-connector/J 3.0.16
  • \n *\n *
  • MySQL 4.15 using MySQL-connector/J 3.0.16
  • \n *\n *
  • Postgres 8.0 beta using postgresql-driver-jdbc3-74-214.jar
  • \n *\n *
  • Oracle 10g using ojdbc14.jar
  • \n *\n *
\n *\n *

Output can be to a set of files with create table, insert and create index\n * statements, or directly to a JDBC connection with JDBC batches (lots faster!)

\n *\n *

On the command line:

\n *\n *
MySQL example\n * $ mysqladmin create foodmart
\n * $ java -cp 'classes;testclasses' mondrian.test.loader.MondrianFoodMartLoader\n * -verbose -tables -data -indexes -jdbcDrivers=com.mysql.jdbc.Driver\n * -inputJdbcURL=jdbc:odbc:MondrianFoodMart -outputJdbcURL=jdbc:mysql://localhost/foodmart\n *
\n *\n * @author jhyde\n * @since 23 December, 2004\n * @version $Id$\n */\npublic class MondrianFoodMartLoader {\n final Pattern decimalDataTypeRegex = Pattern.compile(\"DECIMAL\\\\((.*),(.*)\\\\)\");\n final DecimalFormat integerFormatter = new DecimalFormat(decimalFormat(15, 0));\n final String dateFormatString = \"yyyy-MM-dd\";\n final String oracleDateFormatString = \"YYYY-MM-DD\";\n final DateFormat dateFormatter = new SimpleDateFormat(dateFormatString);\n private String jdbcDrivers;\n private String jdbcURL;\n private String userName;\n private String password;\n private String inputJdbcURL;\n private String inputUserName;\n private String inputPassword;\n private String inputFile;\n private String outputDirectory;\n private boolean tables = false;\n private boolean indexes = false;\n private boolean data = false;\n private static final String nl = System.getProperty(\"line.separator\");\n private boolean verbose = false;\n private boolean jdbcInput = false;\n private boolean jdbcOutput = false;\n private int inputBatchSize = 50;\n private Connection connection;\n private Connection inputConnection;\n\n private FileWriter fileOutput = null;\n\n private SqlQuery sqlQuery;\n private String booleanColumnType;\n private String bigIntColumnType;\n private final HashMap mapTableNameToColumns = new HashMap();\n\n public MondrianFoodMartLoader(String[] args) {\n\n StringBuffer errorMessage = new StringBuffer();\n\n for ( int i=0; i 0) {\n usage();\n throw MondrianResource.instance().newMissingArg(errorMessage.toString());\n }\n }\n\n public void usage() {\n System.out.println(\"Usage: MondrianFoodMartLoader [-verbose] [-tables] [-data] [-indexes] \" +\n \"-jdbcDrivers= \" +\n \"-outputJdbcURL= [-outputJdbcUser=user] [-outputJdbcPassword=password]\" +\n \"[-outputJdbcBatchSize=] \" +\n \"| \" +\n \"[-outputDirectory=] \" +\n \"[\" +\n \" [-inputJdbcURL= [-inputJdbcUser=user] [-inputJdbcPassword=password]]\" +\n \" | \" +\n \" [-inputfile=]\" +\n \"]\");\n System.out.println(\"\");\n System.out.println(\" JDBC connect string for DB\");\n System.out.println(\" [user] JDBC user name for DB\");\n System.out.println(\" [password] JDBC password for user for DB\");\n System.out.println(\" If no source DB parameters are given, assumes data comes from file\");\n System.out.println(\" [file name] file containing test data - INSERT statements in MySQL format\");\n System.out.println(\" If no input file name or input JDBC parameters are given, assume insert statements come from demo/FoodMartCreateData.zip file\");\n System.out.println(\" [outputDirectory] Where FoodMartCreateTables.sql, FoodMartCreateData.sql and FoodMartCreateIndexes.sql will be created\");\n\n System.out.println(\" size of JDBC batch updates - default to 50 inserts\");\n System.out.println(\" Comma-separated list of JDBC drivers.\");\n System.out.println(\" They must be on the classpath.\");\n System.out.println(\" -verbose Verbose mode.\");\n System.out.println(\" -tables If specified, drop and create the tables.\");\n System.out.println(\" -data If specified, load the data.\");\n System.out.println(\" -indexes If specified, drop and create the tables.\");\n }\n\n public static void main(String[] args) {\n System.out.println(\"Starting load at: \" + (new Date()));\n try {\n new MondrianFoodMartLoader(args).load();\n } catch (Throwable e) {\n e.printStackTrace();\n }\n System.out.println(\"Finished load at: \" + (new Date()));\n }\n\n /**\n * Load output from the input, optionally creating tables,\n * populating tables and creating indexes\n *\n * @throws Exception\n */\n private void load() throws Exception {\n RolapUtil.loadDrivers(jdbcDrivers);\n\n if (userName == null) {\n connection = DriverManager.getConnection(jdbcURL);\n } else {\n connection = DriverManager.getConnection(jdbcURL, userName, password);\n }\n\n if (jdbcInput) {\n if (inputUserName == null) {\n inputConnection = DriverManager.getConnection(inputJdbcURL);\n } else {\n inputConnection = DriverManager.getConnection(inputJdbcURL, inputUserName, inputPassword);\n }\n }\n final DatabaseMetaData metaData = connection.getMetaData();\n\n String productName = metaData.getDatabaseProductName();\n String version = metaData.getDatabaseProductVersion();\n\n System.out.println(\"Output connection is \" + productName + \", \" + version);\n\n sqlQuery = new SqlQuery(metaData);\n booleanColumnType = \"SMALLINT\";\n if (sqlQuery.isPostgres()) {\n booleanColumnType = \"BOOLEAN\";\n } else if (sqlQuery.isMySQL()) {\n booleanColumnType = \"BIT\";\n }\n\n bigIntColumnType = \"BIGINT\";\n if (sqlQuery.isOracle()) {\n bigIntColumnType = \"DECIMAL(15,0)\";\n }\n\n try {\n createTables(); // This also initializes mapTableNameToColumns\n if (data) {\n if (jdbcInput) {\n loadDataFromJdbcInput();\n } else {\n loadDataFromFile();\n }\n }\n if (indexes) {\n createIndexes();\n }\n } finally {\n if (connection != null) {\n connection.close();\n connection = null;\n }\n if (inputConnection != null) {\n inputConnection.close();\n inputConnection = null;\n }\n if (fileOutput != null) {\n fileOutput.close();\n fileOutput = null;\n }\n }\n }\n\n /**\n * Parse a file of INSERT statements and output to the configured JDBC\n * connection or another file in the dialect of the target data source.\n *\n * The assumption is that the input INSERT statements are out of MySQL, generated\n * by this loader by something like:\n *\n * MondrianFoodLoader\n * -verbose -tables -data -indexes\n * -jdbcDrivers=sun.jdbc.odbc.JdbcOdbcDriver,com.mysql.jdbc.Driver\n * -inputJdbcURL=jdbc:odbc:MondrianFoodMart\n * -outputJdbcURL=jdbc:mysql://localhost/textload?user=root&password=myAdmin\n * -outputDirectory=C:\\Temp\\wip\\Loader-Output\n *\n * @throws Exception\n */\n private void loadDataFromFile() throws Exception {\n InputStream is = openInputStream();\n\n if (is == null) {\n throw new Exception(\"No data file to process\");\n }\n\n try {\n final InputStreamReader reader = new InputStreamReader(is);\n final BufferedReader bufferedReader = new BufferedReader(reader);\n final Pattern regex = Pattern.compile(\"INSERT INTO `([^ ]+)` \\\\((.*)\\\\) VALUES\\\\((.*)\\\\);\");\n String line;\n int lineNumber = 0;\n int tableRowCount = 0;\n String prevTable = \"\";\n String quotedTableName = null;\n String quotedColumnNames = null;\n Column[] orderedColumns = null;\n\n String[] batch = new String[inputBatchSize];\n int batchSize = 0;\n\n while ((line = bufferedReader.readLine()) != null) {\n ++lineNumber;\n if (line.startsWith(\"#\")) {\n continue;\n }\n // Split the up the line. For example,\n // INSERT INTO `foo` ( `column1`,`column2` ) VALUES (1, 'bar');\n // would yield\n // tableName = \"foo\"\n // columnNames = \" `column1`,`column2` \"\n // values = \"1, 'bar'\"\n final Matcher matcher = regex.matcher(line);\n if (!matcher.matches()) {\n throw MondrianResource.instance().newInvalidInsertLine(\n new Integer(lineNumber), line);\n }\n String tableName = matcher.group(1); // e.g. \"foo\"\n String columnNames = matcher.group(2);\n String values = matcher.group(3);\n\n // If table just changed, flush the previous batch.\n if (!tableName.equals(prevTable)) {\n if (!prevTable.equals(\"\")) {\n System.out.println(\"Table \" + prevTable +\n \": loaded \" + tableRowCount + \" rows.\");\n }\n tableRowCount = 0;\n writeBatch(batch, batchSize);\n batchSize = 0;\n prevTable = tableName;\n quotedTableName = quoteId(tableName);\n quotedColumnNames = columnNames\n .replaceAll(\"`\", sqlQuery.getQuoteIdentifierString());\n String[] splitColumnNames = columnNames.replaceAll(\"`\", \"\")\n .replaceAll(\" \", \"\").split(\",\");\n Column[] columns = (Column[]) mapTableNameToColumns.get(tableName);\n\n orderedColumns = new Column[columns.length];\n\n for (int i = 0; i < splitColumnNames.length; i++) {\n Column thisColumn = null;\n for (int j = 0; j < columns.length && thisColumn == null; j++) {\n if (columns[j].name.equalsIgnoreCase(splitColumnNames[i])) {\n thisColumn = columns[j];\n }\n }\n if (thisColumn == null) {\n throw new Exception(\"Unknown column in INSERT statement from file: \" + splitColumnNames[i]);\n } else {\n orderedColumns[i] = thisColumn;\n }\n }\n\n\n }\n\n StringBuffer massagedLine = new StringBuffer();\n\n massagedLine\n .append(\"INSERT INTO \")\n .append(quotedTableName)\n .append(\" (\")\n .append(quotedColumnNames)\n .append(\" ) VALUES(\")\n .append(getMassagedValues(orderedColumns, values))\n .append(\" )\");\n\n line = massagedLine.toString();\n\n ++tableRowCount;\n\n batch[batchSize++] = line;\n if (batchSize >= inputBatchSize) {\n writeBatch(batch, batchSize);\n batchSize = 0;\n }\n }\n // Print summary of the final table.\n if (!prevTable.equals(\"\")) {\n System.out.println(\"Table \" + prevTable +\n \": loaded \" + tableRowCount + \" rows.\");\n tableRowCount = 0;\n writeBatch(batch, batchSize);\n batchSize = 0;\n }\n } finally {\n if (is != null) {\n is.close();\n }\n }\n }\n\n /**\n * @param splitColumnNames the individual column names in the same order as the values\n * @param columns column metadata for the table\n * @param values the contents of the INSERT VALUES clause ie. \"34,67.89,'GHt''ab'\". These are in MySQL form.\n * @return String values for the destination dialect\n * @throws Exception\n */\n private String getMassagedValues(Column[] columns, String values) throws Exception {\n StringBuffer sb = new StringBuffer();\n\n // Get the values out as individual elements\n // Split the string at commas, and cope with embedded commas\n String[] individualValues = new String[columns.length];\n\n String[] splitValues = values.split(\",\");\n\n // If these 2 are the same length, then there are no embedded commas\n\n if (splitValues.length == columns.length) {\n individualValues = splitValues;\n } else {\n // \"34,67.89,'GH,t''a,b'\" => { \"34\", \"67.89\", \"'GH\", \"t''a\", \"b'\"\n int valuesPos = 0;\n boolean inQuote = false;\n for (int i = 0; i < splitValues.length; i++) {\n if (i == 0) {\n individualValues[valuesPos] = splitValues[i];\n inQuote = inQuote(splitValues[i], inQuote);\n } else {\n // at end\n if (inQuote) {\n individualValues[valuesPos] = individualValues[valuesPos] + \",\" + splitValues[i];\n inQuote = inQuote(splitValues[i], inQuote);\n } else {\n valuesPos++;\n individualValues[valuesPos] = splitValues[i];\n inQuote = inQuote(splitValues[i], inQuote);\n }\n }\n }\n\n assert(valuesPos + 1 == columns.length);\n }\n\n for (int i = 0; i < columns.length; i++) {\n if (i > 0) {\n sb.append(\",\");\n }\n String value = individualValues[i];\n if (value != null && value.trim().equals(\"NULL\")) {\n value = null;\n }\n sb.append(columnValue(value, columns[i]));\n }\n return sb.toString();\n\n }\n\n private boolean inQuote(String str, boolean nowInQuote) {\n if (str.indexOf('\\'') == -1) {\n // No quote, so stay the same\n return nowInQuote;\n }\n int lastPos = 0;\n while (lastPos <= str.length() && str.indexOf('\\'', lastPos) != -1) {\n int pos = str.indexOf('\\'', lastPos);\n nowInQuote = !nowInQuote;\n lastPos = pos + 1;\n }\n return nowInQuote;\n }\n\n private void loadDataFromJdbcInput() throws Exception {\n if (outputDirectory != null) {\n fileOutput = new FileWriter(new File(outputDirectory, \"createData.sql\"));\n }\n\n /*\n * For each input table,\n * read specified columns for all rows in the input connection\n *\n * For each row, insert a row\n */\n\n for (Iterator it = mapTableNameToColumns.entrySet().iterator(); it.hasNext(); ) {\n Map.Entry tableEntry = (Map.Entry) it.next();\n int rowsAdded = loadTable((String) tableEntry.getKey(), (Column[]) tableEntry.getValue());\n System.out.println(\"Table \" + (String) tableEntry.getKey() +\n \": loaded \" + rowsAdded + \" rows.\");\n }\n\n if (outputDirectory != null) {\n fileOutput.close();\n }\n }\n\n /**\n * Read the given table from the input RDBMS and output to destination\n * RDBMS or file\n *\n * @param name name of table\n * @param columns columns to be read/output\n * @return #rows inserted\n * @throws Exception\n */\n private int loadTable(String name, Column[] columns) throws Exception {\n int rowsAdded = 0;\n StringBuffer buf = new StringBuffer();\n\n buf.append(\"select \");\n for (int i = 0; i < columns.length; i++) {\n Column column = columns[i];\n if (i > 0) {\n buf.append(\",\");\n }\n buf.append(quoteId(column.name));\n }\n buf.append(\" from \")\n .append(quoteId(name));\n String ddl = buf.toString();\n Statement statement = inputConnection.createStatement();\n if (verbose) {\n System.out.println(\"Input table SQL: \" + ddl);\n }\n ResultSet rs = statement.executeQuery(ddl);\n\n String[] batch = new String[inputBatchSize];\n int batchSize = 0;\n boolean displayedInsert = false;\n\n while (rs.next()) {\n /*\n * Get a batch of insert statements, then save a batch\n */\n\n String insertStatement = createInsertStatement(rs, name, columns);\n if (!displayedInsert && verbose) {\n System.out.println(\"Example Insert statement: \" + insertStatement);\n displayedInsert = true;\n }\n batch[batchSize++] = insertStatement;\n if (batchSize >= inputBatchSize) {\n rowsAdded += writeBatch(batch, batchSize);\n batchSize = 0;\n }\n }\n\n if (batchSize > 0) {\n rowsAdded += writeBatch(batch, batchSize);\n }\n\n return rowsAdded;\n }\n\n /**\n * Create a SQL INSERT statement in the dialect of the output RDBMS.\n *\n * @param rs ResultSet of input RDBMS\n * @param name name of table\n * @param columns column definitions for INSERT statement\n * @return String the INSERT statement\n * @throws Exception\n */\n private String createInsertStatement(ResultSet rs, String name, Column[] columns) throws Exception {\n StringBuffer buf = new StringBuffer();\n\n buf.append(\"INSERT INTO \")\n .append(quoteId(name))\n .append(\" ( \");\n for (int i = 0; i < columns.length; i++) {\n Column column = columns[i];\n if (i > 0) {\n buf.append(\",\");\n }\n buf.append(quoteId(column.name));\n }\n buf.append(\" ) VALUES(\");\n for (int i = 0; i < columns.length; i++) {\n Column column = columns[i];\n if (i > 0) {\n buf.append(\",\");\n }\n buf.append(columnValue(rs, column));\n }\n buf.append(\" )\");\n return buf.toString();\n }\n\n /**\n * If we are outputting to JDBC,\n * Execute the given set of SQL statements\n *\n * Otherwise,\n * output the statements to a file.\n *\n * @param batch SQL statements to execute\n * @param batchSize # SQL statements to execute\n * @return # SQL statements executed\n * @throws IOException\n * @throws SQLException\n */\n private int writeBatch(String[] batch, int batchSize) throws IOException, SQLException {\n if (outputDirectory != null) {\n for (int i = 0; i < batchSize; i++) {\n fileOutput.write(batch[i]);\n fileOutput.write(\";\\n\");\n }\n } else {\n connection.setAutoCommit(false);\n Statement stmt = connection.createStatement();\n if (batchSize == 1) {\n // Don't use batching if there's only one item. This allows\n // us to work around bugs in the JDBC driver by setting\n // outputJdbcBatchSize=1.\n stmt.execute(batch[0]);\n } else {\n for (int i = 0; i < batchSize; i++) {\n stmt.addBatch(batch[i]);\n }\n int [] updateCounts = null;\n\n try {\n updateCounts = stmt.executeBatch();\n } catch (SQLException e) {\n for (int i = 0; i < batchSize; i++) {\n System.out.println(\"Error in SQL batch: \" + batch[i]);\n }\n throw e;\n }\n int updates = 0;\n for (int i = 0; i < updateCounts.length; updates += updateCounts[i], i++) {\n if (updateCounts[i] == 0) {\n System.out.println(\"Error in SQL: \" + batch[i]);\n }\n }\n if (updates < batchSize) {\n throw new RuntimeException(\"Failed to execute batch: \" + batchSize + \" versus \" + updates);\n }\n }\n stmt.close();\n connection.setAutoCommit(true);\n }\n return batchSize;\n }\n\n /**\n * Open the file of INSERT statements to load the data. Default\n * file name is ./demo/FoodMartCreateData.zip\n *\n * @return FileInputStream\n */\n private InputStream openInputStream() throws Exception {\n final String defaultZipFileName = \"FoodMartCreateData.zip\";\n final String defaultDataFileName = \"FoodMartCreateData.sql\";\n final File file = (inputFile != null) ? new File(inputFile) : new File(\"demo\", defaultZipFileName);\n if (!file.exists()) {\n System.out.println(\"No input file: \" + file);\n return null;\n }\n if (file.getName().toLowerCase().endsWith(\".zip\")) {\n ZipFile zippedData = new ZipFile(file);\n ZipEntry entry = zippedData.getEntry(defaultDataFileName);\n return zippedData.getInputStream(entry);\n } else {\n return new FileInputStream(file);\n }\n }\n\n /**\n * Create all indexes for the FoodMart database\n *\n * @throws Exception\n */\n private void createIndexes() throws Exception {\n if (outputDirectory != null) {\n fileOutput = new FileWriter(new File(outputDirectory, \"createIndexes.sql\"));\n }\n\n createIndex(true, \"account\", \"i_account_id\", new String[] {\"account_id\"});\n createIndex(false, \"account\", \"i_account_parent\", new String[] {\"account_parent\"});\n createIndex(true, \"category\", \"i_category_id\", new String[] {\"category_id\"});\n createIndex(false, \"category\", \"i_category_parent\", new String[] {\"category_parent\"});\n createIndex(true, \"currency\", \"i_currency\", new String[] {\"currency_id\", \"date\"});\n createIndex(false, \"customer\", \"i_cust_acct_num\", new String[] {\"account_num\"});\n createIndex(false, \"customer\", \"i_customer_fname\", new String[] {\"fname\"});\n createIndex(false, \"customer\", \"i_customer_lname\", new String[] {\"lname\"});\n createIndex(false, \"customer\", \"i_cust_child_home\", new String[] {\"num_children_at_home\"});\n createIndex(true, \"customer\", \"i_customer_id\", new String[] {\"customer_id\"});\n createIndex(false, \"customer\", \"i_cust_postal_code\", new String[] {\"postal_code\"});\n createIndex(false, \"customer\", \"i_cust_region_id\", new String[] {\"customer_region_id\"});\n createIndex(true, \"department\", \"i_department_id\", new String[] {\"department_id\"});\n createIndex(true, \"employee\", \"i_employee_id\", new String[] {\"employee_id\"});\n createIndex(false, \"employee\", \"i_empl_dept_id\", new String[] {\"department_id\"});\n createIndex(false, \"employee\", \"i_empl_store_id\", new String[] {\"store_id\"});\n createIndex(false, \"employee\", \"i_empl_super_id\", new String[] {\"supervisor_id\"});\n createIndex(true, \"employee_closure\", \"i_empl_closure\", new String[] {\"supervisor_id\", \"employee_id\"});\n createIndex(false, \"employee_closure\", \"i_empl_closure_emp\", new String[] {\"employee_id\"});\n createIndex(false, \"expense_fact\", \"i_expense_store_id\", new String[] {\"store_id\"});\n createIndex(false, \"expense_fact\", \"i_expense_acct_id\", new String[] {\"account_id\"});\n createIndex(false, \"expense_fact\", \"i_expense_time_id\", new String[] {\"time_id\"});\n createIndex(false, \"inventory_fact_1997\", \"i_inv_97_prod_id\", new String[] {\"product_id\"});\n createIndex(false, \"inventory_fact_1997\", \"i_inv_97_store_id\", new String[] {\"store_id\"});\n createIndex(false, \"inventory_fact_1997\", \"i_inv_97_time_id\", new String[] {\"time_id\"});\n createIndex(false, \"inventory_fact_1997\", \"i_inv_97_wrhse_id\", new String[] {\"warehouse_id\"});\n createIndex(false, \"inventory_fact_1998\", \"i_inv_98_prod_id\", new String[] {\"product_id\"});\n createIndex(false, \"inventory_fact_1998\", \"i_inv_98_store_id\", new String[] {\"store_id\"});\n createIndex(false, \"inventory_fact_1998\", \"i_inv_98_time_id\", new String[] {\"time_id\"});\n createIndex(false, \"inventory_fact_1998\", \"i_inv_98_wrhse_id\", new String[] {\"warehouse_id\"});\n createIndex(true, \"position\", \"i_position_id\", new String[] {\"position_id\"});\n createIndex(false, \"product\", \"i_prod_brand_name\", new String[] {\"brand_name\"});\n createIndex(true, \"product\", \"i_product_id\", new String[] {\"product_id\"});\n createIndex(false, \"product\", \"i_prod_class_id\", new String[] {\"product_class_id\"});\n createIndex(false, \"product\", \"i_product_name\", new String[] {\"product_name\"});\n createIndex(false, \"product\", \"i_product_SKU\", new String[] {\"SKU\"});\n createIndex(true, \"promotion\", \"i_promotion_id\", new String[] {\"promotion_id\"});\n createIndex(false, \"promotion\", \"i_promo_dist_id\", new String[] {\"promotion_district_id\"});\n createIndex(true, \"reserve_employee\", \"i_rsrv_empl_id\", new String[] {\"employee_id\"});\n createIndex(false, \"reserve_employee\", \"i_rsrv_empl_dept\", new String[] {\"department_id\"});\n createIndex(false, \"reserve_employee\", \"i_rsrv_empl_store\", new String[] {\"store_id\"});\n createIndex(false, \"reserve_employee\", \"i_rsrv_empl_sup\", new String[] {\"supervisor_id\"});\n createIndex(false, \"salary\", \"i_salary_pay_date\", new String[] {\"pay_date\"});\n createIndex(false, \"salary\", \"i_salary_employee\", new String[] {\"employee_id\"});\n createIndex(false, \"sales_fact_1997\", \"i_sls_97_cust_id\", new String[] {\"customer_id\"});\n createIndex(false, \"sales_fact_1997\", \"i_sls_97_prod_id\", new String[] {\"product_id\"});\n createIndex(false, \"sales_fact_1997\", \"i_sls_97_promo_id\", new String[] {\"promotion_id\"});\n createIndex(false, \"sales_fact_1997\", \"i_sls_97_store_id\", new String[] {\"store_id\"});\n createIndex(false, \"sales_fact_1997\", \"i_sls_97_time_id\", new String[] {\"time_id\"});\n createIndex(false, \"sales_fact_dec_1998\", \"i_sls_dec98_cust\", new String[] {\"customer_id\"});\n createIndex(false, \"sales_fact_dec_1998\", \"i_sls_dec98_prod\", new String[] {\"product_id\"});\n createIndex(false, \"sales_fact_dec_1998\", \"i_sls_dec98_promo\", new String[] {\"promotion_id\"});\n createIndex(false, \"sales_fact_dec_1998\", \"i_sls_dec98_store\", new String[] {\"store_id\"});\n createIndex(false, \"sales_fact_dec_1998\", \"i_sls_dec98_time\", new String[] {\"time_id\"});\n createIndex(false, \"sales_fact_1998\", \"i_sls_98_cust_id\", new String[] {\"customer_id\"});\n createIndex(false, \"sales_fact_1998\", \"i_sls_1998_prod_id\", new String[] {\"product_id\"});\n createIndex(false, \"sales_fact_1998\", \"i_sls_1998_promo\", new String[] {\"promotion_id\"});\n createIndex(false, \"sales_fact_1998\", \"i_sls_1998_store\", new String[] {\"store_id\"});\n createIndex(false, \"sales_fact_1998\", \"i_sls_1998_time_id\", new String[] {\"time_id\"});\n createIndex(true, \"store\", \"i_store_id\", new String[] {\"store_id\"});\n createIndex(false, \"store\", \"i_store_region_id\", new String[] {\"region_id\"});\n createIndex(true, \"store_ragged\", \"i_store_raggd_id\", new String[] {\"store_id\"});\n createIndex(false, \"store_ragged\", \"i_store_rggd_reg\", new String[] {\"region_id\"});\n createIndex(true, \"time_by_day\", \"i_time_id\", new String[] {\"time_id\"});\n createIndex(true, \"time_by_day\", \"i_time_day\", new String[] {\"the_date\"});\n createIndex(false, \"time_by_day\", \"i_time_year\", new String[] {\"the_year\"});\n createIndex(false, \"time_by_day\", \"i_time_quarter\", new String[] {\"quarter\"});\n createIndex(false, \"time_by_day\", \"i_time_month\", new String[] {\"month_of_year\"});\n\n if (outputDirectory != null) {\n fileOutput.close();\n }\n }\n\n /**\n *\n * If we are outputting to JDBC,\n * Execute the CREATE INDEX statement\n *\n * Otherwise,\n * output the statement to a file.\n *\n * @param isUnique\n * @param tableName\n * @param indexName\n * @param columnNames\n */\n private void createIndex(\n boolean isUnique,\n String tableName,\n String indexName,\n String[] columnNames)\n {\n try {\n StringBuffer buf = new StringBuffer();\n if (jdbcOutput) {\n try {\n buf.append(\"DROP INDEX \")\n .append(quoteId(indexName));\n if (sqlQuery.isMySQL()) {\n buf.append(\" ON \")\n .append(quoteId(tableName));\n }\n final String deleteDDL = buf.toString();\n executeDDL(deleteDDL);\n } catch (Exception e1) {\n System.out.println(\"Drop failed: but continue\");\n }\n }\n\n buf = new StringBuffer();\n buf.append(isUnique ? \"CREATE UNIQUE INDEX \" : \"CREATE INDEX \")\n .append(quoteId(indexName)).append(\" ON \")\n .append(quoteId(tableName)).append(\" (\");\n for (int i = 0; i < columnNames.length; i++) {\n String columnName = columnNames[i];\n if (i > 0) {\n buf.append(\", \");\n }\n buf.append(quoteId(columnName));\n }\n buf.append(\")\");\n final String createDDL = buf.toString();\n executeDDL(createDDL);\n } catch (Exception e) {\n throw MondrianResource.instance().newCreateIndexFailed(indexName,\n tableName, e);\n }\n }\n\n /**\n * Define all tables for the FoodMart database.\n *\n * Also initializes mapTableNameToColumns\n *\n * @throws Exception\n */\n private void createTables() throws Exception {\n if (outputDirectory != null) {\n fileOutput = new FileWriter(new File(outputDirectory, \"createTables.sql\"));\n }\n\n createTable(\"sales_fact_1997\", new Column[] {\n new Column(\"product_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"time_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"customer_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"promotion_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"store_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"store_sales\", \"DECIMAL(10,4)\", \"NOT NULL\"),\n new Column(\"store_cost\", \"DECIMAL(10,4)\", \"NOT NULL\"),\n new Column(\"unit_sales\", \"DECIMAL(10,4)\", \"NOT NULL\"),\n });\n createTable(\"sales_fact_1998\", new Column[] {\n new Column(\"product_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"time_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"customer_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"promotion_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"store_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"store_sales\", \"DECIMAL(10,4)\", \"NOT NULL\"),\n new Column(\"store_cost\", \"DECIMAL(10,4)\", \"NOT NULL\"),\n new Column(\"unit_sales\", \"DECIMAL(10,4)\", \"NOT NULL\"),\n });\n createTable(\"sales_fact_dec_1998\", new Column[] {\n new Column(\"product_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"time_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"customer_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"promotion_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"store_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"store_sales\", \"DECIMAL(10,4)\", \"NOT NULL\"),\n new Column(\"store_cost\", \"DECIMAL(10,4)\", \"NOT NULL\"),\n new Column(\"unit_sales\", \"DECIMAL(10,4)\", \"NOT NULL\"),\n });\n createTable(\"inventory_fact_1997\", new Column[] {\n new Column(\"product_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"time_id\", \"INTEGER\", \"\"),\n new Column(\"warehouse_id\", \"INTEGER\", \"\"),\n new Column(\"store_id\", \"INTEGER\", \"\"),\n new Column(\"units_ordered\", \"INTEGER\", \"\"),\n new Column(\"units_shipped\", \"INTEGER\", \"\"),\n new Column(\"warehouse_sales\", \"DECIMAL(10,4)\", \"\"),\n new Column(\"warehouse_cost\", \"DECIMAL(10,4)\", \"\"),\n new Column(\"supply_time\", \"SMALLINT\", \"\"),\n new Column(\"store_invoice\", \"DECIMAL(10,4)\", \"\"),\n });\n createTable(\"inventory_fact_1998\", new Column[] {\n new Column(\"product_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"time_id\", \"INTEGER\", \"\"),\n new Column(\"warehouse_id\", \"INTEGER\", \"\"),\n new Column(\"store_id\", \"INTEGER\", \"\"),\n new Column(\"units_ordered\", \"INTEGER\", \"\"),\n new Column(\"units_shipped\", \"INTEGER\", \"\"),\n new Column(\"warehouse_sales\", \"DECIMAL(10,4)\", \"\"),\n new Column(\"warehouse_cost\", \"DECIMAL(10,4)\", \"\"),\n new Column(\"supply_time\", \"SMALLINT\", \"\"),\n new Column(\"store_invoice\", \"DECIMAL(10,4)\", \"\"),\n });\n createTable(\"currency\", new Column[] {\n new Column(\"currency_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"date\", \"DATE\", \"NOT NULL\"),\n new Column(\"currency\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"conversion_ratio\", \"DECIMAL(10,4)\", \"NOT NULL\"),\n });\n createTable(\"account\", new Column[] {\n new Column(\"account_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"account_parent\", \"INTEGER\", \"\"),\n new Column(\"account_description\", \"VARCHAR(30)\", \"\"),\n new Column(\"account_type\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"account_rollup\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"Custom_Members\", \"VARCHAR(255)\", \"\"),\n });\n createTable(\"category\", new Column[] {\n new Column(\"category_id\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"category_parent\", \"VARCHAR(30)\", \"\"),\n new Column(\"category_description\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"category_rollup\", \"VARCHAR(30)\", \"\"),\n });\n createTable(\"customer\", new Column[] {\n new Column(\"customer_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"account_num\", bigIntColumnType, \"NOT NULL\"),\n new Column(\"lname\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"fname\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"mi\", \"VARCHAR(30)\", \"\"),\n new Column(\"address1\", \"VARCHAR(30)\", \"\"),\n new Column(\"address2\", \"VARCHAR(30)\", \"\"),\n new Column(\"address3\", \"VARCHAR(30)\", \"\"),\n new Column(\"address4\", \"VARCHAR(30)\", \"\"),\n new Column(\"city\", \"VARCHAR(30)\", \"\"),\n new Column(\"state_province\", \"VARCHAR(30)\", \"\"),\n new Column(\"postal_code\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"country\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"customer_region_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"phone1\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"phone2\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"birthdate\", \"DATE\", \"NOT NULL\"),\n new Column(\"marital_status\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"yearly_income\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"gender\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"total_children\", \"SMALLINT\", \"NOT NULL\"),\n new Column(\"num_children_at_home\", \"SMALLINT\", \"NOT NULL\"),\n new Column(\"education\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"date_accnt_opened\", \"DATE\", \"NOT NULL\"),\n new Column(\"member_card\", \"VARCHAR(30)\", \"\"),\n new Column(\"occupation\", \"VARCHAR(30)\", \"\"),\n new Column(\"houseowner\", \"VARCHAR(30)\", \"\"),\n new Column(\"num_cars_owned\", \"INTEGER\", \"\"),\n });\n createTable(\"days\", new Column[] {\n new Column(\"day\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"week_day\", \"VARCHAR(30)\", \"NOT NULL\"),\n });\n createTable(\"department\", new Column[] {\n new Column(\"department_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"department_description\", \"VARCHAR(30)\", \"NOT NULL\"),\n });\n createTable(\"employee\", new Column[] {\n new Column(\"employee_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"full_name\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"first_name\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"last_name\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"position_id\", \"INTEGER\", \"\"),\n new Column(\"position_title\", \"VARCHAR(30)\", \"\"),\n new Column(\"store_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"department_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"birth_date\", \"DATE\", \"NOT NULL\"),\n new Column(\"hire_date\", \"TIMESTAMP\", \"\"),\n new Column(\"end_date\", \"TIMESTAMP\", \"\"),\n new Column(\"salary\", \"DECIMAL(10,4)\", \"NOT NULL\"),\n new Column(\"supervisor_id\", \"INTEGER\", \"\"),\n new Column(\"education_level\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"marital_status\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"gender\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"management_role\", \"VARCHAR(30)\", \"\"),\n });\n createTable(\"employee_closure\", new Column[] {\n new Column(\"employee_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"supervisor_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"distance\", \"INTEGER\", \"\"),\n });\n createTable(\"expense_fact\", new Column[] {\n new Column(\"store_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"account_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"exp_date\", \"TIMESTAMP\", \"NOT NULL\"),\n new Column(\"time_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"category_id\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"currency_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"amount\", \"DECIMAL(10,4)\", \"NOT NULL\"),\n });\n createTable(\"position\", new Column[] {\n new Column(\"position_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"position_title\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"pay_type\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"min_scale\", \"DECIMAL(10,4)\", \"NOT NULL\"),\n new Column(\"max_scale\", \"DECIMAL(10,4)\", \"NOT NULL\"),\n new Column(\"management_role\", \"VARCHAR(30)\", \"NOT NULL\"),\n });\n createTable(\"product\", new Column[] {\n new Column(\"product_class_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"product_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"brand_name\", \"VARCHAR(60)\", \"\"),\n new Column(\"product_name\", \"VARCHAR(60)\", \"NOT NULL\"),\n new Column(\"SKU\", bigIntColumnType, \"NOT NULL\"),\n new Column(\"SRP\", \"DECIMAL(10,4)\", \"\"),\n new Column(\"gross_weight\", \"REAL\", \"\"),\n new Column(\"net_weight\", \"REAL\", \"\"),\n new Column(\"recyclable_package\", booleanColumnType, \"\"),\n new Column(\"low_fat\", booleanColumnType, \"\"),\n new Column(\"units_per_case\", \"SMALLINT\", \"\"),\n new Column(\"cases_per_pallet\", \"SMALLINT\", \"\"),\n new Column(\"shelf_width\", \"REAL\", \"\"),\n new Column(\"shelf_height\", \"REAL\", \"\"),\n new Column(\"shelf_depth\", \"REAL\", \"\"),\n });\n createTable(\"product_class\", new Column[] {\n new Column(\"product_class_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"product_subcategory\", \"VARCHAR(30)\", \"\"),\n new Column(\"product_category\", \"VARCHAR(30)\", \"\"),\n new Column(\"product_department\", \"VARCHAR(30)\", \"\"),\n new Column(\"product_family\", \"VARCHAR(30)\", \"\"),\n });\n createTable(\"promotion\", new Column[] {\n new Column(\"promotion_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"promotion_district_id\", \"INTEGER\", \"\"),\n new Column(\"promotion_name\", \"VARCHAR(30)\", \"\"),\n new Column(\"media_type\", \"VARCHAR(30)\", \"\"),\n new Column(\"cost\", \"DECIMAL(10,4)\", \"\"),\n new Column(\"start_date\", \"TIMESTAMP\", \"\"),\n new Column(\"end_date\", \"TIMESTAMP\", \"\"),\n });\n createTable(\"region\", new Column[] {\n new Column(\"region_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"sales_city\", \"VARCHAR(30)\", \"\"),\n new Column(\"sales_state_province\", \"VARCHAR(30)\", \"\"),\n new Column(\"sales_district\", \"VARCHAR(30)\", \"\"),\n new Column(\"sales_region\", \"VARCHAR(30)\", \"\"),\n new Column(\"sales_country\", \"VARCHAR(30)\", \"\"),\n new Column(\"sales_district_id\", \"INTEGER\", \"\"),\n });\n createTable(\"reserve_employee\", new Column[] {\n new Column(\"employee_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"full_name\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"first_name\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"last_name\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"position_id\", \"INTEGER\", \"\"),\n new Column(\"position_title\", \"VARCHAR(30)\", \"\"),\n new Column(\"store_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"department_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"birth_date\", \"TIMESTAMP\", \"NOT NULL\"),\n new Column(\"hire_date\", \"TIMESTAMP\", \"\"),\n new Column(\"end_date\", \"TIMESTAMP\", \"\"),\n new Column(\"salary\", \"DECIMAL(10,4)\", \"NOT NULL\"),\n new Column(\"supervisor_id\", \"INTEGER\", \"\"),\n new Column(\"education_level\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"marital_status\", \"VARCHAR(30)\", \"NOT NULL\"),\n new Column(\"gender\", \"VARCHAR(30)\", \"NOT NULL\"),\n });\n createTable(\"salary\", new Column[] {\n new Column(\"pay_date\", \"TIMESTAMP\", \"NOT NULL\"),\n new Column(\"employee_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"department_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"currency_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"salary_paid\", \"DECIMAL(10,4)\", \"NOT NULL\"),\n new Column(\"overtime_paid\", \"DECIMAL(10,4)\", \"NOT NULL\"),\n new Column(\"vacation_accrued\", \"REAL\", \"NOT NULL\"),\n new Column(\"vacation_used\", \"REAL\", \"NOT NULL\"),\n });\n createTable(\"store\", new Column[] {\n new Column(\"store_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"store_type\", \"VARCHAR(30)\", \"\"),\n new Column(\"region_id\", \"INTEGER\", \"\"),\n new Column(\"store_name\", \"VARCHAR(30)\", \"\"),\n new Column(\"store_number\", \"INTEGER\", \"\"),\n new Column(\"store_street_address\", \"VARCHAR(30)\", \"\"),\n new Column(\"store_city\", \"VARCHAR(30)\", \"\"),\n new Column(\"store_state\", \"VARCHAR(30)\", \"\"),\n new Column(\"store_postal_code\", \"VARCHAR(30)\", \"\"),\n new Column(\"store_country\", \"VARCHAR(30)\", \"\"),\n new Column(\"store_manager\", \"VARCHAR(30)\", \"\"),\n new Column(\"store_phone\", \"VARCHAR(30)\", \"\"),\n new Column(\"store_fax\", \"VARCHAR(30)\", \"\"),\n new Column(\"first_opened_date\", \"TIMESTAMP\", \"\"),\n new Column(\"last_remodel_date\", \"TIMESTAMP\", \"\"),\n new Column(\"store_sqft\", \"INTEGER\", \"\"),\n new Column(\"grocery_sqft\", \"INTEGER\", \"\"),\n new Column(\"frozen_sqft\", \"INTEGER\", \"\"),\n new Column(\"meat_sqft\", \"INTEGER\", \"\"),\n new Column(\"coffee_bar\", booleanColumnType, \"\"),\n new Column(\"video_store\", booleanColumnType, \"\"),\n new Column(\"salad_bar\", booleanColumnType, \"\"),\n new Column(\"prepared_food\", booleanColumnType, \"\"),\n new Column(\"florist\", booleanColumnType, \"\"),\n });\n createTable(\"store_ragged\", new Column[] {\n new Column(\"store_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"store_type\", \"VARCHAR(30)\", \"\"),\n new Column(\"region_id\", \"INTEGER\", \"\"),\n new Column(\"store_name\", \"VARCHAR(30)\", \"\"),\n new Column(\"store_number\", \"INTEGER\", \"\"),\n new Column(\"store_street_address\", \"VARCHAR(30)\", \"\"),\n new Column(\"store_city\", \"VARCHAR(30)\", \"\"),\n new Column(\"store_state\", \"VARCHAR(30)\", \"\"),\n new Column(\"store_postal_code\", \"VARCHAR(30)\", \"\"),\n new Column(\"store_country\", \"VARCHAR(30)\", \"\"),\n new Column(\"store_manager\", \"VARCHAR(30)\", \"\"),\n new Column(\"store_phone\", \"VARCHAR(30)\", \"\"),\n new Column(\"store_fax\", \"VARCHAR(30)\", \"\"),\n new Column(\"first_opened_date\", \"TIMESTAMP\", \"\"),\n new Column(\"last_remodel_date\", \"TIMESTAMP\", \"\"),\n new Column(\"store_sqft\", \"INTEGER\", \"\"),\n new Column(\"grocery_sqft\", \"INTEGER\", \"\"),\n new Column(\"frozen_sqft\", \"INTEGER\", \"\"),\n new Column(\"meat_sqft\", \"INTEGER\", \"\"),\n new Column(\"coffee_bar\", booleanColumnType, \"\"),\n new Column(\"video_store\", booleanColumnType, \"\"),\n new Column(\"salad_bar\", booleanColumnType, \"\"),\n new Column(\"prepared_food\", booleanColumnType, \"\"),\n new Column(\"florist\", booleanColumnType, \"\"),\n });\n createTable(\"time_by_day\", new Column[] {\n new Column(\"time_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"the_date\", \"TIMESTAMP\", \"\"),\n new Column(\"the_day\", \"VARCHAR(30)\", \"\"),\n new Column(\"the_month\", \"VARCHAR(30)\", \"\"),\n new Column(\"the_year\", \"SMALLINT\", \"\"),\n new Column(\"day_of_month\", \"SMALLINT\", \"\"),\n new Column(\"week_of_year\", \"INTEGER\", \"\"),\n new Column(\"month_of_year\", \"SMALLINT\", \"\"),\n new Column(\"quarter\", \"VARCHAR(30)\", \"\"),\n new Column(\"fiscal_period\", \"VARCHAR(30)\", \"\"),\n });\n createTable(\"warehouse\", new Column[] {\n new Column(\"warehouse_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"warehouse_class_id\", \"INTEGER\", \"\"),\n new Column(\"stores_id\", \"INTEGER\", \"\"),\n new Column(\"warehouse_name\", \"VARCHAR(60)\", \"\"),\n new Column(\"wa_address1\", \"VARCHAR(30)\", \"\"),\n new Column(\"wa_address2\", \"VARCHAR(30)\", \"\"),\n new Column(\"wa_address3\", \"VARCHAR(30)\", \"\"),\n new Column(\"wa_address4\", \"VARCHAR(30)\", \"\"),\n new Column(\"warehouse_city\", \"VARCHAR(30)\", \"\"),\n new Column(\"warehouse_state_province\", \"VARCHAR(30)\", \"\"),\n new Column(\"warehouse_postal_code\", \"VARCHAR(30)\", \"\"),\n new Column(\"warehouse_country\", \"VARCHAR(30)\", \"\"),\n new Column(\"warehouse_owner_name\", \"VARCHAR(30)\", \"\"),\n new Column(\"warehouse_phone\", \"VARCHAR(30)\", \"\"),\n new Column(\"warehouse_fax\", \"VARCHAR(30)\", \"\"),\n });\n createTable(\"warehouse_class\", new Column[] {\n new Column(\"warehouse_class_id\", \"INTEGER\", \"NOT NULL\"),\n new Column(\"description\", \"VARCHAR(30)\", \"\"),\n });\n if (outputDirectory != null) {\n fileOutput.close();\n }\n }\n\n /**\n * If we are outputting to JDBC, and not creating tables, delete all rows.\n *\n * Otherwise:\n *\n * Generate the SQL CREATE TABLE statement.\n *\n * If we are outputting to JDBC,\n * Execute a DROP TABLE statement\n * Execute the CREATE TABLE statement\n *\n * Otherwise,\n * output the statement to a file.\n *\n * @param name\n * @param columns\n */\n private void createTable(String name, Column[] columns) {\n try {\n // Define the table.\n mapTableNameToColumns.put(name, columns);\n if (!tables) {\n if (data && jdbcOutput) {\n // We're going to load the data without [re]creating\n // the table, so let's remove the data.\n try {\n executeDDL(\"DELETE FROM \" + quoteId(name));\n } catch (SQLException e) {\n throw MondrianResource.instance().newCreateTableFailed(name, e);\n }\n }\n return;\n }\n // If table does not exist, that is OK\n try {\n \texecuteDDL(\"DROP TABLE \" + quoteId(name));\n } catch (Exception e) {\n \tif (verbose) {\n \t\tSystem.out.println(\"Drop of \" + name + \" failed. Ignored\");\n \t}\n }\n StringBuffer buf = new StringBuffer();\n buf.append(\"CREATE TABLE \").append(quoteId(name)).append(\"(\");\n for (int i = 0; i < columns.length; i++) {\n Column column = columns[i];\n if (i > 0) {\n buf.append(\",\");\n }\n buf.append(nl);\n buf.append(\" \").append(quoteId(column.name)).append(\" \")\n .append(column.type);\n if (!column.constraint.equals(\"\")) {\n buf.append(\" \").append(column.constraint);\n }\n }\n buf.append(\")\");\n final String ddl = buf.toString();\n executeDDL(ddl);\n } catch (Exception e) {\n throw MondrianResource.instance().newCreateTableFailed(name, e);\n }\n }\n \n private void executeDDL(String ddl) throws Exception {\n if (verbose) {\n System.out.println(ddl);\n }\n if (jdbcOutput) {\n final Statement statement = connection.createStatement();\n statement.execute(ddl);\n } else {\n fileOutput.write(ddl);\n fileOutput.write(\";\\n\");\n }\n\n }\n\n /**\n * Quote the given SQL identifier suitable for the output DBMS.\n * @param name\n * @return\n */\n private String quoteId(String name) {\n return sqlQuery.quoteIdentifier(name);\n }\n\n /**\n * String representation of the column in the result set, suitable for\n * inclusion in a SQL insert statement.\n *\n * The column in the result set is transformed according to the type in\n * the column parameter.\n *\n * Different DBMSs return different Java types for a given column.\n * ClassCastExceptions may occur.\n *\n * @param rs ResultSet row to process\n * @param column Column to process\n * @return String representation of column value\n * @throws Exception\n */\n private String columnValue(ResultSet rs, Column column) throws Exception {\n\n Object obj = rs.getObject(column.name);\n String columnType = column.type;\n\n if (obj == null) {\n return \"NULL\";\n }\n\n /*\n * Output for an INTEGER column, handling Doubles and Integers\n * in the result set\n */\n if (columnType.startsWith(\"INTEGER\")) {\n if (obj.getClass() == Double.class) {\n try {\n Double result = (Double) obj;\n return integerFormatter.format(result.doubleValue());\n } catch (ClassCastException cce) {\n System.out.println(\"CCE: \" + column.name + \" to Long from: \" + obj.getClass().getName() + \" - \" + obj.toString());\n throw cce;\n }\n } else {\n try {\n Integer result = (Integer) obj;\n return result.toString();\n } catch (ClassCastException cce) {\n System.out.println(\"CCE: \" + column.name + \" to Integer from: \" + obj.getClass().getName() + \" - \" + obj.toString());\n throw cce;\n }\n }\n\n /*\n * Output for an SMALLINT column, handling Integers\n * in the result set\n */\n } else if (columnType.startsWith(\"SMALLINT\")) {\n if (obj.getClass() == Boolean.class) {\n Boolean result = (Boolean) obj;\n if (result.booleanValue()) {\n return \"1\";\n } else {\n return \"0\";\n }\n } else {\n try {\n Integer result = (Integer) obj;\n return result.toString();\n } catch (ClassCastException cce) {\n System.out.println(\"CCE: \" + column.name + \" to Integer from: \" + obj.getClass().getName() + \" - \" + obj.toString());\n throw cce;\n }\n }\n /*\n * Output for an BIGINT column, handling Doubles and Longs\n * in the result set\n */\n } else if (columnType.startsWith(\"BIGINT\")) {\n if (obj.getClass() == Double.class) {\n try {\n Double result = (Double) obj;\n return integerFormatter.format(result.doubleValue());\n } catch (ClassCastException cce) {\n System.out.println(\"CCE: \" + column.name + \" to Double from: \" + obj.getClass().getName() + \" - \" + obj.toString());\n throw cce;\n }\n } else {\n try {\n Long result = (Long) obj;\n return result.toString();\n } catch (ClassCastException cce) {\n System.out.println(\"CCE: \" + column.name + \" to Long from: \" + obj.getClass().getName() + \" - \" + obj.toString());\n throw cce;\n }\n }\n\n /*\n * Output for a String, managing embedded quotes\n */\n } else if (columnType.startsWith(\"VARCHAR\")) {\n return embedQuotes((String) obj);\n\n /*\n * Output for a TIMESTAMP\n */\n } else if (columnType.startsWith(\"TIMESTAMP\")) {\n Timestamp ts = (Timestamp) obj;\n if (sqlQuery.isOracle()) {\n return \"TIMESTAMP '\" + ts + \"'\";\n } else {\n return \"'\" + ts + \"'\";\n }\n //return \"'\" + ts + \"'\" ;\n\n /*\n * Output for a DATE\n */\n } else if (columnType.startsWith(\"DATE\")) {\n Date dt = (Date) obj;\n if (sqlQuery.isOracle()) {\n return \"DATE '\" + dateFormatter.format(dt) + \"'\";\n } else {\n return \"'\" + dateFormatter.format(dt) + \"'\";\n }\n\n /*\n * Output for a FLOAT\n */\n } else if (columnType.startsWith(\"REAL\")) {\n Float result = (Float) obj;\n return result.toString();\n\n /*\n * Output for a DECIMAL(length, places)\n */\n } else if (columnType.startsWith(\"DECIMAL\")) {\n final Matcher matcher = decimalDataTypeRegex.matcher(columnType);\n if (!matcher.matches()) {\n throw new Exception(\"Bad DECIMAL column type for \" + columnType);\n }\n DecimalFormat formatter = new DecimalFormat(decimalFormat(matcher.group(1), matcher.group(2)));\n if (obj.getClass() == Double.class) {\n try {\n Double result = (Double) obj;\n return formatter.format(result.doubleValue());\n } catch (ClassCastException cce) {\n System.out.println(\"CCE: \" + column.name + \" to Double from: \" + obj.getClass().getName() + \" - \" + obj.toString());\n throw cce;\n }\n } else {\n // should be (obj.getClass() == BigDecimal.class)\n try {\n BigDecimal result = (BigDecimal) obj;\n return formatter.format(result);\n } catch (ClassCastException cce) {\n System.out.println(\"CCE: \" + column.name + \" to BigDecimal from: \" + obj.getClass().getName() + \" - \" + obj.toString());\n throw cce;\n }\n }\n\n /*\n * Output for a BOOLEAN (Postgres) or BIT (other DBMSs)\n */\n } else if (columnType.startsWith(\"BOOLEAN\") || columnType.startsWith(\"BIT\")) {\n Boolean result = (Boolean) obj;\n return result.toString();\n }\n throw new Exception(\"Unknown column type: \" + columnType + \" for column: \" + column.name);\n }\n\n private String columnValue(String columnValue, Column column) throws Exception {\n String columnType = column.type;\n\n if (columnValue == null) {\n return \"NULL\";\n }\n\n /*\n * Output for a TIMESTAMP\n */\n if (columnType.startsWith(\"TIMESTAMP\")) {\n if (sqlQuery.isOracle()) {\n return \"TIMESTAMP \" + columnValue;\n }\n\n /*\n * Output for a DATE\n */\n } else if (columnType.startsWith(\"DATE\")) {\n if (sqlQuery.isOracle()) {\n return \"DATE \" + columnValue;\n }\n\n /*\n * Output for a BOOLEAN (Postgres) or BIT (other DBMSs)\n *\n * FIXME This code assumes that only a boolean column would\n * map onto booleanColumnType. It would be better if we had a\n * logical and physical type for each column.\n */\n } else if (columnType.equals(booleanColumnType)) {\n String trimmedValue = columnValue.trim();\n if (!sqlQuery.isMySQL() &&\n !sqlQuery.isOracle()) {\n if (trimmedValue.equals(\"1\")) {\n return \"true\";\n } else if (trimmedValue.equals(\"0\")) {\n return \"false\";\n }\n } else {\n if (trimmedValue.equals(\"true\")) {\n return \"1\";\n } else if (trimmedValue.equals(\"false\")) {\n return \"0\";\n }\n }\n }\n return columnValue;\n //throw new Exception(\"Unknown column type: \" + columnType + \" for column: \" + column.name);\n }\n\n /**\n * Generate an appropriate string to use in an SQL insert statement for\n * a VARCHAR colummn, taking into account NULL strings and strings with embedded\n * quotes\n *\n * @param original String to transform\n * @return NULL if null string, otherwise massaged string with doubled quotes\n * for SQL\n */\n private String embedQuotes(String original) {\n if (original == null) {\n return \"NULL\";\n }\n StringBuffer sb = new StringBuffer();\n\n sb.append(\"'\");\n for (int i = 0; i < original.length(); i++) {\n char ch = original.charAt(i);\n sb.append(ch);\n if (ch == '\\'') {\n sb.append('\\'');\n }\n }\n sb.append(\"'\");\n return sb.toString();\n }\n\n /**\n * Generate an appropriate number format string for doubles etc\n * to be used to include a number in an SQL insert statement.\n *\n * Calls decimalFormat(int length, int places) to do the work.\n *\n * @param lengthStr String representing integer: number of digits to format\n * @param placesStr String representing integer: number of decimal places\n * @return number format, ie. length = 6, places = 2 => \"####.##\"\n */\n private static String decimalFormat(String lengthStr, String placesStr) {\n\n int length = Integer.parseInt(lengthStr);\n int places = Integer.parseInt(placesStr);\n return decimalFormat(length, places);\n }\n\n /**\n * Generate an appropriate number format string for doubles etc\n * to be used to include a number in an SQL insert statement.\n *\n * @param length int: number of digits to format\n * @param places int: number of decimal places\n * @return number format, ie. length = 6, places = 2 => \"###0.00\"\n */\n private static String decimalFormat(int length, int places) {\n StringBuffer sb = new StringBuffer();\n for (int i = 0; i < length; i++) {\n if ((length - i) == places) {\n sb.append('.');\n }\n if ((length - i) <= (places + 1)) {\n sb.append(\"0\");\n } else {\n sb.append(\"#\");\n }\n }\n return sb.toString();\n }\n\n private static class Column {\n private final String name;\n private final String type;\n private final String constraint;\n\n public Column(String name, String type, String constraint) {\n this.name = name;\n this.type = type;\n this.constraint = constraint;\n }\n }\n}\n\n\n// End MondrianFoodMartLoader.java\n"},"message":{"kind":"string","value":"MONDRIAN: Added customer.fullname column. Allow flexibility in the loadFromFile to cope with non-MySQL insert statements\n\n[git-p4: depot-paths = \"//open/mondrian/\": change = 3467]\n"},"old_file":{"kind":"string","value":"testsrc/main/mondrian/test/loader/MondrianFoodMartLoader.java"},"subject":{"kind":"string","value":"MONDRIAN: Added customer.fullname column. Allow flexibility in the loadFromFile to cope with non-MySQL insert statements"},"git_diff":{"kind":"string","value":"estsrc/main/mondrian/test/loader/MondrianFoodMartLoader.java\n * Parse a file of INSERT statements and output to the configured JDBC\n * connection or another file in the dialect of the target data source.\n *\n * The assumption is that the input INSERT statements are out of MySQL, generated\n * The assumption is that the input INSERT statements are generated\n * by this loader by something like:\n *\n * MondrianFoodLoader\n try {\n final InputStreamReader reader = new InputStreamReader(is);\n final BufferedReader bufferedReader = new BufferedReader(reader);\n final Pattern regex = Pattern.compile(\"INSERT INTO `([^ ]+)` \\\\((.*)\\\\) VALUES\\\\((.*)\\\\);\");\n final Pattern mySQLRegex = Pattern.compile(\"INSERT INTO `([^ ]+)` \\\\((.*)\\\\) VALUES\\\\((.*)\\\\);\");\n final Pattern doubleQuoteRegex = Pattern.compile(\"INSERT INTO \\\"([^ ]+)\\\" \\\\((.*)\\\\) VALUES\\\\((.*)\\\\);\");\n String line;\n int lineNumber = 0;\n int tableRowCount = 0;\n String[] batch = new String[inputBatchSize];\n int batchSize = 0;\n \n Pattern regex = null;\n String quoteChar = null;\n \n while ((line = bufferedReader.readLine()) != null) {\n ++lineNumber;\n if (line.startsWith(\"#\")) {\n continue;\n }\n if (regex == null) {\n \tMatcher m1 = mySQLRegex.matcher(line);\n \tif (m1.matches()) {\n \t\tregex = mySQLRegex;\n \t\tquoteChar = \"`\";\n \t} else {\n \t\tregex = doubleQuoteRegex;\n \t\tquoteChar = \"\\\"\";\n \t}\n }\n // Split the up the line. For example,\n // INSERT INTO `foo` ( `column1`,`column2` ) VALUES (1, 'bar');\n batchSize = 0;\n prevTable = tableName;\n quotedTableName = quoteId(tableName);\n quotedColumnNames = columnNames\n .replaceAll(\"`\", sqlQuery.getQuoteIdentifierString());\n String[] splitColumnNames = columnNames.replaceAll(\"`\", \"\")\n .replaceAll(\" \", \"\").split(\",\");\n quotedColumnNames = columnNames.replaceAll(quoteChar, \n \t\t\t\t\t\t\t\t\tsqlQuery.getQuoteIdentifierString());\n String[] splitColumnNames = columnNames.replaceAll(quoteChar, \"\")\n \t\t\t\t\t\t.replaceAll(\" \", \"\").split(\",\");\n Column[] columns = (Column[]) mapTableNameToColumns.get(tableName);\n \n orderedColumns = new Column[columns.length];\n new Column(\"occupation\", \"VARCHAR(30)\", \"\"),\n new Column(\"houseowner\", \"VARCHAR(30)\", \"\"),\n new Column(\"num_cars_owned\", \"INTEGER\", \"\"),\n new Column(\"fullname\", \"VARCHAR(60)\", \"NOT NULL\"),\n });\n createTable(\"days\", new Column[] {\n new Column(\"day\", \"INTEGER\", \"NOT NULL\"),"}}},{"rowIdx":1920,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"6b354fd3bb4956f28dec54bbd498a2e9f67ce387"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"openzipkin/zipkin,twitter/zipkin,abesto/zipkin,twitter/zipkin,adriancole/zipkin,twitter/zipkin,openzipkin/zipkin,adriancole/zipkin,abesto/zipkin,abesto/zipkin,twitter/zipkin,abesto/zipkin,openzipkin/zipkin,adriancole/zipkin,openzipkin/zipkin,adriancole/zipkin,openzipkin/zipkin"},"new_contents":{"kind":"string","value":"/**\n * Copyright 2015 The OpenZipkin Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the License\n * is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express\n * or implied. See the License for the specific language governing permissions and limitations under\n * the License.\n */\npackage io.zipkin.jdbc;\n\nimport io.zipkin.Annotation;\nimport io.zipkin.BinaryAnnotation;\nimport io.zipkin.BinaryAnnotation.Type;\nimport io.zipkin.Dependencies;\nimport io.zipkin.DependencyLink;\nimport io.zipkin.Endpoint;\nimport io.zipkin.QueryRequest;\nimport io.zipkin.Span;\nimport io.zipkin.SpanStore;\nimport io.zipkin.internal.Nullable;\nimport io.zipkin.internal.Pair;\nimport io.zipkin.internal.Util;\nimport io.zipkin.jdbc.internal.generated.tables.ZipkinAnnotations;\nimport java.nio.charset.Charset;\nimport java.sql.Connection;\nimport java.sql.SQLException;\nimport java.util.ArrayList;\nimport java.util.Comparator;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.stream.Collectors;\nimport javax.sql.DataSource;\nimport org.jooq.DSLContext;\nimport org.jooq.ExecuteListenerProvider;\nimport org.jooq.Field;\nimport org.jooq.InsertSetMoreStep;\nimport org.jooq.Query;\nimport org.jooq.Record;\nimport org.jooq.Record1;\nimport org.jooq.Record2;\nimport org.jooq.Record3;\nimport org.jooq.SelectConditionStep;\nimport org.jooq.SelectOffsetStep;\nimport org.jooq.Table;\nimport org.jooq.conf.Settings;\nimport org.jooq.impl.DSL;\nimport org.jooq.impl.DefaultConfiguration;\nimport org.jooq.tools.jdbc.JDBCUtils;\n\nimport static io.zipkin.BinaryAnnotation.Type.STRING;\nimport static io.zipkin.internal.Util.checkNotNull;\nimport static io.zipkin.jdbc.internal.generated.tables.ZipkinAnnotations.ZIPKIN_ANNOTATIONS;\nimport static io.zipkin.jdbc.internal.generated.tables.ZipkinSpans.ZIPKIN_SPANS;\nimport static java.util.Collections.emptyList;\nimport static java.util.concurrent.TimeUnit.DAYS;\nimport static java.util.concurrent.TimeUnit.MICROSECONDS;\nimport static java.util.stream.Collectors.groupingBy;\n\npublic final class JDBCSpanStore implements SpanStore {\n\n private static final Charset UTF_8 = Charset.forName(\"UTF-8\");\n\n {\n System.setProperty(\"org.jooq.no-logo\", \"true\");\n }\n\n private final DataSource datasource;\n private final Settings settings;\n private final ExecuteListenerProvider listenerProvider;\n\n public JDBCSpanStore(DataSource datasource, Settings settings, @Nullable ExecuteListenerProvider listenerProvider) {\n this.datasource = checkNotNull(datasource, \"datasource\");\n this.settings = checkNotNull(settings, \"settings\");\n this.listenerProvider = listenerProvider;\n }\n\n void clear() throws SQLException {\n try (Connection conn = this.datasource.getConnection()) {\n context(conn).truncate(ZIPKIN_SPANS).execute();\n context(conn).truncate(ZIPKIN_ANNOTATIONS).execute();\n }\n }\n\n @Override\n public void accept(List spans) {\n try (Connection conn = this.datasource.getConnection()) {\n DSLContext create = context(conn);\n\n List inserts = new ArrayList<>();\n\n for (Span span : spans) {\n Long startTs = span.annotations.stream()\n .map(a -> a.timestamp)\n .min(Comparator.naturalOrder()).orElse(null);\n\n inserts.add(create.insertInto(ZIPKIN_SPANS)\n .set(ZIPKIN_SPANS.TRACE_ID, span.traceId)\n .set(ZIPKIN_SPANS.ID, span.id)\n .set(ZIPKIN_SPANS.NAME, span.name)\n .set(ZIPKIN_SPANS.PARENT_ID, span.parentId)\n .set(ZIPKIN_SPANS.DEBUG, span.debug)\n .set(ZIPKIN_SPANS.START_TS, startTs)\n .onDuplicateKeyIgnore()\n );\n\n for (Annotation annotation : span.annotations) {\n InsertSetMoreStep insert = create.insertInto(ZIPKIN_ANNOTATIONS)\n .set(ZIPKIN_ANNOTATIONS.TRACE_ID, span.traceId)\n .set(ZIPKIN_ANNOTATIONS.SPAN_ID, span.id)\n .set(ZIPKIN_ANNOTATIONS.A_KEY, annotation.value)\n .set(ZIPKIN_ANNOTATIONS.A_TYPE, -1)\n .set(ZIPKIN_ANNOTATIONS.A_TIMESTAMP, annotation.timestamp);\n if (annotation.endpoint != null) {\n insert.set(ZIPKIN_ANNOTATIONS.ENDPOINT_SERVICE_NAME, annotation.endpoint.serviceName);\n insert.set(ZIPKIN_ANNOTATIONS.ENDPOINT_IPV4, annotation.endpoint.ipv4);\n insert.set(ZIPKIN_ANNOTATIONS.ENDPOINT_PORT, annotation.endpoint.port);\n }\n inserts.add(insert.onDuplicateKeyIgnore());\n }\n\n for (BinaryAnnotation annotation : span.binaryAnnotations) {\n InsertSetMoreStep insert = create.insertInto(ZIPKIN_ANNOTATIONS)\n .set(ZIPKIN_ANNOTATIONS.TRACE_ID, span.traceId)\n .set(ZIPKIN_ANNOTATIONS.SPAN_ID, span.id)\n .set(ZIPKIN_ANNOTATIONS.A_KEY, annotation.key)\n .set(ZIPKIN_ANNOTATIONS.A_VALUE, annotation.value)\n .set(ZIPKIN_ANNOTATIONS.A_TYPE, annotation.type.value)\n .set(ZIPKIN_ANNOTATIONS.A_TIMESTAMP, span.endTs());\n if (annotation.endpoint != null) {\n insert.set(ZIPKIN_ANNOTATIONS.ENDPOINT_SERVICE_NAME, annotation.endpoint.serviceName);\n insert.set(ZIPKIN_ANNOTATIONS.ENDPOINT_IPV4, annotation.endpoint.ipv4);\n insert.set(ZIPKIN_ANNOTATIONS.ENDPOINT_PORT, annotation.endpoint.port);\n }\n inserts.add(insert.onDuplicateKeyIgnore());\n }\n }\n create.batch(inserts).execute();\n } catch (SQLException e) {\n throw new RuntimeException(e); // TODO\n }\n }\n\n private List> getTraces(@Nullable QueryRequest request, @Nullable List traceIds) {\n final Map> spansWithoutAnnotations;\n final Map, List> dbAnnotations;\n try (Connection conn = this.datasource.getConnection()) {\n if (request != null) {\n traceIds = toTraceIdQuery(context(conn), request).fetch(ZIPKIN_SPANS.TRACE_ID);\n }\n spansWithoutAnnotations = context(conn)\n .selectFrom(ZIPKIN_SPANS).where(ZIPKIN_SPANS.TRACE_ID.in(traceIds))\n .orderBy(ZIPKIN_SPANS.START_TS.asc())\n .stream()\n .map(r -> new Span.Builder()\n .traceId(r.getValue(ZIPKIN_SPANS.TRACE_ID))\n .name(r.getValue(ZIPKIN_SPANS.NAME))\n .id(r.getValue(ZIPKIN_SPANS.ID))\n .parentId(r.getValue(ZIPKIN_SPANS.PARENT_ID))\n .debug(r.getValue(ZIPKIN_SPANS.DEBUG))\n .build())\n .collect(groupingBy((Span s) -> s.traceId, LinkedHashMap::new, Collectors.toList()));\n\n dbAnnotations = context(conn)\n .selectFrom(ZIPKIN_ANNOTATIONS)\n .where(ZIPKIN_ANNOTATIONS.TRACE_ID.in(spansWithoutAnnotations.keySet()))\n .orderBy(ZIPKIN_ANNOTATIONS.A_TIMESTAMP.asc(), ZIPKIN_ANNOTATIONS.A_KEY.asc())\n .stream()\n .collect(groupingBy((Record a) -> Pair.create(\n a.getValue(ZIPKIN_ANNOTATIONS.TRACE_ID),\n a.getValue(ZIPKIN_ANNOTATIONS.SPAN_ID)\n ), LinkedHashMap::new, Collectors.toList())); // LinkedHashMap preserves order while grouping\n } catch (SQLException e) {\n throw new RuntimeException(\"Error querying for \" + request + \": \" + e.getMessage());\n }\n\n List> result = new ArrayList<>(spansWithoutAnnotations.keySet().size());\n for (List spans : spansWithoutAnnotations.values()) {\n List trace = new ArrayList<>(spans.size());\n for (Span s : spans) {\n Span.Builder span = new Span.Builder(s);\n Pair key = Pair.create(s.traceId, s.id);\n\n if (dbAnnotations.containsKey(key)) {\n for (Record a : dbAnnotations.get(key)) {\n Endpoint endpoint = endpoint(a);\n int type = a.getValue(ZIPKIN_ANNOTATIONS.A_TYPE);\n if (type == -1) {\n span.addAnnotation(Annotation.create(\n a.getValue(ZIPKIN_ANNOTATIONS.A_TIMESTAMP),\n a.getValue(ZIPKIN_ANNOTATIONS.A_KEY),\n endpoint));\n } else {\n span.addBinaryAnnotation(BinaryAnnotation.create(\n a.getValue(ZIPKIN_ANNOTATIONS.A_KEY),\n a.getValue(ZIPKIN_ANNOTATIONS.A_VALUE),\n Type.fromValue(type),\n endpoint));\n }\n }\n }\n trace.add(span.build());\n }\n result.add(Util.merge(trace));\n }\n return result;\n }\n\n @Override\n public List> getTraces(QueryRequest request) {\n return getTraces(request, null);\n }\n\n private DSLContext context(Connection conn) {\n return DSL.using(new DefaultConfiguration()\n .set(conn)\n .set(JDBCUtils.dialect(conn))\n .set(this.settings)\n .set(this.listenerProvider));\n }\n\n @Override\n public List> getTracesByIds(List traceIds) {\n return traceIds.isEmpty() ? emptyList() : getTraces(null, traceIds);\n }\n\n @Override\n public List getServiceNames() {\n try (Connection conn = this.datasource.getConnection()) {\n return context(conn)\n .selectDistinct(ZIPKIN_ANNOTATIONS.ENDPOINT_SERVICE_NAME)\n .from(ZIPKIN_ANNOTATIONS)\n .where(ZIPKIN_ANNOTATIONS.ENDPOINT_SERVICE_NAME.isNotNull())\n .fetch(ZIPKIN_ANNOTATIONS.ENDPOINT_SERVICE_NAME);\n } catch (SQLException e) {\n throw new RuntimeException(\"Error querying for \" + e + \": \" + e.getMessage());\n }\n }\n\n @Override\n public List getSpanNames(String serviceName) {\n if (serviceName == null) return emptyList();\n try (Connection conn = this.datasource.getConnection()) {\n return context(conn)\n .selectDistinct(ZIPKIN_SPANS.NAME)\n .from(ZIPKIN_SPANS)\n .join(ZIPKIN_ANNOTATIONS)\n .on(ZIPKIN_SPANS.TRACE_ID.eq(ZIPKIN_ANNOTATIONS.TRACE_ID))\n .and(ZIPKIN_SPANS.ID.eq(ZIPKIN_ANNOTATIONS.SPAN_ID))\n .where(ZIPKIN_ANNOTATIONS.ENDPOINT_SERVICE_NAME.eq(serviceName))\n .orderBy(ZIPKIN_SPANS.NAME)\n .fetch(ZIPKIN_SPANS.NAME);\n } catch (SQLException e) {\n throw new RuntimeException(\"Error querying for \" + serviceName + \": \" + e.getMessage());\n }\n }\n\n @Override\n public Dependencies getDependencies(@Nullable Long startTs, @Nullable Long endTs) {\n if (endTs == null) {\n endTs = System.currentTimeMillis() * 1000;\n }\n if (startTs == null) {\n startTs = endTs - MICROSECONDS.convert(1, DAYS);\n }\n try (Connection conn = this.datasource.getConnection()) {\n Map>> parentChild = context(conn)\n .select(ZIPKIN_SPANS.TRACE_ID, ZIPKIN_SPANS.PARENT_ID, ZIPKIN_SPANS.ID)\n .from(ZIPKIN_SPANS)\n .where(ZIPKIN_SPANS.START_TS.between(startTs, endTs))\n .and(ZIPKIN_SPANS.PARENT_ID.isNotNull())\n .stream().collect(Collectors.groupingBy(r -> r.value1()));\n\n Map, String> traceSpanServiceName = traceSpanServiceName(conn, parentChild.keySet());\n\n Dependencies.Builder result = new Dependencies.Builder().startTs(startTs).endTs(endTs);\n\n parentChild.values().stream().flatMap(List::stream).forEach(r -> {\n String parent = traceSpanServiceName.get(Pair.create(r.value1(), r.value2()));\n // can be null if a root span is missing, or the root's span id doesn't eq the trace id\n if (parent != null) {\n String child = traceSpanServiceName.get(Pair.create(r.value1(), r.value3()));\n DependencyLink link = new DependencyLink.Builder()\n .parent(parent)\n .child(child)\n .callCount(1).build();\n result.addLink(link);\n }\n });\n\n return result.build();\n } catch (SQLException e) {\n throw new RuntimeException(\"Error querying dependencies between \" + startTs + \" and \" + endTs + \": \" + e.getMessage());\n }\n }\n\n private Map, String> traceSpanServiceName(Connection conn, Set traceIds) {\n return context(conn)\n .selectDistinct(ZIPKIN_ANNOTATIONS.TRACE_ID, ZIPKIN_ANNOTATIONS.SPAN_ID, ZIPKIN_ANNOTATIONS.ENDPOINT_SERVICE_NAME)\n .from(ZIPKIN_ANNOTATIONS)\n .where(ZIPKIN_ANNOTATIONS.TRACE_ID.in(traceIds))\n .and(ZIPKIN_ANNOTATIONS.ENDPOINT_SERVICE_NAME.isNotNull())\n .groupBy(ZIPKIN_ANNOTATIONS.TRACE_ID, ZIPKIN_ANNOTATIONS.SPAN_ID)\n .fetchMap(r -> Pair.create(r.value1(), r.value2()), r -> r.value3());\n }\n\n @Override\n public void close() {\n }\n\n static Endpoint endpoint(Record a) {\n String serviceName = a.getValue(ZIPKIN_ANNOTATIONS.ENDPOINT_SERVICE_NAME);\n if (serviceName == null) {\n return null;\n }\n return Endpoint.create(\n serviceName,\n a.getValue(ZIPKIN_ANNOTATIONS.ENDPOINT_IPV4),\n a.getValue(ZIPKIN_ANNOTATIONS.ENDPOINT_PORT).intValue());\n }\n\n static SelectOffsetStep> toTraceIdQuery(DSLContext context, QueryRequest request) {\n long endTs = (request.endTs > 0 && request.endTs != Long.MAX_VALUE) ? request.endTs\n : System.currentTimeMillis() / 1000;\n\n Field lastTimestamp = ZIPKIN_ANNOTATIONS.A_TIMESTAMP.max().as(\"last_timestamp\");\n Table> a1 = context.selectDistinct(ZIPKIN_ANNOTATIONS.TRACE_ID, lastTimestamp)\n .from(ZIPKIN_ANNOTATIONS)\n .where(ZIPKIN_ANNOTATIONS.ENDPOINT_SERVICE_NAME.eq(request.serviceName))\n .groupBy(ZIPKIN_ANNOTATIONS.TRACE_ID).asTable();\n\n Table table = ZIPKIN_SPANS.join(a1)\n .on(ZIPKIN_SPANS.TRACE_ID.eq(a1.field(ZIPKIN_ANNOTATIONS.TRACE_ID)));\n\n Map keyToTables = new LinkedHashMap<>();\n int i = 0;\n for (String key : request.binaryAnnotations.keySet()) {\n keyToTables.put(key, ZIPKIN_ANNOTATIONS.as(\"a\" + i++));\n table = join(table, keyToTables.get(key), key, STRING.value);\n }\n\n for (String key : request.annotations) {\n keyToTables.put(key, ZIPKIN_ANNOTATIONS.as(\"a\" + i++));\n table = join(table, keyToTables.get(key), key, -1);\n }\n\n SelectConditionStep> dsl = context.selectDistinct(ZIPKIN_SPANS.TRACE_ID)\n .from(table)\n .where(lastTimestamp.le(endTs));\n\n if (request.spanName != null) {\n dsl.and(ZIPKIN_SPANS.NAME.eq(request.spanName));\n }\n\n for (Map.Entry entry : request.binaryAnnotations.entrySet()) {\n dsl.and(keyToTables.get(entry.getKey()).A_VALUE.eq(entry.getValue().getBytes(UTF_8)));\n }\n return dsl.limit(request.limit);\n }\n\n private static Table join(Table table, ZipkinAnnotations joinTable, String key, int type) {\n table = table.join(joinTable)\n .on(ZIPKIN_SPANS.TRACE_ID.eq(joinTable.TRACE_ID))\n .and(ZIPKIN_SPANS.ID.eq(joinTable.SPAN_ID))\n .and(joinTable.A_TYPE.eq(type))\n .and(joinTable.A_KEY.eq(key));\n return table;\n }\n}\n"},"new_file":{"kind":"string","value":"zipkin-java-jdbc/src/main/java/io/zipkin/jdbc/JDBCSpanStore.java"},"old_contents":{"kind":"string","value":"/**\n * Copyright 2015 The OpenZipkin Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the License\n * is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express\n * or implied. See the License for the specific language governing permissions and limitations under\n * the License.\n */\npackage io.zipkin.jdbc;\n\nimport io.zipkin.Annotation;\nimport io.zipkin.BinaryAnnotation;\nimport io.zipkin.BinaryAnnotation.Type;\nimport io.zipkin.Dependencies;\nimport io.zipkin.DependencyLink;\nimport io.zipkin.Endpoint;\nimport io.zipkin.QueryRequest;\nimport io.zipkin.Span;\nimport io.zipkin.SpanStore;\nimport io.zipkin.internal.Nullable;\nimport io.zipkin.internal.Pair;\nimport io.zipkin.internal.Util;\nimport io.zipkin.jdbc.internal.generated.tables.ZipkinAnnotations;\nimport java.nio.charset.Charset;\nimport java.sql.Connection;\nimport java.sql.SQLException;\nimport java.util.ArrayList;\nimport java.util.Comparator;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.stream.Collectors;\nimport javax.sql.DataSource;\nimport org.jooq.DSLContext;\nimport org.jooq.ExecuteListenerProvider;\nimport org.jooq.Field;\nimport org.jooq.InsertSetMoreStep;\nimport org.jooq.Query;\nimport org.jooq.Record;\nimport org.jooq.Record1;\nimport org.jooq.Record2;\nimport org.jooq.Record3;\nimport org.jooq.SelectConditionStep;\nimport org.jooq.SelectOffsetStep;\nimport org.jooq.Table;\nimport org.jooq.conf.Settings;\nimport org.jooq.impl.DSL;\nimport org.jooq.impl.DefaultConfiguration;\nimport org.jooq.tools.jdbc.JDBCUtils;\n\nimport static io.zipkin.BinaryAnnotation.Type.STRING;\nimport static io.zipkin.internal.Util.checkNotNull;\nimport static io.zipkin.jdbc.internal.generated.tables.ZipkinAnnotations.ZIPKIN_ANNOTATIONS;\nimport static io.zipkin.jdbc.internal.generated.tables.ZipkinSpans.ZIPKIN_SPANS;\nimport static java.util.Collections.emptyList;\nimport static java.util.concurrent.TimeUnit.DAYS;\nimport static java.util.concurrent.TimeUnit.MICROSECONDS;\nimport static java.util.stream.Collectors.groupingBy;\nimport static java.util.stream.Collectors.toList;\n\npublic final class JDBCSpanStore implements SpanStore {\n\n private static final Charset UTF_8 = Charset.forName(\"UTF-8\");\n\n {\n System.setProperty(\"org.jooq.no-logo\", \"true\");\n }\n\n private final DataSource datasource;\n private final Settings settings;\n private final ExecuteListenerProvider listenerProvider;\n\n public JDBCSpanStore(DataSource datasource, Settings settings, @Nullable ExecuteListenerProvider listenerProvider) {\n this.datasource = checkNotNull(datasource, \"datasource\");\n this.settings = checkNotNull(settings, \"settings\");\n this.listenerProvider = listenerProvider;\n }\n\n void clear() throws SQLException {\n try (Connection conn = this.datasource.getConnection()) {\n context(conn).truncate(ZIPKIN_SPANS).execute();\n context(conn).truncate(ZIPKIN_ANNOTATIONS).execute();\n }\n }\n\n @Override\n public void accept(List spans) {\n try (Connection conn = this.datasource.getConnection()) {\n DSLContext create = context(conn);\n\n List inserts = new ArrayList<>();\n\n for (Span span : spans) {\n Long startTs = span.annotations.stream()\n .map(a -> a.timestamp)\n .min(Comparator.naturalOrder()).orElse(null);\n\n inserts.add(create.insertInto(ZIPKIN_SPANS)\n .set(ZIPKIN_SPANS.TRACE_ID, span.traceId)\n .set(ZIPKIN_SPANS.ID, span.id)\n .set(ZIPKIN_SPANS.NAME, span.name)\n .set(ZIPKIN_SPANS.PARENT_ID, span.parentId)\n .set(ZIPKIN_SPANS.DEBUG, span.debug)\n .set(ZIPKIN_SPANS.START_TS, startTs)\n .onDuplicateKeyIgnore()\n );\n\n for (Annotation annotation : span.annotations) {\n InsertSetMoreStep insert = create.insertInto(ZIPKIN_ANNOTATIONS)\n .set(ZIPKIN_ANNOTATIONS.TRACE_ID, span.traceId)\n .set(ZIPKIN_ANNOTATIONS.SPAN_ID, span.id)\n .set(ZIPKIN_ANNOTATIONS.A_KEY, annotation.value)\n .set(ZIPKIN_ANNOTATIONS.A_TYPE, -1)\n .set(ZIPKIN_ANNOTATIONS.A_TIMESTAMP, annotation.timestamp);\n if (annotation.endpoint != null) {\n insert.set(ZIPKIN_ANNOTATIONS.ENDPOINT_SERVICE_NAME, annotation.endpoint.serviceName);\n insert.set(ZIPKIN_ANNOTATIONS.ENDPOINT_IPV4, annotation.endpoint.ipv4);\n insert.set(ZIPKIN_ANNOTATIONS.ENDPOINT_PORT, annotation.endpoint.port);\n }\n inserts.add(insert.onDuplicateKeyIgnore());\n }\n\n for (BinaryAnnotation annotation : span.binaryAnnotations) {\n InsertSetMoreStep insert = create.insertInto(ZIPKIN_ANNOTATIONS)\n .set(ZIPKIN_ANNOTATIONS.TRACE_ID, span.traceId)\n .set(ZIPKIN_ANNOTATIONS.SPAN_ID, span.id)\n .set(ZIPKIN_ANNOTATIONS.A_KEY, annotation.key)\n .set(ZIPKIN_ANNOTATIONS.A_VALUE, annotation.value)\n .set(ZIPKIN_ANNOTATIONS.A_TYPE, annotation.type.value)\n .set(ZIPKIN_ANNOTATIONS.A_TIMESTAMP, span.endTs());\n if (annotation.endpoint != null) {\n insert.set(ZIPKIN_ANNOTATIONS.ENDPOINT_SERVICE_NAME, annotation.endpoint.serviceName);\n insert.set(ZIPKIN_ANNOTATIONS.ENDPOINT_IPV4, annotation.endpoint.ipv4);\n insert.set(ZIPKIN_ANNOTATIONS.ENDPOINT_PORT, annotation.endpoint.port);\n }\n inserts.add(insert.onDuplicateKeyIgnore());\n }\n }\n create.batch(inserts).execute();\n } catch (SQLException e) {\n throw new RuntimeException(e); // TODO\n }\n }\n\n private List> getTraces(@Nullable QueryRequest request, @Nullable List traceIds) {\n final Map> spansWithoutAnnotations;\n final Map> dbAnnotations;\n try (Connection conn = this.datasource.getConnection()) {\n if (request != null) {\n traceIds = toTraceIdQuery(context(conn), request).fetch(ZIPKIN_SPANS.TRACE_ID);\n }\n spansWithoutAnnotations = context(conn)\n .selectFrom(ZIPKIN_SPANS).where(ZIPKIN_SPANS.TRACE_ID.in(traceIds))\n .orderBy(ZIPKIN_SPANS.START_TS.asc())\n .stream()\n .map(r -> new Span.Builder()\n .traceId(r.getValue(ZIPKIN_SPANS.TRACE_ID))\n .name(r.getValue(ZIPKIN_SPANS.NAME))\n .id(r.getValue(ZIPKIN_SPANS.ID))\n .parentId(r.getValue(ZIPKIN_SPANS.PARENT_ID))\n .debug(r.getValue(ZIPKIN_SPANS.DEBUG))\n .build())\n .collect(groupingBy(s -> s.traceId, LinkedHashMap::new, toList()));\n\n dbAnnotations = context(conn)\n .selectFrom(ZIPKIN_ANNOTATIONS)\n .where(ZIPKIN_ANNOTATIONS.TRACE_ID.in(spansWithoutAnnotations.keySet()))\n .orderBy(ZIPKIN_ANNOTATIONS.A_TIMESTAMP.asc(), ZIPKIN_ANNOTATIONS.A_KEY.asc())\n .stream()\n .collect(groupingBy(a -> Pair.create(\n a.getValue(ZIPKIN_ANNOTATIONS.TRACE_ID),\n a.getValue(ZIPKIN_ANNOTATIONS.SPAN_ID)\n ), LinkedHashMap::new, toList())); // LinkedHashMap preserves order while grouping\n } catch (SQLException e) {\n throw new RuntimeException(\"Error querying for \" + request + \": \" + e.getMessage());\n }\n\n List> result = new ArrayList<>(spansWithoutAnnotations.keySet().size());\n for (List spans : spansWithoutAnnotations.values()) {\n List trace = new ArrayList<>(spans.size());\n for (Span s : spans) {\n Span.Builder span = new Span.Builder(s);\n Pair key = Pair.create(s.traceId, s.id);\n\n if (dbAnnotations.containsKey(key)) {\n for (Record a : dbAnnotations.get(key)) {\n Endpoint endpoint = endpoint(a);\n int type = a.getValue(ZIPKIN_ANNOTATIONS.A_TYPE);\n if (type == -1) {\n span.addAnnotation(Annotation.create(\n a.getValue(ZIPKIN_ANNOTATIONS.A_TIMESTAMP),\n a.getValue(ZIPKIN_ANNOTATIONS.A_KEY),\n endpoint));\n } else {\n span.addBinaryAnnotation(BinaryAnnotation.create(\n a.getValue(ZIPKIN_ANNOTATIONS.A_KEY),\n a.getValue(ZIPKIN_ANNOTATIONS.A_VALUE),\n Type.fromValue(type),\n endpoint));\n }\n }\n }\n trace.add(span.build());\n }\n result.add(Util.merge(trace));\n }\n return result;\n }\n\n @Override\n public List> getTraces(QueryRequest request) {\n return getTraces(request, null);\n }\n\n private DSLContext context(Connection conn) {\n return DSL.using(new DefaultConfiguration()\n .set(conn)\n .set(JDBCUtils.dialect(conn))\n .set(this.settings)\n .set(this.listenerProvider));\n }\n\n @Override\n public List> getTracesByIds(List traceIds) {\n return traceIds.isEmpty() ? emptyList() : getTraces(null, traceIds);\n }\n\n @Override\n public List getServiceNames() {\n try (Connection conn = this.datasource.getConnection()) {\n return context(conn)\n .selectDistinct(ZIPKIN_ANNOTATIONS.ENDPOINT_SERVICE_NAME)\n .from(ZIPKIN_ANNOTATIONS)\n .where(ZIPKIN_ANNOTATIONS.ENDPOINT_SERVICE_NAME.isNotNull())\n .fetch(ZIPKIN_ANNOTATIONS.ENDPOINT_SERVICE_NAME);\n } catch (SQLException e) {\n throw new RuntimeException(\"Error querying for \" + e + \": \" + e.getMessage());\n }\n }\n\n @Override\n public List getSpanNames(String serviceName) {\n if (serviceName == null) return emptyList();\n try (Connection conn = this.datasource.getConnection()) {\n return context(conn)\n .selectDistinct(ZIPKIN_SPANS.NAME)\n .from(ZIPKIN_SPANS)\n .join(ZIPKIN_ANNOTATIONS)\n .on(ZIPKIN_SPANS.TRACE_ID.eq(ZIPKIN_ANNOTATIONS.TRACE_ID))\n .and(ZIPKIN_SPANS.ID.eq(ZIPKIN_ANNOTATIONS.SPAN_ID))\n .where(ZIPKIN_ANNOTATIONS.ENDPOINT_SERVICE_NAME.eq(serviceName))\n .orderBy(ZIPKIN_SPANS.NAME)\n .fetch(ZIPKIN_SPANS.NAME);\n } catch (SQLException e) {\n throw new RuntimeException(\"Error querying for \" + serviceName + \": \" + e.getMessage());\n }\n }\n\n @Override\n public Dependencies getDependencies(@Nullable Long startTs, @Nullable Long endTs) {\n if (endTs == null) {\n endTs = System.currentTimeMillis() * 1000;\n }\n if (startTs == null) {\n startTs = endTs - MICROSECONDS.convert(1, DAYS);\n }\n try (Connection conn = this.datasource.getConnection()) {\n Map>> parentChild = context(conn)\n .select(ZIPKIN_SPANS.TRACE_ID, ZIPKIN_SPANS.PARENT_ID, ZIPKIN_SPANS.ID)\n .from(ZIPKIN_SPANS)\n .where(ZIPKIN_SPANS.START_TS.between(startTs, endTs))\n .and(ZIPKIN_SPANS.PARENT_ID.isNotNull())\n .stream().collect(Collectors.groupingBy(r -> r.value1()));\n\n Map, String> traceSpanServiceName = traceSpanServiceName(conn, parentChild.keySet());\n\n Dependencies.Builder result = new Dependencies.Builder().startTs(startTs).endTs(endTs);\n\n parentChild.values().stream().flatMap(List::stream).forEach(r -> {\n String parent = traceSpanServiceName.get(Pair.create(r.value1(), r.value2()));\n // can be null if a root span is missing, or the root's span id doesn't eq the trace id\n if (parent != null) {\n String child = traceSpanServiceName.get(Pair.create(r.value1(), r.value3()));\n DependencyLink link = new DependencyLink.Builder()\n .parent(parent)\n .child(child)\n .callCount(1).build();\n result.addLink(link);\n }\n });\n\n return result.build();\n } catch (SQLException e) {\n throw new RuntimeException(\"Error querying dependencies between \" + startTs + \" and \" + endTs + \": \" + e.getMessage());\n }\n }\n\n private Map, String> traceSpanServiceName(Connection conn, Set traceIds) {\n return context(conn)\n .selectDistinct(ZIPKIN_ANNOTATIONS.TRACE_ID, ZIPKIN_ANNOTATIONS.SPAN_ID, ZIPKIN_ANNOTATIONS.ENDPOINT_SERVICE_NAME)\n .from(ZIPKIN_ANNOTATIONS)\n .where(ZIPKIN_ANNOTATIONS.TRACE_ID.in(traceIds))\n .and(ZIPKIN_ANNOTATIONS.ENDPOINT_SERVICE_NAME.isNotNull())\n .groupBy(ZIPKIN_ANNOTATIONS.TRACE_ID, ZIPKIN_ANNOTATIONS.SPAN_ID)\n .fetchMap(r -> Pair.create(r.value1(), r.value2()), r -> r.value3());\n }\n\n @Override\n public void close() {\n }\n\n static Endpoint endpoint(Record a) {\n String serviceName = a.getValue(ZIPKIN_ANNOTATIONS.ENDPOINT_SERVICE_NAME);\n if (serviceName == null) {\n return null;\n }\n return Endpoint.create(\n serviceName,\n a.getValue(ZIPKIN_ANNOTATIONS.ENDPOINT_IPV4),\n a.getValue(ZIPKIN_ANNOTATIONS.ENDPOINT_PORT).intValue());\n }\n\n static SelectOffsetStep> toTraceIdQuery(DSLContext context, QueryRequest request) {\n long endTs = (request.endTs > 0 && request.endTs != Long.MAX_VALUE) ? request.endTs\n : System.currentTimeMillis() / 1000;\n\n Field lastTimestamp = ZIPKIN_ANNOTATIONS.A_TIMESTAMP.max().as(\"last_timestamp\");\n Table> a1 = context.selectDistinct(ZIPKIN_ANNOTATIONS.TRACE_ID, lastTimestamp)\n .from(ZIPKIN_ANNOTATIONS)\n .where(ZIPKIN_ANNOTATIONS.ENDPOINT_SERVICE_NAME.eq(request.serviceName))\n .groupBy(ZIPKIN_ANNOTATIONS.TRACE_ID).asTable();\n\n Table table = ZIPKIN_SPANS.join(a1)\n .on(ZIPKIN_SPANS.TRACE_ID.eq(a1.field(ZIPKIN_ANNOTATIONS.TRACE_ID)));\n\n Map keyToTables = new LinkedHashMap<>();\n int i = 0;\n for (String key : request.binaryAnnotations.keySet()) {\n keyToTables.put(key, ZIPKIN_ANNOTATIONS.as(\"a\" + i++));\n table = join(table, keyToTables.get(key), key, STRING.value);\n }\n\n for (String key : request.annotations) {\n keyToTables.put(key, ZIPKIN_ANNOTATIONS.as(\"a\" + i++));\n table = join(table, keyToTables.get(key), key, -1);\n }\n\n SelectConditionStep> dsl = context.selectDistinct(ZIPKIN_SPANS.TRACE_ID)\n .from(table)\n .where(lastTimestamp.le(endTs));\n\n if (request.spanName != null) {\n dsl.and(ZIPKIN_SPANS.NAME.eq(request.spanName));\n }\n\n for (Map.Entry entry : request.binaryAnnotations.entrySet()) {\n dsl.and(keyToTables.get(entry.getKey()).A_VALUE.eq(entry.getValue().getBytes(UTF_8)));\n }\n return dsl.limit(request.limit);\n }\n\n private static Table join(Table table, ZipkinAnnotations joinTable, String key, int type) {\n table = table.join(joinTable)\n .on(ZIPKIN_SPANS.TRACE_ID.eq(joinTable.TRACE_ID))\n .and(ZIPKIN_SPANS.ID.eq(joinTable.SPAN_ID))\n .and(joinTable.A_TYPE.eq(type))\n .and(joinTable.A_KEY.eq(key));\n return table;\n }\n}\n"},"message":{"kind":"string","value":"Fix compiler errors for Eclipse\n"},"old_file":{"kind":"string","value":"zipkin-java-jdbc/src/main/java/io/zipkin/jdbc/JDBCSpanStore.java"},"subject":{"kind":"string","value":"Fix compiler errors for Eclipse"},"git_diff":{"kind":"string","value":"ipkin-java-jdbc/src/main/java/io/zipkin/jdbc/JDBCSpanStore.java\n import static java.util.concurrent.TimeUnit.DAYS;\n import static java.util.concurrent.TimeUnit.MICROSECONDS;\n import static java.util.stream.Collectors.groupingBy;\nimport static java.util.stream.Collectors.toList;\n \n public final class JDBCSpanStore implements SpanStore {\n \n \n private List> getTraces(@Nullable QueryRequest request, @Nullable List traceIds) {\n final Map> spansWithoutAnnotations;\n final Map> dbAnnotations;\n final Map, List> dbAnnotations;\n try (Connection conn = this.datasource.getConnection()) {\n if (request != null) {\n traceIds = toTraceIdQuery(context(conn), request).fetch(ZIPKIN_SPANS.TRACE_ID);\n .parentId(r.getValue(ZIPKIN_SPANS.PARENT_ID))\n .debug(r.getValue(ZIPKIN_SPANS.DEBUG))\n .build())\n .collect(groupingBy(s -> s.traceId, LinkedHashMap::new, toList()));\n .collect(groupingBy((Span s) -> s.traceId, LinkedHashMap::new, Collectors.toList()));\n \n dbAnnotations = context(conn)\n .selectFrom(ZIPKIN_ANNOTATIONS)\n .where(ZIPKIN_ANNOTATIONS.TRACE_ID.in(spansWithoutAnnotations.keySet()))\n .orderBy(ZIPKIN_ANNOTATIONS.A_TIMESTAMP.asc(), ZIPKIN_ANNOTATIONS.A_KEY.asc())\n .stream()\n .collect(groupingBy(a -> Pair.create(\n .collect(groupingBy((Record a) -> Pair.create(\n a.getValue(ZIPKIN_ANNOTATIONS.TRACE_ID),\n a.getValue(ZIPKIN_ANNOTATIONS.SPAN_ID)\n ), LinkedHashMap::new, toList())); // LinkedHashMap preserves order while grouping\n ), LinkedHashMap::new, Collectors.toList())); // LinkedHashMap preserves order while grouping\n } catch (SQLException e) {\n throw new RuntimeException(\"Error querying for \" + request + \": \" + e.getMessage());\n }\n List trace = new ArrayList<>(spans.size());\n for (Span s : spans) {\n Span.Builder span = new Span.Builder(s);\n Pair key = Pair.create(s.traceId, s.id);\n Pair key = Pair.create(s.traceId, s.id);\n \n if (dbAnnotations.containsKey(key)) {\n for (Record a : dbAnnotations.get(key)) {"}}},{"rowIdx":1921,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"8bc670617a60b5c3fca657d70ac1517c89ff3463"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"StepicOrg/stepic-android,StepicOrg/stepik-android,StepicOrg/stepik-android,StepicOrg/stepic-android,StepicOrg/stepic-android,StepicOrg/stepik-android"},"new_contents":{"kind":"string","value":"package org.stepic.droid.base;\n\nimport android.content.Context;\nimport android.support.multidex.MultiDex;\nimport android.support.multidex.MultiDexApplication;\n\nimport com.facebook.drawee.backends.pipeline.Fresco;\nimport com.squareup.leakcanary.LeakCanary;\nimport com.squareup.leakcanary.RefWatcher;\nimport com.yandex.metrica.YandexMetrica;\n\nimport org.stepic.droid.R;\nimport org.stepic.droid.core.DaggerStepicCoreComponent;\nimport org.stepic.droid.core.StepicCoreComponent;\nimport org.stepic.droid.core.StepicDefaultModule;\n\nimport uk.co.chrisjenx.calligraphy.CalligraphyConfig;\n\npublic class MainApplication extends MultiDexApplication {\n\n protected static MainApplication application;\n private StepicCoreComponent component;\n\n private RefWatcher refWatcher;\n\n @Override\n public void onCreate() {\n super.onCreate();\n init();\n }\n\n private void init() {\n refWatcher = LeakCanary.install(this);\n application = this;\n Fresco.initialize(this);\n CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()\n .setDefaultFontPath(\"fonts/NotoSans-Regular.ttf\")\n .setFontAttrId(R.attr.fontPath)\n .build()\n );\n\n component = DaggerStepicCoreComponent.builder().\n stepicDefaultModule(new StepicDefaultModule(application)).build();\n\n // Инициализация AppMetrica SDK\n YandexMetrica.activate(getApplicationContext(), \"fd479031-bdf4-419e-8d8f-6895aab23502\");\n // Отслеживание активности пользователей\n YandexMetrica.enableActivityAutoTracking(this);\n }\n\n public static RefWatcher getRefWatcher(Context context) {\n MainApplication application = (MainApplication) context.getApplicationContext();\n return application.refWatcher;\n }\n\n public static StepicCoreComponent component(Context context) {\n return ((MainApplication) context.getApplicationContext()).component;\n }\n\n\n public static StepicCoreComponent component() {\n return ((MainApplication) getAppContext()).component;\n }\n\n\n @Override\n protected void attachBaseContext(Context base) {\n super.attachBaseContext(base);\n MultiDex.install(this);\n }\n\n public static Context getAppContext() {\n return application.getApplicationContext();\n }\n\n}\n"},"new_file":{"kind":"string","value":"app/src/main/java/org/stepic/droid/base/MainApplication.java"},"old_contents":{"kind":"string","value":"package org.stepic.droid.base;\n\nimport android.content.Context;\nimport android.support.multidex.MultiDex;\nimport android.support.multidex.MultiDexApplication;\n\nimport com.squareup.leakcanary.LeakCanary;\nimport com.squareup.leakcanary.RefWatcher;\nimport com.yandex.metrica.YandexMetrica;\n\nimport org.stepic.droid.R;\nimport org.stepic.droid.core.DaggerStepicCoreComponent;\nimport org.stepic.droid.core.StepicCoreComponent;\nimport org.stepic.droid.core.StepicDefaultModule;\n\nimport uk.co.chrisjenx.calligraphy.CalligraphyConfig;\n\npublic class MainApplication extends MultiDexApplication {\n\n protected static MainApplication application;\n private StepicCoreComponent component;\n\n private RefWatcher refWatcher;\n\n @Override\n public void onCreate() {\n super.onCreate();\n init();\n }\n\n private void init() {\n refWatcher = LeakCanary.install(this);\n application = this;\n\n CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()\n .setDefaultFontPath(\"fonts/NotoSans-Regular.ttf\")\n .setFontAttrId(R.attr.fontPath)\n .build()\n );\n\n component = DaggerStepicCoreComponent.builder().\n stepicDefaultModule(new StepicDefaultModule(application)).build();\n\n // Инициализация AppMetrica SDK\n YandexMetrica.activate(getApplicationContext(), \"fd479031-bdf4-419e-8d8f-6895aab23502\");\n // Отслеживание активности пользователей\n YandexMetrica.enableActivityAutoTracking(this);\n }\n\n public static RefWatcher getRefWatcher(Context context) {\n MainApplication application = (MainApplication) context.getApplicationContext();\n return application.refWatcher;\n }\n\n public static StepicCoreComponent component(Context context) {\n return ((MainApplication) context.getApplicationContext()).component;\n }\n\n\n public static StepicCoreComponent component() {\n return ((MainApplication) getAppContext()).component;\n }\n\n\n @Override\n protected void attachBaseContext(Context base) {\n super.attachBaseContext(base);\n MultiDex.install(this);\n }\n\n public static Context getAppContext() {\n return application.getApplicationContext();\n }\n\n}\n"},"message":{"kind":"string","value":"install fresco\n"},"old_file":{"kind":"string","value":"app/src/main/java/org/stepic/droid/base/MainApplication.java"},"subject":{"kind":"string","value":"install fresco"},"git_diff":{"kind":"string","value":"pp/src/main/java/org/stepic/droid/base/MainApplication.java\n import android.support.multidex.MultiDex;\n import android.support.multidex.MultiDexApplication;\n \nimport com.facebook.drawee.backends.pipeline.Fresco;\n import com.squareup.leakcanary.LeakCanary;\n import com.squareup.leakcanary.RefWatcher;\n import com.yandex.metrica.YandexMetrica;\n private void init() {\n refWatcher = LeakCanary.install(this);\n application = this;\n\n Fresco.initialize(this);\n CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()\n .setDefaultFontPath(\"fonts/NotoSans-Regular.ttf\")\n .setFontAttrId(R.attr.fontPath)"}}},{"rowIdx":1922,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"15eb29676f1a3218eea4c9e866af0aa16dcd522e"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"Floobits/floobits-intellij"},"new_contents":{"kind":"string","value":"package floobits.windows;\n\nimport com.intellij.openapi.application.ApplicationManager;\nimport com.intellij.openapi.application.ModalityState;\nimport com.intellij.openapi.project.Project;\nimport com.intellij.openapi.util.IconLoader;\nimport com.intellij.openapi.wm.ToolWindow;\nimport com.intellij.openapi.wm.ToolWindowAnchor;\nimport com.intellij.openapi.wm.ToolWindowManager;\nimport com.intellij.ui.content.Content;\nimport com.intellij.ui.content.ContentFactory;\nimport floobits.common.interfaces.IContext;\nimport floobits.common.FlooUrl;\nimport floobits.common.protocol.handlers.FlooHandler;\nimport floobits.common.protocol.FlooUser;\nimport floobits.impl.ContextImpl;\nimport floobits.utilities.Flog;\n\nimport java.util.*;\n\n\npublic class ChatManager {\n protected IContext context;\n protected ToolWindow toolWindow;\n protected ChatForm chatForm;\n\n public ChatManager (ContextImpl context) {\n this.context = context;\n chatForm = new ChatForm(context);\n this.createChatWindow(context.project);\n }\n\n protected void createChatWindow(Project project) {\n ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(project);\n toolWindow = toolWindowManager.registerToolWindow(\"Floobits Chat\", true, ToolWindowAnchor.BOTTOM);\n toolWindow.setIcon(IconLoader.getIcon(\"/icons/floo13.png\"));\n Content content = ContentFactory.SERVICE.getInstance().createContent(chatForm.getChatPanel(), \"\", true);\n toolWindow.getContentManager().addContent(content);\n }\n\n public void openChat() {\n FlooHandler flooHandler = context.getFlooHandler();\n if (flooHandler == null) {\n return;\n }\n try {\n toolWindow.show(null);\n } catch (NullPointerException e) {\n Flog.warn(\"Could not open chat window.\");\n return;\n }\n FlooUrl url = flooHandler.getUrl();\n toolWindow.setTitle(String.format(\"- %s\", url.toString()));\n }\n\n public void closeChat() {\n toolWindow.hide(null);\n }\n\n public boolean isOpen() {\n try {\n return toolWindow.isVisible();\n } catch (IllegalStateException e) {\n return false;\n }\n }\n\n public void clearUsers() {\n ApplicationManager.getApplication().invokeLater(new Runnable() {\n @Override\n public void run() {\n chatForm.clearClients();\n }\n }, ModalityState.NON_MODAL);\n }\n\n public void addUser(final FlooUser user) {\n ApplicationManager.getApplication().invokeLater(new Runnable() {\n @Override\n public void run() {\n chatForm.addUser(user);\n }\n }, ModalityState.NON_MODAL);\n }\n\n public void statusMessage(final String message) {\n ApplicationManager.getApplication().invokeLater(new Runnable() {\n @Override\n public void run() {\n chatForm.statusMessage(message);\n }\n }, ModalityState.NON_MODAL);\n }\n\n public void errorMessage(final String message) {\n ApplicationManager.getApplication().invokeLater(new Runnable() {\n @Override\n public void run() {\n chatForm.errorMessage(message);\n }\n }, ModalityState.NON_MODAL);\n }\n\n public void chatMessage(final String username, final String msg, final Date messageDate) {\n if (context.lastChatMessage != null && context.lastChatMessage.compareTo(messageDate) > -1) {\n // Don't replay previously shown chat messages.\n return;\n }\n context.lastChatMessage = messageDate;\n ApplicationManager.getApplication().invokeLater(new Runnable() {\n @Override\n public void run() {\n chatForm.chatMessage(username, msg, messageDate);\n }\n }, ModalityState.NON_MODAL);\n }\n\n public void removeUser(final FlooUser user) {\n ApplicationManager.getApplication().invokeLater(new Runnable() {\n @Override\n public void run() {\n chatForm.removeUser(user);\n }\n }, ModalityState.NON_MODAL);\n }\n\n public void updateUserList() {\n ApplicationManager.getApplication().invokeLater(new Runnable() {\n @Override\n public void run() {\n chatForm.updateGravatars();\n }\n }, ModalityState.NON_MODAL);\n }\n}\n"},"new_file":{"kind":"string","value":"src/floobits/windows/ChatManager.java"},"old_contents":{"kind":"string","value":"package floobits.windows;\n\nimport com.intellij.openapi.application.ApplicationManager;\nimport com.intellij.openapi.application.ModalityState;\nimport com.intellij.openapi.project.Project;\nimport com.intellij.openapi.util.IconLoader;\nimport com.intellij.openapi.wm.ToolWindow;\nimport com.intellij.openapi.wm.ToolWindowAnchor;\nimport com.intellij.openapi.wm.ToolWindowManager;\nimport com.intellij.ui.content.Content;\nimport com.intellij.ui.content.ContentFactory;\nimport floobits.common.interfaces.IContext;\nimport floobits.common.FlooUrl;\nimport floobits.common.protocol.handlers.FlooHandler;\nimport floobits.common.protocol.FlooUser;\nimport floobits.impl.ContextImpl;\nimport floobits.utilities.Flog;\n\nimport java.util.*;\n\n\npublic class ChatManager {\n protected IContext context;\n protected ToolWindow toolWindow;\n protected ChatForm chatForm;\n\n public ChatManager (ContextImpl context) {\n this.context = context;\n chatForm = new ChatForm(context);\n this.createChatWindow(context.project);\n }\n\n protected void createChatWindow(Project project) {\n ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(project);\n toolWindow = toolWindowManager.registerToolWindow(\"Floobits Chat\", true, ToolWindowAnchor.BOTTOM);\n toolWindow.setIcon(IconLoader.getIcon(\"/icons/floo13.png\"));\n Content content = ContentFactory.SERVICE.getInstance().createContent(chatForm.getChatPanel(), \"\", true);\n toolWindow.getContentManager().addContent(content);\n }\n\n public void openChat() {\n FlooHandler flooHandler = context.getFlooHandler();\n if (flooHandler == null) {\n return;\n }\n try {\n toolWindow.show(null);\n } catch (NullPointerException e) {\n Flog.warn(\"Could not open chat window.\");\n return;\n }\n FlooUrl url = flooHandler.getUrl();\n toolWindow.setTitle(String.format(\"- %s\", url.toString()));\n }\n\n public void closeChat() {\n toolWindow.hide(null);\n }\n\n public boolean isOpen() {\n try {\n return toolWindow.isVisible();\n } catch (IllegalStateException e) {\n return false;\n }\n }\n\n public void clearUsers() {\n ApplicationManager.getApplication().invokeLater(new Runnable() {\n @Override\n public void run() {\n chatForm.clearClients();\n }\n }, ModalityState.NON_MODAL);\n }\n\n public void addUser(final FlooUser user) {\n ApplicationManager.getApplication().invokeLater(new Runnable() {\n @Override\n public void run() {\n chatForm.addUser(user);\n }\n }, ModalityState.NON_MODAL);\n }\n\n public void statusMessage(final String message) {\n ApplicationManager.getApplication().invokeLater(new Runnable() {\n @Override\n public void run() {\n chatForm.statusMessage(message);\n }\n }, ModalityState.NON_MODAL);\n }\n\n public void errorMessage(final String message) {\n ApplicationManager.getApplication().invokeLater(new Runnable() {\n @Override\n public void run() {\n chatForm.errorMessage(message);\n }\n }, ModalityState.NON_MODAL);\n }\n\n public void chatMessage(final String username, final String msg, final Date messageDate) {\n if (context.lastChatMessage != null && context.lastChatMessage.compareTo(messageDate) > -1) {\n // Don't replay previously shown chat messages.\n return;\n }\n context.lastChatMessage = messageDate;\n ApplicationManager.getApplication().invokeLater(new Runnable() {\n @Override\n public void run() {\n chatForm.chatMessage(username, msg, messageDate);\n }\n }, ModalityState.NON_MODAL);\n }\n\n public void removeUser(FlooUser user) {\n chatForm.removeUser(user);\n }\n\n public void updateUserList() {\n ApplicationManager.getApplication().invokeLater(new Runnable() {\n @Override\n public void run() {\n chatForm.updateGravatars();\n }\n }, ModalityState.NON_MODAL);\n }\n}\n"},"message":{"kind":"string","value":"Remove user from list in ui thread. #199\n"},"old_file":{"kind":"string","value":"src/floobits/windows/ChatManager.java"},"subject":{"kind":"string","value":"Remove user from list in ui thread. #199"},"git_diff":{"kind":"string","value":"rc/floobits/windows/ChatManager.java\n }, ModalityState.NON_MODAL);\n }\n \n public void removeUser(FlooUser user) {\n chatForm.removeUser(user);\n public void removeUser(final FlooUser user) {\n ApplicationManager.getApplication().invokeLater(new Runnable() {\n @Override\n public void run() {\n chatForm.removeUser(user);\n }\n }, ModalityState.NON_MODAL);\n }\n \n public void updateUserList() {"}}},{"rowIdx":1923,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"eb1101f06dc84fad63fc02fee2d51286dad5ea89"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"ryano144/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,caot/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,ryano144/intellij-community,allotria/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,samthor/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,hurricup/intellij-community,semonte/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,fitermay/intellij-community,supersven/intellij-community,da1z/intellij-community,signed/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,ibinti/intellij-community,holmes/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,ryano144/intellij-community,caot/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,semonte/intellij-community,FHannes/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,semonte/intellij-community,izonder/intellij-community,MER-GROUP/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,fnouama/intellij-community,izonder/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,signed/intellij-community,FHannes/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,amith01994/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,ibinti/intellij-community,retomerz/intellij-community,da1z/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,amith01994/intellij-community,apixandru/intellij-community,blademainer/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,robovm/robovm-studio,semonte/intellij-community,tmpgit/intellij-community,kool79/intellij-community,dslomov/intellij-community,apixandru/intellij-community,semonte/intellij-community,amith01994/intellij-community,retomerz/intellij-community,robovm/robovm-studio,signed/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,izonder/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,FHannes/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,lucafavatella/intellij-community,caot/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,samthor/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,caot/intellij-community,adedayo/intellij-community,xfournet/intellij-community,dslomov/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,ibinti/intellij-community,adedayo/intellij-community,kdwink/intellij-community,slisson/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,da1z/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,semonte/intellij-community,allotria/intellij-community,supersven/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,ryano144/intellij-community,fnouama/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,semonte/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,holmes/intellij-community,signed/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,jagguli/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,supersven/intellij-community,adedayo/intellij-community,hurricup/intellij-community,hurricup/intellij-community,kool79/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,holmes/intellij-community,kool79/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,robovm/robovm-studio,pwoodworth/intellij-community,petteyg/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,izonder/intellij-community,xfournet/intellij-community,vladmm/intellij-community,asedunov/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,blademainer/intellij-community,signed/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,FHannes/intellij-community,hurricup/intellij-community,dslomov/intellij-community,diorcety/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,diorcety/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,kdwink/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,fitermay/intellij-community,vladmm/intellij-community,izonder/intellij-community,hurricup/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,ahb0327/intellij-community,xfournet/intellij-community,hurricup/intellij-community,holmes/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,slisson/intellij-community,retomerz/intellij-community,hurricup/intellij-community,jagguli/intellij-community,allotria/intellij-community,holmes/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,allotria/intellij-community,signed/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,Lekanich/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,allotria/intellij-community,ibinti/intellij-community,da1z/intellij-community,caot/intellij-community,izonder/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,asedunov/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,slisson/intellij-community,kdwink/intellij-community,allotria/intellij-community,samthor/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,apixandru/intellij-community,allotria/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,supersven/intellij-community,blademainer/intellij-community,diorcety/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,slisson/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,retomerz/intellij-community,ibinti/intellij-community,slisson/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,signed/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,dslomov/intellij-community,ibinti/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,da1z/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,robovm/robovm-studio,jagguli/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,retomerz/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,samthor/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,FHannes/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,signed/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,holmes/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,petteyg/intellij-community,asedunov/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,signed/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,caot/intellij-community,kool79/intellij-community,signed/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,adedayo/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,semonte/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,kool79/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,fnouama/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,adedayo/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,holmes/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,retomerz/intellij-community,hurricup/intellij-community,da1z/intellij-community,kool79/intellij-community,kdwink/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,holmes/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,xfournet/intellij-community,slisson/intellij-community,vladmm/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,izonder/intellij-community,adedayo/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,signed/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,signed/intellij-community,izonder/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,caot/intellij-community,FHannes/intellij-community,FHannes/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,diorcety/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,fnouama/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,caot/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,samthor/intellij-community,samthor/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,retomerz/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,ol-loginov/intellij-community"},"new_contents":{"kind":"string","value":"/*\n * Copyright 2000-2013 JetBrains s.r.o.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.intellij.openapi.vfs.impl.jar;\n\nimport com.intellij.openapi.diagnostic.Logger;\nimport com.intellij.openapi.util.io.BufferExposingByteArrayInputStream;\nimport com.intellij.openapi.util.io.FileAttributes;\nimport com.intellij.openapi.util.io.FileUtil;\nimport com.intellij.openapi.util.text.StringUtil;\nimport com.intellij.openapi.vfs.JarFile;\nimport com.intellij.openapi.vfs.VirtualFile;\nimport com.intellij.reference.SoftReference;\nimport com.intellij.util.ArrayUtil;\nimport com.intellij.util.TimedReference;\nimport gnu.trove.THashMap;\nimport org.jetbrains.annotations.NotNull;\nimport org.jetbrains.annotations.Nullable;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.lang.ref.Reference;\nimport java.util.Enumeration;\nimport java.util.HashSet;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.zip.ZipEntry;\nimport java.util.zip.ZipFile;\n\npublic class JarHandlerBase {\n private static final Logger LOG = Logger.getInstance(\"#com.intellij.openapi.vfs.impl.jar.JarHandlerBase\");\n\n private static final long DEFAULT_LENGTH = 0L;\n private static final long DEFAULT_TIMESTAMP = -1L;\n\n private final TimedReference myJarFile = new TimedReference(null);\n private Reference> myRelPathsToEntries = new SoftReference>(null);\n private final Object lock = new Object();\n\n protected final String myBasePath;\n\n protected static class EntryInfo {\n protected final boolean isDirectory;\n protected final String shortName;\n protected final EntryInfo parent;\n\n public EntryInfo(@NotNull String shortName, final EntryInfo parent, final boolean directory) {\n this.shortName = shortName;\n this.parent = parent;\n isDirectory = directory;\n }\n }\n\n public JarHandlerBase(@NotNull String path) {\n myBasePath = path;\n }\n\n protected void clear() {\n synchronized (lock) {\n myRelPathsToEntries = null;\n myJarFile.set(null);\n }\n }\n\n public File getMirrorFile(@NotNull File originalFile) {\n return originalFile;\n }\n\n @Nullable\n public JarFile getJar() {\n JarFile jar = myJarFile.get();\n if (jar == null) {\n synchronized (lock) {\n jar = myJarFile.get();\n if (jar == null) {\n jar = createJarFile();\n if (jar != null) {\n myJarFile.set(jar);\n }\n }\n }\n }\n return jar;\n }\n\n @Nullable\n protected JarFile createJarFile() {\n final File originalFile = getOriginalFile();\n try {\n @SuppressWarnings(\"IOResourceOpenedButNotSafelyClosed\") final ZipFile zipFile = new ZipFile(getMirrorFile(originalFile));\n\n class MyJarEntry implements JarFile.JarEntry {\n private final ZipEntry myEntry;\n\n MyJarEntry(ZipEntry entry) {\n myEntry = entry;\n }\n\n public ZipEntry getEntry() {\n return myEntry;\n }\n\n @Override\n public String getName() {\n return myEntry.getName();\n }\n\n @Override\n public long getSize() {\n return myEntry.getSize();\n }\n\n @Override\n public long getTime() {\n return myEntry.getTime();\n }\n\n @Override\n public boolean isDirectory() {\n return myEntry.isDirectory();\n }\n }\n\n return new JarFile() {\n @Override\n public JarFile.JarEntry getEntry(String name) {\n try {\n ZipEntry entry = zipFile.getEntry(name);\n if (entry != null) {\n return new MyJarEntry(entry);\n }\n }\n catch (IllegalArgumentException e) {\n LOG.warn(e);\n }\n return null;\n }\n\n @Override\n public InputStream getInputStream(JarFile.JarEntry entry) throws IOException {\n return zipFile.getInputStream(((MyJarEntry)entry).myEntry);\n }\n\n @Override\n public Enumeration entries() {\n return new Enumeration() {\n private final Enumeration entries = zipFile.entries();\n\n @Override\n public boolean hasMoreElements() {\n return entries.hasMoreElements();\n }\n\n @Override\n public JarEntry nextElement() {\n try {\n ZipEntry entry = entries.nextElement();\n if (entry != null) {\n return new MyJarEntry(entry);\n }\n }\n catch (IllegalArgumentException e) {\n LOG.warn(e);\n }\n return null;\n }\n };\n }\n\n @Override\n public ZipFile getZipFile() {\n return zipFile;\n }\n };\n }\n catch (IOException e) {\n LOG.warn(e.getMessage() + \": \" + originalFile.getPath(), e);\n return null;\n }\n }\n\n @NotNull\n protected File getOriginalFile() {\n return new File(myBasePath);\n }\n\n @NotNull\n private static EntryInfo getOrCreate(@NotNull String entryName, boolean isDirectory, @NotNull Map map) {\n EntryInfo info = map.get(entryName);\n if (info == null) {\n int idx = entryName.lastIndexOf('/');\n final String parentEntryName = idx > 0 ? entryName.substring(0, idx) : \"\";\n String shortName = idx > 0 ? entryName.substring(idx + 1) : entryName;\n if (\".\".equals(shortName)) return getOrCreate(parentEntryName, true, map);\n\n info = new EntryInfo(shortName, getOrCreate(parentEntryName, true, map), isDirectory);\n map.put(entryName, info);\n }\n\n return info;\n }\n\n @NotNull\n public String[] list(@NotNull final VirtualFile file) {\n synchronized (lock) {\n EntryInfo parentEntry = getEntryInfo(file);\n\n Set names = new HashSet();\n for (EntryInfo info : getEntriesMap().values()) {\n if (info.parent == parentEntry) {\n names.add(info.shortName);\n }\n }\n\n return ArrayUtil.toStringArray(names);\n }\n }\n\n protected EntryInfo getEntryInfo(@NotNull VirtualFile file) {\n synchronized (lock) {\n String parentPath = getRelativePath(file);\n return getEntryInfo(parentPath);\n }\n }\n\n public EntryInfo getEntryInfo(@NotNull String parentPath) {\n return getEntriesMap().get(parentPath);\n }\n\n @NotNull\n protected Map getEntriesMap() {\n synchronized (lock) {\n Map map = myRelPathsToEntries != null ? myRelPathsToEntries.get() : null;\n if (map == null) {\n final JarFile zip = getJar();\n LOG.info(\"mapping \" + myBasePath);\n\n map = new THashMap();\n if (zip != null) {\n map.put(\"\", new EntryInfo(\"\", null, true));\n final Enumeration entries = zip.entries();\n while (entries.hasMoreElements()) {\n JarFile.JarEntry entry = entries.nextElement();\n final String name = entry.getName();\n final boolean isDirectory = StringUtil.endsWithChar(name, '/');\n getOrCreate(isDirectory ? name.substring(0, name.length() - 1) : name, isDirectory, map);\n }\n\n myRelPathsToEntries = new SoftReference>(map);\n }\n }\n return map;\n }\n }\n\n @NotNull\n private String getRelativePath(@NotNull VirtualFile file) {\n final String path = file.getPath().substring(myBasePath.length() + 1);\n return StringUtil.startsWithChar(path, '/') ? path.substring(1) : path;\n }\n\n @Nullable\n private JarFile.JarEntry convertToEntry(@NotNull VirtualFile file) {\n String path = getRelativePath(file);\n final JarFile jar = getJar();\n return jar == null ? null : jar.getEntry(path);\n }\n\n public long getLength(@NotNull final VirtualFile file) {\n final JarFile.JarEntry entry = convertToEntry(file);\n synchronized (lock) {\n return entry == null ? DEFAULT_LENGTH : entry.getSize();\n }\n }\n\n @NotNull\n public InputStream getInputStream(@NotNull final VirtualFile file) throws IOException {\n return new BufferExposingByteArrayInputStream(contentsToByteArray(file));\n }\n\n @NotNull\n public byte[] contentsToByteArray(@NotNull final VirtualFile file) throws IOException {\n final JarFile.JarEntry entry = convertToEntry(file);\n if (entry == null) {\n return ArrayUtil.EMPTY_BYTE_ARRAY;\n }\n synchronized (lock) {\n final JarFile jar = getJar();\n assert jar != null : file;\n\n final InputStream stream = jar.getInputStream(entry);\n assert stream != null : file;\n\n try {\n return FileUtil.loadBytes(stream, (int)entry.getSize());\n }\n finally {\n stream.close();\n }\n }\n }\n\n public long getTimeStamp(@NotNull final VirtualFile file) {\n if (file.getParent() == null) return getOriginalFile().lastModified(); // Optimization\n final JarFile.JarEntry entry = convertToEntry(file);\n synchronized (lock) {\n return entry == null ? DEFAULT_TIMESTAMP : entry.getTime();\n }\n }\n\n public boolean isDirectory(@NotNull final VirtualFile file) {\n if (file.getParent() == null) return true; // Optimization\n synchronized (lock) {\n final String path = getRelativePath(file);\n final EntryInfo info = getEntryInfo(path);\n return info == null || info.isDirectory;\n }\n }\n\n public boolean exists(@NotNull final VirtualFile fileOrDirectory) {\n if (fileOrDirectory.getParent() == null) {\n // Optimization. Do not build entries if asked for jar root existence.\n return myJarFile.get() != null || getOriginalFile().exists();\n }\n\n return getEntryInfo(fileOrDirectory) != null;\n }\n\n @Nullable\n public FileAttributes getAttributes(@NotNull final VirtualFile file) {\n final JarFile.JarEntry entry = convertToEntry(file);\n synchronized (lock) {\n final EntryInfo entryInfo = getEntryInfo(getRelativePath(file));\n if (entryInfo == null) return null;\n final long length = entry != null ? entry.getSize() : DEFAULT_LENGTH;\n final long timeStamp = entry != null ? entry.getTime() : DEFAULT_TIMESTAMP;\n return new FileAttributes(entryInfo.isDirectory, false, false, false, length, timeStamp, false);\n }\n }\n}\n"},"new_file":{"kind":"string","value":"platform/core-impl/src/com/intellij/openapi/vfs/impl/jar/JarHandlerBase.java"},"old_contents":{"kind":"string","value":"/*\n * Copyright 2000-2013 JetBrains s.r.o.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.intellij.openapi.vfs.impl.jar;\n\nimport com.intellij.openapi.diagnostic.Logger;\nimport com.intellij.openapi.util.io.BufferExposingByteArrayInputStream;\nimport com.intellij.openapi.util.io.FileAttributes;\nimport com.intellij.openapi.util.io.FileUtil;\nimport com.intellij.openapi.util.text.StringUtil;\nimport com.intellij.openapi.vfs.JarFile;\nimport com.intellij.openapi.vfs.VirtualFile;\nimport com.intellij.reference.SoftReference;\nimport com.intellij.util.ArrayUtil;\nimport com.intellij.util.TimedReference;\nimport gnu.trove.THashMap;\nimport org.jetbrains.annotations.NotNull;\nimport org.jetbrains.annotations.Nullable;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.lang.ref.Reference;\nimport java.util.Enumeration;\nimport java.util.HashSet;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.zip.ZipEntry;\nimport java.util.zip.ZipFile;\n\npublic class JarHandlerBase {\n private static final Logger LOG = Logger.getInstance(\"#com.intellij.openapi.vfs.impl.jar.JarHandlerBase\");\n\n private static final long DEFAULT_LENGTH = 0L;\n private static final long DEFAULT_TIMESTAMP = -1L;\n\n private final TimedReference myJarFile = new TimedReference(null);\n private Reference> myRelPathsToEntries = new SoftReference>(null);\n private final Object lock = new Object();\n\n protected final String myBasePath;\n\n protected static class EntryInfo {\n protected final boolean isDirectory;\n protected final String shortName;\n protected final EntryInfo parent;\n\n public EntryInfo(@NotNull String shortName, final EntryInfo parent, final boolean directory) {\n this.shortName = shortName;\n this.parent = parent;\n isDirectory = directory;\n }\n }\n\n public JarHandlerBase(@NotNull String path) {\n myBasePath = path;\n }\n\n protected void clear() {\n synchronized (lock) {\n myRelPathsToEntries = null;\n myJarFile.set(null);\n }\n }\n\n public File getMirrorFile(@NotNull File originalFile) {\n return originalFile;\n }\n\n @Nullable\n public JarFile getJar() {\n JarFile jar = myJarFile.get();\n if (jar == null) {\n synchronized (lock) {\n jar = myJarFile.get();\n if (jar == null) {\n jar = createJarFile();\n if (jar != null) {\n myJarFile.set(jar);\n }\n }\n }\n }\n return jar;\n }\n\n @Nullable\n protected JarFile createJarFile() {\n final File originalFile = getOriginalFile();\n try {\n @SuppressWarnings(\"IOResourceOpenedButNotSafelyClosed\") final ZipFile zipFile = new ZipFile(getMirrorFile(originalFile));\n\n class MyJarEntry implements JarFile.JarEntry {\n private final ZipEntry myEntry;\n\n MyJarEntry(ZipEntry entry) {\n myEntry = entry;\n }\n\n public ZipEntry getEntry() {\n return myEntry;\n }\n\n @Override\n public String getName() {\n return myEntry.getName();\n }\n\n @Override\n public long getSize() {\n return myEntry.getSize();\n }\n\n @Override\n public long getTime() {\n return myEntry.getTime();\n }\n\n @Override\n public boolean isDirectory() {\n return myEntry.isDirectory();\n }\n }\n\n return new JarFile() {\n @Override\n public JarFile.JarEntry getEntry(String name) {\n try {\n ZipEntry entry = zipFile.getEntry(name);\n if (entry != null) {\n return new MyJarEntry(entry);\n }\n }\n catch (IllegalArgumentException e) {\n LOG.warn(e);\n }\n return null;\n }\n\n @Override\n public InputStream getInputStream(JarFile.JarEntry entry) throws IOException {\n return zipFile.getInputStream(((MyJarEntry)entry).myEntry);\n }\n\n @Override\n public Enumeration entries() {\n return new Enumeration() {\n private final Enumeration entries = zipFile.entries();\n\n @Override\n public boolean hasMoreElements() {\n return entries.hasMoreElements();\n }\n\n @Override\n public JarEntry nextElement() {\n try {\n ZipEntry entry = entries.nextElement();\n if (entry != null) {\n return new MyJarEntry(entry);\n }\n }\n catch (IllegalArgumentException e) {\n LOG.warn(e);\n }\n return null;\n }\n };\n }\n\n @Override\n public ZipFile getZipFile() {\n return zipFile;\n }\n };\n }\n catch (IOException e) {\n LOG.warn(e.getMessage() + \": \" + originalFile.getPath(), e);\n return null;\n }\n }\n\n @NotNull\n protected File getOriginalFile() {\n return new File(myBasePath);\n }\n\n @NotNull\n private static EntryInfo getOrCreate(@NotNull String entryName, boolean isDirectory, @NotNull Map map) {\n EntryInfo info = map.get(entryName);\n if (info == null) {\n int idx = entryName.lastIndexOf('/');\n final String parentEntryName = idx > 0 ? entryName.substring(0, idx) : \"\";\n String shortName = idx > 0 ? entryName.substring(idx + 1) : entryName;\n if (\".\".equals(shortName)) return getOrCreate(parentEntryName, true, map);\n\n info = new EntryInfo(shortName, getOrCreate(parentEntryName, true, map), isDirectory);\n map.put(entryName, info);\n }\n\n return info;\n }\n\n @NotNull\n public String[] list(@NotNull final VirtualFile file) {\n synchronized (lock) {\n EntryInfo parentEntry = getEntryInfo(file);\n\n Set names = new HashSet();\n for (EntryInfo info : getEntriesMap().values()) {\n if (info.parent == parentEntry) {\n names.add(info.shortName);\n }\n }\n\n return ArrayUtil.toStringArray(names);\n }\n }\n\n protected EntryInfo getEntryInfo(@NotNull VirtualFile file) {\n synchronized (lock) {\n String parentPath = getRelativePath(file);\n return getEntryInfo(parentPath);\n }\n }\n\n public EntryInfo getEntryInfo(@NotNull String parentPath) {\n return getEntriesMap().get(parentPath);\n }\n\n @NotNull\n protected Map getEntriesMap() {\n synchronized (lock) {\n Map map = myRelPathsToEntries != null ? myRelPathsToEntries.get() : null;\n if (map == null) {\n final JarFile zip = getJar();\n\n map = new THashMap();\n if (zip != null) {\n map.put(\"\", new EntryInfo(\"\", null, true));\n final Enumeration entries = zip.entries();\n while (entries.hasMoreElements()) {\n JarFile.JarEntry entry = entries.nextElement();\n final String name = entry.getName();\n final boolean isDirectory = StringUtil.endsWithChar(name, '/');\n getOrCreate(isDirectory ? name.substring(0, name.length() - 1) : name, isDirectory, map);\n }\n\n myRelPathsToEntries = new SoftReference>(map);\n }\n }\n return map;\n }\n }\n\n @NotNull\n private String getRelativePath(@NotNull VirtualFile file) {\n final String path = file.getPath().substring(myBasePath.length() + 1);\n return StringUtil.startsWithChar(path, '/') ? path.substring(1) : path;\n }\n\n @Nullable\n private JarFile.JarEntry convertToEntry(@NotNull VirtualFile file) {\n String path = getRelativePath(file);\n final JarFile jar = getJar();\n return jar == null ? null : jar.getEntry(path);\n }\n\n public long getLength(@NotNull final VirtualFile file) {\n final JarFile.JarEntry entry = convertToEntry(file);\n synchronized (lock) {\n return entry == null ? DEFAULT_LENGTH : entry.getSize();\n }\n }\n\n @NotNull\n public InputStream getInputStream(@NotNull final VirtualFile file) throws IOException {\n return new BufferExposingByteArrayInputStream(contentsToByteArray(file));\n }\n\n @NotNull\n public byte[] contentsToByteArray(@NotNull final VirtualFile file) throws IOException {\n final JarFile.JarEntry entry = convertToEntry(file);\n if (entry == null) {\n return ArrayUtil.EMPTY_BYTE_ARRAY;\n }\n synchronized (lock) {\n final JarFile jar = getJar();\n assert jar != null : file;\n\n final InputStream stream = jar.getInputStream(entry);\n assert stream != null : file;\n\n try {\n return FileUtil.loadBytes(stream, (int)entry.getSize());\n }\n finally {\n stream.close();\n }\n }\n }\n\n public long getTimeStamp(@NotNull final VirtualFile file) {\n if (file.getParent() == null) return getOriginalFile().lastModified(); // Optimization\n final JarFile.JarEntry entry = convertToEntry(file);\n synchronized (lock) {\n return entry == null ? DEFAULT_TIMESTAMP : entry.getTime();\n }\n }\n\n public boolean isDirectory(@NotNull final VirtualFile file) {\n if (file.getParent() == null) return true; // Optimization\n synchronized (lock) {\n final String path = getRelativePath(file);\n final EntryInfo info = getEntryInfo(path);\n return info == null || info.isDirectory;\n }\n }\n\n public boolean exists(@NotNull final VirtualFile fileOrDirectory) {\n if (fileOrDirectory.getParent() == null) {\n // Optimization. Do not build entries if asked for jar root existence.\n return myJarFile.get() != null || getOriginalFile().exists();\n }\n\n return getEntryInfo(fileOrDirectory) != null;\n }\n\n @Nullable\n public FileAttributes getAttributes(@NotNull final VirtualFile file) {\n final JarFile.JarEntry entry = convertToEntry(file);\n synchronized (lock) {\n final EntryInfo entryInfo = getEntryInfo(getRelativePath(file));\n if (entryInfo == null) return null;\n final long length = entry != null ? entry.getSize() : DEFAULT_LENGTH;\n final long timeStamp = entry != null ? entry.getTime() : DEFAULT_TIMESTAMP;\n return new FileAttributes(entryInfo.isDirectory, false, false, false, length, timeStamp, false);\n }\n }\n}\n"},"message":{"kind":"string","value":"IDEA-114283 (diagnostic)\n"},"old_file":{"kind":"string","value":"platform/core-impl/src/com/intellij/openapi/vfs/impl/jar/JarHandlerBase.java"},"subject":{"kind":"string","value":"IDEA-114283 (diagnostic)"},"git_diff":{"kind":"string","value":"latform/core-impl/src/com/intellij/openapi/vfs/impl/jar/JarHandlerBase.java\n Map map = myRelPathsToEntries != null ? myRelPathsToEntries.get() : null;\n if (map == null) {\n final JarFile zip = getJar();\n LOG.info(\"mapping \" + myBasePath);\n \n map = new THashMap();\n if (zip != null) {"}}},{"rowIdx":1924,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"b102e0c48fcebbbd327064c380b9420782c4e04e"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"DC37/Super-Mario-Paint"},"new_contents":{"kind":"string","value":"package smp;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.net.MalformedURLException;\n\nimport javafx.application.Application;\nimport javafx.fxml.FXMLLoader;\nimport javafx.scene.Parent;\nimport javafx.scene.Scene;\nimport javafx.scene.input.KeyEvent;\nimport javafx.stage.Stage;\nimport smp.fx.SMPFXController;\nimport smp.fx.SplashScreen;\n\n/**\n * Super Mario Paint
\n * Based on the old SNES game from 1992, Mario Paint
\n * Inspired by:
\n * MarioSequencer (2002)
\n * TrioSequencer
\n * Robby Mulvany's Mario Paint Composer 1.0 / 2.0 (2007-2008)
\n * FordPrefect's Advanced Mario Sequencer (2009)
\n * The GUI is primarily written with JavaFX2.2.
\n * @author RehdBlob\n * @since 2012.08.16\n * @version 1.00\n */\npublic class SuperMarioPaint extends Application {\n\n /**\n * Location of the Main Window fxml file.\n */\n private String mainFxml = \"./MainWindow.fxml\";\n\n /**\n * Location of the Arrangement Window fxml file.\n */\n private String arrFxml = \"./ArrWindow.fxml\";\n\n /**\n * Location of the Advanced Mode (super secret!!)\n * fxml file.\n */\n private String advFxml = \"./AdvWindow.fxml\";\n\n /**\n * The number of threads that are running to load things for Super Mario\n * Paint.\n */\n private static final int NUM_THREADS = 2;\n\n /**\n * Until I figure out the mysteries of the Preloader class in\n * JavaFX, I will stick to what I know, which is swing, unfortunately.\n */\n private SplashScreen dummyPreloader = new SplashScreen();\n\n /**\n * Loads all the sprites that will be used in Super Mario Paint.\n */\n private Loader imgLoader = new ImageLoader();\n\n /**\n * Loads the soundfonts that will be used in Super Mario Paint.\n */\n private Loader sfLoader = new SoundfontLoader();\n\n /**\n * Starts three Threads. One of them is currently\n * a dummy splash screen, the second an ImageLoader,\n * and the third one a SoundfontLoader.\n * @see ImageLoader\n * @see SoundfontLoader\n * @see SplashScreen\n */\n @Override\n public void init() {\n Thread splash = new Thread(dummyPreloader);\n splash.start();\n Thread imgLd = new Thread(imgLoader);\n Thread sfLd = new Thread(sfLoader);\n sfLd.start();\n imgLd.start();\n while (imgLd.isAlive() || sfLd.isAlive()) {\n try {\n Thread.sleep(1);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n double imgStatus = imgLoader.getLoadStatus();\n double sfStatus = sfLoader.getLoadStatus();\n dummyPreloader.updateStatus((imgStatus + sfStatus) * 100, NUM_THREADS);\n }\n\n }\n\n /**\n * Starts the application and loads the FXML file that contains\n * a lot of the class hierarchy.\n * @param primaryStage The primary stage that will be showing the\n * main window of Super Mario Paint.\n */\n @Override\n public void start(Stage primaryStage) {\n try {\n Parent root =\n (Parent) FXMLLoader.load(\n new File(mainFxml).toURI().toURL());\n primaryStage.setTitle(\"Super Mario Paint\");\n primaryStage.setResizable(true);\n Scene primaryScene = new Scene(root, 800, 600);\n primaryStage.setScene(primaryScene);\n SMPFXController.initializeHandlers();\n makeKeyboardListeners(primaryScene);\n dummyPreloader.updateStatus(NUM_THREADS * 100, NUM_THREADS);\n primaryStage.show();\n dummyPreloader.dispose();\n } catch (MalformedURLException e) {\n e.printStackTrace();\n System.exit(1);\n } catch (IOException e) {\n e.printStackTrace();\n System.exit(1);\n }\n }\n\n /**\n * Creates the keyboard listeners that we will be using for various\n * other portions of the program.\n * @param primaryScene The main window.\n */\n private void makeKeyboardListeners(Scene primaryScene) {\n\n }\n\n /**\n * Launches the application.\n * @param unused Currently unused arguments for run configs.\n */\n public static void main(String... unused) {\n launch(unused);\n }\n\n}\n\n\n"},"new_file":{"kind":"string","value":"src/smp/SuperMarioPaint.java"},"old_contents":{"kind":"string","value":"package smp;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.net.MalformedURLException;\n\nimport javafx.application.Application;\nimport javafx.fxml.FXMLLoader;\nimport javafx.scene.Parent;\nimport javafx.scene.Scene;\nimport javafx.stage.Stage;\nimport smp.fx.SMPFXController;\nimport smp.fx.SplashScreen;\n\n/**\n * Super Mario Paint
\n * Based on the old SNES game from 1992, Mario Paint
\n * Inspired by:
\n * MarioSequencer (2002)
\n * TrioSequencer
\n * Robby Mulvany's Mario Paint Composer 1.0 / 2.0 (2007-2008)
\n * FordPrefect's Advanced Mario Sequencer (2009)
\n * The GUI is primarily written with JavaFX2.2.
\n * @author RehdBlob\n * @since 2012.08.16\n * @version 1.00\n */\npublic class SuperMarioPaint extends Application {\n\n /**\n * Location of the Main Window fxml file.\n */\n private String mainFxml = \"./MainWindow.fxml\";\n\n /**\n * Location of the Arrangement Window fxml file.\n */\n private String arrFxml = \"./ArrWindow.fxml\";\n\n /**\n * Location of the Advanced Mode (super secret!!)\n * fxml file.\n */\n private String advFxml = \"./AdvWindow.fxml\";\n\n /**\n * The number of threads that are running to load things for Super Mario\n * Paint.\n */\n private static final int NUM_THREADS = 2;\n\n /**\n * Until I figure out the mysteries of the Preloader class in\n * JavaFX, I will stick to what I know, which is swing, unfortunately.\n */\n private SplashScreen dummyPreloader = new SplashScreen();\n\n /**\n * Loads all the sprites that will be used in Super Mario Paint.\n */\n private Loader imgLoader = new ImageLoader();\n\n /**\n * Loads the soundfonts that will be used in Super Mario Paint.\n */\n private Loader sfLoader = new SoundfontLoader();\n\n /**\n * Starts three Threads. One of them is currently\n * a dummy splash screen, the second an ImageLoader,\n * and the third one a SoundfontLoader.\n * @see ImageLoader\n * @see SoundfontLoader\n * @see SplashScreen\n */\n @Override\n public void init() {\n Thread splash = new Thread(dummyPreloader);\n splash.start();\n Thread imgLd = new Thread(imgLoader);\n Thread sfLd = new Thread(sfLoader);\n sfLd.start();\n imgLd.start();\n while (imgLd.isAlive() || sfLd.isAlive()) {\n try {\n Thread.sleep(1);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n double imgStatus = imgLoader.getLoadStatus();\n double sfStatus = sfLoader.getLoadStatus();\n dummyPreloader.updateStatus((imgStatus + sfStatus) * 100, NUM_THREADS);\n }\n\n }\n\n /**\n * Starts the application and loads the FXML file that contains\n * a lot of the class hierarchy.\n * @param primaryStage The primary stage that will be showing the\n * main window of Super Mario Paint.\n */\n @Override\n public void start(Stage primaryStage) {\n try {\n Parent root =\n (Parent) FXMLLoader.load(\n new File(mainFxml).toURI().toURL());\n primaryStage.setTitle(\"Super Mario Paint\");\n primaryStage.setResizable(true);\n primaryStage.setScene(new Scene(root, 800, 600));\n SMPFXController.initializeHandlers();\n dummyPreloader.updateStatus(NUM_THREADS * 100, NUM_THREADS);\n primaryStage.show();\n dummyPreloader.dispose();\n } catch (MalformedURLException e) {\n e.printStackTrace();\n System.exit(1);\n } catch (IOException e) {\n e.printStackTrace();\n System.exit(1);\n }\n }\n\n /**\n * Launches the application.\n * @param unused Currently unused arguments for run configs.\n */\n public static void main(String... unused) {\n launch(unused);\n }\n\n}\n\n\n"},"message":{"kind":"string","value":"Setting up event handler for key presses\n"},"old_file":{"kind":"string","value":"src/smp/SuperMarioPaint.java"},"subject":{"kind":"string","value":"Setting up event handler for key presses"},"git_diff":{"kind":"string","value":"rc/smp/SuperMarioPaint.java\n import javafx.fxml.FXMLLoader;\n import javafx.scene.Parent;\n import javafx.scene.Scene;\nimport javafx.scene.input.KeyEvent;\n import javafx.stage.Stage;\n import smp.fx.SMPFXController;\n import smp.fx.SplashScreen;\n new File(mainFxml).toURI().toURL());\n primaryStage.setTitle(\"Super Mario Paint\");\n primaryStage.setResizable(true);\n primaryStage.setScene(new Scene(root, 800, 600));\n Scene primaryScene = new Scene(root, 800, 600);\n primaryStage.setScene(primaryScene);\n SMPFXController.initializeHandlers();\n makeKeyboardListeners(primaryScene);\n dummyPreloader.updateStatus(NUM_THREADS * 100, NUM_THREADS);\n primaryStage.show();\n dummyPreloader.dispose();\n }\n \n /**\n * Creates the keyboard listeners that we will be using for various\n * other portions of the program.\n * @param primaryScene The main window.\n */\n private void makeKeyboardListeners(Scene primaryScene) {\n\n }\n\n /**\n * Launches the application.\n * @param unused Currently unused arguments for run configs.\n */"}}},{"rowIdx":1925,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":"error: pathspec 'src/main/java/cn/gyyx/gy4j/cache/mogodb/MogodbHelper.java' did not match any file(s) known to git\n"},"commit":{"kind":"string","value":"d80910ea517e4ee3741cd9ce41414023721fb540"},"returncode":{"kind":"number","value":1,"string":"1"},"repos":{"kind":"string","value":"eastFu/gy4j-framework"},"new_contents":{"kind":"string","value":"package cn.gyyx.gy4j.cache;\n\n/**\n * Created by Administrator on 2017/9/27 0027.\n */\npublic class CacheHelper {\n\n}\n"},"new_file":{"kind":"string","value":"src/main/java/cn/gyyx/gy4j/cache/mogodb/MogodbHelper.java"},"old_contents":{"kind":"string","value":""},"message":{"kind":"string","value":"0.0.1\n"},"old_file":{"kind":"string","value":"src/main/java/cn/gyyx/gy4j/cache/mogodb/MogodbHelper.java"},"subject":{"kind":"string","value":"0.0.1"},"git_diff":{"kind":"string","value":"rc/main/java/cn/gyyx/gy4j/cache/mogodb/MogodbHelper.java\npackage cn.gyyx.gy4j.cache;\n\n/**\n * Created by Administrator on 2017/9/27 0027.\n */\npublic class CacheHelper {\n\n}"}}},{"rowIdx":1926,"cells":{"lang":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"22fba69b4a5e6a312e40a3f644c3d42e379a478d"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"bolster/node-xmlrpc,hobbyquaker/homematic-xmlrpc,patricklodder/node-xmlrpc,Growmies/node-xmlrpc,baalexander/node-xmlrpc,AfterShip/node-xmlrpc,xmlrpc-js/xmlrpc-marshalling,MiniGod/node-gbxremote"},"new_contents":{"kind":"string","value":"var vows = require('vows')\n , assert = require('assert')\n , xmlrpcParser = require('../lib/xmlrpc-parser.js')\n\nvows.describe('XML-RPC Parser').addBatch({\n // Test parseResponseXml functionality\n 'A parseResponseXml call' : {\n // Test Array\n 'with an Array param' : {\n topic: function() {\n var xml = ''\n + '178testString'\n + ''\n xmlrpcParser.parseResponseXml(xml, this.callback)\n }\n , 'contains an array of arrays' : function (err, params) {\n assert.typeOf(params[0], 'array')\n assert.deepEqual(params, [[178, 'testString']])\n }\n }\n , 'with a nested Array param' : {\n topic: function() {\n var xml = ''\n + '178testLevel1StringtestString64'\n + ''\n xmlrpcParser.parseResponseXml(xml, this.callback)\n }\n , 'contains an array of arrays' : function (err, params) {\n assert.typeOf(params[0], 'array')\n assert.deepEqual(params, [[178, 'testLevel1String', ['testString', 64]]])\n }\n }\n , 'with a nested Array param and values after the nested array' : {\n topic: function() {\n var xml = ''\n + '178testLevel1StringtestString64testLevel1StringAfter'\n + ''\n xmlrpcParser.parseResponseXml(xml, this.callback)\n }\n , 'contains an array of arrays' : function (err, params) {\n assert.typeOf(params[0], 'array')\n assert.deepEqual(params, [[178, 'testLevel1String', ['testString', 64], 'testLevel1StringAfter']])\n }\n }\n , 'with multiple params containing Arrays and other values mixed in' : {\n topic: function() {\n var xml = ''\n + '178testLevel1StringtestString64testLevel1StringAfter'\n + '191testSomeString60pleasework7.11'\n + ''\n xmlrpcParser.parseResponseXml(xml, this.callback)\n }\n , 'contains an array of arrays' : function (err, params) {\n assert.typeOf(params[0], 'array')\n assert.typeOf(params[1], 'array')\n assert.deepEqual(params, [[178, 'testLevel1String', ['testString', 64], 'testLevel1StringAfter'], [19, true, ['testSomeString', 60], 'pleasework', 7.11]])\n }\n }\n // Test Boolean\n , 'with a true Boolean param' : {\n topic: function() {\n var xml = ''\n + '1'\n + ''\n xmlrpcParser.parseResponseXml(xml, this.callback)\n }\n , 'contains an array with a true value' : function (err, params) {\n assert.typeOf(params[0], 'boolean')\n assert.deepEqual(params, [true])\n }\n }\n , 'with a false Boolean param' : {\n topic: function() {\n var xml = ''\n + '0'\n + ''\n xmlrpcParser.parseResponseXml(xml, this.callback)\n }\n , 'contains an array with a false value' : function (err, params) {\n assert.typeOf(params[0], 'boolean')\n assert.deepEqual(params, [false])\n }\n }\n // Test DateTime\n , 'with a Datetime param' : {\n topic: function() {\n var xml = ''\n + '20120608T11:35:10'\n + ''\n xmlrpcParser.parseResponseXml(xml, this.callback)\n }\n , 'contains the Date object' : function (err, params) {\n assert.typeOf(params[0], 'date')\n assert.deepEqual(params, [new Date(2012, 05, 08, 11, 35, 10)])\n }\n }\n // Test Double\n , 'with a positive Double param' : {\n topic: function() {\n var xml = ''\n + '4.11'\n + ''\n xmlrpcParser.parseResponseXml(xml, this.callback)\n }\n , 'contains the positive double' : function (err, params) {\n assert.typeOf(params[0], 'number')\n assert.deepEqual(params, [4.11])\n }\n }\n , 'with a negative Double param' : {\n topic: function() {\n var xml = ''\n + '-4.2221'\n + ''\n xmlrpcParser.parseResponseXml(xml, this.callback)\n }\n , 'contains the positive double' : function (err, params) {\n assert.typeOf(params[0], 'number')\n assert.deepEqual(params, [-4.2221])\n }\n }\n // Test Integer\n , 'with a positive Int param' : {\n topic: function() {\n var xml = ''\n + '4'\n + ''\n xmlrpcParser.parseResponseXml(xml, this.callback)\n }\n , 'contains the positive integer' : function (err, params) {\n assert.typeOf(params[0], 'number')\n assert.deepEqual(params, [4])\n }\n }\n , 'with a positive I4 param' : {\n topic: function() {\n var xml = ''\n + '6'\n + ''\n xmlrpcParser.parseResponseXml(xml, this.callback)\n }\n , 'contains the positive integer' : function (err, params) {\n assert.typeOf(params[0], 'number')\n assert.deepEqual(params, [6])\n }\n }\n , 'with a negative Int param' : {\n topic: function() {\n var xml = ''\n + '-14'\n + ''\n xmlrpcParser.parseResponseXml(xml, this.callback)\n }\n , 'contains the negative integer' : function (err, params) {\n assert.typeOf(params[0], 'number')\n assert.deepEqual(params, [-14])\n }\n }\n , 'with a negative I4 param' : {\n topic: function() {\n var xml = ''\n + '-26'\n + ''\n xmlrpcParser.parseResponseXml(xml, this.callback)\n }\n , 'contains the negative integer' : function (err, params) {\n assert.typeOf(params[0], 'number')\n assert.deepEqual(params, [-26])\n }\n }\n , 'with a Int param of 0' : {\n topic: function() {\n var xml = ''\n + '0'\n + ''\n xmlrpcParser.parseResponseXml(xml, this.callback)\n }\n , 'contains the value 0' : function (err, params) {\n assert.typeOf(params[0], 'number')\n assert.deepEqual(params, [0])\n }\n }\n , 'with a I4 param of 0' : {\n topic: function() {\n var xml = ''\n + '0'\n + ''\n xmlrpcParser.parseResponseXml(xml, this.callback)\n }\n , 'contains the value 0' : function (err, params) {\n assert.typeOf(params[0], 'number')\n assert.deepEqual(params, [0])\n }\n }\n // Test String\n , 'with a String param' : {\n topic: function() {\n var xml = ''\n + 'testString'\n + ''\n xmlrpcParser.parseResponseXml(xml, this.callback)\n }\n , 'contains an array with the string' : function (err, params) {\n assert.typeOf(params[0], 'string')\n assert.deepEqual(params, ['testString'])\n }\n }\n // Test Struct\n , 'with a Struct param' : {\n topic: function() {\n var xml = ''\n + 'theNametestValue'\n + ''\n xmlrpcParser.parseResponseXml(xml, this.callback)\n }\n , 'contains the object' : function (err, params) {\n assert.isObject(params[0])\n assert.deepEqual(params, [{ theName: 'testValue'}])\n }\n }\n , 'with a nested Struct param' : {\n topic: function() {\n var xml = ''\n + 'theNametestValueanotherNamenestedNamenestedValuelastNameSmith'\n + ''\n xmlrpcParser.parseResponseXml(xml, this.callback)\n }\n , 'contains the objects' : function (err, params) {\n assert.isObject(params[0])\n assert.deepEqual(params, [{ theName: 'testValue', anotherName: {nestedName: 'nestedValue' }, lastName: 'Smith'}])\n }\n }\n // The grinder\n , 'with a mix of everything' : {\n topic: function() {\n var xml = ''\n + 'theNametestValue2anotherName2somenestedNamenestedValue2klastNameSmith'\n + ''\n + 'theNametestValueanotherNamenestedNamenestedValuelastNameSmith'\n + ''\n + 'yetAnotherName1999.26'\n + 'moreNested'\n + ''\n + ''\n + '19850608T14:35:10'\n + ''\n xmlrpcParser.parseResponseXml(xml, this.callback)\n }\n , 'contains the objects' : function (err, params) {\n assert.isObject(params[0])\n var expected = [\n { theName: 'testValue2', anotherName2: {somenestedName: 'nestedValue2k' }, lastName: 'Smith'}\n , [\n { theName: 'testValue', anotherName: {nestedName: 'nestedValue' }, lastName: 'Smith' }\n , [\n { yetAnotherName: 1999.26}\n , 'moreNested'\n ]\n ]\n , new Date(1985, 05, 08, 14, 35, 10)\n ]\n assert.deepEqual(params, expected)\n }\n }\n }\n\n}).export(module)\n"},"new_file":{"kind":"string","value":"test/xmlrpc-parser-test.js"},"old_contents":{"kind":"string","value":"var vows = require('vows')\n , assert = require('assert')\n , xmlrpcParser = require('../lib/xmlrpc-parser.js')\n\nvows.describe('XML-RPC Parser').addBatch({\n // Test parseResponseXml functionality\n 'A parseResponseXml call' : {\n // Test Array\n 'with an Array param' : { topic: function() {\n xmlrpcParser.parseResponseXml('178testString', this.callback)\n }\n , 'contains an array of arrays' : function (err, params) {\n assert.typeOf(params[0], 'array')\n assert.deepEqual(params, [[178, 'testString']])\n }\n }\n , 'with a nested Array param' : {\n topic: function() {\n xmlrpcParser.parseResponseXml('178testLevel1StringtestString64', this.callback)\n }\n , 'contains an array of arrays' : function (err, params) {\n assert.typeOf(params[0], 'array')\n assert.deepEqual(params, [[178, 'testLevel1String', ['testString', 64]]])\n }\n }\n , 'with a nested Array param and values after the nested array' : {\n topic: function() {\n xmlrpcParser.parseResponseXml('178testLevel1StringtestString64testLevel1StringAfter', this.callback)\n }\n , 'contains an array of arrays' : function (err, params) {\n assert.typeOf(params[0], 'array')\n assert.deepEqual(params, [[178, 'testLevel1String', ['testString', 64], 'testLevel1StringAfter']])\n }\n }\n , 'with multiple params containing Arrays and other values mixed in' : {\n topic: function() {\n var xml = ''\n + '178testLevel1StringtestString64testLevel1StringAfter'\n + '191testSomeString60pleasework7.11'\n + ''\n xmlrpcParser.parseResponseXml(xml, this.callback)\n }\n , 'contains an array of arrays' : function (err, params) {\n assert.typeOf(params[0], 'array')\n assert.typeOf(params[1], 'array')\n assert.deepEqual(params, [[178, 'testLevel1String', ['testString', 64], 'testLevel1StringAfter'], [19, true, ['testSomeString', 60], 'pleasework', 7.11]])\n }\n }\n // Test Boolean\n , 'with a true Boolean param' : {\n topic: function() {\n xmlrpcParser.parseResponseXml('1', this.callback)\n }\n , 'contains an array with a true value' : function (err, params) {\n assert.typeOf(params[0], 'boolean')\n assert.deepEqual(params, [true])\n }\n }\n , 'with a false Boolean param' : {\n topic: function() {\n xmlrpcParser.parseResponseXml('0', this.callback)\n }\n , 'contains an array with a false value' : function (err, params) {\n assert.typeOf(params[0], 'boolean')\n assert.deepEqual(params, [false])\n }\n }\n // Test DateTime\n , 'with a Datetime param' : {\n topic: function() {\n xmlrpcParser.parseResponseXml('20120608T11:35:10', this.callback)\n }\n , 'contains the Date object' : function (err, params) {\n assert.typeOf(params[0], 'date')\n assert.deepEqual(params, [new Date(2012, 05, 08, 11, 35, 10)])\n }\n }\n // Test Double\n , 'with a positive Double param' : {\n topic: function() {\n xmlrpcParser.parseResponseXml('4.11', this.callback)\n }\n , 'contains the positive double' : function (err, params) {\n assert.typeOf(params[0], 'number')\n assert.deepEqual(params, [4.11])\n }\n }\n , 'with a negative Double param' : {\n topic: function() {\n xmlrpcParser.parseResponseXml('-4.2221', this.callback)\n }\n , 'contains the positive double' : function (err, params) {\n assert.typeOf(params[0], 'number')\n assert.deepEqual(params, [-4.2221])\n }\n }\n // Test Integer\n , 'with a positive Int param' : {\n topic: function() {\n xmlrpcParser.parseResponseXml('4', this.callback)\n }\n , 'contains the positive integer' : function (err, params) {\n assert.typeOf(params[0], 'number')\n assert.deepEqual(params, [4])\n }\n }\n , 'with a positive I4 param' : {\n topic: function() {\n xmlrpcParser.parseResponseXml('6', this.callback)\n }\n , 'contains the positive integer' : function (err, params) {\n assert.typeOf(params[0], 'number')\n assert.deepEqual(params, [6])\n }\n }\n , 'with a negative Int param' : {\n topic: function() {\n xmlrpcParser.parseResponseXml('-14', this.callback)\n }\n , 'contains the negative integer' : function (err, params) {\n assert.typeOf(params[0], 'number')\n assert.deepEqual(params, [-14])\n }\n }\n , 'with a negative I4 param' : {\n topic: function() {\n xmlrpcParser.parseResponseXml('-26', this.callback)\n }\n , 'contains the negative integer' : function (err, params) {\n assert.typeOf(params[0], 'number')\n assert.deepEqual(params, [-26])\n }\n }\n , 'with a Int param of 0' : {\n topic: function() {\n xmlrpcParser.parseResponseXml('0', this.callback)\n }\n , 'contains the value 0' : function (err, params) {\n assert.typeOf(params[0], 'number')\n assert.deepEqual(params, [0])\n }\n }\n , 'with a I4 param of 0' : {\n topic: function() {\n xmlrpcParser.parseResponseXml('0', this.callback)\n }\n , 'contains the value 0' : function (err, params) {\n assert.typeOf(params[0], 'number')\n assert.deepEqual(params, [0])\n }\n }\n // Test String\n , 'with a String param' : {\n topic: function() {\n xmlrpcParser.parseResponseXml('testString', this.callback)\n }\n , 'contains an array with the string' : function (err, params) {\n assert.typeOf(params[0], 'string')\n assert.deepEqual(params, ['testString'])\n }\n }\n // Test Struct\n , 'with a Struct param' : {\n topic: function() {\n xmlrpcParser.parseResponseXml('theNametestValue', this.callback)\n }\n , 'contains the object' : function (err, params) {\n assert.isObject(params[0])\n assert.deepEqual(params, [{ theName: 'testValue'}])\n }\n }\n , 'with a nested Struct param' : {\n topic: function() {\n var xml = ''\n + 'theNametestValueanotherNamenestedNamenestedValuelastNameSmith'\n + ''\n xmlrpcParser.parseResponseXml(xml, this.callback)\n }\n , 'contains the objects' : function (err, params) {\n assert.isObject(params[0])\n assert.deepEqual(params, [{ theName: 'testValue', anotherName: {nestedName: 'nestedValue' }, lastName: 'Smith'}])\n }\n }\n }\n\n}).export(module)\n"},"message":{"kind":"string","value":"Minor refactoring and beefing up of the parser test cases.\n"},"old_file":{"kind":"string","value":"test/xmlrpc-parser-test.js"},"subject":{"kind":"string","value":"Minor refactoring and beefing up of the parser test cases."},"git_diff":{"kind":"string","value":"est/xmlrpc-parser-test.js\n // Test parseResponseXml functionality\n 'A parseResponseXml call' : {\n // Test Array\n 'with an Array param' : { topic: function() {\n xmlrpcParser.parseResponseXml('178testString', this.callback)\n 'with an Array param' : {\n topic: function() {\n var xml = ''\n + '178testString'\n + ''\n xmlrpcParser.parseResponseXml(xml, this.callback)\n }\n , 'contains an array of arrays' : function (err, params) {\n assert.typeOf(params[0], 'array')\n }\n , 'with a nested Array param' : {\n topic: function() {\n xmlrpcParser.parseResponseXml('178testLevel1StringtestString64', this.callback)\n var xml = ''\n + '178testLevel1StringtestString64'\n + ''\n xmlrpcParser.parseResponseXml(xml, this.callback)\n }\n , 'contains an array of arrays' : function (err, params) {\n assert.typeOf(params[0], 'array')\n }\n , 'with a nested Array param and values after the nested array' : {\n topic: function() {\n xmlrpcParser.parseResponseXml('178testLevel1StringtestString64testLevel1StringAfter', this.callback)\n var xml = ''\n + '178testLevel1StringtestString64testLevel1StringAfter'\n + ''\n xmlrpcParser.parseResponseXml(xml, this.callback)\n }\n , 'contains an array of arrays' : function (err, params) {\n assert.typeOf(params[0], 'array')\n // Test Boolean\n , 'with a true Boolean param' : {\n topic: function() {\n xmlrpcParser.parseResponseXml('1', this.callback)\n var xml = ''\n + '1'\n + ''\n xmlrpcParser.parseResponseXml(xml, this.callback)\n }\n , 'contains an array with a true value' : function (err, params) {\n assert.typeOf(params[0], 'boolean')\n }\n , 'with a false Boolean param' : {\n topic: function() {\n xmlrpcParser.parseResponseXml('0', this.callback)\n var xml = ''\n + '0'\n + ''\n xmlrpcParser.parseResponseXml(xml, this.callback)\n }\n , 'contains an array with a false value' : function (err, params) {\n assert.typeOf(params[0], 'boolean')\n // Test DateTime\n , 'with a Datetime param' : {\n topic: function() {\n xmlrpcParser.parseResponseXml('20120608T11:35:10', this.callback)\n var xml = ''\n + '20120608T11:35:10'\n + ''\n xmlrpcParser.parseResponseXml(xml, this.callback)\n }\n , 'contains the Date object' : function (err, params) {\n assert.typeOf(params[0], 'date')\n // Test Double\n , 'with a positive Double param' : {\n topic: function() {\n xmlrpcParser.parseResponseXml('4.11', this.callback)\n var xml = ''\n + '4.11'\n + ''\n xmlrpcParser.parseResponseXml(xml, this.callback)\n }\n , 'contains the positive double' : function (err, params) {\n assert.typeOf(params[0], 'number')\n }\n , 'with a negative Double param' : {\n topic: function() {\n xmlrpcParser.parseResponseXml('-4.2221', this.callback)\n var xml = ''\n + '-4.2221'\n + ''\n xmlrpcParser.parseResponseXml(xml, this.callback)\n }\n , 'contains the positive double' : function (err, params) {\n assert.typeOf(params[0], 'number')\n // Test Integer\n , 'with a positive Int param' : {\n topic: function() {\n xmlrpcParser.parseResponseXml('4', this.callback)\n var xml = ''\n + '4'\n + ''\n xmlrpcParser.parseResponseXml(xml, this.callback)\n }\n , 'contains the positive integer' : function (err, params) {\n assert.typeOf(params[0], 'number')\n }\n , 'with a positive I4 param' : {\n topic: function() {\n xmlrpcParser.parseResponseXml('6', this.callback)\n var xml = ''\n + '6'\n + ''\n xmlrpcParser.parseResponseXml(xml, this.callback)\n }\n , 'contains the positive integer' : function (err, params) {\n assert.typeOf(params[0], 'number')\n }\n , 'with a negative Int param' : {\n topic: function() {\n xmlrpcParser.parseResponseXml('-14', this.callback)\n var xml = ''\n + '-14'\n + ''\n xmlrpcParser.parseResponseXml(xml, this.callback)\n }\n , 'contains the negative integer' : function (err, params) {\n assert.typeOf(params[0], 'number')\n }\n , 'with a negative I4 param' : {\n topic: function() {\n xmlrpcParser.parseResponseXml('-26', this.callback)\n var xml = ''\n + '-26'\n + ''\n xmlrpcParser.parseResponseXml(xml, this.callback)\n }\n , 'contains the negative integer' : function (err, params) {\n assert.typeOf(params[0], 'number')\n }\n , 'with a Int param of 0' : {\n topic: function() {\n xmlrpcParser.parseResponseXml('0', this.callback)\n var xml = ''\n + '0'\n + ''\n xmlrpcParser.parseResponseXml(xml, this.callback)\n }\n , 'contains the value 0' : function (err, params) {\n assert.typeOf(params[0], 'number')\n }\n , 'with a I4 param of 0' : {\n topic: function() {\n xmlrpcParser.parseResponseXml('0', this.callback)\n var xml = ''\n + '0'\n + ''\n xmlrpcParser.parseResponseXml(xml, this.callback)\n }\n , 'contains the value 0' : function (err, params) {\n assert.typeOf(params[0], 'number')\n // Test String\n , 'with a String param' : {\n topic: function() {\n xmlrpcParser.parseResponseXml('testString', this.callback)\n var xml = ''\n + 'testString'\n + ''\n xmlrpcParser.parseResponseXml(xml, this.callback)\n }\n , 'contains an array with the string' : function (err, params) {\n assert.typeOf(params[0], 'string')\n // Test Struct\n , 'with a Struct param' : {\n topic: function() {\n xmlrpcParser.parseResponseXml('theNametestValue', this.callback)\n var xml = ''\n + 'theNametestValue'\n + ''\n xmlrpcParser.parseResponseXml(xml, this.callback)\n }\n , 'contains the object' : function (err, params) {\n assert.isObject(params[0])\n assert.deepEqual(params, [{ theName: 'testValue', anotherName: {nestedName: 'nestedValue' }, lastName: 'Smith'}])\n }\n }\n // The grinder\n , 'with a mix of everything' : {\n topic: function() {\n var xml = ''\n + 'theNametestValue2anotherName2somenestedNamenestedValue2klastNameSmith'\n + ''\n + 'theNametestValueanotherNamenestedNamenestedValuelastNameSmith'\n + ''\n + 'yetAnotherName1999.26'\n + 'moreNested'\n + ''\n + ''\n + '19850608T14:35:10'\n + ''\n xmlrpcParser.parseResponseXml(xml, this.callback)\n }\n , 'contains the objects' : function (err, params) {\n assert.isObject(params[0])\n var expected = [\n { theName: 'testValue2', anotherName2: {somenestedName: 'nestedValue2k' }, lastName: 'Smith'}\n , [\n { theName: 'testValue', anotherName: {nestedName: 'nestedValue' }, lastName: 'Smith' }\n , [\n { yetAnotherName: 1999.26}\n , 'moreNested'\n ]\n ]\n , new Date(1985, 05, 08, 14, 35, 10)\n ]\n assert.deepEqual(params, expected)\n }\n }\n }\n \n }).export(module)"}}},{"rowIdx":1927,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"684aaa72dcb7e3c09a08ed8ef7db02fff78f1e75"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"osmdroid/osmdroid,osmdroid/osmdroid,osmdroid/osmdroid,osmdroid/osmdroid"},"new_contents":{"kind":"string","value":"package org.osmdroid.samplefragments.data;\n\nimport android.graphics.Color;\nimport android.util.DisplayMetrics;\nimport android.util.Log;\n\nimport org.osmdroid.api.IGeoPoint;\nimport org.osmdroid.events.MapListener;\nimport org.osmdroid.events.ScrollEvent;\nimport org.osmdroid.events.ZoomEvent;\nimport org.osmdroid.samplefragments.BaseSampleFragment;\nimport org.osmdroid.util.BoundingBox;\nimport org.osmdroid.util.GeoPoint;\nimport org.osmdroid.views.overlay.FolderOverlay;\nimport org.osmdroid.views.overlay.Overlay;\nimport org.osmdroid.views.overlay.Polygon;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\n\n/**\n * https://github.com/osmdroid/osmdroid/issues/499\n *

\n * Demonstrates a way to generate heatmaps using osmdroid and a collection of data points.\n * There's a lot of room for improvement but this class demonstrates two things\n *

    \n *
  • How to load data asynchronously when the map moves/zooms
  • \n *
  • How to generate a basic heat map
  • \n *
\n *

\n * There's probably a many options to implement this. This example basically chops up the screen\n * into cells, generates some random data, then iterates all of the data and increments up a\n * counter based on the cell that it was rendered into. Finally the cells are converted into square\n * polygons with a fill color based on the counter.\n *

\n * It's assumed that all required data is available on device for this example.\n *

\n * For future readers: other approaches\n *

    \n *
  • if a server/network connection is available, it would be better to have the server\n * generate a kml/kmz for the heat map, then use osmbonuspack to do the parsing. this will be much\n * better at handling higher volumes of data
  • \n *
  • use a server that generates slippy map tiles representing the overlay, then add a secondary {@link org.osmdroid.views.overlay.TilesOverlay} with that source.
  • \n *
  • locally (on device) generates an image for the slippy map tiles representing the data, then add a secondary {@link org.osmdroid.views.overlay.TilesOverlay} with that source.
  • \n *
  • make a custom {@link Overlay} class that has some custom onDraw logical to paint the image.
  • \n *
\n *

\n * created on 1/1/2017.\n *\n * @author Alex O'Ree\n * @since 5.6.3\n */\n\npublic class HeatMap extends BaseSampleFragment implements MapListener, Runnable {\n @Override\n public String getSampleTitle() {\n return \"Heatmap with Async loading\";\n }\n\n String TAG = \"heatmap\";\n DisplayMetrics dm = null;\n\n // async loading stuff\n boolean renderJobActive = false;\n boolean running = true;\n long lastMovement = 0;\n boolean needsDataRefresh = true;\n // end async loading stuff\n\n\n /**\n * the size of the cell in density independent pixels\n * a higher value = smoother image but higher processing and rendering times\n */\n int cellSizeInDp = 20;\n\n\n //colors and alpha settings\n String alpha = \"#55\";\n String red = \"FF0000\";\n String orange = \"FFA500\";\n String yellow = \"FFFF00\";\n\n //a pointer to the last render overlay, so that we can remove/replace it with the new one\n FolderOverlay heatmapOverlay = null;\n\n\n @Override\n public void addOverlays() {\n super.addOverlays();\n dm = getResources().getDisplayMetrics();\n mMapView.getController().setCenter(new GeoPoint(38.8977, -77.0365));\n mMapView.getController().setZoom(14);\n mMapView.setMapListener(this);\n }\n\n @Override\n public void onPause() {\n super.onPause();\n running = false;\n }\n\n @Override\n public void onResume() {\n super.onResume();\n running = true;\n Thread t = new Thread(this);\n t.start();\n }\n\n /**\n * this generates the heatmap off of the main thread, loads the data, makes the overlay, then\n * adds it to the map\n */\n private void generateMap() {\n\n if (getActivity()==null) //java.lang.IllegalStateException: Fragment HeatMap{44f341d0} not attached to Activity\n return;\n if (renderJobActive)\n return;\n renderJobActive = true;\n\n\n\n int densityDpi = (int) (dm.density * cellSizeInDp);\n //10 dpi sized cells\n\n IGeoPoint iGeoPoint = mMapView.getProjection().fromPixels(0, 0);\n IGeoPoint iGeoPoint2 = mMapView.getProjection().fromPixels(densityDpi, densityDpi);\n //delta is the size of our cell in lat,lon\n //since this is zoom dependent, rerun the calculations on zoom changes\n double xCellSizeLongitude = Math.abs(iGeoPoint.getLongitude() - iGeoPoint2.getLongitude());\n double yCellSizeLatitude = Math.abs(iGeoPoint.getLatitude() - iGeoPoint2.getLatitude());\n\n BoundingBox view = mMapView.getBoundingBox();\n //a set of a GeoPoints representing what we want a heat map of.\n List pts = loadPoints(view);\n\n //the highest value in our collection of stuff\n int maxHeat = 0;\n //a temp container of all grid cells and their hit count (which turns into a color on render)\n\n //the lower the cell size the more cells and items in the map.\n Map heatmap = new HashMap();\n //create the grid\n\n Log.i(TAG, \"heatmap builder \" + yCellSizeLatitude + \" \" + xCellSizeLongitude);\n Log.i(TAG, \"heatmap builder \" + view);\n\n //populate the cells\n for (double lat = view.getLatNorth(); lat >= view.getLatSouth(); lat = lat - yCellSizeLatitude) {\n for (double lon = view.getLonEast(); lon >= view.getLonWest(); lon = lon - xCellSizeLongitude) {\n //Log.i(TAG,\"heatmap builder \" + lat + \",\" + lon);\n heatmap.put(new BoundingBox(lat, lon, lat - yCellSizeLatitude, lon - xCellSizeLongitude), 0);\n }\n }\n\n\n Log.i(TAG, \"generating the heatmap\");\n long now = System.currentTimeMillis();\n\n //generate the map, put the items in each cell\n for (int i = 0; i < pts.size(); i++) {\n //get the box for this pt's coordinates\n int x = increment(pts.get(i), heatmap);\n if (x > maxHeat)\n maxHeat = x;\n\n }\n Log.i(TAG, \"generating the heatmap, done \" + (System.currentTimeMillis() - now));\n\n //figure out the color scheme\n //if you need a more logirthmic scale, this is the place to do it.\n //cells with a 0 value are blank\n //cells 1 to 1/3 of the max value are yellow\n //cells from 1/3 to 2/3 are organge\n //cells 2/3 or higher are red\n int redthreshold = maxHeat * 2 / 3; //upper 1/3\n int orangethreshold = maxHeat * 1 / 3; //middle 1/3\n\n //render the map\n Log.i(TAG, \"rendering\");\n now = System.currentTimeMillis();\n //each bounding box if the hit count > 0 create a polygon with the bounding box coordinates with the right fill color\n final FolderOverlay group = new FolderOverlay();\n Iterator> iterator = heatmap.entrySet().iterator();\n while (iterator.hasNext()) {\n Map.Entry next = iterator.next();\n if (next.getValue() > 0) {\n group.add(createPolygon(next.getKey(), next.getValue(), redthreshold, orangethreshold));\n }\n }\n Log.i(TAG, \"render done , done \" + (System.currentTimeMillis() - now));\n if (getActivity()==null) //java.lang.IllegalStateException: Fragment HeatMap{44f341d0} not attached to Activity\n return;\n if (mMapView==null) //java.lang.IllegalStateException: Fragment HeatMap{44f341d0} not attached to Activity\n return;\n mMapView.post(new Runnable() {\n @Override\n public void run() {\n if (heatmapOverlay != null)\n mMapView.getOverlayManager().remove(heatmapOverlay);\n mMapView.getOverlayManager().add(group);\n heatmapOverlay = group;\n\n mMapView.invalidate();\n renderJobActive = false;\n }\n });\n }\n\n\n /**\n * generates a bunch of random data\n *\n * @param view\n * @return\n */\n private List loadPoints(BoundingBox view) {\n List pts = new ArrayList();\n\n for (int i = 0; i < 10000; i++) {\n pts.add(new GeoPoint((Math.random() * view.getLatitudeSpan()) + view.getLatSouth(),\n (Math.random() * view.getLongitudeSpan()) + view.getLonWest()));\n }\n pts.add(new GeoPoint(0d, 0d));\n pts.add(new GeoPoint(0d, 0d));\n pts.add(new GeoPoint(0d, 0d));\n pts.add(new GeoPoint(0d, 0d));\n pts.add(new GeoPoint(0d, 0d));\n pts.add(new GeoPoint(0d, 0d));\n pts.add(new GeoPoint(0d, 0d));\n pts.add(new GeoPoint(0d, 0d));\n pts.add(new GeoPoint(0d, 0d));\n pts.add(new GeoPoint(0d, 0d));\n pts.add(new GeoPoint(0d, 0d));\n pts.add(new GeoPoint(0d, 0d));\n pts.add(new GeoPoint(0d, 0d));\n pts.add(new GeoPoint(0d, 0d));\n\n\n pts.add(new GeoPoint(1.1d * cellSizeInDp, 1.1d * cellSizeInDp));\n pts.add(new GeoPoint(1.1d * cellSizeInDp, 1.1d * cellSizeInDp));\n pts.add(new GeoPoint(1.1d * cellSizeInDp, 1.1d * cellSizeInDp));\n pts.add(new GeoPoint(1.1d * cellSizeInDp, 1.1d * cellSizeInDp));\n pts.add(new GeoPoint(1.1d * cellSizeInDp, 1.1d * cellSizeInDp));\n pts.add(new GeoPoint(1.1d * cellSizeInDp, 1.1d * cellSizeInDp));\n pts.add(new GeoPoint(1.1d * cellSizeInDp, 1.1d * cellSizeInDp));\n\n pts.add(new GeoPoint(-1.1d * cellSizeInDp, -1.1d * cellSizeInDp));\n pts.add(new GeoPoint(-1.1d * cellSizeInDp, -1.1d * cellSizeInDp));\n pts.add(new GeoPoint(-1.1d * cellSizeInDp, -1.1d * cellSizeInDp));\n pts.add(new GeoPoint(-1.1d * cellSizeInDp, -1.1d * cellSizeInDp));\n pts.add(new GeoPoint(-1.1d * cellSizeInDp, -1.1d * cellSizeInDp));\n pts.add(new GeoPoint(-1.1d * cellSizeInDp, -1.1d * cellSizeInDp));\n pts.add(new GeoPoint(-1.1d * cellSizeInDp, -1.1d * cellSizeInDp));\n\n pts.add(new GeoPoint(-1.1d * cellSizeInDp, 1.1d * cellSizeInDp));\n pts.add(new GeoPoint(-1.1d * cellSizeInDp, 1.1d * cellSizeInDp));\n pts.add(new GeoPoint(-1.1d * cellSizeInDp, 1.1d * cellSizeInDp));\n pts.add(new GeoPoint(-1.1d * cellSizeInDp, 1.1d * cellSizeInDp));\n\n\n pts.add(new GeoPoint(1.1d * cellSizeInDp, -1.1d * cellSizeInDp));\n pts.add(new GeoPoint(1.1d * cellSizeInDp, -1.1d * cellSizeInDp));\n pts.add(new GeoPoint(1.1d * cellSizeInDp, -1.1d * cellSizeInDp));\n\n return pts;\n }\n\n /**\n * converts the bounding box into a color filled polygon\n *\n * @param key\n * @param value\n * @param redthreshold\n * @param orangethreshold\n * @return\n */\n private Overlay createPolygon(BoundingBox key, Integer value, int redthreshold, int orangethreshold) {\n Polygon polygon = new Polygon();\n if (value < orangethreshold)\n polygon.setFillColor(Color.parseColor(alpha + yellow));\n else if (value < redthreshold)\n polygon.setFillColor(Color.parseColor(alpha + orange));\n else if (value >= redthreshold)\n polygon.setFillColor(Color.parseColor(alpha + red));\n else {\n //no polygon\n }\n polygon.setStrokeColor(polygon.getFillColor());\n\n //if you set this to something like 20f and have a low alpha setting,\n // you'll end with a gaussian blur like effect\n polygon.setStrokeWidth(0f);\n List pts = new ArrayList();\n pts.add(new GeoPoint(key.getLatNorth(), key.getLonWest()));\n pts.add(new GeoPoint(key.getLatNorth(), key.getLonEast()));\n pts.add(new GeoPoint(key.getLatSouth(), key.getLonEast()));\n pts.add(new GeoPoint(key.getLatSouth(), key.getLonWest()));\n polygon.setPoints(pts);\n return polygon;\n }\n\n /**\n * For each data point, find the corresponding cell, then increment the count. This is the\n * most inefficient portion of this example.\n *

\n * room for improvement: replace with some kind of geospatial indexing mechanism\n *\n * @param iGeoPoint\n * @param heatmap\n * @return\n */\n private int increment(IGeoPoint iGeoPoint, Map heatmap) {\n\n Iterator> iterator = heatmap.entrySet().iterator();\n while (iterator.hasNext()) {\n Map.Entry next = iterator.next();\n if (next.getKey().contains(iGeoPoint)) {\n int newval = next.getValue() + 1;\n heatmap.put(next.getKey(), newval);\n return newval;\n }\n }\n return 0;\n }\n\n /**\n * handles the map movement rendering portions, prevents more than one render at a time,\n * waits for the user to stop moving the map before triggering the render\n */\n @Override\n public boolean onScroll(ScrollEvent event) {\n lastMovement = System.currentTimeMillis();\n needsDataRefresh = true;\n return false;\n }\n\n /**\n * handles the map movement rendering portions, prevents more than one render at a time,\n * waits for the user to stop moving the map before triggering the render\n */\n @Override\n public boolean onZoom(ZoomEvent event) {\n lastMovement = System.currentTimeMillis();\n needsDataRefresh = true;\n return false;\n }\n\n /**\n * handles the map movement rendering portions, prevents more than one render at a time,\n * waits for the user to stop moving the map before triggering the render\n */\n @Override\n public void run() {\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e) {\n\n }\n while (running) {\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n if (needsDataRefresh) {\n if (System.currentTimeMillis() - lastMovement > 500) {\n generateMap();\n needsDataRefresh = false;\n }\n }\n }\n }\n\n\n /**\n * optional place to put automated test procedures, used during the connectCheck tests\n * this is called OFF of the UI thread. block this method call util the test is done\n */\n @Override\n public void runTestProcedures() throws Exception{\n Thread.sleep(5000);\n\n }\n}\n"},"new_file":{"kind":"string","value":"OpenStreetMapViewer/src/main/java/org/osmdroid/samplefragments/data/HeatMap.java"},"old_contents":{"kind":"string","value":"package org.osmdroid.samplefragments.data;\n\nimport android.graphics.Color;\nimport android.util.DisplayMetrics;\nimport android.util.Log;\n\nimport org.osmdroid.api.IGeoPoint;\nimport org.osmdroid.events.MapListener;\nimport org.osmdroid.events.ScrollEvent;\nimport org.osmdroid.events.ZoomEvent;\nimport org.osmdroid.samplefragments.BaseSampleFragment;\nimport org.osmdroid.util.BoundingBox;\nimport org.osmdroid.util.GeoPoint;\nimport org.osmdroid.views.overlay.FolderOverlay;\nimport org.osmdroid.views.overlay.Overlay;\nimport org.osmdroid.views.overlay.Polygon;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\n\n/**\n * https://github.com/osmdroid/osmdroid/issues/499\n *

\n * Demonstrates a way to generate heatmaps using osmdroid and a collection of data points.\n * There's a lot of room for improvement but this class demonstrates two things\n *

    \n *
  • How to load data asynchronously when the map moves/zooms
  • \n *
  • How to generate a basic heat map
  • \n *
\n *

\n * There's probably a many options to implement this. This example basically chops up the screen\n * into cells, generates some random data, then iterates all of the data and increments up a\n * counter based on the cell that it was rendered into. Finally the cells are converted into square\n * polygons with a fill color based on the counter.\n *

\n * It's assumed that all required data is available on device for this example.\n *

\n * For future readers: other approaches\n *

    \n *
  • if a server/network connection is available, it would be better to have the server\n * generate a kml/kmz for the heat map, then use osmbonuspack to do the parsing. this will be much\n * better at handling higher volumes of data
  • \n *
  • use a server that generates slippy map tiles representing the overlay, then add a secondary {@link org.osmdroid.views.overlay.TilesOverlay} with that source.
  • \n *
  • locally (on device) generates an image for the slippy map tiles representing the data, then add a secondary {@link org.osmdroid.views.overlay.TilesOverlay} with that source.
  • \n *
  • make a custom {@link Overlay} class that has some custom onDraw logical to paint the image.
  • \n *
\n *

\n * created on 1/1/2017.\n *\n * @author Alex O'Ree\n * @since 5.6.3\n */\n\npublic class HeatMap extends BaseSampleFragment implements MapListener, Runnable {\n @Override\n public String getSampleTitle() {\n return \"Heatmap with Async loading\";\n }\n\n String TAG = \"heatmap\";\n\n // async loading stuff\n boolean renderJobActive = false;\n boolean running = true;\n long lastMovement = 0;\n boolean needsDataRefresh = true;\n // end async loading stuff\n\n\n /**\n * the size of the cell in density independent pixels\n * a higher value = smoother image but higher processing and rendering times\n */\n int cellSizeInDp = 20;\n\n\n //colors and alpha settings\n String alpha = \"#55\";\n String red = \"FF0000\";\n String orange = \"FFA500\";\n String yellow = \"FFFF00\";\n\n //a pointer to the last render overlay, so that we can remove/replace it with the new one\n FolderOverlay heatmapOverlay = null;\n\n\n @Override\n public void addOverlays() {\n super.addOverlays();\n mMapView.getController().setCenter(new GeoPoint(38.8977, -77.0365));\n mMapView.getController().setZoom(14);\n mMapView.setMapListener(this);\n }\n\n @Override\n public void onPause() {\n super.onPause();\n running = false;\n }\n\n @Override\n public void onResume() {\n super.onResume();\n running = true;\n Thread t = new Thread(this);\n t.start();\n }\n\n /**\n * this generates the heatmap off of the main thread, loads the data, makes the overlay, then\n * adds it to the map\n */\n private void generateMap() {\n\n if (renderJobActive)\n return;\n renderJobActive = true;\n\n DisplayMetrics dm = getResources().getDisplayMetrics();\n\n int densityDpi = (int) (dm.density * cellSizeInDp);\n //10 dpi sized cells\n\n IGeoPoint iGeoPoint = mMapView.getProjection().fromPixels(0, 0);\n IGeoPoint iGeoPoint2 = mMapView.getProjection().fromPixels(densityDpi, densityDpi);\n //delta is the size of our cell in lat,lon\n //since this is zoom dependent, rerun the calculations on zoom changes\n double xCellSizeLongitude = Math.abs(iGeoPoint.getLongitude() - iGeoPoint2.getLongitude());\n double yCellSizeLatitude = Math.abs(iGeoPoint.getLatitude() - iGeoPoint2.getLatitude());\n\n BoundingBox view = mMapView.getBoundingBox();\n //a set of a GeoPoints representing what we want a heat map of.\n List pts = loadPoints(view);\n\n //the highest value in our collection of stuff\n int maxHeat = 0;\n //a temp container of all grid cells and their hit count (which turns into a color on render)\n\n //the lower the cell size the more cells and items in the map.\n Map heatmap = new HashMap();\n //create the grid\n\n Log.i(TAG, \"heatmap builder \" + yCellSizeLatitude + \" \" + xCellSizeLongitude);\n Log.i(TAG, \"heatmap builder \" + view);\n\n //populate the cells\n for (double lat = view.getLatNorth(); lat >= view.getLatSouth(); lat = lat - yCellSizeLatitude) {\n for (double lon = view.getLonEast(); lon >= view.getLonWest(); lon = lon - xCellSizeLongitude) {\n //Log.i(TAG,\"heatmap builder \" + lat + \",\" + lon);\n heatmap.put(new BoundingBox(lat, lon, lat - yCellSizeLatitude, lon - xCellSizeLongitude), 0);\n }\n }\n\n\n Log.i(TAG, \"generating the heatmap\");\n long now = System.currentTimeMillis();\n\n //generate the map, put the items in each cell\n for (int i = 0; i < pts.size(); i++) {\n //get the box for this pt's coordinates\n int x = increment(pts.get(i), heatmap);\n if (x > maxHeat)\n maxHeat = x;\n\n }\n Log.i(TAG, \"generating the heatmap, done \" + (System.currentTimeMillis() - now));\n\n //figure out the color scheme\n //if you need a more logirthmic scale, this is the place to do it.\n //cells with a 0 value are blank\n //cells 1 to 1/3 of the max value are yellow\n //cells from 1/3 to 2/3 are organge\n //cells 2/3 or higher are red\n int redthreshold = maxHeat * 2 / 3; //upper 1/3\n int orangethreshold = maxHeat * 1 / 3; //middle 1/3\n\n //render the map\n Log.i(TAG, \"rendering\");\n now = System.currentTimeMillis();\n //each bounding box if the hit count > 0 create a polygon with the bounding box coordinates with the right fill color\n final FolderOverlay group = new FolderOverlay();\n Iterator> iterator = heatmap.entrySet().iterator();\n while (iterator.hasNext()) {\n Map.Entry next = iterator.next();\n if (next.getValue() > 0) {\n group.add(createPolygon(next.getKey(), next.getValue(), redthreshold, orangethreshold));\n }\n }\n Log.i(TAG, \"render done , done \" + (System.currentTimeMillis() - now));\n mMapView.post(new Runnable() {\n @Override\n public void run() {\n if (heatmapOverlay != null)\n mMapView.getOverlayManager().remove(heatmapOverlay);\n mMapView.getOverlayManager().add(group);\n heatmapOverlay = group;\n\n mMapView.invalidate();\n renderJobActive = false;\n }\n });\n }\n\n\n /**\n * generates a bunch of random data\n *\n * @param view\n * @return\n */\n private List loadPoints(BoundingBox view) {\n List pts = new ArrayList();\n\n for (int i = 0; i < 10000; i++) {\n pts.add(new GeoPoint((Math.random() * view.getLatitudeSpan()) + view.getLatSouth(),\n (Math.random() * view.getLongitudeSpan()) + view.getLonWest()));\n }\n pts.add(new GeoPoint(0d, 0d));\n pts.add(new GeoPoint(0d, 0d));\n pts.add(new GeoPoint(0d, 0d));\n pts.add(new GeoPoint(0d, 0d));\n pts.add(new GeoPoint(0d, 0d));\n pts.add(new GeoPoint(0d, 0d));\n pts.add(new GeoPoint(0d, 0d));\n pts.add(new GeoPoint(0d, 0d));\n pts.add(new GeoPoint(0d, 0d));\n pts.add(new GeoPoint(0d, 0d));\n pts.add(new GeoPoint(0d, 0d));\n pts.add(new GeoPoint(0d, 0d));\n pts.add(new GeoPoint(0d, 0d));\n pts.add(new GeoPoint(0d, 0d));\n\n\n pts.add(new GeoPoint(1.1d * cellSizeInDp, 1.1d * cellSizeInDp));\n pts.add(new GeoPoint(1.1d * cellSizeInDp, 1.1d * cellSizeInDp));\n pts.add(new GeoPoint(1.1d * cellSizeInDp, 1.1d * cellSizeInDp));\n pts.add(new GeoPoint(1.1d * cellSizeInDp, 1.1d * cellSizeInDp));\n pts.add(new GeoPoint(1.1d * cellSizeInDp, 1.1d * cellSizeInDp));\n pts.add(new GeoPoint(1.1d * cellSizeInDp, 1.1d * cellSizeInDp));\n pts.add(new GeoPoint(1.1d * cellSizeInDp, 1.1d * cellSizeInDp));\n\n pts.add(new GeoPoint(-1.1d * cellSizeInDp, -1.1d * cellSizeInDp));\n pts.add(new GeoPoint(-1.1d * cellSizeInDp, -1.1d * cellSizeInDp));\n pts.add(new GeoPoint(-1.1d * cellSizeInDp, -1.1d * cellSizeInDp));\n pts.add(new GeoPoint(-1.1d * cellSizeInDp, -1.1d * cellSizeInDp));\n pts.add(new GeoPoint(-1.1d * cellSizeInDp, -1.1d * cellSizeInDp));\n pts.add(new GeoPoint(-1.1d * cellSizeInDp, -1.1d * cellSizeInDp));\n pts.add(new GeoPoint(-1.1d * cellSizeInDp, -1.1d * cellSizeInDp));\n\n pts.add(new GeoPoint(-1.1d * cellSizeInDp, 1.1d * cellSizeInDp));\n pts.add(new GeoPoint(-1.1d * cellSizeInDp, 1.1d * cellSizeInDp));\n pts.add(new GeoPoint(-1.1d * cellSizeInDp, 1.1d * cellSizeInDp));\n pts.add(new GeoPoint(-1.1d * cellSizeInDp, 1.1d * cellSizeInDp));\n\n\n pts.add(new GeoPoint(1.1d * cellSizeInDp, -1.1d * cellSizeInDp));\n pts.add(new GeoPoint(1.1d * cellSizeInDp, -1.1d * cellSizeInDp));\n pts.add(new GeoPoint(1.1d * cellSizeInDp, -1.1d * cellSizeInDp));\n\n return pts;\n }\n\n /**\n * converts the bounding box into a color filled polygon\n *\n * @param key\n * @param value\n * @param redthreshold\n * @param orangethreshold\n * @return\n */\n private Overlay createPolygon(BoundingBox key, Integer value, int redthreshold, int orangethreshold) {\n Polygon polygon = new Polygon();\n if (value < orangethreshold)\n polygon.setFillColor(Color.parseColor(alpha + yellow));\n else if (value < redthreshold)\n polygon.setFillColor(Color.parseColor(alpha + orange));\n else if (value >= redthreshold)\n polygon.setFillColor(Color.parseColor(alpha + red));\n else {\n //no polygon\n }\n polygon.setStrokeColor(polygon.getFillColor());\n\n //if you set this to something like 20f and have a low alpha setting,\n // you'll end with a gaussian blur like effect\n polygon.setStrokeWidth(0f);\n List pts = new ArrayList();\n pts.add(new GeoPoint(key.getLatNorth(), key.getLonWest()));\n pts.add(new GeoPoint(key.getLatNorth(), key.getLonEast()));\n pts.add(new GeoPoint(key.getLatSouth(), key.getLonEast()));\n pts.add(new GeoPoint(key.getLatSouth(), key.getLonWest()));\n polygon.setPoints(pts);\n return polygon;\n }\n\n /**\n * For each data point, find the corresponding cell, then increment the count. This is the\n * most inefficient portion of this example.\n *

\n * room for improvement: replace with some kind of geospatial indexing mechanism\n *\n * @param iGeoPoint\n * @param heatmap\n * @return\n */\n private int increment(IGeoPoint iGeoPoint, Map heatmap) {\n\n Iterator> iterator = heatmap.entrySet().iterator();\n while (iterator.hasNext()) {\n Map.Entry next = iterator.next();\n if (next.getKey().contains(iGeoPoint)) {\n int newval = next.getValue() + 1;\n heatmap.put(next.getKey(), newval);\n return newval;\n }\n }\n return 0;\n }\n\n /**\n * handles the map movement rendering portions, prevents more than one render at a time,\n * waits for the user to stop moving the map before triggering the render\n */\n @Override\n public boolean onScroll(ScrollEvent event) {\n lastMovement = System.currentTimeMillis();\n needsDataRefresh = true;\n return false;\n }\n\n /**\n * handles the map movement rendering portions, prevents more than one render at a time,\n * waits for the user to stop moving the map before triggering the render\n */\n @Override\n public boolean onZoom(ZoomEvent event) {\n lastMovement = System.currentTimeMillis();\n needsDataRefresh = true;\n return false;\n }\n\n /**\n * handles the map movement rendering portions, prevents more than one render at a time,\n * waits for the user to stop moving the map before triggering the render\n */\n @Override\n public void run() {\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e) {\n\n }\n while (running) {\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n if (needsDataRefresh) {\n if (System.currentTimeMillis() - lastMovement > 500) {\n generateMap();\n needsDataRefresh = false;\n }\n }\n }\n }\n}\n"},"message":{"kind":"string","value":"#499 should fix the unit tests\n"},"old_file":{"kind":"string","value":"OpenStreetMapViewer/src/main/java/org/osmdroid/samplefragments/data/HeatMap.java"},"subject":{"kind":"string","value":"#499 should fix the unit tests"},"git_diff":{"kind":"string","value":"penStreetMapViewer/src/main/java/org/osmdroid/samplefragments/data/HeatMap.java\n }\n \n String TAG = \"heatmap\";\n DisplayMetrics dm = null;\n \n // async loading stuff\n boolean renderJobActive = false;\n @Override\n public void addOverlays() {\n super.addOverlays();\n dm = getResources().getDisplayMetrics();\n mMapView.getController().setCenter(new GeoPoint(38.8977, -77.0365));\n mMapView.getController().setZoom(14);\n mMapView.setMapListener(this);\n */\n private void generateMap() {\n \n if (getActivity()==null) //java.lang.IllegalStateException: Fragment HeatMap{44f341d0} not attached to Activity\n return;\n if (renderJobActive)\n return;\n renderJobActive = true;\n \n DisplayMetrics dm = getResources().getDisplayMetrics();\n\n \n int densityDpi = (int) (dm.density * cellSizeInDp);\n //10 dpi sized cells\n }\n }\n Log.i(TAG, \"render done , done \" + (System.currentTimeMillis() - now));\n if (getActivity()==null) //java.lang.IllegalStateException: Fragment HeatMap{44f341d0} not attached to Activity\n return;\n if (mMapView==null) //java.lang.IllegalStateException: Fragment HeatMap{44f341d0} not attached to Activity\n return;\n mMapView.post(new Runnable() {\n @Override\n public void run() {\n }\n }\n }\n\n\n /**\n * optional place to put automated test procedures, used during the connectCheck tests\n * this is called OFF of the UI thread. block this method call util the test is done\n */\n @Override\n public void runTestProcedures() throws Exception{\n Thread.sleep(5000);\n\n }\n }"}}},{"rowIdx":1928,"cells":{"lang":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"5c2db72cc2ef7c6483d50355f2fe9ce4521b4c04"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"cristobal-io/aviation-scrapper,cristobal-io/aviation-scraper,cristobal-io/aviation-scraper,cristobal-io/aviation-scrapper"},"new_contents":{"kind":"string","value":"\"use strict\";\n\nvar sjs = require(\"scraperjs\");\nvar fs = require(\"fs\");\nvar scrapers = require(\"../scrapers/\");\nvar _ = require(\"lodash\");\nvar async = require(\"async\");\n\nvar BASE_URL = \"https://en.wikipedia.org\";\n\nvar airlines = require(\"../data/destination_pages.json\");\n\nfunction getRoutes(options, callback) {\n console.log(\"options: \", options);\n var url = options.url || BASE_URL + options.destinationsLink;\n\n if (process.env.NODE_ENV !== \"test\") {\n console.log(\"Getting routes for %s from %s\", options.name, url); // eslint-disable-line no-console\n }\n sjs.StaticScraper.create(url)\n .scrape(scrapers[options.scraper] || scrapers[\"default\"])\n .then(function (data) {\n console.log(\"Results for %s\", options.name);\n console.log(JSON.stringify(data, null, 2));\n callback(null, data, options);\n });\n}\n\nvar writeJson = function (err, routes, options) {\n if (err) {\n throw err;\n }\n var filename = \"./data/routes_\" + options.name + \".json\";\n\n fs.writeFile(filename,\n JSON.stringify(routes, null, 2),\n function (err) {\n if (err) {\n throw err;\n }\n console.log(\"Saved %s\", filename); // eslint-disable-line no-console\n }\n );\n};\n\nairlines = _.where(airlines, {\n \"isolate\": true\n}) || airlines;\n// console.trace(airlines);\n// process.exit();\n// getRoutes(airlines[1], writeJson);\n\ngetAllRoutes(airlines, function () {\n console.log(\"callback finished\");\n});\n\n\n// changed to use the function inside the test, not sure if the callback will \n// work properly\n\nfunction getAllRoutes(airlines, callback) {\n console.log(airlines);\n async.forEachOf(airlines, function (value, key, callback) {\n getRoutes(value, writeJson);\n callback();\n }, function (err) {\n if (err) {\n throw err;\n }\n });\n // todo: this callback is not really working when called among process.\n callback();\n}\n\nmodule.exports.getRoutes = getRoutes;\nmodule.exports.getAllRoutes = getAllRoutes;\n"},"new_file":{"kind":"string","value":"src/airline_routes.js"},"old_contents":{"kind":"string","value":"\"use strict\";\n\nvar sjs = require(\"scraperjs\");\nvar fs = require(\"fs\");\nvar scrapers = require(\"../scrapers/\");\nvar _ = require(\"lodash\");\n\nvar BASE_URL = \"https://en.wikipedia.org\";\n\nvar airlines = require(\"../data/destination_pages.json\");\n\nfunction getRoutes(options, callback) {\n var url = options.url || BASE_URL + options.destinationsLink;\n\n if (process.env.NODE_ENV !== \"test\") {\n console.log(\"Getting routes for %s from %s\", options.name, url); // eslint-disable-line no-console\n }\n sjs.StaticScraper.create(url)\n .scrape(scrapers[options.scraper] || scrapers[\"default\"])\n .then(function (data) {\n // console.log(\"Results for %s\", options.name);\n // console.log(JSON.stringify(data, null, 2));\n callback(null, data, options);\n });\n}\n\nvar writeJson = function (err, routes, options) {\n if (err) {\n throw err;\n }\n var filename = \"./data/routes_\" + options.name + \".json\";\n\n fs.writeFile(filename,\n JSON.stringify(routes, null, 2),\n function (err) {\n if (err) {\n throw err;\n }\n console.log(\"Saved %s\", filename); // eslint-disable-line no-console\n }\n );\n};\n\nairlines = _.where(airlines, {\n \"isolate\": true\n}) || airlines;\n\n// console.trace(airlines);\n// process.exit();\n// getRoutes(airlines[1], writeJson);\n\nvar async = require(\"async\");\n\n// changed to use the function inside the test, not sure if the callback will \n// work properly\n\nfunction getAllRoutes(airlines, callback) {\n async.forEachOf(airlines, function (value, key, callback) {\n getRoutes(value, writeJson);\n callback();\n }, function (err) {\n if (err) {\n throw err;\n }\n });\n callback();\n}\n\nmodule.exports.getRoutes = getRoutes;\nmodule.exports.getAllRoutes = getAllRoutes;\n"},"message":{"kind":"string","value":"updated with new todo for fix\n"},"old_file":{"kind":"string","value":"src/airline_routes.js"},"subject":{"kind":"string","value":"updated with new todo for fix"},"git_diff":{"kind":"string","value":"rc/airline_routes.js\n var fs = require(\"fs\");\n var scrapers = require(\"../scrapers/\");\n var _ = require(\"lodash\");\nvar async = require(\"async\");\n \n var BASE_URL = \"https://en.wikipedia.org\";\n \n var airlines = require(\"../data/destination_pages.json\");\n \n function getRoutes(options, callback) {\n console.log(\"options: \", options);\n var url = options.url || BASE_URL + options.destinationsLink;\n \n if (process.env.NODE_ENV !== \"test\") {\n sjs.StaticScraper.create(url)\n .scrape(scrapers[options.scraper] || scrapers[\"default\"])\n .then(function (data) {\n // console.log(\"Results for %s\", options.name);\n // console.log(JSON.stringify(data, null, 2));\n console.log(\"Results for %s\", options.name);\n console.log(JSON.stringify(data, null, 2));\n callback(null, data, options);\n });\n }\n airlines = _.where(airlines, {\n \"isolate\": true\n }) || airlines;\n\n // console.trace(airlines);\n // process.exit();\n // getRoutes(airlines[1], writeJson);\n \nvar async = require(\"async\");\ngetAllRoutes(airlines, function () {\n console.log(\"callback finished\");\n});\n\n \n // changed to use the function inside the test, not sure if the callback will \n // work properly\n \n function getAllRoutes(airlines, callback) {\n console.log(airlines);\n async.forEachOf(airlines, function (value, key, callback) {\n getRoutes(value, writeJson);\n callback();\n throw err;\n }\n });\n // todo: this callback is not really working when called among process.\n callback();\n }\n "}}},{"rowIdx":1929,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"bfca4e59a1df1c5f92c7fdb27bb9e5fe2bfd5bfb"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"hashar/jenkins,ErikVerheul/jenkins,hemantojhaa/jenkins,DoctorQ/jenkins,SenolOzer/jenkins,jk47/jenkins,NehemiahMi/jenkins,varmenise/jenkins,Jimilian/jenkins,gitaccountforprashant/gittest,MichaelPranovich/jenkins_sc,292388900/jenkins,nandan4/Jenkins,DoctorQ/jenkins,aldaris/jenkins,kzantow/jenkins,everyonce/jenkins,brunocvcunha/jenkins,goldchang/jenkins,oleg-nenashev/jenkins,Jimilian/jenkins,akshayabd/jenkins,ndeloof/jenkins,jzjzjzj/jenkins,yonglehou/jenkins,bkmeneguello/jenkins,aduprat/jenkins,mpeltonen/jenkins,KostyaSha/jenkins,h4ck3rm1k3/jenkins,evernat/jenkins,SenolOzer/jenkins,jcsirot/jenkins,aldaris/jenkins,KostyaSha/jenkins,wangyikai/jenkins,tfennelly/jenkins,pantheon-systems/jenkins,samatdav/jenkins,paulmillar/jenkins,dennisjlee/jenkins,tangkun75/jenkins,msrb/jenkins,ajshastri/jenkins,bpzhang/jenkins,jpbriend/jenkins,rsandell/jenkins,scoheb/jenkins,keyurpatankar/hudson,lordofthejars/jenkins,albers/jenkins,aduprat/jenkins,huybrechts/hudson,jglick/jenkins,paulmillar/jenkins,gusreiber/jenkins,olivergondza/jenkins,stefanbrausch/hudson-main,ndeloof/jenkins,tfennelly/jenkins,mrobinet/jenkins,noikiy/jenkins,jzjzjzj/jenkins,paulwellnerbou/jenkins,lvotypko/jenkins,NehemiahMi/jenkins,soenter/jenkins,soenter/jenkins,6WIND/jenkins,andresrc/jenkins,mpeltonen/jenkins,iterate/coding-dojo,yonglehou/jenkins,aquarellian/jenkins,dariver/jenkins,pantheon-systems/jenkins,lvotypko/jenkins3,paulmillar/jenkins,kohsuke/hudson,evernat/jenkins,github-api-test-org/jenkins,evernat/jenkins,daspilker/jenkins,rlugojr/jenkins,azweb76/jenkins,recena/jenkins,patbos/jenkins,arcivanov/jenkins,NehemiahMi/jenkins,csimons/jenkins,FTG-003/jenkins,protazy/jenkins,seanlin816/jenkins,varmenise/jenkins,shahharsh/jenkins,github-api-test-org/jenkins,sathiya-mit/jenkins,Krasnyanskiy/jenkins,MadsNielsen/jtemp,h4ck3rm1k3/jenkins,FarmGeek4Life/jenkins,mrooney/jenkins,christ66/jenkins,vvv444/jenkins,wangyikai/jenkins,lordofthejars/jenkins,maikeffi/hudson,jpederzolli/jenkins-1,hplatou/jenkins,noikiy/jenkins,wangyikai/jenkins,ndeloof/jenkins,shahharsh/jenkins,huybrechts/hudson,alvarolobato/jenkins,aquarellian/jenkins,paulmillar/jenkins,verbitan/jenkins,hemantojhaa/jenkins,synopsys-arc-oss/jenkins,mdonohue/jenkins,gorcz/jenkins,stephenc/jenkins,vivek/hudson,1and1/jenkins,luoqii/jenkins,morficus/jenkins,mcanthony/jenkins,rsandell/jenkins,duzifang/my-jenkins,dennisjlee/jenkins,fbelzunc/jenkins,mattclark/jenkins,oleg-nenashev/jenkins,ydubreuil/jenkins,wuwen5/jenkins,wuwen5/jenkins,gusreiber/jenkins,pselle/jenkins,verbitan/jenkins,olivergondza/jenkins,6WIND/jenkins,jenkinsci/jenkins,intelchen/jenkins,stefanbrausch/hudson-main,NehemiahMi/jenkins,hemantojhaa/jenkins,sathiya-mit/jenkins,msrb/jenkins,duzifang/my-jenkins,DoctorQ/jenkins,morficus/jenkins,samatdav/jenkins,lilyJi/jenkins,daniel-beck/jenkins,verbitan/jenkins,lvotypko/jenkins2,mattclark/jenkins,christ66/jenkins,wuwen5/jenkins,jcsirot/jenkins,rashmikanta-1984/jenkins,paulwellnerbou/jenkins,abayer/jenkins,svanoort/jenkins,pjanouse/jenkins,ChrisA89/jenkins,hashar/jenkins,huybrechts/hudson,huybrechts/hudson,pselle/jenkins,jenkinsci/jenkins,msrb/jenkins,csimons/jenkins,ajshastri/jenkins,stephenc/jenkins,viqueen/jenkins,FTG-003/jenkins,synopsys-arc-oss/jenkins,Jimilian/jenkins,ndeloof/jenkins,noikiy/jenkins,jpederzolli/jenkins-1,pjanouse/jenkins,Ykus/jenkins,jk47/jenkins,MadsNielsen/jtemp,vlajos/jenkins,escoem/jenkins,goldchang/jenkins,tfennelly/jenkins,vvv444/jenkins,bpzhang/jenkins,huybrechts/hudson,vjuranek/jenkins,tastatur/jenkins,godfath3r/jenkins,292388900/jenkins,lordofthejars/jenkins,godfath3r/jenkins,liorhson/jenkins,guoxu0514/jenkins,mrobinet/jenkins,wangyikai/jenkins,wuwen5/jenkins,jpederzolli/jenkins-1,arcivanov/jenkins,patbos/jenkins,albers/jenkins,6WIND/jenkins,elkingtonmcb/jenkins,protazy/jenkins,amuniz/jenkins,AustinKwang/jenkins,bpzhang/jenkins,jk47/jenkins,azweb76/jenkins,MarkEWaite/jenkins,MichaelPranovich/jenkins_sc,petermarcoen/jenkins,daspilker/jenkins,ajshastri/jenkins,vivek/hudson,akshayabd/jenkins,arunsingh/jenkins,github-api-test-org/jenkins,mpeltonen/jenkins,jglick/jenkins,pantheon-systems/jenkins,ChrisA89/jenkins,batmat/jenkins,gorcz/jenkins,arcivanov/jenkins,ChrisA89/jenkins,verbitan/jenkins,CodeShane/jenkins,seanlin816/jenkins,andresrc/jenkins,mdonohue/jenkins,amruthsoft9/Jenkis,azweb76/jenkins,nandan4/Jenkins,Ykus/jenkins,khmarbaise/jenkins,tfennelly/jenkins,6WIND/jenkins,albers/jenkins,mpeltonen/jenkins,sathiya-mit/jenkins,mcanthony/jenkins,morficus/jenkins,hashar/jenkins,jcsirot/jenkins,dariver/jenkins,rlugojr/jenkins,noikiy/jenkins,deadmoose/jenkins,soenter/jenkins,FTG-003/jenkins,rsandell/jenkins,svanoort/jenkins,lindzh/jenkins,shahharsh/jenkins,ndeloof/jenkins,mrooney/jenkins,goldchang/jenkins,stephenc/jenkins,tfennelly/jenkins,DanielWeber/jenkins,aduprat/jenkins,varmenise/jenkins,CodeShane/jenkins,kzantow/jenkins,amruthsoft9/Jenkis,olivergondza/jenkins,patbos/jenkins,keyurpatankar/hudson,lilyJi/jenkins,paulmillar/jenkins,Jimilian/jenkins,lvotypko/jenkins2,fbelzunc/jenkins,FTG-003/jenkins,recena/jenkins,dennisjlee/jenkins,recena/jenkins,bpzhang/jenkins,h4ck3rm1k3/jenkins,jpederzolli/jenkins-1,stefanbrausch/hudson-main,pjanouse/jenkins,jzjzjzj/jenkins,daniel-beck/jenkins,Krasnyanskiy/jenkins,ikedam/jenkins,wuwen5/jenkins,daniel-beck/jenkins,CodeShane/jenkins,liupugong/jenkins,dariver/jenkins,maikeffi/hudson,escoem/jenkins,samatdav/jenkins,MadsNielsen/jtemp,vlajos/jenkins,sathiya-mit/jenkins,jhoblitt/jenkins,tangkun75/jenkins,jzjzjzj/jenkins,ns163/jenkins,ajshastri/jenkins,vlajos/jenkins,goldchang/jenkins,arcivanov/jenkins,duzifang/my-jenkins,gorcz/jenkins,kohsuke/hudson,synopsys-arc-oss/jenkins,thomassuckow/jenkins,sathiya-mit/jenkins,dennisjlee/jenkins,v1v/jenkins,fbelzunc/jenkins,damianszczepanik/jenkins,lvotypko/jenkins,oleg-nenashev/jenkins,kohsuke/hudson,mrooney/jenkins,daniel-beck/jenkins,vjuranek/jenkins,christ66/jenkins,jenkinsci/jenkins,jzjzjzj/jenkins,nandan4/Jenkins,bkmeneguello/jenkins,vjuranek/jenkins,pjanouse/jenkins,svanoort/jenkins,liorhson/jenkins,bkmeneguello/jenkins,lordofthejars/jenkins,chbiel/jenkins,khmarbaise/jenkins,vijayto/jenkins,Vlatombe/jenkins,ns163/jenkins,petermarcoen/jenkins,vjuranek/jenkins,stephenc/jenkins,oleg-nenashev/jenkins,escoem/jenkins,bkmeneguello/jenkins,jcsirot/jenkins,vvv444/jenkins,albers/jenkins,csimons/jenkins,github-api-test-org/jenkins,alvarolobato/jenkins,jk47/jenkins,noikiy/jenkins,kzantow/jenkins,daspilker/jenkins,thomassuckow/jenkins,DoctorQ/jenkins,liupugong/jenkins,duzifang/my-jenkins,godfath3r/jenkins,tangkun75/jenkins,protazy/jenkins,daniel-beck/jenkins,AustinKwang/jenkins,ajshastri/jenkins,godfath3r/jenkins,amuniz/jenkins,albers/jenkins,oleg-nenashev/jenkins,SenolOzer/jenkins,hplatou/jenkins,daspilker/jenkins,jcarrothers-sap/jenkins,tastatur/jenkins,rlugojr/jenkins,sathiya-mit/jenkins,jglick/jenkins,liorhson/jenkins,daspilker/jenkins,shahharsh/jenkins,FarmGeek4Life/jenkins,vijayto/jenkins,gitaccountforprashant/gittest,jglick/jenkins,arunsingh/jenkins,svanoort/jenkins,FarmGeek4Life/jenkins,gusreiber/jenkins,Krasnyanskiy/jenkins,pantheon-systems/jenkins,svanoort/jenkins,jcsirot/jenkins,keyurpatankar/hudson,SenolOzer/jenkins,scoheb/jenkins,mattclark/jenkins,stefanbrausch/hudson-main,dbroady1/jenkins,arunsingh/jenkins,daspilker/jenkins,gitaccountforprashant/gittest,samatdav/jenkins,h4ck3rm1k3/jenkins,patbos/jenkins,csimons/jenkins,brunocvcunha/jenkins,jtnord/jenkins,jtnord/jenkins,akshayabd/jenkins,tangkun75/jenkins,iterate/coding-dojo,jhoblitt/jenkins,hudson/hudson-2.x,jglick/jenkins,deadmoose/jenkins,aduprat/jenkins,jpbriend/jenkins,NehemiahMi/jenkins,luoqii/jenkins,lvotypko/jenkins2,bpzhang/jenkins,chbiel/jenkins,pselle/jenkins,liupugong/jenkins,viqueen/jenkins,Wilfred/jenkins,oleg-nenashev/jenkins,hplatou/jenkins,khmarbaise/jenkins,vlajos/jenkins,pjanouse/jenkins,MichaelPranovich/jenkins_sc,1and1/jenkins,arunsingh/jenkins,viqueen/jenkins,SenolOzer/jenkins,maikeffi/hudson,olivergondza/jenkins,recena/jenkins,aldaris/jenkins,keyurpatankar/hudson,tastatur/jenkins,paulwellnerbou/jenkins,Vlatombe/jenkins,batmat/jenkins,v1v/jenkins,wuwen5/jenkins,verbitan/jenkins,CodeShane/jenkins,stephenc/jenkins,vivek/hudson,synopsys-arc-oss/jenkins,wangyikai/jenkins,duzifang/my-jenkins,MichaelPranovich/jenkins_sc,patbos/jenkins,alvarolobato/jenkins,v1v/jenkins,jtnord/jenkins,morficus/jenkins,recena/jenkins,jtnord/jenkins,maikeffi/hudson,AustinKwang/jenkins,luoqii/jenkins,guoxu0514/jenkins,ikedam/jenkins,liorhson/jenkins,AustinKwang/jenkins,Ykus/jenkins,vlajos/jenkins,KostyaSha/jenkins,seanlin816/jenkins,olivergondza/jenkins,Krasnyanskiy/jenkins,aldaris/jenkins,vivek/hudson,MarkEWaite/jenkins,rashmikanta-1984/jenkins,github-api-test-org/jenkins,lindzh/jenkins,vjuranek/jenkins,andresrc/jenkins,vlajos/jenkins,morficus/jenkins,Wilfred/jenkins,seanlin816/jenkins,alvarolobato/jenkins,ErikVerheul/jenkins,ikedam/jenkins,elkingtonmcb/jenkins,msrb/jenkins,ErikVerheul/jenkins,1and1/jenkins,jtnord/jenkins,samatdav/jenkins,ydubreuil/jenkins,everyonce/jenkins,shahharsh/jenkins,guoxu0514/jenkins,lvotypko/jenkins2,dbroady1/jenkins,Jochen-A-Fuerbacher/jenkins,ns163/jenkins,oleg-nenashev/jenkins,rashmikanta-1984/jenkins,noikiy/jenkins,SebastienGllmt/jenkins,daspilker/jenkins,rsandell/jenkins,h4ck3rm1k3/jenkins,github-api-test-org/jenkins,csimons/jenkins,SebastienGllmt/jenkins,ns163/jenkins,mattclark/jenkins,varmenise/jenkins,hplatou/jenkins,vijayto/jenkins,lvotypko/jenkins3,dariver/jenkins,abayer/jenkins,huybrechts/hudson,petermarcoen/jenkins,khmarbaise/jenkins,hplatou/jenkins,mcanthony/jenkins,aquarellian/jenkins,KostyaSha/jenkins,lvotypko/jenkins,lvotypko/jenkins3,jpbriend/jenkins,Wilfred/jenkins,albers/jenkins,vjuranek/jenkins,hashar/jenkins,verbitan/jenkins,pselle/jenkins,tangkun75/jenkins,damianszczepanik/jenkins,Ykus/jenkins,abayer/jenkins,Krasnyanskiy/jenkins,kzantow/jenkins,SebastienGllmt/jenkins,jpbriend/jenkins,jhoblitt/jenkins,amuniz/jenkins,mrobinet/jenkins,aquarellian/jenkins,SenolOzer/jenkins,csimons/jenkins,Vlatombe/jenkins,thomassuckow/jenkins,amuniz/jenkins,jenkinsci/jenkins,alvarolobato/jenkins,singh88/jenkins,protazy/jenkins,dariver/jenkins,pantheon-systems/jenkins,aldaris/jenkins,tastatur/jenkins,aheritier/jenkins,varmenise/jenkins,elkingtonmcb/jenkins,MichaelPranovich/jenkins_sc,damianszczepanik/jenkins,Wilfred/jenkins,vvv444/jenkins,yonglehou/jenkins,pantheon-systems/jenkins,ikedam/jenkins,daniel-beck/jenkins,KostyaSha/jenkins,mdonohue/jenkins,Jochen-A-Fuerbacher/jenkins,liupugong/jenkins,vijayto/jenkins,shahharsh/jenkins,soenter/jenkins,jk47/jenkins,guoxu0514/jenkins,brunocvcunha/jenkins,arunsingh/jenkins,mrooney/jenkins,ajshastri/jenkins,lilyJi/jenkins,akshayabd/jenkins,iqstack/jenkins,MadsNielsen/jtemp,jtnord/jenkins,h4ck3rm1k3/jenkins,my7seven/jenkins,ikedam/jenkins,DanielWeber/jenkins,fbelzunc/jenkins,andresrc/jenkins,rlugojr/jenkins,kzantow/jenkins,amuniz/jenkins,ydubreuil/jenkins,ydubreuil/jenkins,yonglehou/jenkins,nandan4/Jenkins,FTG-003/jenkins,jpederzolli/jenkins-1,seanlin816/jenkins,msrb/jenkins,scoheb/jenkins,hashar/jenkins,Jimilian/jenkins,292388900/jenkins,pantheon-systems/jenkins,jglick/jenkins,goldchang/jenkins,christ66/jenkins,jhoblitt/jenkins,luoqii/jenkins,kzantow/jenkins,mcanthony/jenkins,rashmikanta-1984/jenkins,petermarcoen/jenkins,aquarellian/jenkins,ndeloof/jenkins,vjuranek/jenkins,evernat/jenkins,jcarrothers-sap/jenkins,DoctorQ/jenkins,stephenc/jenkins,mpeltonen/jenkins,amruthsoft9/Jenkis,Vlatombe/jenkins,NehemiahMi/jenkins,jcsirot/jenkins,elkingtonmcb/jenkins,fbelzunc/jenkins,CodeShane/jenkins,gusreiber/jenkins,yonglehou/jenkins,Vlatombe/jenkins,292388900/jenkins,jcarrothers-sap/jenkins,Ykus/jenkins,MarkEWaite/jenkins,jenkinsci/jenkins,FarmGeek4Life/jenkins,maikeffi/hudson,1and1/jenkins,CodeShane/jenkins,aldaris/jenkins,olivergondza/jenkins,iqstack/jenkins,protazy/jenkins,ikedam/jenkins,ns163/jenkins,jglick/jenkins,jhoblitt/jenkins,vijayto/jenkins,my7seven/jenkins,pselle/jenkins,6WIND/jenkins,patbos/jenkins,liupugong/jenkins,chbiel/jenkins,paulwellnerbou/jenkins,guoxu0514/jenkins,kohsuke/hudson,fbelzunc/jenkins,bkmeneguello/jenkins,pjanouse/jenkins,lvotypko/jenkins2,mrooney/jenkins,escoem/jenkins,hplatou/jenkins,viqueen/jenkins,brunocvcunha/jenkins,lindzh/jenkins,rsandell/jenkins,iqstack/jenkins,mattclark/jenkins,huybrechts/hudson,recena/jenkins,singh88/jenkins,lilyJi/jenkins,hudson/hudson-2.x,abayer/jenkins,FTG-003/jenkins,dennisjlee/jenkins,khmarbaise/jenkins,MarkEWaite/jenkins,gorcz/jenkins,lordofthejars/jenkins,scoheb/jenkins,hudson/hudson-2.x,dennisjlee/jenkins,mdonohue/jenkins,vvv444/jenkins,6WIND/jenkins,jcarrothers-sap/jenkins,Jochen-A-Fuerbacher/jenkins,gitaccountforprashant/gittest,292388900/jenkins,chbiel/jenkins,maikeffi/hudson,kohsuke/hudson,mdonohue/jenkins,amruthsoft9/Jenkis,lvotypko/jenkins2,aheritier/jenkins,aduprat/jenkins,intelchen/jenkins,ErikVerheul/jenkins,arunsingh/jenkins,amruthsoft9/Jenkis,gusreiber/jenkins,jk47/jenkins,jhoblitt/jenkins,deadmoose/jenkins,Krasnyanskiy/jenkins,luoqii/jenkins,chbiel/jenkins,luoqii/jenkins,guoxu0514/jenkins,dbroady1/jenkins,rashmikanta-1984/jenkins,vijayto/jenkins,synopsys-arc-oss/jenkins,jtnord/jenkins,batmat/jenkins,deadmoose/jenkins,jzjzjzj/jenkins,godfath3r/jenkins,mattclark/jenkins,iterate/coding-dojo,varmenise/jenkins,pjanouse/jenkins,6WIND/jenkins,paulmillar/jenkins,luoqii/jenkins,samatdav/jenkins,Jochen-A-Fuerbacher/jenkins,ns163/jenkins,mpeltonen/jenkins,wuwen5/jenkins,viqueen/jenkins,v1v/jenkins,brunocvcunha/jenkins,Ykus/jenkins,DanielWeber/jenkins,stefanbrausch/hudson-main,recena/jenkins,lindzh/jenkins,intelchen/jenkins,andresrc/jenkins,arcivanov/jenkins,ikedam/jenkins,rsandell/jenkins,Jochen-A-Fuerbacher/jenkins,Jimilian/jenkins,vlajos/jenkins,thomassuckow/jenkins,jzjzjzj/jenkins,my7seven/jenkins,iterate/coding-dojo,intelchen/jenkins,intelchen/jenkins,aldaris/jenkins,lvotypko/jenkins,ydubreuil/jenkins,DanielWeber/jenkins,alvarolobato/jenkins,bpzhang/jenkins,MadsNielsen/jtemp,MadsNielsen/jtemp,escoem/jenkins,daniel-beck/jenkins,github-api-test-org/jenkins,amruthsoft9/Jenkis,maikeffi/hudson,batmat/jenkins,vvv444/jenkins,duzifang/my-jenkins,aquarellian/jenkins,Jochen-A-Fuerbacher/jenkins,everyonce/jenkins,ndeloof/jenkins,wangyikai/jenkins,tfennelly/jenkins,tangkun75/jenkins,damianszczepanik/jenkins,mrobinet/jenkins,AustinKwang/jenkins,mrooney/jenkins,iqstack/jenkins,Jimilian/jenkins,AustinKwang/jenkins,DanielWeber/jenkins,deadmoose/jenkins,paulwellnerbou/jenkins,godfath3r/jenkins,github-api-test-org/jenkins,batmat/jenkins,liorhson/jenkins,KostyaSha/jenkins,varmenise/jenkins,Ykus/jenkins,ErikVerheul/jenkins,everyonce/jenkins,KostyaSha/jenkins,gorcz/jenkins,hudson/hudson-2.x,keyurpatankar/hudson,iterate/coding-dojo,elkingtonmcb/jenkins,v1v/jenkins,tfennelly/jenkins,FarmGeek4Life/jenkins,h4ck3rm1k3/jenkins,dennisjlee/jenkins,aduprat/jenkins,yonglehou/jenkins,Jochen-A-Fuerbacher/jenkins,jhoblitt/jenkins,hemantojhaa/jenkins,jenkinsci/jenkins,aheritier/jenkins,scoheb/jenkins,albers/jenkins,ajshastri/jenkins,andresrc/jenkins,mrobinet/jenkins,svanoort/jenkins,my7seven/jenkins,verbitan/jenkins,synopsys-arc-oss/jenkins,rlugojr/jenkins,guoxu0514/jenkins,ChrisA89/jenkins,NehemiahMi/jenkins,ChrisA89/jenkins,Wilfred/jenkins,shahharsh/jenkins,amruthsoft9/Jenkis,hashar/jenkins,SebastienGllmt/jenkins,patbos/jenkins,ChrisA89/jenkins,MarkEWaite/jenkins,msrb/jenkins,lindzh/jenkins,lordofthejars/jenkins,pselle/jenkins,vivek/hudson,lindzh/jenkins,aheritier/jenkins,azweb76/jenkins,MichaelPranovich/jenkins_sc,azweb76/jenkins,rashmikanta-1984/jenkins,ErikVerheul/jenkins,bpzhang/jenkins,damianszczepanik/jenkins,escoem/jenkins,soenter/jenkins,gitaccountforprashant/gittest,rsandell/jenkins,ns163/jenkins,azweb76/jenkins,gorcz/jenkins,paulwellnerbou/jenkins,FarmGeek4Life/jenkins,1and1/jenkins,amuniz/jenkins,hplatou/jenkins,stefanbrausch/hudson-main,iterate/coding-dojo,hemantojhaa/jenkins,evernat/jenkins,arcivanov/jenkins,vivek/hudson,SenolOzer/jenkins,singh88/jenkins,alvarolobato/jenkins,wangyikai/jenkins,Wilfred/jenkins,abayer/jenkins,hudson/hudson-2.x,thomassuckow/jenkins,lvotypko/jenkins,khmarbaise/jenkins,liupugong/jenkins,gitaccountforprashant/gittest,evernat/jenkins,Wilfred/jenkins,singh88/jenkins,MarkEWaite/jenkins,CodeShane/jenkins,singh88/jenkins,lvotypko/jenkins3,nandan4/Jenkins,goldchang/jenkins,lvotypko/jenkins3,jpbriend/jenkins,Krasnyanskiy/jenkins,everyonce/jenkins,goldchang/jenkins,292388900/jenkins,stefanbrausch/hudson-main,mattclark/jenkins,lindzh/jenkins,azweb76/jenkins,Vlatombe/jenkins,MadsNielsen/jtemp,rlugojr/jenkins,maikeffi/hudson,amuniz/jenkins,v1v/jenkins,DoctorQ/jenkins,aduprat/jenkins,jpederzolli/jenkins-1,lvotypko/jenkins3,soenter/jenkins,dbroady1/jenkins,iqstack/jenkins,intelchen/jenkins,aheritier/jenkins,andresrc/jenkins,godfath3r/jenkins,mcanthony/jenkins,liupugong/jenkins,brunocvcunha/jenkins,bkmeneguello/jenkins,ikedam/jenkins,keyurpatankar/hudson,jenkinsci/jenkins,my7seven/jenkins,tastatur/jenkins,damianszczepanik/jenkins,elkingtonmcb/jenkins,lvotypko/jenkins3,seanlin816/jenkins,petermarcoen/jenkins,vijayto/jenkins,lvotypko/jenkins,kohsuke/hudson,1and1/jenkins,my7seven/jenkins,MichaelPranovich/jenkins_sc,292388900/jenkins,paulmillar/jenkins,aheritier/jenkins,SebastienGllmt/jenkins,thomassuckow/jenkins,paulwellnerbou/jenkins,akshayabd/jenkins,bkmeneguello/jenkins,dbroady1/jenkins,mdonohue/jenkins,vvv444/jenkins,lvotypko/jenkins2,seanlin816/jenkins,jpbriend/jenkins,ChrisA89/jenkins,akshayabd/jenkins,ydubreuil/jenkins,liorhson/jenkins,kzantow/jenkins,petermarcoen/jenkins,tangkun75/jenkins,aheritier/jenkins,mdonohue/jenkins,duzifang/my-jenkins,nandan4/Jenkins,protazy/jenkins,samatdav/jenkins,jpbriend/jenkins,gusreiber/jenkins,mpeltonen/jenkins,DoctorQ/jenkins,MarkEWaite/jenkins,deadmoose/jenkins,petermarcoen/jenkins,iterate/coding-dojo,dariver/jenkins,christ66/jenkins,jcarrothers-sap/jenkins,hudson/hudson-2.x,kohsuke/hudson,DanielWeber/jenkins,mrooney/jenkins,intelchen/jenkins,rlugojr/jenkins,iqstack/jenkins,SebastienGllmt/jenkins,olivergondza/jenkins,dbroady1/jenkins,hemantojhaa/jenkins,FarmGeek4Life/jenkins,protazy/jenkins,gorcz/jenkins,singh88/jenkins,DanielWeber/jenkins,liorhson/jenkins,mcanthony/jenkins,SebastienGllmt/jenkins,brunocvcunha/jenkins,ydubreuil/jenkins,csimons/jenkins,scoheb/jenkins,jcsirot/jenkins,lilyJi/jenkins,jcarrothers-sap/jenkins,batmat/jenkins,fbelzunc/jenkins,hashar/jenkins,v1v/jenkins,lilyJi/jenkins,DoctorQ/jenkins,iqstack/jenkins,khmarbaise/jenkins,abayer/jenkins,everyonce/jenkins,Vlatombe/jenkins,vivek/hudson,gitaccountforprashant/gittest,chbiel/jenkins,christ66/jenkins,msrb/jenkins,damianszczepanik/jenkins,yonglehou/jenkins,vivek/hudson,dariver/jenkins,lilyJi/jenkins,batmat/jenkins,deadmoose/jenkins,mrobinet/jenkins,AustinKwang/jenkins,mcanthony/jenkins,everyonce/jenkins,scoheb/jenkins,singh88/jenkins,arunsingh/jenkins,soenter/jenkins,elkingtonmcb/jenkins,escoem/jenkins,morficus/jenkins,jcarrothers-sap/jenkins,1and1/jenkins,damianszczepanik/jenkins,abayer/jenkins,keyurpatankar/hudson,jk47/jenkins,nandan4/Jenkins,FTG-003/jenkins,arcivanov/jenkins,jcarrothers-sap/jenkins,jpederzolli/jenkins-1,christ66/jenkins,dbroady1/jenkins,sathiya-mit/jenkins,my7seven/jenkins,tastatur/jenkins,pselle/jenkins,jenkinsci/jenkins,tastatur/jenkins,lordofthejars/jenkins,thomassuckow/jenkins,synopsys-arc-oss/jenkins,akshayabd/jenkins,gusreiber/jenkins,rsandell/jenkins,kohsuke/hudson,gorcz/jenkins,ErikVerheul/jenkins,rashmikanta-1984/jenkins,hemantojhaa/jenkins,chbiel/jenkins,keyurpatankar/hudson,MarkEWaite/jenkins,lvotypko/jenkins,shahharsh/jenkins,daniel-beck/jenkins,aquarellian/jenkins,morficus/jenkins,svanoort/jenkins,KostyaSha/jenkins,mrobinet/jenkins,goldchang/jenkins,viqueen/jenkins,jzjzjzj/jenkins,noikiy/jenkins,evernat/jenkins,stephenc/jenkins,viqueen/jenkins"},"new_contents":{"kind":"string","value":"package hudson.model;\n\nimport com.thoughtworks.xstream.XStream;\nimport hudson.CloseProofOutputStream;\nimport hudson.EnvVars;\nimport hudson.ExtensionPoint;\nimport hudson.FeedAdapter;\nimport hudson.FilePath;\nimport hudson.Util;\nimport static hudson.Util.combine;\nimport hudson.XmlFile;\nimport hudson.AbortException;\nimport hudson.BulkChange;\nimport hudson.matrix.MatrixBuild;\nimport hudson.matrix.MatrixRun;\nimport hudson.model.listeners.RunListener;\nimport hudson.search.SearchIndexBuilder;\nimport hudson.security.ACL;\nimport hudson.security.AccessControlled;\nimport hudson.security.Permission;\nimport hudson.security.PermissionGroup;\nimport hudson.tasks.BuildStep;\nimport hudson.tasks.BuildWrapper;\nimport hudson.tasks.LogRotator;\nimport hudson.tasks.Mailer;\nimport hudson.tasks.test.AbstractTestResultAction;\nimport hudson.util.IOException2;\nimport hudson.util.XStream2;\nimport org.kohsuke.stapler.QueryParameter;\nimport org.kohsuke.stapler.StaplerRequest;\nimport org.kohsuke.stapler.StaplerResponse;\nimport org.kohsuke.stapler.export.Exported;\nimport org.kohsuke.stapler.export.ExportedBean;\nimport org.kohsuke.stapler.framework.io.LargeText;\n\nimport javax.servlet.ServletException;\nimport javax.servlet.http.HttpServletResponse;\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.PrintStream;\nimport java.io.PrintWriter;\nimport java.io.Writer;\nimport java.io.InputStreamReader;\nimport java.io.FileInputStream;\nimport java.text.DateFormat;\nimport java.text.ParseException;\nimport java.text.SimpleDateFormat;\nimport java.util.ArrayList;\nimport java.util.Calendar;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.Date;\nimport java.util.GregorianCalendar;\nimport java.util.HashMap;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.Map;\nimport java.util.TreeMap;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\nimport java.nio.charset.Charset;\n\n/**\n * A particular execution of {@link Job}.\n *\n *

\n * Custom {@link Run} type is always used in conjunction with\n * a custom {@link Job} type, so there's no separate registration\n * mechanism for custom {@link Run} types.\n *\n * @author Kohsuke Kawaguchi\n * @see RunListener\n */\n@ExportedBean\npublic abstract class Run ,RunT extends Run>\n extends Actionable implements ExtensionPoint, Comparable, AccessControlled, PersistenceRoot {\n\n protected transient final JobT project;\n\n /**\n * Build number.\n *\n *

\n * In earlier versions &lt; 1.24, this number is not unique nor continuous,\n * but going forward, it will, and this really replaces the build id.\n */\n public /*final*/ int number;\n\n /**\n * Previous build. Can be null.\n * These two fields are maintained and updated by {@link RunMap}.\n */\n protected volatile transient RunT previousBuild;\n /**\n * Next build. Can be null.\n */\n protected volatile transient RunT nextBuild;\n\n /**\n * When the build is scheduled.\n */\n protected transient final long timestamp;\n\n /**\n * The build result.\n * This value may change while the state is in {@link State#BUILDING}.\n */\n protected volatile Result result;\n\n /**\n * Human-readable description. Can be null.\n */\n protected volatile String description;\n\n /**\n * The current build state.\n */\n protected volatile transient State state;\n\n private static enum State {\n /**\n * Build is created/queued but we haven't started building it.\n */\n NOT_STARTED,\n /**\n * Build is in progress.\n */\n BUILDING,\n /**\n * Build is completed now, and the status is determined,\n * but log files are still being updated.\n */\n POST_PRODUCTION,\n /**\n * Build is completed now, and log file is closed.\n */\n COMPLETED\n }\n\n /**\n * Number of milli-seconds it took to run this build.\n */\n protected long duration;\n\n /**\n * Charset in which the log file is written.\n * For compatibility reason, this field may be null.\n * For persistence, this field is string and not {@link Charset}.\n *\n * @see #getCharset()\n * @since 1.257\n */\n private String charset;\n\n /**\n * Keeps this log entries.\n */\n private boolean keepLog;\n\n protected static final ThreadLocal ID_FORMATTER =\n new ThreadLocal() {\n @Override\n protected SimpleDateFormat initialValue() {\n return new SimpleDateFormat(\"yyyy-MM-dd_HH-mm-ss\");\n }\n };\n\n /**\n * Creates a new {@link Run}.\n */\n protected Run(JobT job) throws IOException {\n this(job, new GregorianCalendar());\n this.number = project.assignBuildNumber();\n }\n\n /**\n * Constructor for creating a {@link Run} object in\n * an arbitrary state.\n */\n protected Run(JobT job, Calendar timestamp) {\n this(job,timestamp.getTimeInMillis());\n }\n\n protected Run(JobT job, long timestamp) {\n this.project = job;\n this.timestamp = timestamp;\n this.state = State.NOT_STARTED;\n }\n\n /**\n * Loads a run from a log file.\n */\n protected Run(JobT project, File buildDir) throws IOException {\n this(project, parseTimestampFromBuildDir(buildDir));\n this.state = State.COMPLETED;\n this.result = Result.FAILURE; // defensive measure. value should be overwritten by unmarshal, but just in case the saved data is inconsistent\n getDataFile().unmarshal(this); // load the rest of the data\n }\n\n /*package*/ static long parseTimestampFromBuildDir(File buildDir) throws IOException {\n try {\n return ID_FORMATTER.get().parse(buildDir.getName()).getTime();\n } catch (ParseException e) {\n throw new IOException2(\"Invalid directory name \"+buildDir,e);\n } catch (NumberFormatException e) {\n throw new IOException2(\"Invalid directory name \"+buildDir,e);\n }\n }\n\n /**\n * Ordering based on build numbers.\n */\n public int compareTo(RunT that) {\n return this.number - that.number;\n }\n\n /**\n * Returns the build result.\n *\n *

\n * When a build is {@link #isBuilding() in progress}, this method\n * may return null or a temporary intermediate result.\n */\n @Exported\n public Result getResult() {\n return result;\n }\n\n public void setResult(Result r) {\n // state can change only when we are building\n assert state==State.BUILDING;\n\n StackTraceElement caller = findCaller(Thread.currentThread().getStackTrace(),\"setResult\");\n\n\n // result can only get worse\n if(result==null) {\n result = r;\n LOGGER.fine(toString()+\" : result is set to \"+r+\" by \"+caller);\n } else {\n if(r.isWorseThan(result)) {\n LOGGER.fine(toString()+\" : result is set to \"+r+\" by \"+caller);\n result = r;\n }\n }\n }\n\n /**\n * Gets the subset of {@link #getActions()} that consists of {@link BuildBadgeAction}s.\n */\n public List getBadgeActions() {\n List r = null;\n for (Action a : getActions()) {\n if(a instanceof BuildBadgeAction) {\n if(r==null)\n r = new ArrayList();\n r.add((BuildBadgeAction)a);\n }\n }\n if(isKeepLog()) {\n if(r==null)\n r = new ArrayList();\n r.add(new KeepLogBuildBadge());\n }\n if(r==null) return Collections.emptyList();\n else return r;\n }\n\n private StackTraceElement findCaller(StackTraceElement[] stackTrace, String callee) {\n for(int i=0; iNEVER be used during HTML page rendering, as it won't work with\n * network set up like Apache reverse proxy.\n * This method is only intended for the remote API clients who cannot resolve relative references\n * (even this won't work for the same reason, which should be fixed.)\n */\n @Exported(visibility=2,name=\"url\")\n public final String getAbsoluteUrl() {\n return project.getAbsoluteUrl()+getNumber()+'/';\n }\n\n public final String getSearchUrl() {\n return getNumber()+\"/\";\n }\n\n /**\n * Unique ID of this build.\n */\n public String getId() {\n return ID_FORMATTER.get().format(new Date(timestamp));\n }\n\n /**\n * Root directory of this {@link Run} on the master.\n *\n * Files related to this {@link Run} should be stored below this directory.\n */\n public File getRootDir() {\n File f = new File(project.getBuildDir(),getId());\n f.mkdirs();\n return f;\n }\n\n /**\n * Gets the directory where the artifacts are archived.\n */\n public File getArtifactsDir() {\n return new File(getRootDir(),\"archive\");\n }\n\n /**\n * Gets the first {@value #CUTOFF} artifacts (relative to {@link #getArtifactsDir()}.\n */\n @Exported\n public List getArtifacts() {\n ArtifactList r = new ArtifactList();\n addArtifacts(getArtifactsDir(),\"\",r);\n r.computeDisplayName();\n return r;\n }\n\n /**\n * Returns true if this run has any artifacts.\n *\n *

\n * The strange method name is so that we can access it from EL.\n */\n public boolean getHasArtifacts() {\n return !getArtifacts().isEmpty();\n }\n\n private void addArtifacts( File dir, String path, List r ) {\n String[] children = dir.list();\n if(children==null) return;\n for (String child : children) {\n if(r.size()>CUTOFF)\n return;\n File sub = new File(dir, child);\n if (sub.isDirectory()) {\n addArtifacts(sub, path + child + '/', r);\n } else {\n r.add(new Artifact(path + child));\n }\n }\n }\n\n private static final int CUTOFF = 17; // 0, 1,... 16, and then \"too many\"\n\n public final class ArtifactList extends ArrayList {\n public void computeDisplayName() {\n if(size()>CUTOFF) return; // we are not going to display file names, so no point in computing this\n\n int maxDepth = 0;\n int[] len = new int[size()];\n String[][] tokens = new String[size()][];\n for( int i=0; i names = new HashMap();\n for (int i = 0; i < tokens.length; i++) {\n String[] token = tokens[i];\n String displayName = combineLast(token,len[i]);\n Integer j = names.put(displayName, i);\n if(j!=null) {\n collision = true;\n if(j>=0)\n len[j]++;\n len[i]++;\n names.put(displayName,-1); // occupy this name but don't let len[i] incremented with additional collisions\n }\n }\n } while(collision && depth++ names = new HashSet();\n// for (String[] token : tokens) {\n// if(!names.add(combineLast(token,n)))\n// continue OUTER; // collision. Increase n and try again\n// }\n//\n// // this n successfully diambiguates\n// for (int i = 0; i < tokens.length; i++) {\n// String[] token = tokens[i];\n// get(i).displayPath = combineLast(token,n);\n// }\n// return;\n// }\n\n// // it's impossible to get here, as that means\n// // we have the same artifacts archived twice, but be defensive\n// for (Artifact a : this)\n// a.displayPath = a.relativePath;\n }\n\n /**\n * Combines last N token into the \"a/b/c\" form.\n */\n private String combineLast(String[] token, int n) {\n StringBuffer buf = new StringBuffer();\n for( int i=Math.max(0,token.length-n); i0) buf.append('/');\n buf.append(token[i]);\n }\n return buf.toString();\n }\n }\n\n /**\n * A build artifact.\n */\n @ExportedBean\n public class Artifact {\n /**\n * Relative path name from {@link Run#getArtifactsDir()}\n */\n \t@Exported(visibility=3)\n public final String relativePath;\n\n /**\n * Truncated form of {@link #relativePath} just enough\n * to disambiguate {@link Artifact}s.\n */\n /*package*/ String displayPath;\n\n /*package for test*/ Artifact(String relativePath) {\n this.relativePath = relativePath;\n }\n\n /**\n * Gets the artifact file.\n */\n public File getFile() {\n return new File(getArtifactsDir(),relativePath);\n }\n\n /**\n * Returns just the file name portion, without the path.\n */\n \t@Exported(visibility=3)\n public String getFileName() {\n return getFile().getName();\n }\n\n \t@Exported(visibility=3)\n public String getDisplayPath() {\n return displayPath;\n }\n\n public String toString() {\n return relativePath;\n }\n }\n\n /**\n * Returns the log file.\n */\n public File getLogFile() {\n return new File(getRootDir(),\"log\");\n }\n\n protected SearchIndexBuilder makeSearchIndex() {\n SearchIndexBuilder builder = super.makeSearchIndex()\n .add(\"console\")\n .add(\"changes\");\n for (Action a : getActions()) {\n if(a.getIconFileName()!=null)\n builder.add(a.getUrlName());\n }\n return builder;\n }\n\n public Api getApi(final StaplerRequest req) {\n return new Api(this);\n }\n\n public void checkPermission(Permission p) {\n getACL().checkPermission(p);\n }\n\n public boolean hasPermission(Permission p) {\n return getACL().hasPermission(p);\n }\n\n public ACL getACL() {\n // for now, don't maintain ACL per run, and do it at project level\n return getParent().getACL();\n }\n\n /**\n * Deletes this build and its entire log\n *\n * @throws IOException\n * if we fail to delete.\n */\n public synchronized void delete() throws IOException {\n File rootDir = getRootDir();\n File tmp = new File(rootDir.getParentFile(),'.'+rootDir.getName());\n \n boolean renamingSucceeded = rootDir.renameTo(tmp);\n Util.deleteRecursive(tmp);\n\n if(!renamingSucceeded)\n throw new IOException(rootDir+\" is in use\");\n\n removeRunFromParent();\n }\n @SuppressWarnings(\"unchecked\") // seems this is too clever for Java's type system?\n private void removeRunFromParent() {\n getParent().removeRun((RunT)this);\n }\n\n protected static interface Runner {\n /**\n * Performs the main build and returns the status code.\n *\n * @throws Exception\n * exception will be recorded and the build will be considered a failure.\n */\n Result run( BuildListener listener ) throws Exception, RunnerAbortedException;\n\n /**\n * Performs the post-build action.\n *

\n * This method is called after the status of the build is determined.\n * This is a good opportunity to do notifications based on the result\n * of the build. When this method is called, the build is not really\n * finalized yet, and the build is still considered in progress --- for example,\n * even if the build is successful, this build still won't be picked up\n * by {@link Job#getLastSuccessfulBuild()}.\n */\n void post( BuildListener listener ) throws Exception;\n\n /**\n * Performs final clean up action.\n *

\n * This method is called after {@link #post(BuildListener)},\n * after the build result is fully finalized. This is the point\n * where the build is already considered completed.\n *

\n * Among other things, this is often a necessary pre-condition\n * before invoking other builds that depend on this build.\n */\n void cleanUp(BuildListener listener) throws Exception;\n }\n\n /**\n * Used in {@link Runner#run} to indicates that a fatal error in a build\n * is reported to {@link BuildListener} and the build should be simply aborted\n * without further recording a stack trace.\n */\n public static final class RunnerAbortedException extends RuntimeException {}\n\n protected final void run(Runner job) {\n if(result!=null)\n return; // already built.\n\n BuildListener listener=null;\n PrintStream log = null;\n\n onStartBuilding();\n try {\n // to set the state to COMPLETE in the end, even if the thread dies abnormally.\n // otherwise the queue state becomes inconsistent\n\n long start = System.currentTimeMillis();\n\n try {\n try {\n log = new PrintStream(new FileOutputStream(getLogFile()));\n Charset charset = Computer.currentComputer().getDefaultCharset();\n this.charset = charset.name();\n listener = new StreamBuildListener(new PrintStream(new CloseProofOutputStream(log)),charset);\n\n listener.started();\n\n RunListener.fireStarted(this,listener);\n\n setResult(job.run(listener));\n\n LOGGER.info(toString()+\" main build action completed: \"+result);\n } catch (ThreadDeath t) {\n throw t;\n } catch( AbortException e ) {\n result = Result.FAILURE;\n } catch( RunnerAbortedException e ) {\n result = Result.FAILURE;\n } catch( InterruptedException e) {\n // aborted\n result = Result.ABORTED;\n listener.getLogger().println(Messages.Run_BuildAborted());\n LOGGER.log(Level.INFO,toString()+\" aborted\",e);\n } catch( Throwable e ) {\n handleFatalBuildProblem(listener,e);\n result = Result.FAILURE;\n }\n\n // even if the main build fails fatally, try to run post build processing\n job.post(listener);\n\n } catch (ThreadDeath t) {\n throw t;\n } catch( Throwable e ) {\n handleFatalBuildProblem(listener,e);\n result = Result.FAILURE;\n } finally {\n long end = System.currentTimeMillis();\n duration = end-start;\n\n // advance the state.\n // the significance of doing this is that Hudson\n // will now see this build as completed.\n // things like triggering other builds requires this as pre-condition.\n // see issue #980.\n state = State.POST_PRODUCTION;\n\n try {\n job.cleanUp(listener);\n } catch (Exception e) {\n handleFatalBuildProblem(listener,e);\n // too late to update the result now\n }\n\n RunListener.fireCompleted(this,listener);\n\n if(listener!=null)\n listener.finished(result);\n if(log!=null)\n log.close();\n\n try {\n save();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n try {\n getParent().logRotate();\n } catch (IOException e) {\n e.printStackTrace();\n }\n } finally {\n onEndBuilding();\n }\n }\n\n /**\n * Handles a fatal build problem (exception) that occurred during the build.\n */\n private void handleFatalBuildProblem(BuildListener listener, Throwable e) {\n if(listener!=null) {\n if(e instanceof IOException)\n Util.displayIOException((IOException)e,listener);\n\n Writer w = listener.fatalError(e.getMessage());\n if(w!=null) {\n try {\n e.printStackTrace(new PrintWriter(w));\n w.close();\n } catch (IOException e1) {\n // ignore\n }\n }\n }\n }\n\n /**\n * Called when a job started building.\n */\n protected void onStartBuilding() {\n state = State.BUILDING;\n }\n\n /**\n * Called when a job finished building normally or abnormally.\n */\n protected void onEndBuilding() {\n state = State.COMPLETED;\n if(result==null) {\n // shouldn't happen, but be defensive until we figure out why\n result = Result.FAILURE;\n LOGGER.warning(toString()+\": No build result is set, so marking as failure. This shouldn't happen\");\n }\n RunListener.fireFinalized(this);\n }\n\n /**\n * Save the settings to a file.\n */\n public synchronized void save() throws IOException {\n if(BulkChange.contains(this)) return;\n getDataFile().write(this);\n }\n\n private XmlFile getDataFile() {\n return new XmlFile(XSTREAM,new File(getRootDir(),\"build.xml\"));\n }\n\n /**\n * Gets the log of the build as a string.\n *\n * @deprecated Use {@link #getLog(int)} instead as it avoids loading\n * the whole log into memory unnecessarily.\n */\n @Deprecated\n public String getLog() throws IOException {\n return Util.loadFile(getLogFile(),getCharset());\n }\n\n /**\n * Gets the log of the build as a list of strings (one per log line).\n * The number of lines returned is constrained by the maxLines parameter.\n *\n * @param maxLines The maximum number of log lines to return. If the log\n * is bigger than this, only the most recent lines are returned.\n * @return A list of log lines. Will have no more than maxLines elements.\n * @throws IOException If there is a problem reading the log file.\n */\n public List getLog(int maxLines) throws IOException {\n int lineCount = 0;\n List logLines = new LinkedList();\n BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(getLogFile()),getCharset()));\n try {\n for (String line = reader.readLine(); line != null; line = reader.readLine()) {\n logLines.add(line);\n ++lineCount;\n // If we have too many lines, remove the oldest line. This way we\n // never have to hold the full contents of a huge log file in memory.\n // Adding to and removing from the ends of a linked list are cheap\n // operations.\n if (lineCount > maxLines)\n logLines.remove(0);\n }\n } finally {\n reader.close();\n }\n\n // If the log has been truncated, include that information.\n // Use set (replaces the first element) rather than add so that\n // the list doesn't grow beyond the specified maximum number of lines.\n if (lineCount > maxLines)\n logLines.set(0, \"[...truncated \" + (lineCount - (maxLines - 1)) + \" lines...]\");\n\n return logLines;\n }\n\n public void doBuildStatus( StaplerRequest req, StaplerResponse rsp ) throws IOException {\n // see Hudson.doNocacheImages. this is a work around for a bug in Firefox\n rsp.sendRedirect2(req.getContextPath()+\"/nocacheImages/48x48/\"+getBuildStatusUrl());\n }\n\n public String getBuildStatusUrl() {\n return getIconColor().getImage();\n }\n\n public static class Summary {\n /**\n * Is this build worse or better, compared to the previous build?\n */\n public boolean isWorse;\n public String message;\n\n public Summary(boolean worse, String message) {\n this.isWorse = worse;\n this.message = message;\n }\n }\n\n /**\n * Gets an object that computes the single line summary of this build.\n */\n public Summary getBuildStatusSummary() {\n Run prev = getPreviousBuild();\n\n if(getResult()==Result.SUCCESS) {\n if(prev==null || prev.getResult()== Result.SUCCESS)\n return new Summary(false,\"stable\");\n else\n return new Summary(false,\"back to normal\");\n }\n\n if(getResult()==Result.FAILURE) {\n RunT since = getPreviousNotFailedBuild();\n if(since==null)\n return new Summary(false,\"broken for a long time\");\n if(since==prev)\n return new Summary(true,\"broken since this build\");\n return new Summary(false,\"broken since \"+since.getDisplayName());\n }\n\n if(getResult()==Result.ABORTED)\n return new Summary(false,\"aborted\");\n\n if(getResult()==Result.UNSTABLE) {\n if(((Run)this) instanceof Build) {\n AbstractTestResultAction trN = ((Build)(Run)this).getTestResultAction();\n AbstractTestResultAction trP = prev==null ? null : ((Build) prev).getTestResultAction();\n if(trP==null) {\n if(trN!=null && trN.getFailCount()>0)\n return new Summary(false,combine(trN.getFailCount(),\"test failure\"));\n else // ???\n return new Summary(false,\"unstable\");\n }\n if(trP.getFailCount()==0)\n return new Summary(true,combine(trN.getFailCount(),\"test\")+\" started to fail\");\n if(trP.getFailCount() < trN.getFailCount())\n return new Summary(true,combine(trN.getFailCount()-trP.getFailCount(),\"more test\")\n +\" are failing (\"+trN.getFailCount()+\" total)\");\n if(trP.getFailCount() > trN.getFailCount())\n return new Summary(false,combine(trP.getFailCount()-trN.getFailCount(),\"less test\")\n +\" are failing (\"+trN.getFailCount()+\" total)\");\n\n return new Summary(false,combine(trN.getFailCount(),\"test\")+\" are still failing\");\n }\n }\n\n return new Summary(false,\"?\");\n }\n\n /**\n * Serves the artifacts.\n */\n public void doArtifact( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, InterruptedException {\n new DirectoryBrowserSupport(this,project.getDisplayName()+' '+getDisplayName())\n .serveFile(req, rsp, new FilePath(getArtifactsDir()), \"package.gif\", true);\n }\n\n /**\n * Returns the build number in the body.\n */\n public void doBuildNumber( StaplerRequest req, StaplerResponse rsp ) throws IOException {\n rsp.setContentType(\"text/plain\");\n rsp.setCharacterEncoding(\"US-ASCII\");\n rsp.setStatus(HttpServletResponse.SC_OK);\n rsp.getWriter().print(number);\n }\n\n /**\n * Returns the build time stamp in the body.\n */\n public void doBuildTimestamp( StaplerRequest req, StaplerResponse rsp, @QueryParameter String format) throws IOException {\n rsp.setContentType(\"text/plain\");\n rsp.setCharacterEncoding(\"US-ASCII\");\n rsp.setStatus(HttpServletResponse.SC_OK);\n DateFormat df = format==null ?\n DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.SHORT, Locale.ENGLISH) :\n new SimpleDateFormat(format,req.getLocale());\n rsp.getWriter().print(df.format(getTimestamp().getTime()));\n }\n\n /**\n * Handles incremental log output.\n */\n public void doProgressiveLog( StaplerRequest req, StaplerResponse rsp) throws IOException {\n new LargeText(getLogFile(),getCharset(),!isLogUpdated()).doProgressText(req,rsp);\n }\n\n public void doToggleLogKeep( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {\n checkPermission(UPDATE);\n\n keepLog(!keepLog);\n rsp.forwardToPreviousPage(req);\n }\n\n /**\n * Marks this build to keep the log.\n */\n public final void keepLog() throws IOException {\n keepLog(true);\n }\n\n public void keepLog(boolean newValue) throws IOException {\n keepLog = newValue;\n save();\n }\n\n /**\n * Deletes the build when the button is pressed.\n */\n public void doDoDelete( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {\n checkPermission(DELETE);\n\n // We should not simply delete the build if it has been explicitly\n // marked to be preserved, or if the build should not be deleted\n // due to dependencies!\n String why = getWhyKeepLog();\n if (why!=null) {\n sendError(Messages.Run_UnableToDelete(toString(),why),req,rsp);\n return;\n }\n\n delete();\n rsp.sendRedirect2(req.getContextPath()+'/' + getParent().getUrl());\n }\n\n public void setDescription(String description) throws IOException {\n checkPermission(UPDATE);\n this.description = description;\n save();\n }\n \n /**\n * Accepts the new description.\n */\n public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {\n req.setCharacterEncoding(\"UTF-8\");\n setDescription(req.getParameter(\"description\"));\n rsp.sendRedirect(\".\"); // go to the top page\n }\n\n /**\n * Returns the map that contains environmental variable overrides for this build.\n *\n *

\n * {@link BuildStep}s that invoke external processes should use this.\n * This allows {@link BuildWrapper}s and other project configurations (such as JDK selection)\n * to take effect.\n *\n *

\n * On Windows systems, environment variables are case-preserving but\n * comparison/query is case insensitive (IOW, you can set 'Path' to something\n * and you get the same value by doing '%PATH%'.) So to implement this semantics\n * the map returned from here is a {@link TreeMap} with a special comparator.\n *\n */\n public Map getEnvVars() {\n EnvVars env = new EnvVars();\n env.put(\"BUILD_NUMBER\",String.valueOf(number));\n env.put(\"BUILD_ID\",getId());\n env.put(\"BUILD_TAG\",\"hudson-\"+getParent().getName()+\"-\"+number);\n env.put(\"JOB_NAME\",getParent().getFullName());\n String rootUrl = Hudson.getInstance().getRootUrl();\n if(rootUrl!=null)\n env.put(\"HUDSON_URL\", rootUrl);\n\n Thread t = Thread.currentThread();\n if (t instanceof Executor) {\n Executor e = (Executor) t;\n env.put(\"EXECUTOR_NUMBER\",String.valueOf(e.getNumber()));\n }\n\n return env;\n }\n\n public static final XStream XSTREAM = new XStream2();\n static {\n XSTREAM.alias(\"build\",FreeStyleBuild.class);\n XSTREAM.alias(\"matrix-build\",MatrixBuild.class);\n XSTREAM.alias(\"matrix-run\",MatrixRun.class);\n XSTREAM.registerConverter(Result.conv);\n }\n\n private static final Logger LOGGER = Logger.getLogger(Run.class.getName());\n\n /**\n * Sort by date. Newer ones first. \n */\n public static final Comparator ORDER_BY_DATE = new Comparator() {\n public int compare(Run lhs, Run rhs) {\n long lt = lhs.getTimestamp().getTimeInMillis();\n long rt = rhs.getTimestamp().getTimeInMillis();\n if(lt>rt) return -1;\n if(lt FEED_ADAPTER = new DefaultFeedAdapter();\n\n /**\n * {@link FeedAdapter} to produce feeds to show one build per project.\n */\n public static final FeedAdapter FEED_ADAPTER_LATEST = new DefaultFeedAdapter() {\n /**\n * The entry unique ID needs to be tied to a project, so that\n * new builds will replace the old result.\n */\n public String getEntryID(Run e) {\n // can't use a meaningful year field unless we remember when the job was created.\n return \"tag:hudson.dev.java.net,2008:\"+e.getParent().getAbsoluteUrl();\n }\n };\n\n /**\n * {@link BuildBadgeAction} that shows the logs are being kept.\n */\n public final class KeepLogBuildBadge implements BuildBadgeAction {\n public String getIconFileName() { return null; }\n public String getDisplayName() { return null; }\n public String getUrlName() { return null; }\n public String getWhyKeepLog() { return Run.this.getWhyKeepLog(); }\n }\n\n public static final PermissionGroup PERMISSIONS = new PermissionGroup(Run.class,Messages._Run_Permissions_Title());\n public static final Permission DELETE = new Permission(PERMISSIONS,\"Delete\",Messages._Run_DeletePermission_Description(),Permission.DELETE);\n public static final Permission UPDATE = new Permission(PERMISSIONS,\"Update\",Messages._Run_UpdatePermission_Description(),Permission.UPDATE);\n\n private static class DefaultFeedAdapter implements FeedAdapter {\n public String getEntryTitle(Run entry) {\n return entry+\" (\"+entry.getResult()+\")\";\n }\n\n public String getEntryUrl(Run entry) {\n return entry.getUrl();\n }\n\n public String getEntryID(Run entry) {\n return \"tag:\" + \"hudson.dev.java.net,\"\n + entry.getTimestamp().get(Calendar.YEAR) + \":\"\n + entry.getParent().getName()+':'+entry.getId();\n }\n\n public String getEntryDescription(Run entry) {\n // TODO: this could provide some useful details\n return null;\n }\n\n public Calendar getEntryTimestamp(Run entry) {\n return entry.getTimestamp();\n }\n\n public String getEntryAuthor(Run entry) {\n return Mailer.DESCRIPTOR.getAdminAddress();\n }\n }\n}\n"},"new_file":{"kind":"string","value":"core/src/main/java/hudson/model/Run.java"},"old_contents":{"kind":"string","value":"package hudson.model;\n\nimport com.thoughtworks.xstream.XStream;\nimport hudson.CloseProofOutputStream;\nimport hudson.EnvVars;\nimport hudson.ExtensionPoint;\nimport hudson.FeedAdapter;\nimport hudson.FilePath;\nimport hudson.Util;\nimport static hudson.Util.combine;\nimport hudson.XmlFile;\nimport hudson.AbortException;\nimport hudson.BulkChange;\nimport hudson.matrix.MatrixBuild;\nimport hudson.matrix.MatrixRun;\nimport hudson.model.listeners.RunListener;\nimport hudson.search.SearchIndexBuilder;\nimport hudson.security.ACL;\nimport hudson.security.AccessControlled;\nimport hudson.security.Permission;\nimport hudson.security.PermissionGroup;\nimport hudson.tasks.BuildStep;\nimport hudson.tasks.BuildWrapper;\nimport hudson.tasks.LogRotator;\nimport hudson.tasks.Mailer;\nimport hudson.tasks.test.AbstractTestResultAction;\nimport hudson.util.IOException2;\nimport hudson.util.XStream2;\nimport org.kohsuke.stapler.QueryParameter;\nimport org.kohsuke.stapler.StaplerRequest;\nimport org.kohsuke.stapler.StaplerResponse;\nimport org.kohsuke.stapler.export.Exported;\nimport org.kohsuke.stapler.export.ExportedBean;\nimport org.kohsuke.stapler.framework.io.LargeText;\n\nimport javax.servlet.ServletException;\nimport javax.servlet.http.HttpServletResponse;\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.PrintStream;\nimport java.io.PrintWriter;\nimport java.io.Writer;\nimport java.io.InputStreamReader;\nimport java.io.FileInputStream;\nimport java.text.DateFormat;\nimport java.text.ParseException;\nimport java.text.SimpleDateFormat;\nimport java.util.ArrayList;\nimport java.util.Calendar;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.Date;\nimport java.util.GregorianCalendar;\nimport java.util.HashMap;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.Map;\nimport java.util.TreeMap;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\nimport java.nio.charset.Charset;\n\n/**\n * A particular execution of {@link Job}.\n *\n *

\n * Custom {@link Run} type is always used in conjunction with\n * a custom {@link Job} type, so there's no separate registration\n * mechanism for custom {@link Run} types.\n *\n * @author Kohsuke Kawaguchi\n * @see RunListener\n */\n@ExportedBean\npublic abstract class Run ,RunT extends Run>\n extends Actionable implements ExtensionPoint, Comparable, AccessControlled, PersistenceRoot {\n\n protected transient final JobT project;\n\n /**\n * Build number.\n *\n *

\n * In earlier versions &lt; 1.24, this number is not unique nor continuous,\n * but going forward, it will, and this really replaces the build id.\n */\n public /*final*/ int number;\n\n /**\n * Previous build. Can be null.\n * These two fields are maintained and updated by {@link RunMap}.\n */\n protected volatile transient RunT previousBuild;\n /**\n * Next build. Can be null.\n */\n protected volatile transient RunT nextBuild;\n\n /**\n * When the build is scheduled.\n */\n protected transient final long timestamp;\n\n /**\n * The build result.\n * This value may change while the state is in {@link State#BUILDING}.\n */\n protected volatile Result result;\n\n /**\n * Human-readable description. Can be null.\n */\n protected volatile String description;\n\n /**\n * The current build state.\n */\n protected volatile transient State state;\n\n private static enum State {\n /**\n * Build is created/queued but we haven't started building it.\n */\n NOT_STARTED,\n /**\n * Build is in progress.\n */\n BUILDING,\n /**\n * Build is completed now, and the status is determined,\n * but log files are still being updated.\n */\n POST_PRODUCTION,\n /**\n * Build is completed now, and log file is closed.\n */\n COMPLETED\n }\n\n /**\n * Number of milli-seconds it took to run this build.\n */\n protected long duration;\n\n /**\n * Charset in which the log file is written.\n * For compatibility reason, this field may be null.\n * For persistence, this field is string and not {@link Charset}.\n *\n * @see #getCharset()\n * @since 1.257\n */\n private String charset;\n\n /**\n * Keeps this log entries.\n */\n private boolean keepLog;\n\n protected static final ThreadLocal ID_FORMATTER =\n new ThreadLocal() {\n @Override\n protected SimpleDateFormat initialValue() {\n return new SimpleDateFormat(\"yyyy-MM-dd_HH-mm-ss\");\n }\n };\n\n /**\n * Creates a new {@link Run}.\n */\n protected Run(JobT job) throws IOException {\n this(job, new GregorianCalendar());\n this.number = project.assignBuildNumber();\n }\n\n /**\n * Constructor for creating a {@link Run} object in\n * an arbitrary state.\n */\n protected Run(JobT job, Calendar timestamp) {\n this(job,timestamp.getTimeInMillis());\n }\n\n protected Run(JobT job, long timestamp) {\n this.project = job;\n this.timestamp = timestamp;\n this.state = State.NOT_STARTED;\n }\n\n /**\n * Loads a run from a log file.\n */\n protected Run(JobT project, File buildDir) throws IOException {\n this(project, parseTimestampFromBuildDir(buildDir));\n this.state = State.COMPLETED;\n this.result = Result.FAILURE; // defensive measure. value should be overwritten by unmarshal, but just in case the saved data is inconsistent\n getDataFile().unmarshal(this); // load the rest of the data\n }\n\n /*package*/ static long parseTimestampFromBuildDir(File buildDir) throws IOException {\n try {\n return ID_FORMATTER.get().parse(buildDir.getName()).getTime();\n } catch (ParseException e) {\n throw new IOException2(\"Invalid directory name \"+buildDir,e);\n } catch (NumberFormatException e) {\n throw new IOException2(\"Invalid directory name \"+buildDir,e);\n }\n }\n\n /**\n * Ordering based on build numbers.\n */\n public int compareTo(RunT that) {\n return this.number - that.number;\n }\n\n /**\n * Returns the build result.\n *\n *

\n * When a build is {@link #isBuilding() in progress}, this method\n * may return null or a temporary intermediate result.\n */\n @Exported\n public Result getResult() {\n return result;\n }\n\n public void setResult(Result r) {\n // state can change only when we are building\n assert state==State.BUILDING;\n\n StackTraceElement caller = findCaller(Thread.currentThread().getStackTrace(),\"setResult\");\n\n\n // result can only get worse\n if(result==null) {\n result = r;\n LOGGER.fine(toString()+\" : result is set to \"+r+\" by \"+caller);\n } else {\n if(r.isWorseThan(result)) {\n LOGGER.fine(toString()+\" : result is set to \"+r+\" by \"+caller);\n result = r;\n }\n }\n }\n\n /**\n * Gets the subset of {@link #getActions()} that consists of {@link BuildBadgeAction}s.\n */\n public List getBadgeActions() {\n List r = null;\n for (Action a : getActions()) {\n if(a instanceof BuildBadgeAction) {\n if(r==null)\n r = new ArrayList();\n r.add((BuildBadgeAction)a);\n }\n }\n if(isKeepLog()) {\n if(r==null)\n r = new ArrayList();\n r.add(new KeepLogBuildBadge());\n }\n if(r==null) return Collections.emptyList();\n else return r;\n }\n\n private StackTraceElement findCaller(StackTraceElement[] stackTrace, String callee) {\n for(int i=0; iNEVER be used during HTML page rendering, as it won't work with\n * network set up like Apache reverse proxy.\n * This method is only intended for the remote API clients who cannot resolve relative references\n * (even this won't work for the same reason, which should be fixed.)\n */\n @Exported(visibility=2,name=\"url\")\n public final String getAbsoluteUrl() {\n return project.getAbsoluteUrl()+getNumber()+'/';\n }\n\n public final String getSearchUrl() {\n return getNumber()+\"/\";\n }\n\n /**\n * Unique ID of this build.\n */\n public String getId() {\n return ID_FORMATTER.get().format(new Date(timestamp));\n }\n\n /**\n * Root directory of this {@link Run} on the master.\n *\n * Files related to this {@link Run} should be stored below this directory.\n */\n public File getRootDir() {\n File f = new File(project.getBuildDir(),getId());\n f.mkdirs();\n return f;\n }\n\n /**\n * Gets the directory where the artifacts are archived.\n */\n public File getArtifactsDir() {\n return new File(getRootDir(),\"archive\");\n }\n\n /**\n * Gets the first {@value #CUTOFF} artifacts (relative to {@link #getArtifactsDir()}.\n */\n public List getArtifacts() {\n ArtifactList r = new ArtifactList();\n addArtifacts(getArtifactsDir(),\"\",r);\n r.computeDisplayName();\n return r;\n }\n\n /**\n * Returns true if this run has any artifacts.\n *\n *

\n * The strange method name is so that we can access it from EL.\n */\n public boolean getHasArtifacts() {\n return !getArtifacts().isEmpty();\n }\n\n private void addArtifacts( File dir, String path, List r ) {\n String[] children = dir.list();\n if(children==null) return;\n for (String child : children) {\n if(r.size()>CUTOFF)\n return;\n File sub = new File(dir, child);\n if (sub.isDirectory()) {\n addArtifacts(sub, path + child + '/', r);\n } else {\n r.add(new Artifact(path + child));\n }\n }\n }\n\n private static final int CUTOFF = 17; // 0, 1,... 16, and then \"too many\"\n\n public final class ArtifactList extends ArrayList {\n public void computeDisplayName() {\n if(size()>CUTOFF) return; // we are not going to display file names, so no point in computing this\n\n int maxDepth = 0;\n int[] len = new int[size()];\n String[][] tokens = new String[size()][];\n for( int i=0; i names = new HashMap();\n for (int i = 0; i < tokens.length; i++) {\n String[] token = tokens[i];\n String displayName = combineLast(token,len[i]);\n Integer j = names.put(displayName, i);\n if(j!=null) {\n collision = true;\n if(j>=0)\n len[j]++;\n len[i]++;\n names.put(displayName,-1); // occupy this name but don't let len[i] incremented with additional collisions\n }\n }\n } while(collision && depth++ names = new HashSet();\n// for (String[] token : tokens) {\n// if(!names.add(combineLast(token,n)))\n// continue OUTER; // collision. Increase n and try again\n// }\n//\n// // this n successfully diambiguates\n// for (int i = 0; i < tokens.length; i++) {\n// String[] token = tokens[i];\n// get(i).displayPath = combineLast(token,n);\n// }\n// return;\n// }\n\n// // it's impossible to get here, as that means\n// // we have the same artifacts archived twice, but be defensive\n// for (Artifact a : this)\n// a.displayPath = a.relativePath;\n }\n\n /**\n * Combines last N token into the \"a/b/c\" form.\n */\n private String combineLast(String[] token, int n) {\n StringBuffer buf = new StringBuffer();\n for( int i=Math.max(0,token.length-n); i0) buf.append('/');\n buf.append(token[i]);\n }\n return buf.toString();\n }\n }\n\n /**\n * A build artifact.\n */\n public class Artifact {\n /**\n * Relative path name from {@link Run#getArtifactsDir()}\n */\n public final String relativePath;\n\n /**\n * Truncated form of {@link #relativePath} just enough\n * to disambiguate {@link Artifact}s.\n */\n /*package*/ String displayPath;\n\n /*package for test*/ Artifact(String relativePath) {\n this.relativePath = relativePath;\n }\n\n /**\n * Gets the artifact file.\n */\n public File getFile() {\n return new File(getArtifactsDir(),relativePath);\n }\n\n /**\n * Returns just the file name portion, without the path.\n */\n public String getFileName() {\n return getFile().getName();\n }\n\n public String getDisplayPath() {\n return displayPath;\n }\n\n public String toString() {\n return relativePath;\n }\n }\n\n /**\n * Returns the log file.\n */\n public File getLogFile() {\n return new File(getRootDir(),\"log\");\n }\n\n protected SearchIndexBuilder makeSearchIndex() {\n SearchIndexBuilder builder = super.makeSearchIndex()\n .add(\"console\")\n .add(\"changes\");\n for (Action a : getActions()) {\n if(a.getIconFileName()!=null)\n builder.add(a.getUrlName());\n }\n return builder;\n }\n\n public Api getApi(final StaplerRequest req) {\n return new Api(this);\n }\n\n public void checkPermission(Permission p) {\n getACL().checkPermission(p);\n }\n\n public boolean hasPermission(Permission p) {\n return getACL().hasPermission(p);\n }\n\n public ACL getACL() {\n // for now, don't maintain ACL per run, and do it at project level\n return getParent().getACL();\n }\n\n /**\n * Deletes this build and its entire log\n *\n * @throws IOException\n * if we fail to delete.\n */\n public synchronized void delete() throws IOException {\n File rootDir = getRootDir();\n File tmp = new File(rootDir.getParentFile(),'.'+rootDir.getName());\n \n boolean renamingSucceeded = rootDir.renameTo(tmp);\n Util.deleteRecursive(tmp);\n\n if(!renamingSucceeded)\n throw new IOException(rootDir+\" is in use\");\n\n removeRunFromParent();\n }\n @SuppressWarnings(\"unchecked\") // seems this is too clever for Java's type system?\n private void removeRunFromParent() {\n getParent().removeRun((RunT)this);\n }\n\n protected static interface Runner {\n /**\n * Performs the main build and returns the status code.\n *\n * @throws Exception\n * exception will be recorded and the build will be considered a failure.\n */\n Result run( BuildListener listener ) throws Exception, RunnerAbortedException;\n\n /**\n * Performs the post-build action.\n *

\n * This method is called after the status of the build is determined.\n * This is a good opportunity to do notifications based on the result\n * of the build. When this method is called, the build is not really\n * finalized yet, and the build is still considered in progress --- for example,\n * even if the build is successful, this build still won't be picked up\n * by {@link Job#getLastSuccessfulBuild()}.\n */\n void post( BuildListener listener ) throws Exception;\n\n /**\n * Performs final clean up action.\n *

\n * This method is called after {@link #post(BuildListener)},\n * after the build result is fully finalized. This is the point\n * where the build is already considered completed.\n *

\n * Among other things, this is often a necessary pre-condition\n * before invoking other builds that depend on this build.\n */\n void cleanUp(BuildListener listener) throws Exception;\n }\n\n /**\n * Used in {@link Runner#run} to indicates that a fatal error in a build\n * is reported to {@link BuildListener} and the build should be simply aborted\n * without further recording a stack trace.\n */\n public static final class RunnerAbortedException extends RuntimeException {}\n\n protected final void run(Runner job) {\n if(result!=null)\n return; // already built.\n\n BuildListener listener=null;\n PrintStream log = null;\n\n onStartBuilding();\n try {\n // to set the state to COMPLETE in the end, even if the thread dies abnormally.\n // otherwise the queue state becomes inconsistent\n\n long start = System.currentTimeMillis();\n\n try {\n try {\n log = new PrintStream(new FileOutputStream(getLogFile()));\n Charset charset = Computer.currentComputer().getDefaultCharset();\n this.charset = charset.name();\n listener = new StreamBuildListener(new PrintStream(new CloseProofOutputStream(log)),charset);\n\n listener.started();\n\n RunListener.fireStarted(this,listener);\n\n setResult(job.run(listener));\n\n LOGGER.info(toString()+\" main build action completed: \"+result);\n } catch (ThreadDeath t) {\n throw t;\n } catch( AbortException e ) {\n result = Result.FAILURE;\n } catch( RunnerAbortedException e ) {\n result = Result.FAILURE;\n } catch( InterruptedException e) {\n // aborted\n result = Result.ABORTED;\n listener.getLogger().println(Messages.Run_BuildAborted());\n LOGGER.log(Level.INFO,toString()+\" aborted\",e);\n } catch( Throwable e ) {\n handleFatalBuildProblem(listener,e);\n result = Result.FAILURE;\n }\n\n // even if the main build fails fatally, try to run post build processing\n job.post(listener);\n\n } catch (ThreadDeath t) {\n throw t;\n } catch( Throwable e ) {\n handleFatalBuildProblem(listener,e);\n result = Result.FAILURE;\n } finally {\n long end = System.currentTimeMillis();\n duration = end-start;\n\n // advance the state.\n // the significance of doing this is that Hudson\n // will now see this build as completed.\n // things like triggering other builds requires this as pre-condition.\n // see issue #980.\n state = State.POST_PRODUCTION;\n\n try {\n job.cleanUp(listener);\n } catch (Exception e) {\n handleFatalBuildProblem(listener,e);\n // too late to update the result now\n }\n\n RunListener.fireCompleted(this,listener);\n\n if(listener!=null)\n listener.finished(result);\n if(log!=null)\n log.close();\n\n try {\n save();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n try {\n getParent().logRotate();\n } catch (IOException e) {\n e.printStackTrace();\n }\n } finally {\n onEndBuilding();\n }\n }\n\n /**\n * Handles a fatal build problem (exception) that occurred during the build.\n */\n private void handleFatalBuildProblem(BuildListener listener, Throwable e) {\n if(listener!=null) {\n if(e instanceof IOException)\n Util.displayIOException((IOException)e,listener);\n\n Writer w = listener.fatalError(e.getMessage());\n if(w!=null) {\n try {\n e.printStackTrace(new PrintWriter(w));\n w.close();\n } catch (IOException e1) {\n // ignore\n }\n }\n }\n }\n\n /**\n * Called when a job started building.\n */\n protected void onStartBuilding() {\n state = State.BUILDING;\n }\n\n /**\n * Called when a job finished building normally or abnormally.\n */\n protected void onEndBuilding() {\n state = State.COMPLETED;\n if(result==null) {\n // shouldn't happen, but be defensive until we figure out why\n result = Result.FAILURE;\n LOGGER.warning(toString()+\": No build result is set, so marking as failure. This shouldn't happen\");\n }\n RunListener.fireFinalized(this);\n }\n\n /**\n * Save the settings to a file.\n */\n public synchronized void save() throws IOException {\n if(BulkChange.contains(this)) return;\n getDataFile().write(this);\n }\n\n private XmlFile getDataFile() {\n return new XmlFile(XSTREAM,new File(getRootDir(),\"build.xml\"));\n }\n\n /**\n * Gets the log of the build as a string.\n *\n * @deprecated Use {@link #getLog(int)} instead as it avoids loading\n * the whole log into memory unnecessarily.\n */\n @Deprecated\n public String getLog() throws IOException {\n return Util.loadFile(getLogFile(),getCharset());\n }\n\n /**\n * Gets the log of the build as a list of strings (one per log line).\n * The number of lines returned is constrained by the maxLines parameter.\n *\n * @param maxLines The maximum number of log lines to return. If the log\n * is bigger than this, only the most recent lines are returned.\n * @return A list of log lines. Will have no more than maxLines elements.\n * @throws IOException If there is a problem reading the log file.\n */\n public List getLog(int maxLines) throws IOException {\n int lineCount = 0;\n List logLines = new LinkedList();\n BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(getLogFile()),getCharset()));\n try {\n for (String line = reader.readLine(); line != null; line = reader.readLine()) {\n logLines.add(line);\n ++lineCount;\n // If we have too many lines, remove the oldest line. This way we\n // never have to hold the full contents of a huge log file in memory.\n // Adding to and removing from the ends of a linked list are cheap\n // operations.\n if (lineCount > maxLines)\n logLines.remove(0);\n }\n } finally {\n reader.close();\n }\n\n // If the log has been truncated, include that information.\n // Use set (replaces the first element) rather than add so that\n // the list doesn't grow beyond the specified maximum number of lines.\n if (lineCount > maxLines)\n logLines.set(0, \"[...truncated \" + (lineCount - (maxLines - 1)) + \" lines...]\");\n\n return logLines;\n }\n\n public void doBuildStatus( StaplerRequest req, StaplerResponse rsp ) throws IOException {\n // see Hudson.doNocacheImages. this is a work around for a bug in Firefox\n rsp.sendRedirect2(req.getContextPath()+\"/nocacheImages/48x48/\"+getBuildStatusUrl());\n }\n\n public String getBuildStatusUrl() {\n return getIconColor().getImage();\n }\n\n public static class Summary {\n /**\n * Is this build worse or better, compared to the previous build?\n */\n public boolean isWorse;\n public String message;\n\n public Summary(boolean worse, String message) {\n this.isWorse = worse;\n this.message = message;\n }\n }\n\n /**\n * Gets an object that computes the single line summary of this build.\n */\n public Summary getBuildStatusSummary() {\n Run prev = getPreviousBuild();\n\n if(getResult()==Result.SUCCESS) {\n if(prev==null || prev.getResult()== Result.SUCCESS)\n return new Summary(false,\"stable\");\n else\n return new Summary(false,\"back to normal\");\n }\n\n if(getResult()==Result.FAILURE) {\n RunT since = getPreviousNotFailedBuild();\n if(since==null)\n return new Summary(false,\"broken for a long time\");\n if(since==prev)\n return new Summary(true,\"broken since this build\");\n return new Summary(false,\"broken since \"+since.getDisplayName());\n }\n\n if(getResult()==Result.ABORTED)\n return new Summary(false,\"aborted\");\n\n if(getResult()==Result.UNSTABLE) {\n if(((Run)this) instanceof Build) {\n AbstractTestResultAction trN = ((Build)(Run)this).getTestResultAction();\n AbstractTestResultAction trP = prev==null ? null : ((Build) prev).getTestResultAction();\n if(trP==null) {\n if(trN!=null && trN.getFailCount()>0)\n return new Summary(false,combine(trN.getFailCount(),\"test failure\"));\n else // ???\n return new Summary(false,\"unstable\");\n }\n if(trP.getFailCount()==0)\n return new Summary(true,combine(trN.getFailCount(),\"test\")+\" started to fail\");\n if(trP.getFailCount() < trN.getFailCount())\n return new Summary(true,combine(trN.getFailCount()-trP.getFailCount(),\"more test\")\n +\" are failing (\"+trN.getFailCount()+\" total)\");\n if(trP.getFailCount() > trN.getFailCount())\n return new Summary(false,combine(trP.getFailCount()-trN.getFailCount(),\"less test\")\n +\" are failing (\"+trN.getFailCount()+\" total)\");\n\n return new Summary(false,combine(trN.getFailCount(),\"test\")+\" are still failing\");\n }\n }\n\n return new Summary(false,\"?\");\n }\n\n /**\n * Serves the artifacts.\n */\n public void doArtifact( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, InterruptedException {\n new DirectoryBrowserSupport(this,project.getDisplayName()+' '+getDisplayName())\n .serveFile(req, rsp, new FilePath(getArtifactsDir()), \"package.gif\", true);\n }\n\n /**\n * Returns the build number in the body.\n */\n public void doBuildNumber( StaplerRequest req, StaplerResponse rsp ) throws IOException {\n rsp.setContentType(\"text/plain\");\n rsp.setCharacterEncoding(\"US-ASCII\");\n rsp.setStatus(HttpServletResponse.SC_OK);\n rsp.getWriter().print(number);\n }\n\n /**\n * Returns the build time stamp in the body.\n */\n public void doBuildTimestamp( StaplerRequest req, StaplerResponse rsp, @QueryParameter String format) throws IOException {\n rsp.setContentType(\"text/plain\");\n rsp.setCharacterEncoding(\"US-ASCII\");\n rsp.setStatus(HttpServletResponse.SC_OK);\n DateFormat df = format==null ?\n DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.SHORT, Locale.ENGLISH) :\n new SimpleDateFormat(format,req.getLocale());\n rsp.getWriter().print(df.format(getTimestamp().getTime()));\n }\n\n /**\n * Handles incremental log output.\n */\n public void doProgressiveLog( StaplerRequest req, StaplerResponse rsp) throws IOException {\n new LargeText(getLogFile(),getCharset(),!isLogUpdated()).doProgressText(req,rsp);\n }\n\n public void doToggleLogKeep( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {\n checkPermission(UPDATE);\n\n keepLog(!keepLog);\n rsp.forwardToPreviousPage(req);\n }\n\n /**\n * Marks this build to keep the log.\n */\n public final void keepLog() throws IOException {\n keepLog(true);\n }\n\n public void keepLog(boolean newValue) throws IOException {\n keepLog = newValue;\n save();\n }\n\n /**\n * Deletes the build when the button is pressed.\n */\n public void doDoDelete( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {\n checkPermission(DELETE);\n\n // We should not simply delete the build if it has been explicitly\n // marked to be preserved, or if the build should not be deleted\n // due to dependencies!\n String why = getWhyKeepLog();\n if (why!=null) {\n sendError(Messages.Run_UnableToDelete(toString(),why),req,rsp);\n return;\n }\n\n delete();\n rsp.sendRedirect2(req.getContextPath()+'/' + getParent().getUrl());\n }\n\n public void setDescription(String description) throws IOException {\n checkPermission(UPDATE);\n this.description = description;\n save();\n }\n \n /**\n * Accepts the new description.\n */\n public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {\n req.setCharacterEncoding(\"UTF-8\");\n setDescription(req.getParameter(\"description\"));\n rsp.sendRedirect(\".\"); // go to the top page\n }\n\n /**\n * Returns the map that contains environmental variable overrides for this build.\n *\n *

\n * {@link BuildStep}s that invoke external processes should use this.\n * This allows {@link BuildWrapper}s and other project configurations (such as JDK selection)\n * to take effect.\n *\n *

\n * On Windows systems, environment variables are case-preserving but\n * comparison/query is case insensitive (IOW, you can set 'Path' to something\n * and you get the same value by doing '%PATH%'.) So to implement this semantics\n * the map returned from here is a {@link TreeMap} with a special comparator.\n *\n */\n public Map getEnvVars() {\n EnvVars env = new EnvVars();\n env.put(\"BUILD_NUMBER\",String.valueOf(number));\n env.put(\"BUILD_ID\",getId());\n env.put(\"BUILD_TAG\",\"hudson-\"+getParent().getName()+\"-\"+number);\n env.put(\"JOB_NAME\",getParent().getFullName());\n String rootUrl = Hudson.getInstance().getRootUrl();\n if(rootUrl!=null)\n env.put(\"HUDSON_URL\", rootUrl);\n\n Thread t = Thread.currentThread();\n if (t instanceof Executor) {\n Executor e = (Executor) t;\n env.put(\"EXECUTOR_NUMBER\",String.valueOf(e.getNumber()));\n }\n\n return env;\n }\n\n public static final XStream XSTREAM = new XStream2();\n static {\n XSTREAM.alias(\"build\",FreeStyleBuild.class);\n XSTREAM.alias(\"matrix-build\",MatrixBuild.class);\n XSTREAM.alias(\"matrix-run\",MatrixRun.class);\n XSTREAM.registerConverter(Result.conv);\n }\n\n private static final Logger LOGGER = Logger.getLogger(Run.class.getName());\n\n /**\n * Sort by date. Newer ones first. \n */\n public static final Comparator ORDER_BY_DATE = new Comparator() {\n public int compare(Run lhs, Run rhs) {\n long lt = lhs.getTimestamp().getTimeInMillis();\n long rt = rhs.getTimestamp().getTimeInMillis();\n if(lt>rt) return -1;\n if(lt FEED_ADAPTER = new DefaultFeedAdapter();\n\n /**\n * {@link FeedAdapter} to produce feeds to show one build per project.\n */\n public static final FeedAdapter FEED_ADAPTER_LATEST = new DefaultFeedAdapter() {\n /**\n * The entry unique ID needs to be tied to a project, so that\n * new builds will replace the old result.\n */\n public String getEntryID(Run e) {\n // can't use a meaningful year field unless we remember when the job was created.\n return \"tag:hudson.dev.java.net,2008:\"+e.getParent().getAbsoluteUrl();\n }\n };\n\n /**\n * {@link BuildBadgeAction} that shows the logs are being kept.\n */\n public final class KeepLogBuildBadge implements BuildBadgeAction {\n public String getIconFileName() { return null; }\n public String getDisplayName() { return null; }\n public String getUrlName() { return null; }\n public String getWhyKeepLog() { return Run.this.getWhyKeepLog(); }\n }\n\n public static final PermissionGroup PERMISSIONS = new PermissionGroup(Run.class,Messages._Run_Permissions_Title());\n public static final Permission DELETE = new Permission(PERMISSIONS,\"Delete\",Messages._Run_DeletePermission_Description(),Permission.DELETE);\n public static final Permission UPDATE = new Permission(PERMISSIONS,\"Update\",Messages._Run_UpdatePermission_Description(),Permission.UPDATE);\n\n private static class DefaultFeedAdapter implements FeedAdapter {\n public String getEntryTitle(Run entry) {\n return entry+\" (\"+entry.getResult()+\")\";\n }\n\n public String getEntryUrl(Run entry) {\n return entry.getUrl();\n }\n\n public String getEntryID(Run entry) {\n return \"tag:\" + \"hudson.dev.java.net,\"\n + entry.getTimestamp().get(Calendar.YEAR) + \":\"\n + entry.getParent().getName()+':'+entry.getId();\n }\n\n public String getEntryDescription(Run entry) {\n // TODO: this could provide some useful details\n return null;\n }\n\n public Calendar getEntryTimestamp(Run entry) {\n return entry.getTimestamp();\n }\n\n public String getEntryAuthor(Run entry) {\n return Mailer.DESCRIPTOR.getAdminAddress();\n }\n }\n}\n"},"message":{"kind":"string","value":"Issue 2249: export available artifacts in xml api\n\ngit-svn-id: 28f34f9aa52bc55a5ddd5be9e183c5cccadc6ee4@13562 71c3de6d-444a-0410-be80-ed276b4c234a\n"},"old_file":{"kind":"string","value":"core/src/main/java/hudson/model/Run.java"},"subject":{"kind":"string","value":"Issue 2249: export available artifacts in xml api"},"git_diff":{"kind":"string","value":"ore/src/main/java/hudson/model/Run.java\n /**\n * Gets the first {@value #CUTOFF} artifacts (relative to {@link #getArtifactsDir()}.\n */\n @Exported\n public List getArtifacts() {\n ArtifactList r = new ArtifactList();\n addArtifacts(getArtifactsDir(),\"\",r);\n /**\n * A build artifact.\n */\n @ExportedBean\n public class Artifact {\n /**\n * Relative path name from {@link Run#getArtifactsDir()}\n */\n \t@Exported(visibility=3)\n public final String relativePath;\n \n /**\n /**\n * Returns just the file name portion, without the path.\n */\n \t@Exported(visibility=3)\n public String getFileName() {\n return getFile().getName();\n }\n \n \t@Exported(visibility=3)\n public String getDisplayPath() {\n return displayPath;\n }"}}},{"rowIdx":1930,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"lgpl-2.1"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"8d12b1ab85a2d94b1be8a850a7b9284e2ef45047"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"IDgis/geo-publisher,IDgis/geo-publisher,IDgis/geo-publisher,IDgis/geo-publisher"},"new_contents":{"kind":"string","value":"package nl.idgis.publisher.service.geoserver;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.Arrays;\r\nimport java.util.Collections;\r\nimport java.util.List;\r\nimport java.util.Optional;\r\n\r\nimport org.junit.Before;\r\nimport org.junit.Test;\r\n\r\nimport com.typesafe.config.Config;\r\nimport com.typesafe.config.ConfigFactory;\r\nimport com.typesafe.config.ConfigValueFactory;\r\n\r\nimport akka.actor.ActorRef;\r\nimport akka.actor.ActorSystem;\r\nimport akka.actor.Props;\r\nimport akka.actor.Terminated;\r\nimport akka.actor.UntypedActor;\r\nimport akka.event.Logging;\r\nimport akka.event.LoggingAdapter;\r\nimport akka.japi.Procedure;\r\n\r\nimport nl.idgis.publisher.domain.web.tree.DatasetLayer;\r\nimport nl.idgis.publisher.domain.web.tree.DatasetLayerRef;\r\nimport nl.idgis.publisher.domain.web.tree.GroupLayer;\r\nimport nl.idgis.publisher.domain.web.tree.GroupLayerRef;\r\nimport nl.idgis.publisher.domain.web.tree.LayerRef;\r\nimport nl.idgis.publisher.domain.web.tree.Service;\r\nimport nl.idgis.publisher.domain.web.tree.Tiling;\r\n\r\nimport nl.idgis.publisher.protocol.messages.Ack;\r\nimport nl.idgis.publisher.recorder.Recorder;\r\nimport nl.idgis.publisher.recorder.Recording;\r\nimport nl.idgis.publisher.recorder.messages.GetRecording;\r\nimport nl.idgis.publisher.recorder.messages.RecordedMessage;\r\nimport nl.idgis.publisher.recorder.messages.Wait;\r\nimport nl.idgis.publisher.recorder.messages.Waited;\r\nimport nl.idgis.publisher.service.TestStyle;\r\nimport nl.idgis.publisher.service.geoserver.messages.EnsureFeatureTypeLayer;\r\nimport nl.idgis.publisher.service.geoserver.messages.EnsureGroupLayer;\r\nimport nl.idgis.publisher.service.geoserver.messages.EnsureStyle;\r\nimport nl.idgis.publisher.service.geoserver.messages.EnsureWorkspace;\r\nimport nl.idgis.publisher.service.geoserver.messages.Ensured;\r\nimport nl.idgis.publisher.service.geoserver.messages.FinishEnsure;\r\nimport nl.idgis.publisher.service.manager.messages.Style;\r\nimport nl.idgis.publisher.stream.messages.End;\r\nimport nl.idgis.publisher.utils.SyncAskHelper;\r\nimport nl.idgis.publisher.utils.UniqueNameGenerator;\r\nimport static org.junit.Assert.assertEquals;\r\nimport static org.junit.Assert.assertNotNull;\r\nimport static org.junit.Assert.assertTrue;\r\nimport static org.mockito.Mockito.mock;\r\nimport static org.mockito.Mockito.when;\r\n\r\npublic class EnsureServiceTest {\r\n\t\r\n\tprivate static class Ensure {\r\n\t\t\r\n\t\tprivate final List messages;\r\n\t\t\r\n\t\tEnsure(Object... messages) {\r\n\t\t\tthis.messages = Arrays.asList(messages);\r\n\t\t}\r\n\t\t\r\n\t\tpublic List getMessages() {\r\n\t\t\treturn messages;\r\n\t\t}\r\n\t}\r\n\t\r\n\tstatic class GeoServerServiceMock extends UntypedActor {\r\n\t\t\r\n\t\tprivate final LoggingAdapter log = Logging.getLogger(getContext().system(), this);\r\n\t\t\r\n\t\tprivate final UniqueNameGenerator nameGenerator = new UniqueNameGenerator();\r\n\t\t\r\n\t\tprivate final ActorRef recorder;\r\n\t\t\r\n\t\tpublic GeoServerServiceMock(ActorRef recorder) {\r\n\t\t\tthis.recorder = recorder;\r\n\t\t}\r\n\t\t\r\n\t\tpublic static Props props(ActorRef recorder) {\r\n\t\t\treturn Props.create(GeoServerServiceMock.class, recorder);\r\n\t\t}\r\n\t\t\r\n\t\tprivate void unexpected(Object msg) {\r\n\t\t\tif(msg instanceof Terminated) {\r\n\t\t\t\trecord(msg);\r\n\t\t\t} else {\t\t\t\r\n\t\t\t\tlog.error(\"unhandled: {}\", msg);\r\n\t\t\t\r\n\t\t\t\tunhandled(msg);\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tprivate void record(Object msg) {\r\n\t\t\tlog.debug(\"recorded: {}\", msg);\r\n\t\t\t\r\n\t\t\trecorder.tell(new RecordedMessage(getSelf(), getSender(), msg), getSelf());\r\n\t\t}\r\n\t\t\r\n\t\tprivate void ensured() {\r\n\t\t\tlog.debug(\"ensured\");\r\n\t\t\t\r\n\t\t\tgetSender().tell(new Ensured(), getSelf());\r\n\t\t}\r\n\t\t\r\n\t\tprivate Procedure layers(ActorRef initiator) {\r\n\t\t\treturn layers(initiator, 0);\r\n\t\t}\r\n\t\t\r\n\t\tprivate Procedure layers(ActorRef initiator, int depth) {\r\n\t\t\tlog.debug(\"group\");\r\n\t\t\t\r\n\t\t\treturn new Procedure() {\r\n\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic void apply(Object msg) throws Exception {\r\n\t\t\t\t\trecord(msg);\r\n\t\t\t\t\t\r\n\t\t\t\t\tif(msg instanceof EnsureGroupLayer) {\r\n\t\t\t\t\t\tensured();\r\n\t\t\t\t\t\tgetContext().become(layers(initiator, depth + 1), false);\r\n\t\t\t\t\t} else if(msg instanceof EnsureFeatureTypeLayer) {\r\n\t\t\t\t\t\tensured();\r\n\t\t\t\t\t} else if(msg instanceof FinishEnsure) {\r\n\t\t\t\t\t\tensured();\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tif(depth == 0) {\r\n\t\t\t\t\t\t\tlog.debug(\"ack\");\r\n\t\t\t\t\t\t\tinitiator.tell(new Ack(), getSelf());\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\tlog.debug(\"unbecome {}\", depth);\t\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tgetContext().unbecome();\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tunexpected(msg);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\t\t\t\t\r\n\t\t\t};\r\n\t\t}\r\n\t\t\r\n\t\tprivate Procedure provisioning(ActorRef initiator) {\r\n\t\t\tlog.debug(\"provisioning\");\r\n\t\t\t\r\n\t\t\treturn new Procedure() {\r\n\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic void apply(Object msg) throws Exception {\r\n\t\t\t\t\tif(msg instanceof EnsureStyle) {\r\n\t\t\t\t\t\trecord(msg);\r\n\t\t\t\t\t\tensured();\r\n\t\t\t\t\t} else if(msg instanceof EnsureWorkspace) {\r\n\t\t\t\t\t\trecord(msg);\r\n\t\t\t\t\t\tensured();\r\n\t\t\t\t\t\tgetContext().become(layers(initiator), false);\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tunexpected(msg);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t};\r\n\t\t}\r\n\r\n\t\t@Override\r\n\t\tpublic void onReceive(Object msg) throws Exception {\r\n\t\t\tif(msg instanceof Ensure) {\r\n\t\t\t\tActorRef ensureService = getContext().actorOf(EnsureService.props(), nameGenerator.getName(EnsureService.class));\r\n\t\t\t\t\r\n\t\t\t\tEnsure ensure = (Ensure)msg;\r\n\t\t\t\tensure.getMessages().stream()\r\n\t\t\t\t\t.forEach(item -> ensureService.tell(item, getSelf()));\r\n\t\t\t\t\r\n\t\t\t\tgetContext().watch(ensureService);\r\n\t\t\t\tgetContext().become(provisioning(getSender()), false);\t\t\t\t\r\n\t\t\t} else {\r\n\t\t\t\tlog.error(\"unexpected: {}\", msg);\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t}\r\n\t\r\n\tActorRef recorder, geoServerService;\r\n\t\r\n\tSyncAskHelper sync;\r\n\t\r\n\t@Before\r\n\tpublic void setUp() {\r\n\t\tConfig akkaConfig = ConfigFactory.empty()\r\n\t\t\t.withValue(\"akka.loggers\", ConfigValueFactory.fromIterable(Arrays.asList(\"akka.event.slf4j.Slf4jLogger\")))\r\n\t\t\t.withValue(\"akka.loglevel\", ConfigValueFactory.fromAnyRef(\"DEBUG\"));\r\n\t\t\t\r\n\t\tActorSystem actorSystem = ActorSystem.create(\"test\", akkaConfig);\r\n\t\t\r\n\t\trecorder = actorSystem.actorOf(Recorder.props(), \"recorder\");\t\t\r\n\t\tgeoServerService = actorSystem.actorOf(GeoServerServiceMock.props(recorder), \"service-mock\");\r\n\t\t\r\n\t\tsync = new SyncAskHelper(actorSystem);\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testEmptyService() throws Exception {\r\n\t\tService service = mock(Service.class);\r\n\t\twhen(service.getId()).thenReturn(\"service0\");\r\n\t\twhen(service.getName()).thenReturn(\"serviceName0\");\r\n\t\twhen(service.getRootId()).thenReturn(\"root\");\r\n\t\twhen(service.getLayers()).thenReturn(Collections.emptyList());\r\n\t\t\r\n\t\tsync.ask(geoServerService, new Ensure(service, new End()), Ack.class);\t\t\r\n\t\t\r\n\t\tsync.ask(recorder, new Wait(3), Waited.class);\r\n\t\tsync.ask(recorder, new GetRecording(), Recording.class)\t\t\t\r\n\t\t\t.assertNext(EnsureWorkspace.class, workspace -> {\r\n\t\t\t\tassertEquals(\"serviceName0\", workspace.getWorkspaceId());\r\n\t\t\t})\t\t\t\r\n\t\t\t.assertNext(FinishEnsure.class)\r\n\t\t\t.assertNext(Terminated.class)\r\n\t\t\t.assertNotHasNext();\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testSingleLayer() throws Exception {\r\n\t\tTiling tilingSettings = mock(Tiling.class);\r\n\t\t\r\n\t\tDatasetLayer datasetLayer = mock(DatasetLayer.class);\r\n\t\twhen(datasetLayer.getName()).thenReturn(\"layer0\");\r\n\t\twhen(datasetLayer.getTitle()).thenReturn(\"title0\");\r\n\t\twhen(datasetLayer.getAbstract()).thenReturn(\"abstract0\");\r\n\t\twhen(datasetLayer.getTableName()).thenReturn(\"tableName0\");\t\t\r\n\t\twhen(datasetLayer.getTiling()).thenReturn(Optional.of(tilingSettings));\r\n\t\twhen(datasetLayer.getKeywords()).thenReturn(Arrays.asList(\"keyword0\", \"keyword1\"));\r\n\t\t\r\n\t\tService service = mock(Service.class);\r\n\t\twhen(service.getId()).thenReturn(\"service0\");\r\n\t\twhen(service.getName()).thenReturn(\"serviceName0\");\r\n\t\twhen(service.getTitle()).thenReturn(\"serviceTitle0\");\r\n\t\twhen(service.getAbstract()).thenReturn(\"serviceAbstract0\");\r\n\t\twhen(service.getKeywords()).thenReturn(Arrays.asList(\"keyword0\", \"keyword1\", \"keyword2\"));\r\n\t\twhen(service.getTelephone()).thenReturn(\"serviceTelephone0\");\r\n\t\t\r\n\t\tDatasetLayerRef datasetLayerRef = mock(DatasetLayerRef.class);\r\n\t\twhen(datasetLayerRef.isGroupRef()).thenReturn(false);\r\n\t\twhen(datasetLayerRef.asDatasetRef()).thenReturn(datasetLayerRef);\r\n\t\twhen(datasetLayerRef.getLayer()).thenReturn(datasetLayer);\r\n\t\t\r\n\t\twhen(service.getRootId()).thenReturn(\"root\");\r\n\t\twhen(service.getLayers()).thenReturn(Collections.singletonList(datasetLayerRef));\r\n\t\t\r\n\t\tsync.ask(geoServerService, new Ensure(\r\n\t\t\tservice, \r\n\t\t\tnew Style(\"style0\", TestStyle.getGreenSld()),\r\n\t\t\tnew Style(\"style1\", TestStyle.getGreenSld()),\r\n\t\t\tnew End()), Ack.class);\r\n\t\t\r\n\t\tsync.ask(recorder, new Wait(6), Waited.class);\r\n\t\tsync.ask(recorder, new GetRecording(), Recording.class)\r\n\t\t\t.assertNext(EnsureStyle.class, style -> {\r\n\t\t\t\tassertEquals(\"style0\", style.getName());\r\n\t\t\t})\r\n\t\t\t.assertNext(EnsureStyle.class, style -> {\r\n\t\t\t\tassertEquals(\"style1\", style.getName());\r\n\t\t\t})\r\n\t\t\t.assertNext(EnsureWorkspace.class, workspace -> {\r\n\t\t\t\tassertEquals(\"serviceName0\", workspace.getWorkspaceId());\r\n\t\t\t\tassertEquals(\"serviceTitle0\", workspace.getTitle());\r\n\t\t\t\tassertEquals(\"serviceAbstract0\", workspace.getAbstract());\r\n\t\t\t\tassertEquals(Arrays.asList(\"keyword0\", \"keyword1\", \"keyword2\"), workspace.getKeywords());\r\n\t\t\t\t\r\n\t\t\t})\r\n\t\t\t.assertNext(EnsureFeatureTypeLayer.class, featureType -> {\r\n\t\t\t\tassertEquals(\"layer0\", featureType.getLayerId());\r\n\t\t\t\tassertEquals(\"title0\", featureType.getTitle());\r\n\t\t\t\tassertEquals(\"abstract0\", featureType.getAbstract());\r\n\t\t\t\tassertEquals(\"tableName0\", featureType.getTableName());\r\n\t\t\t\tassertTrue(featureType.getTiledLayer().isPresent());\r\n\t\t\t\t\r\n\t\t\t\tList keywords = featureType.getKeywords();\r\n\t\t\t\tassertNotNull(keywords);\r\n\t\t\t\tassertTrue(keywords.contains(\"keyword0\"));\r\n\t\t\t\tassertTrue(keywords.contains(\"keyword1\"));\r\n\t\t\t})\r\n\t\t\t.assertNext(FinishEnsure.class)\r\n\t\t\t.assertNext(Terminated.class)\r\n\t\t\t.assertNotHasNext();\t\t\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testGroup() throws Exception {\r\n\t\tfinal int numberOfLayers = 10;\r\n\t\t\r\n\t\tList> layers = new ArrayList<>();\r\n\t\tfor(int i = 0; i < numberOfLayers; i++) {\r\n\t\t\tDatasetLayer layer = mock(DatasetLayer.class);\t\t\t\r\n\t\t\twhen(layer.getName()).thenReturn(\"layer\" + i);\r\n\t\t\twhen(layer.getTableName()).thenReturn(\"tableName\" + i);\r\n\t\t\twhen(layer.getTiling()).thenReturn(Optional.empty());\r\n\t\t\t\r\n\t\t\tDatasetLayerRef layerRef = mock(DatasetLayerRef.class);\r\n\t\t\twhen(layerRef.isGroupRef()).thenReturn(false);\r\n\t\t\twhen(layerRef.asDatasetRef()).thenReturn(layerRef);\r\n\t\t\twhen(layerRef.getLayer()).thenReturn(layer);\r\n\t\t\t\r\n\t\t\tlayers.add(layerRef);\r\n\t\t}\r\n\t\t\r\n\t\tGroupLayer groupLayer = mock(GroupLayer.class);\t\t\r\n\t\twhen(groupLayer.getName()).thenReturn(\"group0\");\r\n\t\twhen(groupLayer.getTitle()).thenReturn(\"groupTitle0\");\r\n\t\twhen(groupLayer.getAbstract()).thenReturn(\"groupAbstract0\");\r\n\t\twhen(groupLayer.getLayers()).thenReturn(layers);\r\n\t\twhen(groupLayer.getTiling()).thenReturn(Optional.empty());\r\n\t\t\r\n\t\tGroupLayerRef groupLayerRef = mock(GroupLayerRef.class);\r\n\t\twhen(groupLayerRef.isGroupRef()).thenReturn(true);\r\n\t\twhen(groupLayerRef.asGroupRef()).thenReturn(groupLayerRef);\r\n\t\twhen(groupLayerRef.getLayer()).thenReturn(groupLayer);\r\n\t\t\r\n\t\tService service = mock(Service.class);\r\n\t\twhen(service.getId()).thenReturn(\"service0\");\r\n\t\twhen(service.getName()).thenReturn(\"serviceName0\");\r\n\t\twhen(service.getRootId()).thenReturn(\"root\");\r\n\t\twhen(service.getLayers()).thenReturn(Collections.singletonList(groupLayerRef));\r\n\t\t\r\n\t\tsync.ask(geoServerService, new Ensure(service, new End()), Ack.class);\r\n\t\tsync.ask(recorder, new Wait(5 + numberOfLayers), Waited.class);\r\n\t\t\r\n\t\tRecording recording = sync.ask(recorder, new GetRecording(), Recording.class)\r\n\t\t\t.assertNext(EnsureWorkspace.class, workspace -> {\r\n\t\t\t\tassertEquals(\"serviceName0\", workspace.getWorkspaceId());\r\n\t\t\t})\r\n\t\t\t.assertNext(EnsureGroupLayer.class, group -> {\r\n\t\t\t\tassertEquals(\"group0\", group.getLayerId());\r\n\t\t\t\tassertEquals(\"groupTitle0\", group.getTitle());\r\n\t\t\t\tassertEquals(\"groupAbstract0\", group.getAbstract());\r\n\t\t\t});\r\n\t\t\r\n\t\tfor(int i = 0; i < numberOfLayers; i++) {\r\n\t\t\tString featureTypeId = \"layer\" + i;\r\n\t\t\tString tableName = \"tableName\" + i;\r\n\t\t\trecording.assertNext(EnsureFeatureTypeLayer.class, featureType -> {\r\n\t\t\t\tassertEquals(featureTypeId, featureType.getLayerId());\r\n\t\t\t\tassertEquals(tableName, featureType.getTableName());\r\n\t\t\t});\r\n\t\t}\r\n\t\t\t\r\n\t\trecording\r\n\t\t\t.assertNext(FinishEnsure.class)\r\n\t\t\t.assertNext(FinishEnsure.class)\r\n\t\t\t.assertNext(Terminated.class)\r\n\t\t\t.assertNotHasNext();\r\n\t}\r\n}\r\n"},"new_file":{"kind":"string","value":"publisher-service/src/test/java/nl/idgis/publisher/service/geoserver/EnsureServiceTest.java"},"old_contents":{"kind":"string","value":"package nl.idgis.publisher.service.geoserver;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.Arrays;\r\nimport java.util.Collections;\r\nimport java.util.List;\r\nimport java.util.Optional;\r\n\r\nimport org.junit.Before;\r\nimport org.junit.Test;\r\n\r\nimport com.typesafe.config.Config;\r\nimport com.typesafe.config.ConfigFactory;\r\nimport com.typesafe.config.ConfigValueFactory;\r\n\r\nimport akka.actor.ActorRef;\r\nimport akka.actor.ActorSystem;\r\nimport akka.actor.Props;\r\nimport akka.actor.Terminated;\r\nimport akka.actor.UntypedActor;\r\nimport akka.event.Logging;\r\nimport akka.event.LoggingAdapter;\r\nimport akka.japi.Procedure;\r\n\r\nimport nl.idgis.publisher.domain.web.tree.DatasetLayer;\r\nimport nl.idgis.publisher.domain.web.tree.DatasetLayerRef;\r\nimport nl.idgis.publisher.domain.web.tree.GroupLayer;\r\nimport nl.idgis.publisher.domain.web.tree.GroupLayerRef;\r\nimport nl.idgis.publisher.domain.web.tree.LayerRef;\r\nimport nl.idgis.publisher.domain.web.tree.Service;\r\nimport nl.idgis.publisher.domain.web.tree.Tiling;\r\n\r\nimport nl.idgis.publisher.protocol.messages.Ack;\r\nimport nl.idgis.publisher.recorder.Recorder;\r\nimport nl.idgis.publisher.recorder.Recording;\r\nimport nl.idgis.publisher.recorder.messages.GetRecording;\r\nimport nl.idgis.publisher.recorder.messages.RecordedMessage;\r\nimport nl.idgis.publisher.recorder.messages.Wait;\r\nimport nl.idgis.publisher.recorder.messages.Waited;\r\nimport nl.idgis.publisher.service.TestStyle;\r\nimport nl.idgis.publisher.service.geoserver.messages.EnsureFeatureTypeLayer;\r\nimport nl.idgis.publisher.service.geoserver.messages.EnsureGroupLayer;\r\nimport nl.idgis.publisher.service.geoserver.messages.EnsureStyle;\r\nimport nl.idgis.publisher.service.geoserver.messages.EnsureWorkspace;\r\nimport nl.idgis.publisher.service.geoserver.messages.Ensured;\r\nimport nl.idgis.publisher.service.geoserver.messages.FinishEnsure;\r\nimport nl.idgis.publisher.service.manager.messages.Style;\r\nimport nl.idgis.publisher.stream.messages.End;\r\nimport nl.idgis.publisher.utils.SyncAskHelper;\r\nimport nl.idgis.publisher.utils.UniqueNameGenerator;\r\nimport static org.junit.Assert.assertEquals;\r\nimport static org.junit.Assert.assertNotNull;\r\nimport static org.junit.Assert.assertTrue;\r\nimport static org.mockito.Mockito.mock;\r\nimport static org.mockito.Mockito.when;\r\n\r\npublic class EnsureServiceTest {\r\n\t\r\n\tprivate static class Ensure {\r\n\t\t\r\n\t\tprivate final List messages;\r\n\t\t\r\n\t\tEnsure(Object... messages) {\r\n\t\t\tthis.messages = Arrays.asList(messages);\r\n\t\t}\r\n\t\t\r\n\t\tpublic List getMessages() {\r\n\t\t\treturn messages;\r\n\t\t}\r\n\t}\r\n\t\r\n\tstatic class GeoServerServiceMock extends UntypedActor {\r\n\t\t\r\n\t\tprivate final LoggingAdapter log = Logging.getLogger(getContext().system(), this);\r\n\t\t\r\n\t\tprivate final UniqueNameGenerator nameGenerator = new UniqueNameGenerator();\r\n\t\t\r\n\t\tprivate final ActorRef recorder;\r\n\t\t\r\n\t\tpublic GeoServerServiceMock(ActorRef recorder) {\r\n\t\t\tthis.recorder = recorder;\r\n\t\t}\r\n\t\t\r\n\t\tpublic static Props props(ActorRef recorder) {\r\n\t\t\treturn Props.create(GeoServerServiceMock.class, recorder);\r\n\t\t}\r\n\t\t\r\n\t\tprivate void unexpected(Object msg) {\r\n\t\t\tif(msg instanceof Terminated) {\r\n\t\t\t\trecord(msg);\r\n\t\t\t} else {\t\t\t\r\n\t\t\t\tlog.error(\"unhandled: {}\", msg);\r\n\t\t\t\r\n\t\t\t\tunhandled(msg);\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tprivate void record(Object msg) {\r\n\t\t\tlog.debug(\"recorded: {}\", msg);\r\n\t\t\t\r\n\t\t\trecorder.tell(new RecordedMessage(getSelf(), getSender(), msg), getSelf());\r\n\t\t}\r\n\t\t\r\n\t\tprivate void ensured() {\r\n\t\t\tlog.debug(\"ensured\");\r\n\t\t\t\r\n\t\t\tgetSender().tell(new Ensured(), getSelf());\r\n\t\t}\r\n\t\t\r\n\t\tprivate Procedure layers(ActorRef initiator) {\r\n\t\t\treturn layers(initiator, 0);\r\n\t\t}\r\n\t\t\r\n\t\tprivate Procedure layers(ActorRef initiator, int depth) {\r\n\t\t\tlog.debug(\"group\");\r\n\t\t\t\r\n\t\t\treturn new Procedure() {\r\n\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic void apply(Object msg) throws Exception {\r\n\t\t\t\t\trecord(msg);\r\n\t\t\t\t\t\r\n\t\t\t\t\tif(msg instanceof EnsureGroupLayer) {\r\n\t\t\t\t\t\tensured();\r\n\t\t\t\t\t\tgetContext().become(layers(initiator, depth + 1), false);\r\n\t\t\t\t\t} else if(msg instanceof EnsureFeatureTypeLayer) {\r\n\t\t\t\t\t\tensured();\r\n\t\t\t\t\t} else if(msg instanceof FinishEnsure) {\r\n\t\t\t\t\t\tensured();\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tif(depth == 0) {\r\n\t\t\t\t\t\t\tlog.debug(\"ack\");\r\n\t\t\t\t\t\t\tinitiator.tell(new Ack(), getSelf());\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\tlog.debug(\"unbecome {}\", depth);\t\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tgetContext().unbecome();\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tunexpected(msg);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\t\t\t\t\r\n\t\t\t};\r\n\t\t}\r\n\t\t\r\n\t\tprivate Procedure provisioning(ActorRef initiator) {\r\n\t\t\tlog.debug(\"provisioning\");\r\n\t\t\t\r\n\t\t\treturn new Procedure() {\r\n\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic void apply(Object msg) throws Exception {\r\n\t\t\t\t\tif(msg instanceof EnsureStyle) {\r\n\t\t\t\t\t\trecord(msg);\r\n\t\t\t\t\t\tensured();\r\n\t\t\t\t\t} else if(msg instanceof EnsureWorkspace) {\r\n\t\t\t\t\t\trecord(msg);\r\n\t\t\t\t\t\tensured();\r\n\t\t\t\t\t\tgetContext().become(layers(initiator), false);\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tunexpected(msg);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t};\r\n\t\t}\r\n\r\n\t\t@Override\r\n\t\tpublic void onReceive(Object msg) throws Exception {\r\n\t\t\tif(msg instanceof Ensure) {\r\n\t\t\t\tActorRef ensureService = getContext().actorOf(EnsureService.props(), nameGenerator.getName(EnsureService.class));\r\n\t\t\t\t\r\n\t\t\t\tEnsure ensure = (Ensure)msg;\r\n\t\t\t\tensure.getMessages().stream()\r\n\t\t\t\t\t.forEach(item -> ensureService.tell(item, getSelf()));\r\n\t\t\t\t\r\n\t\t\t\tgetContext().watch(ensureService);\r\n\t\t\t\tgetContext().become(provisioning(getSender()), false);\t\t\t\t\r\n\t\t\t} else {\r\n\t\t\t\tlog.error(\"unexpected: {}\", msg);\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t}\r\n\t\r\n\tActorRef recorder, geoServerService;\r\n\t\r\n\tSyncAskHelper sync;\r\n\t\r\n\t@Before\r\n\tpublic void setUp() {\r\n\t\tConfig akkaConfig = ConfigFactory.empty()\r\n\t\t\t.withValue(\"akka.loggers\", ConfigValueFactory.fromIterable(Arrays.asList(\"akka.event.slf4j.Slf4jLogger\")))\r\n\t\t\t.withValue(\"akka.loglevel\", ConfigValueFactory.fromAnyRef(\"DEBUG\"));\r\n\t\t\t\r\n\t\tActorSystem actorSystem = ActorSystem.create(\"test\", akkaConfig);\r\n\t\t\r\n\t\trecorder = actorSystem.actorOf(Recorder.props(), \"recorder\");\t\t\r\n\t\tgeoServerService = actorSystem.actorOf(GeoServerServiceMock.props(recorder), \"service-mock\");\r\n\t\t\r\n\t\tsync = new SyncAskHelper(actorSystem);\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testEmptyService() throws Exception {\r\n\t\tService service = mock(Service.class);\r\n\t\twhen(service.getId()).thenReturn(\"service0\");\r\n\t\twhen(service.getName()).thenReturn(\"serviceName0\");\r\n\t\twhen(service.getRootId()).thenReturn(\"root\");\r\n\t\twhen(service.getLayers()).thenReturn(Collections.emptyList());\r\n\t\t\r\n\t\tsync.ask(geoServerService, new Ensure(service, new End()), Ack.class);\t\t\r\n\t\t\r\n\t\tsync.ask(recorder, new Wait(3), Waited.class);\r\n\t\tsync.ask(recorder, new GetRecording(), Recording.class)\t\t\t\r\n\t\t\t.assertNext(EnsureWorkspace.class, workspace -> {\r\n\t\t\t\tassertEquals(\"serviceName0\", workspace.getWorkspaceId());\r\n\t\t\t})\t\t\t\r\n\t\t\t.assertNext(FinishEnsure.class)\r\n\t\t\t.assertNext(Terminated.class)\r\n\t\t\t.assertNotHasNext();\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testSingleLayer() throws Exception {\r\n\t\tTiling tilingSettings = mock(Tiling.class);\r\n\t\t\r\n\t\tDatasetLayer datasetLayer = mock(DatasetLayer.class);\r\n\t\twhen(datasetLayer.getName()).thenReturn(\"layer0\");\r\n\t\twhen(datasetLayer.getTitle()).thenReturn(\"title0\");\r\n\t\twhen(datasetLayer.getAbstract()).thenReturn(\"abstract0\");\r\n\t\twhen(datasetLayer.getTableName()).thenReturn(\"tableName0\");\t\t\r\n\t\twhen(datasetLayer.getTiling()).thenReturn(Optional.of(tilingSettings));\r\n\t\twhen(datasetLayer.getKeywords()).thenReturn(Arrays.asList(\"keyword0\", \"keyword1\"));\r\n\t\t\r\n\t\tService service = mock(Service.class);\r\n\t\twhen(service.getId()).thenReturn(\"service0\");\r\n\t\twhen(service.getName()).thenReturn(\"serviceName0\");\r\n\t\twhen(service.getTitle()).thenReturn(\"serviceTitle0\");\r\n\t\twhen(service.getAbstract()).thenReturn(\"serviceAbstract0\");\r\n\t\twhen(service.getKeywords()).thenReturn(Arrays.asList(\"keyword0\", \"keyword1\", \"keyword2\"));\r\n\t\twhen(service.getTelephone()).thenReturn(\"serviceTelephone0\");\r\n\t\t\r\n\t\tDatasetLayerRef datasetLayerRef = mock(DatasetLayerRef.class);\r\n\t\twhen(datasetLayerRef.isGroupRef()).thenReturn(false);\r\n\t\twhen(datasetLayerRef.asDatasetRef()).thenReturn(datasetLayerRef);\r\n\t\twhen(datasetLayerRef.getLayer()).thenReturn(datasetLayer);\r\n\t\t\r\n\t\twhen(service.getRootId()).thenReturn(\"root\");\r\n\t\twhen(service.getLayers()).thenReturn(Collections.singletonList(datasetLayerRef));\r\n\t\t\r\n\t\tsync.ask(geoServerService, new Ensure(\r\n\t\t\tservice, \r\n\t\t\tnew Style(\"style0\", TestStyle.getGreenSld()),\r\n\t\t\tnew Style(\"style1\", TestStyle.getGreenSld()),\r\n\t\t\tnew End()), Ack.class);\r\n\t\t\r\n\t\tsync.ask(recorder, new Wait(4), Waited.class);\r\n\t\tsync.ask(recorder, new GetRecording(), Recording.class)\r\n\t\t\t.assertNext(EnsureStyle.class, style -> {\r\n\t\t\t\tassertEquals(\"style0\", style.getName());\r\n\t\t\t})\r\n\t\t\t.assertNext(EnsureStyle.class, style -> {\r\n\t\t\t\tassertEquals(\"style1\", style.getName());\r\n\t\t\t})\r\n\t\t\t.assertNext(EnsureWorkspace.class, workspace -> {\r\n\t\t\t\tassertEquals(\"serviceName0\", workspace.getWorkspaceId());\r\n\t\t\t\tassertEquals(\"serviceTitle0\", workspace.getTitle());\r\n\t\t\t\tassertEquals(\"serviceAbstract0\", workspace.getAbstract());\r\n\t\t\t\tassertEquals(Arrays.asList(\"keyword0\", \"keyword1\", \"keyword2\"), workspace.getKeywords());\r\n\t\t\t\t\r\n\t\t\t})\r\n\t\t\t.assertNext(EnsureFeatureTypeLayer.class, featureType -> {\r\n\t\t\t\tassertEquals(\"layer0\", featureType.getLayerId());\r\n\t\t\t\tassertEquals(\"title0\", featureType.getTitle());\r\n\t\t\t\tassertEquals(\"abstract0\", featureType.getAbstract());\r\n\t\t\t\tassertEquals(\"tableName0\", featureType.getTableName());\r\n\t\t\t\tassertTrue(featureType.getTiledLayer().isPresent());\r\n\t\t\t\t\r\n\t\t\t\tList keywords = featureType.getKeywords();\r\n\t\t\t\tassertNotNull(keywords);\r\n\t\t\t\tassertTrue(keywords.contains(\"keyword0\"));\r\n\t\t\t\tassertTrue(keywords.contains(\"keyword1\"));\r\n\t\t\t})\r\n\t\t\t.assertNext(FinishEnsure.class)\r\n\t\t\t.assertNext(Terminated.class)\r\n\t\t\t.assertNotHasNext();\t\t\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testGroup() throws Exception {\r\n\t\tfinal int numberOfLayers = 10;\r\n\t\t\r\n\t\tList> layers = new ArrayList<>();\r\n\t\tfor(int i = 0; i < numberOfLayers; i++) {\r\n\t\t\tDatasetLayer layer = mock(DatasetLayer.class);\t\t\t\r\n\t\t\twhen(layer.getName()).thenReturn(\"layer\" + i);\r\n\t\t\twhen(layer.getTableName()).thenReturn(\"tableName\" + i);\r\n\t\t\twhen(layer.getTiling()).thenReturn(Optional.empty());\r\n\t\t\t\r\n\t\t\tDatasetLayerRef layerRef = mock(DatasetLayerRef.class);\r\n\t\t\twhen(layerRef.isGroupRef()).thenReturn(false);\r\n\t\t\twhen(layerRef.asDatasetRef()).thenReturn(layerRef);\r\n\t\t\twhen(layerRef.getLayer()).thenReturn(layer);\r\n\t\t\t\r\n\t\t\tlayers.add(layerRef);\r\n\t\t}\r\n\t\t\r\n\t\tGroupLayer groupLayer = mock(GroupLayer.class);\t\t\r\n\t\twhen(groupLayer.getName()).thenReturn(\"group0\");\r\n\t\twhen(groupLayer.getTitle()).thenReturn(\"groupTitle0\");\r\n\t\twhen(groupLayer.getAbstract()).thenReturn(\"groupAbstract0\");\r\n\t\twhen(groupLayer.getLayers()).thenReturn(layers);\r\n\t\twhen(groupLayer.getTiling()).thenReturn(Optional.empty());\r\n\t\t\r\n\t\tGroupLayerRef groupLayerRef = mock(GroupLayerRef.class);\r\n\t\twhen(groupLayerRef.isGroupRef()).thenReturn(true);\r\n\t\twhen(groupLayerRef.asGroupRef()).thenReturn(groupLayerRef);\r\n\t\twhen(groupLayerRef.getLayer()).thenReturn(groupLayer);\r\n\t\t\r\n\t\tService service = mock(Service.class);\r\n\t\twhen(service.getId()).thenReturn(\"service0\");\r\n\t\twhen(service.getName()).thenReturn(\"serviceName0\");\r\n\t\twhen(service.getRootId()).thenReturn(\"root\");\r\n\t\twhen(service.getLayers()).thenReturn(Collections.singletonList(groupLayerRef));\r\n\t\t\r\n\t\tsync.ask(geoServerService, new Ensure(service, new End()), Ack.class);\r\n\t\tsync.ask(recorder, new Wait(5 + numberOfLayers), Waited.class);\r\n\t\t\r\n\t\tRecording recording = sync.ask(recorder, new GetRecording(), Recording.class)\r\n\t\t\t.assertNext(EnsureWorkspace.class, workspace -> {\r\n\t\t\t\tassertEquals(\"serviceName0\", workspace.getWorkspaceId());\r\n\t\t\t})\r\n\t\t\t.assertNext(EnsureGroupLayer.class, group -> {\r\n\t\t\t\tassertEquals(\"group0\", group.getLayerId());\r\n\t\t\t\tassertEquals(\"groupTitle0\", group.getTitle());\r\n\t\t\t\tassertEquals(\"groupAbstract0\", group.getAbstract());\r\n\t\t\t});\r\n\t\t\r\n\t\tfor(int i = 0; i < numberOfLayers; i++) {\r\n\t\t\tString featureTypeId = \"layer\" + i;\r\n\t\t\tString tableName = \"tableName\" + i;\r\n\t\t\trecording.assertNext(EnsureFeatureTypeLayer.class, featureType -> {\r\n\t\t\t\tassertEquals(featureTypeId, featureType.getLayerId());\r\n\t\t\t\tassertEquals(tableName, featureType.getTableName());\r\n\t\t\t});\r\n\t\t}\r\n\t\t\t\r\n\t\trecording\r\n\t\t\t.assertNext(FinishEnsure.class)\r\n\t\t\t.assertNext(FinishEnsure.class)\r\n\t\t\t.assertNext(Terminated.class)\r\n\t\t\t.assertNotHasNext();\r\n\t}\r\n}\r\n"},"message":{"kind":"string","value":"incorrect expected message count corrected"},"old_file":{"kind":"string","value":"publisher-service/src/test/java/nl/idgis/publisher/service/geoserver/EnsureServiceTest.java"},"subject":{"kind":"string","value":"incorrect expected message count corrected"},"git_diff":{"kind":"string","value":"ublisher-service/src/test/java/nl/idgis/publisher/service/geoserver/EnsureServiceTest.java\n \t\t\tnew Style(\"style1\", TestStyle.getGreenSld()),\n \t\t\tnew End()), Ack.class);\n \t\t\n\t\tsync.ask(recorder, new Wait(4), Waited.class);\n\t\tsync.ask(recorder, new Wait(6), Waited.class);\n \t\tsync.ask(recorder, new GetRecording(), Recording.class)\n \t\t\t.assertNext(EnsureStyle.class, style -> {\n \t\t\t\tassertEquals(\"style0\", style.getName());"}}},{"rowIdx":1931,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"f8de1476b5fbf99fded5e0f29b21ff2f4e34c4e3"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"sizebay/Sizebay-Catalog-API-Client,sizebay/Sizebay-Catalog-API-Client"},"new_contents":{"kind":"string","value":"package sizebay.catalog.client.model;\n\nimport lombok.*;\n\n@Getter\n@Setter\n@EqualsAndHashCode\n@AllArgsConstructor\n@NoArgsConstructor\npublic class ImportationError {\n private String message;\n private String brandName;\n private String genderItWasDesignedFor;\n private String availableSizes;\n private String categoryName;\n private String ageGroup;\n private String permalink;\n}\n"},"new_file":{"kind":"string","value":"src/main/java/sizebay/catalog/client/model/ImportationError.java"},"old_contents":{"kind":"string","value":"package sizebay.catalog.client.model;\n\nimport lombok.*;\n\n@Getter\n@Setter\n@EqualsAndHashCode\n@AllArgsConstructor\npublic class ImportationError {\n private String message;\n private String brandName;\n private String genderItWasDesignedFor;\n private String availableSizes;\n private String categoryName;\n private String ageGroup;\n private String permalink;\n}\n"},"message":{"kind":"string","value":"feat: add @NoArgsConstructor in ImportationError class\n"},"old_file":{"kind":"string","value":"src/main/java/sizebay/catalog/client/model/ImportationError.java"},"subject":{"kind":"string","value":"feat: add @NoArgsConstructor in ImportationError class"},"git_diff":{"kind":"string","value":"rc/main/java/sizebay/catalog/client/model/ImportationError.java\n @Setter\n @EqualsAndHashCode\n @AllArgsConstructor\n@NoArgsConstructor\n public class ImportationError {\n private String message;\n private String brandName;"}}},{"rowIdx":1932,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"lgpl-2.1"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"e381dce2fdedad2d2efd8fda6311d518b37b0b5d"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"tmyroadctfig/mpxj"},"new_contents":{"kind":"string","value":"/*\n * file: MPPUtility.java\n * author: Jon Iles\n * copyright: (c) Tapster Rock Limited 2002-2003\n * date: 05/01/2003\n */\n\n/*\n * This library is free software; you can redistribute it and/or modify it\n * under the terms of the GNU Lesser General Public License as published by the\n * Free Software Foundation; either version 2.1 of the License, or (at your\n * option) any later version.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\n * License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this library; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.\n */\n\npackage net.sf.mpxj.mpp;\n\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.text.DecimalFormat;\nimport java.util.Calendar;\nimport java.util.Date;\nimport java.util.TimeZone;\n\nimport net.sf.mpxj.CurrencySymbolPosition;\nimport net.sf.mpxj.Duration;\nimport net.sf.mpxj.ProjectFile;\nimport net.sf.mpxj.TimeUnit;\n\n\n\n/**\n * This class provides common functionality used by each of the classes\n * that read the different sections of the MPP file.\n */\nfinal class MPPUtility\n{\n /**\n * Private constructor to prevent instantiation.\n */\n private MPPUtility ()\n {\n // private constructor to prevent instantiation\n }\n\n /**\n * This method extracts a portion of a byte array and writes it into\n * another byte array.\n *\n * @param data Source data\n * @param offset Offset into source data\n * @param size Requied size to be extracted from the source data\n * @param buffer Destination buffer\n * @param bufferOffset Offset into destination buffer\n */\n public static final void getByteArray (byte[] data, int offset, int size, byte[] buffer, int bufferOffset)\n {\n for (int loop = 0; loop < size; loop++)\n {\n buffer[bufferOffset + loop] = data[offset + loop];\n }\n }\n\n /**\n * This method reads a single byte from the input array.\n *\n * @param data byte array of data\n * @param offset offset of byte data in the array\n * @return byte value\n */\n public static final int getByte (byte[] data, int offset)\n {\n int result = data[offset] & 0x0F;\n result += (((data[offset] >> 4) & 0x0F) * 16);\n return (result);\n }\n\n /**\n * This method reads a single byte from the input array.\n * The byte is assumed to be at the start of the array.\n *\n * @param data byte array of data\n * @return byte value\n */\n public static final int getByte (byte[] data)\n {\n return (getByte(data, 0));\n }\n\n /**\n * This method reads a two byte integer from the input array.\n *\n * @param data the input array\n * @param offset offset of integer data in the array\n * @return integer value\n */\n public static final int getShort (byte[] data, int offset)\n {\n int result = (data[offset] & 0x0F);\n result += (((data[offset] >> 4) & 0x0F) * 16);\n result += ((data[offset + 1] & 0x0F) * 256);\n result += (((data[offset + 1] >> 4) & 0x0F) * 4096);\n return (result);\n }\n\n /**\n * This method reads a two byte integer from the input array.\n * The integer is assumed to be at the start of the array.\n *\n * @param data the input array\n * @return integer value\n */\n public static final int getShort (byte[] data)\n {\n return (getShort(data, 0));\n }\n\n /**\n * This method reads a four byte integer from the input array.\n *\n * @param data the input array\n * @param offset offset of integer data in the array\n * @return integer value\n */\n public static final int getInt (byte[] data, int offset)\n {\n int result = (data[offset] & 0x0F);\n result += (((data[offset] >> 4) & 0x0F) * 16);\n result += ((data[offset + 1] & 0x0F) * 256);\n result += (((data[offset + 1] >> 4) & 0x0F) * 4096);\n result += ((data[offset + 2] & 0x0F) * 65536);\n result += (((data[offset + 2] >> 4) & 0x0F) * 1048576);\n result += ((data[offset + 3] & 0x0F) * 16777216);\n result += (((data[offset + 3] >> 4) & 0x0F) * 268435456);\n return (result);\n }\n\n /**\n * This method reads a four byte integer from the input array.\n * The integer is assumed to be at the start of the array.\n *\n * @param data the input array\n * @return integer value\n */\n public static final int getInt (byte[] data)\n {\n return (getInt(data, 0));\n }\n\n /**\n * This method reads an eight byte integer from the input array.\n *\n * @param data the input array\n * @param offset offset of integer data in the array\n * @return integer value\n */\n public static final long getLong (byte[] data, int offset)\n {\n long result = (data[offset] & 0x0F); // 0\n result += (((data[offset] >> 4) & 0x0F) * 16); // 1\n result += ((data[offset + 1] & 0x0F) * 256); // 2\n result += (((data[offset + 1] >> 4) & 0x0F) * 4096); // 3\n result += ((data[offset + 2] & 0x0F) * 65536); // 4\n result += (((data[offset + 2] >> 4) & 0x0F) * 1048576); // 5\n result += ((data[offset + 3] & 0x0F) * 16777216); // 6\n result += (((data[offset + 3] >> 4) & 0x0F) * 268435456); // 7\n result += ((data[offset + 4] & 0x0F) * 4294967296L); // 8\n result += (((data[offset + 4] >> 4) & 0x0F) * 68719476736L); // 9\n result += ((data[offset + 5] & 0x0F) * 1099511627776L); // 10\n result += (((data[offset + 5] >> 4) & 0x0F) * 17592186044416L); // 11\n result += ((data[offset + 6] & 0x0F) * 281474976710656L); // 12\n result += (((data[offset + 6] >> 4) & 0x0F) * 4503599627370496L); // 13\n result += ((data[offset + 7] & 0x0F) * 72057594037927936L); // 14\n result += (((data[offset + 7] >> 4) & 0x0F) * 1152921504606846976L); // 15\n return (result);\n }\n\n /**\n * This method reads a six byte long from the input array.\n *\n * @param data the input array\n * @param offset offset of integer data in the array\n * @return integer value\n */\n public static final long getLong6 (byte[] data, int offset)\n {\n long result = (data[offset] & 0x0F); // 0\n result += (((data[offset] >> 4) & 0x0F) * 16); // 1\n result += ((data[offset + 1] & 0x0F) * 256); // 2\n result += (((data[offset + 1] >> 4) & 0x0F) * 4096); // 3\n result += ((data[offset + 2] & 0x0F) * 65536); // 4\n result += (((data[offset + 2] >> 4) & 0x0F) * 1048576); // 5\n result += ((data[offset + 3] & 0x0F) * 16777216); // 6\n result += (((data[offset + 3] >> 4) & 0x0F) * 268435456); // 7\n result += ((data[offset + 4] & 0x0F) * 4294967296L); // 8\n result += (((data[offset + 4] >> 4) & 0x0F) * 68719476736L); // 9\n result += ((data[offset + 5] & 0x0F) * 1099511627776L); // 10\n result += (((data[offset + 5] >> 4) & 0x0F) * 17592186044416L); // 11\n\n return (result);\n }\n\n /**\n * This method reads a six byte long from the input array.\n * The integer is assumed to be at the start of the array.\n *\n * @param data the input array\n * @return integer value\n */\n public static final long getLong6 (byte[] data)\n {\n return (getLong6(data, 0));\n }\n\n /**\n * This method reads a eight byte integer from the input array.\n * The integer is assumed to be at the start of the array.\n *\n * @param data the input array\n * @return integer value\n */\n public static final long getLong (byte[] data)\n {\n return (getLong(data, 0));\n }\n\n /**\n * This method reads an eight byte double from the input array.\n *\n * @param data the input array\n * @param offset offset of double data in the array\n * @return double value\n */\n public static final double getDouble (byte[] data, int offset)\n {\n return (Double.longBitsToDouble(getLong(data, offset)));\n }\n\n /**\n * This method reads an eight byte double from the input array.\n * The double is assumed to be at the start of the array.\n *\n * @param data the input array\n * @return double value\n */\n public static final double getDouble (byte[] data)\n {\n return (Double.longBitsToDouble(getLong(data, 0)));\n }\n\n /**\n * Reads a date value. Note that an NA is represented as 65535 in the\n * MPP file. We represent this in Java using a null value. The actual\n * value in the MPP file is number of days since 31/12/1983.\n *\n * @param data byte array of data\n * @param offset location of data as offset into the array\n * @return date value\n */\n public static final Date getDate (byte[] data, int offset)\n {\n Date result;\n long days = getShort(data, offset);\n\n if (days == 65535)\n {\n result = null;\n }\n else\n {\n TimeZone tz = TimeZone.getDefault();\n result = new Date(EPOCH + (days * MS_PER_DAY) - tz.getRawOffset());\n }\n\n return (result);\n }\n\n /**\n * Reads a time value. The time is represented as tenths of a\n * minute since midnight.\n *\n * @param data byte array of data\n * @param offset location of data as offset into the array\n * @return time value\n */\n public static final Date getTime (byte[] data, int offset)\n {\n int time = getShort(data, offset) / 10;\n Calendar cal = Calendar.getInstance();\n cal.set(Calendar.HOUR_OF_DAY, (time / 60));\n cal.set(Calendar.MINUTE, (time % 60));\n cal.set(Calendar.SECOND, 0);\n cal.set(Calendar.MILLISECOND, 0);\n return (cal.getTime());\n }\n\n /**\n * Reads a time value. The time is represented as tenths of a\n * minute since midnight.\n *\n * @param data byte array of data\n * @return time value\n */\n public static final Date getTime (byte[] data)\n {\n return (getTime(data, 0));\n }\n\n /**\n * Reads a duration value in milliseconds. The time is represented as\n * tenths of a minute since midnight.\n *\n * @param data byte array of data\n * @param offset location of data as offset into the array\n * @return duration value\n */\n public static final long getDuration (byte[] data, int offset)\n {\n return ((getShort(data, offset) * MS_PER_MINUTE) / 10);\n }\n\n /**\n * Reads a combined date and time value.\n *\n * @param data byte array of data\n * @param offset location of data as offset into the array\n * @return time value\n */\n public static final Date getTimestamp (byte[] data, int offset)\n {\n Date result;\n\n long days = getShort(data, offset + 2);\n\n if (days == 65535)\n {\n result = null;\n }\n else\n {\n TimeZone tz = TimeZone.getDefault();\n long time = getShort(data, offset);\n if (time == 65535)\n {\n time = 0;\n }\n result = new Date((EPOCH + (days * MS_PER_DAY) + ((time * MS_PER_MINUTE) / 10)) - tz.getRawOffset());\n\n if (tz.inDaylightTime(result) == true)\n {\n int savings;\n\n if (HAS_DST_SAVINGS == true)\n {\n savings = tz.getDSTSavings();\n }\n else\n {\n savings = DEFAULT_DST_SAVINGS;\n }\n\n result = new Date(result.getTime() - savings);\n }\n }\n\n return (result);\n }\n\n /**\n * Reads a combined date and time value.\n * The value is assumed to be at the start of the array.\n *\n * @param data byte array of data\n * @return time value\n */\n public static final Date getTimestamp (byte[] data)\n {\n return (getTimestamp(data, 0));\n }\n\n /**\n * Reads a string of two byte characters from the input array.\n * This method assumes that the string finishes either at the\n * end of the array, or when char zero is encountered.\n * The value is assumed to be at the start of the array.\n *\n * @param data byte array of data\n * @return string value\n */\n public static final String getUnicodeString (byte[] data)\n {\n return (getUnicodeString(data, 0));\n }\n\n /**\n * Reads a string of two byte characters from the input array.\n * This method assumes that the string finishes either at the\n * end of the array, or when char zero is encountered.\n * The value starts at the position specified by the offset\n * parameter.\n *\n * @param data byte array of data\n * @param offset start point of unicode string\n * @return string value\n */\n public static final String getUnicodeString (byte[] data, int offset)\n {\n StringBuffer buffer = new StringBuffer();\n char c;\n\n for (int loop = offset; loop < (data.length - 1); loop += 2)\n {\n c = (char)getShort(data, loop);\n\n if (c == 0)\n {\n break;\n }\n\n buffer.append(c);\n }\n\n return (buffer.toString());\n }\n\n\n /**\n * Reads a string of two byte characters from the input array.\n * This method assumes that the string finishes either at the\n * end of the array, or when char zero is encountered, or\n * when a string of a certain length in bytes has been read.\n * The value starts at the position specified by the offset\n * parameter.\n *\n * @param data byte array of data\n * @param offset start point of unicode string\n * @param length length in bytes of the string\n * @return string value\n */\n public static final String getUnicodeString (byte[] data, int offset, int length)\n {\n StringBuffer buffer = new StringBuffer();\n char c;\n int loop = offset;\n int byteLength = 0;\n\n while (loop < (data.length - 1) && byteLength < length)\n {\n c = (char)getShort(data, loop);\n\n if (c == 0)\n {\n break;\n }\n\n buffer.append(c);\n\n loop += 2;\n byteLength += 2;\n }\n\n return (buffer.toString());\n }\n\n /**\n * Reads a string of single byte characters from the input array.\n * This method assumes that the string finishes either at the\n * end of the array, or when char zero is encountered.\n * The value is assumed to be at the start of the array.\n *\n * @param data byte array of data\n * @return string value\n */\n public static final String getString (byte[] data)\n {\n return (getString(data, 0));\n }\n\n /**\n * Reads a string of single byte characters from the input array.\n * This method assumes that the string finishes either at the\n * end of the array, or when char zero is encountered.\n * Redaing begins at the supplied offset into the array.\n *\n * @param data byte array of data\n * @param offset offset into the array\n * @return string value\n */\n public static final String getString (byte[] data, int offset)\n {\n StringBuffer buffer = new StringBuffer();\n char c;\n\n for (int loop = 0; offset+loop < data.length; loop++)\n {\n c = (char)data[offset+loop];\n\n if (c == 0)\n {\n break;\n }\n\n buffer.append(c);\n }\n\n return (buffer.toString());\n }\n\n /**\n * Reads a duration value. This method relies on the fact that\n * the units of the duration have been specified elsewhere.\n *\n * @param value Duration value\n * @param type type of units of the duration\n * @return Duration instance\n */\n public static final Duration getDuration (int value, TimeUnit type)\n {\n return (getDuration((double)value, type));\n }\n\n /**\n * Reads a duration value. This method relies on the fact that\n * the units of the duration have been specified elsewhere.\n *\n * @param value Duration value\n * @param type type of units of the duration\n * @return Duration instance\n */\n public static final Duration getDuration (double value, TimeUnit type)\n {\n double duration;\n\n switch (type.getValue())\n {\n case TimeUnit.MINUTES_VALUE:\n case TimeUnit.ELAPSED_MINUTES_VALUE:\n {\n duration = value / 10;\n break;\n }\n\n case TimeUnit.HOURS_VALUE:\n case TimeUnit.ELAPSED_HOURS_VALUE:\n {\n duration = value / 600;\n break;\n }\n\n case TimeUnit.DAYS_VALUE:\n case TimeUnit.ELAPSED_DAYS_VALUE:\n {\n duration = value / 4800;\n break;\n }\n\n case TimeUnit.WEEKS_VALUE:\n case TimeUnit.ELAPSED_WEEKS_VALUE:\n {\n duration = value / 24000;\n break;\n }\n\n case TimeUnit.MONTHS_VALUE:\n case TimeUnit.ELAPSED_MONTHS_VALUE:\n {\n duration = value / 96000;\n break;\n }\n\n default:\n {\n duration = value;\n break;\n }\n }\n\n return (Duration.getInstance(duration, type));\n }\n\n /**\n * This method converts between the duration units representation\n * used in the MPP file, and the standard MPX duration units.\n * If the supplied units are unrecognised, the units default to days.\n *\n * @param type MPP units\n * @return MPX units\n */\n public static final TimeUnit getDurationTimeUnits (int type)\n {\n TimeUnit units;\n\n switch (type & DURATION_UNITS_MASK)\n {\n case 3:\n {\n units = TimeUnit.MINUTES;\n break;\n }\n\n case 4:\n {\n units = TimeUnit.ELAPSED_MINUTES;\n break;\n }\n\n case 5:\n {\n units = TimeUnit.HOURS;\n break;\n }\n\n case 6:\n {\n units = TimeUnit.ELAPSED_HOURS;\n break;\n }\n\n case 8:\n {\n units = TimeUnit.ELAPSED_DAYS;\n break;\n }\n\n case 9:\n {\n units = TimeUnit.WEEKS;\n break;\n }\n\n case 10:\n {\n units = TimeUnit.ELAPSED_WEEKS;\n break;\n }\n\n case 11:\n {\n units = TimeUnit.MONTHS;\n break;\n }\n\n case 12:\n {\n units = TimeUnit.ELAPSED_MONTHS;\n break;\n }\n\n default:\n case 7:\n {\n units = TimeUnit.DAYS;\n break;\n }\n }\n\n return (units);\n }\n\n /**\n * Given a duration and the time units for the duration extracted from an MPP\n * file, this method creates a new Duration to represent the given\n * duration. This instance has been adjusted to take into account the\n * number of \"hours per day\" specified for the current project.\n *\n * @param file parent file\n * @param duration duration length\n * @param timeUnit duration units\n * @return Duration instance\n */\n public static Duration getAdjustedDuration (ProjectFile file, int duration, TimeUnit timeUnit)\n {\n Duration result;\n switch (timeUnit.getValue())\n {\n case TimeUnit.DAYS_VALUE:\n {\n double unitsPerDay = file.getProjectHeader().getMinutesPerDay().doubleValue() * 10d;\n double totalDays = duration / unitsPerDay;\n result = Duration.getInstance(totalDays, timeUnit);\n break;\n }\n\n case TimeUnit.ELAPSED_DAYS_VALUE:\n {\n double unitsPerDay = 24d * 600d;\n double totalDays = duration / unitsPerDay;\n result = Duration.getInstance(totalDays, timeUnit);\n break;\n }\n\n case TimeUnit.ELAPSED_WEEKS_VALUE:\n {\n double unitsPerWeek = (60 * 24 * 7 * 10);\n double totalWeeks = duration / unitsPerWeek;\n result = Duration.getInstance(totalWeeks, timeUnit);\n break;\n }\n\n case TimeUnit.ELAPSED_MONTHS_VALUE:\n {\n double unitsPerMonth = (60 * 24 * 29 * 10);\n double totalMonths = duration / unitsPerMonth;\n result = Duration.getInstance(totalMonths, timeUnit);\n break;\n }\n \n default:\n {\n result = getDuration(duration, timeUnit);\n break;\n }\n }\n\n return (result);\n }\n\n\n /**\n * This method maps from the value used to specify default work units in the\n * MPP file to a standard TimeUnit.\n *\n * @param value Default work units\n * @return TimeUnit value\n */\n public static TimeUnit getWorkTimeUnits (int value)\n {\n TimeUnit result;\n\n switch (value)\n {\n case 1:\n {\n result = TimeUnit.MINUTES;\n break;\n }\n\n case 3:\n {\n result = TimeUnit.DAYS;\n break;\n }\n\n case 4:\n {\n result = TimeUnit.WEEKS;\n break;\n }\n\n case 2:default:\n {\n result = TimeUnit.HOURS;\n break;\n }\n }\n\n return (result);\n }\n\n /**\n * This method maps the currency symbol position from the\n * representation used in the MPP file to the representation\n * used by MPX.\n *\n * @param value MPP symbol position\n * @return MPX symbol position\n */\n public static CurrencySymbolPosition getSymbolPosition (int value)\n {\n CurrencySymbolPosition result;\n\n switch (value)\n {\n case 1:\n {\n result = CurrencySymbolPosition.AFTER;\n break;\n }\n\n case 2:\n {\n result = CurrencySymbolPosition.BEFORE_WITH_SPACE;\n break;\n }\n\n case 3:\n {\n result = CurrencySymbolPosition.AFTER_WITH_SPACE;\n break;\n }\n\n case 0:default:\n {\n result = CurrencySymbolPosition.BEFORE;\n break;\n }\n }\n\n return (result);\n }\n\n /**\n * Utility methdo to remove ampersands embedded in names.\n *\n * @param name name text\n * @return name text without embedded ampersands\n */\n public static final String removeAmpersands (String name)\n {\n if (name != null)\n {\n if (name.indexOf('&') != -1)\n {\n StringBuffer sb = new StringBuffer();\n int index = 0;\n char c;\n\n while (index < name.length())\n {\n c = name.charAt(index);\n if (c != '&')\n {\n sb.append(c);\n }\n ++index;\n }\n\n name = sb.toString();\n }\n }\n\n return (name);\n }\n\n /**\n * This method allows a subsection of a byte array to be copied.\n *\n * @param data source data\n * @param offset offset into the source data\n * @param size length of the source data to copy\n * @return new byte array containing copied data\n */\n public static final byte[] cloneSubArray (byte[] data, int offset, int size)\n {\n byte[] newData = new byte[size];\n System.arraycopy(data, offset, newData, 0, size);\n return (newData);\n }\n\n /**\n * This method generates a formatted version of the data contained\n * in a byte array. The data is written both in hex, and as ASCII\n * characters.\n *\n * @param buffer data to be displayed\n * @param offset offset of start of data to be displayed\n * @param length length of data to be displayed\n * @param ascii flag indicating whether ASCII equivalent chars should also be displayed\n * @return formatted string\n */\n public static final String hexdump (byte[] buffer, int offset, int length, boolean ascii)\n {\n StringBuffer sb = new StringBuffer();\n\n if (buffer != null)\n {\n char c;\n int loop;\n int count = offset + length;\n\n for (loop = offset; loop < count; loop++)\n {\n sb.append(\" \");\n sb.append(HEX_DIGITS[(buffer[loop] & 0xF0) >> 4]);\n sb.append(HEX_DIGITS[buffer[loop] & 0x0F]);\n }\n\n if (ascii == true)\n {\n sb.append(\" \");\n\n for (loop = offset; loop < count; loop++)\n {\n c = (char)buffer[loop];\n\n if ((c > 200) || (c < 27))\n {\n c = ' ';\n }\n\n sb.append(c);\n }\n }\n }\n\n return (sb.toString());\n }\n\n /**\n * This method generates a formatted version of the data contained\n * in a byte array. The data is written both in hex, and as ASCII\n * characters.\n *\n * @param buffer data to be displayed\n * @param ascii flag indicating whether ASCII equivalent chars should also be displayed\n * @return formatted string\n */\n public static final String hexdump (byte[] buffer, boolean ascii)\n {\n int length = 0;\n\n if (buffer != null)\n {\n length = buffer.length;\n }\n\n return (hexdump(buffer, 0, length, ascii));\n }\n\n /**\n * This method generates a formatted version of the data contained\n * in a byte array. The data is written both in hex, and as ASCII\n * characters. The data is organised into fixed width columns.\n *\n * @param buffer data to be displayed\n * @param ascii flag indicating whether ASCII equivalent chars should also be displayed\n * @param columns number of columns\n * @param prefix prefix to be added before the start of the data\n * @return formatted string\n */\n public static final String hexdump (byte[] buffer, boolean ascii, int columns, String prefix)\n {\n StringBuffer sb = new StringBuffer();\n if (buffer != null)\n {\n int index = 0;\n DecimalFormat df = new DecimalFormat(\"00000\");\n\n while (index < buffer.length)\n {\n if (index + columns > buffer.length)\n {\n columns = buffer.length - index;\n }\n\n sb.append (prefix);\n sb.append (df.format(index));\n sb.append (\":\");\n sb.append (hexdump(buffer, index, columns, ascii));\n sb.append ('\\n');\n\n index += columns;\n }\n }\n\n return (sb.toString());\n }\n\n /**\n * This method generates a formatted version of the data contained\n * in a byte array. The data is written both in hex, and as ASCII\n * characters. The data is organised into fixed width columns.\n * \n * @param buffer data to be displayed\n * @param offset offset into buffer\n * @param length number of bytes to display\n * @param ascii flag indicating whether ASCII equivalent chars should also be displayed\n * @param columns number of columns\n * @param prefix prefix to be added before the start of the data\n * @return formatted string\n */\n public static final String hexdump (byte[] buffer, int offset, int length, boolean ascii, int columns, String prefix)\n {\n StringBuffer sb = new StringBuffer();\n if (buffer != null)\n {\n int index = offset;\n DecimalFormat df = new DecimalFormat(\"00000\");\n\n while (index < (offset+length))\n {\n if (index + columns > (offset+length))\n {\n columns = (offset+length) - index;\n }\n\n sb.append (prefix);\n sb.append (df.format(index));\n sb.append (\":\");\n sb.append (hexdump(buffer, index, columns, ascii));\n sb.append ('\\n');\n\n index += columns;\n }\n }\n\n return (sb.toString());\n }\n \n /**\n * Writes a hex dump to a file for a large byte array.\n *\n * @param fileName output file name\n * @param data target data\n */\n public static final void fileHexDump (String fileName, byte[] data)\n {\n try\n {\n FileOutputStream os = new FileOutputStream(fileName);\n os.write(hexdump(data, true, 16, \"\").getBytes());\n os.close();\n }\n\n catch (IOException ex)\n {\n ex.printStackTrace();\n }\n }\n\n /**\n * Writes a hex dump to a file from a POI input stream.\n * Note that this assumes that the complete size of the data in\n * the stream is returned by the available() method.\n *\n * @param fileName output file name\n * @param is input stream\n */\n public static final void fileHexDump (String fileName, InputStream is)\n {\n try\n {\n byte[] data = new byte[is.available()];\n is.read(data);\n fileHexDump(fileName, data);\n }\n\n catch (IOException ex)\n {\n ex.printStackTrace();\n }\n }\n\n /**\n * Writes a large byte array to a file.\n *\n * @param fileName output file name\n * @param data target data\n */\n public static final void fileDump (String fileName, byte[] data)\n {\n try\n {\n FileOutputStream os = new FileOutputStream(fileName);\n os.write(data);\n os.close();\n }\n\n catch (IOException ex)\n {\n ex.printStackTrace();\n }\n }\n\n /**\n * Epoch date for MPP date calculation is 31/12/1983. This constant\n * is that date expressed in milliseconds using the Java date epoch.\n */\n private static final long EPOCH = 441676800000L;\n\n /**\n * Number of milliseconds per day.\n */\n private static final long MS_PER_DAY = 24 * 60 * 60 * 1000;\n\n /**\n * Number of milliseconds per minute.\n */\n private static final long MS_PER_MINUTE = 60 * 1000;\n\n /**\n * Constants used to convert bytes to hex digits.\n */\n private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};\n\n /**\n * Mask used to remove flags from the duration units field.\n */\n private static final int DURATION_UNITS_MASK = 0x1F;\n\n /**\n * Default value to use for DST savings if we are using a version\n * of Java < 1.4.\n */\n private static final int DEFAULT_DST_SAVINGS = 3600000;\n\n /**\n * Flag used to indicate the existance of the getDSTSavings\n * method that was introduced in Java 1.4.\n */\n private static boolean HAS_DST_SAVINGS;\n\n static\n {\n Class tz = TimeZone.class;\n\n try\n {\n tz.getMethod(\"getDSTSavings\", (Class[])null);\n HAS_DST_SAVINGS = true;\n }\n\n catch (NoSuchMethodException ex)\n {\n HAS_DST_SAVINGS = false;\n }\n }\n}\n"},"new_file":{"kind":"string","value":"net/sf/mpxj/mpp/MPPUtility.java"},"old_contents":{"kind":"string","value":"/*\n * file: MPPUtility.java\n * author: Jon Iles\n * copyright: (c) Tapster Rock Limited 2002-2003\n * date: 05/01/2003\n */\n\n/*\n * This library is free software; you can redistribute it and/or modify it\n * under the terms of the GNU Lesser General Public License as published by the\n * Free Software Foundation; either version 2.1 of the License, or (at your\n * option) any later version.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\n * License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this library; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.\n */\n\npackage net.sf.mpxj.mpp;\n\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.text.DecimalFormat;\nimport java.util.Calendar;\nimport java.util.Date;\nimport java.util.TimeZone;\n\nimport net.sf.mpxj.CurrencySymbolPosition;\nimport net.sf.mpxj.Duration;\nimport net.sf.mpxj.ProjectFile;\nimport net.sf.mpxj.TimeUnit;\n\n\n\n/**\n * This class provides common functionality used by each of the classes\n * that read the different sections of the MPP file.\n */\nfinal class MPPUtility\n{\n /**\n * Private constructor to prevent instantiation.\n */\n private MPPUtility ()\n {\n // private constructor to prevent instantiation\n }\n\n /**\n * This method extracts a portion of a byte array and writes it into\n * another byte array.\n *\n * @param data Source data\n * @param offset Offset into source data\n * @param size Requied size to be extracted from the source data\n * @param buffer Destination buffer\n * @param bufferOffset Offset into destination buffer\n */\n public static final void getByteArray (byte[] data, int offset, int size, byte[] buffer, int bufferOffset)\n {\n for (int loop = 0; loop < size; loop++)\n {\n buffer[bufferOffset + loop] = data[offset + loop];\n }\n }\n\n /**\n * This method reads a single byte from the input array.\n *\n * @param data byte array of data\n * @param offset offset of byte data in the array\n * @return byte value\n */\n public static final int getByte (byte[] data, int offset)\n {\n int result = data[offset] & 0x0F;\n result += (((data[offset] >> 4) & 0x0F) * 16);\n return (result);\n }\n\n /**\n * This method reads a single byte from the input array.\n * The byte is assumed to be at the start of the array.\n *\n * @param data byte array of data\n * @return byte value\n */\n public static final int getByte (byte[] data)\n {\n return (getByte(data, 0));\n }\n\n /**\n * This method reads a two byte integer from the input array.\n *\n * @param data the input array\n * @param offset offset of integer data in the array\n * @return integer value\n */\n public static final int getShort (byte[] data, int offset)\n {\n int result = (data[offset] & 0x0F);\n result += (((data[offset] >> 4) & 0x0F) * 16);\n result += ((data[offset + 1] & 0x0F) * 256);\n result += (((data[offset + 1] >> 4) & 0x0F) * 4096);\n return (result);\n }\n\n /**\n * This method reads a two byte integer from the input array.\n * The integer is assumed to be at the start of the array.\n *\n * @param data the input array\n * @return integer value\n */\n public static final int getShort (byte[] data)\n {\n return (getShort(data, 0));\n }\n\n /**\n * This method reads a four byte integer from the input array.\n *\n * @param data the input array\n * @param offset offset of integer data in the array\n * @return integer value\n */\n public static final int getInt (byte[] data, int offset)\n {\n int result = (data[offset] & 0x0F);\n result += (((data[offset] >> 4) & 0x0F) * 16);\n result += ((data[offset + 1] & 0x0F) * 256);\n result += (((data[offset + 1] >> 4) & 0x0F) * 4096);\n result += ((data[offset + 2] & 0x0F) * 65536);\n result += (((data[offset + 2] >> 4) & 0x0F) * 1048576);\n result += ((data[offset + 3] & 0x0F) * 16777216);\n result += (((data[offset + 3] >> 4) & 0x0F) * 268435456);\n return (result);\n }\n\n /**\n * This method reads a four byte integer from the input array.\n * The integer is assumed to be at the start of the array.\n *\n * @param data the input array\n * @return integer value\n */\n public static final int getInt (byte[] data)\n {\n return (getInt(data, 0));\n }\n\n /**\n * This method reads an eight byte integer from the input array.\n *\n * @param data the input array\n * @param offset offset of integer data in the array\n * @return integer value\n */\n public static final long getLong (byte[] data, int offset)\n {\n long result = (data[offset] & 0x0F); // 0\n result += (((data[offset] >> 4) & 0x0F) * 16); // 1\n result += ((data[offset + 1] & 0x0F) * 256); // 2\n result += (((data[offset + 1] >> 4) & 0x0F) * 4096); // 3\n result += ((data[offset + 2] & 0x0F) * 65536); // 4\n result += (((data[offset + 2] >> 4) & 0x0F) * 1048576); // 5\n result += ((data[offset + 3] & 0x0F) * 16777216); // 6\n result += (((data[offset + 3] >> 4) & 0x0F) * 268435456); // 7\n result += ((data[offset + 4] & 0x0F) * 4294967296L); // 8\n result += (((data[offset + 4] >> 4) & 0x0F) * 68719476736L); // 9\n result += ((data[offset + 5] & 0x0F) * 1099511627776L); // 10\n result += (((data[offset + 5] >> 4) & 0x0F) * 17592186044416L); // 11\n result += ((data[offset + 6] & 0x0F) * 281474976710656L); // 12\n result += (((data[offset + 6] >> 4) & 0x0F) * 4503599627370496L); // 13\n result += ((data[offset + 7] & 0x0F) * 72057594037927936L); // 14\n result += (((data[offset + 7] >> 4) & 0x0F) * 1152921504606846976L); // 15\n return (result);\n }\n\n /**\n * This method reads a six byte long from the input array.\n *\n * @param data the input array\n * @param offset offset of integer data in the array\n * @return integer value\n */\n public static final long getLong6 (byte[] data, int offset)\n {\n long result = (data[offset] & 0x0F); // 0\n result += (((data[offset] >> 4) & 0x0F) * 16); // 1\n result += ((data[offset + 1] & 0x0F) * 256); // 2\n result += (((data[offset + 1] >> 4) & 0x0F) * 4096); // 3\n result += ((data[offset + 2] & 0x0F) * 65536); // 4\n result += (((data[offset + 2] >> 4) & 0x0F) * 1048576); // 5\n result += ((data[offset + 3] & 0x0F) * 16777216); // 6\n result += (((data[offset + 3] >> 4) & 0x0F) * 268435456); // 7\n result += ((data[offset + 4] & 0x0F) * 4294967296L); // 8\n result += (((data[offset + 4] >> 4) & 0x0F) * 68719476736L); // 9\n result += ((data[offset + 5] & 0x0F) * 1099511627776L); // 10\n result += (((data[offset + 5] >> 4) & 0x0F) * 17592186044416L); // 11\n\n return (result);\n }\n\n /**\n * This method reads a six byte long from the input array.\n * The integer is assumed to be at the start of the array.\n *\n * @param data the input array\n * @return integer value\n */\n public static final long getLong6 (byte[] data)\n {\n return (getLong6(data, 0));\n }\n\n /**\n * This method reads a eight byte integer from the input array.\n * The integer is assumed to be at the start of the array.\n *\n * @param data the input array\n * @return integer value\n */\n public static final long getLong (byte[] data)\n {\n return (getLong(data, 0));\n }\n\n /**\n * This method reads an eight byte double from the input array.\n *\n * @param data the input array\n * @param offset offset of double data in the array\n * @return double value\n */\n public static final double getDouble (byte[] data, int offset)\n {\n return (Double.longBitsToDouble(getLong(data, offset)));\n }\n\n /**\n * This method reads an eight byte double from the input array.\n * The double is assumed to be at the start of the array.\n *\n * @param data the input array\n * @return double value\n */\n public static final double getDouble (byte[] data)\n {\n return (Double.longBitsToDouble(getLong(data, 0)));\n }\n\n /**\n * Reads a date value. Note that an NA is represented as 65535 in the\n * MPP file. We represent this in Java using a null value. The actual\n * value in the MPP file is number of days since 31/12/1983.\n *\n * @param data byte array of data\n * @param offset location of data as offset into the array\n * @return date value\n */\n public static final Date getDate (byte[] data, int offset)\n {\n Date result;\n long days = getShort(data, offset);\n\n if (days == 65535)\n {\n result = null;\n }\n else\n {\n TimeZone tz = TimeZone.getDefault();\n result = new Date(EPOCH + (days * MS_PER_DAY) - tz.getRawOffset());\n }\n\n return (result);\n }\n\n /**\n * Reads a time value. The time is represented as tenths of a\n * minute since midnight.\n *\n * @param data byte array of data\n * @param offset location of data as offset into the array\n * @return time value\n */\n public static final Date getTime (byte[] data, int offset)\n {\n int time = getShort(data, offset) / 10;\n Calendar cal = Calendar.getInstance();\n cal.set(Calendar.HOUR_OF_DAY, (time / 60));\n cal.set(Calendar.MINUTE, (time % 60));\n cal.set(Calendar.SECOND, 0);\n cal.set(Calendar.MILLISECOND, 0);\n return (cal.getTime());\n }\n\n /**\n * Reads a time value. The time is represented as tenths of a\n * minute since midnight.\n *\n * @param data byte array of data\n * @return time value\n */\n public static final Date getTime (byte[] data)\n {\n return (getTime(data, 0));\n }\n\n /**\n * Reads a duration value in milliseconds. The time is represented as\n * tenths of a minute since midnight.\n *\n * @param data byte array of data\n * @param offset location of data as offset into the array\n * @return duration value\n */\n public static final long getDuration (byte[] data, int offset)\n {\n return ((getShort(data, offset) * MS_PER_MINUTE) / 10);\n }\n\n /**\n * Reads a combined date and time value.\n *\n * @param data byte array of data\n * @param offset location of data as offset into the array\n * @return time value\n */\n public static final Date getTimestamp (byte[] data, int offset)\n {\n Date result;\n\n long days = getShort(data, offset + 2);\n\n if (days == 65535)\n {\n result = null;\n }\n else\n {\n TimeZone tz = TimeZone.getDefault();\n long time = getShort(data, offset);\n if (time == 65535)\n {\n time = 0;\n }\n result = new Date((EPOCH + (days * MS_PER_DAY) + ((time * MS_PER_MINUTE) / 10)) - tz.getRawOffset());\n\n if (tz.inDaylightTime(result) == true)\n {\n int savings;\n\n if (HAS_DST_SAVINGS == true)\n {\n savings = tz.getDSTSavings();\n }\n else\n {\n savings = DEFAULT_DST_SAVINGS;\n }\n\n result = new Date(result.getTime() - savings);\n }\n }\n\n return (result);\n }\n\n /**\n * Reads a combined date and time value.\n * The value is assumed to be at the start of the array.\n *\n * @param data byte array of data\n * @return time value\n */\n public static final Date getTimestamp (byte[] data)\n {\n return (getTimestamp(data, 0));\n }\n\n /**\n * Reads a string of two byte characters from the input array.\n * This method assumes that the string finishes either at the\n * end of the array, or when char zero is encountered.\n * The value is assumed to be at the start of the array.\n *\n * @param data byte array of data\n * @return string value\n */\n public static final String getUnicodeString (byte[] data)\n {\n return (getUnicodeString(data, 0));\n }\n\n /**\n * Reads a string of two byte characters from the input array.\n * This method assumes that the string finishes either at the\n * end of the array, or when char zero is encountered.\n * The value starts at the position specified by the offset\n * parameter.\n *\n * @param data byte array of data\n * @param offset start point of unicode string\n * @return string value\n */\n public static final String getUnicodeString (byte[] data, int offset)\n {\n StringBuffer buffer = new StringBuffer();\n char c;\n\n for (int loop = offset; loop < (data.length - 1); loop += 2)\n {\n c = (char)getShort(data, loop);\n\n if (c == 0)\n {\n break;\n }\n\n buffer.append(c);\n }\n\n return (buffer.toString());\n }\n\n\n /**\n * Reads a string of two byte characters from the input array.\n * This method assumes that the string finishes either at the\n * end of the array, or when char zero is encountered, or\n * when a string of a certain length in bytes has been read.\n * The value starts at the position specified by the offset\n * parameter.\n *\n * @param data byte array of data\n * @param offset start point of unicode string\n * @param length length in bytes of the string\n * @return string value\n */\n public static final String getUnicodeString (byte[] data, int offset, int length)\n {\n StringBuffer buffer = new StringBuffer();\n char c;\n int loop = offset;\n int byteLength = 0;\n\n while (loop < (data.length - 1) && byteLength < length)\n {\n c = (char)getShort(data, loop);\n\n if (c == 0)\n {\n break;\n }\n\n buffer.append(c);\n\n loop += 2;\n byteLength += 2;\n }\n\n return (buffer.toString());\n }\n\n /**\n * Reads a string of single byte characters from the input array.\n * This method assumes that the string finishes either at the\n * end of the array, or when char zero is encountered.\n * The value is assumed to be at the start of the array.\n *\n * @param data byte array of data\n * @return string value\n */\n public static final String getString (byte[] data)\n {\n return (getString(data, 0));\n }\n\n /**\n * Reads a string of single byte characters from the input array.\n * This method assumes that the string finishes either at the\n * end of the array, or when char zero is encountered.\n * Redaing begins at the supplied offset into the array.\n *\n * @param data byte array of data\n * @param offset offset into the array\n * @return string value\n */\n public static final String getString (byte[] data, int offset)\n {\n StringBuffer buffer = new StringBuffer();\n char c;\n\n for (int loop = 0; offset+loop < data.length; loop++)\n {\n c = (char)data[offset+loop];\n\n if (c == 0)\n {\n break;\n }\n\n buffer.append(c);\n }\n\n return (buffer.toString());\n }\n\n /**\n * Reads a duration value. This method relies on the fact that\n * the units of the duration have been specified elsewhere.\n *\n * @param value Duration value\n * @param type type of units of the duration\n * @return Duration instance\n */\n public static final Duration getDuration (int value, TimeUnit type)\n {\n return (getDuration((double)value, type));\n }\n\n /**\n * Reads a duration value. This method relies on the fact that\n * the units of the duration have been specified elsewhere.\n *\n * @param value Duration value\n * @param type type of units of the duration\n * @return Duration instance\n */\n public static final Duration getDuration (double value, TimeUnit type)\n {\n double duration;\n\n switch (type.getValue())\n {\n case TimeUnit.MINUTES_VALUE:\n case TimeUnit.ELAPSED_MINUTES_VALUE:\n {\n duration = value / 10;\n break;\n }\n\n case TimeUnit.HOURS_VALUE:\n case TimeUnit.ELAPSED_HOURS_VALUE:\n {\n duration = value / 600;\n break;\n }\n\n case TimeUnit.DAYS_VALUE:\n case TimeUnit.ELAPSED_DAYS_VALUE:\n {\n duration = value / 4800;\n break;\n }\n\n case TimeUnit.WEEKS_VALUE:\n case TimeUnit.ELAPSED_WEEKS_VALUE:\n {\n duration = value / 24000;\n break;\n }\n\n case TimeUnit.MONTHS_VALUE:\n case TimeUnit.ELAPSED_MONTHS_VALUE:\n {\n duration = value / 96000;\n break;\n }\n\n default:\n {\n duration = value;\n break;\n }\n }\n\n return (Duration.getInstance(duration, type));\n }\n\n /**\n * This method converts between the duration units representation\n * used in the MPP file, and the standard MPX duration units.\n * If the supplied units are unrecognised, the units default to days.\n *\n * @param type MPP units\n * @return MPX units\n */\n public static final TimeUnit getDurationTimeUnits (int type)\n {\n TimeUnit units;\n\n switch (type & DURATION_UNITS_MASK)\n {\n case 3:\n {\n units = TimeUnit.MINUTES;\n break;\n }\n\n case 4:\n {\n units = TimeUnit.ELAPSED_MINUTES;\n break;\n }\n\n case 5:\n {\n units = TimeUnit.HOURS;\n break;\n }\n\n case 6:\n {\n units = TimeUnit.ELAPSED_HOURS;\n break;\n }\n\n case 8:\n {\n units = TimeUnit.ELAPSED_DAYS;\n break;\n }\n\n case 9:\n {\n units = TimeUnit.WEEKS;\n break;\n }\n\n case 10:\n {\n units = TimeUnit.ELAPSED_WEEKS;\n break;\n }\n\n case 11:\n {\n units = TimeUnit.MONTHS;\n break;\n }\n\n case 12:\n {\n units = TimeUnit.ELAPSED_MONTHS;\n break;\n }\n\n default:\n case 7:\n {\n units = TimeUnit.DAYS;\n break;\n }\n }\n\n return (units);\n }\n\n /**\n * Given a duration and the time units for the duration extracted from an MPP\n * file, this method creates a new Duration to represent the given\n * duration. This instance has been adjusted to take into account the\n * number of \"hours per day\" specified for the current project.\n *\n * @param file parent file\n * @param duration duration length\n * @param timeUnit duration units\n * @return Duration instance\n */\n public static Duration getAdjustedDuration (ProjectFile file, int duration, TimeUnit timeUnit)\n {\n Duration result;\n switch (timeUnit.getValue())\n {\n case TimeUnit.DAYS_VALUE:\n {\n double unitsPerDay = file.getProjectHeader().getMinutesPerDay().doubleValue() * 10d;\n double totalDays = duration / unitsPerDay;\n result = Duration.getInstance(totalDays, timeUnit);\n break;\n }\n\n case TimeUnit.ELAPSED_DAYS_VALUE:\n {\n double unitsPerDay = 24d * 600d;\n double totalDays = duration / unitsPerDay;\n result = Duration.getInstance(totalDays, timeUnit);\n break;\n }\n\n default:\n {\n result = getDuration(duration, timeUnit);\n break;\n }\n }\n\n return (result);\n }\n\n\n /**\n * This method maps from the value used to specify default work units in the\n * MPP file to a standard TimeUnit.\n *\n * @param value Default work units\n * @return TimeUnit value\n */\n public static TimeUnit getWorkTimeUnits (int value)\n {\n TimeUnit result;\n\n switch (value)\n {\n case 1:\n {\n result = TimeUnit.MINUTES;\n break;\n }\n\n case 3:\n {\n result = TimeUnit.DAYS;\n break;\n }\n\n case 4:\n {\n result = TimeUnit.WEEKS;\n break;\n }\n\n case 2:default:\n {\n result = TimeUnit.HOURS;\n break;\n }\n }\n\n return (result);\n }\n\n /**\n * This method maps the currency symbol position from the\n * representation used in the MPP file to the representation\n * used by MPX.\n *\n * @param value MPP symbol position\n * @return MPX symbol position\n */\n public static CurrencySymbolPosition getSymbolPosition (int value)\n {\n CurrencySymbolPosition result;\n\n switch (value)\n {\n case 1:\n {\n result = CurrencySymbolPosition.AFTER;\n break;\n }\n\n case 2:\n {\n result = CurrencySymbolPosition.BEFORE_WITH_SPACE;\n break;\n }\n\n case 3:\n {\n result = CurrencySymbolPosition.AFTER_WITH_SPACE;\n break;\n }\n\n case 0:default:\n {\n result = CurrencySymbolPosition.BEFORE;\n break;\n }\n }\n\n return (result);\n }\n\n /**\n * Utility methdo to remove ampersands embedded in names.\n *\n * @param name name text\n * @return name text without embedded ampersands\n */\n public static final String removeAmpersands (String name)\n {\n if (name != null)\n {\n if (name.indexOf('&') != -1)\n {\n StringBuffer sb = new StringBuffer();\n int index = 0;\n char c;\n\n while (index < name.length())\n {\n c = name.charAt(index);\n if (c != '&')\n {\n sb.append(c);\n }\n ++index;\n }\n\n name = sb.toString();\n }\n }\n\n return (name);\n }\n\n /**\n * This method allows a subsection of a byte array to be copied.\n *\n * @param data source data\n * @param offset offset into the source data\n * @param size length of the source data to copy\n * @return new byte array containing copied data\n */\n public static final byte[] cloneSubArray (byte[] data, int offset, int size)\n {\n byte[] newData = new byte[size];\n System.arraycopy(data, offset, newData, 0, size);\n return (newData);\n }\n\n /**\n * This method generates a formatted version of the data contained\n * in a byte array. The data is written both in hex, and as ASCII\n * characters.\n *\n * @param buffer data to be displayed\n * @param offset offset of start of data to be displayed\n * @param length length of data to be displayed\n * @param ascii flag indicating whether ASCII equivalent chars should also be displayed\n * @return formatted string\n */\n public static final String hexdump (byte[] buffer, int offset, int length, boolean ascii)\n {\n StringBuffer sb = new StringBuffer();\n\n if (buffer != null)\n {\n char c;\n int loop;\n int count = offset + length;\n\n for (loop = offset; loop < count; loop++)\n {\n sb.append(\" \");\n sb.append(HEX_DIGITS[(buffer[loop] & 0xF0) >> 4]);\n sb.append(HEX_DIGITS[buffer[loop] & 0x0F]);\n }\n\n if (ascii == true)\n {\n sb.append(\" \");\n\n for (loop = offset; loop < count; loop++)\n {\n c = (char)buffer[loop];\n\n if ((c > 200) || (c < 27))\n {\n c = ' ';\n }\n\n sb.append(c);\n }\n }\n }\n\n return (sb.toString());\n }\n\n /**\n * This method generates a formatted version of the data contained\n * in a byte array. The data is written both in hex, and as ASCII\n * characters.\n *\n * @param buffer data to be displayed\n * @param ascii flag indicating whether ASCII equivalent chars should also be displayed\n * @return formatted string\n */\n public static final String hexdump (byte[] buffer, boolean ascii)\n {\n int length = 0;\n\n if (buffer != null)\n {\n length = buffer.length;\n }\n\n return (hexdump(buffer, 0, length, ascii));\n }\n\n /**\n * This method generates a formatted version of the data contained\n * in a byte array. The data is written both in hex, and as ASCII\n * characters. The data is organised into fixed width columns.\n *\n * @param buffer data to be displayed\n * @param ascii flag indicating whether ASCII equivalent chars should also be displayed\n * @param columns number of columns\n * @param prefix prefix to be added before the start of the data\n * @return formatted string\n */\n public static final String hexdump (byte[] buffer, boolean ascii, int columns, String prefix)\n {\n StringBuffer sb = new StringBuffer();\n if (buffer != null)\n {\n int index = 0;\n DecimalFormat df = new DecimalFormat(\"00000\");\n\n while (index < buffer.length)\n {\n if (index + columns > buffer.length)\n {\n columns = buffer.length - index;\n }\n\n sb.append (prefix);\n sb.append (df.format(index));\n sb.append (\":\");\n sb.append (hexdump(buffer, index, columns, ascii));\n sb.append ('\\n');\n\n index += columns;\n }\n }\n\n return (sb.toString());\n }\n\n /**\n * This method generates a formatted version of the data contained\n * in a byte array. The data is written both in hex, and as ASCII\n * characters. The data is organised into fixed width columns.\n * \n * @param buffer data to be displayed\n * @param offset offset into buffer\n * @param length number of bytes to display\n * @param ascii flag indicating whether ASCII equivalent chars should also be displayed\n * @param columns number of columns\n * @param prefix prefix to be added before the start of the data\n * @return formatted string\n */\n public static final String hexdump (byte[] buffer, int offset, int length, boolean ascii, int columns, String prefix)\n {\n StringBuffer sb = new StringBuffer();\n if (buffer != null)\n {\n int index = offset;\n DecimalFormat df = new DecimalFormat(\"00000\");\n\n while (index < (offset+length))\n {\n if (index + columns > (offset+length))\n {\n columns = (offset+length) - index;\n }\n\n sb.append (prefix);\n sb.append (df.format(index));\n sb.append (\":\");\n sb.append (hexdump(buffer, index, columns, ascii));\n sb.append ('\\n');\n\n index += columns;\n }\n }\n\n return (sb.toString());\n }\n \n /**\n * Writes a hex dump to a file for a large byte array.\n *\n * @param fileName output file name\n * @param data target data\n */\n public static final void fileHexDump (String fileName, byte[] data)\n {\n try\n {\n FileOutputStream os = new FileOutputStream(fileName);\n os.write(hexdump(data, true, 16, \"\").getBytes());\n os.close();\n }\n\n catch (IOException ex)\n {\n ex.printStackTrace();\n }\n }\n\n /**\n * Writes a hex dump to a file from a POI input stream.\n * Note that this assumes that the complete size of the data in\n * the stream is returned by the available() method.\n *\n * @param fileName output file name\n * @param is input stream\n */\n public static final void fileHexDump (String fileName, InputStream is)\n {\n try\n {\n byte[] data = new byte[is.available()];\n is.read(data);\n fileHexDump(fileName, data);\n }\n\n catch (IOException ex)\n {\n ex.printStackTrace();\n }\n }\n\n /**\n * Writes a large byte array to a file.\n *\n * @param fileName output file name\n * @param data target data\n */\n public static final void fileDump (String fileName, byte[] data)\n {\n try\n {\n FileOutputStream os = new FileOutputStream(fileName);\n os.write(data);\n os.close();\n }\n\n catch (IOException ex)\n {\n ex.printStackTrace();\n }\n }\n\n /**\n * Epoch date for MPP date calculation is 31/12/1983. This constant\n * is that date expressed in milliseconds using the Java date epoch.\n */\n private static final long EPOCH = 441676800000L;\n\n /**\n * Number of milliseconds per day.\n */\n private static final long MS_PER_DAY = 24 * 60 * 60 * 1000;\n\n /**\n * Number of milliseconds per minute.\n */\n private static final long MS_PER_MINUTE = 60 * 1000;\n\n /**\n * Constants used to convert bytes to hex digits.\n */\n private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};\n\n /**\n * Mask used to remove flags from the duration units field.\n */\n private static final int DURATION_UNITS_MASK = 0x1F;\n\n /**\n * Default value to use for DST savings if we are using a version\n * of Java < 1.4.\n */\n private static final int DEFAULT_DST_SAVINGS = 3600000;\n\n /**\n * Flag used to indicate the existance of the getDSTSavings\n * method that was introduced in Java 1.4.\n */\n private static boolean HAS_DST_SAVINGS;\n\n static\n {\n Class tz = TimeZone.class;\n\n try\n {\n tz.getMethod(\"getDSTSavings\", (Class[])null);\n HAS_DST_SAVINGS = true;\n }\n\n catch (NoSuchMethodException ex)\n {\n HAS_DST_SAVINGS = false;\n }\n }\n}\n"},"message":{"kind":"string","value":"Added correct handling for elapsed weeks and months.\n"},"old_file":{"kind":"string","value":"net/sf/mpxj/mpp/MPPUtility.java"},"subject":{"kind":"string","value":"Added correct handling for elapsed weeks and months."},"git_diff":{"kind":"string","value":"et/sf/mpxj/mpp/MPPUtility.java\n break;\n }\n \n case TimeUnit.ELAPSED_WEEKS_VALUE:\n {\n double unitsPerWeek = (60 * 24 * 7 * 10);\n double totalWeeks = duration / unitsPerWeek;\n result = Duration.getInstance(totalWeeks, timeUnit);\n break;\n }\n\n case TimeUnit.ELAPSED_MONTHS_VALUE:\n {\n double unitsPerMonth = (60 * 24 * 29 * 10);\n double totalMonths = duration / unitsPerMonth;\n result = Duration.getInstance(totalMonths, timeUnit);\n break;\n }\n \n default:\n {\n result = getDuration(duration, timeUnit);"}}},{"rowIdx":1933,"cells":{"lang":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"17c4c96c2967e640a6f6819b9fa9699e592039ad"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"wekan/wekan,GhassenRjab/wekan,GhassenRjab/wekan,GhassenRjab/wekan,wekan/wekan,wekan/wekan,wekan/wekan,wekan/wekan"},"new_contents":{"kind":"string","value":"// A inlined form is used to provide a quick edition of single field for a given\n// document. Clicking on a edit button should display the form to edit the field\n// value. The form can then be submited, or just closed.\n//\n// When the form is closed we save non-submitted values in memory to avoid any\n// data loss.\n//\n// Usage:\n//\n// +inlineForm\n// // the content when the form is open\n// else\n// // the content when the form is close (optional)\n\n// We can only have one inlined form element opened at a time\nconst currentlyOpenedForm = new ReactiveVar(null);\n\nInlinedForm = BlazeComponent.extendComponent({\n template() {\n return 'inlinedForm';\n },\n\n onCreated() {\n this.isOpen = new ReactiveVar(false);\n },\n\n onDestroyed() {\n currentlyOpenedForm.set(null);\n },\n\n open(evt) {\n evt && evt.preventDefault();\n\n // Close currently opened form, if any\n EscapeActions.executeUpTo('inlinedForm');\n this.isOpen.set(true);\n currentlyOpenedForm.set(this);\n },\n\n close() {\n this.isOpen.set(false);\n currentlyOpenedForm.set(null);\n },\n\n getValue() {\n const input = this.find('textarea,input[type=text]');\n return this.isOpen.get() && input && input.value;\n },\n\n events() {\n return [{\n 'click .js-close-inlined-form': this.close,\n 'click .js-open-inlined-form': this.open,\n\n // Pressing Ctrl+Enter should submit the form\n 'keydown form textarea'(evt) {\n if (evt.keyCode === 13 && (evt.metaKey || evt.ctrlKey)) {\n this.find('button[type=submit]').click();\n }\n },\n\n // Close the inlined form when after its submission\n submit() {\n if (this.currentData().autoclose !== false) {\n Tracker.afterFlush(() => {\n this.close();\n });\n }\n },\n }];\n },\n}).register('inlinedForm');\n\n// Press escape to close the currently opened inlinedForm\nEscapeActions.register('inlinedForm',\n () => { currentlyOpenedForm.get().close(); },\n () => { return currentlyOpenedForm.get() !== null; }, {\n enabledOnClick: false,\n }\n);\n\n// submit on click outside\n//document.addEventListener('click', function(evt) {\n// const openedForm = currentlyOpenedForm.get();\n// const isClickOutside = $(evt.target).closest('.js-inlined-form').length === 0;\n// if (openedForm && isClickOutside) {\n// $('.js-inlined-form button[type=submit]').click();\n// openedForm.close();\n// }\n//}, true);\n"},"new_file":{"kind":"string","value":"client/lib/inlinedform.js"},"old_contents":{"kind":"string","value":"// A inlined form is used to provide a quick edition of single field for a given\n// document. Clicking on a edit button should display the form to edit the field\n// value. The form can then be submited, or just closed.\n//\n// When the form is closed we save non-submitted values in memory to avoid any\n// data loss.\n//\n// Usage:\n//\n// +inlineForm\n// // the content when the form is open\n// else\n// // the content when the form is close (optional)\n\n// We can only have one inlined form element opened at a time\nconst currentlyOpenedForm = new ReactiveVar(null);\n\nInlinedForm = BlazeComponent.extendComponent({\n template() {\n return 'inlinedForm';\n },\n\n onCreated() {\n this.isOpen = new ReactiveVar(false);\n },\n\n onDestroyed() {\n currentlyOpenedForm.set(null);\n },\n\n open(evt) {\n evt && evt.preventDefault();\n\n // Close currently opened form, if any\n EscapeActions.executeUpTo('inlinedForm');\n this.isOpen.set(true);\n currentlyOpenedForm.set(this);\n },\n\n close() {\n this.isOpen.set(false);\n currentlyOpenedForm.set(null);\n },\n\n getValue() {\n const input = this.find('textarea,input[type=text]');\n return this.isOpen.get() && input && input.value;\n },\n\n events() {\n return [{\n 'click .js-close-inlined-form': this.close,\n 'click .js-open-inlined-form': this.open,\n\n // Pressing Ctrl+Enter should submit the form\n 'keydown form textarea'(evt) {\n if (evt.keyCode === 13 && (evt.metaKey || evt.ctrlKey)) {\n this.find('button[type=submit]').click();\n }\n },\n\n // Close the inlined form when after its submission\n submit() {\n if (this.currentData().autoclose !== false) {\n Tracker.afterFlush(() => {\n this.close();\n });\n }\n },\n }];\n },\n}).register('inlinedForm');\n\n// Press escape to close the currently opened inlinedForm\nEscapeActions.register('inlinedForm',\n () => { currentlyOpenedForm.get().close(); },\n () => { return currentlyOpenedForm.get() !== null; }, {\n enabledOnClick: false,\n }\n);\n\n// submit on click outside\ndocument.addEventListener('click', function(evt) {\n const openedForm = currentlyOpenedForm.get();\n const isClickOutside = $(evt.target).closest('.js-inlined-form').length === 0;\n if (openedForm && isClickOutside) {\n $('.js-inlined-form button[type=submit]').click();\n openedForm.close();\n }\n}, true);\n"},"message":{"kind":"string","value":"- [Fix Wekan unable to Select Text from Description edit box](https://github.com/wekan/wekan/issues/2451)\n by removing feature of card description submit on click outside. This is because when selecting text\n and dragging up did trigger submit of description, so description was closed and selecting text failed.\n This did affect all Chromium-based browsers: Chrome, Chromium, Chromium Edge.\n\nThanks to xet7 !\n\nCloses #2451\n"},"old_file":{"kind":"string","value":"client/lib/inlinedform.js"},"subject":{"kind":"string","value":"- [Fix Wekan unable to Select Text from Description edit box](https://github.com/wekan/wekan/issues/2451) by removing feature of card description submit on click outside. This is because when selecting text and dragging up did trigger submit of description, so description was closed and selecting text failed. This did affect all Chromium-based browsers: Chrome, Chromium, Chromium Edge."},"git_diff":{"kind":"string","value":"lient/lib/inlinedform.js\n );\n \n // submit on click outside\ndocument.addEventListener('click', function(evt) {\n const openedForm = currentlyOpenedForm.get();\n const isClickOutside = $(evt.target).closest('.js-inlined-form').length === 0;\n if (openedForm && isClickOutside) {\n $('.js-inlined-form button[type=submit]').click();\n openedForm.close();\n }\n}, true);\n//document.addEventListener('click', function(evt) {\n// const openedForm = currentlyOpenedForm.get();\n// const isClickOutside = $(evt.target).closest('.js-inlined-form').length === 0;\n// if (openedForm && isClickOutside) {\n// $('.js-inlined-form button[type=submit]').click();\n// openedForm.close();\n// }\n//}, true);"}}},{"rowIdx":1934,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"bsd-3-clause"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"24778e6447852896ba759f2e8dc811d082a5b845"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"edina/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon"},"new_contents":{"kind":"string","value":"/*\n * $Id:$\n */\n/*\n\n Copyright (c) 2000-2016 Board of Trustees of Leland Stanford Jr. University,\n all rights reserved.\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of his software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR\n IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n Except as contained in this notice, the name of Stanford University shall not\n be used in advertising or otherwise to promote the sale, use or other dealings\n in this Software without prior written authorization from Stanford University.\n\n */\n\npackage org.lockss.plugin.pub2web.ms;\n\nimport java.io.InputStream;\nimport java.util.Set;\n\nimport org.lockss.extractor.JsoupHtmlLinkExtractor;\nimport org.lockss.extractor.LinkExtractor;\nimport org.lockss.test.LockssTestCase;\nimport org.lockss.test.MockArchivalUnit;\nimport org.lockss.test.StringInputStream;\nimport org.lockss.util.Constants;\nimport org.lockss.util.IOUtil;\nimport org.lockss.util.SetUtil;\nimport org.lockss.util.StringUtil;\n\n\npublic class TestMsHtmlLinkExtractorFactory extends LockssTestCase {\n\n private MsHtmlLinkExtractorFactory msfact;\n private LinkExtractor m_extractor;\n private MyLinkExtractorCallback m_callback;\n static String ENC = Constants.DEFAULT_ENCODING;\n private MockArchivalUnit m_mau;\n private final String BASE_URL = \"http://www.asmscience.org/\";\n private final String JID = \"microbiolspec\";\n\n \n @Override\n public void setUp() throws Exception {\n super.setUp();\n log.setLevel(\"debug3\");\n m_mau = new MockArchivalUnit();\n m_callback = new MyLinkExtractorCallback();\n\n msfact = new MsHtmlLinkExtractorFactory();\n //m_extractor = msfact.createLinkExtractor(\"html\");\n m_extractor = new JsoupHtmlLinkExtractor(); \n }\n \n public static final String htmlSnippet =\n \"Test Title\" +\n \"
\" +\n \"\" +\n \"insert html to pull links from here\" +\n \"\" +\n \"\";\n \n \n public void testPlaceholder() throws Exception {\n InputStream inStream;\n //placeholder - took out real world file tests\n assertEquals(true,true);\n\n }\n \n private void testExpectedAgainstParsedUrls(Set expectedUrls, \n String source, String srcUrl) throws Exception {\n\n Set result_strings = parseSingleSource(source, srcUrl);\n //assertEquals(expectedUrls.size(), result_strings.size());\n for (String url : result_strings) {\n log.debug3(\"URL: \" + url);\n //assertTrue(expectedUrls.contains(url));\n }\n }\n private Set parseSingleSource(String source, String srcUrl)\n throws Exception {\n\n m_callback.reset();\n m_extractor.extractUrls(m_mau,\n new org.lockss.test.StringInputStream(source), ENC,\n srcUrl, m_callback);\n return m_callback.getFoundUrls();\n }\n\n private static class MyLinkExtractorCallback implements\n LinkExtractor.Callback {\n\n Set foundUrls = new java.util.HashSet();\n\n public void foundLink(String url) {\n foundUrls.add(url);\n }\n\n public Set getFoundUrls() {\n return foundUrls;\n }\n\n public void reset() {\n foundUrls = new java.util.HashSet();\n }\n }\n\n}\n"},"new_file":{"kind":"string","value":"plugins/test/src/org/lockss/plugin/pub2web/ms/TestMsHtmlLinkExtractorFactory.java"},"old_contents":{"kind":"string","value":"/*\n * $Id:$\n */\n/*\n\n Copyright (c) 2000-2016 Board of Trustees of Leland Stanford Jr. University,\n all rights reserved.\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of his software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR\n IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n Except as contained in this notice, the name of Stanford University shall not\n be used in advertising or otherwise to promote the sale, use or other dealings\n in this Software without prior written authorization from Stanford University.\n\n */\n\npackage org.lockss.plugin.pub2web.ms;\n\nimport java.io.InputStream;\nimport java.util.Set;\n\nimport org.lockss.extractor.JsoupHtmlLinkExtractor;\nimport org.lockss.extractor.LinkExtractor;\nimport org.lockss.test.LockssTestCase;\nimport org.lockss.test.MockArchivalUnit;\nimport org.lockss.util.Constants;\nimport org.lockss.util.IOUtil;\nimport org.lockss.util.SetUtil;\nimport org.lockss.util.StringUtil;\n\n\npublic class TestMsHtmlLinkExtractorFactory extends LockssTestCase {\n\n private MsHtmlLinkExtractorFactory msfact;\n private LinkExtractor m_extractor;\n private MyLinkExtractorCallback m_callback;\n static String ENC = Constants.DEFAULT_ENCODING;\n private MockArchivalUnit m_mau;\n private final String BASE_URL = \"http://www.asmscience.org/\";\n private final String JID = \"microbiolspec\";\n\n \n @Override\n public void setUp() throws Exception {\n super.setUp();\n log.setLevel(\"debug3\");\n m_mau = new MockArchivalUnit();\n m_callback = new MyLinkExtractorCallback();\n\n msfact = new MsHtmlLinkExtractorFactory();\n //m_extractor = msfact.createLinkExtractor(\"html\");\n m_extractor = new JsoupHtmlLinkExtractor(); \n }\n \n public static final String htmlSnippet =\n \"Test Title\" +\n \"
\" +\n \"\" +\n \"insert html to pull links from here\" +\n \"\" +\n \"\";\n \n \n private void testExpectedAgainstParsedUrls(Set expectedUrls, \n String source, String srcUrl) throws Exception {\n\n Set result_strings = parseSingleSource(source, srcUrl);\n //assertEquals(expectedUrls.size(), result_strings.size());\n for (String url : result_strings) {\n log.debug3(\"URL: \" + url);\n //assertTrue(expectedUrls.contains(url));\n }\n }\n private Set parseSingleSource(String source, String srcUrl)\n throws Exception {\n\n m_callback.reset();\n m_extractor.extractUrls(m_mau,\n new org.lockss.test.StringInputStream(source), ENC,\n srcUrl, m_callback);\n return m_callback.getFoundUrls();\n }\n\n private static class MyLinkExtractorCallback implements\n LinkExtractor.Callback {\n\n Set foundUrls = new java.util.HashSet();\n\n public void foundLink(String url) {\n foundUrls.add(url);\n }\n\n public Set getFoundUrls() {\n return foundUrls;\n }\n\n public void reset() {\n foundUrls = new java.util.HashSet();\n }\n }\n\n}\n"},"message":{"kind":"string","value":"add placeholder test to avoid fail"},"old_file":{"kind":"string","value":"plugins/test/src/org/lockss/plugin/pub2web/ms/TestMsHtmlLinkExtractorFactory.java"},"subject":{"kind":"string","value":"add placeholder test to avoid fail"},"git_diff":{"kind":"string","value":"lugins/test/src/org/lockss/plugin/pub2web/ms/TestMsHtmlLinkExtractorFactory.java\n import org.lockss.extractor.LinkExtractor;\n import org.lockss.test.LockssTestCase;\n import org.lockss.test.MockArchivalUnit;\nimport org.lockss.test.StringInputStream;\n import org.lockss.util.Constants;\n import org.lockss.util.IOUtil;\n import org.lockss.util.SetUtil;\n \"\" +\n \"\";\n \n \n public void testPlaceholder() throws Exception {\n InputStream inStream;\n //placeholder - took out real world file tests\n assertEquals(true,true);\n\n }\n \n private void testExpectedAgainstParsedUrls(Set expectedUrls, \n String source, String srcUrl) throws Exception {"}}},{"rowIdx":1935,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"3d2b33582543c1036e62514726db5b6031f196ed"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"androidx/media,androidx/media,androidx/media"},"new_contents":{"kind":"string","value":"/*\n * Copyright 2020 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage androidx.media3.exoplayer.ima;\n\nimport static com.google.common.truth.Truth.assertThat;\n\nimport android.content.Context;\nimport android.net.Uri;\nimport android.view.Surface;\nimport android.widget.FrameLayout;\nimport androidx.annotation.Nullable;\nimport androidx.media3.common.C;\nimport androidx.media3.common.MediaItem;\nimport androidx.media3.common.Player;\nimport androidx.media3.common.Player.DiscontinuityReason;\nimport androidx.media3.common.Player.TimelineChangeReason;\nimport androidx.media3.common.Timeline.Window;\nimport androidx.media3.common.util.Assertions;\nimport androidx.media3.common.util.Util;\nimport androidx.media3.datasource.DataSpec;\nimport androidx.media3.exoplayer.DecoderCounters;\nimport androidx.media3.exoplayer.ExoPlayer;\nimport androidx.media3.exoplayer.analytics.AnalyticsListener;\nimport androidx.media3.exoplayer.drm.DrmSessionManager;\nimport androidx.media3.exoplayer.source.DefaultMediaSourceFactory;\nimport androidx.media3.exoplayer.source.MediaSource;\nimport androidx.media3.exoplayer.source.ads.AdsMediaSource;\nimport androidx.media3.exoplayer.trackselection.MappingTrackSelector;\nimport androidx.media3.test.utils.ActionSchedule;\nimport androidx.media3.test.utils.ExoHostedTest;\nimport androidx.media3.test.utils.HostActivity;\nimport androidx.media3.test.utils.TestUtil;\nimport androidx.test.ext.junit.runners.AndroidJUnit4;\nimport androidx.test.rule.ActivityTestRule;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport org.checkerframework.checker.nullness.qual.MonotonicNonNull;\nimport org.junit.Ignore;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\n\n/** Playback tests using {@link ImaAdsLoader}. */\n@RunWith(AndroidJUnit4.class)\npublic final class ImaPlaybackTest {\n\n private static final String TAG = \"ImaPlaybackTest\";\n\n private static final long TIMEOUT_MS = 5 * 60 * C.MILLIS_PER_SECOND;\n\n private static final String CONTENT_URI_SHORT =\n \"https://storage.googleapis.com/exoplayer-test-media-1/mp4/android-screens-10s.mp4\";\n private static final String CONTENT_URI_LONG =\n \"https://storage.googleapis.com/exoplayer-test-media-1/mp4/android-screens-25s.mp4\";\n private static final AdId CONTENT = new AdId(C.INDEX_UNSET, C.INDEX_UNSET);\n\n @Rule public ActivityTestRule testRule = new ActivityTestRule<>(HostActivity.class);\n\n @Test\n public void playbackWithPrerollAdTag_playsAdAndContent() throws Exception {\n String adsResponse =\n TestUtil.getString(/* context= */ testRule.getActivity(), \"media/ad-responses/preroll.xml\");\n AdId[] expectedAdIds = new AdId[] {ad(0), CONTENT};\n ImaHostedTest hostedTest =\n new ImaHostedTest(Uri.parse(CONTENT_URI_SHORT), adsResponse, expectedAdIds);\n\n testRule.getActivity().runTest(hostedTest, TIMEOUT_MS);\n }\n\n @Test\n public void playbackWithMidrolls_playsAdAndContent() throws Exception {\n String adsResponse =\n TestUtil.getString(\n /* context= */ testRule.getActivity(),\n \"media/ad-responses/preroll_midroll6s_postroll.xml\");\n AdId[] expectedAdIds = new AdId[] {ad(0), CONTENT, ad(1), CONTENT, ad(2), CONTENT};\n ImaHostedTest hostedTest =\n new ImaHostedTest(Uri.parse(CONTENT_URI_SHORT), adsResponse, expectedAdIds);\n\n testRule.getActivity().runTest(hostedTest, TIMEOUT_MS);\n }\n\n @Test\n public void playbackWithMidrolls1And7_playsAdsAndContent() throws Exception {\n String adsResponse =\n TestUtil.getString(\n /* context= */ testRule.getActivity(), \"media/ad-responses/midroll1s_midroll7s.xml\");\n AdId[] expectedAdIds = new AdId[] {CONTENT, ad(0), CONTENT, ad(1), CONTENT};\n ImaHostedTest hostedTest =\n new ImaHostedTest(Uri.parse(CONTENT_URI_SHORT), adsResponse, expectedAdIds);\n\n testRule.getActivity().runTest(hostedTest, TIMEOUT_MS);\n }\n\n @Test\n public void playbackWithMidrolls10And20WithSeekTo12_playsAdsAndContent() throws Exception {\n String adsResponse =\n TestUtil.getString(\n /* context= */ testRule.getActivity(), \"media/ad-responses/midroll10s_midroll20s.xml\");\n AdId[] expectedAdIds = new AdId[] {CONTENT, ad(0), CONTENT, ad(1), CONTENT};\n ImaHostedTest hostedTest =\n new ImaHostedTest(Uri.parse(CONTENT_URI_LONG), adsResponse, expectedAdIds);\n hostedTest.setSchedule(\n new ActionSchedule.Builder(TAG)\n .waitForPlaybackState(Player.STATE_READY)\n .seek(12 * C.MILLIS_PER_SECOND)\n .build());\n testRule.getActivity().runTest(hostedTest, TIMEOUT_MS);\n }\n\n @Ignore(\"The second ad doesn't preload so playback gets stuck. See [internal: b/155615925].\")\n @Test\n public void playbackWithMidrolls10And20WithSeekTo18_playsAdsAndContent() throws Exception {\n String adsResponse =\n TestUtil.getString(\n /* context= */ testRule.getActivity(), \"media/ad-responses/midroll10s_midroll20s.xml\");\n AdId[] expectedAdIds = new AdId[] {CONTENT, ad(0), CONTENT, ad(1), CONTENT};\n ImaHostedTest hostedTest =\n new ImaHostedTest(Uri.parse(CONTENT_URI_LONG), adsResponse, expectedAdIds);\n hostedTest.setSchedule(\n new ActionSchedule.Builder(TAG)\n .waitForPlaybackState(Player.STATE_READY)\n .seek(18 * C.MILLIS_PER_SECOND)\n .build());\n testRule.getActivity().runTest(hostedTest, TIMEOUT_MS);\n }\n\n private static AdId ad(int groupIndex) {\n return new AdId(groupIndex, /* indexInGroup= */ 0);\n }\n\n private static final class AdId {\n\n public final int groupIndex;\n public final int indexInGroup;\n\n public AdId(int groupIndex, int indexInGroup) {\n this.groupIndex = groupIndex;\n this.indexInGroup = indexInGroup;\n }\n\n @Override\n public String toString() {\n return \"(\" + groupIndex + \", \" + indexInGroup + ')';\n }\n\n @Override\n public boolean equals(@Nullable Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n\n AdId that = (AdId) o;\n\n if (groupIndex != that.groupIndex) {\n return false;\n }\n return indexInGroup == that.indexInGroup;\n }\n\n @Override\n public int hashCode() {\n int result = groupIndex;\n result = 31 * result + indexInGroup;\n return result;\n }\n }\n\n private static final class ImaHostedTest extends ExoHostedTest implements Player.Listener {\n\n private final Uri contentUri;\n private final DataSpec adTagDataSpec;\n private final List expectedAdIds;\n private final List seenAdIds;\n private @MonotonicNonNull ImaAdsLoader imaAdsLoader;\n private @MonotonicNonNull ExoPlayer player;\n\n private ImaHostedTest(Uri contentUri, String adsResponse, AdId... expectedAdIds) {\n // fullPlaybackNoSeeking is false as the playback lasts longer than the content source\n // duration due to ad playback, so the hosted test shouldn't assert the playing duration.\n super(ImaPlaybackTest.class.getSimpleName(), /* fullPlaybackNoSeeking= */ false);\n this.contentUri = contentUri;\n this.adTagDataSpec =\n new DataSpec(\n Util.getDataUriForString(/* mimeType= */ \"text/xml\", /* data= */ adsResponse));\n this.expectedAdIds = Arrays.asList(expectedAdIds);\n seenAdIds = new ArrayList<>();\n }\n\n @Override\n protected ExoPlayer buildExoPlayer(\n HostActivity host, Surface surface, MappingTrackSelector trackSelector) {\n player = super.buildExoPlayer(host, surface, trackSelector);\n player.addAnalyticsListener(\n new AnalyticsListener() {\n @Override\n public void onTimelineChanged(EventTime eventTime, @TimelineChangeReason int reason) {\n maybeUpdateSeenAdIdentifiers();\n }\n\n @Override\n public void onPositionDiscontinuity(\n EventTime eventTime, @DiscontinuityReason int reason) {\n if (reason != Player.DISCONTINUITY_REASON_SEEK) {\n maybeUpdateSeenAdIdentifiers();\n }\n }\n });\n Context context = host.getApplicationContext();\n imaAdsLoader = new ImaAdsLoader.Builder(context).build();\n imaAdsLoader.setPlayer(player);\n return player;\n }\n\n @Override\n protected MediaSource buildSource(\n HostActivity host, DrmSessionManager drmSessionManager, FrameLayout overlayFrameLayout) {\n Context context = host.getApplicationContext();\n MediaSource contentMediaSource =\n new DefaultMediaSourceFactory(context).createMediaSource(MediaItem.fromUri(contentUri));\n return new AdsMediaSource(\n contentMediaSource,\n adTagDataSpec,\n /* adsId= */ adTagDataSpec.uri,\n new DefaultMediaSourceFactory(context),\n Assertions.checkNotNull(imaAdsLoader),\n () -> overlayFrameLayout);\n }\n\n @Override\n protected void assertPassed(DecoderCounters audioCounters, DecoderCounters videoCounters) {\n assertThat(seenAdIds).isEqualTo(expectedAdIds);\n }\n\n private void maybeUpdateSeenAdIdentifiers() {\n if (Assertions.checkNotNull(player)\n .getCurrentTimeline()\n .getWindow(/* windowIndex= */ 0, new Window())\n .isPlaceholder) {\n // The window is still an initial placeholder so do nothing.\n return;\n }\n AdId adId = new AdId(player.getCurrentAdGroupIndex(), player.getCurrentAdIndexInAdGroup());\n if (seenAdIds.isEmpty() || !seenAdIds.get(seenAdIds.size() - 1).equals(adId)) {\n seenAdIds.add(adId);\n }\n }\n }\n}\n"},"new_file":{"kind":"string","value":"libraries/exoplayer_ima/src/androidTest/java/androidx/media3/exoplayer/ima/ImaPlaybackTest.java"},"old_contents":{"kind":"string","value":"/*\n * Copyright 2020 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage androidx.media3.exoplayer.ima;\n\nimport static com.google.common.truth.Truth.assertThat;\n\nimport android.content.Context;\nimport android.net.Uri;\nimport android.view.Surface;\nimport android.widget.FrameLayout;\nimport androidx.annotation.Nullable;\nimport androidx.media3.common.C;\nimport androidx.media3.common.MediaItem;\nimport androidx.media3.common.Player;\nimport androidx.media3.common.Player.DiscontinuityReason;\nimport androidx.media3.common.Player.TimelineChangeReason;\nimport androidx.media3.common.Timeline.Window;\nimport androidx.media3.common.util.Assertions;\nimport androidx.media3.common.util.Util;\nimport androidx.media3.datasource.DataSource;\nimport androidx.media3.datasource.DataSpec;\nimport androidx.media3.datasource.DefaultDataSource;\nimport androidx.media3.exoplayer.DecoderCounters;\nimport androidx.media3.exoplayer.ExoPlayer;\nimport androidx.media3.exoplayer.analytics.AnalyticsListener;\nimport androidx.media3.exoplayer.drm.DrmSessionManager;\nimport androidx.media3.exoplayer.source.DefaultMediaSourceFactory;\nimport androidx.media3.exoplayer.source.MediaSource;\nimport androidx.media3.exoplayer.source.ads.AdsMediaSource;\nimport androidx.media3.exoplayer.trackselection.MappingTrackSelector;\nimport androidx.media3.test.utils.ActionSchedule;\nimport androidx.media3.test.utils.ExoHostedTest;\nimport androidx.media3.test.utils.HostActivity;\nimport androidx.media3.test.utils.TestUtil;\nimport androidx.test.ext.junit.runners.AndroidJUnit4;\nimport androidx.test.rule.ActivityTestRule;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport org.checkerframework.checker.nullness.qual.MonotonicNonNull;\nimport org.junit.Ignore;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\n\n/** Playback tests using {@link ImaAdsLoader}. */\n@RunWith(AndroidJUnit4.class)\npublic final class ImaPlaybackTest {\n\n private static final String TAG = \"ImaPlaybackTest\";\n\n private static final long TIMEOUT_MS = 5 * 60 * C.MILLIS_PER_SECOND;\n\n private static final String CONTENT_URI_SHORT =\n \"https://storage.googleapis.com/exoplayer-test-media-1/mp4/android-screens-10s.mp4\";\n private static final String CONTENT_URI_LONG =\n \"https://storage.googleapis.com/exoplayer-test-media-1/mp4/android-screens-25s.mp4\";\n private static final AdId CONTENT = new AdId(C.INDEX_UNSET, C.INDEX_UNSET);\n\n @Rule public ActivityTestRule testRule = new ActivityTestRule<>(HostActivity.class);\n\n @Test\n public void playbackWithPrerollAdTag_playsAdAndContent() throws Exception {\n String adsResponse =\n TestUtil.getString(/* context= */ testRule.getActivity(), \"media/ad-responses/preroll.xml\");\n AdId[] expectedAdIds = new AdId[] {ad(0), CONTENT};\n ImaHostedTest hostedTest =\n new ImaHostedTest(Uri.parse(CONTENT_URI_SHORT), adsResponse, expectedAdIds);\n\n testRule.getActivity().runTest(hostedTest, TIMEOUT_MS);\n }\n\n @Test\n public void playbackWithMidrolls_playsAdAndContent() throws Exception {\n String adsResponse =\n TestUtil.getString(\n /* context= */ testRule.getActivity(),\n \"media/ad-responses/preroll_midroll6s_postroll.xml\");\n AdId[] expectedAdIds = new AdId[] {ad(0), CONTENT, ad(1), CONTENT, ad(2), CONTENT};\n ImaHostedTest hostedTest =\n new ImaHostedTest(Uri.parse(CONTENT_URI_SHORT), adsResponse, expectedAdIds);\n\n testRule.getActivity().runTest(hostedTest, TIMEOUT_MS);\n }\n\n @Test\n public void playbackWithMidrolls1And7_playsAdsAndContent() throws Exception {\n String adsResponse =\n TestUtil.getString(\n /* context= */ testRule.getActivity(), \"media/ad-responses/midroll1s_midroll7s.xml\");\n AdId[] expectedAdIds = new AdId[] {CONTENT, ad(0), CONTENT, ad(1), CONTENT};\n ImaHostedTest hostedTest =\n new ImaHostedTest(Uri.parse(CONTENT_URI_SHORT), adsResponse, expectedAdIds);\n\n testRule.getActivity().runTest(hostedTest, TIMEOUT_MS);\n }\n\n @Test\n public void playbackWithMidrolls10And20WithSeekTo12_playsAdsAndContent() throws Exception {\n String adsResponse =\n TestUtil.getString(\n /* context= */ testRule.getActivity(), \"media/ad-responses/midroll10s_midroll20s.xml\");\n AdId[] expectedAdIds = new AdId[] {CONTENT, ad(0), CONTENT, ad(1), CONTENT};\n ImaHostedTest hostedTest =\n new ImaHostedTest(Uri.parse(CONTENT_URI_LONG), adsResponse, expectedAdIds);\n hostedTest.setSchedule(\n new ActionSchedule.Builder(TAG)\n .waitForPlaybackState(Player.STATE_READY)\n .seek(12 * C.MILLIS_PER_SECOND)\n .build());\n testRule.getActivity().runTest(hostedTest, TIMEOUT_MS);\n }\n\n @Ignore(\"The second ad doesn't preload so playback gets stuck. See [internal: b/155615925].\")\n @Test\n public void playbackWithMidrolls10And20WithSeekTo18_playsAdsAndContent() throws Exception {\n String adsResponse =\n TestUtil.getString(\n /* context= */ testRule.getActivity(), \"media/ad-responses/midroll10s_midroll20s.xml\");\n AdId[] expectedAdIds = new AdId[] {CONTENT, ad(0), CONTENT, ad(1), CONTENT};\n ImaHostedTest hostedTest =\n new ImaHostedTest(Uri.parse(CONTENT_URI_LONG), adsResponse, expectedAdIds);\n hostedTest.setSchedule(\n new ActionSchedule.Builder(TAG)\n .waitForPlaybackState(Player.STATE_READY)\n .seek(18 * C.MILLIS_PER_SECOND)\n .build());\n testRule.getActivity().runTest(hostedTest, TIMEOUT_MS);\n }\n\n private static AdId ad(int groupIndex) {\n return new AdId(groupIndex, /* indexInGroup= */ 0);\n }\n\n private static final class AdId {\n\n public final int groupIndex;\n public final int indexInGroup;\n\n public AdId(int groupIndex, int indexInGroup) {\n this.groupIndex = groupIndex;\n this.indexInGroup = indexInGroup;\n }\n\n @Override\n public String toString() {\n return \"(\" + groupIndex + \", \" + indexInGroup + ')';\n }\n\n @Override\n public boolean equals(@Nullable Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n\n AdId that = (AdId) o;\n\n if (groupIndex != that.groupIndex) {\n return false;\n }\n return indexInGroup == that.indexInGroup;\n }\n\n @Override\n public int hashCode() {\n int result = groupIndex;\n result = 31 * result + indexInGroup;\n return result;\n }\n }\n\n private static final class ImaHostedTest extends ExoHostedTest implements Player.Listener {\n\n private final Uri contentUri;\n private final DataSpec adTagDataSpec;\n private final List expectedAdIds;\n private final List seenAdIds;\n private @MonotonicNonNull ImaAdsLoader imaAdsLoader;\n private @MonotonicNonNull ExoPlayer player;\n\n private ImaHostedTest(Uri contentUri, String adsResponse, AdId... expectedAdIds) {\n // fullPlaybackNoSeeking is false as the playback lasts longer than the content source\n // duration due to ad playback, so the hosted test shouldn't assert the playing duration.\n super(ImaPlaybackTest.class.getSimpleName(), /* fullPlaybackNoSeeking= */ false);\n this.contentUri = contentUri;\n this.adTagDataSpec =\n new DataSpec(\n Util.getDataUriForString(/* mimeType= */ \"text/xml\", /* data= */ adsResponse));\n this.expectedAdIds = Arrays.asList(expectedAdIds);\n seenAdIds = new ArrayList<>();\n }\n\n @Override\n protected ExoPlayer buildExoPlayer(\n HostActivity host, Surface surface, MappingTrackSelector trackSelector) {\n player = super.buildExoPlayer(host, surface, trackSelector);\n player.addAnalyticsListener(\n new AnalyticsListener() {\n @Override\n public void onTimelineChanged(EventTime eventTime, @TimelineChangeReason int reason) {\n maybeUpdateSeenAdIdentifiers();\n }\n\n @Override\n public void onPositionDiscontinuity(\n EventTime eventTime, @DiscontinuityReason int reason) {\n if (reason != Player.DISCONTINUITY_REASON_SEEK) {\n maybeUpdateSeenAdIdentifiers();\n }\n }\n });\n Context context = host.getApplicationContext();\n imaAdsLoader = new ImaAdsLoader.Builder(context).build();\n imaAdsLoader.setPlayer(player);\n return player;\n }\n\n @Override\n protected MediaSource buildSource(\n HostActivity host, DrmSessionManager drmSessionManager, FrameLayout overlayFrameLayout) {\n Context context = host.getApplicationContext();\n DataSource.Factory dataSourceFactory = new DefaultDataSource.Factory(context);\n MediaSource contentMediaSource =\n new DefaultMediaSourceFactory(context).createMediaSource(MediaItem.fromUri(contentUri));\n return new AdsMediaSource(\n contentMediaSource,\n adTagDataSpec,\n /* adsId= */ adTagDataSpec.uri,\n new DefaultMediaSourceFactory(dataSourceFactory),\n Assertions.checkNotNull(imaAdsLoader),\n () -> overlayFrameLayout);\n }\n\n @Override\n protected void assertPassed(DecoderCounters audioCounters, DecoderCounters videoCounters) {\n assertThat(seenAdIds).isEqualTo(expectedAdIds);\n }\n\n private void maybeUpdateSeenAdIdentifiers() {\n if (Assertions.checkNotNull(player)\n .getCurrentTimeline()\n .getWindow(/* windowIndex= */ 0, new Window())\n .isPlaceholder) {\n // The window is still an initial placeholder so do nothing.\n return;\n }\n AdId adId = new AdId(player.getCurrentAdGroupIndex(), player.getCurrentAdIndexInAdGroup());\n if (seenAdIds.isEmpty() || !seenAdIds.get(seenAdIds.size() - 1).equals(adId)) {\n seenAdIds.add(adId);\n }\n }\n }\n}\n"},"message":{"kind":"string","value":"Simplify `DefaultMediaSourceFactory` instantiation in a test\n\nThere's no need to manually construct a 'default'\nDefaultDataSource.Factory instance, we can just pass the `Context` to\n`DefaultMediaSourceFactory` and let it construct the\n`DefaultDataSource.Factory` internally.\n\nPiperOrigin-RevId: 451155747\n"},"old_file":{"kind":"string","value":"libraries/exoplayer_ima/src/androidTest/java/androidx/media3/exoplayer/ima/ImaPlaybackTest.java"},"subject":{"kind":"string","value":"Simplify `DefaultMediaSourceFactory` instantiation in a test"},"git_diff":{"kind":"string","value":"ibraries/exoplayer_ima/src/androidTest/java/androidx/media3/exoplayer/ima/ImaPlaybackTest.java\n import androidx.media3.common.Timeline.Window;\n import androidx.media3.common.util.Assertions;\n import androidx.media3.common.util.Util;\nimport androidx.media3.datasource.DataSource;\n import androidx.media3.datasource.DataSpec;\nimport androidx.media3.datasource.DefaultDataSource;\n import androidx.media3.exoplayer.DecoderCounters;\n import androidx.media3.exoplayer.ExoPlayer;\n import androidx.media3.exoplayer.analytics.AnalyticsListener;\n protected MediaSource buildSource(\n HostActivity host, DrmSessionManager drmSessionManager, FrameLayout overlayFrameLayout) {\n Context context = host.getApplicationContext();\n DataSource.Factory dataSourceFactory = new DefaultDataSource.Factory(context);\n MediaSource contentMediaSource =\n new DefaultMediaSourceFactory(context).createMediaSource(MediaItem.fromUri(contentUri));\n return new AdsMediaSource(\n contentMediaSource,\n adTagDataSpec,\n /* adsId= */ adTagDataSpec.uri,\n new DefaultMediaSourceFactory(dataSourceFactory),\n new DefaultMediaSourceFactory(context),\n Assertions.checkNotNull(imaAdsLoader),\n () -> overlayFrameLayout);\n }"}}},{"rowIdx":1936,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"f2e6d1e170bf887a9e141081146ca9ae49a65843"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"javamelody/javamelody,javamelody/javamelody,javamelody/javamelody"},"new_contents":{"kind":"string","value":"/*\r\n * Copyright 2008-2010 by Emeric Vernat\r\n *\r\n * This file is part of Java Melody.\r\n *\r\n * Java Melody is free software: you can redistribute it and/or modify\r\n * it under the terms of the GNU Lesser General Public License as published by\r\n * the Free Software Foundation, either version 3 of the License, or\r\n * (at your option) any later version.\r\n *\r\n * Java Melody is distributed in the hope that it will be useful,\r\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n * GNU Lesser General Public License for more details.\r\n *\r\n * You should have received a copy of the GNU Lesser General Public License\r\n * along with Java Melody. If not, see .\r\n */\r\npackage net.bull.javamelody;\r\n\r\nimport static net.bull.javamelody.HttpParameters.SESSIONS_PART;\r\nimport static org.junit.Assert.assertEquals;\r\nimport static org.junit.Assert.assertTrue;\r\nimport static org.junit.Assert.fail;\r\n\r\nimport java.io.IOException;\r\nimport java.io.StringWriter;\r\nimport java.sql.Connection;\r\nimport java.util.Arrays;\r\nimport java.util.Collections;\r\nimport java.util.Date;\r\nimport java.util.List;\r\nimport java.util.Locale;\r\nimport java.util.Random;\r\nimport java.util.Timer;\r\n\r\nimport net.sf.ehcache.Cache;\r\nimport net.sf.ehcache.CacheManager;\r\nimport net.sf.ehcache.Element;\r\n\r\nimport org.junit.After;\r\nimport org.junit.Before;\r\nimport org.junit.Test;\r\nimport org.quartz.JobDetail;\r\nimport org.quartz.Scheduler;\r\nimport org.quartz.SchedulerException;\r\nimport org.quartz.SimpleTrigger;\r\nimport org.quartz.Trigger;\r\nimport org.quartz.impl.StdSchedulerFactory;\r\n\r\n/**\r\n * Test unitaire de la classe HtmlReport.\r\n * @author Emeric Vernat\r\n */\r\npublic class TestHtmlReport {\r\n\tprivate Timer timer;\r\n\tprivate List javaInformationsList;\r\n\tprivate Counter sqlCounter;\r\n\tprivate Counter servicesCounter;\r\n\tprivate Counter counter;\r\n\tprivate Counter errorCounter;\r\n\tprivate Collector collector;\r\n\tprivate StringWriter writer;\r\n\r\n\t/** Initialisation. */\r\n\t@Before\r\n\tpublic void setUp() {\r\n\t\ttimer = new Timer(\"test timer\", true);\r\n\t\tjavaInformationsList = Collections.singletonList(new JavaInformations(null, true));\r\n\t\tsqlCounter = new Counter(\"sql\", \"db.png\");\r\n\t\tsqlCounter.setDisplayed(false);\r\n\t\tservicesCounter = new Counter(\"services\", \"beans.png\", sqlCounter);\r\n\t\t// counterName doit être http, sql ou ejb pour que les libellés de graph soient trouvés dans les traductions\r\n\t\tcounter = new Counter(\"http\", \"dbweb.png\", sqlCounter);\r\n\t\terrorCounter = new Counter(Counter.ERROR_COUNTER_NAME, null);\r\n\t\tfinal Counter jobCounter = new Counter(Counter.JOB_COUNTER_NAME, \"jobs.png\");\r\n\t\tcollector = new Collector(\"test\", Arrays.asList(counter, sqlCounter, servicesCounter,\r\n\t\t\t\terrorCounter, jobCounter), timer);\r\n\t\twriter = new StringWriter();\r\n\t}\r\n\r\n\t/** Finalisation. */\r\n\t@After\r\n\tpublic void tearDown() {\r\n\t\ttimer.cancel();\r\n\t}\r\n\r\n\t/** Test.\r\n\t * @throws IOException e */\r\n\t@Test\r\n\tpublic void testEmptyCounter() throws IOException {\r\n\t\tfinal HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList,\r\n\t\t\t\tPeriod.TOUT, writer);\r\n\t\t// rapport avec counter sans requête\r\n\t\tcounter.clear();\r\n\t\terrorCounter.clear();\r\n\t\thtmlReport.toHtml(null);\r\n\t\tassertNotEmptyAndClear(writer);\r\n\t}\r\n\r\n\t/** Test.\r\n\t * @throws IOException e */\r\n\t@Test\r\n\tpublic void testDoubleJavaInformations() throws IOException {\r\n\t\tfinal List myJavaInformationsList = Arrays.asList(new JavaInformations(\r\n\t\t\t\tnull, true), new JavaInformations(null, true));\r\n\t\tfinal HtmlReport htmlReport = new HtmlReport(collector, null, myJavaInformationsList,\r\n\t\t\t\tPeriod.TOUT, writer);\r\n\t\thtmlReport.toHtml(null);\r\n\t\tassertNotEmptyAndClear(writer);\r\n\t}\r\n\r\n\t/** Test.\r\n\t * @throws IOException e */\r\n\t@Test\r\n\tpublic void testCounter() throws IOException {\r\n\t\t// counter avec 3 requêtes\r\n\t\tsetProperty(Parameter.WARNING_THRESHOLD_MILLIS, \"500\");\r\n\t\tsetProperty(Parameter.SEVERE_THRESHOLD_MILLIS, \"1500\");\r\n\t\tsetProperty(Parameter.ANALYTICS_ID, \"123456789\");\r\n\t\tcounter.addRequest(\"test1\", 0, 0, false, 1000);\r\n\t\tcounter.addRequest(\"test2\", 1000, 500, false, 1000);\r\n\t\tcounter.addRequest(\"test3\", 100000, 50000, true, 10000);\r\n\t\tcollector.collectWithoutErrors(javaInformationsList);\r\n\r\n\t\tfinal HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList,\r\n\t\t\t\tPeriod.TOUT, writer);\r\n\t\thtmlReport.toHtml(\"message 2\");\r\n\t\tassertNotEmptyAndClear(writer);\r\n\r\n\t\tsetProperty(Parameter.NO_DATABASE, \"true\");\r\n\t\tcollector.collectWithoutErrors(javaInformationsList);\r\n\t\thtmlReport.toHtml(\"message 2\");\r\n\t\tassertNotEmptyAndClear(writer);\r\n\t\tsetProperty(Parameter.NO_DATABASE, \"false\");\r\n\t}\r\n\r\n\t/** Test.\r\n\t * @throws IOException e */\r\n\t@Test\r\n\tpublic void testErrorCounter() throws IOException {\r\n\t\t// errorCounter\r\n\t\terrorCounter.addRequestForSystemError(\"error\", -1, -1, null);\r\n\t\terrorCounter.addRequestForSystemError(\"error2\", -1, -1, \"ma stack-trace\");\r\n\t\tcollector.collectWithoutErrors(javaInformationsList);\r\n\t\tfinal HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList,\r\n\t\t\t\tPeriod.TOUT, writer);\r\n\t\thtmlReport.toHtml(\"message 3\");\r\n\t\tassertNotEmptyAndClear(writer);\r\n\t\tfor (final CounterRequest request : errorCounter.getRequests()) {\r\n\t\t\thtmlReport.writeRequestAndGraphDetail(request.getId());\r\n\t\t}\r\n\t\thtmlReport.writeRequestAndGraphDetail(\"n'importe quoi\");\r\n\t\tassertNotEmptyAndClear(writer);\r\n\t}\r\n\r\n\t/** Test.\r\n\t * @throws IOException e */\r\n\t@Test\r\n\tpublic void testPeriodeNonTout() throws IOException {\r\n\t\t// counter avec période non TOUT et des requêtes\r\n\t\tcollector.collectWithoutErrors(javaInformationsList);\r\n\t\tfinal String requestName = \"test 1\";\r\n\t\tcounter.bindContext(requestName, \"complete test 1\");\r\n\t\tsqlCounter.addRequest(\"sql1\", 10, 10, false, -1);\r\n\t\tcounter.addRequest(requestName, 0, 0, false, 1000);\r\n\t\tcounter.addRequest(\"test2\", 1000, 500, false, 1000);\r\n\t\tcounter.addRequest(\"test3\", 10000, 500, true, 10000);\r\n\t\tcollector.collectWithoutErrors(javaInformationsList);\r\n\t\tfinal HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList,\r\n\t\t\t\tPeriod.SEMAINE, writer);\r\n\t\thtmlReport.toHtml(\"message 6\");\r\n\t\tassertNotEmptyAndClear(writer);\r\n\r\n\t\t// période personnalisée\r\n\t\tfinal HtmlReport htmlReportRange = new HtmlReport(collector, null, javaInformationsList,\r\n\t\t\t\tRange.createCustomRange(new Date(), new Date()), writer);\r\n\t\thtmlReportRange.toHtml(\"message 6\");\r\n\t\tassertNotEmptyAndClear(writer);\r\n\t}\r\n\r\n\t/** Test.\r\n\t * @throws Exception e */\r\n\t@Test\r\n\tpublic void testAllWrite() throws Exception { // NOPMD\r\n\t\tfinal HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList,\r\n\t\t\t\tPeriod.SEMAINE, writer);\r\n\t\thtmlReport.writeRequestAndGraphDetail(\"httpHitsRate\");\r\n\r\n\t\t// writeRequestAndGraphDetail avec drill-down\r\n\t\tcollector.collectWithoutErrors(javaInformationsList);\r\n\t\t// si sqlCounter reste à displayed=false,\r\n\t\t// il ne sera pas utilisé dans writeRequestAndGraphDetail\r\n\t\tsqlCounter.setDisplayed(true);\r\n\t\tfinal String requestName = \"test 1\";\r\n\t\tcounter.bindContext(requestName, \"complete test 1\");\r\n\t\tservicesCounter.bindContext(\"service1\", \"service1\");\r\n\t\tsqlCounter.bindContext(\"sql1\", \"complete sql1\");\r\n\t\tsqlCounter.addRequest(\"sql1\", 5, -1, false, -1);\r\n\t\tservicesCounter.addRequest(\"service1\", 10, 10, false, -1);\r\n\t\tservicesCounter.bindContext(\"service2\", \"service2\");\r\n\t\tservicesCounter.addRequest(\"service2\", 10, 10, false, -1);\r\n\t\tcounter.addRequest(requestName, 0, 0, false, 1000);\r\n\t\tcollector.collectWithoutErrors(javaInformationsList);\r\n\t\tfinal HtmlReport toutHtmlReport = new HtmlReport(collector, null, javaInformationsList,\r\n\t\t\t\tPeriod.TOUT, writer);\r\n\t\tfor (final Counter collectorCounter : collector.getCounters()) {\r\n\t\t\tfor (final CounterRequest request : collectorCounter.getRequests()) {\r\n\t\t\t\ttoutHtmlReport.writeRequestAndGraphDetail(request.getId());\r\n\t\t\t\ttoutHtmlReport.writeRequestUsages(request.getId());\r\n\t\t\t}\r\n\t\t}\r\n\t\tsqlCounter.setDisplayed(false);\r\n\r\n\t\thtmlReport.writeSessionDetail(\"\", null);\r\n\t\thtmlReport.writeSessions(Collections. emptyList(), \"message\",\r\n\t\t\t\tSESSIONS_PART);\r\n\t\thtmlReport\r\n\t\t\t\t.writeSessions(Collections. emptyList(), null, SESSIONS_PART);\r\n\t\tfinal String fileName = ProcessInformations.WINDOWS ? \"/tasklist.txt\" : \"/ps.txt\";\r\n\t\thtmlReport.writeProcesses(ProcessInformations.buildProcessInformations(getClass()\r\n\t\t\t\t.getResourceAsStream(fileName), ProcessInformations.WINDOWS));\r\n\t\t// avant initH2 pour avoir une liste de connexions vide\r\n\t\thtmlReport.writeConnections(JdbcWrapper.getConnectionInformationsList(), false);\r\n\t\tfinal Connection connection = TestDatabaseInformations.initH2();\r\n\t\ttry {\r\n\t\t\thtmlReport.writeConnections(JdbcWrapper.getConnectionInformationsList(), false);\r\n\t\t\thtmlReport.writeConnections(JdbcWrapper.getConnectionInformationsList(), true);\r\n\t\t\thtmlReport.writeDatabase(new DatabaseInformations(0)); // h2.memory\r\n\t\t\thtmlReport.writeDatabase(new DatabaseInformations(3)); // h2.settings avec nbColumns==2\r\n\t\t\tHtmlReport.writeAddAndRemoveApplicationLinks(null, writer);\r\n\t\t\tHtmlReport.writeAddAndRemoveApplicationLinks(\"test\", writer);\r\n\t\t\tsetProperty(Parameter.SYSTEM_ACTIONS_ENABLED, \"true\");\r\n\t\t\thtmlReport.toHtml(null); // writeSystemActionsLinks\r\n\t\t\tassertNotEmptyAndClear(writer);\r\n\t\t\tsetProperty(Parameter.NO_DATABASE, \"true\");\r\n\t\t\thtmlReport.toHtml(null); // writeSystemActionsLinks\r\n\t\t\tassertNotEmptyAndClear(writer);\r\n\t\t\tsetProperty(Parameter.SYSTEM_ACTIONS_ENABLED, \"false\");\r\n\t\t\tsetProperty(Parameter.NO_DATABASE, \"false\");\r\n\t\t} finally {\r\n\t\t\tconnection.close();\r\n\t\t}\r\n\t}\r\n\r\n\t/** Test.\r\n\t * @throws IOException e */\r\n\t@Test\r\n\tpublic void testRootContexts() throws IOException {\r\n\t\tHtmlReport htmlReport;\r\n\t\t// addRequest pour que CounterRequestContext.getCpuTime() soit appelée\r\n\t\tcounter.addRequest(\"first request\", 100, 100, false, 1000);\r\n\t\tTestCounter.bindRootContexts(\"first request\", counter, 3);\r\n\t\tsqlCounter.bindContext(\"sql\", \"sql\");\r\n\t\thtmlReport = new HtmlReport(collector, null, javaInformationsList, Period.TOUT, writer);\r\n\t\thtmlReport.toHtml(\"message a\");\r\n\t\tassertNotEmptyAndClear(writer);\r\n\r\n\t\tfinal Counter myCounter = new Counter(\"http\", null);\r\n\t\tfinal Collector collector2 = new Collector(\"test 2\", Arrays.asList(myCounter), timer);\r\n\t\tmyCounter.bindContext(\"my context\", \"my context\");\r\n\t\thtmlReport = new HtmlReport(collector2, null, javaInformationsList, Period.SEMAINE, writer);\r\n\t\thtmlReport.toHtml(\"message b\");\r\n\t\tassertNotEmptyAndClear(writer);\r\n\t}\r\n\r\n\t/** Test.\r\n\t * @throws IOException e */\r\n\t@Test\r\n\tpublic void testCache() throws IOException {\r\n\t\tfinal String cacheName = \"test 1\";\r\n\t\tfinal CacheManager cacheManager = CacheManager.getInstance();\r\n\t\tcacheManager.addCache(cacheName);\r\n\t\tfinal String cacheName2 = \"test 2\";\r\n\t\ttry {\r\n\t\t\tfinal Cache cache = cacheManager.getCache(cacheName);\r\n\t\t\tcache.put(new Element(1, Math.random()));\r\n\t\t\tcache.get(1);\r\n\t\t\tcache.get(0);\r\n\t\t\tcacheManager.addCache(cacheName2);\r\n\t\t\tfinal Cache cache2 = cacheManager.getCache(cacheName2);\r\n\t\t\tcache2.getCacheConfiguration().setOverflowToDisk(false);\r\n\t\t\tcache2.getCacheConfiguration().setEternal(true);\r\n\r\n\t\t\t// JavaInformations doit être réinstancié pour récupérer les caches\r\n\t\t\tfinal List javaInformationsList2 = Collections\r\n\t\t\t\t\t.singletonList(new JavaInformations(null, true));\r\n\t\t\tfinal HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList2,\r\n\t\t\t\t\tPeriod.TOUT, writer);\r\n\t\t\thtmlReport.toHtml(null);\r\n\t\t\tassertNotEmptyAndClear(writer);\r\n\t\t} finally {\r\n\t\t\tcacheManager.removeCache(cacheName);\r\n\t\t\tcacheManager.removeCache(cacheName2);\r\n\t\t}\r\n\t}\r\n\r\n\t/** Test.\r\n\t * @throws IOException e\r\n\t * @throws SchedulerException e */\r\n\t@Test\r\n\tpublic void testJob() throws IOException, SchedulerException {\r\n\t\t//Grab the Scheduler instance from the Factory\r\n\t\tfinal Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();\r\n\r\n\t\ttry {\r\n\t\t\t// and start it off\r\n\t\t\tscheduler.start();\r\n\r\n\t\t\t//Define job instance\r\n\t\t\tfinal Random random = new Random();\r\n\t\t\tfinal JobDetail job = new JobDetail(\"job\" + random.nextInt(), null, JobTestImpl.class);\r\n\r\n\t\t\t//Define a Trigger that will fire \"now\"\r\n\t\t\tfinal Trigger trigger = new SimpleTrigger(\"trigger\" + random.nextInt(), null,\r\n\t\t\t\t\tnew Date());\r\n\t\t\t//Schedule the job with the trigger\r\n\t\t\tscheduler.scheduleJob(job, trigger);\r\n\r\n\t\t\t//Define a Trigger that will fire \"later\"\r\n\t\t\tfinal JobDetail job2 = new JobDetail(\"job\" + random.nextInt(), null, JobTestImpl.class);\r\n\t\t\tfinal Trigger trigger2 = new SimpleTrigger(\"trigger\" + random.nextInt(), null,\r\n\t\t\t\t\tnew Date(System.currentTimeMillis() + random.nextInt(60000)));\r\n\t\t\tscheduler.scheduleJob(job2, trigger2);\r\n\r\n\t\t\t// JavaInformations doit être réinstancié pour récupérer les jobs\r\n\t\t\tfinal List javaInformationsList2 = Collections\r\n\t\t\t\t\t.singletonList(new JavaInformations(null, true));\r\n\t\t\tfinal HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList2,\r\n\t\t\t\t\tPeriod.TOUT, writer);\r\n\t\t\thtmlReport.toHtml(null);\r\n\t\t\tassertNotEmptyAndClear(writer);\r\n\t\t} finally {\r\n\t\t\tscheduler.shutdown();\r\n\t\t}\r\n\t}\r\n\r\n\t/** Test.\r\n\t * @throws IOException e */\r\n\t@Test\r\n\tpublic void testWithCollectorServer() throws IOException {\r\n\t\tfinal CollectorServer collectorServer = new CollectorServer();\r\n\t\tfinal HtmlReport htmlReport = new HtmlReport(collector, collectorServer,\r\n\t\t\t\tjavaInformationsList, Period.TOUT, writer);\r\n\t\thtmlReport.toHtml(null);\r\n\t\tassertNotEmptyAndClear(writer);\r\n\r\n\t\tcollectorServer.collectWithoutErrors();\r\n\t\thtmlReport.toHtml(null);\r\n\t\tassertNotEmptyAndClear(writer);\r\n\t}\r\n\r\n\t/** Test.\r\n\t * @throws IOException e */\r\n\t@Test\r\n\tpublic void testWithNoDatabase() throws IOException {\r\n\t\tfinal HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList,\r\n\t\t\t\tPeriod.TOUT, writer);\r\n\t\thtmlReport.toHtml(null);\r\n\t\tassertNotEmptyAndClear(writer);\r\n\t}\r\n\r\n\t/** Test.\r\n\t * @throws IOException e */\r\n\t@Test\r\n\tpublic void testEmptyHtmlCounterRequestContext() throws IOException {\r\n\t\tfinal HtmlCounterRequestContextReport report = new HtmlCounterRequestContextReport(\r\n\t\t\t\tCollections. emptyList(), Collections\r\n\t\t\t\t\t\t. emptyMap(), Collections\r\n\t\t\t\t\t\t. emptyList(), true, writer);\r\n\t\treport.toHtml();\r\n\t\tif (writer.getBuffer().length() != 0) {\r\n\t\t\tfail(\"HtmlCounterRequestContextReport\");\r\n\t\t}\r\n\t}\r\n\r\n\tprivate static void setProperty(Parameter parameter, String value) {\r\n\t\tSystem.setProperty(Parameters.PARAMETER_SYSTEM_PREFIX + parameter.getCode(), value);\r\n\t}\r\n\r\n\tprivate static void assertNotEmptyAndClear(final StringWriter writer) {\r\n\t\tassertTrue(\"rapport vide\", writer.getBuffer().length() > 0);\r\n\t\twriter.getBuffer().setLength(0);\r\n\t}\r\n\r\n\t/** Test.\r\n\t * @throws IOException e */\r\n\t@Test\r\n\tpublic void testToHtmlEn() throws IOException {\r\n\t\tI18N.bindLocale(Locale.UK);\r\n\t\ttry {\r\n\t\t\tassertEquals(\"locale en\", Locale.UK, I18N.getCurrentLocale());\r\n\r\n\t\t\t// counter avec 3 requêtes\r\n\t\t\tcounter.addRequest(\"test1\", 0, 0, false, 1000);\r\n\t\t\tcounter.addRequest(\"test2\", 1000, 500, false, 1000);\r\n\t\t\tcounter.addRequest(\"test3\", 10000, 5000, true, 10000);\r\n\t\t\tfinal HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList,\r\n\t\t\t\t\tPeriod.TOUT, writer);\r\n\t\t\thtmlReport.toHtml(\"message\");\r\n\t\t\tassertNotEmptyAndClear(writer);\r\n\t\t} finally {\r\n\t\t\tI18N.unbindLocale();\r\n\t\t}\r\n\t}\r\n}\r\n"},"new_file":{"kind":"string","value":"javamelody-core/src/test/java/net/bull/javamelody/TestHtmlReport.java"},"old_contents":{"kind":"string","value":"/*\r\n * Copyright 2008-2010 by Emeric Vernat\r\n *\r\n * This file is part of Java Melody.\r\n *\r\n * Java Melody is free software: you can redistribute it and/or modify\r\n * it under the terms of the GNU Lesser General Public License as published by\r\n * the Free Software Foundation, either version 3 of the License, or\r\n * (at your option) any later version.\r\n *\r\n * Java Melody is distributed in the hope that it will be useful,\r\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n * GNU Lesser General Public License for more details.\r\n *\r\n * You should have received a copy of the GNU Lesser General Public License\r\n * along with Java Melody. If not, see .\r\n */\r\npackage net.bull.javamelody;\r\n\r\nimport static net.bull.javamelody.HttpParameters.SESSIONS_PART;\r\nimport static org.junit.Assert.assertEquals;\r\nimport static org.junit.Assert.assertTrue;\r\nimport static org.junit.Assert.fail;\r\n\r\nimport java.io.IOException;\r\nimport java.io.StringWriter;\r\nimport java.sql.Connection;\r\nimport java.util.Arrays;\r\nimport java.util.Collections;\r\nimport java.util.Date;\r\nimport java.util.List;\r\nimport java.util.Locale;\r\nimport java.util.Random;\r\nimport java.util.Timer;\r\n\r\nimport net.sf.ehcache.Cache;\r\nimport net.sf.ehcache.CacheManager;\r\nimport net.sf.ehcache.Element;\r\n\r\nimport org.junit.After;\r\nimport org.junit.Before;\r\nimport org.junit.Test;\r\nimport org.quartz.JobDetail;\r\nimport org.quartz.Scheduler;\r\nimport org.quartz.SchedulerException;\r\nimport org.quartz.SimpleTrigger;\r\nimport org.quartz.Trigger;\r\nimport org.quartz.impl.StdSchedulerFactory;\r\n\r\n/**\r\n * Test unitaire de la classe HtmlReport.\r\n * @author Emeric Vernat\r\n */\r\npublic class TestHtmlReport {\r\n\tprivate Timer timer;\r\n\tprivate List javaInformationsList;\r\n\tprivate Counter sqlCounter;\r\n\tprivate Counter servicesCounter;\r\n\tprivate Counter counter;\r\n\tprivate Counter errorCounter;\r\n\tprivate Collector collector;\r\n\tprivate StringWriter writer;\r\n\r\n\t/** Initialisation. */\r\n\t@Before\r\n\tpublic void setUp() {\r\n\t\ttimer = new Timer(\"test timer\", true);\r\n\t\tjavaInformationsList = Collections.singletonList(new JavaInformations(null, true));\r\n\t\tsqlCounter = new Counter(\"sql\", \"db.png\");\r\n\t\tsqlCounter.setDisplayed(false);\r\n\t\tservicesCounter = new Counter(\"services\", \"beans.png\", sqlCounter);\r\n\t\t// counterName doit être http, sql ou ejb pour que les libellés de graph soient trouvés dans les traductions\r\n\t\tcounter = new Counter(\"http\", \"dbweb.png\", sqlCounter);\r\n\t\terrorCounter = new Counter(Counter.ERROR_COUNTER_NAME, null);\r\n\t\tfinal Counter jobCounter = new Counter(Counter.JOB_COUNTER_NAME, \"jobs.png\");\r\n\t\tcollector = new Collector(\"test\", Arrays.asList(counter, sqlCounter, servicesCounter,\r\n\t\t\t\terrorCounter, jobCounter), timer);\r\n\t\twriter = new StringWriter();\r\n\t}\r\n\r\n\t/** Finalisation. */\r\n\t@After\r\n\tpublic void tearDown() {\r\n\t\ttimer.cancel();\r\n\t}\r\n\r\n\t/** Test.\r\n\t * @throws IOException e */\r\n\t@Test\r\n\tpublic void testEmptyCounter() throws IOException {\r\n\t\tfinal HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList,\r\n\t\t\t\tPeriod.TOUT, writer);\r\n\t\t// rapport avec counter sans requête\r\n\t\tcounter.clear();\r\n\t\terrorCounter.clear();\r\n\t\thtmlReport.toHtml(null);\r\n\t\tassertNotEmptyAndClear(writer);\r\n\t}\r\n\r\n\t/** Test.\r\n\t * @throws IOException e */\r\n\t@Test\r\n\tpublic void testDoubleJavaInformations() throws IOException {\r\n\t\tfinal List myJavaInformationsList = Arrays.asList(new JavaInformations(\r\n\t\t\t\tnull, true), new JavaInformations(null, true));\r\n\t\tfinal HtmlReport htmlReport = new HtmlReport(collector, null, myJavaInformationsList,\r\n\t\t\t\tPeriod.TOUT, writer);\r\n\t\thtmlReport.toHtml(null);\r\n\t\tassertNotEmptyAndClear(writer);\r\n\t}\r\n\r\n\t/** Test.\r\n\t * @throws IOException e */\r\n\t@Test\r\n\tpublic void testCounter() throws IOException {\r\n\t\t// counter avec 3 requêtes\r\n\t\tsetProperty(Parameter.WARNING_THRESHOLD_MILLIS, \"500\");\r\n\t\tsetProperty(Parameter.SEVERE_THRESHOLD_MILLIS, \"1500\");\r\n\t\tsetProperty(Parameter.ANALYTICS_ID, \"123456789\");\r\n\t\tcounter.addRequest(\"test1\", 0, 0, false, 1000);\r\n\t\tcounter.addRequest(\"test2\", 1000, 500, false, 1000);\r\n\t\tcounter.addRequest(\"test3\", 100000, 50000, true, 10000);\r\n\t\tcollector.collectWithoutErrors(javaInformationsList);\r\n\r\n\t\tfinal HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList,\r\n\t\t\t\tPeriod.TOUT, writer);\r\n\t\thtmlReport.toHtml(\"message 2\");\r\n\t\tassertNotEmptyAndClear(writer);\r\n\r\n\t\tsetProperty(Parameter.NO_DATABASE, \"true\");\r\n\t\tcollector.collectWithoutErrors(javaInformationsList);\r\n\t\thtmlReport.toHtml(\"message 2\");\r\n\t\tassertNotEmptyAndClear(writer);\r\n\t\tsetProperty(Parameter.NO_DATABASE, \"false\");\r\n\t}\r\n\r\n\t/** Test.\r\n\t * @throws IOException e */\r\n\t@Test\r\n\tpublic void testErrorCounter() throws IOException {\r\n\t\t// errorCounter\r\n\t\terrorCounter.addRequestForSystemError(\"error\", -1, -1, null);\r\n\t\terrorCounter.addRequestForSystemError(\"error2\", -1, -1, \"ma stack-trace\");\r\n\t\tcollector.collectWithoutErrors(javaInformationsList);\r\n\t\tfinal HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList,\r\n\t\t\t\tPeriod.TOUT, writer);\r\n\t\thtmlReport.toHtml(\"message 3\");\r\n\t\tassertNotEmptyAndClear(writer);\r\n\t\tfor (final CounterRequest request : errorCounter.getRequests()) {\r\n\t\t\thtmlReport.writeRequestAndGraphDetail(request.getId());\r\n\t\t}\r\n\t\thtmlReport.writeRequestAndGraphDetail(\"n'importe quoi\");\r\n\t\tassertNotEmptyAndClear(writer);\r\n\t}\r\n\r\n\t/** Test.\r\n\t * @throws IOException e */\r\n\t@Test\r\n\tpublic void testPeriodeNonTout() throws IOException {\r\n\t\t// counter avec période non TOUT et des requêtes\r\n\t\tcollector.collectWithoutErrors(javaInformationsList);\r\n\t\tfinal String requestName = \"test 1\";\r\n\t\tcounter.bindContext(requestName, \"complete test 1\");\r\n\t\tsqlCounter.addRequest(\"sql1\", 10, 10, false, -1);\r\n\t\tcounter.addRequest(requestName, 0, 0, false, 1000);\r\n\t\tcounter.addRequest(\"test2\", 1000, 500, false, 1000);\r\n\t\tcounter.addRequest(\"test3\", 10000, 500, true, 10000);\r\n\t\tcollector.collectWithoutErrors(javaInformationsList);\r\n\t\tfinal HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList,\r\n\t\t\t\tPeriod.SEMAINE, writer);\r\n\t\thtmlReport.toHtml(\"message 6\");\r\n\t\tassertNotEmptyAndClear(writer);\r\n\r\n\t\t// période personnalisée\r\n\t\tfinal HtmlReport htmlReportRange = new HtmlReport(collector, null, javaInformationsList,\r\n\t\t\t\tRange.createCustomRange(new Date(), new Date()), writer);\r\n\t\thtmlReportRange.toHtml(\"message 6\");\r\n\t\tassertNotEmptyAndClear(writer);\r\n\t}\r\n\r\n\t/** Test.\r\n\t * @throws Exception e */\r\n\t@Test\r\n\tpublic void testAllWrite() throws Exception { // NOPMD\r\n\t\tfinal HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList,\r\n\t\t\t\tPeriod.SEMAINE, writer);\r\n\t\thtmlReport.writeRequestAndGraphDetail(\"httpHitsRate\");\r\n\r\n\t\t// writeRequestAndGraphDetail avec drill-down\r\n\t\tcollector.collectWithoutErrors(javaInformationsList);\r\n\t\t// si sqlCounter reste à displayed=false,\r\n\t\t// il ne sera pas utilisé dans writeRequestAndGraphDetail\r\n\t\tsqlCounter.setDisplayed(true);\r\n\t\tfinal String requestName = \"test 1\";\r\n\t\tcounter.bindContext(requestName, \"complete test 1\");\r\n\t\tservicesCounter.bindContext(\"service1\", \"service1\");\r\n\t\tsqlCounter.bindContext(\"sql1\", \"complete sql1\");\r\n\t\tsqlCounter.addRequest(\"sql1\", 5, -1, false, -1);\r\n\t\tservicesCounter.addRequest(\"service1\", 10, 10, false, -1);\r\n\t\tservicesCounter.bindContext(\"service2\", \"service2\");\r\n\t\tservicesCounter.addRequest(\"service2\", 10, 10, false, -1);\r\n\t\tcounter.addRequest(requestName, 0, 0, false, 1000);\r\n\t\tcollector.collectWithoutErrors(javaInformationsList);\r\n\t\tfinal HtmlReport toutHtmlReport = new HtmlReport(collector, null, javaInformationsList,\r\n\t\t\t\tPeriod.TOUT, writer);\r\n\t\tfor (final Counter collectorCounter : collector.getCounters()) {\r\n\t\t\tfor (final CounterRequest request : collectorCounter.getRequests()) {\r\n\t\t\t\ttoutHtmlReport.writeRequestAndGraphDetail(request.getId());\r\n\t\t\t\ttoutHtmlReport.writeRequestUsages(request.getId());\r\n\t\t\t}\r\n\t\t}\r\n\t\tsqlCounter.setDisplayed(false);\r\n\r\n\t\thtmlReport.writeSessionDetail(\"\", null);\r\n\t\thtmlReport.writeSessions(Collections. emptyList(), \"message\",\r\n\t\t\t\tSESSIONS_PART);\r\n\t\thtmlReport\r\n\t\t\t\t.writeSessions(Collections. emptyList(), null, SESSIONS_PART);\r\n\t\tfinal String fileName = ProcessInformations.WINDOWS ? \"/tasklist.txt\" : \"/ps.txt\";\r\n\t\thtmlReport.writeProcesses(ProcessInformations.buildProcessInformations(getClass()\r\n\t\t\t\t.getResourceAsStream(fileName), ProcessInformations.WINDOWS));\r\n\t\t// avant initH2 pour avoir une liste de connexions vide\r\n\t\thtmlReport.writeConnections(JdbcWrapper.getConnectionInformationsList(), false);\r\n\t\tfinal Connection connection = TestDatabaseInformations.initH2();\r\n\t\ttry {\r\n\t\t\thtmlReport.writeConnections(JdbcWrapper.getConnectionInformationsList(), false);\r\n\t\t\thtmlReport.writeConnections(JdbcWrapper.getConnectionInformationsList(), true);\r\n\t\t\thtmlReport.writeDatabase(new DatabaseInformations(0));\r\n\t\t\tHtmlReport.writeAddAndRemoveApplicationLinks(null, writer);\r\n\t\t\tHtmlReport.writeAddAndRemoveApplicationLinks(\"test\", writer);\r\n\t\t\tsetProperty(Parameter.SYSTEM_ACTIONS_ENABLED, \"true\");\r\n\t\t\thtmlReport.toHtml(null); // writeSystemActionsLinks\r\n\t\t\tassertNotEmptyAndClear(writer);\r\n\t\t\tsetProperty(Parameter.NO_DATABASE, \"true\");\r\n\t\t\thtmlReport.toHtml(null); // writeSystemActionsLinks\r\n\t\t\tassertNotEmptyAndClear(writer);\r\n\t\t\tsetProperty(Parameter.SYSTEM_ACTIONS_ENABLED, \"false\");\r\n\t\t\tsetProperty(Parameter.NO_DATABASE, \"false\");\r\n\t\t} finally {\r\n\t\t\tconnection.close();\r\n\t\t}\r\n\t}\r\n\r\n\t/** Test.\r\n\t * @throws IOException e */\r\n\t@Test\r\n\tpublic void testRootContexts() throws IOException {\r\n\t\tHtmlReport htmlReport;\r\n\t\t// addRequest pour que CounterRequestContext.getCpuTime() soit appelée\r\n\t\tcounter.addRequest(\"first request\", 100, 100, false, 1000);\r\n\t\tTestCounter.bindRootContexts(\"first request\", counter, 3);\r\n\t\tsqlCounter.bindContext(\"sql\", \"sql\");\r\n\t\thtmlReport = new HtmlReport(collector, null, javaInformationsList, Period.TOUT, writer);\r\n\t\thtmlReport.toHtml(\"message a\");\r\n\t\tassertNotEmptyAndClear(writer);\r\n\r\n\t\tfinal Counter myCounter = new Counter(\"http\", null);\r\n\t\tfinal Collector collector2 = new Collector(\"test 2\", Arrays.asList(myCounter), timer);\r\n\t\tmyCounter.bindContext(\"my context\", \"my context\");\r\n\t\thtmlReport = new HtmlReport(collector2, null, javaInformationsList, Period.SEMAINE, writer);\r\n\t\thtmlReport.toHtml(\"message b\");\r\n\t\tassertNotEmptyAndClear(writer);\r\n\t}\r\n\r\n\t/** Test.\r\n\t * @throws IOException e */\r\n\t@Test\r\n\tpublic void testCache() throws IOException {\r\n\t\tfinal String cacheName = \"test 1\";\r\n\t\tfinal CacheManager cacheManager = CacheManager.getInstance();\r\n\t\tcacheManager.addCache(cacheName);\r\n\t\tfinal String cacheName2 = \"test 2\";\r\n\t\ttry {\r\n\t\t\tfinal Cache cache = cacheManager.getCache(cacheName);\r\n\t\t\tcache.put(new Element(1, Math.random()));\r\n\t\t\tcache.get(1);\r\n\t\t\tcache.get(0);\r\n\t\t\tcacheManager.addCache(cacheName2);\r\n\t\t\tfinal Cache cache2 = cacheManager.getCache(cacheName2);\r\n\t\t\tcache2.getCacheConfiguration().setOverflowToDisk(false);\r\n\t\t\tcache2.getCacheConfiguration().setEternal(true);\r\n\r\n\t\t\t// JavaInformations doit être réinstancié pour récupérer les caches\r\n\t\t\tfinal List javaInformationsList2 = Collections\r\n\t\t\t\t\t.singletonList(new JavaInformations(null, true));\r\n\t\t\tfinal HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList2,\r\n\t\t\t\t\tPeriod.TOUT, writer);\r\n\t\t\thtmlReport.toHtml(null);\r\n\t\t\tassertNotEmptyAndClear(writer);\r\n\t\t} finally {\r\n\t\t\tcacheManager.removeCache(cacheName);\r\n\t\t\tcacheManager.removeCache(cacheName2);\r\n\t\t}\r\n\t}\r\n\r\n\t/** Test.\r\n\t * @throws IOException e\r\n\t * @throws SchedulerException e */\r\n\t@Test\r\n\tpublic void testJob() throws IOException, SchedulerException {\r\n\t\t//Grab the Scheduler instance from the Factory\r\n\t\tfinal Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();\r\n\r\n\t\ttry {\r\n\t\t\t// and start it off\r\n\t\t\tscheduler.start();\r\n\r\n\t\t\t//Define job instance\r\n\t\t\tfinal Random random = new Random();\r\n\t\t\tfinal JobDetail job = new JobDetail(\"job\" + random.nextInt(), null, JobTestImpl.class);\r\n\r\n\t\t\t//Define a Trigger that will fire \"now\"\r\n\t\t\tfinal Trigger trigger = new SimpleTrigger(\"trigger\" + random.nextInt(), null,\r\n\t\t\t\t\tnew Date());\r\n\t\t\t//Schedule the job with the trigger\r\n\t\t\tscheduler.scheduleJob(job, trigger);\r\n\r\n\t\t\t//Define a Trigger that will fire \"later\"\r\n\t\t\tfinal JobDetail job2 = new JobDetail(\"job\" + random.nextInt(), null, JobTestImpl.class);\r\n\t\t\tfinal Trigger trigger2 = new SimpleTrigger(\"trigger\" + random.nextInt(), null,\r\n\t\t\t\t\tnew Date(System.currentTimeMillis() + random.nextInt(60000)));\r\n\t\t\tscheduler.scheduleJob(job2, trigger2);\r\n\r\n\t\t\t// JavaInformations doit être réinstancié pour récupérer les jobs\r\n\t\t\tfinal List javaInformationsList2 = Collections\r\n\t\t\t\t\t.singletonList(new JavaInformations(null, true));\r\n\t\t\tfinal HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList2,\r\n\t\t\t\t\tPeriod.TOUT, writer);\r\n\t\t\thtmlReport.toHtml(null);\r\n\t\t\tassertNotEmptyAndClear(writer);\r\n\t\t} finally {\r\n\t\t\tscheduler.shutdown();\r\n\t\t}\r\n\t}\r\n\r\n\t/** Test.\r\n\t * @throws IOException e */\r\n\t@Test\r\n\tpublic void testWithCollectorServer() throws IOException {\r\n\t\tfinal CollectorServer collectorServer = new CollectorServer();\r\n\t\tfinal HtmlReport htmlReport = new HtmlReport(collector, collectorServer,\r\n\t\t\t\tjavaInformationsList, Period.TOUT, writer);\r\n\t\thtmlReport.toHtml(null);\r\n\t\tassertNotEmptyAndClear(writer);\r\n\r\n\t\tcollectorServer.collectWithoutErrors();\r\n\t\thtmlReport.toHtml(null);\r\n\t\tassertNotEmptyAndClear(writer);\r\n\t}\r\n\r\n\t/** Test.\r\n\t * @throws IOException e */\r\n\t@Test\r\n\tpublic void testWithNoDatabase() throws IOException {\r\n\t\tfinal HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList,\r\n\t\t\t\tPeriod.TOUT, writer);\r\n\t\thtmlReport.toHtml(null);\r\n\t\tassertNotEmptyAndClear(writer);\r\n\t}\r\n\r\n\t/** Test.\r\n\t * @throws IOException e */\r\n\t@Test\r\n\tpublic void testEmptyHtmlCounterRequestContext() throws IOException {\r\n\t\tfinal HtmlCounterRequestContextReport report = new HtmlCounterRequestContextReport(\r\n\t\t\t\tCollections. emptyList(), Collections\r\n\t\t\t\t\t\t. emptyMap(), Collections\r\n\t\t\t\t\t\t. emptyList(), true, writer);\r\n\t\treport.toHtml();\r\n\t\tif (writer.getBuffer().length() != 0) {\r\n\t\t\tfail(\"HtmlCounterRequestContextReport\");\r\n\t\t}\r\n\t}\r\n\r\n\tprivate static void setProperty(Parameter parameter, String value) {\r\n\t\tSystem.setProperty(Parameters.PARAMETER_SYSTEM_PREFIX + parameter.getCode(), value);\r\n\t}\r\n\r\n\tprivate static void assertNotEmptyAndClear(final StringWriter writer) {\r\n\t\tassertTrue(\"rapport vide\", writer.getBuffer().length() > 0);\r\n\t\twriter.getBuffer().setLength(0);\r\n\t}\r\n\r\n\t/** Test.\r\n\t * @throws IOException e */\r\n\t@Test\r\n\tpublic void testToHtmlEn() throws IOException {\r\n\t\tI18N.bindLocale(Locale.UK);\r\n\t\ttry {\r\n\t\t\tassertEquals(\"locale en\", Locale.UK, I18N.getCurrentLocale());\r\n\r\n\t\t\t// counter avec 3 requêtes\r\n\t\t\tcounter.addRequest(\"test1\", 0, 0, false, 1000);\r\n\t\t\tcounter.addRequest(\"test2\", 1000, 500, false, 1000);\r\n\t\t\tcounter.addRequest(\"test3\", 10000, 5000, true, 10000);\r\n\t\t\tfinal HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList,\r\n\t\t\t\t\tPeriod.TOUT, writer);\r\n\t\t\thtmlReport.toHtml(\"message\");\r\n\t\t\tassertNotEmptyAndClear(writer);\r\n\t\t} finally {\r\n\t\t\tI18N.unbindLocale();\r\n\t\t}\r\n\t}\r\n}\r\n"},"message":{"kind":"string","value":"compléments tests unitaires"},"old_file":{"kind":"string","value":"javamelody-core/src/test/java/net/bull/javamelody/TestHtmlReport.java"},"subject":{"kind":"string","value":"compléments tests unitaires"},"git_diff":{"kind":"string","value":"avamelody-core/src/test/java/net/bull/javamelody/TestHtmlReport.java\n \t\ttry {\n \t\t\thtmlReport.writeConnections(JdbcWrapper.getConnectionInformationsList(), false);\n \t\t\thtmlReport.writeConnections(JdbcWrapper.getConnectionInformationsList(), true);\n\t\t\thtmlReport.writeDatabase(new DatabaseInformations(0));\n\t\t\thtmlReport.writeDatabase(new DatabaseInformations(0)); // h2.memory\n\t\t\thtmlReport.writeDatabase(new DatabaseInformations(3)); // h2.settings avec nbColumns==2\n \t\t\tHtmlReport.writeAddAndRemoveApplicationLinks(null, writer);\n \t\t\tHtmlReport.writeAddAndRemoveApplicationLinks(\"test\", writer);\n \t\t\tsetProperty(Parameter.SYSTEM_ACTIONS_ENABLED, \"true\");"}}},{"rowIdx":1937,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"24f1f80389bb1adb8980b0a82e4dbe19fb250c41"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"bd-dev-mobileum/presto,bd-dev-mobileum/presto,bd-dev-mobileum/presto,bd-dev-mobileum/presto,bd-dev-mobileum/presto"},"new_contents":{"kind":"string","value":"/*\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.facebook.presto.raptor.storage;\n\nimport com.google.inject.Binder;\nimport com.google.inject.Module;\nimport com.google.inject.Scopes;\n\nimport static io.airlift.configuration.ConfigurationModule.bindConfig;\n\npublic class StorageModule\n implements Module\n{\n @Override\n public void configure(Binder binder)\n {\n bindConfig(binder).to(StorageManagerConfig.class);\n binder.bind(StorageManager.class).to(OrcStorageManager.class).in(Scopes.SINGLETON);\n }\n}\n"},"new_file":{"kind":"string","value":"presto-raptor/src/main/java/com/facebook/presto/raptor/storage/StorageModule.java"},"old_contents":{"kind":"string","value":"/*\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.facebook.presto.raptor.storage;\n\nimport com.google.inject.Binder;\nimport com.google.inject.Module;\nimport com.google.inject.Provides;\nimport com.google.inject.Scopes;\nimport io.airlift.dbpool.H2EmbeddedDataSource;\nimport io.airlift.dbpool.H2EmbeddedDataSourceConfig;\nimport io.airlift.units.Duration;\nimport org.skife.jdbi.v2.DBI;\nimport org.skife.jdbi.v2.IDBI;\n\nimport javax.inject.Singleton;\n\nimport java.io.File;\n\nimport static io.airlift.configuration.ConfigurationModule.bindConfig;\nimport static java.util.concurrent.TimeUnit.SECONDS;\n\npublic class StorageModule\n implements Module\n{\n @Override\n public void configure(Binder binder)\n {\n bindConfig(binder).to(StorageManagerConfig.class);\n binder.bind(StorageManager.class).to(OrcStorageManager.class).in(Scopes.SINGLETON);\n }\n\n @Provides\n @Singleton\n @ForStorageManager\n public IDBI createLocalStorageManagerDBI(StorageManagerConfig config)\n throws Exception\n {\n return new DBI(new H2EmbeddedDataSource(new H2EmbeddedDataSourceConfig()\n .setFilename(new File(config.getDataDirectory(), \"db/StorageManager\").getAbsolutePath())\n .setMaxConnections(500)\n .setMaxConnectionWait(new Duration(1, SECONDS))));\n }\n}\n"},"message":{"kind":"string","value":"Remove unused StorageManager H2 database\n"},"old_file":{"kind":"string","value":"presto-raptor/src/main/java/com/facebook/presto/raptor/storage/StorageModule.java"},"subject":{"kind":"string","value":"Remove unused StorageManager H2 database"},"git_diff":{"kind":"string","value":"resto-raptor/src/main/java/com/facebook/presto/raptor/storage/StorageModule.java\n \n import com.google.inject.Binder;\n import com.google.inject.Module;\nimport com.google.inject.Provides;\n import com.google.inject.Scopes;\nimport io.airlift.dbpool.H2EmbeddedDataSource;\nimport io.airlift.dbpool.H2EmbeddedDataSourceConfig;\nimport io.airlift.units.Duration;\nimport org.skife.jdbi.v2.DBI;\nimport org.skife.jdbi.v2.IDBI;\n\nimport javax.inject.Singleton;\n\nimport java.io.File;\n \n import static io.airlift.configuration.ConfigurationModule.bindConfig;\nimport static java.util.concurrent.TimeUnit.SECONDS;\n \n public class StorageModule\n implements Module\n bindConfig(binder).to(StorageManagerConfig.class);\n binder.bind(StorageManager.class).to(OrcStorageManager.class).in(Scopes.SINGLETON);\n }\n\n @Provides\n @Singleton\n @ForStorageManager\n public IDBI createLocalStorageManagerDBI(StorageManagerConfig config)\n throws Exception\n {\n return new DBI(new H2EmbeddedDataSource(new H2EmbeddedDataSourceConfig()\n .setFilename(new File(config.getDataDirectory(), \"db/StorageManager\").getAbsolutePath())\n .setMaxConnections(500)\n .setMaxConnectionWait(new Duration(1, SECONDS))));\n }\n }"}}},{"rowIdx":1938,"cells":{"lang":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"d016a7d1aa58be19dc52ee80ba7a06be735995ba"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"Esri/crowdsource-reporter,Esri/crowdsource-reporter"},"new_contents":{"kind":"string","value":"/*global define */\n/*\n | Copyright 2014 Esri\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 */\ndefine({\n root: ({\n map: {\n error: \"Unable to create map\",\n licenseError: {\n message: \"Your account is not licensed to use Configurable Apps that are not public. Please ask your organization administrator to assign you a user type that includes Essential Apps or an add-on Essential Apps license.\",\n title: \"Not Licensed\"\n },\n warningMessageTitle: \"Limited browser support\",\n warningMessageAGOL: \"You are using a browser that is deprecated. Some parts of this application may not work optimally or at all in this browser. Support for this browser will be discontinued in the future.

Please use the latest versions of Google Chrome, Mozilla Firefox, Apple Safari, or Microsoft Edge.

For more information on browser support, see our documentation. Provide your feedback through GeoNet, the Esri Community.\",\n warningMessageEnterprise: \"You are using a browser that is no longer supported. Some parts of this application may not work optimally or at all in this browser.

Please use the latest versions of Google Chrome, Mozilla Firefox, Apple Safari, or Microsoft Edge.\",\n zoomInTooltip: \"Zoom in\", // Command button to zoom in to the map\n zoomOutTooltip: \"Zoom out\", // Command button to zoom out of the map\n geolocationTooltip: \"Current location\" // Command button to navigate to the current geographical position\n },\n main: {\n noGroup: \"No group configured\", // Shown when no group is configured in the configuration file\n submitReportButtonText: \"Submit a Report\", //Submit report text for buttons on map and list\n gotoListViewTooltip: \"List view\", // Go to List view tooltip text\n noFeatureGeomtery: \"Feature cannot be displayed\", // Error message when geometry is not available\n featureOutsideAOIMessage: \"Feature cannot be added outside study area\", // Error message when feature edits are performed outside the study area\n noEditingPermissionsMessage: \"You do not have permission to perform this action.\", //Message when user do not have editing permissions\n basemapGalleryText: \"Basemap Gallery\", // Basemap gallery text\n basemapThumbnailAltText: \"Click to load ${basemapTitle} ${index} of ${totalBasemaps}\", //Alt text for basemap thumbnail\n legendText: \"Legend\", //Legend text\n featureNotFoundMessage: \"Requested feature not found\", //Message displayed when feature is not found\n backButton:\"back\",\n panelCloseButton: \"Close\" //Title for on screen widgets close button basemap/legend\n },\n signin: {\n guestSigninText: \"Proceed as Guest\", // Shown in the 'Sign in' page below the icon for accessing application as an anonymous user\n signInOrText: \"Or\", // Or text on sign in screen\n signinOptionsText: \"Sign in with:\", // Shown in the 'Sign in' page above the icons for social media sign in\n noGroupNameText: \"Please sign in\", // Shown when the group title is not available or the group is private\n guestLoginTooltip: \"Sign in as a guest\", // Command button to access the application as an anonymous user\n facebookLoginTooltip: \"Sign in with Facebook\", // Command button to access the application via Facebook login\n twitterLoginTooltip: \"Sign in with Twitter\", // Command button to access the application via Twitter login\n googlePlusLoginTooltip: \"Sign in with Google+\", // Command button to access the application via Google+ login\n agolLoginTooltip: \"Sign in with ArcGIS\" // Command button to access the application via AGOL login\n },\n webMapList: {\n owner: \"Owner\", // Shown in the 'Map information' section indicating the owner of the webmap\n created: \"Date created\", // Shown in the 'Map information' section indicating the date when the webmap was created\n modified: \"Date modified\", // Shown in the 'Map information' section indicating the date when the webmap was modified\n description: \"Description\", // Shown in the 'Map information' section describing the webmap\n snippet: \"Summary\", // Shown in the 'Map information' section providing the summary of the webmap\n licenseInfo: \"Access and use constraints\", // Shown in the map information section indicating the webmap license information\n accessInformation: \"Credits\", // Shown in the 'Map information' section indicating account credits\n tags: \"Tags\", // Shown in the 'Map information' section indicating tags of the webmap\n numViews: \"Number of views\", // Shown in the 'Map information' section indicating number of times the webmap has been viewed\n avgRating: \"Rating\", // Shown in the 'Map information' section indicating webmap rating\n noWebMapInGroup: \"Configured group is invalid or no items have been shared with this group yet.\", // Shown when the configured group is invalid/private or no items have been shared with the group\n infoBtnToolTip: \"Map information\" // Command button to view the 'Map information'\n },\n issueWall: {\n noResultsFound: \"No features found\", // Shown in the issue wall when no issues are present in layer\n noResultsFoundInCurrentBuffer: \"No features found near you\", // Shown in the issue wall when no issues are present in the current buffer extent\n unableToFetchFeatureError: \"Unable to complete operation\", // Shown in the issue wall when layer does not return any features and throws an error\n gotoWebmapListTooltip: \"Go to main list\", // Tooltip for back icon in list header\n gotoMapViewTooltip: \"Map view\" // Tooltip for map-it icon in list header\n },\n appHeader: {\n help: \"Help\", //fallback title for accessibility\n myReport: \"My Submissions\", // Command button shown in mobile menu list\n signIn: \"Sign In\", // Command button shown in mobile menu list and in appheader\n signOut: \"Sign Out\", // Command button shown in mobile menu list\n signInTooltip: \"Sign in\", // Tooltip to 'Sign in' option\n signOutTooltip: \"Sign out\", // Tooltip to 'Sign out' option\n myReportTooltip: \"View my submissions\", // Tooltip to 'My Reports' option\n share: \"Share\", //Tooltip share button\n shareDialogTitle: \"Share Dialog\", //Share dialog header\n shareDialogAppURLLabel: \"Application URL\", // App url label\n mobileHamburger: \"Hamburger\" //Hamburger button\n },\n geoform: {\n enterInformation: \"Details\", // Shown as the first section of the geoform, where the user can enter details of the issue\n selectAttachments: \"Attachments\", // Appears above 'Select file' button indicating option to attach files\n selectFileText: \"Browse\", // Command button to open a dialog box to select file(s) to be attached\n enterLocation: \"Location\", // Shown as the second section of the geoform, where the user can select a location on the map\n reportItButton: \"Report It\", // Command button to submit the geoform to report an issue\n editReportButton: \"Update\", // Command button to edit reported issue\n cancelButton: \"Cancel\", //Command button to close the geoform\n requiredField: \"(required)\", // Shown next to the field in which the data is mandatory\n selectDefaultText: \"Select&hellip;\", // Shown in the dropdown field indicating to select an option\n invalidInputValue: \"Please enter valid value.\", // Shown when user clicks/taps the required field but does not enter the data and comes out of the required field\n noFieldsConfiguredMessage: \"Layer fields are not configured to capture data\", // Shown when all the fields of the selected layer are disabled\n invalidSmallNumber: \"Please enter an integer\", // Shown when the entered value is beyond the specified range (valid ${openStrong}integer${closeStrong} value between -32768 and 32767.)\n invalidNumber: \"Please enter an integer\", // Shown when the entered value is beyond the specified range (valid ${openStrong}integer${closeStrong} value between -2147483648 and 2147483647.)\n invalidFloat: \"Please enter a number\", // Shown when the entered value is beyond the specified range (valid ${openStrong}floating point${closeStrong} value between -3.4E38 and 1.2E38 )\n invalidDouble: \"Please enter a number\", // Shown when the entered value is beyond the specified range (valid ${openStrong}double${closeStrong} value between -2.2E308 and 1.8E308)\n requiredFields: \"Please provide values for all required fields\", // Shown when user submits the geoform without entering data in the mandatory field(s)\n selectLocation: \"Please select the location for your report\", // Shown when user submits the geoform without selecting location on the map\n numericRangeHintMessage: \"${openStrong}Hint:${closeStrong} Minimum value ${minValue} and Maximum value ${maxValue}\", // Shown as a pop over above the fields with numeric values, indicating the minimum and maximum range\n dateRangeHintMessage: \"${openStrong}Hint:${closeStrong} Minimum Date ${minValue} and Maximum Date ${maxValue}\", // Shown as a pop over above the fields with date values, indicating the minimum and maximum date range\n errorsInApplyEdits: \"Values could not be submitted.\", // Shown when there is an error in any of the services while submitting the geoform\n attachmentSelectedMsg: \"attachment(s) selected\", // Shown besides the select file button indicating the number of files attached\n attachmentUploadStatus: \"${failed} of ${total} attachment(s) failed to upload\", // Shown when there is error while uploading the attachment, while submitting the geoform\n geoLocationError: \"Current location not available\", // Shown when the browser returns an error instead of the current geographical position\n geoLocationOutOfExtent: \"Current location is out of basemap extent\", // Shown when the current geographical position is out of the basemap extent\n submitButtonTooltip: \"Submit\", // Command button to open the geoform\n cancelButtonTooltip: \"Cancel\", //tooltip for cancel button\n geoformBackButtonTooltip: \"Return to the list\", //tooltip for Geoform back button\n locationSelectionHintForPointLayer : \"Tap the map to draw the location.\", //hint text for selecting location incase of point layer\n locationSelectionHintForPolygonLayer : \"Tap the map to draw the location. Double tap to complete the drawing.\", //hint text for selecting location incase of line and polygon layer\n locationSelectionHintForPointLayerDesktop : \"Click the map to draw the location.\", //hint text for selecting location incase of point layer\n locationSelectionHintForPolygonLayerDesktop : \"Click the map to draw the location. Double click to complete the drawing.\", //hint text for selecting location incase of line and polygon layer\n locationDialogTitle: \"Select location for report\", //Title for location dialog header\n locationDialogContent: \"Are you sure you want to use image location ?\", //Content for location dialog\n errorMessageText: \"${message} for field ${fieldName}\",\n deleteAttachmentBtnText: \"Delete attachment\"\n },\n locator: {\n addressText: \"Address:\", // Shown as a title for a group of addresses returned on performing unified search\n usngText: \"USNG\", // Shown as a title for a group of USNG values returned on performing unified search\n mgrsText: \"MGRS\", // Shown as a title for a group of MGRS values returned on performing unified search\n latLongText: \"Latitude/Longitude\", // Shown as a title for a group of latitude longitude values returned on performing unified search\n invalidSearch: \"No results found\", // Shown in the address container when no results are returned on performing unified search\n locatorPlaceholder: \"Enter an address to search\", // Shown in the address container textbox as a placeholder\n locationOutOfExtent: \"Location is outside the submission area\", // Shown as an alert when the selected address in the search result is out of basemap extent\n searchButtonTooltip: \"Search\", // Tooltip for search button\n clearButtonTooltip: \"Clear search value\" // Tooltip for Geocoder clear button\n },\n myIssues: {\n title: \"My Submissions\", // Shown as a title in 'My issues' panel\n myIssuesTooltip: \"My Submissions\", // Command button to access issues reported by the logged in user\n noResultsFound: \"No submissions found\" // Shown when no issues are reported by the logged in user\n },\n itemDetails: { // Detailed information about an item and a list of its comments\n likeButtonLabel: \"\", // Command button for up-voting a report\n likeButtonTooltip: \"I agree\", // Tooltip for Like button\n commentButtonLabel: \"\", // Command button for submitting feedback\n commentButtonTooltip: \"Leave a reply\", // Tooltip for Comment button\n galleryButtonLabel: \"\", // Command button for opening and closing attachment file gallery\n galleryButtonTooltip: \"See attached documents\", // Tooltip for command button shown in details panel\n mapButtonLabel: \"View on Map\", // Command button shown in details panel\n mapButtonTooltip: \"View the location of this submission\", // Tooltip for Gallery button\n commentsListHeading: \"Comments\", // List heading for Comments section in details panel\n unableToUpdateVoteField: \"Your vote cannot be counted at this time.\", // Error message for feature unable to update\n gotoIssueListTooltip: \"View the list of submissions\", // Tooltip for back icon in Issue list header\n deleteMessage : \"Are you sure you want to delete?\", //shown when user tries to delete a report or comment\n },\n itemList: { // List of feature layer items shown in my-issues and issue-wall\n likesForThisItemTooltip: \"Number of votes\", //Shown on hovering of the like icon in my-issues and issue-wall\n loadMoreButtonText: \"Load More...\" //Text for load more button\n },\n comment: {\n commentsFormHeading: \"Comment\",\n commentsFormSubmitButton: \"Submit Comment\",\n commentsFormEditButton: \"Update Comment\",\n commentsFormCancelButton: \"Cancel\",\n errorInSubmittingComment: \"Comment could not be submitted.\", // Shown when user is unable to add comments\n commentSubmittedMessage: \"Thank you for your feedback.\", // Shown when user is comment is successfully submitted\n emptyCommentMessage: \"Please enter a comment.\", // Shown when user submits a comment without any text/character\n placeHolderText: \"Type a comment\", // Shown as a placeholder in comments textbox\n noCommentsAvailableText: \"No comments available\", // Shown when no comments are available for the selected issue\n remainingTextCount: \"${0} character(s) remain\", // Shown below the comments textbox indicating the number of characters that can be added\n showNoText: \"No\", // Shown when comments character limit is exceeded\n selectAttachments: \"Attachments\", // Appears above 'Select file' button indicating option to attach files while adding comments\n selectFileText: \"Browse\", // Command button to open a dialog box to select file(s) to be attached\n attachmentSelectedMsg: \"attachment(s) selected\", // Shown besides the select file button indicating the number of files attached\n attachmentHeaderText: \"Attachments\", //attachment header Text\n unknownCommentAttachment: \"FILE\", // displayed for attached file having unknown extension\n editRecordText: \"Edit\", // Displayed on hover of edit comment button\n deleteRecordText: \"Delete\", // Displayed on hover of delete comment button\n deleteCommentFailedMessage: \"Unable to delete comment\" // Displayed when delete comment operation gets failed\n },\n gallery: {\n galleryHeaderText: \"Gallery\",\n noAttachmentsAvailableText: \"No attachments found\" // Shown when no comments are available for the selected issue\n },\n dialog: {\n okButton: \"Ok\",\n cancelButton: \"Cancel\",\n yesButton: \"Yes\",\n noButton: \"No\"\n }\n }),\n \"ar\": 1,\n \"bs\": 1,\n \"ca\": 1,\n \"cs\": 1,\n \"da\": 1,\n \"de\": 1,\n \"el\": 1,\n \"es\": 1,\n \"et\": 1,\n \"fi\": 1,\n \"fr\": 1,\n \"he\": 1,\n \"hr\": 1,\n \"hu\": 1,\n \"id\": 1,\n \"it\": 1,\n \"ja\": 1,\n \"ko\": 1,\n \"lt\": 1,\n \"lv\": 1,\n \"nb\": 1,\n \"nl\": 1,\n \"pl\": 1,\n \"pt-br\": 1,\n \"pt-pt\": 1,\n \"ro\": 1,\n \"ru\": 1,\n \"sl\": 1,\n \"sk\": 1,\n \"sr\": 1,\n \"sv\": 1,\n \"th\": 1,\n \"tr\": 1,\n \"uk\": 1,\n \"vi\": 1,\n \"zh-cn\": 1,\n \"zh-hk\": 1,\n \"zh-tw\": 1\n});\n"},"new_file":{"kind":"string","value":"js/nls/resources.js"},"old_contents":{"kind":"string","value":"/*global define */\n/*\n | Copyright 2014 Esri\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 */\ndefine({\n root: ({\n map: {\n error: \"Unable to create map\",\n licenseError: {\n message: \"Your account is not licensed to use Configurable Apps that are not public. Please ask your organization administrator to assign you a user type that includes Essential Apps or an add-on Essential Apps license.\",\n title: \"Not Licensed\"\n },\n warningMessageTitle: \"Limited browser support\",\n warningMessageAGOL: \"You are using a browser that is deprecated. Some parts of this application may not work optimally or at all in this browser. Support for this browser will be discontinued in the future.

Please use the latest versions of Google Chrome, Mozilla Firefox, Apple Safari, or Microsoft Edge.

For more information on browser support, see our documentation. Provide your feedback through GeoNet, the Esri Community.\",\n warningMessageEnterprise: \"You are using a browser that is no longer supported. Some parts of this application may not work optimally or at all in this browser.

Please use the latest versions of Google Chrome, Mozilla Firefox, Apple Safari, or Microsoft Edge.\",\n zoomInTooltip: \"Zoom in\", // Command button to zoom in to the map\n zoomOutTooltip: \"Zoom out\", // Command button to zoom out of the map\n geolocationTooltip: \"Current location\" // Command button to navigate to the current geographical position\n },\n main: {\n noGroup: \"No group configured\", // Shown when no group is configured in the configuration file\n submitReportButtonText: \"Submit a Report\", //Submit report text for buttons on map and list\n gotoListViewTooltip: \"List view\", // Go to List view tooltip text\n noFeatureGeomtery: \"Feature cannot be displayed\", // Error message when geometry is not available\n featureOutsideAOIMessage: \"Feature cannot be added outside study area\", // Error message when feature edits are performed outside the study area\n noEditingPermissionsMessage: \"You do not have permission to perform this action.\", //Message when user do not have editing permissions\n basemapGalleryText: \"Basemap Gallery\", // Basemap gallery text\n basemapThumbnailAltText: \"Click to load ${basemapTitle} ${index} of ${totalBasemaps}\", //Alt text for basemap thumbnail\n legendText: \"Legend\", //Legend text\n featureNotFoundMessage: \"Requested feature not found\", //Message displayed when feature is not found\n backButton:\"back\",\n panelCloseButton: \"Close\" //Title for on screen widgets close button basemap/legend\n },\n signin: {\n guestSigninText: \"Proceed as Guest\", // Shown in the 'Sign in' page below the icon for accessing application as an anonymous user\n signInOrText: \"Or\", // Or text on sign in screen\n signinOptionsText: \"Sign in with:\", // Shown in the 'Sign in' page above the icons for social media sign in\n noGroupNameText: \"Please sign in\", // Shown when the group title is not available or the group is private\n guestLoginTooltip: \"Sign in as a guest\", // Command button to access the application as an anonymous user\n facebookLoginTooltip: \"Sign in with Facebook\", // Command button to access the application via Facebook login\n twitterLoginTooltip: \"Sign in with Twitter\", // Command button to access the application via Twitter login\n googlePlusLoginTooltip: \"Sign in with Google+\", // Command button to access the application via Google+ login\n agolLoginTooltip: \"Sign in with ArcGIS\" // Command button to access the application via AGOL login\n },\n webMapList: {\n owner: \"Owner\", // Shown in the 'Map information' section indicating the owner of the webmap\n created: \"Date created\", // Shown in the 'Map information' section indicating the date when the webmap was created\n modified: \"Date modified\", // Shown in the 'Map information' section indicating the date when the webmap was modified\n description: \"Description\", // Shown in the 'Map information' section describing the webmap\n snippet: \"Summary\", // Shown in the 'Map information' section providing the summary of the webmap\n licenseInfo: \"Access and use constraints\", // Shown in the map information section indicating the webmap license information\n accessInformation: \"Credits\", // Shown in the 'Map information' section indicating account credits\n tags: \"Tags\", // Shown in the 'Map information' section indicating tags of the webmap\n numViews: \"Number of views\", // Shown in the 'Map information' section indicating number of times the webmap has been viewed\n avgRating: \"Rating\", // Shown in the 'Map information' section indicating webmap rating\n noWebMapInGroup: \"Configured group is invalid or no items have been shared with this group yet.\", // Shown when the configured group is invalid/private or no items have been shared with the group\n infoBtnToolTip: \"Map information\" // Command button to view the 'Map information'\n },\n issueWall: {\n noResultsFound: \"No features found\", // Shown in the issue wall when no issues are present in layer\n noResultsFoundInCurrentBuffer: \"No features found near you\", // Shown in the issue wall when no issues are present in the current buffer extent\n unableToFetchFeatureError: \"Unable to complete operation\", // Shown in the issue wall when layer does not return any features and throws an error\n gotoWebmapListTooltip: \"Go to main list\", // Tooltip for back icon in list header\n gotoMapViewTooltip: \"Map view\" // Tooltip for map-it icon in list header\n },\n appHeader: {\n help: \"Help\", //fallback title for accessibility\n myReport: \"My Submissions\", // Command button shown in mobile menu list\n signIn: \"Sign In\", // Command button shown in mobile menu list and in appheader\n signOut: \"Sign Out\", // Command button shown in mobile menu list\n signInTooltip: \"Sign in\", // Tooltip to 'Sign in' option\n signOutTooltip: \"Sign out\", // Tooltip to 'Sign out' option\n myReportTooltip: \"View my submissions\", // Tooltip to 'My Reports' option\n share: \"Share\", //Tooltip share button\n shareDialogTitle: \"Share Dialog\", //Share dialog header\n shareDialogAppURLLabel: \"Application URL\", // App url label\n mobileHamburger: \"Hamburger\" //Hamburger button\n },\n geoform: {\n enterInformation: \"Details\", // Shown as the first section of the geoform, where the user can enter details of the issue\n selectAttachments: \"Attachments\", // Appears above 'Select file' button indicating option to attach files\n selectFileText: \"Browse\", // Command button to open a dialog box to select file(s) to be attached\n enterLocation: \"Location\", // Shown as the second section of the geoform, where the user can select a location on the map\n reportItButton: \"Report It\", // Command button to submit the geoform to report an issue\n editReportButton: \"Update\", // Command button to edit reported issue\n cancelButton: \"Cancel\", //Command button to close the geoform\n requiredField: \"(required)\", // Shown next to the field in which the data is mandatory\n selectDefaultText: \"Select&hellip;\", // Shown in the dropdown field indicating to select an option\n invalidInputValue: \"Please enter valid value.\", // Shown when user clicks/taps the required field but does not enter the data and comes out of the required field\n noFieldsConfiguredMessage: \"Layer fields are not configured to capture data\", // Shown when all the fields of the selected layer are disabled\n invalidSmallNumber: \"Please enter an integer\", // Shown when the entered value is beyond the specified range (valid ${openStrong}integer${closeStrong} value between -32768 and 32767.)\n invalidNumber: \"Please enter an integer\", // Shown when the entered value is beyond the specified range (valid ${openStrong}integer${closeStrong} value between -2147483648 and 2147483647.)\n invalidFloat: \"Please enter a number\", // Shown when the entered value is beyond the specified range (valid ${openStrong}floating point${closeStrong} value between -3.4E38 and 1.2E38 )\n invalidDouble: \"Please enter a number\", // Shown when the entered value is beyond the specified range (valid ${openStrong}double${closeStrong} value between -2.2E308 and 1.8E308)\n requiredFields: \"Please provide values for all required fields\", // Shown when user submits the geoform without entering data in the mandatory field(s)\n selectLocation: \"Please select the location for your report\", // Shown when user submits the geoform without selecting location on the map\n numericRangeHintMessage: \"${openStrong}Hint:${closeStrong} Minimum value ${minValue} and Maximum value ${maxValue}\", // Shown as a pop over above the fields with numeric values, indicating the minimum and maximum range\n dateRangeHintMessage: \"${openStrong}Hint:${closeStrong} Minimum Date ${minValue} and Maximum Date ${maxValue}\", // Shown as a pop over above the fields with date values, indicating the minimum and maximum date range\n errorsInApplyEdits: \"Values could not be submitted.\", // Shown when there is an error in any of the services while submitting the geoform\n attachmentSelectedMsg: \"attachment(s) selected\", // Shown besides the select file button indicating the number of files attached\n attachmentUploadStatus: \"${failed} of ${total} attachment(s) failed to upload\", // Shown when there is error while uploading the attachment, while submitting the geoform\n geoLocationError: \"Current location not available\", // Shown when the browser returns an error instead of the current geographical position\n geoLocationOutOfExtent: \"Current location is out of basemap extent\", // Shown when the current geographical position is out of the basemap extent\n submitButtonTooltip: \"Submit\", // Command button to open the geoform\n cancelButtonTooltip: \"Cancel\", //tooltip for cancel button\n geoformBackButtonTooltip: \"Return to the list\", //tooltip for Geoform back button\n locationSelectionHintForPointLayer : \"Tap the map to draw the location.\", //hint text for selecting location incase of point layer\n locationSelectionHintForPolygonLayer : \"Tap the map to draw the location. Double tap to complete the drawing.\", //hint text for selecting location incase of line and polygon layer\n locationSelectionHintForPointLayerDesktop : \"Click the map to draw the location.\", //hint text for selecting location incase of point layer\n locationSelectionHintForPolygonLayerDesktop : \"Click the map to draw the location. Double click to complete the drawing.\", //hint text for selecting location incase of line and polygon layer\n locationDialogTitle: \"Select location for report\", //Title for location dialog header\n locationDialogContent: \"Are you sure you want to use image location ?\", //Content for location dialog\n errorMessageText: \"${message} for field ${fieldName}\",\n deleteAttachmentBtnText: \"Delete attachment\"\n },\n locator: {\n addressText: \"Address:\", // Shown as a title for a group of addresses returned on performing unified search\n usngText: \"USNG\", // Shown as a title for a group of USNG values returned on performing unified search\n mgrsText: \"MGRS\", // Shown as a title for a group of MGRS values returned on performing unified search\n latLongText: \"Latitude/Longitude\", // Shown as a title for a group of latitude longitude values returned on performing unified search\n invalidSearch: \"No results found\", // Shown in the address container when no results are returned on performing unified search\n locatorPlaceholder: \"Enter an address to search\", // Shown in the address container textbox as a placeholder\n locationOutOfExtent: \"Location is outside the submission area\", // Shown as an alert when the selected address in the search result is out of basemap extent\n searchButtonTooltip: \"Search\", // Tooltip for search button\n clearButtonTooltip: \"Clear search value\" // Tooltip for Geocoder clear button\n },\n myIssues: {\n title: \"My Submissions\", // Shown as a title in 'My issues' panel\n myIssuesTooltip: \"My Submissions\", // Command button to access issues reported by the logged in user\n noResultsFound: \"No submissions found\" // Shown when no issues are reported by the logged in user\n },\n itemDetails: { // Detailed information about an item and a list of its comments\n likeButtonLabel: \"\", // Command button for up-voting a report\n likeButtonTooltip: \"I agree\", // Tooltip for Like button\n commentButtonLabel: \"\", // Command button for submitting feedback\n commentButtonTooltip: \"Leave a reply\", // Tooltip for Comment button\n galleryButtonLabel: \"\", // Command button for opening and closing attachment file gallery\n galleryButtonTooltip: \"See attached documents\", // Tooltip for command button shown in details panel\n mapButtonLabel: \"View on Map\", // Command button shown in details panel\n mapButtonTooltip: \"View the location of this submission\", // Tooltip for Gallery button\n commentsListHeading: \"Comments\", // List heading for Comments section in details panel\n unableToUpdateVoteField: \"Your vote cannot be counted at this time.\", // Error message for feature unable to update\n gotoIssueListTooltip: \"View the list of submissions\", // Tooltip for back icon in Issue list header\n deleteMessage : \"Are you sure you want to delete?\", //shown when user tries to delete a report or comment\n },\n itemList: { // List of feature layer items shown in my-issues and issue-wall\n likesForThisItemTooltip: \"Number of votes\", //Shown on hovering of the like icon in my-issues and issue-wall\n loadMoreButtonText: \"Load More...\" //Text for load more button\n },\n comment: {\n commentsFormHeading: \"Comment\",\n commentsFormSubmitButton: \"Submit Comment\",\n commentsFormEditButton: \"Update Comment\",\n commentsFormCancelButton: \"Cancel\",\n errorInSubmittingComment: \"Comment could not be submitted.\", // Shown when user is unable to add comments\n commentSubmittedMessage: \"Thank you for your feedback.\", // Shown when user is comment is successfully submitted\n emptyCommentMessage: \"Please enter a comment.\", // Shown when user submits a comment without any text/character\n placeHolderText: \"Type a comment\", // Shown as a placeholder in comments textbox\n noCommentsAvailableText: \"No comments available\", // Shown when no comments are available for the selected issue\n remainingTextCount: \"${0} character(s) remain\", // Shown below the comments textbox indicating the number of characters that can be added\n showNoText: \"No\", // Shown when comments character limit is exceeded\n selectAttachments: \"Attachments\", // Appears above 'Select file' button indicating option to attach files while adding comments\n selectFileText: \"Browse\", // Command button to open a dialog box to select file(s) to be attached\n attachmentSelectedMsg: \"attachment(s) selected\", // Shown besides the select file button indicating the number of files attached\n attachmentHeaderText: \"Attachments\", //attachment header Text\n unknownCommentAttachment: \"FILE\", // displayed for attached file having unknown extension\n editRecordText: \"Edit\", // Displayed on hover of edit comment button\n deleteRecordText: \"Delete\", // Displayed on hover of delete comment button\n deleteCommentFailedMessage: \"Unable to delete comment\" // Displayed when delete comment operation gets failed\n },\n gallery: {\n galleryHeaderText: \"Gallery\",\n noAttachmentsAvailableText: \"No attachments found\" // Shown when no comments are available for the selected issue\n },\n dialog: {\n okButton: \"Ok\",\n cancelButton: \"Cancel\",\n yesButton: \"Yes\",\n noButton: \"No\"\n }\n }),\n \"ar\": 1,\n \"bs\": 1,\n \"ca\": 1,\n \"cs\": 1,\n \"da\": 1,\n \"de\": 1,\n \"el\": 1,\n \"es\": 1,\n \"et\": 1,\n \"fi\": 1,\n \"fr\": 1,\n \"he\": 1,\n \"hr\": 1,\n \"hu\": 1,\n \"id\": 1,\n \"it\": 1,\n \"ja\": 1,\n \"ko\": 1,\n \"lt\": 1,\n \"lv\": 1,\n \"nb\": 1,\n \"nl\": 1,\n \"pl\": 1,\n \"pt-br\": 1,\n \"pt-pt\": 1,\n \"ro\": 1,\n \"ru\": 1,\n \"sl\": 1,\n \"sr\": 1,\n \"sv\": 1,\n \"th\": 1,\n \"tr\": 1,\n \"uk\": 1,\n \"vi\": 1,\n \"zh-cn\": 1,\n \"zh-hk\": 1,\n \"zh-tw\": 1\n});\n"},"message":{"kind":"string","value":"enable slovak\n"},"old_file":{"kind":"string","value":"js/nls/resources.js"},"subject":{"kind":"string","value":"enable slovak"},"git_diff":{"kind":"string","value":"s/nls/resources.js\n \"ro\": 1,\n \"ru\": 1,\n \"sl\": 1,\n \"sk\": 1,\n \"sr\": 1,\n \"sv\": 1,\n \"th\": 1,"}}},{"rowIdx":1939,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"88e2960b440103d40f46c6cc2e8d3de3c686d7d3"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"youdonghai/intellij-community,semonte/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,da1z/intellij-community,da1z/intellij-community,xfournet/intellij-community,da1z/intellij-community,asedunov/intellij-community,ibinti/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,signed/intellij-community,asedunov/intellij-community,semonte/intellij-community,xfournet/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,da1z/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,apixandru/intellij-community,semonte/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,FHannes/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,fitermay/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,signed/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,mglukhikh/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,semonte/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,ibinti/intellij-community,semonte/intellij-community,xfournet/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,semonte/intellij-community,ibinti/intellij-community,allotria/intellij-community,FHannes/intellij-community,da1z/intellij-community,apixandru/intellij-community,da1z/intellij-community,da1z/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,xfournet/intellij-community,allotria/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,semonte/intellij-community,FHannes/intellij-community,FHannes/intellij-community,ibinti/intellij-community,fitermay/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,hurricup/intellij-community,ibinti/intellij-community,signed/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,apixandru/intellij-community,allotria/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,ibinti/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,allotria/intellij-community,signed/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,apixandru/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,signed/intellij-community,allotria/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,fitermay/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,fitermay/intellij-community,FHannes/intellij-community,hurricup/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,da1z/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,xfournet/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,xfournet/intellij-community,ibinti/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,signed/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,xfournet/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,signed/intellij-community,asedunov/intellij-community,signed/intellij-community,asedunov/intellij-community,apixandru/intellij-community,allotria/intellij-community,hurricup/intellij-community,xfournet/intellij-community"},"new_contents":{"kind":"string","value":"/*\n * Copyright 2000-2016 JetBrains s.r.o.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.intellij.ide.bookmarks;\n\nimport com.intellij.codeInsight.daemon.GutterMark;\nimport com.intellij.icons.AllIcons;\nimport com.intellij.ide.IdeBundle;\nimport com.intellij.ide.structureView.StructureViewBuilder;\nimport com.intellij.ide.structureView.StructureViewModel;\nimport com.intellij.ide.structureView.TreeBasedStructureViewBuilder;\nimport com.intellij.lang.LanguageStructureViewBuilder;\nimport com.intellij.navigation.ItemPresentation;\nimport com.intellij.navigation.NavigationItem;\nimport com.intellij.openapi.editor.Document;\nimport com.intellij.openapi.editor.RangeMarker;\nimport com.intellij.openapi.editor.colors.CodeInsightColors;\nimport com.intellij.openapi.editor.colors.EditorColors;\nimport com.intellij.openapi.editor.colors.EditorColorsManager;\nimport com.intellij.openapi.editor.ex.MarkupModelEx;\nimport com.intellij.openapi.editor.ex.RangeHighlighterEx;\nimport com.intellij.openapi.editor.impl.DocumentMarkupModel;\nimport com.intellij.openapi.editor.markup.GutterIconRenderer;\nimport com.intellij.openapi.editor.markup.HighlighterLayer;\nimport com.intellij.openapi.editor.markup.RangeHighlighter;\nimport com.intellij.openapi.editor.markup.TextAttributes;\nimport com.intellij.openapi.fileEditor.FileDocumentManager;\nimport com.intellij.openapi.fileEditor.OpenFileDescriptor;\nimport com.intellij.openapi.project.DumbAware;\nimport com.intellij.openapi.project.Project;\nimport com.intellij.openapi.util.Comparing;\nimport com.intellij.openapi.util.Ref;\nimport com.intellij.openapi.util.text.StringUtil;\nimport com.intellij.openapi.vfs.VirtualFile;\nimport com.intellij.pom.Navigatable;\nimport com.intellij.psi.PsiDocumentManager;\nimport com.intellij.psi.PsiFile;\nimport com.intellij.psi.PsiManager;\nimport com.intellij.reference.SoftReference;\nimport com.intellij.ui.ColorUtil;\nimport com.intellij.ui.JBColor;\nimport com.intellij.ui.RetrievableIcon;\nimport com.intellij.util.PlatformIcons;\nimport com.intellij.util.containers.WeakHashMap;\nimport org.jetbrains.annotations.NotNull;\nimport org.jetbrains.annotations.Nullable;\n\nimport javax.swing.*;\nimport java.awt.*;\nimport java.lang.ref.Reference;\nimport java.lang.ref.WeakReference;\n\npublic class Bookmark implements Navigatable, Comparable {\n public static final Icon DEFAULT_ICON = new MyCheckedIcon();\n\n private final VirtualFile myFile;\n @NotNull private OpenFileDescriptor myTarget;\n private final Project myProject;\n private WeakHashMap> myHighlighterRefs;\n\n private String myDescription;\n private char myMnemonic = 0;\n public static final Font MNEMONIC_FONT = new Font(\"Monospaced\", Font.PLAIN, 11);\n\n public Bookmark(@NotNull Project project, @NotNull VirtualFile file, int line, @NotNull String description) {\n myFile = file;\n myProject = project;\n myDescription = description;\n\n myTarget = new OpenFileDescriptor(project, file, line, -1, true);\n\n addHighlighter();\n }\n\n @Override\n public int compareTo(Bookmark o) {\n int i = myMnemonic != 0 ? o.myMnemonic != 0 ? myMnemonic - o.myMnemonic : -1: o.myMnemonic != 0 ? 1 : 0;\n if (i != 0) return i;\n i = myProject.getName().compareTo(o.myProject.getName());\n if (i != 0) return i;\n i = myFile.getName().compareTo(o.getFile().getName());\n if (i != 0) return i;\n return getTarget().compareTo(o.getTarget());\n }\n\n public void updateHighlighter() {\n release();\n addHighlighter();\n }\n\n private void addHighlighter() {\n Document document = FileDocumentManager.getInstance().getCachedDocument(getFile());\n if (document != null) {\n createHighlighter((MarkupModelEx)DocumentMarkupModel.forDocument(document, myProject, true));\n }\n }\n\n public RangeHighlighter createHighlighter(@NotNull MarkupModelEx markup) {\n final RangeHighlighterEx highlighter;\n int line = getLine();\n if (line >= 0) {\n highlighter = markup.addPersistentLineHighlighter(line, HighlighterLayer.ERROR + 1, null);\n if (highlighter != null) {\n highlighter.setGutterIconRenderer(new MyGutterIconRenderer(this));\n\n TextAttributes textAttributes =\n EditorColorsManager.getInstance().getGlobalScheme().getAttributes(CodeInsightColors.BOOKMARKS_ATTRIBUTES);\n\n Color stripeColor = textAttributes.getErrorStripeColor();\n highlighter.setErrorStripeMarkColor(stripeColor != null ? stripeColor : Color.black);\n highlighter.setErrorStripeTooltip(getBookmarkTooltip());\n\n TextAttributes attributes = highlighter.getTextAttributes();\n if (attributes == null) {\n attributes = new TextAttributes();\n }\n attributes.setBackgroundColor(textAttributes.getBackgroundColor());\n attributes.setForegroundColor(textAttributes.getForegroundColor());\n highlighter.setTextAttributes(attributes);\n }\n }\n else {\n highlighter = null;\n }\n if (myHighlighterRefs == null) myHighlighterRefs = new WeakHashMap<>();\n if (highlighter != null) {\n myHighlighterRefs.put(markup.getDocument(), new WeakReference(highlighter));\n }\n return highlighter;\n }\n\n @Nullable\n public Document getDocument() {\n return FileDocumentManager.getInstance().getCachedDocument(getFile());\n }\n\n public void release() {\n try {\n int line = getLine();\n if (line < 0) {\n return;\n }\n final Document document = getDocument();\n if (document == null) return;\n MarkupModelEx markup = (MarkupModelEx)DocumentMarkupModel.forDocument(document, myProject, true);\n final Document markupDocument = markup.getDocument();\n if (markupDocument.getLineCount() <= line) return;\n RangeHighlighterEx highlighter = findMyHighlighter();\n if (highlighter != null) {\n highlighter.dispose();\n }\n } finally {\n myHighlighterRefs = null;\n }\n }\n\n private RangeHighlighterEx findMyHighlighter() {\n final Document document = getDocument();\n if (document == null) return null;\n Reference reference = myHighlighterRefs != null ? myHighlighterRefs.get(document) : null;\n RangeHighlighterEx result = SoftReference.dereference(reference);\n if (result != null) {\n return result;\n }\n MarkupModelEx markup = (MarkupModelEx)DocumentMarkupModel.forDocument(document, myProject, true);\n final Document markupDocument = markup.getDocument();\n final int startOffset = 0;\n final int endOffset = markupDocument.getTextLength();\n\n final Ref found = new Ref();\n markup.processRangeHighlightersOverlappingWith(startOffset, endOffset, highlighter -> {\n GutterMark renderer = highlighter.getGutterIconRenderer();\n if (renderer instanceof MyGutterIconRenderer && ((MyGutterIconRenderer)renderer).myBookmark == Bookmark.this) {\n found.set(highlighter);\n return false;\n }\n return true;\n });\n result = found.get();\n if (result != null) {\n if (myHighlighterRefs == null) myHighlighterRefs = new WeakHashMap<>();\n myHighlighterRefs.put(document, new WeakReference(result));\n }\n return result;\n }\n\n public Icon getIcon() {\n return myMnemonic == 0 ? DEFAULT_ICON : MnemonicIcon.getIcon(myMnemonic);\n }\n\n public String getDescription() {\n return myDescription;\n }\n\n public void setDescription(String description) {\n myDescription = description;\n }\n\n public char getMnemonic() {\n return myMnemonic;\n }\n\n public void setMnemonic(char mnemonic) {\n myMnemonic = Character.toUpperCase(mnemonic);\n }\n\n @NotNull\n public VirtualFile getFile() {\n return myFile;\n }\n\n @Nullable\n public String getNotEmptyDescription() {\n return StringUtil.isEmpty(myDescription) ? null : myDescription;\n }\n\n public boolean isValid() {\n if (!getFile().isValid()) {\n return false;\n }\n if (getLine() ==-1) {\n return true;\n }\n RangeHighlighterEx highlighter = findMyHighlighter();\n return highlighter != null && highlighter.isValid();\n }\n\n @Override\n public boolean canNavigate() {\n return getTarget().canNavigate();\n }\n\n @Override\n public boolean canNavigateToSource() {\n return getTarget().canNavigateToSource();\n }\n\n @Override\n public void navigate(boolean requestFocus) {\n getTarget().navigate(requestFocus);\n }\n\n public int getLine() {\n int targetLine = myTarget.getLine();\n if (targetLine == -1) return targetLine;\n //What user sees in gutter\n RangeHighlighterEx highlighter = findMyHighlighter();\n if (highlighter != null && highlighter.isValid()) {\n Document document = getDocument();\n if (document != null) {\n return document.getLineNumber(highlighter.getStartOffset());\n }\n }\n RangeMarker marker = myTarget.getRangeMarker();\n if (marker != null && marker.isValid()) {\n Document document = marker.getDocument();\n return document.getLineNumber(marker.getStartOffset());\n }\n return targetLine;\n }\n\n private OpenFileDescriptor getTarget() {\n int line = getLine();\n if (line != myTarget.getLine()) {\n myTarget = new OpenFileDescriptor(myProject, myFile, line, -1, true);\n }\n return myTarget;\n }\n\n @Override\n public String toString() {\n StringBuilder result = new StringBuilder(getQualifiedName());\n String description = StringUtil.escapeXml(getNotEmptyDescription());\n if (description != null) {\n result.append(\": \").append(description);\n }\n return result.toString();\n }\n\n public String getQualifiedName() {\n String presentableUrl = myFile.getPresentableUrl();\n if (myFile.isDirectory()) return presentableUrl;\n\n PsiDocumentManager.getInstance(myProject).commitAllDocuments();\n final PsiFile psiFile = PsiManager.getInstance(myProject).findFile(myFile);\n\n if (psiFile == null) return presentableUrl;\n\n StructureViewBuilder builder = LanguageStructureViewBuilder.INSTANCE.getStructureViewBuilder(psiFile);\n if (builder instanceof TreeBasedStructureViewBuilder) {\n StructureViewModel model = ((TreeBasedStructureViewBuilder)builder).createStructureViewModel(null);\n Object element;\n try {\n element = model.getCurrentEditorElement();\n }\n finally {\n model.dispose();\n }\n if (element instanceof NavigationItem) {\n ItemPresentation presentation = ((NavigationItem)element).getPresentation();\n if (presentation != null) {\n presentableUrl = ((NavigationItem)element).getName() + \" \" + presentation.getLocationString();\n }\n }\n }\n\n return IdeBundle.message(\"bookmark.file.X.line.Y\", presentableUrl, getLine() + 1);\n }\n\n private String getBookmarkTooltip() {\n StringBuilder result = new StringBuilder(\"Bookmark\");\n if (myMnemonic != 0) {\n result.append(\" \").append(myMnemonic);\n }\n String description = StringUtil.escapeXml(getNotEmptyDescription());\n if (description != null) {\n result.append(\": \").append(description);\n }\n return result.toString();\n }\n\n static class MnemonicIcon implements Icon {\n private static final MnemonicIcon[] cache = new MnemonicIcon[36];//0..9 + A..Z\n private final char myMnemonic;\n\n @NotNull\n static MnemonicIcon getIcon(char mnemonic) {\n int index = mnemonic - 48;\n if (index > 9)\n index -= 7;\n if (index < 0 || index > cache.length-1)\n return new MnemonicIcon(mnemonic);\n if (cache[index] == null)\n cache[index] = new MnemonicIcon(mnemonic);\n return cache[index];\n }\n\n private MnemonicIcon(char mnemonic) {\n myMnemonic = mnemonic;\n }\n\n @Override\n public void paintIcon(Component c, Graphics g, int x, int y) {\n g.setColor(new JBColor(() -> {\n //noinspection UseJBColor\n return !darkBackground() ? new Color(0xffffcc) : new Color(0x675133);\n }));\n g.fillRect(x, y, getIconWidth(), getIconHeight());\n\n g.setColor(JBColor.GRAY);\n g.drawRect(x, y, getIconWidth(), getIconHeight());\n\n g.setColor(EditorColorsManager.getInstance().getGlobalScheme().getDefaultForeground());\n final Font oldFont = g.getFont();\n g.setFont(MNEMONIC_FONT);\n\n ((Graphics2D)g).drawString(Character.toString(myMnemonic), x + 3, y + getIconHeight() - 1.5F);\n g.setFont(oldFont);\n }\n\n @Override\n public int getIconWidth() {\n return DEFAULT_ICON.getIconWidth();\n }\n\n @Override\n public int getIconHeight() {\n return DEFAULT_ICON.getIconHeight();\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n MnemonicIcon that = (MnemonicIcon)o;\n\n return myMnemonic == that.myMnemonic;\n }\n\n @Override\n public int hashCode() {\n return (int)myMnemonic;\n }\n }\n\n private static class MyCheckedIcon implements Icon, RetrievableIcon {\n @Nullable\n @Override\n public Icon retrieveIcon() {\n return PlatformIcons.CHECK_ICON;\n }\n\n @Override\n public void paintIcon(Component c, Graphics g, int x, int y) {\n (darkBackground() ? AllIcons.Actions.CheckedGrey : AllIcons.Actions.CheckedBlack).paintIcon(c, g, x, y);\n }\n\n @Override\n public int getIconWidth() {\n return PlatformIcons.CHECK_ICON.getIconWidth();\n }\n\n @Override\n public int getIconHeight() {\n return PlatformIcons.CHECK_ICON.getIconHeight();\n }\n }\n\n private static boolean darkBackground() {\n Color gutterBackground = EditorColorsManager.getInstance().getGlobalScheme().getColor(EditorColors.GUTTER_BACKGROUND);\n if (gutterBackground == null) {\n gutterBackground = EditorColors.GUTTER_BACKGROUND.getDefaultColor();\n }\n return ColorUtil.isDark(gutterBackground);\n }\n\n private static class MyGutterIconRenderer extends GutterIconRenderer implements DumbAware {\n private final Bookmark myBookmark;\n\n public MyGutterIconRenderer(@NotNull Bookmark bookmark) {\n myBookmark = bookmark;\n }\n\n @Override\n @NotNull\n public Icon getIcon() {\n return myBookmark.getIcon();\n }\n\n @Override\n public String getTooltipText() {\n return myBookmark.getBookmarkTooltip();\n }\n\n @Override\n public boolean equals(Object obj) {\n return obj instanceof MyGutterIconRenderer &&\n Comparing.equal(getTooltipText(), ((MyGutterIconRenderer)obj).getTooltipText()) &&\n Comparing.equal(getIcon(), ((MyGutterIconRenderer)obj).getIcon());\n }\n\n @Override\n public int hashCode() {\n return getIcon().hashCode();\n }\n }\n}\n"},"new_file":{"kind":"string","value":"platform/lang-impl/src/com/intellij/ide/bookmarks/Bookmark.java"},"old_contents":{"kind":"string","value":"/*\n * Copyright 2000-2016 JetBrains s.r.o.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.intellij.ide.bookmarks;\n\nimport com.intellij.codeInsight.daemon.GutterMark;\nimport com.intellij.icons.AllIcons;\nimport com.intellij.ide.IdeBundle;\nimport com.intellij.ide.structureView.StructureViewBuilder;\nimport com.intellij.ide.structureView.StructureViewModel;\nimport com.intellij.ide.structureView.TreeBasedStructureViewBuilder;\nimport com.intellij.lang.LanguageStructureViewBuilder;\nimport com.intellij.navigation.ItemPresentation;\nimport com.intellij.navigation.NavigationItem;\nimport com.intellij.openapi.editor.Document;\nimport com.intellij.openapi.editor.RangeMarker;\nimport com.intellij.openapi.editor.colors.CodeInsightColors;\nimport com.intellij.openapi.editor.colors.EditorColors;\nimport com.intellij.openapi.editor.colors.EditorColorsManager;\nimport com.intellij.openapi.editor.ex.MarkupModelEx;\nimport com.intellij.openapi.editor.ex.RangeHighlighterEx;\nimport com.intellij.openapi.editor.impl.DocumentMarkupModel;\nimport com.intellij.openapi.editor.markup.GutterIconRenderer;\nimport com.intellij.openapi.editor.markup.HighlighterLayer;\nimport com.intellij.openapi.editor.markup.RangeHighlighter;\nimport com.intellij.openapi.editor.markup.TextAttributes;\nimport com.intellij.openapi.fileEditor.FileDocumentManager;\nimport com.intellij.openapi.fileEditor.OpenFileDescriptor;\nimport com.intellij.openapi.project.DumbAware;\nimport com.intellij.openapi.project.Project;\nimport com.intellij.openapi.util.Comparing;\nimport com.intellij.openapi.util.Ref;\nimport com.intellij.openapi.util.text.StringUtil;\nimport com.intellij.openapi.vfs.VirtualFile;\nimport com.intellij.pom.Navigatable;\nimport com.intellij.psi.PsiDocumentManager;\nimport com.intellij.psi.PsiFile;\nimport com.intellij.psi.PsiManager;\nimport com.intellij.ui.ColorUtil;\nimport com.intellij.ui.JBColor;\nimport com.intellij.ui.RetrievableIcon;\nimport com.intellij.util.NotNullProducer;\nimport com.intellij.util.PlatformIcons;\nimport com.intellij.util.Processor;\nimport org.jetbrains.annotations.NotNull;\nimport org.jetbrains.annotations.Nullable;\n\nimport javax.swing.*;\nimport java.awt.*;\n\npublic class Bookmark implements Navigatable, Comparable {\n public static final Icon DEFAULT_ICON = new MyCheckedIcon();\n\n private final VirtualFile myFile;\n @NotNull private OpenFileDescriptor myTarget;\n private final Project myProject;\n\n private String myDescription;\n private char myMnemonic = 0;\n public static final Font MNEMONIC_FONT = new Font(\"Monospaced\", Font.PLAIN, 11);\n\n public Bookmark(@NotNull Project project, @NotNull VirtualFile file, int line, @NotNull String description) {\n myFile = file;\n myProject = project;\n myDescription = description;\n\n myTarget = new OpenFileDescriptor(project, file, line, -1, true);\n\n addHighlighter();\n }\n\n @Override\n public int compareTo(Bookmark o) {\n int i = myMnemonic != 0 ? o.myMnemonic != 0 ? myMnemonic - o.myMnemonic : -1: o.myMnemonic != 0 ? 1 : 0;\n if (i != 0) return i;\n i = myProject.getName().compareTo(o.myProject.getName());\n if (i != 0) return i;\n i = myFile.getName().compareTo(o.getFile().getName());\n if (i != 0) return i;\n return getTarget().compareTo(o.getTarget());\n }\n\n public void updateHighlighter() {\n release();\n addHighlighter();\n }\n\n private void addHighlighter() {\n Document document = FileDocumentManager.getInstance().getCachedDocument(getFile());\n if (document != null) {\n createHighlighter((MarkupModelEx)DocumentMarkupModel.forDocument(document, myProject, true));\n }\n }\n\n public RangeHighlighter createHighlighter(@NotNull MarkupModelEx markup) {\n final RangeHighlighterEx myHighlighter;\n int line = getLine();\n if (line >= 0) {\n myHighlighter = markup.addPersistentLineHighlighter(line, HighlighterLayer.ERROR + 1, null);\n if (myHighlighter != null) {\n myHighlighter.setGutterIconRenderer(new MyGutterIconRenderer(this));\n\n TextAttributes textAttributes =\n EditorColorsManager.getInstance().getGlobalScheme().getAttributes(CodeInsightColors.BOOKMARKS_ATTRIBUTES);\n\n Color stripeColor = textAttributes.getErrorStripeColor();\n myHighlighter.setErrorStripeMarkColor(stripeColor != null ? stripeColor : Color.black);\n myHighlighter.setErrorStripeTooltip(getBookmarkTooltip());\n\n TextAttributes attributes = myHighlighter.getTextAttributes();\n if (attributes == null) {\n attributes = new TextAttributes();\n }\n attributes.setBackgroundColor(textAttributes.getBackgroundColor());\n attributes.setForegroundColor(textAttributes.getForegroundColor());\n myHighlighter.setTextAttributes(attributes);\n }\n }\n else {\n myHighlighter = null;\n }\n return myHighlighter;\n }\n\n @Nullable\n public Document getDocument() {\n return FileDocumentManager.getInstance().getCachedDocument(getFile());\n }\n\n public void release() {\n int line = getLine();\n if (line < 0) {\n return;\n }\n final Document document = getDocument();\n if (document == null) return;\n MarkupModelEx markup = (MarkupModelEx)DocumentMarkupModel.forDocument(document, myProject, true);\n final Document markupDocument = markup.getDocument();\n if (markupDocument.getLineCount() <= line) return;\n RangeHighlighterEx highlighter = findMyHighlighter();\n if (highlighter != null) {\n highlighter.dispose();\n }\n }\n\n private RangeHighlighterEx findMyHighlighter() {\n final Document document = getDocument();\n if (document == null) return null;\n MarkupModelEx markup = (MarkupModelEx)DocumentMarkupModel.forDocument(document, myProject, true);\n final Document markupDocument = markup.getDocument();\n final int startOffset = 0;\n final int endOffset = markupDocument.getTextLength();\n\n final Ref found = new Ref();\n markup.processRangeHighlightersOverlappingWith(startOffset, endOffset, highlighter -> {\n GutterMark renderer = highlighter.getGutterIconRenderer();\n if (renderer instanceof MyGutterIconRenderer && ((MyGutterIconRenderer)renderer).myBookmark == Bookmark.this) {\n found.set(highlighter);\n return false;\n }\n return true;\n });\n return found.get();\n }\n\n public Icon getIcon() {\n return myMnemonic == 0 ? DEFAULT_ICON : MnemonicIcon.getIcon(myMnemonic);\n }\n\n public String getDescription() {\n return myDescription;\n }\n\n public void setDescription(String description) {\n myDescription = description;\n }\n\n public char getMnemonic() {\n return myMnemonic;\n }\n\n public void setMnemonic(char mnemonic) {\n myMnemonic = Character.toUpperCase(mnemonic);\n }\n\n @NotNull\n public VirtualFile getFile() {\n return myFile;\n }\n\n @Nullable\n public String getNotEmptyDescription() {\n return StringUtil.isEmpty(myDescription) ? null : myDescription;\n }\n\n public boolean isValid() {\n if (!getFile().isValid()) {\n return false;\n }\n if (getLine() ==-1) {\n return true;\n }\n RangeHighlighterEx highlighter = findMyHighlighter();\n return highlighter != null && highlighter.isValid();\n }\n\n @Override\n public boolean canNavigate() {\n return getTarget().canNavigate();\n }\n\n @Override\n public boolean canNavigateToSource() {\n return getTarget().canNavigateToSource();\n }\n\n @Override\n public void navigate(boolean requestFocus) {\n getTarget().navigate(requestFocus);\n }\n\n public int getLine() {\n int targetLine = myTarget.getLine();\n if (targetLine == -1) return targetLine;\n //What user sees in gutter\n RangeHighlighterEx highlighter = findMyHighlighter();\n if (highlighter != null && highlighter.isValid()) {\n Document document = getDocument();\n if (document != null) {\n return document.getLineNumber(highlighter.getStartOffset());\n }\n }\n RangeMarker marker = myTarget.getRangeMarker();\n if (marker != null && marker.isValid()) {\n Document document = marker.getDocument();\n return document.getLineNumber(marker.getStartOffset());\n }\n return targetLine;\n }\n\n private OpenFileDescriptor getTarget() {\n int line = getLine();\n if (line != myTarget.getLine()) {\n myTarget = new OpenFileDescriptor(myProject, myFile, line, -1, true);\n }\n return myTarget;\n }\n\n @Override\n public String toString() {\n StringBuilder result = new StringBuilder(getQualifiedName());\n String description = StringUtil.escapeXml(getNotEmptyDescription());\n if (description != null) {\n result.append(\": \").append(description);\n }\n return result.toString();\n }\n\n public String getQualifiedName() {\n String presentableUrl = myFile.getPresentableUrl();\n if (myFile.isDirectory()) return presentableUrl;\n\n PsiDocumentManager.getInstance(myProject).commitAllDocuments();\n final PsiFile psiFile = PsiManager.getInstance(myProject).findFile(myFile);\n\n if (psiFile == null) return presentableUrl;\n\n StructureViewBuilder builder = LanguageStructureViewBuilder.INSTANCE.getStructureViewBuilder(psiFile);\n if (builder instanceof TreeBasedStructureViewBuilder) {\n StructureViewModel model = ((TreeBasedStructureViewBuilder)builder).createStructureViewModel(null);\n Object element;\n try {\n element = model.getCurrentEditorElement();\n }\n finally {\n model.dispose();\n }\n if (element instanceof NavigationItem) {\n ItemPresentation presentation = ((NavigationItem)element).getPresentation();\n if (presentation != null) {\n presentableUrl = ((NavigationItem)element).getName() + \" \" + presentation.getLocationString();\n }\n }\n }\n\n return IdeBundle.message(\"bookmark.file.X.line.Y\", presentableUrl, getLine() + 1);\n }\n\n private String getBookmarkTooltip() {\n StringBuilder result = new StringBuilder(\"Bookmark\");\n if (myMnemonic != 0) {\n result.append(\" \").append(myMnemonic);\n }\n String description = StringUtil.escapeXml(getNotEmptyDescription());\n if (description != null) {\n result.append(\": \").append(description);\n }\n return result.toString();\n }\n\n static class MnemonicIcon implements Icon {\n private static final MnemonicIcon[] cache = new MnemonicIcon[36];//0..9 + A..Z\n private final char myMnemonic;\n\n @NotNull\n static MnemonicIcon getIcon(char mnemonic) {\n int index = mnemonic - 48;\n if (index > 9)\n index -= 7;\n if (index < 0 || index > cache.length-1)\n return new MnemonicIcon(mnemonic);\n if (cache[index] == null)\n cache[index] = new MnemonicIcon(mnemonic);\n return cache[index];\n }\n\n private MnemonicIcon(char mnemonic) {\n myMnemonic = mnemonic;\n }\n\n @Override\n public void paintIcon(Component c, Graphics g, int x, int y) {\n g.setColor(new JBColor(() -> {\n //noinspection UseJBColor\n return !darkBackground() ? new Color(0xffffcc) : new Color(0x675133);\n }));\n g.fillRect(x, y, getIconWidth(), getIconHeight());\n\n g.setColor(JBColor.GRAY);\n g.drawRect(x, y, getIconWidth(), getIconHeight());\n\n g.setColor(EditorColorsManager.getInstance().getGlobalScheme().getDefaultForeground());\n final Font oldFont = g.getFont();\n g.setFont(MNEMONIC_FONT);\n\n ((Graphics2D)g).drawString(Character.toString(myMnemonic), x + 3, y + getIconHeight() - 1.5F);\n g.setFont(oldFont);\n }\n\n @Override\n public int getIconWidth() {\n return DEFAULT_ICON.getIconWidth();\n }\n\n @Override\n public int getIconHeight() {\n return DEFAULT_ICON.getIconHeight();\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n MnemonicIcon that = (MnemonicIcon)o;\n\n return myMnemonic == that.myMnemonic;\n }\n\n @Override\n public int hashCode() {\n return (int)myMnemonic;\n }\n }\n\n private static class MyCheckedIcon implements Icon, RetrievableIcon {\n @Nullable\n @Override\n public Icon retrieveIcon() {\n return PlatformIcons.CHECK_ICON;\n }\n\n @Override\n public void paintIcon(Component c, Graphics g, int x, int y) {\n (darkBackground() ? AllIcons.Actions.CheckedGrey : AllIcons.Actions.CheckedBlack).paintIcon(c, g, x, y);\n }\n\n @Override\n public int getIconWidth() {\n return PlatformIcons.CHECK_ICON.getIconWidth();\n }\n\n @Override\n public int getIconHeight() {\n return PlatformIcons.CHECK_ICON.getIconHeight();\n }\n }\n\n private static boolean darkBackground() {\n Color gutterBackground = EditorColorsManager.getInstance().getGlobalScheme().getColor(EditorColors.GUTTER_BACKGROUND);\n if (gutterBackground == null) {\n gutterBackground = EditorColors.GUTTER_BACKGROUND.getDefaultColor();\n }\n return ColorUtil.isDark(gutterBackground);\n }\n\n private static class MyGutterIconRenderer extends GutterIconRenderer implements DumbAware {\n private final Bookmark myBookmark;\n\n public MyGutterIconRenderer(@NotNull Bookmark bookmark) {\n myBookmark = bookmark;\n }\n\n @Override\n @NotNull\n public Icon getIcon() {\n return myBookmark.getIcon();\n }\n\n @Override\n public String getTooltipText() {\n return myBookmark.getBookmarkTooltip();\n }\n\n @Override\n public boolean equals(Object obj) {\n return obj instanceof MyGutterIconRenderer &&\n Comparing.equal(getTooltipText(), ((MyGutterIconRenderer)obj).getTooltipText()) &&\n Comparing.equal(getIcon(), ((MyGutterIconRenderer)obj).getIcon());\n }\n\n @Override\n public int hashCode() {\n return getIcon().hashCode();\n }\n }\n}\n"},"message":{"kind":"string","value":"IDEA-156735 Bookmarks causing typing slowness\n"},"old_file":{"kind":"string","value":"platform/lang-impl/src/com/intellij/ide/bookmarks/Bookmark.java"},"subject":{"kind":"string","value":"IDEA-156735 Bookmarks causing typing slowness"},"git_diff":{"kind":"string","value":"latform/lang-impl/src/com/intellij/ide/bookmarks/Bookmark.java\n import com.intellij.psi.PsiDocumentManager;\n import com.intellij.psi.PsiFile;\n import com.intellij.psi.PsiManager;\nimport com.intellij.reference.SoftReference;\n import com.intellij.ui.ColorUtil;\n import com.intellij.ui.JBColor;\n import com.intellij.ui.RetrievableIcon;\nimport com.intellij.util.NotNullProducer;\n import com.intellij.util.PlatformIcons;\nimport com.intellij.util.Processor;\nimport com.intellij.util.containers.WeakHashMap;\n import org.jetbrains.annotations.NotNull;\n import org.jetbrains.annotations.Nullable;\n \n import javax.swing.*;\n import java.awt.*;\nimport java.lang.ref.Reference;\nimport java.lang.ref.WeakReference;\n \n public class Bookmark implements Navigatable, Comparable {\n public static final Icon DEFAULT_ICON = new MyCheckedIcon();\n private final VirtualFile myFile;\n @NotNull private OpenFileDescriptor myTarget;\n private final Project myProject;\n private WeakHashMap> myHighlighterRefs;\n \n private String myDescription;\n private char myMnemonic = 0;\n }\n \n public RangeHighlighter createHighlighter(@NotNull MarkupModelEx markup) {\n final RangeHighlighterEx myHighlighter;\n final RangeHighlighterEx highlighter;\n int line = getLine();\n if (line >= 0) {\n myHighlighter = markup.addPersistentLineHighlighter(line, HighlighterLayer.ERROR + 1, null);\n if (myHighlighter != null) {\n myHighlighter.setGutterIconRenderer(new MyGutterIconRenderer(this));\n highlighter = markup.addPersistentLineHighlighter(line, HighlighterLayer.ERROR + 1, null);\n if (highlighter != null) {\n highlighter.setGutterIconRenderer(new MyGutterIconRenderer(this));\n \n TextAttributes textAttributes =\n EditorColorsManager.getInstance().getGlobalScheme().getAttributes(CodeInsightColors.BOOKMARKS_ATTRIBUTES);\n \n Color stripeColor = textAttributes.getErrorStripeColor();\n myHighlighter.setErrorStripeMarkColor(stripeColor != null ? stripeColor : Color.black);\n myHighlighter.setErrorStripeTooltip(getBookmarkTooltip());\n\n TextAttributes attributes = myHighlighter.getTextAttributes();\n highlighter.setErrorStripeMarkColor(stripeColor != null ? stripeColor : Color.black);\n highlighter.setErrorStripeTooltip(getBookmarkTooltip());\n\n TextAttributes attributes = highlighter.getTextAttributes();\n if (attributes == null) {\n attributes = new TextAttributes();\n }\n attributes.setBackgroundColor(textAttributes.getBackgroundColor());\n attributes.setForegroundColor(textAttributes.getForegroundColor());\n myHighlighter.setTextAttributes(attributes);\n highlighter.setTextAttributes(attributes);\n }\n }\n else {\n myHighlighter = null;\n }\n return myHighlighter;\n highlighter = null;\n }\n if (myHighlighterRefs == null) myHighlighterRefs = new WeakHashMap<>();\n if (highlighter != null) {\n myHighlighterRefs.put(markup.getDocument(), new WeakReference(highlighter));\n }\n return highlighter;\n }\n \n @Nullable\n }\n \n public void release() {\n int line = getLine();\n if (line < 0) {\n return;\n }\n final Document document = getDocument();\n if (document == null) return;\n MarkupModelEx markup = (MarkupModelEx)DocumentMarkupModel.forDocument(document, myProject, true);\n final Document markupDocument = markup.getDocument();\n if (markupDocument.getLineCount() <= line) return;\n RangeHighlighterEx highlighter = findMyHighlighter();\n if (highlighter != null) {\n highlighter.dispose();\n try {\n int line = getLine();\n if (line < 0) {\n return;\n }\n final Document document = getDocument();\n if (document == null) return;\n MarkupModelEx markup = (MarkupModelEx)DocumentMarkupModel.forDocument(document, myProject, true);\n final Document markupDocument = markup.getDocument();\n if (markupDocument.getLineCount() <= line) return;\n RangeHighlighterEx highlighter = findMyHighlighter();\n if (highlighter != null) {\n highlighter.dispose();\n }\n } finally {\n myHighlighterRefs = null;\n }\n }\n \n private RangeHighlighterEx findMyHighlighter() {\n final Document document = getDocument();\n if (document == null) return null;\n Reference reference = myHighlighterRefs != null ? myHighlighterRefs.get(document) : null;\n RangeHighlighterEx result = SoftReference.dereference(reference);\n if (result != null) {\n return result;\n }\n MarkupModelEx markup = (MarkupModelEx)DocumentMarkupModel.forDocument(document, myProject, true);\n final Document markupDocument = markup.getDocument();\n final int startOffset = 0;\n }\n return true;\n });\n return found.get();\n result = found.get();\n if (result != null) {\n if (myHighlighterRefs == null) myHighlighterRefs = new WeakHashMap<>();\n myHighlighterRefs.put(document, new WeakReference(result));\n }\n return result;\n }\n \n public Icon getIcon() {"}}},{"rowIdx":1940,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"ca151ada6ea46f9ccb533193a760e0c227bc1dbb"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"ONSdigital/The-Train,Carboni/The-Train,Carboni/the-train-destination,Carboni/The-Train,Carboni/the-train-destination,ONSdigital/The-Train"},"new_contents":{"kind":"string","value":"package com.github.davidcarboni.thetrain.destination.json;\n\nimport com.github.davidcarboni.cryptolite.Random;\nimport com.github.davidcarboni.thetrain.destination.helpers.DateConverter;\n\nimport java.util.*;\n\n\n/**\n * Details of a single transaction, including any files transferred and any errors encountered.\n *\n * NB a {@link Transaction} is the unit of synchronization, so methods that manipulate the collections in this class synchronize on this.\n */\npublic class Transaction {\n\n String id = Random.id();\n String startDate = DateConverter.toString(new Date());\n\n Set uris = new HashSet<>();\n List errors = new ArrayList<>();\n\n /**\n * @return The transaction {@link #id}.\n */\n public String id() {\n return id;\n }\n\n /**\n * @return The transaction {@link #startDate}.\n */\n public String startDate() {\n return startDate;\n }\n\n /**\n * @return An unmodifiable set of the URIs in this transaction.\n */\n public Set uris() {\n return Collections.unmodifiableSet(uris);\n }\n\n /**\n * @param uri The URI to add to the set of URIs.\n */\n public void addUri(Uri uri) {\n synchronized (this) {\n Set uris = new HashSet<>(this.uris);\n uris.add(uri);\n this.uris = uris;\n }\n }\n\n /**\n * @param error An error message to be added to this transaction.\n */\n public void addError(String error) {\n synchronized (this) {\n List errors = new ArrayList<>(this.errors);\n errors.add(error);\n this.errors = errors;\n }\n }\n\n @Override\n public String toString() {\n return id + \" (\" + uris.size() + \" URIs)\";\n }\n}\n"},"new_file":{"kind":"string","value":"src/main/java/com/github/davidcarboni/thetrain/destination/json/Transaction.java"},"old_contents":{"kind":"string","value":"package com.github.davidcarboni.thetrain.destination.json;\n\nimport com.github.davidcarboni.cryptolite.Random;\nimport com.github.davidcarboni.thetrain.destination.helpers.DateConverter;\n\nimport java.util.*;\n\n\n/**\n * Details of a single transaction, including any files transferred and any errors encountered.\n *\n * NB a {@link Transaction} is the unit of synchronization, so methods that manipulate the collections in this class synchronize on this.\n */\npublic class Transaction {\n\n String id = Random.id();\n String startDate = DateConverter.toString(new Date());\n\n Set uris = new HashSet<>();\n List errors = new ArrayList<>();\n\n /**\n * @return The transaction {@link #id}.\n */\n public String id() {\n return id;\n }\n\n /**\n * @return The transaction {@link #startDate}.\n */\n public String startDate() {\n return startDate;\n }\n\n /**\n * @return An unmodifiable set of the URIs in this transaction.\n */\n public Set uris() {\n return Collections.unmodifiableSet(uris);\n }\n\n /**\n * @param uri The URI to add to the set of URIs.\n */\n public void addUri(Uri uri) {\n synchronized (this) {\n uris.add(uri);\n }\n }\n\n /**\n * @param error An error message to be added to this transaction.\n */\n public void addError(String error) {\n synchronized (this) {\n errors.add(error);\n }\n }\n\n @Override\n public String toString() {\n return id + \" (\" + uris.size() + \" URIs)\";\n }\n}\n"},"message":{"kind":"string","value":"Changed list additions to operate on new lists in order to avoid concurrent modification.\n"},"old_file":{"kind":"string","value":"src/main/java/com/github/davidcarboni/thetrain/destination/json/Transaction.java"},"subject":{"kind":"string","value":"Changed list additions to operate on new lists in order to avoid concurrent modification."},"git_diff":{"kind":"string","value":"rc/main/java/com/github/davidcarboni/thetrain/destination/json/Transaction.java\n */\n public void addUri(Uri uri) {\n synchronized (this) {\n Set uris = new HashSet<>(this.uris);\n uris.add(uri);\n this.uris = uris;\n }\n }\n \n */\n public void addError(String error) {\n synchronized (this) {\n List errors = new ArrayList<>(this.errors);\n errors.add(error);\n this.errors = errors;\n }\n }\n "}}},{"rowIdx":1941,"cells":{"lang":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"24faa64ab808e936e4adb1da0eb646a4b649c5de"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"desmondmorris/node-twitter,rneilson/node-twitter,gabfusi/node-twitter"},"new_contents":{"kind":"string","value":"/**\n* Module dependencies\n*/\nvar oauth = require('oauth');\nvar Keygrip = require('keygrip');\nvar merge = require('./utils').merge;\nvar querystring = require('querystring');\nvar urlparse = require('url').parse;\n\n// Package version\nvar VERSION = require('../package.json').version;\n\nfunction Twitter(options) {\n if (!(this instanceof Twitter)) return new Twitter(options);\n\n this.VERSION = VERSION;\n\n var defaults = {\n consumer_key: null,\n consumer_secret: null,\n access_token_key: null,\n access_token_secret: null,\n\n headers: {\n 'Accept': '*/*',\n 'Connection': 'close',\n 'User-Agent': 'node-twitter/' + this.VERSION\n },\n\n request_token_url: 'https://api.twitter.com/oauth/request_token',\n access_token_url: 'https://api.twitter.com/oauth/access_token',\n authenticate_url: 'https://api.twitter.com/oauth/authenticate',\n authorize_url: 'https://api.twitter.com/oauth/authorize',\n callback_url: null,\n\n rest_base: 'https://api.twitter.com/1.1',\n stream_base: 'https://stream.twitter.com/1.1',\n search_base: 'https://api.twitter.com/1.1/search',\n user_stream_base: 'https://userstream.twitter.com/1.1',\n site_stream_base: 'https://sitestream.twitter.com/1.1',\n filter_stream_base: 'https://stream.twitter.com/1.1/statuses',\n\n secure: false, // force use of https for login/gatekeeper\n cookie: 'twauth',\n cookie_options: {},\n cookie_secret: null\n };\n\n this.options = merge(defaults, options);\n\n if (this.options.cookie_secret === null) {\n this.keygrip = null;\n }\n else {\n new Keygrip([this.options.cookie_secret]);\n }\n\n this.oauth = new oauth.OAuth(\n this.options.request_token_url,\n this.options.access_token_url,\n this.options.consumer_key,\n this.options.consumer_secret,\n '1.0',\n this.options.callback_url,\n 'HMAC-SHA1', null,\n this.options.headers\n );\n\n this.__generateURL = function(path, query) {\n if (urlparse(path).protocol === null) {\n if (path.charAt(0) != '/') {\n path = '/' + path;\n }\n }\n path = this.options.rest_base + path;\n // Add json extension if not provided in call\n if(path.split('.').pop() !== 'json') {\n path += '.json';\n }\n if (query !== null) {\n path += '?' + querystring.stringify(query);\n }\n return path;\n }\n\n}\n\nTwitter.prototype.__request = function(method, path, params, callback) {\n // Set the callback if no params are passed\n if (typeof params === 'function') {\n callback = params;\n params = {};\n }\n\n var method = method.toLowerCase();\n if ((method !== 'get') && (method !== 'post')) {\n callback(new Error('Twitter API only accepts GET and POST requests'));\n return this;\n }\n\n url = this.__generateURL(path, (method === 'get') ? params : null);\n\n // Since oauth.get and oauth.post take a different set of arguments. Lets\n // build the arguments in an array as we go.\n var request = [\n url,\n this.options.access_token_key,\n this.options.access_token_secret\n ];\n\n if (method === 'post') {\n\n // Workaround: oauth + booleans == broken signatures\n if (params && typeof params === 'object') {\n Object.keys(params).forEach(function(e) {\n if ( typeof params[e] === 'boolean' )\n params[e] = params[e].toString();\n });\n }\n\n request.push(params);\n request.push('application/x-www-form-urlencoded');\n }\n\n // Add response callback function\n request.push(function(error, data, response){\n if (error) {\n // Return error, no payload and the oauth response object\n callback(error, null, response);\n return this;\n }\n else if (response.statusCode !== 200) {\n // Return error, no payload and the oauth response object\n callback(new Error('Status Code: ' + response.statusCode), null, response);\n return this;\n }\n else {\n // Do not fail on JSON parse attempt\n try {\n\tdata = JSON.parse(data);\n }\n catch (parseError) {\n data = data;\n }\n // Return no error, payload and the oauth response object\n callback(null, data, response);\n return this;\n }\n });\n\n // Make oauth request and pass request arguments\n this.oauth[method].apply(this.oauth,request);\n\n return this;\n}\n\n/**\n * GET\n */\nTwitter.prototype.get = function(url, params, callback) {\n this.__request('GET', url, params, callback);\n};\n\n/**\n * POST\n */\nTwitter.prototype.post = function(url, params, callback) {\n this.__request('POST', url, params, callback);\n};\n\n// Load legacy helper methods\nTwitter = require('./legacy')(Twitter);\n\nmodule.exports = Twitter;\n"},"new_file":{"kind":"string","value":"lib/twitter.js"},"old_contents":{"kind":"string","value":"/**\n* Module dependencies\n*/\nvar oauth = require('oauth');\nvar Keygrip = require('keygrip');\nvar merge = require('./utils').merge;\nvar querystring = require('querystring');\nvar urlparse = require('url').parse;\n\n// Package version\nvar VERSION = require('../package.json').version;\n\nfunction Twitter(options) {\n if (!(this instanceof Twitter)) return new Twitter(options);\n\n this.VERSION = VERSION;\n\n var defaults = {\n consumer_key: null,\n consumer_secret: null,\n access_token_key: null,\n access_token_secret: null,\n\n headers: {\n 'Accept': '*/*',\n 'Connection': 'close',\n 'User-Agent': 'node-twitter/' + this.VERSION\n },\n\n request_token_url: 'https://api.twitter.com/oauth/request_token',\n access_token_url: 'https://api.twitter.com/oauth/access_token',\n authenticate_url: 'https://api.twitter.com/oauth/authenticate',\n authorize_url: 'https://api.twitter.com/oauth/authorize',\n callback_url: null,\n\n rest_base: 'https://api.twitter.com/1.1',\n stream_base: 'https://stream.twitter.com/1.1',\n search_base: 'https://api.twitter.com/1.1/search',\n user_stream_base: 'https://userstream.twitter.com/1.1',\n site_stream_base: 'https://sitestream.twitter.com/1.1',\n filter_stream_base: 'https://stream.twitter.com/1.1/statuses',\n\n secure: false, // force use of https for login/gatekeeper\n cookie: 'twauth',\n cookie_options: {},\n cookie_secret: null\n };\n\n this.options = merge(defaults, options);\n\n if (this.options.cookie_secret === null) {\n this.keygrip = null;\n }\n else {\n new Keygrip([this.options.cookie_secret]);\n }\n\n this.oauth = new oauth.OAuth(\n this.options.request_token_url,\n this.options.access_token_url,\n this.options.consumer_key,\n this.options.consumer_secret,\n '1.0',\n this.options.callback_url,\n 'HMAC-SHA1', null,\n this.options.headers\n );\n\n this.__generateURL = function(path, query) {\n if (urlparse(path).protocol === null) {\n if (path.charAt(0) != '/') {\n path = '/' + path;\n }\n }\n path = this.options.rest_base + path;\n // Add json extension if not provided in call\n if(path.split('.').pop() !== 'json') {\n path += '.json';\n }\n if (query !== null) {\n path += '?' + querystring.stringify(query);\n }\n return path;\n }\n\n}\n\nTwitter.prototype.__request = function(method, path, params, callback) {\n // Set the callback if no params are passed\n if (typeof params === 'function') {\n callback = params;\n params = {};\n }\n\n var method = method.toLowerCase();\n if ((method !== 'get') && (method !== 'post')) {\n callback(new Error('Twitter API only accepts GET and POST requests'));\n return this;\n }\n\n url = this.__generateURL(path, (method === 'get') ? params : null);\n\n // Since oauth.get and oauth.post take a different set of arguments. Lets\n // build the arguments in an array as we go.\n var request = [\n url,\n this.options.access_token_key,\n this.options.access_token_secret\n ];\n\n if (method === 'post') {\n\n // Workaround: oauth + booleans == broken signatures\n if (params && typeof params === 'object') {\n Object.keys(params).forEach(function(e) {\n if ( typeof params[e] === 'boolean' )\n params[e] = params[e].toString();\n });\n }\n\n request.push(params);\n request.push('application/x-www-form-urlencoded');\n }\n\n // Add response callback function\n request.push(function(error, data, response){\n if (error) {\n // Return error, no payload and the oauth response object\n callback(error, null, response);\n return this;\n }\n else if (response.statusCode !== 200) {\n // Return error, no payload and the oauth response object\n callback(new Error('Status Code: ' + response.statusCode), null, response);\n return this;\n }\n else {\n // Do not fail on JSON parse attempt\n try {\n\tdata = JSON.parse(data);\n }\n catch (parseError) {\n data = data;\n }\n // Return no error, payload and the oauth response object\n callback(null, data, response);\n return this;\n }\n });\n\n // Make oauth request and pass request arguments\n this.oauth[method].apply(this.oauth,request);\n\n return this;\n}\n\n/**\n * GET\n */\nTwitter.prototype.get = function(url, params, callback) {\n if (typeof Twitter.prototype[arguments.callee.caller.name] !== 'undefined') {\n console.warn('** Deprecated: Please use the `get` function directly ** ');\n console.warn('** Use \"client.get(\\'' + url.substr(0, url.lastIndexOf('.')) + '\\', callback);\" instead **');\n }\n this.__request('GET', url, params, callback);\n};\n\n/**\n * POST\n */\nTwitter.prototype.post = function(url, params, callback) {\n if (typeof Twitter.prototype[arguments.callee.caller.name] !== 'undefined') {\n console.warn('** Deprecated: Please use the `post` function directly ** ');\n console.warn('** Use \"client.post(\\'' + url.substr(0, url.lastIndexOf('.')) + '\\', callback);\" instead **');\n }\n this.__request('POST', url, params, callback);\n};\n\n// Load legacy helper methods\nTwitter = require('./legacy')(Twitter);\n\nmodule.exports = Twitter;\n"},"message":{"kind":"string","value":"Remove deprecation warning checks\n\nThe deprecation warning checks are causing implementations to fail if they are in a \"use strict\" environment. This change eliminates those checks."},"old_file":{"kind":"string","value":"lib/twitter.js"},"subject":{"kind":"string","value":"Remove deprecation warning checks"},"git_diff":{"kind":"string","value":"ib/twitter.js\n * GET\n */\n Twitter.prototype.get = function(url, params, callback) {\n if (typeof Twitter.prototype[arguments.callee.caller.name] !== 'undefined') {\n console.warn('** Deprecated: Please use the `get` function directly ** ');\n console.warn('** Use \"client.get(\\'' + url.substr(0, url.lastIndexOf('.')) + '\\', callback);\" instead **');\n }\n this.__request('GET', url, params, callback);\n };\n \n * POST\n */\n Twitter.prototype.post = function(url, params, callback) {\n if (typeof Twitter.prototype[arguments.callee.caller.name] !== 'undefined') {\n console.warn('** Deprecated: Please use the `post` function directly ** ');\n console.warn('** Use \"client.post(\\'' + url.substr(0, url.lastIndexOf('.')) + '\\', callback);\" instead **');\n }\n this.__request('POST', url, params, callback);\n };\n "}}},{"rowIdx":1942,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"agpl-3.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"b4d6f29b5572b72b619fa548dcbfc37d048a4dec"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"Asqatasun/Asqatasun,medsob/Tanaguru,dzc34/Asqatasun,dzc34/Asqatasun,dzc34/Asqatasun,Asqatasun/Asqatasun,Asqatasun/Asqatasun,medsob/Tanaguru,Asqatasun/Asqatasun,dzc34/Asqatasun,medsob/Tanaguru,Tanaguru/Tanaguru,medsob/Tanaguru,Asqatasun/Asqatasun,dzc34/Asqatasun,Tanaguru/Tanaguru,Tanaguru/Tanaguru,Tanaguru/Tanaguru"},"new_contents":{"kind":"string","value":"/*\r\n * Tanaguru - Automated webpage assessment\r\n * Copyright (C) 2008-2011 Open-S Company\r\n *\r\n * This file is part of Tanaguru.\r\n *\r\n * Tanaguru is free software: you can redistribute it and/or modify\r\n * it under the terms of the GNU Affero General Public License as\r\n * published by the Free Software Foundation, either version 3 of the\r\n * License, or (at your option) any later version.\r\n *\r\n * This program is distributed in the hope that it will be useful,\r\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n * GNU Affero General Public License for more details.\r\n *\r\n * You should have received a copy of the GNU Affero General Public License\r\n * along with this program. If not, see .\r\n *\r\n * Contact us by mail: open-s AT open-s DOT com\r\n */\r\npackage org.opens.tanaguru.contentadapter.util;\r\n\r\n/**\r\n * \r\n * @author jkowalczyk\r\n */\r\npublic abstract class HtmlNodeAttr {\r\n\r\n /**\r\n * Private constructor : Hide Utility Class Constructor\r\n */\r\n private HtmlNodeAttr() {}\r\n \r\n public final static String CLASS = \"class\";\r\n public final static String HREF = \"href\";\r\n public final static String ID = \"id\";\r\n public final static String LINK = \"link\";\r\n public final static String REL = \"rel\";\r\n public final static String SRC = \"src\";\r\n public final static String STYLE = \"style\";\r\n public final static String MEDIA = \"media\";\r\n public final static String TYPE = \"type\";\r\n\r\n}"},"new_file":{"kind":"string","value":"engine/contentadapter/src/main/java/org/opens/tanaguru/contentadapter/util/HtmlNodeAttr.java"},"old_contents":{"kind":"string","value":"/*\r\n * Tanaguru - Automated webpage assessment\r\n * Copyright (C) 2008-2011 Open-S Company\r\n *\r\n * This file is part of Tanaguru.\r\n *\r\n * Tanaguru is free software: you can redistribute it and/or modify\r\n * it under the terms of the GNU Affero General Public License as\r\n * published by the Free Software Foundation, either version 3 of the\r\n * License, or (at your option) any later version.\r\n *\r\n * This program is distributed in the hope that it will be useful,\r\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n * GNU Affero General Public License for more details.\r\n *\r\n * You should have received a copy of the GNU Affero General Public License\r\n * along with this program. If not, see .\r\n *\r\n * Contact us by mail: open-s AT open-s DOT com\r\n */\r\npackage org.opens.tanaguru.contentadapter.util;\r\n\r\n/**\r\n * \r\n * @author jkowalczyk\r\n */\r\npublic abstract class HtmlNodeAttr {\r\n\r\n public final static String CLASS = \"class\";\r\n public final static String HREF = \"href\";\r\n public final static String ID = \"id\";\r\n public final static String LINK = \"link\";\r\n public final static String REL = \"rel\";\r\n public final static String SRC = \"src\";\r\n public final static String STYLE = \"style\";\r\n public final static String MEDIA = \"media\";\r\n public final static String TYPE = \"type\";\r\n\r\n}"},"message":{"kind":"string","value":"add private constructor to utility classes\n"},"old_file":{"kind":"string","value":"engine/contentadapter/src/main/java/org/opens/tanaguru/contentadapter/util/HtmlNodeAttr.java"},"subject":{"kind":"string","value":"add private constructor to utility classes"},"git_diff":{"kind":"string","value":"ngine/contentadapter/src/main/java/org/opens/tanaguru/contentadapter/util/HtmlNodeAttr.java\n */\n public abstract class HtmlNodeAttr {\n \n /**\n * Private constructor : Hide Utility Class Constructor\n */\n private HtmlNodeAttr() {}\n \n public final static String CLASS = \"class\";\n public final static String HREF = \"href\";\n public final static String ID = \"id\";"}}},{"rowIdx":1943,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"lgpl-2.1"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"ef1db946e149749a7a6673a87572aa78a3e1648a"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"vigna/Sux4J,vigna/Sux4J,vigna/Sux4J,vigna/Sux4J"},"new_contents":{"kind":"string","value":"package it.unimi.dsi.sux4j.mph;\n\n/*\t\t \n * Sux4J: Succinct data structures for Java\n *\n * Copyright (C) 2008 Sebastiano Vigna \n *\n * This library is free software; you can redistribute it and/or modify it\n * under the terms of the GNU Lesser General Public License as published by the Free\n * Software Foundation; either version 2.1 of the License, or (at your option)\n * any later version.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License\n * for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n *\n */\n\nimport it.unimi.dsi.Util;\nimport it.unimi.dsi.bits.BitVector;\nimport it.unimi.dsi.bits.Fast;\nimport it.unimi.dsi.bits.LongArrayBitVector;\nimport it.unimi.dsi.bits.TransformationStrategies;\nimport it.unimi.dsi.bits.TransformationStrategy;\nimport it.unimi.dsi.fastutil.ints.IntArrayList;\nimport it.unimi.dsi.fastutil.ints.IntOpenHashSet;\nimport it.unimi.dsi.fastutil.longs.LongArrayList;\nimport it.unimi.dsi.fastutil.objects.AbstractObject2LongFunction;\nimport it.unimi.dsi.fastutil.objects.Object2LongFunction;\nimport it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap;\nimport it.unimi.dsi.fastutil.objects.ObjectArrayList;\nimport it.unimi.dsi.fastutil.objects.ObjectOpenHashSet;\nimport it.unimi.dsi.fastutil.objects.ObjectRBTreeSet;\nimport it.unimi.dsi.lang.MutableString;\nimport it.unimi.dsi.logging.ProgressLogger;\nimport it.unimi.dsi.sux4j.bits.Rank9;\nimport it.unimi.dsi.util.LongBigList;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Iterator;\n\nimport org.apache.log4j.Logger;\n\n/** A distributor based on a probabilistic trie.\n * \n */\n\npublic class RelativeTrieDistributor extends AbstractObject2LongFunction {\n\tprivate final static Logger LOGGER = Util.getLogger( RelativeTrieDistributor.class );\n\tprivate static final long serialVersionUID = 1L;\n\tprivate static final boolean DEBUG = false;\n\tprivate static final boolean DDEBUG = false;\n\tprivate static final boolean ASSERTS = true;\n\n\t/** An integer representing the exit-on-the-left behaviour. */\n\tprivate final static int LEFT = 0;\n\t/** An integer representing the exit-on-the-right behaviour. */\n\tprivate final static int RIGHT = 1;\n\t/** A ranking structure on the vector containing leaves plus p0,p1, etc. */\n\tprivate final Rank9 leaves;\n\t/** The transformation used to map object to bit vectors. */\n\tprivate final TransformationStrategy transformationStrategy;\n\t/** For each external node and each possible path, the related behaviour. */\n\tprivate final MWHCFunction behaviour;\n\t/** The number of (internal and external) nodes of the trie. */\n\tprivate final int size;\n\t/** A debug function used to store explicitly {@link #behaviour}. */\n\tprivate final Object2LongFunction externalTestFunction;\n\tprivate MWHCFunction signatures;\n\tprivate int w;\n\tprivate LcpMonotoneMinimalPerfectHashFunction ranker;\n\tprivate long logWMask;\n\tprivate int logW;\n\tprivate int logLogW;\n\tprivate long logLogWMask;\n\tprivate int numDelimiters;\n\tprivate IntOpenHashSet mistakeSignatures;\n\tprivate MWHCFunction corrections;\n\t\n\t/** An intermediate class containing the compacted trie generated by the delimiters. */\n\tprivate final static class IntermediateTrie {\n\t\t/** A debug function used to store explicitly the internal behaviour. */\n\t\tprivate Object2LongFunction externalTestFunction;\n\t\t/** The root of the trie. */\n\t\tprotected final Node root;\n\t\t/** The number of overall elements to distribute. */\n\t\tprivate final int numElements;\n\t\t/** The number of internal nodes of the trie. */\n\t\tprotected final int size;\n\t\t/** The values associated to the keys in {@link #externalKeysFile}. */\n\t\tprivate LongBigList externalValues;\n\t\t/** The string representing the parent of each key in {@link #externalKeysFile}. */\n\t\tprivate IntArrayList externalParentRepresentations;\n\t\tprivate int w;\n\t\tprivate int logW;\n\t\tprivate int logLogW;\n\t\tprivate long logLogWMask;\n\t\tprivate long logWMask;\n\t\tprivate ObjectArrayList internalNodeKeys;\n\t\tprivate ObjectArrayList internalNodeRepresentations;\n\t\tprivate LongArrayList internalNodeSignatures;\n\t\tprivate ObjectOpenHashSet delimiters;\n\t\t\n\t\t/** A node in the trie. */\n\t\tprivate static class Node {\n\t\t\t/** Left child. */\n\t\t\tprivate Node left;\n\t\t\t/** Right child. */\n\t\t\tprivate Node right;\n\t\t\t/** The path compacted in this node (null if there is no compaction at this node). */\n\t\t\tprivate final LongArrayBitVector path;\n\t\t\t/** The index of this node in breadth-first order. */\n\t\t\tprivate int index;\n\n\t\t\t/** Creates a node. \n\t\t\t * \n\t\t\t * @param left the left child.\n\t\t\t * @param right the right child.\n\t\t\t * @param path the path compacted at this node.\n\t\t\t */\n\t\t\tpublic Node( final Node left, final Node right, final LongArrayBitVector path ) {\n\t\t\t\tthis.left = left;\n\t\t\t\tthis.right = right;\n\t\t\t\tthis.path = path;\n\t\t\t}\n\n\t\t\t/** Returns true if this node is a leaf.\n\t\t\t * \n\t\t\t * @return true if this node is a leaf.\n\t\t\t */\n\t\t\tpublic boolean isLeaf() {\n\t\t\t\treturn right == null && left == null;\n\t\t\t}\n\t\t\t\n\t\t\tpublic String toString() {\n\t\t\t\treturn \"[\" + path + \"]\";\n\t\t\t}\n\t\t}\n\t\t\n\t\tProgressLogger pl = new ProgressLogger();\n\t\t\t\n\t\tvoid labelIntermediateTrie( Node node, LongArrayBitVector path,ObjectArrayList representations, ObjectArrayListkeys, LongArrayList values ) {\n\t\t\tassert ( node.left != null ) == ( node.right != null );\n\t\t\tif ( node.left != null ) {\n\t\t\t\tpl.update();\n\t\t\t\t\n\t\t\t\tlong parentPathLength = path.length() - 1;\n\t\t\t\t\n\t\t\t\tpath.append( node.path );\n\n\t\t\t\tlabelIntermediateTrie( node.left, path.append( 0, 1 ), representations, keys, values );\n\t\t\t\tpath.remove( (int)( path.length() - 1 ) );\n\n\t\t\t\tlong[] h = new long[ 3 ];\n\t\t\t\tHashes.jenkins( path, 0, h );\n\n\t\t\t\tint p = w / 2;\n\t\t\t\tint j = w / 4;\n\t\t\t\twhile( p <= parentPathLength || p > path.length() ) {\n\t\t\t\t\tif ( p <= parentPathLength ) p += j;\n\t\t\t\t\telse p -= j;\n\n\t\t\t\t\tj /= 2;\n\t\t\t\t}\n\n\t\t\t\tassert p <= path.length();\n\t\t\t\tassert p > parentPathLength;\n\n\t\t\t\tkeys.add( LongArrayBitVector.copy( path.subVector( 0, p ) ) );\n\t\t\t\trepresentations.add( path.copy() );\n\t\t\t\tassert Fast.length( path.length() ) <= logW;\n\t\t\t\t//System.err.println( \"Entering \" + path + \" with key \" + path.subVector( 0, p ) + \", signature \" + ( h[ 0 ] & logWMask ) + \" and length \" + ( path.length() & wMask ) );\n\t\t\t\t\n\t\t\t\tvalues.add( ( h[ 0 ] & logLogWMask ) << logW | ( path.length() & logWMask ) );\n\n\t\t\t\tlabelIntermediateTrie( node.right, path.append( 1, 1 ), representations, keys, values );\n\n\t\t\t\tpath.length( path.length() - node.path.length() - 1 );\n\t\t\t}\n\t\t}\n\n\t\t\n\t\t/** Creates a partial compacted trie using given elements, bucket size and transformation strategy.\n\t\t * \n\t\t * @param elements the elements among which the trie must be able to rank.\n\t\t * @param bucketSize the size of a bucket.\n\t\t * @param transformationStrategy a transformation strategy that must turn the elements in elements into a list of\n\t\t * distinct, prefix-free, lexicographically increasing (in iteration order) bit vectors.\n\t\t * @param tempDir a directory for the temporary files created during construction, or null for the default temporary directory. \n\t\t */\n\t\t\n\t\tpublic IntermediateTrie( final Iterable elements, final int bucketSize, final TransformationStrategy transformationStrategy, final File tempDir ) {\n\t\t\tif ( ASSERTS ) {\n\t\t\t\texternalTestFunction = new Object2LongOpenHashMap();\n\t\t\t\texternalTestFunction.defaultReturnValue( -1 );\n\t\t\t}\n\t\t\t\n\t\t\tIterator iterator = elements.iterator(); \n\t\t\tdelimiters = new ObjectOpenHashSet();\n\t\t\t\n\t\t\tif ( iterator.hasNext() ) {\n\t\t\t\tLongArrayBitVector prev = LongArrayBitVector.copy( transformationStrategy.toBitVector( iterator.next() ) );\n\t\t\t\tLongArrayBitVector prevDelimiter = LongArrayBitVector.getInstance();\n\t\t\t\t\n\t\t\t\tNode node, root = null;\n\t\t\t\tBitVector curr;\n\t\t\t\tint cmp, pos, prefix, count = 1;\n\t\t\t\tlong maxLength = prev.length();\n\t\t\t\t\n\t\t\t\twhile( iterator.hasNext() ) {\n\t\t\t\t\t// Check order\n\t\t\t\t\tcurr = transformationStrategy.toBitVector( iterator.next() ).fast();\n\t\t\t\t\tcmp = prev.compareTo( curr );\n\t\t\t\t\tif ( cmp == 0 ) throw new IllegalArgumentException( \"The input bit vectors are not distinct\" );\n\t\t\t\t\tif ( cmp > 0 ) throw new IllegalArgumentException( \"The input bit vectors are not lexicographically sorted\" );\n\t\t\t\t\tif ( curr.longestCommonPrefixLength( prev ) == prev.length() ) throw new IllegalArgumentException( \"The input bit vectors are not prefix-free\" );\n\n\t\t\t\t\tif ( count % bucketSize == 0 ) {\n\t\t\t\t\t\t// Found delimiter. Insert into trie.\n\t\t\t\t\t\tif ( root == null ) {\n\t\t\t\t\t\t\troot = new Node( null, null, prev.copy() );\n\t\t\t\t\t\t\tdelimiters.add( prev.copy() );\n\t\t\t\t\t\t\tprevDelimiter.replace( prev );\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tprefix = (int)prev.longestCommonPrefixLength( prevDelimiter );\n\n\t\t\t\t\t\t\tpos = 0;\n\t\t\t\t\t\t\tnode = root;\n\t\t\t\t\t\t\tNode n = null;\n\t\t\t\t\t\t\twhile( node != null ) {\n\t\t\t\t\t\t\t\tfinal long pathLength = node.path.length();\n\t\t\t\t\t\t\t\tif ( prefix < pathLength ) {\n\t\t\t\t\t\t\t\t\tn = new Node( node.left, node.right, node.path.copy( prefix + 1, pathLength ) );\n\t\t\t\t\t\t\t\t\tnode.path.length( prefix );\n\t\t\t\t\t\t\t\t\tnode.path.trim();\n\t\t\t\t\t\t\t\t\tnode.left = n;\n\t\t\t\t\t\t\t\t\tnode.right = new Node( null, null, prev.copy( pos + prefix + 1, prev.length() ) ); \n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tprefix -= pathLength + 1;\n\t\t\t\t\t\t\t\tpos += pathLength + 1;\n\t\t\t\t\t\t\t\tnode = node.right;\n\t\t\t\t\t\t\t\tif ( ASSERTS ) assert node == null || prefix >= 0 : prefix + \" <= \" + 0;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif ( ASSERTS ) assert node != null;\n\n\t\t\t\t\t\t\tdelimiters.add( prev.copy() );\n\t\t\t\t\t\t\tprevDelimiter.replace( prev );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tprev.replace( curr );\n\t\t\t\t\tmaxLength = Math.max( maxLength, prev.length() );\n\t\t\t\t\tcount++;\n\t\t\t\t}\n\n\t\t\t\tsize = count;\n\t\t\t\tlogLogW = Fast.ceilLog2( Fast.ceilLog2( maxLength ) );\n\t\t\t\tlogW = 1 << logLogW;\n\t\t\t\tw = 1 << logW;\n\t\t\t\tlogWMask = ( 1 << logW ) - 1;\n\t\t\t\tlogLogWMask = ( 1 << logLogW ) - 1;\n\t\t\t\tassert logW + logLogW <= Long.SIZE;\n\t\t\t\t\n\t\t\t\tthis.numElements = count;\n\t\t\t\tthis.root = root;\n\t\t\t\t\n\t\t\t\tif ( DEBUG ) {\n\t\t\t\t\tSystem.err.println( \"w: \" + w );\n\t\t\t\t\tSystem.err.println( \"Delimiters: \" + delimiters );\n\t\t\t\t\tSystem.err.println( this );\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif ( root != null ) {\n\t\t\t\t\tLOGGER.info( \"Computing approximate structure...\" );\n\n\t\t\t\t\tinternalNodeRepresentations = new ObjectArrayList();\n\t\t\t\t\tinternalNodeSignatures = new LongArrayList();\n\t\t\t\t\tinternalNodeKeys = new ObjectArrayList();\n\t\t\t\t\tpl.expectedUpdates = delimiters.size();\n\t\t\t\t\tpl.start( \"Labelling trie...\" );\n\t\t\t\t\tlabelIntermediateTrie( root, LongArrayBitVector.getInstance(), internalNodeRepresentations, internalNodeKeys, internalNodeSignatures );\n\t\t\t\t\tpl.done();\n\n\t\t\t\t\tif ( DEBUG ) {\n\t\t\t\t\t\tSystem.err.println( \"Internal node representations: \" + internalNodeRepresentations );\n\t\t\t\t\t\tSystem.err.println( \"Internal node signatures: \" + internalNodeSignatures );\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tLOGGER.info( \"Computing function keys...\" );\n\n\t\t\t\t\texternalValues = LongArrayBitVector.getInstance().asLongBigList( 1 );\n\t\t\t\t\texternalParentRepresentations = new IntArrayList( size );\n\t\t\t\t\titerator = elements.iterator();\n\n\t\t\t\t\t// The stack of nodes visited the last time\n\t\t\t\t\tfinal Node stack[] = new Node[ (int)maxLength ];\n\t\t\t\t\t// The length of the path compacted in the trie up to the corresponding node, excluded\n\t\t\t\t\tfinal int[] len = new int[ (int)maxLength ];\n\t\t\t\t\tstack[ 0 ] = root;\n\t\t\t\t\tint depth = 0, behaviour;\n\t\t\t\t\tboolean first = true;\n\t\t\t\t\tBitVector currFromPos, path;\n\t\t\t\t\tLongArrayBitVector nodePath;\n\n\t\t\t\t\twhile( iterator.hasNext() ) {\n\t\t\t\t\t\tcurr = transformationStrategy.toBitVector( iterator.next() ).fast();\n\t\t\t\t\t\tif ( DEBUG ) System.err.println( \"Analysing key \" + curr + \"...\" );\n\t\t\t\t\t\tif ( ! first ) {\n\t\t\t\t\t\t\t// Adjust stack using lcp between present string and previous one\n\t\t\t\t\t\t\tprefix = (int)prev.longestCommonPrefixLength( curr );\n\t\t\t\t\t\t\twhile( depth > 0 && len[ depth ] > prefix ) depth--;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse first = false;\n\t\t\t\t\t\tnode = stack[ depth ];\n\t\t\t\t\t\tpos = len[ depth ];\n\n\t\t\t\t\t\tfor(;;) {\n\t\t\t\t\t\t\tnodePath = node.path;\n\t\t\t\t\t\t\tcurrFromPos = curr.subVector( pos ); \n\t\t\t\t\t\t\tprefix = (int)currFromPos.longestCommonPrefixLength( nodePath );\n\n\t\t\t\t\t\t\t//System.err.println( \"prefix: \" + prefix + \" nodePath.length(): \" + nodePath.length() + \" node.isLeaf(): \" + node.isLeaf() );\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif ( prefix < nodePath.length() || node.isLeaf() ) {\n\t\t\t\t\t\t\t\t// Exit. LEFT or RIGHT, depending on the bit at the end of the common prefix. The\n\t\t\t\t\t\t\t\t// path is the remaining path at the current position for external nodes, or a prefix of length\n\t\t\t\t\t\t\t\t// at most pathLength for internal nodes.\n\t\t\t\t\t\t\t\tbehaviour = prefix < nodePath.length() && ! nodePath.getBoolean( prefix ) ? RIGHT : LEFT;\n\t\t\t\t\t\t\t\tpath = curr;\n\n\t\t\t\t\t\t\t\texternalValues.add( behaviour );\n\t\t\t\t\t\t\t\texternalParentRepresentations.add( Math.max( 0, pos - 1 ) );\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tif ( DEBUG ) {\n\t\t\t\t\t\t\t\t\texternalTestFunction.put( path, behaviour );\n\t\t\t\t\t\t\t\t\tSystem.err.println( \"Computed \" + ( node.isLeaf() ? \"leaf \" : \"\" ) + \"mapping <\" + node.index + \", \" + path + \"> -> \" + behaviour );\n\t\t\t\t\t\t\t\t\tSystem.err.println( externalTestFunction );\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tpos += nodePath.length() + 1;\n\t\t\t\t\t\t\tif ( pos > curr.length() ) {\n\t\t\t\t\t\t\t\tassert false;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t// System.err.println( curr.getBoolean( pos - 1 ) ? \"Turning right\" : \"Turning left\" );\n\t\t\t\t\t\t\tnode = curr.getBoolean( pos - 1 ) ? node.right : node.left;\n\t\t\t\t\t\t\t// Update stack\n\t\t\t\t\t\t\tlen[ ++depth ] = pos;\n\t\t\t\t\t\t\tstack[ depth ] = node;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tprev.replace( curr );\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// No elements.\n\t\t\t\tthis.root = null;\n\t\t\t\tthis.size = this.numElements = 0;\n\t\t\t}\n\t\t}\n\n\t\tprivate void recToString( final Node n, final MutableString printPrefix, final MutableString result, final MutableString path, final int level ) {\n\t\t\tif ( n == null ) return;\n\t\t\t\n\t\t\tresult.append( printPrefix ).append( '(' ).append( level ).append( ')' );\n\t\t\t\n\t\t\tif ( n.path != null ) {\n\t\t\t\tpath.append( n.path );\n\t\t\t\tresult.append( \" path:\" ).append( n.path );\n\t\t\t}\n\n\t\t\tresult.append( '\\n' );\n\t\t\t\n\t\t\tpath.append( '0' );\n\t\t\trecToString( n.left, printPrefix.append( '\\t' ).append( \"0 => \" ), result, path, level + 1 );\n\t\t\tpath.charAt( path.length() - 1, '1' ); \n\t\t\trecToString( n.right, printPrefix.replace( printPrefix.length() - 5, printPrefix.length(), \"1 => \"), result, path, level + 1 );\n\t\t\tpath.delete( path.length() - 1, path.length() ); \n\t\t\tprintPrefix.delete( printPrefix.length() - 6, printPrefix.length() );\n\t\t\t\n\t\t\tpath.delete( (int)( path.length() - n.path.length() ), path.length() );\n\t\t}\n\t\t\n\t\tpublic String toString() {\n\t\t\tMutableString s = new MutableString();\n\t\t\trecToString( root, new MutableString(), s, new MutableString(), 0 );\n\t\t\treturn s.toString();\n\t\t}\n\n\t}\n\t\n\t/** Creates a partial compacted trie using given elements, bucket size and transformation strategy.\n\t * \n\t * @param elements the elements among which the trie must be able to rank.\n\t * @param bucketSize the size of a bucket.\n\t * @param transformationStrategy a transformation strategy that must turn the elements in elements into a list of\n\t * distinct, lexicographically increasing (in iteration order) bit vectors.\n\t */\n\tpublic RelativeTrieDistributor( final Iterable elements, final int bucketSize, final TransformationStrategy transformationStrategy ) throws IOException {\n\t\tthis( elements, bucketSize, transformationStrategy, null );\n\t}\n\n\t/** Creates a partial compacted trie using given elements, bucket size, transformation strategy, and temporary directory.\n\t * \n\t * @param elements the elements among which the trie must be able to rank.\n\t * @param bucketSize the size of a bucket.\n\t * @param transformationStrategy a transformation strategy that must turn the elements in elements into a list of\n\t * distinct, lexicographically increasing (in iteration order) bit vectors.\n\t * @param tempDir the directory where temporary files will be created, or for the default directory.\n\t */\n\tpublic RelativeTrieDistributor( final Iterable elements, final int bucketSize, final TransformationStrategy transformationStrategy, final File tempDir ) throws IOException {\n\t\tthis.transformationStrategy = transformationStrategy;\n\t\tfinal IntermediateTrie intermediateTrie = new IntermediateTrie( elements, bucketSize, transformationStrategy, tempDir );\n\n\t\tsize = intermediateTrie.size;\n\t\texternalTestFunction = intermediateTrie.externalTestFunction;\n\t\t\n\t\tint p = 0;\n\t\t\n\t\tif ( DEBUG ) {\n\t\t\tSystem.err.println( \"Internal node representations: \" + intermediateTrie.internalNodeRepresentations );\n\t\t\tSystem.err.println( \"Internal node keys: \" + intermediateTrie.internalNodeKeys );\n\t\t}\n\t\t\n\t\tsignatures = new MWHCFunction( intermediateTrie.internalNodeKeys, TransformationStrategies.identity(), intermediateTrie.internalNodeSignatures, intermediateTrie.logW + intermediateTrie.logLogW );\n\t\tbehaviour = new MWHCFunction( TransformationStrategies.wrap( elements, transformationStrategy ), TransformationStrategies.identity(), intermediateTrie.externalValues, 1 );\n\n\t\tObjectRBTreeSet rankerStrings = new ObjectRBTreeSet();\n\t\tfor( LongArrayBitVector bv: intermediateTrie.internalNodeRepresentations ) {\n\t\t\tLongArrayBitVector t = bv.copy();\n\t\t\tt.add( false );\n\t\t\trankerStrings.add( t );\n\t\t\tt = bv.copy();\n\t\t\tt.add( true );\n\t\t\trankerStrings.add( t );\n\t\t\tt = bv.copy();\n\t\t\tt.add( true );\n\t\t\tfor( p = t.size(); p-- != 0; ) \n\t\t\t\tif ( ! t.getBoolean( p ) ) break;\n\t\t\t\telse t.set( p, false );\n\t\t\tassert p > -1;\n\t\t\tt.set( p );\n\t\t\trankerStrings.add( t );\n\t\t}\n\t\t\n\t\trankerStrings.addAll( intermediateTrie.delimiters );\n\t\t\n\t\tif ( DEBUG ) System.err.println( \"Rankers: \" + rankerStrings );\n\t\t\n\t\tLongArrayBitVector leavesBitVector = LongArrayBitVector.ofLength( rankerStrings.size() );\n\t\tp = 0;\n\t\tfor( BitVector v : rankerStrings ) {\n\t\t\tif ( intermediateTrie.delimiters.contains( v ) ) leavesBitVector.set( p );\n\t\t\tp++;\n\t\t}\n\t\tleaves = new Rank9( leavesBitVector );\n\t\tif ( DEBUG ) System.err.println( \"Rank bit vector: \" + leavesBitVector );\n\t\t\n\t\tranker = new LcpMonotoneMinimalPerfectHashFunction( rankerStrings, TransformationStrategies.prefixFree() );\n\t\tlogWMask = intermediateTrie.logWMask;\n\t\tlogW = intermediateTrie.logW;\n\t\tlogLogW = intermediateTrie.logLogW;\n\t\tlogLogWMask = intermediateTrie.logLogWMask;\n\t\tw = intermediateTrie.w;\n\t\tnumDelimiters = intermediateTrie.delimiters.size();\n\t\t\n\t\t// Compute errors to be corrected\n\t\tthis.mistakeSignatures = new IntOpenHashSet();\n\t\t\n\t\tif ( size > 0 ) {\n\t\t\tfinal IntOpenHashSet mistakeSignatures = new IntOpenHashSet();\n\n\t\t\tIteratoriterator = TransformationStrategies.wrap( elements.iterator(), transformationStrategy );\n\t\t\tint c = 0, mistakes = 0;\n\t\t\twhile( iterator.hasNext() ) {\n\t\t\t\tBitVector curr = iterator.next();\n\t\t\t\tif ( DEBUG ) System.err.println( \"Checking element number \" + c + ( ( c + 1 ) % bucketSize == 0 ? \" (bucket)\" : \"\" ));\n\t\t\t\tif ( getNodeStringLength( curr ) != intermediateTrie.externalParentRepresentations.getInt( c ) ){\n\t\t\t\t\tif ( DEBUG ) System.err.println( \"Error! \" + getNodeStringLength( curr ) + \" != \" + intermediateTrie.externalParentRepresentations.getInt( c ) );\n\t\t\t\t\tmistakeSignatures.add( curr.hashCode() );\n\t\t\t\t\tmistakes++;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tc++;\n\t\t\t\t\t\t\t\n\t\t\t}\n\t\t\tLOGGER.info( \"Errors: \" + mistakes + \" (\" + ( 100.0 * mistakes / size ) + \"%)\" );\n\t\t\t\n\t\t\t\n\t\t\tObjectArrayList positives = new ObjectArrayList();\n\t\t\tLongArrayList results = new LongArrayList();\n\t\t\tc = 0;\n\t\t\t\n\t\t\tfor( BitVector curr: TransformationStrategies.wrap( elements, transformationStrategy ) ) {\n\t\t\t\tif ( mistakeSignatures.contains( curr.hashCode() ) ) {\n\t\t\t\t\tpositives.add( curr.copy() );\n\t\t\t\t\tresults.add( intermediateTrie.externalParentRepresentations.getInt( c ) ); \n\t\t\t\t}\n\t\t\t\tc++;\n\t\t\t}\n\t\t\t\n\t\t\tLOGGER.info( \"False errors: \" + ( positives.size() - mistakes ) + ( positives.size() != 0 ? \" (\" + 100 * ( positives.size() - mistakes ) / ( positives.size() ) + \"%)\" : \"\" ) );\n\t\t\tthis.mistakeSignatures.addAll( mistakeSignatures );\n\t\t\tcorrections = new MWHCFunction( positives, TransformationStrategies.identity(), results, logW );\n\t\t}\n\n\n\t\t\n\t\tif ( ASSERTS ) {\n\t\t\tif ( size > 0 ) {\n\t\t\t\tIteratoriterator = TransformationStrategies.wrap( elements.iterator(), transformationStrategy );\n\t\t\t\tint c = 0;\n\t\t\t\twhile( iterator.hasNext() ) {\n\t\t\t\t\tBitVector curr = iterator.next();\n\t\t\t\t\tif ( DEBUG ) System.err.println( \"Checking element number \" + c + ( ( c + 1 ) % bucketSize == 0 ? \" (bucket)\" : \"\" ));\n\t\t\t\t\tlong t = getLong( curr );\n\t\t\t\t\tassert t == c / bucketSize : \"At \" + c + \": \" + t + \" != \" + c / bucketSize;\n\t\t\t\t\tc++;\n\t\t\t\t}\t\t\n\t\t\t}\n\t\t}\n\n\t\tLOGGER.debug( \"Behaviour bits per elements: \" + (double)behaviour.numBits() / size );\n\t\tLOGGER.debug( \"Signature bits per elements: \" + (double)signatures.numBits() / size );\n\t\tLOGGER.debug( \"Ranker bits per elements: \" + (double)ranker.numBits() / size );\n\t\tLOGGER.debug( \"Leaves bits per elements: \" + (double)leaves.numBits() / size );\n\t\tLOGGER.debug( \"Mistake bits per elements: \" + (double)numBitsForMistakes() / size );\n\t\t\n\t}\n\t\n\t\n\tprivate long getNodeStringLength( BitVector v ) {\n\t\tif ( DEBUG ) System.err.println( \"getNodeStringLength(\" + v + \")...\" );\n\t\tif ( mistakeSignatures.contains( v.hashCode() ) ) {\n\t\t\tif ( DEBUG ) System.err.println( \"Correcting...\" );\n\t\t\treturn corrections.getLong( v );\n\t\t}\n\t\t\n\t\tint i = logW - 1, j = -1, l = 0, r = (int)v.length();\n\t\twhile( r - l > 1 ) {\n\t\t\tassert i > -1;\n\t\t\tif ( DDEBUG ) System.err.println( \"[\" + l + \"..\" + r + \"]; i = \" + i );\n\t\t\t// ALERT: slow!\n\t\t\tfor( j = l + 1; j < r; j++ ) if ( j % ( 1 << i ) == 0 ) break;\n\t\t\tif ( j < w ) {\n\n\t\t\t\tlong data = signatures.getLong( v.subVector( 0, j ) );\n\t\t\t\t\n\t\t\t\tif ( data < 1 ) r = j;\n\t\t\t\telse {\n\t\t\t\t\tlong[] h = new long[ 3 ];\n\t\t\t\t\tint g = (int)( data & logWMask );\n\n\t\t\t\t\tif ( g > v.length() ) r = j;\n\t\t\t\t\telse {\n\t\t\t\t\t\tHashes.jenkins( v.subVector( 0, g ), 0, h );\n\n\t\t\t\t\t\tif ( DEBUG ) System.err.println( \"Recalling \" + v.subVector( 0, j ) + \" with signature \" + ( h[ 0 ] & logLogW ) + \" and length \" + g );\n\n\t\t\t\t\t\tif ( ( data >>> logW ) == ( h[ 0 ] & logLogWMask ) && g >= j ) l = g;\n\t\t\t\t\t\telse r = j;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\t\n\t\t\ti--;\n\t\t}\n\t\t\n\t\treturn l;\n\t}\n\t\n\t@SuppressWarnings(\"unchecked\")\n\tpublic long getLong( final Object o ) {\n\t\tif ( size == 0 ) return 0;\n\t\tBitVector v = (BitVector)o;\n\t\tint b = (int)behaviour.getLong( o );\n\t\tlong length = getNodeStringLength( v );\n\t\t\n\t\tif ( length == 0 ) return b == 0 ? 0 : numDelimiters;\n\t\t\n\t\tBitVector key = v.subVector( 0, length ).copy();\n\t\tif ( b == 0 ) {\n\t\t\tkey.add( v.getBoolean( length ) );\n\t\t\tlong pos = ranker.getLong( key );\n\t\t\treturn leaves.rank( pos ); \n\t\t}\n\t\telse {\n\t\t\tboolean bit = v.getBoolean( length );\n\t\t\tif ( bit ) {\n\t\t\t\tkey.add( true );\n\t\t\t\tint p;\n\t\t\t\tfor( p = key.size(); p-- != 0; ) \n\t\t\t\t\tif ( ! key.getBoolean( p ) ) break;\n\t\t\t\t\telse key.set( p, false );\n\t\t\t\tassert p > -1;\n\t\t\t\tkey.set( p );\n\t\t\t\tlong pos = ranker.getLong( key );\n\t\t\t\treturn leaves.rank( pos ); \n\t\t\t}\n\t\t\telse {\n\t\t\t\tkey.add( true );\n\t\t\t\tlong pos = ranker.getLong( key );\n\t\t\t\treturn leaves.rank( pos ); \n\t\t\t}\n\t\t}\n\t}\n\n\tprivate long numBitsForMistakes() {\n\t\treturn corrections.numBits() + mistakeSignatures.size() * Integer.SIZE;\n\t}\n\t\n\tpublic long numBits() {\t\t\n\t\treturn behaviour.numBits() + signatures.numBits() + ranker.numBits() + leaves.numBits() + transformationStrategy.numBits() + numBitsForMistakes(); \n\t}\n\t\n\tpublic boolean containsKey( Object o ) {\n\t\treturn true;\n\t}\n\n\tpublic int size() {\n\t\treturn size;\n\t}\n}\n"},"new_file":{"kind":"string","value":"src/it/unimi/dsi/sux4j/mph/RelativeTrieDistributor.java"},"old_contents":{"kind":"string","value":"package it.unimi.dsi.sux4j.mph;\n\n/*\t\t \n * Sux4J: Succinct data structures for Java\n *\n * Copyright (C) 2008 Sebastiano Vigna \n *\n * This library is free software; you can redistribute it and/or modify it\n * under the terms of the GNU Lesser General Public License as published by the Free\n * Software Foundation; either version 2.1 of the License, or (at your option)\n * any later version.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License\n * for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n *\n */\n\nimport it.unimi.dsi.Util;\nimport it.unimi.dsi.bits.BitVector;\nimport it.unimi.dsi.bits.Fast;\nimport it.unimi.dsi.bits.LongArrayBitVector;\nimport it.unimi.dsi.bits.TransformationStrategies;\nimport it.unimi.dsi.bits.TransformationStrategy;\nimport it.unimi.dsi.fastutil.ints.IntArrayList;\nimport it.unimi.dsi.fastutil.ints.IntOpenHashSet;\nimport it.unimi.dsi.fastutil.longs.LongArrayList;\nimport it.unimi.dsi.fastutil.objects.AbstractObject2LongFunction;\nimport it.unimi.dsi.fastutil.objects.Object2LongFunction;\nimport it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap;\nimport it.unimi.dsi.fastutil.objects.ObjectArrayList;\nimport it.unimi.dsi.fastutil.objects.ObjectOpenHashSet;\nimport it.unimi.dsi.fastutil.objects.ObjectRBTreeSet;\nimport it.unimi.dsi.lang.MutableString;\nimport it.unimi.dsi.sux4j.bits.Rank9;\nimport it.unimi.dsi.util.LongBigList;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Iterator;\n\nimport org.apache.log4j.Logger;\n\n/** A distributor based on a probabilistic trie.\n * \n */\n\npublic class RelativeTrieDistributor extends AbstractObject2LongFunction {\n\tprivate final static Logger LOGGER = Util.getLogger( RelativeTrieDistributor.class );\n\tprivate static final long serialVersionUID = 1L;\n\tprivate static final boolean DEBUG = false;\n\tprivate static final boolean DDEBUG = false;\n\tprivate static final boolean ASSERTS = true;\n\n\t/** An integer representing the exit-on-the-left behaviour. */\n\tprivate final static int LEFT = 0;\n\t/** An integer representing the exit-on-the-right behaviour. */\n\tprivate final static int RIGHT = 1;\n\t/** A ranking structure on the vector containing leaves plus p0,p1, etc. */\n\tprivate final Rank9 leaves;\n\t/** The transformation used to map object to bit vectors. */\n\tprivate final TransformationStrategy transformationStrategy;\n\t/** For each external node and each possible path, the related behaviour. */\n\tprivate final MWHCFunction behaviour;\n\t/** The number of (internal and external) nodes of the trie. */\n\tprivate final int size;\n\t/** A debug function used to store explicitly {@link #behaviour}. */\n\tprivate final Object2LongFunction externalTestFunction;\n\tprivate MWHCFunction signatures;\n\tprivate int w;\n\tprivate LcpMonotoneMinimalPerfectHashFunction ranker;\n\tprivate long logWMask;\n\tprivate int logW;\n\tprivate int logLogW;\n\tprivate long logLogWMask;\n\tprivate int numDelimiters;\n\tprivate IntOpenHashSet mistakeSignatures;\n\tprivate MWHCFunction corrections;\n\t\n\t/** An intermediate class containing the compacted trie generated by the delimiters. */\n\tprivate final static class IntermediateTrie {\n\t\t/** A debug function used to store explicitly the internal behaviour. */\n\t\tprivate Object2LongFunction externalTestFunction;\n\t\t/** The root of the trie. */\n\t\tprotected final Node root;\n\t\t/** The number of overall elements to distribute. */\n\t\tprivate final int numElements;\n\t\t/** The number of internal nodes of the trie. */\n\t\tprotected final int size;\n\t\t/** The values associated to the keys in {@link #externalKeysFile}. */\n\t\tprivate LongBigList externalValues;\n\t\t/** The string representing the parent of each key in {@link #externalKeysFile}. */\n\t\tprivate IntArrayList externalParentRepresentations;\n\t\tprivate int w;\n\t\tprivate int logW;\n\t\tprivate int logLogW;\n\t\tprivate long logLogWMask;\n\t\tprivate long logWMask;\n\t\tprivate ObjectArrayList internalNodeKeys;\n\t\tprivate ObjectArrayList internalNodeRepresentations;\n\t\tprivate LongArrayList internalNodeSignatures;\n\t\tprivate ObjectOpenHashSet delimiters;\n\t\t\n\t\t/** A node in the trie. */\n\t\tprivate static class Node {\n\t\t\t/** Left child. */\n\t\t\tprivate Node left;\n\t\t\t/** Right child. */\n\t\t\tprivate Node right;\n\t\t\t/** The path compacted in this node (null if there is no compaction at this node). */\n\t\t\tprivate final LongArrayBitVector path;\n\t\t\t/** The index of this node in breadth-first order. */\n\t\t\tprivate int index;\n\n\t\t\t/** Creates a node. \n\t\t\t * \n\t\t\t * @param left the left child.\n\t\t\t * @param right the right child.\n\t\t\t * @param path the path compacted at this node.\n\t\t\t */\n\t\t\tpublic Node( final Node left, final Node right, final LongArrayBitVector path ) {\n\t\t\t\tthis.left = left;\n\t\t\t\tthis.right = right;\n\t\t\t\tthis.path = path;\n\t\t\t}\n\n\t\t\t/** Returns true if this node is a leaf.\n\t\t\t * \n\t\t\t * @return true if this node is a leaf.\n\t\t\t */\n\t\t\tpublic boolean isLeaf() {\n\t\t\t\treturn right == null && left == null;\n\t\t\t}\n\t\t\t\n\t\t\tpublic String toString() {\n\t\t\t\treturn \"[\" + path + \"]\";\n\t\t\t}\n\t\t}\n\t\t\t\n\t\tvoid labelIntermediateTrie( Node node, LongArrayBitVector path,ObjectArrayList representations, ObjectArrayListkeys, LongArrayList values ) {\n\t\t\tassert ( node.left != null ) == ( node.right != null );\n\t\t\tif ( node.left != null ) {\n\n\t\t\t\tlong parentPathLength = path.length() - 1;\n\t\t\t\t\n\t\t\t\tpath.append( node.path );\n\n\t\t\t\tlabelIntermediateTrie( node.left, path.append( 0, 1 ), representations, keys, values );\n\t\t\t\tpath.remove( (int)( path.length() - 1 ) );\n\n\t\t\t\tlong[] h = new long[ 3 ];\n\t\t\t\tHashes.jenkins( path, 0, h );\n\n\t\t\t\tint p = w / 2;\n\t\t\t\tint j = w / 4;\n\t\t\t\twhile( p <= parentPathLength || p > path.length() ) {\n\t\t\t\t\tif ( p <= parentPathLength ) p += j;\n\t\t\t\t\telse p -= j;\n\n\t\t\t\t\tj /= 2;\n\t\t\t\t}\n\n\t\t\t\tassert p <= path.length();\n\t\t\t\tassert p > parentPathLength;\n\n\t\t\t\tkeys.add( LongArrayBitVector.copy( path.subVector( 0, p ) ) );\n\t\t\t\trepresentations.add( path.copy() );\n\t\t\t\tassert Fast.length( path.length() ) <= logW;\n\t\t\t\t//System.err.println( \"Entering \" + path + \" with key \" + path.subVector( 0, p ) + \", signature \" + ( h[ 0 ] & logWMask ) + \" and length \" + ( path.length() & wMask ) );\n\t\t\t\t\n\t\t\t\tvalues.add( ( h[ 0 ] & logLogWMask ) << logW | ( path.length() & logWMask ) );\n\n\t\t\t\tlabelIntermediateTrie( node.right, path.append( 1, 1 ), representations, keys, values );\n\n\t\t\t\tpath.length( path.length() - node.path.length() - 1 );\n\t\t\t}\n\t\t}\n\n\t\t\n\t\t/** Creates a partial compacted trie using given elements, bucket size and transformation strategy.\n\t\t * \n\t\t * @param elements the elements among which the trie must be able to rank.\n\t\t * @param bucketSize the size of a bucket.\n\t\t * @param transformationStrategy a transformation strategy that must turn the elements in elements into a list of\n\t\t * distinct, prefix-free, lexicographically increasing (in iteration order) bit vectors.\n\t\t * @param tempDir a directory for the temporary files created during construction, or null for the default temporary directory. \n\t\t */\n\t\t\n\t\tpublic IntermediateTrie( final Iterable elements, final int bucketSize, final TransformationStrategy transformationStrategy, final File tempDir ) {\n\t\t\tif ( ASSERTS ) {\n\t\t\t\texternalTestFunction = new Object2LongOpenHashMap();\n\t\t\t\texternalTestFunction.defaultReturnValue( -1 );\n\t\t\t}\n\t\t\t\n\t\t\tIterator iterator = elements.iterator(); \n\t\t\tdelimiters = new ObjectOpenHashSet();\n\t\t\t\n\t\t\tif ( iterator.hasNext() ) {\n\t\t\t\tLongArrayBitVector prev = LongArrayBitVector.copy( transformationStrategy.toBitVector( iterator.next() ) );\n\t\t\t\tLongArrayBitVector prevDelimiter = LongArrayBitVector.getInstance();\n\t\t\t\t\n\t\t\t\tNode node, root = null;\n\t\t\t\tBitVector curr;\n\t\t\t\tint cmp, pos, prefix, count = 1;\n\t\t\t\tlong maxLength = prev.length();\n\t\t\t\t\n\t\t\t\twhile( iterator.hasNext() ) {\n\t\t\t\t\t// Check order\n\t\t\t\t\tcurr = transformationStrategy.toBitVector( iterator.next() ).fast();\n\t\t\t\t\tcmp = prev.compareTo( curr );\n\t\t\t\t\tif ( cmp == 0 ) throw new IllegalArgumentException( \"The input bit vectors are not distinct\" );\n\t\t\t\t\tif ( cmp > 0 ) throw new IllegalArgumentException( \"The input bit vectors are not lexicographically sorted\" );\n\t\t\t\t\tif ( curr.longestCommonPrefixLength( prev ) == prev.length() ) throw new IllegalArgumentException( \"The input bit vectors are not prefix-free\" );\n\n\t\t\t\t\tif ( count % bucketSize == 0 ) {\n\t\t\t\t\t\t// Found delimiter. Insert into trie.\n\t\t\t\t\t\tif ( root == null ) {\n\t\t\t\t\t\t\troot = new Node( null, null, prev.copy() );\n\t\t\t\t\t\t\tdelimiters.add( prev.copy() );\n\t\t\t\t\t\t\tprevDelimiter.replace( prev );\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tprefix = (int)prev.longestCommonPrefixLength( prevDelimiter );\n\n\t\t\t\t\t\t\tpos = 0;\n\t\t\t\t\t\t\tnode = root;\n\t\t\t\t\t\t\tNode n = null;\n\t\t\t\t\t\t\twhile( node != null ) {\n\t\t\t\t\t\t\t\tfinal long pathLength = node.path.length();\n\t\t\t\t\t\t\t\tif ( prefix < pathLength ) {\n\t\t\t\t\t\t\t\t\tn = new Node( node.left, node.right, node.path.copy( prefix + 1, pathLength ) );\n\t\t\t\t\t\t\t\t\tnode.path.length( prefix );\n\t\t\t\t\t\t\t\t\tnode.path.trim();\n\t\t\t\t\t\t\t\t\tnode.left = n;\n\t\t\t\t\t\t\t\t\tnode.right = new Node( null, null, prev.copy( pos + prefix + 1, prev.length() ) ); \n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tprefix -= pathLength + 1;\n\t\t\t\t\t\t\t\tpos += pathLength + 1;\n\t\t\t\t\t\t\t\tnode = node.right;\n\t\t\t\t\t\t\t\tif ( ASSERTS ) assert node == null || prefix >= 0 : prefix + \" <= \" + 0;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif ( ASSERTS ) assert node != null;\n\n\t\t\t\t\t\t\tdelimiters.add( prev.copy() );\n\t\t\t\t\t\t\tprevDelimiter.replace( prev );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tprev.replace( curr );\n\t\t\t\t\tmaxLength = Math.max( maxLength, prev.length() );\n\t\t\t\t\tcount++;\n\t\t\t\t}\n\n\t\t\t\tsize = count;\n\t\t\t\tlogLogW = Fast.ceilLog2( Fast.ceilLog2( maxLength ) );\n\t\t\t\tlogW = 1 << logLogW;\n\t\t\t\tw = 1 << logW;\n\t\t\t\tlogWMask = ( 1 << logW ) - 1;\n\t\t\t\tlogLogWMask = ( 1 << logLogW ) - 1;\n\t\t\t\tassert logW + logLogW <= Long.SIZE;\n\t\t\t\t\n\t\t\t\tthis.numElements = count;\n\t\t\t\tthis.root = root;\n\t\t\t\t\n\t\t\t\tif ( DEBUG ) {\n\t\t\t\t\tSystem.err.println( \"w: \" + w );\n\t\t\t\t\tSystem.err.println( \"Delimiters: \" + delimiters );\n\t\t\t\t\tSystem.err.println( this );\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif ( root != null ) {\n\t\t\t\t\tLOGGER.info( \"Computing approximate structure...\" );\n\n\t\t\t\t\tinternalNodeRepresentations = new ObjectArrayList();\n\t\t\t\t\tinternalNodeSignatures = new LongArrayList();\n\t\t\t\t\tinternalNodeKeys = new ObjectArrayList();\n\t\t\t\t\tlabelIntermediateTrie( root, LongArrayBitVector.getInstance(), internalNodeRepresentations, internalNodeKeys, internalNodeSignatures );\n\n\t\t\t\t\tif ( DEBUG ) {\n\t\t\t\t\t\tSystem.err.println( \"Internal node representations: \" + internalNodeRepresentations );\n\t\t\t\t\t\tSystem.err.println( \"Internal node signatures: \" + internalNodeSignatures );\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tLOGGER.info( \"Computing function keys...\" );\n\n\t\t\t\t\texternalValues = LongArrayBitVector.getInstance().asLongBigList( 1 );\n\t\t\t\t\texternalParentRepresentations = new IntArrayList( size );\n\t\t\t\t\titerator = elements.iterator();\n\n\t\t\t\t\t// The stack of nodes visited the last time\n\t\t\t\t\tfinal Node stack[] = new Node[ (int)maxLength ];\n\t\t\t\t\t// The length of the path compacted in the trie up to the corresponding node, excluded\n\t\t\t\t\tfinal int[] len = new int[ (int)maxLength ];\n\t\t\t\t\tstack[ 0 ] = root;\n\t\t\t\t\tint depth = 0, behaviour;\n\t\t\t\t\tboolean first = true;\n\t\t\t\t\tBitVector currFromPos, path;\n\t\t\t\t\tLongArrayBitVector nodePath;\n\n\t\t\t\t\twhile( iterator.hasNext() ) {\n\t\t\t\t\t\tcurr = transformationStrategy.toBitVector( iterator.next() ).fast();\n\t\t\t\t\t\tif ( DEBUG ) System.err.println( \"Analysing key \" + curr + \"...\" );\n\t\t\t\t\t\tif ( ! first ) {\n\t\t\t\t\t\t\t// Adjust stack using lcp between present string and previous one\n\t\t\t\t\t\t\tprefix = (int)prev.longestCommonPrefixLength( curr );\n\t\t\t\t\t\t\twhile( depth > 0 && len[ depth ] > prefix ) depth--;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse first = false;\n\t\t\t\t\t\tnode = stack[ depth ];\n\t\t\t\t\t\tpos = len[ depth ];\n\n\t\t\t\t\t\tfor(;;) {\n\t\t\t\t\t\t\tnodePath = node.path;\n\t\t\t\t\t\t\tcurrFromPos = curr.subVector( pos ); \n\t\t\t\t\t\t\tprefix = (int)currFromPos.longestCommonPrefixLength( nodePath );\n\n\t\t\t\t\t\t\t//System.err.println( \"prefix: \" + prefix + \" nodePath.length(): \" + nodePath.length() + \" node.isLeaf(): \" + node.isLeaf() );\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif ( prefix < nodePath.length() || node.isLeaf() ) {\n\t\t\t\t\t\t\t\t// Exit. LEFT or RIGHT, depending on the bit at the end of the common prefix. The\n\t\t\t\t\t\t\t\t// path is the remaining path at the current position for external nodes, or a prefix of length\n\t\t\t\t\t\t\t\t// at most pathLength for internal nodes.\n\t\t\t\t\t\t\t\tbehaviour = prefix < nodePath.length() && ! nodePath.getBoolean( prefix ) ? RIGHT : LEFT;\n\t\t\t\t\t\t\t\tpath = curr;\n\n\t\t\t\t\t\t\t\texternalValues.add( behaviour );\n\t\t\t\t\t\t\t\texternalParentRepresentations.add( Math.max( 0, pos - 1 ) );\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tif ( DEBUG ) {\n\t\t\t\t\t\t\t\t\texternalTestFunction.put( path, behaviour );\n\t\t\t\t\t\t\t\t\tSystem.err.println( \"Computed \" + ( node.isLeaf() ? \"leaf \" : \"\" ) + \"mapping <\" + node.index + \", \" + path + \"> -> \" + behaviour );\n\t\t\t\t\t\t\t\t\tSystem.err.println( externalTestFunction );\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tpos += nodePath.length() + 1;\n\t\t\t\t\t\t\tif ( pos > curr.length() ) {\n\t\t\t\t\t\t\t\tassert false;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t// System.err.println( curr.getBoolean( pos - 1 ) ? \"Turning right\" : \"Turning left\" );\n\t\t\t\t\t\t\tnode = curr.getBoolean( pos - 1 ) ? node.right : node.left;\n\t\t\t\t\t\t\t// Update stack\n\t\t\t\t\t\t\tlen[ ++depth ] = pos;\n\t\t\t\t\t\t\tstack[ depth ] = node;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tprev.replace( curr );\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// No elements.\n\t\t\t\tthis.root = null;\n\t\t\t\tthis.size = this.numElements = 0;\n\t\t\t}\n\t\t}\n\n\t\tprivate void recToString( final Node n, final MutableString printPrefix, final MutableString result, final MutableString path, final int level ) {\n\t\t\tif ( n == null ) return;\n\t\t\t\n\t\t\tresult.append( printPrefix ).append( '(' ).append( level ).append( ')' );\n\t\t\t\n\t\t\tif ( n.path != null ) {\n\t\t\t\tpath.append( n.path );\n\t\t\t\tresult.append( \" path:\" ).append( n.path );\n\t\t\t}\n\n\t\t\tresult.append( '\\n' );\n\t\t\t\n\t\t\tpath.append( '0' );\n\t\t\trecToString( n.left, printPrefix.append( '\\t' ).append( \"0 => \" ), result, path, level + 1 );\n\t\t\tpath.charAt( path.length() - 1, '1' ); \n\t\t\trecToString( n.right, printPrefix.replace( printPrefix.length() - 5, printPrefix.length(), \"1 => \"), result, path, level + 1 );\n\t\t\tpath.delete( path.length() - 1, path.length() ); \n\t\t\tprintPrefix.delete( printPrefix.length() - 6, printPrefix.length() );\n\t\t\t\n\t\t\tpath.delete( (int)( path.length() - n.path.length() ), path.length() );\n\t\t}\n\t\t\n\t\tpublic String toString() {\n\t\t\tMutableString s = new MutableString();\n\t\t\trecToString( root, new MutableString(), s, new MutableString(), 0 );\n\t\t\treturn s.toString();\n\t\t}\n\n\t}\n\t\n\t/** Creates a partial compacted trie using given elements, bucket size and transformation strategy.\n\t * \n\t * @param elements the elements among which the trie must be able to rank.\n\t * @param bucketSize the size of a bucket.\n\t * @param transformationStrategy a transformation strategy that must turn the elements in elements into a list of\n\t * distinct, lexicographically increasing (in iteration order) bit vectors.\n\t */\n\tpublic RelativeTrieDistributor( final Iterable elements, final int bucketSize, final TransformationStrategy transformationStrategy ) throws IOException {\n\t\tthis( elements, bucketSize, transformationStrategy, null );\n\t}\n\n\t/** Creates a partial compacted trie using given elements, bucket size, transformation strategy, and temporary directory.\n\t * \n\t * @param elements the elements among which the trie must be able to rank.\n\t * @param bucketSize the size of a bucket.\n\t * @param transformationStrategy a transformation strategy that must turn the elements in elements into a list of\n\t * distinct, lexicographically increasing (in iteration order) bit vectors.\n\t * @param tempDir the directory where temporary files will be created, or for the default directory.\n\t */\n\tpublic RelativeTrieDistributor( final Iterable elements, final int bucketSize, final TransformationStrategy transformationStrategy, final File tempDir ) throws IOException {\n\t\tthis.transformationStrategy = transformationStrategy;\n\t\tfinal IntermediateTrie intermediateTrie = new IntermediateTrie( elements, bucketSize, transformationStrategy, tempDir );\n\n\t\tsize = intermediateTrie.size;\n\t\texternalTestFunction = intermediateTrie.externalTestFunction;\n\t\t\n\t\tint p = 0;\n\t\t\n\t\tif ( DEBUG ) {\n\t\t\tSystem.err.println( \"Internal node representations: \" + intermediateTrie.internalNodeRepresentations );\n\t\t\tSystem.err.println( \"Internal node keys: \" + intermediateTrie.internalNodeKeys );\n\t\t}\n\t\t\n\t\tsignatures = new MWHCFunction( intermediateTrie.internalNodeKeys, TransformationStrategies.identity(), intermediateTrie.internalNodeSignatures, intermediateTrie.logW + intermediateTrie.logLogW );\n\t\tbehaviour = new MWHCFunction( TransformationStrategies.wrap( elements, transformationStrategy ), TransformationStrategies.identity(), intermediateTrie.externalValues, 1 );\n\n\t\tObjectRBTreeSet rankerStrings = new ObjectRBTreeSet();\n\t\tfor( LongArrayBitVector bv: intermediateTrie.internalNodeRepresentations ) {\n\t\t\tLongArrayBitVector t = bv.copy();\n\t\t\tt.add( false );\n\t\t\trankerStrings.add( t );\n\t\t\tt = bv.copy();\n\t\t\tt.add( true );\n\t\t\trankerStrings.add( t );\n\t\t\tt = bv.copy();\n\t\t\tt.add( true );\n\t\t\tfor( p = t.size(); p-- != 0; ) \n\t\t\t\tif ( ! t.getBoolean( p ) ) break;\n\t\t\t\telse t.set( p, false );\n\t\t\tassert p > -1;\n\t\t\tt.set( p );\n\t\t\trankerStrings.add( t );\n\t\t}\n\t\t\n\t\trankerStrings.addAll( intermediateTrie.delimiters );\n\t\t\n\t\tif ( DEBUG ) System.err.println( \"Rankers: \" + rankerStrings );\n\t\t\n\t\tLongArrayBitVector leavesBitVector = LongArrayBitVector.ofLength( rankerStrings.size() );\n\t\tp = 0;\n\t\tfor( BitVector v : rankerStrings ) {\n\t\t\tif ( intermediateTrie.delimiters.contains( v ) ) leavesBitVector.set( p );\n\t\t\tp++;\n\t\t}\n\t\tleaves = new Rank9( leavesBitVector );\n\t\tif ( DEBUG ) System.err.println( \"Rank bit vector: \" + leavesBitVector );\n\t\t\n\t\tranker = new LcpMonotoneMinimalPerfectHashFunction( rankerStrings, TransformationStrategies.prefixFree() );\n\t\tlogWMask = intermediateTrie.logWMask;\n\t\tlogW = intermediateTrie.logW;\n\t\tlogLogW = intermediateTrie.logLogW;\n\t\tlogLogWMask = intermediateTrie.logLogWMask;\n\t\tw = intermediateTrie.w;\n\t\tnumDelimiters = intermediateTrie.delimiters.size();\n\t\t\n\t\t// Compute errors to be corrected\n\t\tthis.mistakeSignatures = new IntOpenHashSet();\n\t\t\n\t\tif ( size > 0 ) {\n\t\t\tfinal IntOpenHashSet mistakeSignatures = new IntOpenHashSet();\n\n\t\t\tIteratoriterator = TransformationStrategies.wrap( elements.iterator(), transformationStrategy );\n\t\t\tint c = 0, mistakes = 0;\n\t\t\twhile( iterator.hasNext() ) {\n\t\t\t\tBitVector curr = iterator.next();\n\t\t\t\tif ( DEBUG ) System.err.println( \"Checking element number \" + c + ( ( c + 1 ) % bucketSize == 0 ? \" (bucket)\" : \"\" ));\n\t\t\t\tif ( getNodeStringLength( curr ) != intermediateTrie.externalParentRepresentations.getInt( c ) ){\n\t\t\t\t\tif ( DEBUG ) System.err.println( \"Error! \" + getNodeStringLength( curr ) + \" != \" + intermediateTrie.externalParentRepresentations.getInt( c ) );\n\t\t\t\t\tmistakeSignatures.add( curr.hashCode() );\n\t\t\t\t\tmistakes++;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tc++;\n\t\t\t\t\t\t\t\n\t\t\t}\n\t\t\tLOGGER.info( \"Errors: \" + mistakes + \" (\" + ( 100.0 * mistakes / size ) + \"%)\" );\n\t\t\t\n\t\t\t\n\t\t\tObjectArrayList positives = new ObjectArrayList();\n\t\t\tLongArrayList results = new LongArrayList();\n\t\t\tc = 0;\n\t\t\t\n\t\t\tfor( BitVector curr: TransformationStrategies.wrap( elements, transformationStrategy ) ) {\n\t\t\t\tif ( mistakeSignatures.contains( curr.hashCode() ) ) {\n\t\t\t\t\tpositives.add( curr.copy() );\n\t\t\t\t\tresults.add( intermediateTrie.externalParentRepresentations.getInt( c ) ); \n\t\t\t\t}\n\t\t\t\tc++;\n\t\t\t}\n\t\t\t\n\t\t\tLOGGER.info( \"False errors: \" + ( positives.size() - mistakes ) + ( positives.size() != 0 ? \" (\" + 100 * ( positives.size() - mistakes ) / ( positives.size() ) + \"%)\" : \"\" ) );\n\t\t\tthis.mistakeSignatures.addAll( mistakeSignatures );\n\t\t\tcorrections = new MWHCFunction( positives, TransformationStrategies.identity(), results, logW );\n\t\t}\n\n\n\t\t\n\t\tif ( ASSERTS ) {\n\t\t\tif ( size > 0 ) {\n\t\t\t\tIteratoriterator = TransformationStrategies.wrap( elements.iterator(), transformationStrategy );\n\t\t\t\tint c = 0;\n\t\t\t\twhile( iterator.hasNext() ) {\n\t\t\t\t\tBitVector curr = iterator.next();\n\t\t\t\t\tif ( DEBUG ) System.err.println( \"Checking element number \" + c + ( ( c + 1 ) % bucketSize == 0 ? \" (bucket)\" : \"\" ));\n\t\t\t\t\tlong t = getLong( curr );\n\t\t\t\t\tassert t == c / bucketSize : \"At \" + c + \": \" + t + \" != \" + c / bucketSize;\n\t\t\t\t\tc++;\n\t\t\t\t}\t\t\n\t\t\t}\n\t\t}\n\n\t\tLOGGER.debug( \"Behaviour bits per elements: \" + (double)behaviour.numBits() / size );\n\t\tLOGGER.debug( \"Signature bits per elements: \" + (double)signatures.numBits() / size );\n\t\tLOGGER.debug( \"Ranker bits per elements: \" + (double)ranker.numBits() / size );\n\t\tLOGGER.debug( \"Leaves bits per elements: \" + (double)leaves.numBits() / size );\n\t\tLOGGER.debug( \"Mistake bits per elements: \" + (double)numBitsForMistakes() / size );\n\t\t\n\t}\n\t\n\t\n\tprivate long getNodeStringLength( BitVector v ) {\n\t\tif ( DEBUG ) System.err.println( \"getNodeStringLength(\" + v + \")...\" );\n\t\tif ( mistakeSignatures.contains( v.hashCode() ) ) {\n\t\t\tif ( DEBUG ) System.err.println( \"Correcting...\" );\n\t\t\treturn corrections.getLong( v );\n\t\t}\n\t\t\n\t\tint i = logW - 1, j = -1, l = 0, r = (int)v.length();\n\t\twhile( r - l > 1 ) {\n\t\t\tassert i > -1;\n\t\t\tif ( DDEBUG ) System.err.println( \"[\" + l + \"..\" + r + \"]; i = \" + i );\n\t\t\t// ALERT: slow!\n\t\t\tfor( j = l + 1; j < r; j++ ) if ( j % ( 1 << i ) == 0 ) break;\n\t\t\tif ( j < w ) {\n\n\t\t\t\tlong data = signatures.getLong( v.subVector( 0, j ) );\n\t\t\t\t\n\t\t\t\tif ( data < 1 ) r = j;\n\t\t\t\telse {\n\t\t\t\t\tlong[] h = new long[ 3 ];\n\t\t\t\t\tint g = (int)( data & logWMask );\n\n\t\t\t\t\tif ( g > v.length() ) r = j;\n\t\t\t\t\telse {\n\t\t\t\t\t\tHashes.jenkins( v.subVector( 0, g ), 0, h );\n\n\t\t\t\t\t\tif ( DEBUG ) System.err.println( \"Recalling \" + v.subVector( 0, j ) + \" with signature \" + ( h[ 0 ] & logLogW ) + \" and length \" + g );\n\n\t\t\t\t\t\tif ( ( data >>> logW ) == ( h[ 0 ] & logLogWMask ) && g >= j ) l = g;\n\t\t\t\t\t\telse r = j;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\t\n\t\t\ti--;\n\t\t}\n\t\t\n\t\treturn l;\n\t}\n\t\n\t@SuppressWarnings(\"unchecked\")\n\tpublic long getLong( final Object o ) {\n\t\tif ( size == 0 ) return 0;\n\t\tBitVector v = (BitVector)o;\n\t\tint b = (int)behaviour.getLong( o );\n\t\tlong length = getNodeStringLength( v );\n\t\t\n\t\tif ( length == 0 ) return b == 0 ? 0 : numDelimiters;\n\t\t\n\t\tBitVector key = v.subVector( 0, length ).copy();\n\t\tif ( b == 0 ) {\n\t\t\tkey.add( v.getBoolean( length ) );\n\t\t\tlong pos = ranker.getLong( key );\n\t\t\treturn leaves.rank( pos ); \n\t\t}\n\t\telse {\n\t\t\tboolean bit = v.getBoolean( length );\n\t\t\tif ( bit ) {\n\t\t\t\tkey.add( true );\n\t\t\t\tint p;\n\t\t\t\tfor( p = key.size(); p-- != 0; ) \n\t\t\t\t\tif ( ! key.getBoolean( p ) ) break;\n\t\t\t\t\telse key.set( p, false );\n\t\t\t\tassert p > -1;\n\t\t\t\tkey.set( p );\n\t\t\t\tlong pos = ranker.getLong( key );\n\t\t\t\treturn leaves.rank( pos ); \n\t\t\t}\n\t\t\telse {\n\t\t\t\tkey.add( true );\n\t\t\t\tlong pos = ranker.getLong( key );\n\t\t\t\treturn leaves.rank( pos ); \n\t\t\t}\n\t\t}\n\t}\n\n\tprivate long numBitsForMistakes() {\n\t\treturn corrections.numBits() + mistakeSignatures.size() * Integer.SIZE;\n\t}\n\t\n\tpublic long numBits() {\t\t\n\t\treturn behaviour.numBits() + signatures.numBits() + ranker.numBits() + leaves.numBits() + transformationStrategy.numBits() + numBitsForMistakes(); \n\t}\n\t\n\tpublic boolean containsKey( Object o ) {\n\t\treturn true;\n\t}\n\n\tpublic int size() {\n\t\treturn size;\n\t}\n}\n"},"message":{"kind":"string","value":"Tweaking\n"},"old_file":{"kind":"string","value":"src/it/unimi/dsi/sux4j/mph/RelativeTrieDistributor.java"},"subject":{"kind":"string","value":"Tweaking"},"git_diff":{"kind":"string","value":"rc/it/unimi/dsi/sux4j/mph/RelativeTrieDistributor.java\n import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet;\n import it.unimi.dsi.fastutil.objects.ObjectRBTreeSet;\n import it.unimi.dsi.lang.MutableString;\nimport it.unimi.dsi.logging.ProgressLogger;\n import it.unimi.dsi.sux4j.bits.Rank9;\n import it.unimi.dsi.util.LongBigList;\n \n \t\t\t\treturn \"[\" + path + \"]\";\n \t\t\t}\n \t\t}\n\t\t\n\t\tProgressLogger pl = new ProgressLogger();\n \t\t\t\n \t\tvoid labelIntermediateTrie( Node node, LongArrayBitVector path,ObjectArrayList representations, ObjectArrayListkeys, LongArrayList values ) {\n \t\t\tassert ( node.left != null ) == ( node.right != null );\n \t\t\tif ( node.left != null ) {\n\n\t\t\t\tpl.update();\n\t\t\t\t\n \t\t\t\tlong parentPathLength = path.length() - 1;\n \t\t\t\t\n \t\t\t\tpath.append( node.path );\n \t\t\t\t\tinternalNodeRepresentations = new ObjectArrayList();\n \t\t\t\t\tinternalNodeSignatures = new LongArrayList();\n \t\t\t\t\tinternalNodeKeys = new ObjectArrayList();\n\t\t\t\t\tpl.expectedUpdates = delimiters.size();\n\t\t\t\t\tpl.start( \"Labelling trie...\" );\n \t\t\t\t\tlabelIntermediateTrie( root, LongArrayBitVector.getInstance(), internalNodeRepresentations, internalNodeKeys, internalNodeSignatures );\n\t\t\t\t\tpl.done();\n \n \t\t\t\t\tif ( DEBUG ) {\n \t\t\t\t\t\tSystem.err.println( \"Internal node representations: \" + internalNodeRepresentations );"}}},{"rowIdx":1944,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"e2f39ca8c7052c6e921d259038ca5362bc5a91e5"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"niyueming/Pedometer,j4velin/Pedometer,hibernate2011/Pedometer,hgl888/Pedometer,dhootha/Pedometer,MilanNz/Pedometer,ayyb1988/Pedometer"},"new_contents":{"kind":"string","value":"/*\n * Copyright 2013 Thomas Hoffmann\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 de.j4velin.pedometer;\n\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\n\nimport de.j4velin.pedometer.util.Logger;\nimport de.j4velin.pedometer.util.Util;\n\npublic class ShutdownRecevier extends BroadcastReceiver {\n\n @Override\n public void onReceive(final Context context, final Intent intent) {\n if (BuildConfig.DEBUG) Logger.log(\"shutting down\");\n\n context.startService(new Intent(context, SensorListener.class));\n\n // if the user used a root script for shutdown, the DEVICE_SHUTDOWN\n // broadcast might not be send. Therefore, the app will check this\n // setting on the next boot and displays an error message if it's not\n // set to true\n context.getSharedPreferences(\"pedometer\", Context.MODE_MULTI_PROCESS).edit()\n .putBoolean(\"correctShutdown\", true).commit();\n\n Database db = Database.getInstance(context);\n // if it's already a new day, add the temp. steps to the last one\n if (db.getSteps(Util.getToday()) == Integer.MIN_VALUE) {\n int steps = db.getCurrentSteps();\n int pauseDifference = steps -\n context.getSharedPreferences(\"pedometer\", Context.MODE_MULTI_PROCESS)\n .getInt(\"pauseCount\", steps);\n db.insertNewDay(Util.getToday(), steps - pauseDifference);\n if (pauseDifference > 0) {\n // update pauseCount for the new day\n context.getSharedPreferences(\"pedometer\", Context.MODE_MULTI_PROCESS).edit()\n .putInt(\"pauseCount\", steps).commit();\n }\n } else {\n db.updateSteps(Util.getToday(), db.getCurrentSteps());\n }\n // current steps will be reset on boot @see BootReceiver\n db.close();\n }\n\n}\n"},"new_file":{"kind":"string","value":"src/main/java/de/j4velin/pedometer/ShutdownRecevier.java"},"old_contents":{"kind":"string","value":"/*\n * Copyright 2013 Thomas Hoffmann\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 de.j4velin.pedometer;\n\nimport de.j4velin.pedometer.util.Logger;\nimport de.j4velin.pedometer.util.Util;\n\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\n\npublic class ShutdownRecevier extends BroadcastReceiver {\n\n @Override\n public void onReceive(final Context context, final Intent intent) {\n if (BuildConfig.DEBUG) Logger.log(\"shutting down\");\n\n context.startService(new Intent(context, SensorListener.class));\n\n // if the user used a root script for shutdown, the DEVICE_SHUTDOWN\n // broadcast might not be send. Therefore, the app will check this\n // setting on the next boot and displays an error message if it's not\n // set to true\n context.getSharedPreferences(\"pedometer\", Context.MODE_MULTI_PROCESS).edit()\n .putBoolean(\"correctShutdown\", true).commit();\n\n Database db = Database.getInstance(context);\n db.updateSteps(Util.getToday(), db.getCurrentSteps());\n // current steps will be reset on boot @see BootReceiver\n db.close();\n }\n\n}\n"},"message":{"kind":"string","value":"fix: data on shutdown might have been added to the wrong date\n"},"old_file":{"kind":"string","value":"src/main/java/de/j4velin/pedometer/ShutdownRecevier.java"},"subject":{"kind":"string","value":"fix: data on shutdown might have been added to the wrong date"},"git_diff":{"kind":"string","value":"rc/main/java/de/j4velin/pedometer/ShutdownRecevier.java\n \n package de.j4velin.pedometer;\n \nimport de.j4velin.pedometer.util.Logger;\nimport de.j4velin.pedometer.util.Util;\n\n import android.content.BroadcastReceiver;\n import android.content.Context;\n import android.content.Intent;\n\nimport de.j4velin.pedometer.util.Logger;\nimport de.j4velin.pedometer.util.Util;\n \n public class ShutdownRecevier extends BroadcastReceiver {\n \n .putBoolean(\"correctShutdown\", true).commit();\n \n Database db = Database.getInstance(context);\n db.updateSteps(Util.getToday(), db.getCurrentSteps());\n // if it's already a new day, add the temp. steps to the last one\n if (db.getSteps(Util.getToday()) == Integer.MIN_VALUE) {\n int steps = db.getCurrentSteps();\n int pauseDifference = steps -\n context.getSharedPreferences(\"pedometer\", Context.MODE_MULTI_PROCESS)\n .getInt(\"pauseCount\", steps);\n db.insertNewDay(Util.getToday(), steps - pauseDifference);\n if (pauseDifference > 0) {\n // update pauseCount for the new day\n context.getSharedPreferences(\"pedometer\", Context.MODE_MULTI_PROCESS).edit()\n .putInt(\"pauseCount\", steps).commit();\n }\n } else {\n db.updateSteps(Util.getToday(), db.getCurrentSteps());\n }\n // current steps will be reset on boot @see BootReceiver\n db.close();\n }"}}},{"rowIdx":1945,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"cac71541fb43cb4758b52562aada8a5fa1228c2f"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"goshippo/shippo-java-client"},"new_contents":{"kind":"string","value":"package com.shippo.model;\n\nimport static org.junit.Assert.*;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.junit.Test;\n\nimport com.shippo.exception.APIConnectionException;\nimport com.shippo.exception.APIException;\nimport com.shippo.exception.AuthenticationException;\nimport com.shippo.exception.InvalidRequestException;\nimport com.shippo.exception.ShippoException;\n\npublic class AddressTest extends ShippoTest {\n\n @Test\n public void testValidCreate() {\n Address testObject = (Address) getDefaultObject();\n assertTrue(testObject.getIsComplete());\n }\n\n @Test(expected = InvalidRequestException.class)\n public void testInvalidCreate() throws AuthenticationException, InvalidRequestException, APIConnectionException,\n APIException {\n Address.create(getInvalidObjectMap());\n }\n\n @Test\n public void testRetrieve() throws AuthenticationException, InvalidRequestException, APIConnectionException,\n APIException {\n Address testObject = (Address) getDefaultObject();\n Address retrievedObject;\n\n retrievedObject = Address.retrieve((String) testObject.objectId);\n assertEquals(testObject.objectId, retrievedObject.objectId);\n\n }\n\n @Test(expected = InvalidRequestException.class)\n public void testInvalidRetrieve() throws AuthenticationException, InvalidRequestException, APIConnectionException,\n APIException {\n Address.retrieve(\"invalid_id\");\n }\n\n @Test\n public void testListAll() throws AuthenticationException, InvalidRequestException, APIConnectionException,\n APIException {\n AddressCollection objectCollection = Address.all(null);\n assertNotNull(objectCollection.getData());\n }\n\n @Test\n public void testListPageSize() throws AuthenticationException, InvalidRequestException, APIConnectionException,\n APIException {\n Map objectMap = new HashMap();\n objectMap.put(\"results\", \"1\"); // one result per page\n objectMap.put(\"page\", \"1\"); // the first page of results\n AddressCollection addressCollection = Address.all(objectMap);\n assertEquals(addressCollection.getData().size(), 1);\n }\n\n @Test\n public void testInvalidAddress() throws AuthenticationException, InvalidRequestException, APIConnectionException,\n APIException {\n Address testAddress = (Address) getInvalidAddress();\n assertFalse(testAddress.getValidationResults().getIsValid());\n assertTrue(testAddress.getValidationResults().getValidationMessages().size() > 0);\n assertNotNull(testAddress.getValidationResults().getValidationMessages().get(0).getSource());\n assertNotNull(testAddress.getValidationResults().getValidationMessages().get(0).getCode());\n assertNotNull(testAddress.getValidationResults().getValidationMessages().get(0).getText());\n }\n\n @Test\n public void testValidAddress() throws AuthenticationException, InvalidRequestException, APIConnectionException,\n APIException {\n Address testAddress = (Address) getDefaultObject();\n Address validatedAddress = Address.validate(testAddress.getObjectId());\n assertTrue(validatedAddress.getValidationResults().getIsValid());\n assertEquals(validatedAddress.getValidationResults().getValidationMessages().size(), 0);\n }\n\n public static Object getDefaultObject() {\n Map objectMap = new HashMap();\n objectMap.put(\"name\", \"Undefault New Wu\");\n objectMap.put(\"company\", \"Shippo\");\n objectMap.put(\"street1\", \"Clayton St.\");\n objectMap.put(\"street_no\", \"215\");\n objectMap.put(\"street2\", null);\n objectMap.put(\"city\", \"San Francisco\");\n objectMap.put(\"state\", \"CA\");\n objectMap.put(\"zip\", \"94117\");\n objectMap.put(\"country\", \"US\");\n objectMap.put(\"phone\", \"+1 555 341 9393\");\n objectMap.put(\"email\", \"test@goshipppo.com\");\n objectMap.put(\"is_residential\", false);\n objectMap.put(\"metadata\", \"Customer ID 123456\");\n\n try {\n Address testObject = Address.create(objectMap);\n return testObject;\n } catch (ShippoException e) {\n e.printStackTrace();\n }\n return null;\n }\n\n public static Object getSecondObject() {\n Map objectMap = new HashMap();\n objectMap.put(\"name\", \"Second New Wu\");\n objectMap.put(\"company\", \"Hippo\");\n objectMap.put(\"street1\", \"965 Mission St\");\n objectMap.put(\"street2\", null);\n objectMap.put(\"city\", \"San Francisco\");\n objectMap.put(\"state\", \"CA\");\n objectMap.put(\"zip\", \"94103\");\n objectMap.put(\"country\", \"US\");\n objectMap.put(\"phone\", \"+1 415 111 1111\");\n objectMap.put(\"email\", \"test@goshipppo.com\");\n objectMap.put(\"is_residential\", false);\n objectMap.put(\"metadata\", \"Customer ID 1234567\");\n\n try {\n Address testObject = Address.create(objectMap);\n return testObject;\n } catch (ShippoException e) {\n e.printStackTrace();\n }\n return null;\n }\n\n public static Object getInvalidAddress() {\n Map objectMap = new HashMap();\n objectMap.put(\"name\", \"Undefault New Wu\");\n objectMap.put(\"street1\", \"Clayton St.\");\n objectMap.put(\"street_no\", \"215215\");\n objectMap.put(\"street2\", null);\n objectMap.put(\"city\", \"San Francisco\");\n objectMap.put(\"state\", \"CA\");\n objectMap.put(\"zip\", \"94117\");\n objectMap.put(\"country\", \"US\");\n objectMap.put(\"phone\", \"+1 555 341 9393\");\n objectMap.put(\"email\", \"test@goshipppo.com\");\n objectMap.put(\"is_residential\", false);\n objectMap.put(\"metadata\", \"Customer ID 123456\");\n objectMap.put(\"validate\", true);\n\n try {\n Address testObject = Address.create(objectMap);\n return testObject;\n } catch (ShippoException e) {\n e.printStackTrace();\n }\n return null;\n }\n}\n"},"new_file":{"kind":"string","value":"src/test/java/com/shippo/model/AddressTest.java"},"old_contents":{"kind":"string","value":"package com.shippo.model;\n\nimport static org.junit.Assert.*;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.junit.Test;\n\nimport com.shippo.exception.APIConnectionException;\nimport com.shippo.exception.APIException;\nimport com.shippo.exception.AuthenticationException;\nimport com.shippo.exception.InvalidRequestException;\nimport com.shippo.exception.ShippoException;\n\npublic class AddressTest extends ShippoTest {\n\n @Test\n public void testValidCreate() {\n Address testObject = (Address) getDefaultObject();\n assertTrue(testObject.getIsComplete());\n }\n\n @Test(expected = InvalidRequestException.class)\n public void testInvalidCreate() throws AuthenticationException, InvalidRequestException, APIConnectionException,\n APIException {\n Address.create(getInvalidObjectMap());\n }\n\n @Test\n public void testRetrieve() throws AuthenticationException, InvalidRequestException, APIConnectionException,\n APIException {\n Address testObject = (Address) getDefaultObject();\n Address retrievedObject;\n\n retrievedObject = Address.retrieve((String) testObject.objectId);\n assertEquals(testObject.objectId, retrievedObject.objectId);\n\n }\n\n @Test(expected = InvalidRequestException.class)\n public void testInvalidRetrieve() throws AuthenticationException, InvalidRequestException, APIConnectionException,\n APIException {\n Address.retrieve(\"invalid_id\");\n }\n\n @Test\n public void testListAll() throws AuthenticationException, InvalidRequestException, APIConnectionException,\n APIException {\n AddressCollection objectCollection = Address.all(null);\n assertNotNull(objectCollection.getData());\n }\n\n @Test\n public void testListPageSize() throws AuthenticationException, InvalidRequestException, APIConnectionException,\n APIException {\n Map objectMap = new HashMap();\n objectMap.put(\"results\", \"1\"); // one result per page\n objectMap.put(\"page\", \"1\"); // the first page of results\n AddressCollection addressCollection = Address.all(objectMap);\n assertEquals(addressCollection.getData().size(), 1);\n }\n\n @Test\n public void testInvalidAddress() throws AuthenticationException, InvalidRequestException, APIConnectionException,\n APIException {\n Address testAddress = (Address) getInvalidAddress();\n assertFalse(testAddress.getValidationResults().getIsValid());\n assertTrue(testAddress.getValidationResults().getValidationMessages().size() > 0);\n assertNotNull(testAddress.getValidationResults().getValidationMessages().getSource());\n assertNotNull(testAddress.getValidationResults().getValidationMessages().getCode());\n assertNotNull(testAddress.getValidationResults().getValidationMessages().getText());\n }\n\n @Test\n public void testValidAddress() throws AuthenticationException, InvalidRequestException, APIConnectionException,\n APIException {\n Address testAddress = (Address) getDefaultObject();\n Address validatedAddress = Address.validate(testAddress.getObjectId());\n assertTrue(validatedAddress.getValidationResults().getIsValid());\n assertEquals(validatedAddress.getValidationResults().getValidationMessages().size(), 0);\n }\n\n public static Object getDefaultObject() {\n Map objectMap = new HashMap();\n objectMap.put(\"name\", \"Undefault New Wu\");\n objectMap.put(\"company\", \"Shippo\");\n objectMap.put(\"street1\", \"Clayton St.\");\n objectMap.put(\"street_no\", \"215\");\n objectMap.put(\"street2\", null);\n objectMap.put(\"city\", \"San Francisco\");\n objectMap.put(\"state\", \"CA\");\n objectMap.put(\"zip\", \"94117\");\n objectMap.put(\"country\", \"US\");\n objectMap.put(\"phone\", \"+1 555 341 9393\");\n objectMap.put(\"email\", \"test@goshipppo.com\");\n objectMap.put(\"is_residential\", false);\n objectMap.put(\"metadata\", \"Customer ID 123456\");\n\n try {\n Address testObject = Address.create(objectMap);\n return testObject;\n } catch (ShippoException e) {\n e.printStackTrace();\n }\n return null;\n }\n\n public static Object getSecondObject() {\n Map objectMap = new HashMap();\n objectMap.put(\"name\", \"Second New Wu\");\n objectMap.put(\"company\", \"Hippo\");\n objectMap.put(\"street1\", \"965 Mission St\");\n objectMap.put(\"street2\", null);\n objectMap.put(\"city\", \"San Francisco\");\n objectMap.put(\"state\", \"CA\");\n objectMap.put(\"zip\", \"94103\");\n objectMap.put(\"country\", \"US\");\n objectMap.put(\"phone\", \"+1 415 111 1111\");\n objectMap.put(\"email\", \"test@goshipppo.com\");\n objectMap.put(\"is_residential\", false);\n objectMap.put(\"metadata\", \"Customer ID 1234567\");\n\n try {\n Address testObject = Address.create(objectMap);\n return testObject;\n } catch (ShippoException e) {\n e.printStackTrace();\n }\n return null;\n }\n\n public static Object getInvalidAddress() {\n Map objectMap = new HashMap();\n objectMap.put(\"name\", \"Undefault New Wu\");\n objectMap.put(\"street1\", \"Clayton St.\");\n objectMap.put(\"street_no\", \"215215\");\n objectMap.put(\"street2\", null);\n objectMap.put(\"city\", \"San Francisco\");\n objectMap.put(\"state\", \"CA\");\n objectMap.put(\"zip\", \"94117\");\n objectMap.put(\"country\", \"US\");\n objectMap.put(\"phone\", \"+1 555 341 9393\");\n objectMap.put(\"email\", \"test@goshipppo.com\");\n objectMap.put(\"is_residential\", false);\n objectMap.put(\"metadata\", \"Customer ID 123456\");\n objectMap.put(\"validate\", true);\n\n try {\n Address testObject = Address.create(objectMap);\n return testObject;\n } catch (ShippoException e) {\n e.printStackTrace();\n }\n return null;\n }\n}\n"},"message":{"kind":"string","value":"Fix tests\n"},"old_file":{"kind":"string","value":"src/test/java/com/shippo/model/AddressTest.java"},"subject":{"kind":"string","value":"Fix tests"},"git_diff":{"kind":"string","value":"rc/test/java/com/shippo/model/AddressTest.java\n Address testAddress = (Address) getInvalidAddress();\n assertFalse(testAddress.getValidationResults().getIsValid());\n assertTrue(testAddress.getValidationResults().getValidationMessages().size() > 0);\n assertNotNull(testAddress.getValidationResults().getValidationMessages().getSource());\n assertNotNull(testAddress.getValidationResults().getValidationMessages().getCode());\n assertNotNull(testAddress.getValidationResults().getValidationMessages().getText());\n assertNotNull(testAddress.getValidationResults().getValidationMessages().get(0).getSource());\n assertNotNull(testAddress.getValidationResults().getValidationMessages().get(0).getCode());\n assertNotNull(testAddress.getValidationResults().getValidationMessages().get(0).getText());\n }\n \n @Test"}}},{"rowIdx":1946,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"10e956b98c11c75965fd12d78b395bb44844eb96"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"CaMnter/AndroidLife,CaMnter/AndroidLife,CaMnter/AndroidLife,CaMnter/AndroidLife,CaMnter/AndroidLife,CaMnter/AndroidLife,CaMnter/AndroidLife"},"new_contents":{"kind":"string","value":"package com.camnter.hook.loadedapk.classloader.hook.host.loadedapk;\n\nimport android.annotation.SuppressLint;\nimport android.content.Context;\nimport android.content.pm.ApplicationInfo;\nimport android.content.pm.PackageManager;\nimport android.os.Build;\nimport android.support.annotation.NonNull;\nimport android.util.DisplayMetrics;\nimport com.camnter.hook.loadedapk.classloader.hook.host.AssetsUtils;\nimport java.io.File;\nimport java.lang.ref.WeakReference;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * Hook ActivityThread # ArrayMap> mPackages\n * 添加插件 LoadedApk\n *\n * @author CaMnter\n */\n\n@SuppressWarnings(\"DanglingJavadoc\")\npublic final class LoadedApkHooker {\n\n /**\n * 缓存插件 LoadedApk\n * 因为 ActivityThread # ArrayMap> mPackages 是弱引用\n *\n * 所以,需要这个强引用去保存,防止回收\n */\n public static Map LOADEDAPK_MAP = new HashMap<>();\n\n\n /**\n * Hook ActivityThread # ArrayMap> mPackages\n *\n * @param apkFile apkFile\n * @param context context\n * @throws Exception Exception\n */\n @SuppressWarnings(\"unchecked\")\n public static void hookLoadedApkForActivityThread(@NonNull final File apkFile,\n @NonNull final Context context)\n throws Exception {\n\n /**\n * *****************************************************************************************\n *\n * ActivityThread 部分源码\n *\n * public final class ActivityThread {\n *\n * ...\n *\n * private static volatile ActivityThread sCurrentActivityThread;\n *\n * ...\n *\n * final ArrayMap> mPackages = new ArrayMap>();\n *\n * ...\n *\n * public final LoadedApk getPackageInfoNoCheck(ApplicationInfo ai, CompatibilityInfo compatInfo){\n *\n * return getPackageInfo(ai, compatInfo, null, false, true, false);\n *\n * }\n *\n * ...\n *\n * }\n *\n * *****************************************************************************************\n *\n * CompatibilityInfo 部分源码\n *\n * public class CompatibilityInfo implements Parcelable {\n *\n * ...\n *\n * public static final CompatibilityInfo DEFAULT_COMPATIBILITY_INFO = new CompatibilityInfo() {};\n *\n * ...\n *\n * }\n *\n * *****************************************************************************************\n *\n * public final class LoadedApk {\n *\n * ...\n *\n * private ClassLoader mClassLoader;\n *\n * ...\n *\n * }\n *\n */\n\n /**\n * 获取 ActivityThread 实例\n */\n final Class activityThreadClass = Class.forName(\"android.app.ActivityThread\");\n final Method currentActivityThreadMethod = activityThreadClass.getDeclaredMethod(\n \"currentActivityThread\");\n currentActivityThreadMethod.setAccessible(true);\n final Object currentActivityThread = currentActivityThreadMethod.invoke(null);\n\n /**\n * 获取 ActivityThread # ArrayMap> mPackages\n */\n final Field mPackagesField = activityThreadClass.getDeclaredField(\"mPackages\");\n mPackagesField.setAccessible(true);\n final Map mPackages = (Map) mPackagesField.get(currentActivityThread);\n\n /**\n * 获取 CompatibilityInfo # CompatibilityInfo DEFAULT_COMPATIBILITY_INFO\n */\n final Class compatibilityInfoClass = Class.forName(\n \"android.content.res.CompatibilityInfo\");\n final Field defaultCompatibilityInfoField = compatibilityInfoClass.getDeclaredField(\n \"DEFAULT_COMPATIBILITY_INFO\");\n defaultCompatibilityInfoField.setAccessible(true);\n final Object defaultCompatibilityInfo = defaultCompatibilityInfoField.get(null);\n\n /**\n * 获取 ApplicationInfo\n */\n final ApplicationInfo applicationInfo = getApplicationInfo(apkFile, context);\n\n /**\n * 调用 ActivityThread # getPackageInfoNoCheck\n * 获取插件 LoadedApk\n */\n final Method getPackageInfoNoCheckMethod = activityThreadClass.getDeclaredMethod(\n \"getPackageInfoNoCheck\", ApplicationInfo.class, compatibilityInfoClass);\n final Object loadedApk = getPackageInfoNoCheckMethod.invoke(currentActivityThread,\n applicationInfo, defaultCompatibilityInfo);\n\n /**\n * 创建一个 Classloader\n */\n final String odexPath = AssetsUtils.getPluginOptDexDir(context, applicationInfo.packageName)\n .getPath();\n final String libDir = AssetsUtils.getPluginLibDir(context, applicationInfo.packageName)\n .getPath();\n final ClassLoader classLoader = new SmartClassloader(\n apkFile.getPath(),\n odexPath,\n libDir,\n ClassLoader.getSystemClassLoader()\n );\n\n /**\n * Hook LoadedApk # ClassLoader mClassLoader\n */\n final Field mClassLoaderField = loadedApk.getClass().getDeclaredField(\"mClassLoader\");\n mClassLoaderField.setAccessible(true);\n mClassLoaderField.set(loadedApk, classLoader);\n\n /**\n * 强引用缓存一份 插件 LoadedApk\n */\n LOADEDAPK_MAP.put(applicationInfo.packageName, loadedApk);\n\n /**\n * Hook ActivityThread # ArrayMap> mPackages\n */\n final WeakReference weakReference = new WeakReference<>(loadedApk);\n mPackages.put(applicationInfo.packageName, weakReference);\n }\n\n\n /**\n * 解析 Apk 文件中的 application\n * 并缓存\n *\n * 主要 调用 PackageParser 类的 generateApplicationInfo 方法\n *\n * @param apkFile apkFile\n * @throws Exception exception\n */\n @SuppressLint(\"PrivateApi\")\n public static ApplicationInfo getApplicationInfo(@NonNull final File apkFile,\n @NonNull final Context context)\n throws Exception {\n\n final ApplicationInfo applicationInfo;\n\n /**\n * 反射 获取 PackageParser # parsePackage(File packageFile, int flags)\n */\n final Class packageParserClass = Class.forName(\"android.content.pm.PackageParser\");\n\n /**\n * <= 4.0.0\n *\n * Don't deal with\n *\n * >= 4.0.0\n *\n * parsePackage(File sourceFile, String destCodePath, DisplayMetrics metrics, int flags)\n *\n * ---\n *\n * >= 5.0.0\n *\n * parsePackage(File packageFile, int flags)\n *\n */\n final int sdkVersion = Build.VERSION.SDK_INT;\n if (sdkVersion < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {\n throw new RuntimeException(\n \"[ApkUtils] the sdk version must >= 14 (4.0.0)\");\n }\n\n final Object packageParser;\n final Object packageObject;\n final Method parsePackageMethod;\n\n if (sdkVersion >= Build.VERSION_CODES.LOLLIPOP) {\n // >= 5.0.0\n // parsePackage(File packageFile, int flags)\n /**\n * 反射创建 PackageParser 对象,无参数构造\n *\n * 反射 调用 PackageParser # parsePackage(File packageFile, int flags)\n * 获取 apk 文件对应的 Package 对象\n */\n packageParser = packageParserClass.newInstance();\n\n parsePackageMethod = packageParserClass.getDeclaredMethod(\"parsePackage\",\n File.class, int.class);\n packageObject = parsePackageMethod.invoke(\n packageParser,\n apkFile,\n PackageManager.GET_SERVICES\n );\n } else {\n // >= 4.0.0\n // parsePackage(File sourceFile, String destCodePath, DisplayMetrics metrics, int flags)\n /**\n * 反射创建 PackageParser 对象,PackageParser(String archiveSourcePath)\n *\n * 反射 调用 PackageParser # parsePackage(File sourceFile, String destCodePath, DisplayMetrics metrics, int flags)\n * 获取 apk 文件对应的 Package 对象\n */\n final String apkFileAbsolutePath = apkFile.getAbsolutePath();\n packageParser = packageParserClass.getConstructor(String.class)\n .newInstance(apkFileAbsolutePath);\n\n parsePackageMethod = packageParserClass.getDeclaredMethod(\"parsePackage\",\n File.class, String.class, DisplayMetrics.class, int.class);\n packageObject = parsePackageMethod.invoke(\n packageParser,\n apkFile,\n apkFile.getAbsolutePath(),\n context.getResources().getDisplayMetrics(),\n PackageManager.GET_SERVICES\n );\n }\n\n final Class packageParser$Package = Class.forName(\n \"android.content.pm.PackageParser$Package\");\n\n if (sdkVersion >= Build.VERSION_CODES.JELLY_BEAN_MR1) {\n // >= 4.2.0\n // generateApplicationInfo(Package p, int flags, PackageUserState state)\n\n /**\n * 反射创建 PackageUserState 对象\n */\n final Class packageUserStateClass = Class.forName(\n \"android.content.pm.PackageUserState\");\n final Object defaultUserState = packageUserStateClass.newInstance();\n\n // 需要调用 android.content.pm.PackageParser#generateApplicationInfo(Package p, int flags, PackageUserState state)\n final Method generateApplicationInfo = packageParserClass.getDeclaredMethod(\n \"generateApplicationInfo\",\n packageParser$Package, int.class, packageUserStateClass);\n\n applicationInfo = (ApplicationInfo) generateApplicationInfo.invoke(\n packageParser,\n packageObject,\n 0 /*解析全部信息*/,\n defaultUserState\n );\n\n } else if (sdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {\n // >= 4.1.0\n // generateApplicationInfo(Package p, int flags, boolean stopped, int enabledState, int userId)\n\n // 需要调用 android.content.pm.PackageParser#generateApplicationInfo(Package p, int flags, boolean stopped, int enabledState, int userId)\n final Class userHandler = Class.forName(\"android.os.UserId\");\n final Method getCallingUserIdMethod = userHandler.getDeclaredMethod(\"getCallingUserId\");\n final int userId = (Integer) getCallingUserIdMethod.invoke(null);\n Method generateApplicationInfo = packageParserClass.getDeclaredMethod(\n \"generateApplicationInfo\",\n packageParser$Package, int.class, boolean.class, int.class);\n\n /**\n * 反射调用 PackageParser # generateApplicationInfo(Package p, int flags, boolean stopped, int enabledState, int userId)\n *\n * 在之前版本的 4.0.0 中 存在着\n * public class PackageParser {\n * public final static class Package {\n * // User set enabled state.\n * public int mSetEnabled = PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;\n *\n * // Whether the package has been stopped.\n * public boolean mSetStopped = false;\n * }\n * }\n *\n * 然后保存\n */\n applicationInfo = (ApplicationInfo) generateApplicationInfo.invoke(\n packageParser,\n packageObject,\n 0 /*解析全部信息*/,\n false,\n PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,\n userId\n );\n } else if (sdkVersion >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {\n // >= 4.0.0\n // generateApplicationInfo(Package p, int flags)\n\n // 需要调用 android.content.pm.PackageParser#generateApplicationInfo(Package p, int flags)\n Method generateApplicationInfo = packageParserClass.getDeclaredMethod(\n \"generateApplicationInfo\",\n packageParser$Package, int.class);\n\n /**\n * 反射调用 PackageParser # generateApplicationInfo(Package p, int flags)\n *\n * 然后保存\n */\n applicationInfo = (ApplicationInfo) generateApplicationInfo.invoke(\n packageParser,\n packageObject,\n 0 /*解析全部信息*/\n );\n } else {\n applicationInfo = null;\n }\n\n return applicationInfo;\n\n }\n\n}\n"},"new_file":{"kind":"string","value":"hook-loadedapk-classloader-host/src/main/java/com/camnter/hook/loadedapk/classloader/hook/host/loadedapk/LoadedApkHooker.java"},"old_contents":{"kind":"string","value":"package com.camnter.hook.loadedapk.classloader.hook.host.loadedapk;\n\nimport android.annotation.SuppressLint;\nimport android.content.Context;\nimport android.content.pm.ApplicationInfo;\nimport android.content.pm.PackageManager;\nimport android.os.Build;\nimport android.support.annotation.NonNull;\nimport android.util.DisplayMetrics;\nimport com.camnter.hook.loadedapk.classloader.hook.host.AssetsUtils;\nimport java.io.File;\nimport java.lang.ref.WeakReference;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * Hook ActivityThread # ArrayMap> mPackages\n * 添加插件 LoadedApk\n *\n * @author CaMnter\n */\n\n@SuppressWarnings(\"DanglingJavadoc\")\npublic final class LoadedApkHooker {\n\n /**\n * 缓存插件 LoadedApk\n * 因为 ActivityThread # ArrayMap> mPackages 是弱引用\n *\n * 所以,需要这个强引用去保存,防止回收\n */\n public static Map LOADEDAPK_MAP = new HashMap<>();\n\n\n @SuppressWarnings(\"unchecked\")\n public static void hookLoadedApkForActivityThread(@NonNull final File apkFile,\n @NonNull final Context context)\n throws Exception {\n\n /**\n * 获取 ActivityThread 实例\n */\n final Class activityThreadClass = Class.forName(\"android.app.ActivityThread\");\n final Method currentActivityThreadMethod = activityThreadClass.getDeclaredMethod(\n \"currentActivityThread\");\n currentActivityThreadMethod.setAccessible(true);\n final Object currentActivityThread = currentActivityThreadMethod.invoke(null);\n\n /**\n * 获取 ActivityThread # ArrayMap> mPackages\n */\n final Field mPackagesField = activityThreadClass.getDeclaredField(\"mPackages\");\n mPackagesField.setAccessible(true);\n final Map mPackages = (Map) mPackagesField.get(currentActivityThread);\n\n /**\n * 获取 CompatibilityInfo # CompatibilityInfo DEFAULT_COMPATIBILITY_INFO\n */\n final Class compatibilityInfoClass = Class.forName(\n \"android.content.res.CompatibilityInfo\");\n final Field defaultCompatibilityInfoField = compatibilityInfoClass.getDeclaredField(\n \"DEFAULT_COMPATIBILITY_INFO\");\n defaultCompatibilityInfoField.setAccessible(true);\n final Object defaultCompatibilityInfo = defaultCompatibilityInfoField.get(null);\n\n /**\n * 获取 ApplicationInfo\n */\n final ApplicationInfo applicationInfo = getApplicationInfo(apkFile, context);\n\n /**\n * 调用 ActivityThread # getPackageInfoNoCheck\n * 获取插件 LoadedApk\n */\n final Method getPackageInfoNoCheckMethod = activityThreadClass.getDeclaredMethod(\n \"getPackageInfoNoCheck\", ApplicationInfo.class, compatibilityInfoClass);\n final Object loadedApk = getPackageInfoNoCheckMethod.invoke(currentActivityThread,\n applicationInfo, defaultCompatibilityInfo);\n\n /**\n * 创建一个 Classloader\n */\n final String odexPath = AssetsUtils.getPluginOptDexDir(context, applicationInfo.packageName)\n .getPath();\n final String libDir = AssetsUtils.getPluginLibDir(context, applicationInfo.packageName)\n .getPath();\n final ClassLoader classLoader = new SmartClassloader(\n apkFile.getPath(),\n odexPath,\n libDir,\n ClassLoader.getSystemClassLoader()\n );\n\n /**\n * Hook LoadedApk # ClassLoader mClassLoader\n */\n final Field mClassLoaderField = loadedApk.getClass().getDeclaredField(\"mClassLoader\");\n mClassLoaderField.setAccessible(true);\n mClassLoaderField.set(loadedApk, classLoader);\n\n /**\n * 强引用缓存一份 插件 LoadedApk\n */\n LOADEDAPK_MAP.put(applicationInfo.packageName,loadedApk);\n\n /**\n * Hook ActivityThread # ArrayMap> mPackages\n */\n final WeakReference weakReference = new WeakReference<>(loadedApk);\n mPackages.put(applicationInfo.packageName,weakReference);\n }\n\n\n /**\n * 解析 Apk 文件中的 application\n * 并缓存\n *\n * 主要 调用 PackageParser 类的 generateApplicationInfo 方法\n *\n * @param apkFile apkFile\n * @throws Exception exception\n */\n @SuppressLint(\"PrivateApi\")\n public static ApplicationInfo getApplicationInfo(@NonNull final File apkFile,\n @NonNull final Context context)\n throws Exception {\n\n final ApplicationInfo applicationInfo;\n\n /**\n * 反射 获取 PackageParser # parsePackage(File packageFile, int flags)\n */\n final Class packageParserClass = Class.forName(\"android.content.pm.PackageParser\");\n\n /**\n * <= 4.0.0\n *\n * Don't deal with\n *\n * >= 4.0.0\n *\n * parsePackage(File sourceFile, String destCodePath, DisplayMetrics metrics, int flags)\n *\n * ---\n *\n * >= 5.0.0\n *\n * parsePackage(File packageFile, int flags)\n *\n */\n final int sdkVersion = Build.VERSION.SDK_INT;\n if (sdkVersion < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {\n throw new RuntimeException(\n \"[ApkUtils] the sdk version must >= 14 (4.0.0)\");\n }\n\n final Object packageParser;\n final Object packageObject;\n final Method parsePackageMethod;\n\n if (sdkVersion >= Build.VERSION_CODES.LOLLIPOP) {\n // >= 5.0.0\n // parsePackage(File packageFile, int flags)\n /**\n * 反射创建 PackageParser 对象,无参数构造\n *\n * 反射 调用 PackageParser # parsePackage(File packageFile, int flags)\n * 获取 apk 文件对应的 Package 对象\n */\n packageParser = packageParserClass.newInstance();\n\n parsePackageMethod = packageParserClass.getDeclaredMethod(\"parsePackage\",\n File.class, int.class);\n packageObject = parsePackageMethod.invoke(\n packageParser,\n apkFile,\n PackageManager.GET_SERVICES\n );\n } else {\n // >= 4.0.0\n // parsePackage(File sourceFile, String destCodePath, DisplayMetrics metrics, int flags)\n /**\n * 反射创建 PackageParser 对象,PackageParser(String archiveSourcePath)\n *\n * 反射 调用 PackageParser # parsePackage(File sourceFile, String destCodePath, DisplayMetrics metrics, int flags)\n * 获取 apk 文件对应的 Package 对象\n */\n final String apkFileAbsolutePath = apkFile.getAbsolutePath();\n packageParser = packageParserClass.getConstructor(String.class)\n .newInstance(apkFileAbsolutePath);\n\n parsePackageMethod = packageParserClass.getDeclaredMethod(\"parsePackage\",\n File.class, String.class, DisplayMetrics.class, int.class);\n packageObject = parsePackageMethod.invoke(\n packageParser,\n apkFile,\n apkFile.getAbsolutePath(),\n context.getResources().getDisplayMetrics(),\n PackageManager.GET_SERVICES\n );\n }\n\n final Class packageParser$Package = Class.forName(\n \"android.content.pm.PackageParser$Package\");\n\n if (sdkVersion >= Build.VERSION_CODES.JELLY_BEAN_MR1) {\n // >= 4.2.0\n // generateApplicationInfo(Package p, int flags, PackageUserState state)\n\n /**\n * 反射创建 PackageUserState 对象\n */\n final Class packageUserStateClass = Class.forName(\n \"android.content.pm.PackageUserState\");\n final Object defaultUserState = packageUserStateClass.newInstance();\n\n // 需要调用 android.content.pm.PackageParser#generateApplicationInfo(Package p, int flags, PackageUserState state)\n final Method generateApplicationInfo = packageParserClass.getDeclaredMethod(\n \"generateApplicationInfo\",\n packageParser$Package, int.class, packageUserStateClass);\n\n applicationInfo = (ApplicationInfo) generateApplicationInfo.invoke(\n packageParser,\n packageObject,\n 0 /*解析全部信息*/,\n defaultUserState\n );\n\n } else if (sdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {\n // >= 4.1.0\n // generateApplicationInfo(Package p, int flags, boolean stopped, int enabledState, int userId)\n\n // 需要调用 android.content.pm.PackageParser#generateApplicationInfo(Package p, int flags, boolean stopped, int enabledState, int userId)\n final Class userHandler = Class.forName(\"android.os.UserId\");\n final Method getCallingUserIdMethod = userHandler.getDeclaredMethod(\"getCallingUserId\");\n final int userId = (Integer) getCallingUserIdMethod.invoke(null);\n Method generateApplicationInfo = packageParserClass.getDeclaredMethod(\n \"generateApplicationInfo\",\n packageParser$Package, int.class, boolean.class, int.class);\n\n /**\n * 反射调用 PackageParser # generateApplicationInfo(Package p, int flags, boolean stopped, int enabledState, int userId)\n *\n * 在之前版本的 4.0.0 中 存在着\n * public class PackageParser {\n * public final static class Package {\n * // User set enabled state.\n * public int mSetEnabled = PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;\n *\n * // Whether the package has been stopped.\n * public boolean mSetStopped = false;\n * }\n * }\n *\n * 然后保存\n */\n applicationInfo = (ApplicationInfo) generateApplicationInfo.invoke(\n packageParser,\n packageObject,\n 0 /*解析全部信息*/,\n false,\n PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,\n userId\n );\n } else if (sdkVersion >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {\n // >= 4.0.0\n // generateApplicationInfo(Package p, int flags)\n\n // 需要调用 android.content.pm.PackageParser#generateApplicationInfo(Package p, int flags)\n Method generateApplicationInfo = packageParserClass.getDeclaredMethod(\n \"generateApplicationInfo\",\n packageParser$Package, int.class);\n\n /**\n * 反射调用 PackageParser # generateApplicationInfo(Package p, int flags)\n *\n * 然后保存\n */\n applicationInfo = (ApplicationInfo) generateApplicationInfo.invoke(\n packageParser,\n packageObject,\n 0 /*解析全部信息*/\n );\n } else {\n applicationInfo = null;\n }\n\n return applicationInfo;\n\n }\n\n}\n"},"message":{"kind":"string","value":"[Add] comments of LoadedApkHooker in hook-loadedapk-classloader-host module\n"},"old_file":{"kind":"string","value":"hook-loadedapk-classloader-host/src/main/java/com/camnter/hook/loadedapk/classloader/hook/host/loadedapk/LoadedApkHooker.java"},"subject":{"kind":"string","value":"[Add] comments of LoadedApkHooker in hook-loadedapk-classloader-host module"},"git_diff":{"kind":"string","value":"ook-loadedapk-classloader-host/src/main/java/com/camnter/hook/loadedapk/classloader/hook/host/loadedapk/LoadedApkHooker.java\n public static Map LOADEDAPK_MAP = new HashMap<>();\n \n \n /**\n * Hook ActivityThread # ArrayMap> mPackages\n *\n * @param apkFile apkFile\n * @param context context\n * @throws Exception Exception\n */\n @SuppressWarnings(\"unchecked\")\n public static void hookLoadedApkForActivityThread(@NonNull final File apkFile,\n @NonNull final Context context)\n throws Exception {\n\n /**\n * *****************************************************************************************\n *\n * ActivityThread 部分源码\n *\n * public final class ActivityThread {\n *\n * ...\n *\n * private static volatile ActivityThread sCurrentActivityThread;\n *\n * ...\n *\n * final ArrayMap> mPackages = new ArrayMap>();\n *\n * ...\n *\n * public final LoadedApk getPackageInfoNoCheck(ApplicationInfo ai, CompatibilityInfo compatInfo){\n *\n * return getPackageInfo(ai, compatInfo, null, false, true, false);\n *\n * }\n *\n * ...\n *\n * }\n *\n * *****************************************************************************************\n *\n * CompatibilityInfo 部分源码\n *\n * public class CompatibilityInfo implements Parcelable {\n *\n * ...\n *\n * public static final CompatibilityInfo DEFAULT_COMPATIBILITY_INFO = new CompatibilityInfo() {};\n *\n * ...\n *\n * }\n *\n * *****************************************************************************************\n *\n * public final class LoadedApk {\n *\n * ...\n *\n * private ClassLoader mClassLoader;\n *\n * ...\n *\n * }\n *\n */\n \n /**\n * 获取 ActivityThread 实例\n /**\n * 强引用缓存一份 插件 LoadedApk\n */\n LOADEDAPK_MAP.put(applicationInfo.packageName,loadedApk);\n LOADEDAPK_MAP.put(applicationInfo.packageName, loadedApk);\n \n /**\n * Hook ActivityThread # ArrayMap> mPackages\n */\n final WeakReference weakReference = new WeakReference<>(loadedApk);\n mPackages.put(applicationInfo.packageName,weakReference);\n mPackages.put(applicationInfo.packageName, weakReference);\n }\n \n "}}},{"rowIdx":1947,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"79602f0676d0fe40ce34c99cf287dbc5d3f268cd"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"progolden/dne-utils"},"new_contents":{"kind":"string","value":"/*\n Copyright 2014 ProGolden Soluções Tecnológicas\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 br.com.progolden.dneutils.utils;\n\nimport javax.annotation.PreDestroy;\n\nimport org.hibernate.SessionFactory;\nimport org.hibernate.cfg.Configuration;\nimport org.hibernate.service.ServiceRegistryBuilder;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\npublic class DNEHibernateSessionFactory {\n\n\tprivate static final Logger LOG = LoggerFactory.getLogger(DNEHibernateSessionFactory.class);\n\t\n\tprivate SessionFactory customFactory;\n\t\n\tpublic DNEHibernateSessionFactory(String configFile) {\n\t\tif ((configFile == null) || (configFile.equals(\"\"))) {\n\t\t\tLOG.info(\"Inicializando a DNE sem conexão com o banco de dados.\");\n\t\t\tthis.customFactory = null;\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tLOG.debug(\"Carregando DNE no Hibernate pelo arquivo: \"+configFile);\n\t\t\t\tConfiguration config = new Configuration();\n\t\t\t\tconfig\n\t\t\t\t\t.configure(\"dne.hibernate.mappings.xml\")\n\t\t\t\t\t.configure(configFile)\n\t\t\t\t\t;\n\t\t\t\tServiceRegistryBuilder serviceRegistryBuilder = new ServiceRegistryBuilder()\n\t\t\t\t\t.applySettings(config.getProperties());\n\t\t\t\tthis.customFactory = config.buildSessionFactory(serviceRegistryBuilder.buildServiceRegistry());\n\t\t\t} catch (Exception ex) {\n\t\t\t\tLOG.error(\"Um erro ocorreu ao tentar estabelecer a conexão com a DNE pelo arquivo: \"\n\t\t\t\t\t+configFile,ex);\n\t\t\t\tLOG.info(\"Inicializando a DNE sem conexão com o banco de dados devido à erros.\");\n\t\t\t\tthis.customFactory = null;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic SessionFactory getFactory() {\n\t\treturn this.customFactory;\n\t}\n\t\n\t@PreDestroy\n\tpublic void closeFactory() {\n\t\tif (this.customFactory != null) {\n\t\t\tthis.customFactory.close();\n\t\t\tthis.customFactory = null;\n\t\t}\n\t}\n\n}\n"},"new_file":{"kind":"string","value":"src/main/java/br/com/progolden/dneutils/utils/DNEHibernateSessionFactory.java"},"old_contents":{"kind":"string","value":"/*\n Copyright 2014 ProGolden Soluções Tecnológicas\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 br.com.progolden.dneutils.utils;\n\nimport javax.annotation.PreDestroy;\n\nimport org.hibernate.SessionFactory;\nimport org.hibernate.cfg.Configuration;\nimport org.hibernate.service.ServiceRegistryBuilder;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\npublic class DNEHibernateSessionFactory {\n\n\tprivate static final Logger LOG = LoggerFactory.getLogger(DNEHibernateSessionFactory.class);\n\t\n\tprivate SessionFactory customFactory;\n\t\n\tpublic DNEHibernateSessionFactory(String configFile) {\n\t\tif ((configFile == null) || (configFile.equals(\"\"))) {\n\t\t\tLOG.info(\"Inicializando a DNE sem conexão com o banco de dados.\");\n\t\t\tthis.customFactory = null;\n\t\t} else {\n\t\t\tLOG.debug(\"Carregando Hibernate pelo arquivo: \"+configFile);\n\t\t\tConfiguration config = new Configuration();\n\t\t\tconfig\n\t\t\t\t.configure(\"dne.hibernate.mappings.xml\")\n\t\t\t\t.configure(configFile)\n\t\t\t;\n\t\t\tServiceRegistryBuilder serviceRegistryBuilder = new ServiceRegistryBuilder()\n\t\t\t\t.applySettings(config.getProperties());\n\t\t\tthis.customFactory = config.buildSessionFactory(serviceRegistryBuilder.buildServiceRegistry());\n\t\t}\n\t}\n\t\n\tpublic SessionFactory getFactory() {\n\t\treturn this.customFactory;\n\t}\n\t\n\t@PreDestroy\n\tpublic void closeFactory() {\n\t\tif (this.customFactory != null) {\n\t\t\tthis.customFactory.close();\n\t\t\tthis.customFactory = null;\n\t\t}\n\t}\n\n}\n"},"message":{"kind":"string","value":"Tornando a inicialização \"failsafe\" em relação à conexão com BD. Closes\n#1"},"old_file":{"kind":"string","value":"src/main/java/br/com/progolden/dneutils/utils/DNEHibernateSessionFactory.java"},"subject":{"kind":"string","value":"Tornando a inicialização \"failsafe\" em relação à conexão com BD. Closes #1"},"git_diff":{"kind":"string","value":"rc/main/java/br/com/progolden/dneutils/utils/DNEHibernateSessionFactory.java\n \t\t\tLOG.info(\"Inicializando a DNE sem conexão com o banco de dados.\");\n \t\t\tthis.customFactory = null;\n \t\t} else {\n\t\t\tLOG.debug(\"Carregando Hibernate pelo arquivo: \"+configFile);\n\t\t\tConfiguration config = new Configuration();\n\t\t\tconfig\n\t\t\t\t.configure(\"dne.hibernate.mappings.xml\")\n\t\t\t\t.configure(configFile)\n\t\t\t;\n\t\t\tServiceRegistryBuilder serviceRegistryBuilder = new ServiceRegistryBuilder()\n\t\t\t\t.applySettings(config.getProperties());\n\t\t\tthis.customFactory = config.buildSessionFactory(serviceRegistryBuilder.buildServiceRegistry());\n\t\t\ttry {\n\t\t\t\tLOG.debug(\"Carregando DNE no Hibernate pelo arquivo: \"+configFile);\n\t\t\t\tConfiguration config = new Configuration();\n\t\t\t\tconfig\n\t\t\t\t\t.configure(\"dne.hibernate.mappings.xml\")\n\t\t\t\t\t.configure(configFile)\n\t\t\t\t\t;\n\t\t\t\tServiceRegistryBuilder serviceRegistryBuilder = new ServiceRegistryBuilder()\n\t\t\t\t\t.applySettings(config.getProperties());\n\t\t\t\tthis.customFactory = config.buildSessionFactory(serviceRegistryBuilder.buildServiceRegistry());\n\t\t\t} catch (Exception ex) {\n\t\t\t\tLOG.error(\"Um erro ocorreu ao tentar estabelecer a conexão com a DNE pelo arquivo: \"\n\t\t\t\t\t+configFile,ex);\n\t\t\t\tLOG.info(\"Inicializando a DNE sem conexão com o banco de dados devido à erros.\");\n\t\t\t\tthis.customFactory = null;\n\t\t\t}\n \t\t}\n \t}\n \t"}}},{"rowIdx":1948,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"64da40bfc30053f172969498c3dce16343c0c45f"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"sahan/ZombieLink"},"new_contents":{"kind":"string","value":"package com.lonepulse.zombielink.core;\n\n/*\n * #%L\n * ZombieLink\n * %%\n * Copyright (C) 2013 Lonepulse\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 * #L%\n */\n\nimport java.io.IOException;\n\nimport org.apache.http.HttpResponse;\nimport org.apache.http.client.ClientProtocolException;\nimport org.apache.http.client.HttpClient;\nimport org.apache.http.client.methods.HttpRequestBase;\nimport org.apache.http.conn.scheme.PlainSocketFactory;\nimport org.apache.http.conn.scheme.Scheme;\nimport org.apache.http.conn.scheme.SchemeRegistry;\nimport org.apache.http.conn.ssl.SSLSocketFactory;\nimport org.apache.http.impl.client.DefaultHttpClient;\nimport org.apache.http.impl.conn.PoolingClientConnectionManager;\nimport org.apache.http.protocol.HttpContext;\n\n/**\n *

A concrete implementation of {@link HttpClient} which provides network \n * interfacing over a thread-safe, asynchronous HTTP client.

\n * \n * @version 2.2.0\n *

\n * @author Lahiru Sahan Jayasinghe\n */\npublic enum MultiThreadedHttpClient implements HttpClientContract {\n\n\t\n\t/**\n\t *

Offers an {@link HttpClient} instantiated with a thread-safe \n\t * {@link PoolingClientConnectionManager}.\n\t * \n\t * @since 2.1.0\n\t */\n\tINSTANCE;\n\t\n\t\n\t/**\n\t *

The multi-threaded implementation of {@link HttpClient} which is used to \n\t * execute requests in parallel.

\n\t *

\n\t * @since 1.1.1\n\t */\n\tprivate final transient HttpClient httpClient;\n\t\n\t\n\t/**\n\t *

Default constructor overridden to provide an implementation of \n\t * {@link HttpClient} which can handle multi-threaded request execution.

\n\t * \n\t *

This implementation uses a {@link PoolingClientConnectionManager} with a \n\t * {@link SchemeRegistry} which has default port registrations of HTTP \n\t * and HTTPS.

\n\t *

\n\t * @since 1.1.1\n\t */\n\tprivate MultiThreadedHttpClient() {\n\t\t\n\t\tSchemeRegistry schemeRegistry = new SchemeRegistry();\n\t\tschemeRegistry.register(new Scheme(\"http\", 80, PlainSocketFactory.getSocketFactory()));\n\t\tschemeRegistry.register(new Scheme(\"https\", 443, SSLSocketFactory.getSocketFactory()));\n\t\t\n\t\tPoolingClientConnectionManager pccm = new PoolingClientConnectionManager(schemeRegistry);\n\t\tpccm.setMaxTotal(256); //Max. number of client connections pooled\n\t\tpccm.setDefaultMaxPerRoute(24); //Max connections per route\n\t\t\n\t\tthis.httpClient = new DefaultHttpClient(pccm);\n\t\t\n\t\tRuntime.getRuntime().addShutdownHook(new Thread(new Runnable() {\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void run() { //HttpClient considered to be \"out of scope\" only on VM exit\n\t\t\t\n\t\t\t\thttpClient.getConnectionManager().shutdown(); \n\t\t\t}\n\t\t}));\n\t}\n\n\t/**\n\t * {@inheritDoc} \n\t */\n\t@Override\n\tpublic HttpResponse executeRequest(T httpRequestBase) \n\tthrows ClientProtocolException, IOException {\n\n\t\treturn this.httpClient.execute(httpRequestBase);\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t */\n\t@Override\n\tpublic HttpResponse executeRequest(T httpRequestBase, HttpContext httpContext)\n\tthrows ClientProtocolException, IOException {\n\t\n\t\treturn this.httpClient.execute(httpRequestBase, httpContext);\n\t}\n}\n"},"new_file":{"kind":"string","value":"src/main/java/com/lonepulse/zombielink/core/MultiThreadedHttpClient.java"},"old_contents":{"kind":"string","value":"package com.lonepulse.zombielink.core;\n\n/*\n * #%L\n * ZombieLink\n * %%\n * Copyright (C) 2013 Lonepulse\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 * #L%\n */\n\nimport java.io.IOException;\n\nimport org.apache.http.HttpResponse;\nimport org.apache.http.client.ClientProtocolException;\nimport org.apache.http.client.HttpClient;\nimport org.apache.http.client.methods.HttpRequestBase;\nimport org.apache.http.conn.scheme.PlainSocketFactory;\nimport org.apache.http.conn.scheme.Scheme;\nimport org.apache.http.conn.scheme.SchemeRegistry;\nimport org.apache.http.conn.ssl.SSLSocketFactory;\nimport org.apache.http.impl.client.DefaultHttpClient;\nimport org.apache.http.impl.conn.PoolingClientConnectionManager;\nimport org.apache.http.protocol.HttpContext;\n\n/**\n *

A concrete implementation of {@link HttpClient} which provides network \n * interfacing over a thread-safe, asynchronous HTTP client.

\n * \n * @version 2.2.0\n *

\n * @author Lahiru Sahan Jayasinghe\n */\npublic enum MultiThreadedHttpClient implements HttpClientContract {\n\n\t\n\t/**\n\t *

Offers an {@link HttpClient} instantiated with a thread-safe \n\t * {@link PoolingClientConnectionManager}.\n\t * \n\t * @since 2.1.0\n\t */\n\tINSTANCE;\n\t\n\t\n\t/**\n\t *

The multi-threaded implementation of {@link HttpClient} which is used to \n\t * execute requests in parallel.

\n\t *

\n\t * @since 1.1.1\n\t */\n\tprivate transient HttpClient httpClient;\n\t\n\t\n\t/**\n\t *

Default constructor overridden to provide an implementation of \n\t * {@link HttpClient} which can handle multi-threaded request execution.

\n\t * \n\t *

This implementation uses a {@link PoolingClientConnectionManager} with a \n\t * {@link SchemeRegistry} which has default port registrations of HTTP \n\t * and HTTPS.

\n\t *

\n\t * @since 1.1.1\n\t */\n\tprivate MultiThreadedHttpClient() {\n\t\t\n\t\tSchemeRegistry schemeRegistry = new SchemeRegistry();\n\t\tschemeRegistry.register(new Scheme(\"http\", 80, PlainSocketFactory.getSocketFactory()));\n\t\tschemeRegistry.register(new Scheme(\"https\", 443, SSLSocketFactory.getSocketFactory()));\n\t\t\n\t\tPoolingClientConnectionManager pccm = new PoolingClientConnectionManager(schemeRegistry);\n\t\tpccm.setMaxTotal(128); //Max. number of client connections pooled\n\t\t\n\t\tthis.httpClient = new DefaultHttpClient(pccm);\n\t}\n\n\t/**\n\t * {@inheritDoc} \n\t */\n\t@Override\n\tpublic HttpResponse executeRequest(T httpRequestBase) \n\tthrows ClientProtocolException, IOException {\n\n\t\treturn this.httpClient.execute(httpRequestBase);\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t */\n\t@Override\n\tpublic HttpResponse executeRequest(T httpRequestBase, HttpContext httpContext)\n\tthrows ClientProtocolException, IOException {\n\t\n\t\treturn this.httpClient.execute(httpRequestBase, httpContext);\n\t}\n}\n"},"message":{"kind":"string","value":"Update max connections and connection manager cleanup\n"},"old_file":{"kind":"string","value":"src/main/java/com/lonepulse/zombielink/core/MultiThreadedHttpClient.java"},"subject":{"kind":"string","value":"Update max connections and connection manager cleanup"},"git_diff":{"kind":"string","value":"rc/main/java/com/lonepulse/zombielink/core/MultiThreadedHttpClient.java\n \t *

\n \t * @since 1.1.1\n \t */\n\tprivate transient HttpClient httpClient;\n\tprivate final transient HttpClient httpClient;\n \t\n \t\n \t/**\n \t\tschemeRegistry.register(new Scheme(\"https\", 443, SSLSocketFactory.getSocketFactory()));\n \t\t\n \t\tPoolingClientConnectionManager pccm = new PoolingClientConnectionManager(schemeRegistry);\n\t\tpccm.setMaxTotal(128); //Max. number of client connections pooled\n\t\tpccm.setMaxTotal(256); //Max. number of client connections pooled\n\t\tpccm.setDefaultMaxPerRoute(24); //Max connections per route\n \t\t\n \t\tthis.httpClient = new DefaultHttpClient(pccm);\n\t\t\n\t\tRuntime.getRuntime().addShutdownHook(new Thread(new Runnable() {\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void run() { //HttpClient considered to be \"out of scope\" only on VM exit\n\t\t\t\n\t\t\t\thttpClient.getConnectionManager().shutdown(); \n\t\t\t}\n\t\t}));\n \t}\n \n \t/**"}}},{"rowIdx":1949,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"d54f21a5b8cc3c71f717596c6731bc3dd5f536bb"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"flanglet/kanzi"},"new_contents":{"kind":"string","value":"/*\nCopyright 2011-2021 Frederic Langlet\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nyou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\npackage kanzi.function;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.ByteArrayOutputStream;\nimport java.util.Map;\nimport kanzi.ByteFunction;\nimport kanzi.InputBitStream;\nimport kanzi.Memory;\nimport kanzi.OutputBitStream;\nimport kanzi.SliceByteArray;\nimport kanzi.bitstream.DefaultInputBitStream;\nimport kanzi.bitstream.DefaultOutputBitStream;\nimport kanzi.entropy.ANSRangeDecoder;\nimport kanzi.entropy.ANSRangeEncoder;\n\n\n// Implementation of a Reduced Offset Lempel Ziv transform\n// More information about ROLZ at http://ezcodesample.com/rolz/rolz_article.html\n\npublic class ROLZCodec implements ByteFunction\n{\n private static final int HASH_SIZE = 1 << 16;\n private static final int LOG_POS_CHECKS1 = 4;\n private static final int LOG_POS_CHECKS2 = 5;\n private static final int CHUNK_SIZE = 1 << 26;\n private static final int MATCH_FLAG = 0;\n private static final int LITERAL_FLAG = 1;\n private static final int HASH = 200002979;\n private static final int HASH_MASK = ~(CHUNK_SIZE - 1);\n private static final int MAX_BLOCK_SIZE = 1 << 30; // 1 GB\n private static final int MIN_BLOCK_SIZE = 64;\n\n\n private final ByteFunction delegate;\n\n\n public ROLZCodec()\n {\n this.delegate = new ROLZCodec1(); // defaults to ANS\n }\n\n\n public ROLZCodec(boolean extra)\n {\n this.delegate = (extra == true) ? new ROLZCodec2() : new ROLZCodec1();\n }\n\n\n public ROLZCodec(Map ctx)\n {\n String transform = (String) ctx.getOrDefault(\"transform\", \"NONE\");\n this.delegate = (transform.contains(\"ROLZX\")) ? new ROLZCodec2() : new ROLZCodec1();\n }\n\n\n private static short getKey(final byte[] buf, final int idx)\n {\n return (short) (Memory.LittleEndian.readInt16(buf, idx) & 0x7FFFFFFF);\n }\n\n\n private static int hash(final byte[] buf, final int idx)\n {\n return ((Memory.LittleEndian.readInt32(buf, idx)<<8) * HASH) & HASH_MASK;\n }\n\n\n private static int emitCopy(byte[] dst, int dstIdx, int ref, int matchLen)\n {\n dst[dstIdx] = dst[ref];\n dst[dstIdx+1] = dst[ref+1];\n dst[dstIdx+2] = dst[ref+2];\n dstIdx += 3;\n ref += 3;\n\n while (matchLen >= 4)\n {\n dst[dstIdx] = dst[ref];\n dst[dstIdx+1] = dst[ref+1];\n dst[dstIdx+2] = dst[ref+2];\n dst[dstIdx+3] = dst[ref+3];\n dstIdx += 4;\n ref += 4;\n matchLen -= 4;\n }\n\n while (matchLen != 0)\n {\n dst[dstIdx++] = dst[ref++];\n matchLen--;\n }\n\n return dstIdx;\n }\n\n\n @Override\n public int getMaxEncodedLength(int srcLength)\n {\n return this.delegate.getMaxEncodedLength(srcLength);\n }\n\n\n @Override\n public boolean forward(SliceByteArray src, SliceByteArray dst)\n {\n if (src.length == 0)\n return true;\n\n if (src.length < MIN_BLOCK_SIZE)\n return false;\n\n if (src.array == dst.array)\n return false;\n\n if (src.length > MAX_BLOCK_SIZE)\n throw new IllegalArgumentException(\"The max ROLZ codec block size is \"+MAX_BLOCK_SIZE+\", got \"+src.length);\n\n return this.delegate.forward(src, dst);\n }\n\n\n @Override\n public boolean inverse(SliceByteArray src, SliceByteArray dst)\n {\n if (src.length == 0)\n return true;\n\n if (src.array == dst.array)\n return false;\n\n if (src.length > MAX_BLOCK_SIZE)\n throw new IllegalArgumentException(\"The max ROLZ codec block size is \"+MAX_BLOCK_SIZE+\", got \"+src.length);\n\n return this.delegate.inverse(src, dst);\n }\n\n\n // Use ANS to encode/decode literals and matches\n static class ROLZCodec1 implements ByteFunction\n {\n private static final int MIN_MATCH = 3;\n private static final int MAX_MATCH = MIN_MATCH + 65535;\n\n private final int logPosChecks;\n private final int maskChecks;\n private final int posChecks;\n private final int[] matches;\n private final int[] counters;\n\n\n public ROLZCodec1()\n {\n this(LOG_POS_CHECKS1);\n }\n\n\n public ROLZCodec1(int logPosChecks)\n {\n if ((logPosChecks < 2) || (logPosChecks > 8))\n throw new IllegalArgumentException(\"ROLZ codec: Invalid logPosChecks parameter \" +\n \"(must be in [2..8])\");\n\n this.logPosChecks = logPosChecks;\n this.posChecks = 1 << logPosChecks;\n this.maskChecks = this.posChecks - 1;\n this.counters = new int[1<<16];\n this.matches = new int[HASH_SIZE<= MAX_MATCH) ? MAX_MATCH : sba.length-pos;\n\n // Check all recorded positions\n for (int i=counter; i>counter-this.posChecks; i--)\n {\n int ref = this.matches[base+(i&this.maskChecks)];\n\n // Hash check may save a memory access ...\n if ((ref & HASH_MASK) != hash32)\n continue;\n\n ref = (ref & ~HASH_MASK) + sba.index;\n\n if (buf[ref] != first)\n continue;\n\n int n = 1;\n\n while ((n < maxMatch) && (buf[ref+n] == buf[pos+n]))\n n++;\n\n if (n > bestLen)\n {\n bestIdx = counter - i;\n bestLen = n;\n\n if (bestLen == maxMatch)\n break;\n }\n }\n\n // Register current position\n this.counters[key]++;\n this.matches[base+(this.counters[key]&this.maskChecks)] = hash32 | (pos-sba.index);\n return (bestLen < MIN_MATCH) ? -1 : (bestIdx<<16) | (bestLen-MIN_MATCH);\n }\n\n\n @Override\n public boolean forward(SliceByteArray input, SliceByteArray output)\n {\n final int count = input.length;\n\n if (output.length - output.index < this.getMaxEncodedLength(count))\n return false;\n\n int srcIdx = input.index;\n int dstIdx = output.index;\n final byte[] src = input.array;\n final byte[] dst = output.array;\n final int srcEnd = srcIdx + count - 4;\n Memory.BigEndian.writeInt32(dst, dstIdx, count);\n dstIdx += 4;\n int sizeChunk = (count <= CHUNK_SIZE) ? count : CHUNK_SIZE;\n int startChunk = srcIdx;\n final SliceByteArray litBuf = new SliceByteArray(new byte[this.getMaxEncodedLength(sizeChunk)], 0);\n final SliceByteArray lenBuf = new SliceByteArray(new byte[sizeChunk/5], 0);\n final SliceByteArray mIdxBuf = new SliceByteArray(new byte[sizeChunk/4], 0);\n final SliceByteArray tkBuf = new SliceByteArray(new byte[sizeChunk/5], 0);\n ByteArrayOutputStream baos = new ByteArrayOutputStream(this.getMaxEncodedLength(sizeChunk));\n\n for (int i=0; i L lit length, M match length\n final int litLen = srcIdx - firstLitIdx;\n final int mode = (litLen < 31) ? (litLen << 3) : 0xF8;\n final int mLen = match & 0xFFFF;\n\n if (mLen >= 7)\n {\n tkBuf.array[tkBuf.index++] = (byte) (mode | 0x07);\n emitLength(lenBuf, mLen - 7);\n }\n else\n {\n tkBuf.array[tkBuf.index++] = (byte) (mode | mLen);\n }\n\n // Emit literals\n if (litLen >= 16)\n {\n if (litLen >= 31)\n emitLength(lenBuf, litLen - 31);\n\n System.arraycopy(src, firstLitIdx, litBuf.array, litBuf.index, litLen);\n }\n else\n {\n for (int i=0; i>>16);\n srcIdx += ((match&0xFFFF) + MIN_MATCH);\n firstLitIdx = srcIdx;\n }\n\n // Emit last chunk literals\n final int litLen = srcIdx - firstLitIdx;\n final int mode = (litLen < 31) ? (litLen << 3) : 0xF8;\n tkBuf.array[tkBuf.index++] = (byte) mode;\n\n if (litLen >= 31)\n emitLength(lenBuf, litLen - 31);\n\n for (int i=0; i dst.length)\n {\n output.index = dstIdx;\n input.index = srcIdx;\n return false;\n }\n\n System.arraycopy(buf, 0, dst, dstIdx, buf.length);\n dstIdx += buf.length;\n startChunk = endChunk;\n }\n\n if (dstIdx+4 > dst.length)\n {\n output.index = dstIdx;\n input.index = srcIdx;\n return false;\n }\n\n // Emit last literals\n dst[dstIdx++] = src[srcIdx];\n dst[dstIdx++] = src[srcIdx+1];\n dst[dstIdx++] = src[srcIdx+2];\n dst[dstIdx++] = src[srcIdx+3];\n\n input.index = srcIdx + 4;\n output.index = dstIdx;\n return (srcIdx == srcEnd) && (dstIdx < count);\n }\n\n\n private static void emitLength(SliceByteArray lenBuf, int length)\n {\n if (length >= 1<<7)\n {\n if (length >= 1<<14)\n {\n if (length >= 1<<21)\n lenBuf.array[lenBuf.index++] = (byte) (0x80|(length>>21));\n\n lenBuf.array[lenBuf.index++] = (byte) (0x80|(length>>14));\n }\n\n lenBuf.array[lenBuf.index++] = (byte) (0x80|(length>>7));\n }\n\n lenBuf.array[lenBuf.index++] = (byte) (length&0x7F);\n }\n\n\n @Override\n public boolean inverse(SliceByteArray input, SliceByteArray output)\n {\n final int count = input.length;\n final byte[] src = input.array;\n final byte[] dst = output.array;\n int srcIdx = input.index;\n final int srcEnd = srcIdx + count;\n final int dstEnd = output.index + Memory.BigEndian.readInt32(src, srcIdx) - 4;\n srcIdx += 4;\n int sizeChunk = (dstEnd <= CHUNK_SIZE) ? dstEnd : CHUNK_SIZE;\n int startChunk = output.index;\n final SliceByteArray litBuf = new SliceByteArray(new byte[this.getMaxEncodedLength(sizeChunk)], 0);\n final SliceByteArray lenBuf = new SliceByteArray(new byte[sizeChunk/5], 0);\n final SliceByteArray mIdxBuf = new SliceByteArray(new byte[sizeChunk/4], 0);\n final SliceByteArray tkBuf = new SliceByteArray(new byte[sizeChunk/5], 0);\n\n for (int i=0; isizeChunk) || (tkLen>sizeChunk) || (mLenLen>sizeChunk) || (mIdxLen>sizeChunk))\n {\n input.index = srcIdx;\n output.index = dstIdx;\n return false;\n }\n\n ANSRangeDecoder litDec = new ANSRangeDecoder(ibs, litOrder);\n litDec.decode(litBuf.array, 0, litLen);\n litDec.dispose();\n ANSRangeDecoder mDec = new ANSRangeDecoder(ibs, 0);\n mDec.decode(tkBuf.array, 0, tkLen);\n mDec.decode(lenBuf.array, 0, mLenLen);\n mDec.decode(mIdxBuf.array, 0, mIdxLen);\n mDec.dispose();\n\n srcIdx += (int) ((ibs.read()+7)>>>3);\n ibs.close();\n }\n\n dst[dstIdx++] = litBuf.array[litBuf.index++];\n\n if (dstIdx+1 < dstEnd)\n dst[dstIdx++] = litBuf.array[litBuf.index++];\n\n // Next chunk\n while (dstIdx < endChunk)\n {\n // mode LLLLLMMM -> L lit length, M match length\n final int mode = tkBuf.array[tkBuf.index++] & 0xFF;\n int matchLen = mode & 0x07;\n\n if (matchLen == 7)\n matchLen = readLength(lenBuf) + 7;\n\n final int litLen = (mode < 0xF8) ? mode >> 3 : readLength(lenBuf) + 31;\n this.emitLiterals(litBuf, dst, dstIdx, output.index, litLen);\n litBuf.index += litLen;\n dstIdx += litLen;\n\n if (dstIdx >= endChunk)\n {\n // Last chunk literals not followed by match\n if (dstIdx == endChunk)\n break;\n\n output.index = dstIdx;\n input.index = srcIdx;\n return false;\n }\n\n // Sanity check\n if (dstIdx+matchLen+MIN_MATCH > dstEnd)\n {\n output.index = dstIdx;\n input.index = srcIdx;\n return false;\n }\n\n final int key = getKey(dst, dstIdx-2) & 0xFFFF;\n final int base = key << this.logPosChecks;\n final int matchIdx = mIdxBuf.array[mIdxBuf.index++] & 0xFF;\n final int ref = output.index + this.matches[base+((this.counters[key]-matchIdx)&this.maskChecks)];\n final int savedIdx = dstIdx;\n dstIdx = emitCopy(dst, dstIdx, ref, matchLen);\n this.counters[key]++;\n this.matches[base+(this.counters[key]&this.maskChecks)] = savedIdx - output.index;\n }\n\n startChunk = endChunk;\n output.index = dstIdx;\n }\n\n // Emit last literals\n dst[output.index++] = src[srcIdx++];\n dst[output.index++] = src[srcIdx++];\n dst[output.index++] = src[srcIdx++];\n dst[output.index++] = src[srcIdx++];\n\n input.index = srcIdx;\n return input.index == srcEnd;\n }\n\n\n private static int readLength(SliceByteArray lenBuf)\n {\n int next = lenBuf.array[lenBuf.index++];\n int length = next & 0x7F;\n\n if ((next & 0x80) != 0)\n {\n next = lenBuf.array[lenBuf.index++];\n length = (length<<7) | (next&0x7F);\n\n if ((next & 0x80) != 0)\n {\n next = lenBuf.array[lenBuf.index++];\n length = (length<<7) | (next&0x7F);\n\n if ((next & 0x80) != 0)\n {\n next = lenBuf.array[lenBuf.index++];\n length = (length<<7) | (next&0x7F);\n }\n }\n }\n\n return length;\n }\n\n\n private int emitLiterals(SliceByteArray litBuf, byte[] dst, int dstIdx, int startIdx, final int length)\n {\n final int n0 = dstIdx - startIdx;\n\n for (int n=0; n 8))\n throw new IllegalArgumentException(\"ROLZX codec: Invalid logPosChecks parameter \" +\n \"(must be in [2..8])\");\n\n this.logPosChecks = logPosChecks;\n this.posChecks = 1 << logPosChecks;\n this.maskChecks = this.posChecks - 1;\n this.counters = new int[1<<16];\n this.matches = new int[HASH_SIZE<= MAX_MATCH) ? MAX_MATCH : sba.length-pos;\n\n // Check all recorded positions\n for (int i=counter; i>counter-this.posChecks; i--)\n {\n int ref = this.matches[base+(i&this.maskChecks)];\n\n // Hash check may save a memory access ...\n if ((ref & HASH_MASK) != hash32)\n continue;\n\n ref = (ref & ~HASH_MASK) + sba.index;\n\n if (buf[ref] != first)\n continue;\n\n int n = 1;\n\n while ((n < maxMatch) && (buf[ref+n] == buf[pos+n]))\n n++;\n\n if (n > bestLen)\n {\n bestIdx = counter - i;\n bestLen = n;\n\n if (bestLen == maxMatch)\n break;\n }\n }\n\n // Register current position\n this.counters[key]++;\n this.matches[base+(this.counters[key]&this.maskChecks)] = hash32 | (pos-sba.index);\n return (bestLen < MIN_MATCH) ? -1 : (bestIdx<<16) | (bestLen-MIN_MATCH);\n }\n\n\n @Override\n public boolean forward(SliceByteArray input, SliceByteArray output)\n {\n final int count = input.length;\n\n if (output.length - output.index < this.getMaxEncodedLength(count))\n return false;\n\n int srcIdx = input.index;\n int dstIdx = output.index;\n final byte[] src = input.array;\n final byte[] dst = output.array;\n final int srcEnd = srcIdx + count - 4;\n Memory.BigEndian.writeInt32(dst, dstIdx, count);\n dstIdx += 4;\n int sizeChunk = (count <= CHUNK_SIZE) ? count : CHUNK_SIZE;\n int startChunk = srcIdx;\n SliceByteArray sba1 = new SliceByteArray(dst, dstIdx);\n ROLZEncoder re = new ROLZEncoder(9, this.logPosChecks, sba1);\n\n for (int i=0; i>> 16;\n re.setMode(MATCH_FLAG);\n re.setContext(src[srcIdx-1]);\n re.encodeBits(matchIdx, this.logPosChecks);\n re.setMode(LITERAL_FLAG);\n srcIdx += (matchLen+MIN_MATCH);\n }\n\n startChunk = endChunk;\n }\n\n // Emit last literals\n re.setMode(LITERAL_FLAG);\n\n for (int i=0; i<4; i++, srcIdx++)\n {\n re.setContext(src[srcIdx-1]);\n re.encodeBits((LITERAL_FLAG<<8)|(src[srcIdx]&0xFF), 9);\n }\n\n re.dispose();\n input.index = srcIdx;\n output.index = sba1.index;\n return (input.index == srcEnd+4) && (output.index < count);\n }\n\n\n @Override\n public boolean inverse(SliceByteArray input, SliceByteArray output)\n {\n final int count = input.length;\n final byte[] src = input.array;\n final byte[] dst = output.array;\n int srcIdx = input.index;\n final int srcEnd = srcIdx + count;\n final int dstEnd = output.index + Memory.BigEndian.readInt32(src, srcIdx);\n srcIdx += 4;\n int sizeChunk = (dstEnd < CHUNK_SIZE) ? dstEnd : CHUNK_SIZE;\n int startChunk = output.index;\n SliceByteArray sba = new SliceByteArray(src, srcIdx);\n ROLZDecoder rd = new ROLZDecoder(9, this.logPosChecks, sba);\n\n for (int i=0; i>>8) == MATCH_FLAG)\n {\n output.index = dstIdx;\n break;\n }\n\n dst[dstIdx++] = (byte) val1;\n\n if (dstIdx < dstEnd)\n {\n val1 = rd.decodeBits(9);\n\n // Sanity check\n if ((val1>>>8) == MATCH_FLAG)\n {\n output.index = dstIdx;\n break;\n }\n\n dst[dstIdx++] = (byte) val1;\n }\n\n // Next chunk\n while (dstIdx < endChunk)\n {\n final int savedIdx = dstIdx;\n final int key = getKey(dst, dstIdx-2) & 0xFFFF;\n final int base = key << this.logPosChecks;\n rd.setMode(LITERAL_FLAG);\n rd.setContext(dst[dstIdx-1]);\n final int val = rd.decodeBits(9);\n\n if ((val>>>8) == LITERAL_FLAG)\n {\n // Read one literal\n dst[dstIdx++] = (byte) val;\n }\n else\n {\n // Read one match length and index\n final int matchLen = val & 0xFF;\n\n // Sanity check\n if (dstIdx+matchLen+3 > dstEnd)\n {\n output.index = dstIdx;\n break;\n }\n\n rd.setMode(MATCH_FLAG);\n rd.setContext(dst[dstIdx-1]);\n final int matchIdx = rd.decodeBits(this.logPosChecks);\n final int ref = output.index + this.matches[base+((this.counters[key]-matchIdx)&this.maskChecks)];\n dstIdx = emitCopy(dst, dstIdx, ref, matchLen);\n }\n\n // Update map\n this.counters[key]++;\n this.matches[base+(this.counters[key]&this.maskChecks)] = savedIdx - output.index;\n }\n\n startChunk = endChunk;\n output.index = dstIdx;\n }\n\n rd.dispose();\n input.index = sba.index;\n return input.index == srcEnd;\n }\n\n\n @Override\n public int getMaxEncodedLength(int srcLen)\n {\n // Since we do not check the dst index for each byte (for speed purpose)\n // allocate some extra buffer for incompressible data.\n return (srcLen <= 16384) ? srcLen+1024 : srcLen+(srcLen/32);\n }\n }\n\n\n\n static class ROLZEncoder\n {\n private static final long TOP = 0x00FFFFFFFFFFFFFFL;\n private static final long MASK_0_32 = 0x00000000FFFFFFFFL;\n private static final int PSCALE = 0xFFFF;\n private static final int MATCH_FLAG = 0;\n private static final int LITERAL_FLAG = 1;\n\n\n private final SliceByteArray sba;\n private long low;\n private long high;\n private final int[][] probs;\n private final int[] logSizes;\n private int c1;\n private int ctx;\n private int pIdx;\n\n\n public ROLZEncoder(int litLogSize, int mLogSize, SliceByteArray sba)\n {\n this.low = 0L;\n this.high = TOP;\n this.sba = sba;\n this.pIdx = LITERAL_FLAG;\n this.c1 = 1;\n this.probs = new int[2][];\n this.probs[MATCH_FLAG] = new int[256<>1;\n\n final int litLogSize = this.logSizes[LITERAL_FLAG];\n\n for (int i=0; i<(256<>1;\n }\n\n public void setMode(int n)\n {\n this.pIdx = n;\n }\n\n public void setContext(byte ctx)\n {\n this.ctx = (ctx&0xFF) << this.logSizes[this.pIdx];\n }\n\n public final void encodeBits(int val, int n)\n {\n this.c1 = 1;\n\n do\n {\n n--;\n this.encodeBit(val & (1<>>4) * (this.probs[this.pIdx][this.ctx+this.c1]>>>4)) >>> 8;\n\n // Update fields with new interval bounds\n if (bit == 0)\n {\n this.low += (split+1);\n this.probs[this.pIdx][this.ctx+this.c1] -= (this.probs[this.pIdx][this.ctx+this.c1]>>5);\n this.c1 += this.c1;\n }\n else\n {\n this.high = this.low + split;\n this.probs[this.pIdx][this.ctx+this.c1] -= (((this.probs[this.pIdx][this.ctx+this.c1]-0xFFFF)>>5) + 1);\n this.c1 += (this.c1+1);\n }\n\n // Write unchanged first 32 bits to bitstream\n while (((this.low ^ this.high) >>> 24) == 0)\n {\n Memory.BigEndian.writeInt32(this.sba.array, this.sba.index, (int) (this.high>>>32));\n this.sba.index += 4;\n this.low <<= 32;\n this.high = (this.high << 32) | MASK_0_32;\n }\n }\n\n public void dispose()\n {\n for (int i=0; i<8; i++)\n {\n this.sba.array[this.sba.index+i] = (byte) (this.low>>56);\n this.low <<= 8;\n }\n\n this.sba.index += 8;\n }\n }\n\n\n static class ROLZDecoder\n {\n private static final long TOP = 0x00FFFFFFFFFFFFFFL;\n private static final long MASK_0_56 = 0x00FFFFFFFFFFFFFFL;\n private static final long MASK_0_32 = 0x00000000FFFFFFFFL;\n private static final int PSCALE = 0xFFFF;\n private static final int MATCH_FLAG = 0;\n private static final int LITERAL_FLAG = 1;\n\n private final SliceByteArray sba;\n private long low;\n private long high;\n private long current;\n private final int[][] probs;\n private final int[] logSizes;\n private int c1;\n private int ctx;\n private int pIdx;\n\n\n public ROLZDecoder(int litLogSize, int mLogSize, SliceByteArray sba)\n {\n this.low = 0L;\n this.high = TOP;\n this.sba = sba;\n this.current = 0;\n\n for (int i=0; i<8; i++)\n this.current = (this.current<<8) | (long) (this.sba.array[this.sba.index+i] &0xFF);\n\n this.sba.index += 8;\n this.pIdx = LITERAL_FLAG;\n this.c1 = 1;\n this.probs = new int[2][];\n this.probs[MATCH_FLAG] = new int[256<>1;\n\n final int litLogSize = this.logSizes[LITERAL_FLAG];\n\n for (int i=0; i<(256<>1;\n }\n\n public void setMode(int n)\n {\n this.pIdx = n;\n }\n\n public void setContext(byte ctx)\n {\n this.ctx = (ctx&0xFF) << this.logSizes[this.pIdx];\n }\n\n public int decodeBits(int n)\n {\n this.c1 = 1;\n final int mask = (1<>>4) * (this.probs[this.pIdx][this.ctx+this.c1]>>>4)) >>> 8);\n int bit;\n\n // Update bounds and predictor\n if (mid >= this.current)\n {\n bit = 1;\n this.high = mid;\n this.probs[this.pIdx][this.ctx+this.c1] -= (((this.probs[this.pIdx][this.ctx+this.c1]-0xFFFF)>>5) + 1);\n this.c1 += (this.c1+1);\n }\n else\n {\n bit = 0;\n this.low = mid + 1;\n this.probs[this.pIdx][this.ctx+this.c1] -= (this.probs[this.pIdx][this.ctx+this.c1]>>5);\n this.c1 += this.c1;\n }\n\n // Read 32 bits from bitstream\n while (((this.low ^ this.high) >>> 24) == 0)\n {\n this.low = (this.low << 32) & MASK_0_56;\n this.high = ((this.high << 32) | MASK_0_32) & MASK_0_56;\n final long val = Memory.BigEndian.readInt32(this.sba.array, this.sba.index) & MASK_0_32;\n this.current = ((this.current << 32) | val) & MASK_0_56;\n this.sba.index += 4;\n }\n\n return bit;\n }\n\n public void dispose()\n {\n }\n }\n\n}\n"},"new_file":{"kind":"string","value":"java/src/main/java/kanzi/function/ROLZCodec.java"},"old_contents":{"kind":"string","value":"/*\nCopyright 2011-2021 Frederic Langlet\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nyou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\npackage kanzi.function;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.ByteArrayOutputStream;\nimport java.util.Map;\nimport kanzi.ByteFunction;\nimport kanzi.InputBitStream;\nimport kanzi.Memory;\nimport kanzi.OutputBitStream;\nimport kanzi.SliceByteArray;\nimport kanzi.bitstream.DefaultInputBitStream;\nimport kanzi.bitstream.DefaultOutputBitStream;\nimport kanzi.entropy.ANSRangeDecoder;\nimport kanzi.entropy.ANSRangeEncoder;\n\n\n// Implementation of a Reduced Offset Lempel Ziv transform\n// More information about ROLZ at http://ezcodesample.com/rolz/rolz_article.html\n\npublic class ROLZCodec implements ByteFunction\n{\n private static final int HASH_SIZE = 1 << 16;\n private static final int LOG_POS_CHECKS1 = 4;\n private static final int LOG_POS_CHECKS2 = 5;\n private static final int CHUNK_SIZE = 1 << 26;\n private static final int MATCH_FLAG = 0;\n private static final int LITERAL_FLAG = 1;\n private static final int HASH = 200002979;\n private static final int HASH_MASK = ~(CHUNK_SIZE - 1);\n private static final int MAX_BLOCK_SIZE = 1 << 30; // 1 GB\n private static final int MIN_BLOCK_SIZE = 64;\n\n\n private final ByteFunction delegate;\n\n\n public ROLZCodec()\n {\n this.delegate = new ROLZCodec1(); // defaults to ANS\n }\n\n\n public ROLZCodec(boolean extra)\n {\n this.delegate = (extra == true) ? new ROLZCodec2() : new ROLZCodec1();\n }\n\n\n public ROLZCodec(Map ctx)\n {\n String transform = (String) ctx.getOrDefault(\"transform\", \"NONE\");\n this.delegate = (transform.contains(\"ROLZX\")) ? new ROLZCodec2() : new ROLZCodec1();\n }\n\n\n private static short getKey(final byte[] buf, final int idx)\n {\n return (short) (Memory.LittleEndian.readInt16(buf, idx) & 0x7FFFFFFF);\n }\n\n\n private static int hash(final byte[] buf, final int idx)\n {\n return ((Memory.LittleEndian.readInt32(buf, idx)<<8) * HASH) & HASH_MASK;\n }\n\n\n private static int emitCopy(byte[] dst, int dstIdx, int ref, int matchLen)\n {\n dst[dstIdx] = dst[ref];\n dst[dstIdx+1] = dst[ref+1];\n dst[dstIdx+2] = dst[ref+2];\n dstIdx += 3;\n ref += 3;\n\n while (matchLen >= 4)\n {\n dst[dstIdx] = dst[ref];\n dst[dstIdx+1] = dst[ref+1];\n dst[dstIdx+2] = dst[ref+2];\n dst[dstIdx+3] = dst[ref+3];\n dstIdx += 4;\n ref += 4;\n matchLen -= 4;\n }\n\n while (matchLen != 0)\n {\n dst[dstIdx++] = dst[ref++];\n matchLen--;\n }\n\n return dstIdx;\n }\n\n\n @Override\n public int getMaxEncodedLength(int srcLength)\n {\n return this.delegate.getMaxEncodedLength(srcLength);\n }\n\n\n @Override\n public boolean forward(SliceByteArray src, SliceByteArray dst)\n {\n if (src.length == 0)\n return true;\n\n if (src.length < MIN_BLOCK_SIZE)\n return false;\n\n if (src.array == dst.array)\n return false;\n\n if (src.length > MAX_BLOCK_SIZE)\n throw new IllegalArgumentException(\"The max ROLZ codec block size is \"+MAX_BLOCK_SIZE+\", got \"+src.length);\n\n return this.delegate.forward(src, dst);\n }\n\n\n @Override\n public boolean inverse(SliceByteArray src, SliceByteArray dst)\n {\n if (src.length == 0)\n return true;\n\n if (src.array == dst.array)\n return false;\n\n if (src.length > MAX_BLOCK_SIZE)\n throw new IllegalArgumentException(\"The max ROLZ codec block size is \"+MAX_BLOCK_SIZE+\", got \"+src.length);\n\n return this.delegate.inverse(src, dst);\n }\n\n\n // Use ANS to encode/decode literals and matches\n static class ROLZCodec1 implements ByteFunction\n {\n private static final int MIN_MATCH = 3;\n private static final int MAX_MATCH = MIN_MATCH + 65535 + 7;\n\n private final int logPosChecks;\n private final int maskChecks;\n private final int posChecks;\n private final int[] matches;\n private final int[] counters;\n\n\n public ROLZCodec1()\n {\n this(LOG_POS_CHECKS1);\n }\n\n\n public ROLZCodec1(int logPosChecks)\n {\n if ((logPosChecks < 2) || (logPosChecks > 8))\n throw new IllegalArgumentException(\"ROLZ codec: Invalid logPosChecks parameter \" +\n \"(must be in [2..8])\");\n\n this.logPosChecks = logPosChecks;\n this.posChecks = 1 << logPosChecks;\n this.maskChecks = this.posChecks - 1;\n this.counters = new int[1<<16];\n this.matches = new int[HASH_SIZE<= MAX_MATCH) ? MAX_MATCH : sba.length-pos;\n\n // Check all recorded positions\n for (int i=counter; i>counter-this.posChecks; i--)\n {\n int ref = this.matches[base+(i&this.maskChecks)];\n\n // Hash check may save a memory access ...\n if ((ref & HASH_MASK) != hash32)\n continue;\n\n ref = (ref & ~HASH_MASK) + sba.index;\n\n if (buf[ref] != first)\n continue;\n\n int n = 1;\n\n while ((n < maxMatch) && (buf[ref+n] == buf[pos+n]))\n n++;\n\n if (n > bestLen)\n {\n bestIdx = counter - i;\n bestLen = n;\n\n if (bestLen == maxMatch)\n break;\n }\n }\n\n // Register current position\n this.counters[key]++;\n this.matches[base+(this.counters[key]&this.maskChecks)] = hash32 | (pos-sba.index);\n return (bestLen < MIN_MATCH) ? -1 : (bestIdx<<16) | (bestLen-MIN_MATCH);\n }\n\n\n @Override\n public boolean forward(SliceByteArray input, SliceByteArray output)\n {\n final int count = input.length;\n\n if (output.length - output.index < this.getMaxEncodedLength(count))\n return false;\n\n int srcIdx = input.index;\n int dstIdx = output.index;\n final byte[] src = input.array;\n final byte[] dst = output.array;\n final int srcEnd = srcIdx + count - 4;\n Memory.BigEndian.writeInt32(dst, dstIdx, count);\n dstIdx += 4;\n int sizeChunk = (count <= CHUNK_SIZE) ? count : CHUNK_SIZE;\n int startChunk = srcIdx;\n final SliceByteArray litBuf = new SliceByteArray(new byte[this.getMaxEncodedLength(sizeChunk)], 0);\n final SliceByteArray lenBuf = new SliceByteArray(new byte[sizeChunk/5], 0);\n final SliceByteArray mIdxBuf = new SliceByteArray(new byte[sizeChunk/4], 0);\n final SliceByteArray tkBuf = new SliceByteArray(new byte[sizeChunk/5], 0);\n ByteArrayOutputStream baos = new ByteArrayOutputStream(this.getMaxEncodedLength(sizeChunk));\n\n for (int i=0; i L lit length, M match length\n final int litLen = srcIdx - firstLitIdx;\n final int mode = (litLen < 31) ? (litLen << 3) : 0xF8;\n final int mLen = match & 0xFFFF;\n\n if (mLen >= 7)\n {\n tkBuf.array[tkBuf.index++] = (byte) (mode | 0x07);\n emitLength(lenBuf, mLen - 7);\n }\n else\n {\n tkBuf.array[tkBuf.index++] = (byte) (mode | mLen);\n }\n\n // Emit literals\n if (litLen >= 16)\n {\n if (litLen >= 31)\n emitLength(lenBuf, litLen - 31);\n\n System.arraycopy(src, firstLitIdx, litBuf.array, litBuf.index, litLen);\n }\n else\n {\n for (int i=0; i>>16);\n srcIdx += ((match&0xFFFF) + MIN_MATCH);\n firstLitIdx = srcIdx;\n }\n\n // Emit last chunk literals\n final int litLen = srcIdx - firstLitIdx;\n final int mode = (litLen < 31) ? (litLen << 3) : 0xF8;\n tkBuf.array[tkBuf.index++] = (byte) mode;\n\n if (litLen >= 31)\n emitLength(lenBuf, litLen - 31);\n\n for (int i=0; i dst.length)\n {\n output.index = dstIdx;\n input.index = srcIdx;\n return false;\n }\n\n System.arraycopy(buf, 0, dst, dstIdx, buf.length);\n dstIdx += buf.length;\n startChunk = endChunk;\n }\n\n if (dstIdx+4 > dst.length)\n {\n output.index = dstIdx;\n input.index = srcIdx;\n return false;\n }\n\n // Emit last literals\n dst[dstIdx++] = src[srcIdx];\n dst[dstIdx++] = src[srcIdx+1];\n dst[dstIdx++] = src[srcIdx+2];\n dst[dstIdx++] = src[srcIdx+3];\n\n input.index = srcIdx + 4;\n output.index = dstIdx;\n return (srcIdx == srcEnd) && (dstIdx < count);\n }\n\n\n private static void emitLength(SliceByteArray lenBuf, int length)\n {\n if (length >= 1<<7)\n {\n if (length >= 1<<14)\n {\n if (length >= 1<<21)\n lenBuf.array[lenBuf.index++] = (byte) (0x80|(length>>21));\n\n lenBuf.array[lenBuf.index++] = (byte) (0x80|(length>>14));\n }\n\n lenBuf.array[lenBuf.index++] = (byte) (0x80|(length>>7));\n }\n\n lenBuf.array[lenBuf.index++] = (byte) (length&0x7F);\n }\n\n\n @Override\n public boolean inverse(SliceByteArray input, SliceByteArray output)\n {\n final int count = input.length;\n final byte[] src = input.array;\n final byte[] dst = output.array;\n int srcIdx = input.index;\n final int srcEnd = srcIdx + count;\n final int dstEnd = output.index + Memory.BigEndian.readInt32(src, srcIdx) - 4;\n srcIdx += 4;\n int sizeChunk = (dstEnd <= CHUNK_SIZE) ? dstEnd : CHUNK_SIZE;\n int startChunk = output.index;\n final SliceByteArray litBuf = new SliceByteArray(new byte[this.getMaxEncodedLength(sizeChunk)], 0);\n final SliceByteArray lenBuf = new SliceByteArray(new byte[sizeChunk/5], 0);\n final SliceByteArray mIdxBuf = new SliceByteArray(new byte[sizeChunk/4], 0);\n final SliceByteArray tkBuf = new SliceByteArray(new byte[sizeChunk/5], 0);\n\n for (int i=0; isizeChunk) || (tkLen>sizeChunk) || (mLenLen>sizeChunk) || (mIdxLen>sizeChunk))\n {\n input.index = srcIdx;\n output.index = dstIdx;\n return false;\n }\n\n ANSRangeDecoder litDec = new ANSRangeDecoder(ibs, litOrder);\n litDec.decode(litBuf.array, 0, litLen);\n litDec.dispose();\n ANSRangeDecoder mDec = new ANSRangeDecoder(ibs, 0);\n mDec.decode(tkBuf.array, 0, tkLen);\n mDec.decode(lenBuf.array, 0, mLenLen);\n mDec.decode(mIdxBuf.array, 0, mIdxLen);\n mDec.dispose();\n\n srcIdx += (int) ((ibs.read()+7)>>>3);\n ibs.close();\n }\n\n dst[dstIdx++] = litBuf.array[litBuf.index++];\n\n if (dstIdx+1 < dstEnd)\n dst[dstIdx++] = litBuf.array[litBuf.index++];\n\n // Next chunk\n while (dstIdx < endChunk)\n {\n // mode LLLLLMMM -> L lit length, M match length\n final int mode = tkBuf.array[tkBuf.index++] & 0xFF;\n int matchLen = mode & 0x07;\n\n if (matchLen == 7)\n matchLen = readLength(lenBuf) + 7;\n\n final int litLen = (mode < 0xF8) ? mode >> 3 : readLength(lenBuf) + 31;\n this.emitLiterals(litBuf, dst, dstIdx, output.index, litLen);\n litBuf.index += litLen;\n dstIdx += litLen;\n\n if (dstIdx >= endChunk)\n {\n // Last chunk literals not followed by match\n if (dstIdx == endChunk)\n break;\n\n output.index = dstIdx;\n input.index = srcIdx;\n return false;\n }\n\n // Sanity check\n if (dstIdx+matchLen+MIN_MATCH > dstEnd)\n {\n output.index = dstIdx;\n input.index = srcIdx;\n return false;\n }\n\n final int key = getKey(dst, dstIdx-2) & 0xFFFF;\n final int base = key << this.logPosChecks;\n final int matchIdx = mIdxBuf.array[mIdxBuf.index++] & 0xFF;\n final int ref = output.index + this.matches[base+((this.counters[key]-matchIdx)&this.maskChecks)];\n final int savedIdx = dstIdx;\n dstIdx = emitCopy(dst, dstIdx, ref, matchLen);\n this.counters[key]++;\n this.matches[base+(this.counters[key]&this.maskChecks)] = savedIdx - output.index;\n }\n\n startChunk = endChunk;\n output.index = dstIdx;\n }\n\n // Emit last literals\n dst[output.index++] = src[srcIdx++];\n dst[output.index++] = src[srcIdx++];\n dst[output.index++] = src[srcIdx++];\n dst[output.index++] = src[srcIdx++];\n\n input.index = srcIdx;\n return input.index == srcEnd;\n }\n\n\n private static int readLength(SliceByteArray lenBuf)\n {\n int next = lenBuf.array[lenBuf.index++];\n int length = next & 0x7F;\n\n if ((next & 0x80) != 0)\n {\n next = lenBuf.array[lenBuf.index++];\n length = (length<<7) | (next&0x7F);\n\n if ((next & 0x80) != 0)\n {\n next = lenBuf.array[lenBuf.index++];\n length = (length<<7) | (next&0x7F);\n\n if ((next & 0x80) != 0)\n {\n next = lenBuf.array[lenBuf.index++];\n length = (length<<7) | (next&0x7F);\n }\n }\n }\n\n return length;\n }\n\n\n private int emitLiterals(SliceByteArray litBuf, byte[] dst, int dstIdx, int startIdx, final int length)\n {\n final int n0 = dstIdx - startIdx;\n\n for (int n=0; n 8))\n throw new IllegalArgumentException(\"ROLZX codec: Invalid logPosChecks parameter \" +\n \"(must be in [2..8])\");\n\n this.logPosChecks = logPosChecks;\n this.posChecks = 1 << logPosChecks;\n this.maskChecks = this.posChecks - 1;\n this.counters = new int[1<<16];\n this.matches = new int[HASH_SIZE<= MAX_MATCH) ? MAX_MATCH : sba.length-pos;\n\n // Check all recorded positions\n for (int i=counter; i>counter-this.posChecks; i--)\n {\n int ref = this.matches[base+(i&this.maskChecks)];\n\n // Hash check may save a memory access ...\n if ((ref & HASH_MASK) != hash32)\n continue;\n\n ref = (ref & ~HASH_MASK) + sba.index;\n\n if (buf[ref] != first)\n continue;\n\n int n = 1;\n\n while ((n < maxMatch) && (buf[ref+n] == buf[pos+n]))\n n++;\n\n if (n > bestLen)\n {\n bestIdx = counter - i;\n bestLen = n;\n\n if (bestLen == maxMatch)\n break;\n }\n }\n\n // Register current position\n this.counters[key]++;\n this.matches[base+(this.counters[key]&this.maskChecks)] = hash32 | (pos-sba.index);\n return (bestLen < MIN_MATCH) ? -1 : (bestIdx<<16) | (bestLen-MIN_MATCH);\n }\n\n\n @Override\n public boolean forward(SliceByteArray input, SliceByteArray output)\n {\n final int count = input.length;\n\n if (output.length - output.index < this.getMaxEncodedLength(count))\n return false;\n\n int srcIdx = input.index;\n int dstIdx = output.index;\n final byte[] src = input.array;\n final byte[] dst = output.array;\n final int srcEnd = srcIdx + count - 4;\n Memory.BigEndian.writeInt32(dst, dstIdx, count);\n dstIdx += 4;\n int sizeChunk = (count <= CHUNK_SIZE) ? count : CHUNK_SIZE;\n int startChunk = srcIdx;\n SliceByteArray sba1 = new SliceByteArray(dst, dstIdx);\n ROLZEncoder re = new ROLZEncoder(9, this.logPosChecks, sba1);\n\n for (int i=0; i>> 16;\n re.setMode(MATCH_FLAG);\n re.setContext(src[srcIdx-1]);\n re.encodeBits(matchIdx, this.logPosChecks);\n re.setMode(LITERAL_FLAG);\n srcIdx += (matchLen+MIN_MATCH);\n }\n\n startChunk = endChunk;\n }\n\n // Emit last literals\n re.setMode(LITERAL_FLAG);\n\n for (int i=0; i<4; i++, srcIdx++)\n {\n re.setContext(src[srcIdx-1]);\n re.encodeBits((LITERAL_FLAG<<8)|(src[srcIdx]&0xFF), 9);\n }\n\n re.dispose();\n input.index = srcIdx;\n output.index = sba1.index;\n return (input.index == srcEnd+4) && (output.index < count);\n }\n\n\n @Override\n public boolean inverse(SliceByteArray input, SliceByteArray output)\n {\n final int count = input.length;\n final byte[] src = input.array;\n final byte[] dst = output.array;\n int srcIdx = input.index;\n final int srcEnd = srcIdx + count;\n final int dstEnd = output.index + Memory.BigEndian.readInt32(src, srcIdx);\n srcIdx += 4;\n int sizeChunk = (dstEnd < CHUNK_SIZE) ? dstEnd : CHUNK_SIZE;\n int startChunk = output.index;\n SliceByteArray sba = new SliceByteArray(src, srcIdx);\n ROLZDecoder rd = new ROLZDecoder(9, this.logPosChecks, sba);\n\n for (int i=0; i>>8) == MATCH_FLAG)\n {\n output.index = dstIdx;\n break;\n }\n\n dst[dstIdx++] = (byte) val1;\n\n if (dstIdx < dstEnd)\n {\n val1 = rd.decodeBits(9);\n\n // Sanity check\n if ((val1>>>8) == MATCH_FLAG)\n {\n output.index = dstIdx;\n break;\n }\n\n dst[dstIdx++] = (byte) val1;\n }\n\n // Next chunk\n while (dstIdx < endChunk)\n {\n final int savedIdx = dstIdx;\n final int key = getKey(dst, dstIdx-2) & 0xFFFF;\n final int base = key << this.logPosChecks;\n rd.setMode(LITERAL_FLAG);\n rd.setContext(dst[dstIdx-1]);\n final int val = rd.decodeBits(9);\n\n if ((val>>>8) == LITERAL_FLAG)\n {\n // Read one literal\n dst[dstIdx++] = (byte) val;\n }\n else\n {\n // Read one match length and index\n final int matchLen = val & 0xFF;\n\n // Sanity check\n if (dstIdx+matchLen+3 > dstEnd)\n {\n output.index = dstIdx;\n break;\n }\n\n rd.setMode(MATCH_FLAG);\n rd.setContext(dst[dstIdx-1]);\n final int matchIdx = rd.decodeBits(this.logPosChecks);\n final int ref = output.index + this.matches[base+((this.counters[key]-matchIdx)&this.maskChecks)];\n dstIdx = emitCopy(dst, dstIdx, ref, matchLen);\n }\n\n // Update map\n this.counters[key]++;\n this.matches[base+(this.counters[key]&this.maskChecks)] = savedIdx - output.index;\n }\n\n startChunk = endChunk;\n output.index = dstIdx;\n }\n\n rd.dispose();\n input.index = sba.index;\n return input.index == srcEnd;\n }\n\n\n @Override\n public int getMaxEncodedLength(int srcLen)\n {\n // Since we do not check the dst index for each byte (for speed purpose)\n // allocate some extra buffer for incompressible data.\n return (srcLen <= 16384) ? srcLen+1024 : srcLen+(srcLen/32);\n }\n }\n\n\n\n static class ROLZEncoder\n {\n private static final long TOP = 0x00FFFFFFFFFFFFFFL;\n private static final long MASK_0_32 = 0x00000000FFFFFFFFL;\n private static final int PSCALE = 0xFFFF;\n private static final int MATCH_FLAG = 0;\n private static final int LITERAL_FLAG = 1;\n\n\n private final SliceByteArray sba;\n private long low;\n private long high;\n private final int[][] probs;\n private final int[] logSizes;\n private int c1;\n private int ctx;\n private int pIdx;\n\n\n public ROLZEncoder(int litLogSize, int mLogSize, SliceByteArray sba)\n {\n this.low = 0L;\n this.high = TOP;\n this.sba = sba;\n this.pIdx = LITERAL_FLAG;\n this.c1 = 1;\n this.probs = new int[2][];\n this.probs[MATCH_FLAG] = new int[256<>1;\n\n final int litLogSize = this.logSizes[LITERAL_FLAG];\n\n for (int i=0; i<(256<>1;\n }\n\n public void setMode(int n)\n {\n this.pIdx = n;\n }\n\n public void setContext(byte ctx)\n {\n this.ctx = (ctx&0xFF) << this.logSizes[this.pIdx];\n }\n\n public final void encodeBits(int val, int n)\n {\n this.c1 = 1;\n\n do\n {\n n--;\n this.encodeBit(val & (1<>>4) * (this.probs[this.pIdx][this.ctx+this.c1]>>>4)) >>> 8;\n\n // Update fields with new interval bounds\n if (bit == 0)\n {\n this.low += (split+1);\n this.probs[this.pIdx][this.ctx+this.c1] -= (this.probs[this.pIdx][this.ctx+this.c1]>>5);\n this.c1 += this.c1;\n }\n else\n {\n this.high = this.low + split;\n this.probs[this.pIdx][this.ctx+this.c1] -= (((this.probs[this.pIdx][this.ctx+this.c1]-0xFFFF)>>5) + 1);\n this.c1 += (this.c1+1);\n }\n\n // Write unchanged first 32 bits to bitstream\n while (((this.low ^ this.high) >>> 24) == 0)\n {\n Memory.BigEndian.writeInt32(this.sba.array, this.sba.index, (int) (this.high>>>32));\n this.sba.index += 4;\n this.low <<= 32;\n this.high = (this.high << 32) | MASK_0_32;\n }\n }\n\n public void dispose()\n {\n for (int i=0; i<8; i++)\n {\n this.sba.array[this.sba.index+i] = (byte) (this.low>>56);\n this.low <<= 8;\n }\n\n this.sba.index += 8;\n }\n }\n\n\n static class ROLZDecoder\n {\n private static final long TOP = 0x00FFFFFFFFFFFFFFL;\n private static final long MASK_0_56 = 0x00FFFFFFFFFFFFFFL;\n private static final long MASK_0_32 = 0x00000000FFFFFFFFL;\n private static final int PSCALE = 0xFFFF;\n private static final int MATCH_FLAG = 0;\n private static final int LITERAL_FLAG = 1;\n\n private final SliceByteArray sba;\n private long low;\n private long high;\n private long current;\n private final int[][] probs;\n private final int[] logSizes;\n private int c1;\n private int ctx;\n private int pIdx;\n\n\n public ROLZDecoder(int litLogSize, int mLogSize, SliceByteArray sba)\n {\n this.low = 0L;\n this.high = TOP;\n this.sba = sba;\n this.current = 0;\n\n for (int i=0; i<8; i++)\n this.current = (this.current<<8) | (long) (this.sba.array[this.sba.index+i] &0xFF);\n\n this.sba.index += 8;\n this.pIdx = LITERAL_FLAG;\n this.c1 = 1;\n this.probs = new int[2][];\n this.probs[MATCH_FLAG] = new int[256<>1;\n\n final int litLogSize = this.logSizes[LITERAL_FLAG];\n\n for (int i=0; i<(256<>1;\n }\n\n public void setMode(int n)\n {\n this.pIdx = n;\n }\n\n public void setContext(byte ctx)\n {\n this.ctx = (ctx&0xFF) << this.logSizes[this.pIdx];\n }\n\n public int decodeBits(int n)\n {\n this.c1 = 1;\n final int mask = (1<>>4) * (this.probs[this.pIdx][this.ctx+this.c1]>>>4)) >>> 8);\n int bit;\n\n // Update bounds and predictor\n if (mid >= this.current)\n {\n bit = 1;\n this.high = mid;\n this.probs[this.pIdx][this.ctx+this.c1] -= (((this.probs[this.pIdx][this.ctx+this.c1]-0xFFFF)>>5) + 1);\n this.c1 += (this.c1+1);\n }\n else\n {\n bit = 0;\n this.low = mid + 1;\n this.probs[this.pIdx][this.ctx+this.c1] -= (this.probs[this.pIdx][this.ctx+this.c1]>>5);\n this.c1 += this.c1;\n }\n\n // Read 32 bits from bitstream\n while (((this.low ^ this.high) >>> 24) == 0)\n {\n this.low = (this.low << 32) & MASK_0_56;\n this.high = ((this.high << 32) | MASK_0_32) & MASK_0_56;\n final long val = Memory.BigEndian.readInt32(this.sba.array, this.sba.index) & MASK_0_32;\n this.current = ((this.current << 32) | val) & MASK_0_56;\n this.sba.index += 4;\n }\n\n return bit;\n }\n\n public void dispose()\n {\n }\n }\n\n}\n"},"message":{"kind":"string","value":"Fix commit cad2b0999.\n"},"old_file":{"kind":"string","value":"java/src/main/java/kanzi/function/ROLZCodec.java"},"subject":{"kind":"string","value":"Fix commit cad2b0999."},"git_diff":{"kind":"string","value":"ava/src/main/java/kanzi/function/ROLZCodec.java\n static class ROLZCodec1 implements ByteFunction\n {\n private static final int MIN_MATCH = 3;\n private static final int MAX_MATCH = MIN_MATCH + 65535 + 7;\n private static final int MAX_MATCH = MIN_MATCH + 65535;\n \n private final int logPosChecks;\n private final int maskChecks;"}}},{"rowIdx":1950,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"3dc04bf2a1671381c4fff5d12990ab1e06b7afed"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"zhaorui1/BroadleafCommerce,gengzhengtao/BroadleafCommerce,cloudbearings/BroadleafCommerce,zhaorui1/BroadleafCommerce,shopizer/BroadleafCommerce,wenmangbo/BroadleafCommerce,arshadalisoomro/BroadleafCommerce,bijukunjummen/BroadleafCommerce,cogitoboy/BroadleafCommerce,udayinfy/BroadleafCommerce,macielbombonato/BroadleafCommerce,passion1014/metaworks_framework,lgscofield/BroadleafCommerce,macielbombonato/BroadleafCommerce,ljshj/BroadleafCommerce,daniellavoie/BroadleafCommerce,SerPenTeHoK/BroadleafCommerce,SerPenTeHoK/BroadleafCommerce,TouK/BroadleafCommerce,macielbombonato/BroadleafCommerce,trombka/blc-tmp,rawbenny/BroadleafCommerce,gengzhengtao/BroadleafCommerce,udayinfy/BroadleafCommerce,passion1014/metaworks_framework,liqianggao/BroadleafCommerce,bijukunjummen/BroadleafCommerce,cengizhanozcan/BroadleafCommerce,daniellavoie/BroadleafCommerce,trombka/blc-tmp,arshadalisoomro/BroadleafCommerce,cengizhanozcan/BroadleafCommerce,liqianggao/BroadleafCommerce,shopizer/BroadleafCommerce,alextiannus/BroadleafCommerce,liqianggao/BroadleafCommerce,cengizhanozcan/BroadleafCommerce,lgscofield/BroadleafCommerce,wenmangbo/BroadleafCommerce,caosg/BroadleafCommerce,zhaorui1/BroadleafCommerce,cloudbearings/BroadleafCommerce,bijukunjummen/BroadleafCommerce,cogitoboy/BroadleafCommerce,alextiannus/BroadleafCommerce,caosg/BroadleafCommerce,gengzhengtao/BroadleafCommerce,jiman94/BroadleafCommerce-BroadleafCommerce2014,sitexa/BroadleafCommerce,rawbenny/BroadleafCommerce,cogitoboy/BroadleafCommerce,arshadalisoomro/BroadleafCommerce,jiman94/BroadleafCommerce-BroadleafCommerce2014,ljshj/BroadleafCommerce,sanlingdd/broadleaf,trombka/blc-tmp,sitexa/BroadleafCommerce,cloudbearings/BroadleafCommerce,sanlingdd/broadleaf,rawbenny/BroadleafCommerce,SerPenTeHoK/BroadleafCommerce,sitexa/BroadleafCommerce,TouK/BroadleafCommerce,ljshj/BroadleafCommerce,shopizer/BroadleafCommerce,alextiannus/BroadleafCommerce,udayinfy/BroadleafCommerce,caosg/BroadleafCommerce,wenmangbo/BroadleafCommerce,lgscofield/BroadleafCommerce,TouK/BroadleafCommerce,passion1014/metaworks_framework,daniellavoie/BroadleafCommerce"},"new_contents":{"kind":"string","value":"/*\n * Copyright 2008-2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.broadleafcommerce.core.order.service;\n\nimport org.apache.commons.beanutils.BeanUtils;\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\nimport org.broadleafcommerce.core.catalog.dao.CategoryDao;\nimport org.broadleafcommerce.core.catalog.dao.ProductDao;\nimport org.broadleafcommerce.core.catalog.dao.SkuDao;\nimport org.broadleafcommerce.core.catalog.domain.Category;\nimport org.broadleafcommerce.core.catalog.domain.Product;\nimport org.broadleafcommerce.core.catalog.domain.ProductBundle;\nimport org.broadleafcommerce.core.catalog.domain.Sku;\nimport org.broadleafcommerce.core.catalog.domain.SkuAttribute;\nimport org.broadleafcommerce.core.catalog.domain.SkuBundleItem;\nimport org.broadleafcommerce.core.offer.dao.OfferDao;\nimport org.broadleafcommerce.core.offer.domain.OfferCode;\nimport org.broadleafcommerce.core.offer.service.OfferService;\nimport org.broadleafcommerce.core.offer.service.exception.OfferMaxUseExceededException;\nimport org.broadleafcommerce.core.order.dao.FulfillmentGroupDao;\nimport org.broadleafcommerce.core.order.dao.FulfillmentGroupItemDao;\nimport org.broadleafcommerce.core.order.dao.OrderDao;\nimport org.broadleafcommerce.core.order.dao.OrderItemDao;\nimport org.broadleafcommerce.core.order.domain.BundleOrderItem;\nimport org.broadleafcommerce.core.order.domain.DiscreteOrderItem;\nimport org.broadleafcommerce.core.order.domain.FulfillmentGroup;\nimport org.broadleafcommerce.core.order.domain.FulfillmentGroupItem;\nimport org.broadleafcommerce.core.order.domain.GiftWrapOrderItem;\nimport org.broadleafcommerce.core.order.domain.Order;\nimport org.broadleafcommerce.core.order.domain.OrderItem;\nimport org.broadleafcommerce.core.order.domain.OrderItemAttribute;\nimport org.broadleafcommerce.core.order.domain.OrderItemAttributeImpl;\nimport org.broadleafcommerce.core.order.domain.PersonalMessage;\nimport org.broadleafcommerce.core.order.service.call.BundleOrderItemRequest;\nimport org.broadleafcommerce.core.order.service.call.DiscreteOrderItemRequest;\nimport org.broadleafcommerce.core.order.service.call.FulfillmentGroupItemRequest;\nimport org.broadleafcommerce.core.order.service.call.FulfillmentGroupRequest;\nimport org.broadleafcommerce.core.order.service.call.GiftWrapOrderItemRequest;\nimport org.broadleafcommerce.core.order.service.call.OrderItemRequestDTO;\nimport org.broadleafcommerce.core.order.service.exception.ItemNotFoundException;\nimport org.broadleafcommerce.core.order.service.type.OrderItemType;\nimport org.broadleafcommerce.core.order.service.type.OrderStatus;\nimport org.broadleafcommerce.core.payment.dao.PaymentInfoDao;\nimport org.broadleafcommerce.core.payment.domain.PaymentInfo;\nimport org.broadleafcommerce.core.payment.domain.Referenced;\nimport org.broadleafcommerce.core.payment.service.SecurePaymentInfoService;\nimport org.broadleafcommerce.core.payment.service.type.PaymentInfoType;\nimport org.broadleafcommerce.core.pricing.service.PricingService;\nimport org.broadleafcommerce.core.pricing.service.exception.PricingException;\nimport org.broadleafcommerce.core.workflow.WorkflowException;\nimport org.broadleafcommerce.profile.core.domain.Address;\nimport org.broadleafcommerce.profile.core.domain.Customer;\n\nimport javax.annotation.Resource;\nimport java.lang.reflect.InvocationTargetException;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\n\npublic class OrderServiceImpl implements OrderService {\n\n private static final Log LOG = LogFactory.getLog(OrderServiceImpl.class);\n\n @Resource(name = \"blOrderDao\")\n protected OrderDao orderDao;\n\n @Resource(name = \"blPaymentInfoDao\")\n protected PaymentInfoDao paymentInfoDao;\n\n @Resource(name = \"blFulfillmentGroupDao\")\n protected FulfillmentGroupDao fulfillmentGroupDao;\n\n @Resource(name = \"blFulfillmentGroupItemDao\")\n protected FulfillmentGroupItemDao fulfillmentGroupItemDao;\n\n @Resource(name = \"blOfferDao\")\n protected OfferDao offerDao;\n\n @Resource(name = \"blOrderItemService\")\n protected OrderItemService orderItemService;\n\n @Resource(name = \"blOrderItemDao\")\n protected OrderItemDao orderItemDao;\n\n @Resource(name = \"blSkuDao\")\n protected SkuDao skuDao;\n\n @Resource(name = \"blProductDao\")\n protected ProductDao productDao;\n\n @Resource(name = \"blCategoryDao\")\n protected CategoryDao categoryDao;\n\n @Resource(name = \"blFulfillmentGroupService\")\n protected FulfillmentGroupService fulfillmentGroupService;\n\n @Resource(name = \"blSecurePaymentInfoService\")\n protected SecurePaymentInfoService securePaymentInfoService;\n \n @Resource(name = \"blOfferService\")\n protected OfferService offerService;\n\n @Resource(name = \"blPricingService\")\n protected PricingService pricingService;\n\n protected boolean automaticallyMergeLikeItems = true;\n\n public Order createNamedOrderForCustomer(String name, Customer customer) {\n Order namedOrder = orderDao.create();\n namedOrder.setCustomer(customer);\n namedOrder.setName(name);\n namedOrder.setStatus(OrderStatus.NAMED);\n return persistOrder(namedOrder);\n }\n\n public Order save(Order order, Boolean priceOrder) throws PricingException {\n return updateOrder(order, priceOrder);\n }\n\n public Order findOrderById(Long orderId) {\n return orderDao.readOrderById(orderId);\n }\n\n public List findOrdersForCustomer(Customer customer) {\n return orderDao.readOrdersForCustomer(customer.getId());\n }\n\n public List findOrdersForCustomer(Customer customer, OrderStatus status) {\n return orderDao.readOrdersForCustomer(customer, status);\n }\n\n public Order findNamedOrderForCustomer(String name, Customer customer) {\n return orderDao.readNamedOrderForCustomer(customer, name);\n }\n\n public FulfillmentGroup findDefaultFulfillmentGroupForOrder(Order order) {\n FulfillmentGroup fg = fulfillmentGroupDao.readDefaultFulfillmentGroupForOrder(order);\n\n return fg;\n }\n\n public OrderItem addSkuToOrder(Long orderId, Long skuId, Long productId, Long categoryId, Integer quantity) throws PricingException {\n \treturn addSkuToOrder(orderId, skuId, productId, categoryId, quantity, true, null);\n }\n \n public OrderItem addSkuToOrder(Long orderId, Long skuId, Long productId, Long categoryId, Integer quantity, Map itemAttributes) throws PricingException {\n \treturn addSkuToOrder(orderId, skuId, productId, categoryId, quantity, true, itemAttributes);\n }\n \n public OrderItem addSkuToOrder(Long orderId, Long skuId, Long productId, Long categoryId, Integer quantity, boolean priceOrder) throws PricingException {\n return addSkuToOrder(orderId, skuId, productId, categoryId, quantity, priceOrder, null);\n }\n\n public OrderItem addSkuToOrder(Long orderId, Long skuId, Long productId, Long categoryId, Integer quantity, boolean priceOrder, Map itemAttributes) throws PricingException {\n if (orderId == null || (productId == null && skuId == null) || quantity == null) {\n return null;\n }\n\n OrderItemRequestDTO requestDTO = new OrderItemRequestDTO();\n requestDTO.setCategoryId(categoryId);\n requestDTO.setProductId(productId);\n requestDTO.setSkuId(skuId);\n requestDTO.setQuantity(quantity);\n requestDTO.setItemAttributes(itemAttributes);\n\n Order order = addItemToOrder(orderId, requestDTO, priceOrder);\n if (order == null) {\n return null;\n }\n return findLastMatchingItem(order, skuId, productId);\n }\n\n public OrderItem addDiscreteItemToOrder(Order order, DiscreteOrderItemRequest itemRequest) throws PricingException {\n \treturn addDiscreteItemToOrder(order, itemRequest, true);\n }\n\n public OrderItem addDiscreteItemToOrder(Order order, DiscreteOrderItemRequest itemRequest, boolean priceOrder) throws PricingException {\n DiscreteOrderItem item = orderItemService.createDiscreteOrderItem(itemRequest);\n return addOrderItemToOrder(order, item, priceOrder);\n }\n\n public OrderItem addDynamicPriceDiscreteItemToOrder(Order order, DiscreteOrderItemRequest itemRequest, @SuppressWarnings(\"rawtypes\") HashMap skuPricingConsiderations) throws PricingException {\n \treturn addDynamicPriceDiscreteItemToOrder(order, itemRequest, skuPricingConsiderations, true);\n }\n\n public OrderItem addDynamicPriceDiscreteItemToOrder(Order order, DiscreteOrderItemRequest itemRequest, @SuppressWarnings(\"rawtypes\") HashMap skuPricingConsiderations, boolean priceOrder) throws PricingException {\n DiscreteOrderItem item = orderItemService.createDynamicPriceDiscreteOrderItem(itemRequest, skuPricingConsiderations);\n return addOrderItemToOrder(order, item, priceOrder);\n }\n \n public OrderItem addGiftWrapItemToOrder(Order order, GiftWrapOrderItemRequest itemRequest) throws PricingException {\n \treturn addGiftWrapItemToOrder(order, itemRequest, true);\n }\n\n public OrderItem addGiftWrapItemToOrder(Order order, GiftWrapOrderItemRequest itemRequest, boolean priceOrder) throws PricingException {\n GiftWrapOrderItem item = orderItemService.createGiftWrapOrderItem(itemRequest);\n return addOrderItemToOrder(order, item, priceOrder);\n }\n \n public OrderItem addBundleItemToOrder(Order order, BundleOrderItemRequest itemRequest) throws PricingException {\n \treturn addBundleItemToOrder(order, itemRequest, true);\n }\n\n public OrderItem addBundleItemToOrder(Order order, BundleOrderItemRequest itemRequest, boolean priceOrder) throws PricingException {\n BundleOrderItem item = orderItemService.createBundleOrderItem(itemRequest);\n return addOrderItemToOrder(order, item, priceOrder);\n }\n \n public Order removeItemFromOrder(Long orderId, Long itemId) throws PricingException {\n \treturn removeItemFromOrder(orderId, itemId, true);\n }\n\n public Order removeItemFromOrder(Long orderId, Long itemId, boolean priceOrder) throws PricingException {\n Order order = findOrderById(orderId);\n OrderItem orderItem = orderItemService.readOrderItemById(itemId);\n\n return removeItemFromOrder(order, orderItem, priceOrder);\n }\n \n public Order removeItemFromOrder(Order order, OrderItem item) throws PricingException {\n \treturn removeItemFromOrder(order, item, true);\n }\n\n public Order removeItemFromOrder(Order order, OrderItem item, boolean priceOrder) throws PricingException {\n removeOrderItemFromFullfillmentGroup(order, item);\n OrderItem itemFromOrder = order.getOrderItems().remove(order.getOrderItems().indexOf(item));\n itemFromOrder.setOrder(null);\n orderItemService.delete(itemFromOrder);\n order = updateOrder(order, priceOrder);\n return order;\n }\n \n public Order moveItemToOrder(Order originalOrder, Order destinationOrder, OrderItem item) throws PricingException {\n \treturn moveItemToOrder(originalOrder, destinationOrder, item, true);\n }\n \n public Order moveItemToOrder(Order originalOrder, Order destinationOrder, OrderItem item, boolean priceOrder) throws PricingException {\n \tremoveOrderItemFromFullfillmentGroup(originalOrder, item);\n \tOrderItem itemFromOrder = originalOrder.getOrderItems().remove(originalOrder.getOrderItems().indexOf(item));\n \titemFromOrder.setOrder(null);\n \toriginalOrder = updateOrder(originalOrder, priceOrder);\n \taddOrderItemToOrder(destinationOrder, item, priceOrder);\n \treturn destinationOrder;\n }\n\n public PaymentInfo addPaymentToOrder(Order order, PaymentInfo payment) {\n return addPaymentToOrder(order, payment, null);\n }\n\n public PaymentInfo addPaymentToOrder(Order order, PaymentInfo payment, Referenced securePaymentInfo) {\n payment.setOrder(order);\n order.getPaymentInfos().add(payment);\n order = persistOrder(order);\n int paymentIndex = order.getPaymentInfos().size() - 1;\n\n if (securePaymentInfo != null) {\n securePaymentInfoService.save(securePaymentInfo);\n }\n\n return order.getPaymentInfos().get(paymentIndex);\n }\n\n public void removeAllPaymentsFromOrder(Order order) {\n removePaymentsFromOrder(order, null);\n }\n\n public void removePaymentsFromOrder(Order order, PaymentInfoType paymentInfoType) {\n List infos = new ArrayList();\n for (PaymentInfo paymentInfo : order.getPaymentInfos()) {\n if (paymentInfoType == null || paymentInfoType.equals(paymentInfo.getType())) {\n infos.add(paymentInfo);\n }\n }\n order.getPaymentInfos().removeAll(infos);\n for (PaymentInfo paymentInfo : infos) {\n try {\n securePaymentInfoService.findAndRemoveSecurePaymentInfo(paymentInfo.getReferenceNumber(), paymentInfo.getType());\n } catch (WorkflowException e) {\n // do nothing--this is an acceptable condition\n LOG.debug(\"No secure payment is associated with the PaymentInfo\", e);\n }\n order.getPaymentInfos().remove(paymentInfo);\n paymentInfo = paymentInfoDao.readPaymentInfoById(paymentInfo.getId());\n paymentInfoDao.delete(paymentInfo);\n }\n }\n \n public FulfillmentGroup addFulfillmentGroupToOrder(FulfillmentGroupRequest fulfillmentGroupRequest) throws PricingException {\n \treturn addFulfillmentGroupToOrder(fulfillmentGroupRequest, true);\n }\n\n public FulfillmentGroup addFulfillmentGroupToOrder(FulfillmentGroupRequest fulfillmentGroupRequest, boolean priceOrder) throws PricingException {\n FulfillmentGroup fg = fulfillmentGroupDao.create();\n fg.setAddress(fulfillmentGroupRequest.getAddress());\n fg.setOrder(fulfillmentGroupRequest.getOrder());\n fg.setPhone(fulfillmentGroupRequest.getPhone());\n fg.setMethod(fulfillmentGroupRequest.getMethod());\n fg.setService(fulfillmentGroupRequest.getService());\n\n for (int i=0; i< fulfillmentGroupRequest.getFulfillmentGroupItemRequests().size(); i++) {\n FulfillmentGroupItemRequest request = fulfillmentGroupRequest.getFulfillmentGroupItemRequests().get(i);\n boolean shouldPriceOrder = (priceOrder && (i == (fulfillmentGroupRequest.getFulfillmentGroupItemRequests().size() - 1)));\n fg = addItemToFulfillmentGroup(request.getOrderItem(), fg, request.getQuantity(), shouldPriceOrder);\n }\n\n return fg;\n }\n \n public FulfillmentGroup addFulfillmentGroupToOrder(Order order, FulfillmentGroup fulfillmentGroup) throws PricingException {\n \treturn addFulfillmentGroupToOrder(order, fulfillmentGroup, true);\n }\n\n public FulfillmentGroup addFulfillmentGroupToOrder(Order order, FulfillmentGroup fulfillmentGroup, boolean priceOrder) throws PricingException {\n FulfillmentGroup dfg = findDefaultFulfillmentGroupForOrder(order);\n if (dfg == null) {\n fulfillmentGroup.setPrimary(true);\n } else if (dfg.equals(fulfillmentGroup)) {\n // API user is trying to re-add the default fulfillment group to the\n // same order\n fulfillmentGroup.setPrimary(true);\n order.getFulfillmentGroups().remove(dfg);\n // fulfillmentGroupDao.delete(dfg);\n }\n\n fulfillmentGroup.setOrder(order);\n // 1) For each item in the new fulfillment group\n for (FulfillmentGroupItem fgItem : fulfillmentGroup.getFulfillmentGroupItems()) {\n // 2) Find the item's existing fulfillment group\n for (FulfillmentGroup fg : order.getFulfillmentGroups()) {\n // If the existing fulfillment group is different than passed in\n // fulfillment group\n if (!fg.equals(fulfillmentGroup)) {\n // 3) remove item from it's existing fulfillment\n // group\n fg.getFulfillmentGroupItems().remove(fgItem);\n }\n }\n }\n fulfillmentGroup = fulfillmentGroupDao.save(fulfillmentGroup);\n order.getFulfillmentGroups().add(fulfillmentGroup);\n int fulfillmentGroupIndex = order.getFulfillmentGroups().size() - 1;\n order = updateOrder(order, priceOrder);\n return order.getFulfillmentGroups().get(fulfillmentGroupIndex);\n }\n \n public FulfillmentGroup addItemToFulfillmentGroup(OrderItem item, FulfillmentGroup fulfillmentGroup, int quantity) throws PricingException {\n \treturn addItemToFulfillmentGroup(item, fulfillmentGroup, quantity, true);\n }\n\n public FulfillmentGroup addItemToFulfillmentGroup(OrderItem item, FulfillmentGroup fulfillmentGroup, int quantity, boolean priceOrder) throws PricingException {\n return addItemToFulfillmentGroup(item.getOrder(), item, fulfillmentGroup, quantity, priceOrder);\n }\n\n public FulfillmentGroup addItemToFulfillmentGroup(Order order, OrderItem item, FulfillmentGroup fulfillmentGroup, int quantity, boolean priceOrder) throws PricingException {\n\n // 1) Find the item's existing fulfillment group, if any\n for (FulfillmentGroup fg : order.getFulfillmentGroups()) {\n Iterator itr = fg.getFulfillmentGroupItems().iterator();\n while (itr.hasNext()) {\n FulfillmentGroupItem fgItem = itr.next();\n if (fgItem.getOrderItem().equals(item)) {\n // 2) remove item from it's existing fulfillment group\n itr.remove();\n fulfillmentGroupItemDao.delete(fgItem);\n }\n }\n }\n\n if (fulfillmentGroup.getId() == null) {\n // API user is trying to add an item to a fulfillment group not created\n fulfillmentGroup = addFulfillmentGroupToOrder(order, fulfillmentGroup, priceOrder);\n }\n\n FulfillmentGroupItem fgi = createFulfillmentGroupItemFromOrderItem(item, fulfillmentGroup, quantity);\n fgi = fulfillmentGroupItemDao.save(fgi);\n\n // 3) add the item to the new fulfillment group\n fulfillmentGroup.addFulfillmentGroupItem(fgi);\n order = updateOrder(order, priceOrder);\n\n return fulfillmentGroup;\n }\n\n public FulfillmentGroup addItemToFulfillmentGroup(OrderItem item, FulfillmentGroup fulfillmentGroup) throws PricingException {\n \treturn addItemToFulfillmentGroup(item, fulfillmentGroup, true);\n }\n\n public FulfillmentGroup addItemToFulfillmentGroup(OrderItem item, FulfillmentGroup fulfillmentGroup, boolean priceOrder) throws PricingException {\n return addItemToFulfillmentGroup(item, fulfillmentGroup, item.getQuantity(), priceOrder);\n }\n \n public void updateItemQuantity(Order order, OrderItem item) throws ItemNotFoundException, PricingException {\n \tupdateItemQuantity(order, item, true);\n }\n\n public void updateItemQuantity(Order order, OrderItem item, boolean priceOrder) throws ItemNotFoundException, PricingException {\n if (!order.getOrderItems().contains(item)) {\n throw new ItemNotFoundException(\"Order Item (\" + item.getId() + \") not found in Order (\" + order.getId() + \")\");\n }\n OrderItem itemFromOrder = order.getOrderItems().get(order.getOrderItems().indexOf(item));\n itemFromOrder.setQuantity(item.getQuantity());\n order = updateOrder(order, priceOrder);\n\n }\n\n public void removeAllFulfillmentGroupsFromOrder(Order order) throws PricingException {\n removeAllFulfillmentGroupsFromOrder(order, false);\n }\n\n public void removeAllFulfillmentGroupsFromOrder(Order order, boolean priceOrder) throws PricingException {\n if (order.getFulfillmentGroups() != null) {\n for (Iterator iterator = order.getFulfillmentGroups().iterator(); iterator.hasNext();) {\n FulfillmentGroup fulfillmentGroup = iterator.next();\n iterator.remove();\n fulfillmentGroupDao.delete(fulfillmentGroup);\n }\n updateOrder(order, priceOrder);\n }\n }\n \n public void removeFulfillmentGroupFromOrder(Order order, FulfillmentGroup fulfillmentGroup) throws PricingException {\n \tremoveFulfillmentGroupFromOrder(order, fulfillmentGroup, true);\n }\n\n @Override\n public void removeFulfillmentGroupFromOrder(Order order, FulfillmentGroup fulfillmentGroup, boolean priceOrder) throws PricingException {\n order.getFulfillmentGroups().remove(fulfillmentGroup);\n fulfillmentGroupDao.delete(fulfillmentGroup);\n updateOrder(order, priceOrder);\n }\n\n @Override\n public Order addOfferCode(Order order, OfferCode offerCode, boolean priceOrder) throws PricingException, OfferMaxUseExceededException {\n if( !order.getAddedOfferCodes().contains(offerCode)) {\n if (! offerService.verifyMaxCustomerUsageThreshold(order.getCustomer(), offerCode.getOffer())) {\n throw new OfferMaxUseExceededException(\"The customer has used this offer code more than the maximum allowed number of times.\");\n }\n order.getAddedOfferCodes().add(offerCode);\n order = updateOrder(order, priceOrder);\n }\n return order;\n }\n\n @Override\n public Order removeOfferCode(Order order, OfferCode offerCode, boolean priceOrder) throws PricingException {\n order.getAddedOfferCodes().remove(offerCode);\n order = updateOrder(order, priceOrder);\n return order;\n }\n\n @Override\n public Order removeAllOfferCodes(Order order, boolean priceOrder) throws PricingException {\n order.getAddedOfferCodes().clear();\n order = updateOrder(order, priceOrder);\n return order;\n }\n\n public void removeNamedOrderForCustomer(String name, Customer customer) {\n Order namedOrder = findNamedOrderForCustomer(name, customer);\n cancelOrder(namedOrder);\n }\n\n public Order confirmOrder(Order order) {\n return orderDao.submitOrder(order);\n }\n\n public void cancelOrder(Order order) {\n orderDao.delete(order);\n }\n\n public List readPaymentInfosForOrder(Order order) {\n return paymentInfoDao.readPaymentInfosForOrder(order);\n }\n \n public OrderItem addOrderItemToOrder(Order order, OrderItem newOrderItem) throws PricingException {\n List orderItems = order.getOrderItems();\n orderItems.add(newOrderItem);\n newOrderItem.setOrder(order);\n order = updateOrder(order, true);\n return findLastMatchingItem(order, newOrderItem);\n }\n\n private boolean itemMatches(DiscreteOrderItem item1, DiscreteOrderItem item2) {\n // Must match on SKU and options\n if (item1.getSku() != null && item2.getSku() != null) {\n if (item1.getSku().getId().equals(item2.getSku().getId())) {\n // TODO: Compare options if product has product options\n return true;\n }\n } else {\n if (item1.getProduct() != null && item2.getProduct() != null) {\n if (item1.getProduct().getId().equals(item2.getProduct().getId())) {\n return true;\n }\n }\n }\n return false;\n }\n\n private OrderItem findLastMatchingDiscreteItem(Order order, DiscreteOrderItem itemToFind) {\n for (int i=(order.getOrderItems().size()-1); i >= 0; i--) {\n OrderItem currentItem = (order.getOrderItems().get(i));\n if (currentItem instanceof DiscreteOrderItem) {\n DiscreteOrderItem discreteItem = (DiscreteOrderItem) currentItem;\n if (itemMatches(discreteItem, itemToFind)) {\n return discreteItem;\n }\n\n } else if (currentItem instanceof BundleOrderItem) {\n for (DiscreteOrderItem discreteItem : (((BundleOrderItem) currentItem).getDiscreteOrderItems())) {\n if (itemMatches(discreteItem, itemToFind)) {\n return discreteItem;\n }\n }\n }\n }\n return null;\n }\n\n private boolean bundleItemMatches(BundleOrderItem item1, BundleOrderItem item2) {\n if (item1.getSku() != null && item2.getSku() != null) {\n return item1.getSku().getId().equals(item2.getSku().getId());\n }\n\n // Otherwise, scan the items.\n HashMap skuMap = new HashMap();\n for(DiscreteOrderItem item : item1.getDiscreteOrderItems()) {\n if (skuMap.get(item.getSku().getId()) == null) {\n skuMap.put(item.getSku().getId(), Integer.valueOf(item.getQuantity()));\n } else {\n Integer qty = skuMap.get(item.getSku().getId());\n skuMap.put(item.getSku().getId(), Integer.valueOf(qty + item.getQuantity()));\n }\n }\n\n // Now consume the quantities in the map\n for(DiscreteOrderItem item : item2.getDiscreteOrderItems()) {\n if (skuMap.containsKey(item.getSku().getId())) {\n Integer qty = skuMap.get(item.getSku().getId());\n Integer newQty = Integer.valueOf(qty - item.getQuantity());\n if (newQty.intValue() == 0) {\n skuMap.remove(item.getSku().getId());\n } else if (newQty.intValue() > 0) {\n skuMap.put(item.getSku().getId(), newQty);\n } else {\n return false;\n }\n } else {\n return false;\n }\n }\n\n return skuMap.isEmpty();\n }\n\n\n private OrderItem findLastMatchingBundleItem(Order order, BundleOrderItem itemToFind) {\n for (int i=(order.getOrderItems().size()-1); i >= 0; i--) {\n OrderItem currentItem = (order.getOrderItems().get(i));\n if (currentItem instanceof BundleOrderItem) {\n if (bundleItemMatches((BundleOrderItem) currentItem, itemToFind)) {\n return currentItem;\n }\n }\n }\n return null;\n }\n\n private OrderItem findLastMatchingItem(Order order, OrderItem itemToFind) {\n if (itemToFind instanceof BundleOrderItem) {\n return findLastMatchingBundleItem(order, (BundleOrderItem) itemToFind);\n } else if (itemToFind instanceof DiscreteOrderItem) {\n return findLastMatchingDiscreteItem(order, (DiscreteOrderItem) itemToFind);\n } else {\n return null;\n }\n }\n\n private OrderItem findLastMatchingItem(Order order,Long skuId, Long productId) {\n if (order.getOrderItems() != null) {\n for (int i=(order.getOrderItems().size()-1); i >= 0; i--) {\n OrderItem currentItem = (order.getOrderItems().get(i));\n if (currentItem instanceof DiscreteOrderItem) {\n DiscreteOrderItem discreteItem = (DiscreteOrderItem) currentItem;\n if (skuId != null) {\n if (discreteItem.getSku() != null && skuId.equals(discreteItem.getSku().getId())) {\n return discreteItem;\n }\n } else if (productId != null && discreteItem.getProduct() != null && productId.equals(discreteItem.getProduct().getId())) {\n return discreteItem;\n }\n\n } else if (currentItem instanceof BundleOrderItem) {\n BundleOrderItem bundleItem = (BundleOrderItem) currentItem;\n if (skuId != null) {\n if (bundleItem.getSku() != null && skuId.equals(bundleItem.getSku().getId())) {\n return bundleItem;\n }\n } else if (productId != null && bundleItem.getProduct() != null && productId.equals(bundleItem.getProduct().getId())) {\n return bundleItem;\n }\n }\n }\n }\n return null;\n }\n \t\n public OrderItem addOrderItemToOrder(Order order, OrderItem newOrderItem, boolean priceOrder) throws PricingException {\n List orderItems = order.getOrderItems();\n orderItems.add(newOrderItem);\n newOrderItem.setOrder(order);\n order = updateOrder(order, priceOrder);\n return findLastMatchingItem(order, newOrderItem);\n }\n \n public OrderItem addOrderItemToBundle(Order order, BundleOrderItem bundle, DiscreteOrderItem newOrderItem, boolean priceOrder) throws PricingException {\n List orderItems = bundle.getDiscreteOrderItems();\n orderItems.add(newOrderItem);\n newOrderItem.setBundleOrderItem(bundle);\n\n order = updateOrder(order, priceOrder);\n\n return findLastMatchingItem(order, bundle);\n }\n \n public Order removeItemFromBundle(Order order, BundleOrderItem bundle, OrderItem item, boolean priceOrder) throws PricingException {\n DiscreteOrderItem itemFromBundle = bundle.getDiscreteOrderItems().remove(bundle.getDiscreteOrderItems().indexOf(item));\n orderItemService.delete(itemFromBundle);\n itemFromBundle.setBundleOrderItem(null);\n order = updateOrder(order, priceOrder);\n \n return order;\n }\n\n /**\n * Adds the passed in name/value pair to the order-item. If the\n * attribute already exists, then it is updated with the new value.\n *

\n * If the value passed in is null and the attribute exists, it is removed\n * from the order item.\n *\n * @param order\n * @param item\n * @param attributeValues\n * @param priceOrder\n * @return\n */\n @Override\n public Order addOrUpdateOrderItemAttributes(Order order, OrderItem item, Map attributeValues, boolean priceOrder) throws ItemNotFoundException, PricingException {\n if (!order.getOrderItems().contains(item)) {\n throw new ItemNotFoundException(\"Order Item (\" + item.getId() + \") not found in Order (\" + order.getId() + \")\");\n }\n OrderItem itemFromOrder = order.getOrderItems().get(order.getOrderItems().indexOf(item));\n \n Map orderItemAttributes = itemFromOrder.getOrderItemAttributes();\n if (orderItemAttributes == null) {\n orderItemAttributes = new HashMap();\n itemFromOrder.setOrderItemAttributes(orderItemAttributes);\n }\n \n boolean changeMade = false;\n for (String attributeName : attributeValues.keySet()) {\n String attributeValue = attributeValues.get(attributeName);\n OrderItemAttribute attribute = orderItemAttributes.get(attributeName);\n if (attribute != null && attribute.getValue().equals(attributeValue)) {\n // no change made.\n continue;\n } else {\n changeMade = true;\n if (attribute == null) {\n attribute = new OrderItemAttributeImpl();\n attribute.setOrderItem(itemFromOrder);\n attribute.setName(attributeName);\n attribute.setValue(attributeValue);\n } else if (attributeValue == null) {\n orderItemAttributes.remove(attributeValue);\n } else {\n attribute.setValue(attributeValue);\n }\n }\n }\n\n if (changeMade) {\n return updateOrder(order, priceOrder);\n } else {\n return order;\n }\n }\n\n public Order removeOrderItemAttribute(Order order, OrderItem item, String attributeName, boolean priceOrder) throws ItemNotFoundException, PricingException {\n if (!order.getOrderItems().contains(item)) {\n throw new ItemNotFoundException(\"Order Item (\" + item.getId() + \") not found in Order (\" + order.getId() + \")\");\n }\n OrderItem itemFromOrder = order.getOrderItems().get(order.getOrderItems().indexOf(item));\n\n boolean changeMade = false;\n Map orderItemAttributes = itemFromOrder.getOrderItemAttributes();\n if (orderItemAttributes != null) {\n if (orderItemAttributes.containsKey(attributeName)) {\n changeMade = true;\n orderItemAttributes.remove(attributeName);\n }\n }\n\n if (changeMade) {\n return updateOrder(order, priceOrder);\n } else {\n return order;\n }\n }\n\n public FulfillmentGroup createDefaultFulfillmentGroup(Order order, Address address) {\n for (FulfillmentGroup fulfillmentGroup : order.getFulfillmentGroups()) {\n if (fulfillmentGroup.isPrimary()) {\n return fulfillmentGroup;\n }\n }\n\n FulfillmentGroup newFg = fulfillmentGroupService.createEmptyFulfillmentGroup();\n newFg.setOrder(order);\n newFg.setPrimary(true);\n newFg.setAddress(address);\n for (OrderItem orderItem : order.getOrderItems()) {\n newFg.addFulfillmentGroupItem(createFulfillmentGroupItemFromOrderItem(orderItem, newFg, orderItem.getQuantity()));\n }\n return newFg;\n }\n\n public OrderDao getOrderDao() {\n return orderDao;\n }\n\n public void setOrderDao(OrderDao orderDao) {\n this.orderDao = orderDao;\n }\n\n public PaymentInfoDao getPaymentInfoDao() {\n return paymentInfoDao;\n }\n\n public void setPaymentInfoDao(PaymentInfoDao paymentInfoDao) {\n this.paymentInfoDao = paymentInfoDao;\n }\n\n public FulfillmentGroupDao getFulfillmentGroupDao() {\n return fulfillmentGroupDao;\n }\n\n public void setFulfillmentGroupDao(FulfillmentGroupDao fulfillmentGroupDao) {\n this.fulfillmentGroupDao = fulfillmentGroupDao;\n }\n\n public FulfillmentGroupItemDao getFulfillmentGroupItemDao() {\n return fulfillmentGroupItemDao;\n }\n\n public void setFulfillmentGroupItemDao(FulfillmentGroupItemDao fulfillmentGroupItemDao) {\n this.fulfillmentGroupItemDao = fulfillmentGroupItemDao;\n }\n\n public OrderItemService getOrderItemService() {\n return orderItemService;\n }\n\n public void setOrderItemService(OrderItemService orderItemService) {\n this.orderItemService = orderItemService;\n }\n\n public Order findOrderByOrderNumber(String orderNumber) {\n return orderDao.readOrderByOrderNumber(orderNumber);\n }\n\n protected Order updateOrder(Order order, Boolean priceOrder) throws PricingException {\n if (priceOrder) {\n order = pricingService.executePricing(order);\n }\n return persistOrder(order);\n }\n\n\n protected Order persistOrder(Order order) {\n return orderDao.save(order);\n }\n\n protected FulfillmentGroupItem createFulfillmentGroupItemFromOrderItem(OrderItem orderItem, FulfillmentGroup fulfillmentGroup, int quantity) {\n FulfillmentGroupItem fgi = fulfillmentGroupItemDao.create();\n fgi.setFulfillmentGroup(fulfillmentGroup);\n fgi.setOrderItem(orderItem);\n fgi.setQuantity(quantity);\n return fgi;\n }\n\n protected void removeOrderItemFromFullfillmentGroup(Order order, OrderItem orderItem) {\n List fulfillmentGroups = order.getFulfillmentGroups();\n for (FulfillmentGroup fulfillmentGroup : fulfillmentGroups) {\n Iterator itr = fulfillmentGroup.getFulfillmentGroupItems().iterator();\n while (itr.hasNext()) {\n FulfillmentGroupItem fulfillmentGroupItem = itr.next();\n if (fulfillmentGroupItem.getOrderItem().equals(orderItem)) {\n itr.remove();\n fulfillmentGroupItemDao.delete(fulfillmentGroupItem);\n }\n }\n }\n }\n\n protected DiscreteOrderItemRequest createDiscreteOrderItemRequest(DiscreteOrderItem discreteOrderItem) {\n DiscreteOrderItemRequest itemRequest = new DiscreteOrderItemRequest();\n itemRequest.setCategory(discreteOrderItem.getCategory());\n itemRequest.setProduct(discreteOrderItem.getProduct());\n itemRequest.setQuantity(discreteOrderItem.getQuantity());\n itemRequest.setSku(discreteOrderItem.getSku());\n \n if (discreteOrderItem.getPersonalMessage() != null) {\n PersonalMessage personalMessage = orderItemService.createPersonalMessage();\n try {\n BeanUtils.copyProperties(personalMessage, discreteOrderItem.getPersonalMessage());\n personalMessage.setId(null);\n } catch (IllegalAccessException e) {\n throw new RuntimeException(e);\n } catch (InvocationTargetException e) {\n throw new RuntimeException(e);\n }\n itemRequest.setPersonalMessage(personalMessage);\n }\n \n return itemRequest;\n }\n\n protected BundleOrderItemRequest createBundleOrderItemRequest(BundleOrderItem bundleOrderItem, List discreteOrderItemRequests) {\n BundleOrderItemRequest bundleOrderItemRequest = new BundleOrderItemRequest();\n bundleOrderItemRequest.setCategory(bundleOrderItem.getCategory());\n bundleOrderItemRequest.setName(bundleOrderItem.getName());\n bundleOrderItemRequest.setQuantity(bundleOrderItem.getQuantity());\n bundleOrderItemRequest.setDiscreteOrderItems(discreteOrderItemRequests);\n return bundleOrderItemRequest;\n }\n\n\n /**\n * Returns the order associated with the passed in orderId.\n *\n * @param orderId\n * @return\n */\n protected Order validateOrder(Long orderId) {\n if (orderId == null) {\n throw new IllegalArgumentException(\"orderId required when adding item to order.\");\n }\n\n Order order = findOrderById(orderId);\n if (order == null) {\n throw new IllegalArgumentException(\"No order found matching passed in orderId \" + orderId + \" while trying to addItemToOrder.\");\n }\n\n return order;\n }\n\n protected Product validateProduct(Long productId) {\n if (productId != null) {\n Product product = productDao.readProductById(productId);\n if (product == null) {\n throw new IllegalArgumentException(\"No product found matching passed in productId \" + productId + \" while trying to addItemToOrder.\");\n }\n return product;\n }\n return null;\n }\n\n protected Category determineCategory(Product product, Long categoryId) {\n Category category = null;\n if (categoryId != null) {\n category = categoryDao.readCategoryById(categoryId);\n }\n\n if (category == null && product != null) {\n category = product.getDefaultCategory();\n }\n return category;\n }\n\n protected Sku determineSku(Product product, Long skuId, Map attributeValues) {\n // Check whether the sku is correct given the product options.\n Sku sku = findSkuThatMatchesProductOptions(product, attributeValues);\n\n if (sku == null && skuId != null) {\n sku = skuDao.readSkuById(skuId);\n }\n\n if (sku == null && product != null) {\n // Set to the default sku\n sku = product.getDefaultSku();\n }\n return sku;\n }\n\n private boolean checkSkuForAttribute(Sku sku, String attributeName, String attributeValue) {\n if (sku.getSkuAttributes() == null || sku.getSkuAttributes().size() == 0) {\n for (SkuAttribute skuAttribute : sku.getSkuAttributes()) {\n if (attributeName.equals(skuAttribute.getName()) && attributeValue.equals(skuAttribute.getValue())) {\n return true;\n }\n }\n }\n return false;\n }\n\n private boolean checkSkuForMatch(Sku sku, Map attributeValuesForSku) {\n if (attributeValuesForSku == null || attributeValuesForSku.size() == 0) {\n return false;\n }\n\n for (String attributeName : attributeValuesForSku.keySet()) {\n String attributeValue = attributeValuesForSku.get(attributeName);\n\n if (sku.getSkuAttributes() == null || sku.getSkuAttributes().size() == 0) {\n boolean attributeMatchFound = false;\n for (SkuAttribute skuAttribute : sku.getSkuAttributes()) {\n if (attributeName.equals(skuAttribute.getName()) && attributeValue.equals(skuAttribute.getValue())) {\n attributeMatchFound = true;\n break;\n }\n }\n if (attributeMatchFound) {\n continue;\n }\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Checks to make sure the correct SKU is still attached to the order.\n * For example, if you have the SKU for a Large, Red T-shirt in the\n * cart and your UI allows the user to change the one of the attributes\n * (e.g. red to black), then it is possible that the SKU needs to\n * be adjusted as well.\n */\n protected Sku findSkuThatMatchesProductOptions(Product product, Map attributeValues) {\n Map attributeValuesForSku = new HashMap();\n // Verify that required product-option values were set.\n //TODO: update to use the ProductOptionValues on Sku instead of the sku attribute\n /*\n if (product.getProductOptions() != null) {\n for (ProductOption productOption : product.getProductOptions()) {\n if (productOption.getRequired()) {\n if (attributeValues.get(productOption.getAttributeName()) == null) {\n throw new IllegalArgumentException(\"Unable to add to cart. Not all required options were provided.\");\n } else {\n attributeValuesForSku.put(productOption.getAttributeName(), attributeValues.get(productOption.getAttributeName()));\n }\n }\n }\n }\n */\n if (product !=null && product.getSkus() != null) {\n for (Sku sku : product.getSkus()) {\n if (checkSkuForMatch(sku, attributeValuesForSku)) {\n return sku;\n }\n }\n }\n\n return null;\n }\n\n\n protected DiscreteOrderItem createDiscreteOrderItem(Sku sku, Product product, Category category, int quantity, Map itemAttributes) {\n DiscreteOrderItem item = (DiscreteOrderItem) orderItemDao.create(OrderItemType.DISCRETE);\n item.setSku(sku);\n item.setProduct(product);\n item.setQuantity(quantity);\n item.setCategory(category);\n\n if (itemAttributes != null && itemAttributes.size() > 0) {\n Map orderItemAttributes = new HashMap();\n item.setOrderItemAttributes(orderItemAttributes);\n\n for (String key : itemAttributes.keySet()) {\n String value = itemAttributes.get(key);\n OrderItemAttribute attribute = new OrderItemAttributeImpl();\n attribute.setName(key);\n attribute.setValue(value);\n attribute.setOrderItem(item);\n orderItemAttributes.put(key, attribute);\n }\n }\n\n item.updatePrices();\n item.assignFinalPrice();\n return item;\n }\n\n /**\n * Adds an item to the passed in order.\n *\n * The orderItemRequest can be sparsely populated.\n *\n * When priceOrder is false, the system will not reprice the order. This is more performant in\n * cases such as bulk adds where the repricing could be done for the last item only.\n *\n * @see OrderItemRequestDTO\n * @param orderItemRequestDTO\n * @param priceOrder\n * @return\n */\n @Override\n public Order addItemToOrder(Long orderId, OrderItemRequestDTO orderItemRequestDTO, boolean priceOrder) throws PricingException {\n\n if (orderItemRequestDTO.getQuantity() == null || orderItemRequestDTO.getQuantity() == 0) {\n LOG.debug(\"Not adding item to order because quantity is zero.\");\n return null;\n }\n\n Order order = validateOrder(orderId);\n Product product = validateProduct(orderItemRequestDTO.getProductId());\n Sku sku = determineSku(product, orderItemRequestDTO.getSkuId(), orderItemRequestDTO.getItemAttributes());\n if (sku == null) {\n return null;\n }\n Category category = determineCategory(product, orderItemRequestDTO.getCategoryId());\n\n if (product == null || ! (product instanceof ProductBundle)) {\n DiscreteOrderItem item = createDiscreteOrderItem(sku, product, category, orderItemRequestDTO.getQuantity(), orderItemRequestDTO.getItemAttributes());\n List orderItems = order.getOrderItems();\n orderItems.add(item);\n item.setOrder(order);\n return updateOrder(order, priceOrder);\n } else {\n ProductBundle bundle = (ProductBundle) product;\n BundleOrderItem bundleOrderItem = (BundleOrderItem) orderItemDao.create(OrderItemType.BUNDLE);\n bundleOrderItem.setQuantity(orderItemRequestDTO.getQuantity());\n bundleOrderItem.setCategory(category);\n bundleOrderItem.setSku(sku);\n bundleOrderItem.setName(product.getName());\n bundleOrderItem.setProductBundle(bundle);\n\n for (SkuBundleItem skuBundleItem : bundle.getSkuBundleItems()) {\n Product bundleProduct = skuBundleItem.getBundle();\n Sku bundleSku = skuBundleItem.getSku();\n\n Category bundleCategory = determineCategory(bundleProduct, orderItemRequestDTO.getCategoryId());\n\n DiscreteOrderItem bundleDiscreteItem = createDiscreteOrderItem(bundleSku, bundleProduct, bundleCategory, skuBundleItem.getQuantity(), orderItemRequestDTO.getItemAttributes());\n bundleDiscreteItem.setSkuBundleItem(skuBundleItem);\n bundleDiscreteItem.setBundleOrderItem(bundleOrderItem);\n bundleOrderItem.getDiscreteOrderItems().add(bundleDiscreteItem);\n }\n\n bundleOrderItem.updatePrices();\n bundleOrderItem.assignFinalPrice();\n\n List orderItems = order.getOrderItems();\n orderItems.add(bundleOrderItem);\n bundleOrderItem.setOrder(order);\n return updateOrder(order, priceOrder);\n }\n }\n\n public boolean getAutomaticallyMergeLikeItems() {\n return automaticallyMergeLikeItems;\n }\n\n public void setAutomaticallyMergeLikeItems(boolean automaticallyMergeLikeItems) {\n this.automaticallyMergeLikeItems = automaticallyMergeLikeItems;\n }\n}\n"},"new_file":{"kind":"string","value":"core/broadleaf-framework/src/main/java/org/broadleafcommerce/core/order/service/OrderServiceImpl.java"},"old_contents":{"kind":"string","value":"/*\n * Copyright 2008-2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.broadleafcommerce.core.order.service;\n\nimport org.apache.commons.beanutils.BeanUtils;\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\nimport org.broadleafcommerce.core.catalog.dao.CategoryDao;\nimport org.broadleafcommerce.core.catalog.dao.ProductDao;\nimport org.broadleafcommerce.core.catalog.dao.SkuDao;\nimport org.broadleafcommerce.core.catalog.domain.Category;\nimport org.broadleafcommerce.core.catalog.domain.Product;\nimport org.broadleafcommerce.core.catalog.domain.ProductBundle;\nimport org.broadleafcommerce.core.catalog.domain.ProductOption;\nimport org.broadleafcommerce.core.catalog.domain.Sku;\nimport org.broadleafcommerce.core.catalog.domain.SkuAttribute;\nimport org.broadleafcommerce.core.catalog.domain.SkuBundleItem;\nimport org.broadleafcommerce.core.offer.dao.OfferDao;\nimport org.broadleafcommerce.core.offer.domain.OfferCode;\nimport org.broadleafcommerce.core.offer.service.OfferService;\nimport org.broadleafcommerce.core.offer.service.exception.OfferMaxUseExceededException;\nimport org.broadleafcommerce.core.order.dao.FulfillmentGroupDao;\nimport org.broadleafcommerce.core.order.dao.FulfillmentGroupItemDao;\nimport org.broadleafcommerce.core.order.dao.OrderDao;\nimport org.broadleafcommerce.core.order.dao.OrderItemDao;\nimport org.broadleafcommerce.core.order.domain.BundleOrderItem;\nimport org.broadleafcommerce.core.order.domain.DiscreteOrderItem;\nimport org.broadleafcommerce.core.order.domain.FulfillmentGroup;\nimport org.broadleafcommerce.core.order.domain.FulfillmentGroupItem;\nimport org.broadleafcommerce.core.order.domain.GiftWrapOrderItem;\nimport org.broadleafcommerce.core.order.domain.Order;\nimport org.broadleafcommerce.core.order.domain.OrderItem;\nimport org.broadleafcommerce.core.order.domain.OrderItemAttribute;\nimport org.broadleafcommerce.core.order.domain.OrderItemAttributeImpl;\nimport org.broadleafcommerce.core.order.domain.PersonalMessage;\nimport org.broadleafcommerce.core.order.service.call.BundleOrderItemRequest;\nimport org.broadleafcommerce.core.order.service.call.DiscreteOrderItemRequest;\nimport org.broadleafcommerce.core.order.service.call.FulfillmentGroupItemRequest;\nimport org.broadleafcommerce.core.order.service.call.FulfillmentGroupRequest;\nimport org.broadleafcommerce.core.order.service.call.GiftWrapOrderItemRequest;\nimport org.broadleafcommerce.core.order.service.call.OrderItemRequestDTO;\nimport org.broadleafcommerce.core.order.service.exception.ItemNotFoundException;\nimport org.broadleafcommerce.core.order.service.type.OrderItemType;\nimport org.broadleafcommerce.core.order.service.type.OrderStatus;\nimport org.broadleafcommerce.core.payment.dao.PaymentInfoDao;\nimport org.broadleafcommerce.core.payment.domain.PaymentInfo;\nimport org.broadleafcommerce.core.payment.domain.Referenced;\nimport org.broadleafcommerce.core.payment.service.SecurePaymentInfoService;\nimport org.broadleafcommerce.core.payment.service.type.PaymentInfoType;\nimport org.broadleafcommerce.core.pricing.service.PricingService;\nimport org.broadleafcommerce.core.pricing.service.exception.PricingException;\nimport org.broadleafcommerce.core.workflow.WorkflowException;\nimport org.broadleafcommerce.profile.core.domain.Address;\nimport org.broadleafcommerce.profile.core.domain.Customer;\n\nimport javax.annotation.Resource;\nimport java.lang.reflect.InvocationTargetException;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\n\npublic class OrderServiceImpl implements OrderService {\n\n private static final Log LOG = LogFactory.getLog(OrderServiceImpl.class);\n\n @Resource(name = \"blOrderDao\")\n protected OrderDao orderDao;\n\n @Resource(name = \"blPaymentInfoDao\")\n protected PaymentInfoDao paymentInfoDao;\n\n @Resource(name = \"blFulfillmentGroupDao\")\n protected FulfillmentGroupDao fulfillmentGroupDao;\n\n @Resource(name = \"blFulfillmentGroupItemDao\")\n protected FulfillmentGroupItemDao fulfillmentGroupItemDao;\n\n @Resource(name = \"blOfferDao\")\n protected OfferDao offerDao;\n\n @Resource(name = \"blOrderItemService\")\n protected OrderItemService orderItemService;\n\n @Resource(name = \"blOrderItemDao\")\n protected OrderItemDao orderItemDao;\n\n @Resource(name = \"blSkuDao\")\n protected SkuDao skuDao;\n\n @Resource(name = \"blProductDao\")\n protected ProductDao productDao;\n\n @Resource(name = \"blCategoryDao\")\n protected CategoryDao categoryDao;\n\n @Resource(name = \"blFulfillmentGroupService\")\n protected FulfillmentGroupService fulfillmentGroupService;\n\n @Resource(name = \"blSecurePaymentInfoService\")\n protected SecurePaymentInfoService securePaymentInfoService;\n \n @Resource(name = \"blOfferService\")\n protected OfferService offerService;\n\n @Resource(name = \"blPricingService\")\n protected PricingService pricingService;\n\n protected boolean automaticallyMergeLikeItems = true;\n\n public Order createNamedOrderForCustomer(String name, Customer customer) {\n Order namedOrder = orderDao.create();\n namedOrder.setCustomer(customer);\n namedOrder.setName(name);\n namedOrder.setStatus(OrderStatus.NAMED);\n return persistOrder(namedOrder);\n }\n\n public Order save(Order order, Boolean priceOrder) throws PricingException {\n return updateOrder(order, priceOrder);\n }\n\n public Order findOrderById(Long orderId) {\n return orderDao.readOrderById(orderId);\n }\n\n public List findOrdersForCustomer(Customer customer) {\n return orderDao.readOrdersForCustomer(customer.getId());\n }\n\n public List findOrdersForCustomer(Customer customer, OrderStatus status) {\n return orderDao.readOrdersForCustomer(customer, status);\n }\n\n public Order findNamedOrderForCustomer(String name, Customer customer) {\n return orderDao.readNamedOrderForCustomer(customer, name);\n }\n\n public FulfillmentGroup findDefaultFulfillmentGroupForOrder(Order order) {\n FulfillmentGroup fg = fulfillmentGroupDao.readDefaultFulfillmentGroupForOrder(order);\n\n return fg;\n }\n\n public OrderItem addSkuToOrder(Long orderId, Long skuId, Long productId, Long categoryId, Integer quantity) throws PricingException {\n \treturn addSkuToOrder(orderId, skuId, productId, categoryId, quantity, true, null);\n }\n \n public OrderItem addSkuToOrder(Long orderId, Long skuId, Long productId, Long categoryId, Integer quantity, Map itemAttributes) throws PricingException {\n \treturn addSkuToOrder(orderId, skuId, productId, categoryId, quantity, true, itemAttributes);\n }\n \n public OrderItem addSkuToOrder(Long orderId, Long skuId, Long productId, Long categoryId, Integer quantity, boolean priceOrder) throws PricingException {\n return addSkuToOrder(orderId, skuId, productId, categoryId, quantity, priceOrder, null);\n }\n\n public OrderItem addSkuToOrder(Long orderId, Long skuId, Long productId, Long categoryId, Integer quantity, boolean priceOrder, Map itemAttributes) throws PricingException {\n if (orderId == null || (productId == null && skuId == null) || quantity == null) {\n return null;\n }\n\n OrderItemRequestDTO requestDTO = new OrderItemRequestDTO();\n requestDTO.setCategoryId(categoryId);\n requestDTO.setProductId(productId);\n requestDTO.setSkuId(skuId);\n requestDTO.setQuantity(quantity);\n requestDTO.setItemAttributes(itemAttributes);\n\n Order order = addItemToOrder(orderId, requestDTO, priceOrder);\n return findLastMatchingItem(order, skuId, productId);\n }\n\n public OrderItem addDiscreteItemToOrder(Order order, DiscreteOrderItemRequest itemRequest) throws PricingException {\n \treturn addDiscreteItemToOrder(order, itemRequest, true);\n }\n\n public OrderItem addDiscreteItemToOrder(Order order, DiscreteOrderItemRequest itemRequest, boolean priceOrder) throws PricingException {\n DiscreteOrderItem item = orderItemService.createDiscreteOrderItem(itemRequest);\n return addOrderItemToOrder(order, item, priceOrder);\n }\n\n public OrderItem addDynamicPriceDiscreteItemToOrder(Order order, DiscreteOrderItemRequest itemRequest, @SuppressWarnings(\"rawtypes\") HashMap skuPricingConsiderations) throws PricingException {\n \treturn addDynamicPriceDiscreteItemToOrder(order, itemRequest, skuPricingConsiderations, true);\n }\n\n public OrderItem addDynamicPriceDiscreteItemToOrder(Order order, DiscreteOrderItemRequest itemRequest, @SuppressWarnings(\"rawtypes\") HashMap skuPricingConsiderations, boolean priceOrder) throws PricingException {\n DiscreteOrderItem item = orderItemService.createDynamicPriceDiscreteOrderItem(itemRequest, skuPricingConsiderations);\n return addOrderItemToOrder(order, item, priceOrder);\n }\n \n public OrderItem addGiftWrapItemToOrder(Order order, GiftWrapOrderItemRequest itemRequest) throws PricingException {\n \treturn addGiftWrapItemToOrder(order, itemRequest, true);\n }\n\n public OrderItem addGiftWrapItemToOrder(Order order, GiftWrapOrderItemRequest itemRequest, boolean priceOrder) throws PricingException {\n GiftWrapOrderItem item = orderItemService.createGiftWrapOrderItem(itemRequest);\n return addOrderItemToOrder(order, item, priceOrder);\n }\n \n public OrderItem addBundleItemToOrder(Order order, BundleOrderItemRequest itemRequest) throws PricingException {\n \treturn addBundleItemToOrder(order, itemRequest, true);\n }\n\n public OrderItem addBundleItemToOrder(Order order, BundleOrderItemRequest itemRequest, boolean priceOrder) throws PricingException {\n BundleOrderItem item = orderItemService.createBundleOrderItem(itemRequest);\n return addOrderItemToOrder(order, item, priceOrder);\n }\n \n public Order removeItemFromOrder(Long orderId, Long itemId) throws PricingException {\n \treturn removeItemFromOrder(orderId, itemId, true);\n }\n\n public Order removeItemFromOrder(Long orderId, Long itemId, boolean priceOrder) throws PricingException {\n Order order = findOrderById(orderId);\n OrderItem orderItem = orderItemService.readOrderItemById(itemId);\n\n return removeItemFromOrder(order, orderItem, priceOrder);\n }\n \n public Order removeItemFromOrder(Order order, OrderItem item) throws PricingException {\n \treturn removeItemFromOrder(order, item, true);\n }\n\n public Order removeItemFromOrder(Order order, OrderItem item, boolean priceOrder) throws PricingException {\n removeOrderItemFromFullfillmentGroup(order, item);\n OrderItem itemFromOrder = order.getOrderItems().remove(order.getOrderItems().indexOf(item));\n itemFromOrder.setOrder(null);\n orderItemService.delete(itemFromOrder);\n order = updateOrder(order, priceOrder);\n return order;\n }\n \n public Order moveItemToOrder(Order originalOrder, Order destinationOrder, OrderItem item) throws PricingException {\n \treturn moveItemToOrder(originalOrder, destinationOrder, item, true);\n }\n \n public Order moveItemToOrder(Order originalOrder, Order destinationOrder, OrderItem item, boolean priceOrder) throws PricingException {\n \tremoveOrderItemFromFullfillmentGroup(originalOrder, item);\n \tOrderItem itemFromOrder = originalOrder.getOrderItems().remove(originalOrder.getOrderItems().indexOf(item));\n \titemFromOrder.setOrder(null);\n \toriginalOrder = updateOrder(originalOrder, priceOrder);\n \taddOrderItemToOrder(destinationOrder, item, priceOrder);\n \treturn destinationOrder;\n }\n\n public PaymentInfo addPaymentToOrder(Order order, PaymentInfo payment) {\n return addPaymentToOrder(order, payment, null);\n }\n\n public PaymentInfo addPaymentToOrder(Order order, PaymentInfo payment, Referenced securePaymentInfo) {\n payment.setOrder(order);\n order.getPaymentInfos().add(payment);\n order = persistOrder(order);\n int paymentIndex = order.getPaymentInfos().size() - 1;\n\n if (securePaymentInfo != null) {\n securePaymentInfoService.save(securePaymentInfo);\n }\n\n return order.getPaymentInfos().get(paymentIndex);\n }\n\n public void removeAllPaymentsFromOrder(Order order) {\n removePaymentsFromOrder(order, null);\n }\n\n public void removePaymentsFromOrder(Order order, PaymentInfoType paymentInfoType) {\n List infos = new ArrayList();\n for (PaymentInfo paymentInfo : order.getPaymentInfos()) {\n if (paymentInfoType == null || paymentInfoType.equals(paymentInfo.getType())) {\n infos.add(paymentInfo);\n }\n }\n order.getPaymentInfos().removeAll(infos);\n for (PaymentInfo paymentInfo : infos) {\n try {\n securePaymentInfoService.findAndRemoveSecurePaymentInfo(paymentInfo.getReferenceNumber(), paymentInfo.getType());\n } catch (WorkflowException e) {\n // do nothing--this is an acceptable condition\n LOG.debug(\"No secure payment is associated with the PaymentInfo\", e);\n }\n order.getPaymentInfos().remove(paymentInfo);\n paymentInfo = paymentInfoDao.readPaymentInfoById(paymentInfo.getId());\n paymentInfoDao.delete(paymentInfo);\n }\n }\n \n public FulfillmentGroup addFulfillmentGroupToOrder(FulfillmentGroupRequest fulfillmentGroupRequest) throws PricingException {\n \treturn addFulfillmentGroupToOrder(fulfillmentGroupRequest, true);\n }\n\n public FulfillmentGroup addFulfillmentGroupToOrder(FulfillmentGroupRequest fulfillmentGroupRequest, boolean priceOrder) throws PricingException {\n FulfillmentGroup fg = fulfillmentGroupDao.create();\n fg.setAddress(fulfillmentGroupRequest.getAddress());\n fg.setOrder(fulfillmentGroupRequest.getOrder());\n fg.setPhone(fulfillmentGroupRequest.getPhone());\n fg.setMethod(fulfillmentGroupRequest.getMethod());\n fg.setService(fulfillmentGroupRequest.getService());\n\n for (int i=0; i< fulfillmentGroupRequest.getFulfillmentGroupItemRequests().size(); i++) {\n FulfillmentGroupItemRequest request = fulfillmentGroupRequest.getFulfillmentGroupItemRequests().get(i);\n boolean shouldPriceOrder = (priceOrder && (i == (fulfillmentGroupRequest.getFulfillmentGroupItemRequests().size() - 1)));\n fg = addItemToFulfillmentGroup(request.getOrderItem(), fg, request.getQuantity(), shouldPriceOrder);\n }\n\n return fg;\n }\n \n public FulfillmentGroup addFulfillmentGroupToOrder(Order order, FulfillmentGroup fulfillmentGroup) throws PricingException {\n \treturn addFulfillmentGroupToOrder(order, fulfillmentGroup, true);\n }\n\n public FulfillmentGroup addFulfillmentGroupToOrder(Order order, FulfillmentGroup fulfillmentGroup, boolean priceOrder) throws PricingException {\n FulfillmentGroup dfg = findDefaultFulfillmentGroupForOrder(order);\n if (dfg == null) {\n fulfillmentGroup.setPrimary(true);\n } else if (dfg.equals(fulfillmentGroup)) {\n // API user is trying to re-add the default fulfillment group to the\n // same order\n fulfillmentGroup.setPrimary(true);\n order.getFulfillmentGroups().remove(dfg);\n // fulfillmentGroupDao.delete(dfg);\n }\n\n fulfillmentGroup.setOrder(order);\n // 1) For each item in the new fulfillment group\n for (FulfillmentGroupItem fgItem : fulfillmentGroup.getFulfillmentGroupItems()) {\n // 2) Find the item's existing fulfillment group\n for (FulfillmentGroup fg : order.getFulfillmentGroups()) {\n // If the existing fulfillment group is different than passed in\n // fulfillment group\n if (!fg.equals(fulfillmentGroup)) {\n // 3) remove item from it's existing fulfillment\n // group\n fg.getFulfillmentGroupItems().remove(fgItem);\n }\n }\n }\n fulfillmentGroup = fulfillmentGroupDao.save(fulfillmentGroup);\n order.getFulfillmentGroups().add(fulfillmentGroup);\n int fulfillmentGroupIndex = order.getFulfillmentGroups().size() - 1;\n order = updateOrder(order, priceOrder);\n return order.getFulfillmentGroups().get(fulfillmentGroupIndex);\n }\n \n public FulfillmentGroup addItemToFulfillmentGroup(OrderItem item, FulfillmentGroup fulfillmentGroup, int quantity) throws PricingException {\n \treturn addItemToFulfillmentGroup(item, fulfillmentGroup, quantity, true);\n }\n\n public FulfillmentGroup addItemToFulfillmentGroup(OrderItem item, FulfillmentGroup fulfillmentGroup, int quantity, boolean priceOrder) throws PricingException {\n return addItemToFulfillmentGroup(item.getOrder(), item, fulfillmentGroup, quantity, priceOrder);\n }\n\n public FulfillmentGroup addItemToFulfillmentGroup(Order order, OrderItem item, FulfillmentGroup fulfillmentGroup, int quantity, boolean priceOrder) throws PricingException {\n\n // 1) Find the item's existing fulfillment group, if any\n for (FulfillmentGroup fg : order.getFulfillmentGroups()) {\n Iterator itr = fg.getFulfillmentGroupItems().iterator();\n while (itr.hasNext()) {\n FulfillmentGroupItem fgItem = itr.next();\n if (fgItem.getOrderItem().equals(item)) {\n // 2) remove item from it's existing fulfillment group\n itr.remove();\n fulfillmentGroupItemDao.delete(fgItem);\n }\n }\n }\n\n if (fulfillmentGroup.getId() == null) {\n // API user is trying to add an item to a fulfillment group not created\n fulfillmentGroup = addFulfillmentGroupToOrder(order, fulfillmentGroup, priceOrder);\n }\n\n FulfillmentGroupItem fgi = createFulfillmentGroupItemFromOrderItem(item, fulfillmentGroup, quantity);\n fgi = fulfillmentGroupItemDao.save(fgi);\n\n // 3) add the item to the new fulfillment group\n fulfillmentGroup.addFulfillmentGroupItem(fgi);\n order = updateOrder(order, priceOrder);\n\n return fulfillmentGroup;\n }\n\n public FulfillmentGroup addItemToFulfillmentGroup(OrderItem item, FulfillmentGroup fulfillmentGroup) throws PricingException {\n \treturn addItemToFulfillmentGroup(item, fulfillmentGroup, true);\n }\n\n public FulfillmentGroup addItemToFulfillmentGroup(OrderItem item, FulfillmentGroup fulfillmentGroup, boolean priceOrder) throws PricingException {\n return addItemToFulfillmentGroup(item, fulfillmentGroup, item.getQuantity(), priceOrder);\n }\n \n public void updateItemQuantity(Order order, OrderItem item) throws ItemNotFoundException, PricingException {\n \tupdateItemQuantity(order, item, true);\n }\n\n public void updateItemQuantity(Order order, OrderItem item, boolean priceOrder) throws ItemNotFoundException, PricingException {\n if (!order.getOrderItems().contains(item)) {\n throw new ItemNotFoundException(\"Order Item (\" + item.getId() + \") not found in Order (\" + order.getId() + \")\");\n }\n OrderItem itemFromOrder = order.getOrderItems().get(order.getOrderItems().indexOf(item));\n itemFromOrder.setQuantity(item.getQuantity());\n order = updateOrder(order, priceOrder);\n\n }\n\n public void removeAllFulfillmentGroupsFromOrder(Order order) throws PricingException {\n removeAllFulfillmentGroupsFromOrder(order, false);\n }\n\n public void removeAllFulfillmentGroupsFromOrder(Order order, boolean priceOrder) throws PricingException {\n if (order.getFulfillmentGroups() != null) {\n for (Iterator iterator = order.getFulfillmentGroups().iterator(); iterator.hasNext();) {\n FulfillmentGroup fulfillmentGroup = iterator.next();\n iterator.remove();\n fulfillmentGroupDao.delete(fulfillmentGroup);\n }\n updateOrder(order, priceOrder);\n }\n }\n \n public void removeFulfillmentGroupFromOrder(Order order, FulfillmentGroup fulfillmentGroup) throws PricingException {\n \tremoveFulfillmentGroupFromOrder(order, fulfillmentGroup, true);\n }\n\n @Override\n public void removeFulfillmentGroupFromOrder(Order order, FulfillmentGroup fulfillmentGroup, boolean priceOrder) throws PricingException {\n order.getFulfillmentGroups().remove(fulfillmentGroup);\n fulfillmentGroupDao.delete(fulfillmentGroup);\n updateOrder(order, priceOrder);\n }\n\n @Override\n public Order addOfferCode(Order order, OfferCode offerCode, boolean priceOrder) throws PricingException, OfferMaxUseExceededException {\n if( !order.getAddedOfferCodes().contains(offerCode)) {\n if (! offerService.verifyMaxCustomerUsageThreshold(order.getCustomer(), offerCode.getOffer())) {\n throw new OfferMaxUseExceededException(\"The customer has used this offer code more than the maximum allowed number of times.\");\n }\n order.getAddedOfferCodes().add(offerCode);\n order = updateOrder(order, priceOrder);\n }\n return order;\n }\n\n @Override\n public Order removeOfferCode(Order order, OfferCode offerCode, boolean priceOrder) throws PricingException {\n order.getAddedOfferCodes().remove(offerCode);\n order = updateOrder(order, priceOrder);\n return order;\n }\n\n @Override\n public Order removeAllOfferCodes(Order order, boolean priceOrder) throws PricingException {\n order.getAddedOfferCodes().clear();\n order = updateOrder(order, priceOrder);\n return order;\n }\n\n public void removeNamedOrderForCustomer(String name, Customer customer) {\n Order namedOrder = findNamedOrderForCustomer(name, customer);\n cancelOrder(namedOrder);\n }\n\n public Order confirmOrder(Order order) {\n return orderDao.submitOrder(order);\n }\n\n public void cancelOrder(Order order) {\n orderDao.delete(order);\n }\n\n public List readPaymentInfosForOrder(Order order) {\n return paymentInfoDao.readPaymentInfosForOrder(order);\n }\n \n public OrderItem addOrderItemToOrder(Order order, OrderItem newOrderItem) throws PricingException {\n List orderItems = order.getOrderItems();\n orderItems.add(newOrderItem);\n newOrderItem.setOrder(order);\n order = updateOrder(order, true);\n return findLastMatchingItem(order, newOrderItem);\n }\n\n private boolean itemMatches(DiscreteOrderItem item1, DiscreteOrderItem item2) {\n // Must match on SKU and options\n if (item1.getSku() != null && item2.getSku() != null) {\n if (item1.getSku().getId().equals(item2.getSku().getId())) {\n // TODO: Compare options if product has product options\n return true;\n }\n } else {\n if (item1.getProduct() != null && item2.getProduct() != null) {\n if (item1.getProduct().getId().equals(item2.getProduct().getId())) {\n return true;\n }\n }\n }\n return false;\n }\n\n private OrderItem findLastMatchingDiscreteItem(Order order, DiscreteOrderItem itemToFind) {\n for (int i=(order.getOrderItems().size()-1); i >= 0; i--) {\n OrderItem currentItem = (order.getOrderItems().get(i));\n if (currentItem instanceof DiscreteOrderItem) {\n DiscreteOrderItem discreteItem = (DiscreteOrderItem) currentItem;\n if (itemMatches(discreteItem, itemToFind)) {\n return discreteItem;\n }\n\n } else if (currentItem instanceof BundleOrderItem) {\n for (DiscreteOrderItem discreteItem : (((BundleOrderItem) currentItem).getDiscreteOrderItems())) {\n if (itemMatches(discreteItem, itemToFind)) {\n return discreteItem;\n }\n }\n }\n }\n return null;\n }\n\n private boolean bundleItemMatches(BundleOrderItem item1, BundleOrderItem item2) {\n if (item1.getSku() != null && item2.getSku() != null) {\n return item1.getSku().getId().equals(item1.getSku().getId());\n }\n\n // Otherwise, scan the items.\n HashMap skuMap = new HashMap();\n for(DiscreteOrderItem item : item1.getDiscreteOrderItems()) {\n if (skuMap.get(item.getSku().getId()) == null) {\n skuMap.put(item.getSku().getId(), Integer.valueOf(item.getQuantity()));\n } else {\n Integer qty = skuMap.get(item.getSku().getId());\n skuMap.put(item.getSku().getId(), Integer.valueOf(qty + item.getQuantity()));\n }\n }\n\n // Now consume the quantities in the map\n for(DiscreteOrderItem item : item2.getDiscreteOrderItems()) {\n if (skuMap.containsKey(item.getSku().getId())) {\n Integer qty = skuMap.get(item.getSku().getId());\n Integer newQty = Integer.valueOf(qty - item.getQuantity());\n if (newQty.intValue() == 0) {\n skuMap.remove(item.getSku().getId());\n } else if (newQty.intValue() > 0) {\n skuMap.put(item.getSku().getId(), newQty);\n } else {\n return false;\n }\n } else {\n return false;\n }\n\n // If all of the quantities were consumed, this is a match.\n return skuMap.isEmpty();\n }\n\n return false;\n }\n\n\n private OrderItem findLastMatchingBundleItem(Order order, BundleOrderItem itemToFind) {\n for (int i=(order.getOrderItems().size()-1); i > 0; i--) {\n OrderItem currentItem = (order.getOrderItems().get(i));\n if (currentItem instanceof BundleOrderItem) {\n if (bundleItemMatches((BundleOrderItem) currentItem, itemToFind)) {\n return currentItem;\n }\n }\n }\n return null;\n }\n\n private OrderItem findLastMatchingItem(Order order, OrderItem itemToFind) {\n if (itemToFind instanceof BundleOrderItem) {\n return findLastMatchingBundleItem(order, (BundleOrderItem) itemToFind);\n } else if (itemToFind instanceof DiscreteOrderItem) {\n return findLastMatchingDiscreteItem(order, (DiscreteOrderItem) itemToFind);\n } else {\n return null;\n }\n }\n\n private OrderItem findLastMatchingItem(Order order,Long skuId, Long productId) {\n if (order.getOrderItems() != null) {\n for (int i=(order.getOrderItems().size()-1); i >= 0; i--) {\n OrderItem currentItem = (order.getOrderItems().get(i));\n if (currentItem instanceof DiscreteOrderItem) {\n DiscreteOrderItem discreteItem = (DiscreteOrderItem) currentItem;\n if (skuId != null) {\n if (discreteItem.getSku() != null && skuId.equals(discreteItem.getSku().getId())) {\n return discreteItem;\n }\n } else if (productId != null && discreteItem.getProduct() != null && productId.equals(discreteItem.getProduct().getId())) {\n return discreteItem;\n }\n\n } else if (currentItem instanceof BundleOrderItem) {\n BundleOrderItem bundleItem = (BundleOrderItem) currentItem;\n if (skuId != null) {\n if (bundleItem.getSku() != null && skuId.equals(bundleItem.getSku().getId())) {\n return bundleItem;\n }\n } else if (productId != null && bundleItem.getProduct() != null && productId.equals(bundleItem.getProduct().getId())) {\n return bundleItem;\n }\n }\n }\n }\n return null;\n }\n \t\n public OrderItem addOrderItemToOrder(Order order, OrderItem newOrderItem, boolean priceOrder) throws PricingException {\n List orderItems = order.getOrderItems();\n orderItems.add(newOrderItem);\n newOrderItem.setOrder(order);\n order = updateOrder(order, priceOrder);\n return findLastMatchingItem(order, newOrderItem);\n }\n \n public OrderItem addOrderItemToBundle(Order order, BundleOrderItem bundle, DiscreteOrderItem newOrderItem, boolean priceOrder) throws PricingException {\n List orderItems = bundle.getDiscreteOrderItems();\n orderItems.add(newOrderItem);\n newOrderItem.setBundleOrderItem(bundle);\n\n order = updateOrder(order, priceOrder);\n\n return findLastMatchingItem(order, bundle);\n }\n \n public Order removeItemFromBundle(Order order, BundleOrderItem bundle, OrderItem item, boolean priceOrder) throws PricingException {\n DiscreteOrderItem itemFromBundle = bundle.getDiscreteOrderItems().remove(bundle.getDiscreteOrderItems().indexOf(item));\n orderItemService.delete(itemFromBundle);\n itemFromBundle.setBundleOrderItem(null);\n order = updateOrder(order, priceOrder);\n \n return order;\n }\n\n /**\n * Adds the passed in name/value pair to the order-item. If the\n * attribute already exists, then it is updated with the new value.\n *

\n * If the value passed in is null and the attribute exists, it is removed\n * from the order item.\n *\n * @param order\n * @param item\n * @param attributeValues\n * @param priceOrder\n * @return\n */\n @Override\n public Order addOrUpdateOrderItemAttributes(Order order, OrderItem item, Map attributeValues, boolean priceOrder) throws ItemNotFoundException, PricingException {\n if (!order.getOrderItems().contains(item)) {\n throw new ItemNotFoundException(\"Order Item (\" + item.getId() + \") not found in Order (\" + order.getId() + \")\");\n }\n OrderItem itemFromOrder = order.getOrderItems().get(order.getOrderItems().indexOf(item));\n \n Map orderItemAttributes = itemFromOrder.getOrderItemAttributes();\n if (orderItemAttributes == null) {\n orderItemAttributes = new HashMap();\n itemFromOrder.setOrderItemAttributes(orderItemAttributes);\n }\n \n boolean changeMade = false;\n for (String attributeName : attributeValues.keySet()) {\n String attributeValue = attributeValues.get(attributeName);\n OrderItemAttribute attribute = orderItemAttributes.get(attributeName);\n if (attribute != null && attribute.getValue().equals(attributeValue)) {\n // no change made.\n continue;\n } else {\n changeMade = true;\n if (attribute == null) {\n attribute = new OrderItemAttributeImpl();\n attribute.setOrderItem(itemFromOrder);\n attribute.setName(attributeName);\n attribute.setValue(attributeValue);\n } else if (attributeValue == null) {\n orderItemAttributes.remove(attributeValue);\n } else {\n attribute.setValue(attributeValue);\n }\n }\n }\n\n if (changeMade) {\n return updateOrder(order, priceOrder);\n } else {\n return order;\n }\n }\n\n public Order removeOrderItemAttribute(Order order, OrderItem item, String attributeName, boolean priceOrder) throws ItemNotFoundException, PricingException {\n if (!order.getOrderItems().contains(item)) {\n throw new ItemNotFoundException(\"Order Item (\" + item.getId() + \") not found in Order (\" + order.getId() + \")\");\n }\n OrderItem itemFromOrder = order.getOrderItems().get(order.getOrderItems().indexOf(item));\n\n boolean changeMade = false;\n Map orderItemAttributes = itemFromOrder.getOrderItemAttributes();\n if (orderItemAttributes != null) {\n if (orderItemAttributes.containsKey(attributeName)) {\n changeMade = true;\n orderItemAttributes.remove(attributeName);\n }\n }\n\n if (changeMade) {\n return updateOrder(order, priceOrder);\n } else {\n return order;\n }\n }\n\n public FulfillmentGroup createDefaultFulfillmentGroup(Order order, Address address) {\n for (FulfillmentGroup fulfillmentGroup : order.getFulfillmentGroups()) {\n if (fulfillmentGroup.isPrimary()) {\n return fulfillmentGroup;\n }\n }\n\n FulfillmentGroup newFg = fulfillmentGroupService.createEmptyFulfillmentGroup();\n newFg.setOrder(order);\n newFg.setPrimary(true);\n newFg.setAddress(address);\n for (OrderItem orderItem : order.getOrderItems()) {\n newFg.addFulfillmentGroupItem(createFulfillmentGroupItemFromOrderItem(orderItem, newFg, orderItem.getQuantity()));\n }\n return newFg;\n }\n\n public OrderDao getOrderDao() {\n return orderDao;\n }\n\n public void setOrderDao(OrderDao orderDao) {\n this.orderDao = orderDao;\n }\n\n public PaymentInfoDao getPaymentInfoDao() {\n return paymentInfoDao;\n }\n\n public void setPaymentInfoDao(PaymentInfoDao paymentInfoDao) {\n this.paymentInfoDao = paymentInfoDao;\n }\n\n public FulfillmentGroupDao getFulfillmentGroupDao() {\n return fulfillmentGroupDao;\n }\n\n public void setFulfillmentGroupDao(FulfillmentGroupDao fulfillmentGroupDao) {\n this.fulfillmentGroupDao = fulfillmentGroupDao;\n }\n\n public FulfillmentGroupItemDao getFulfillmentGroupItemDao() {\n return fulfillmentGroupItemDao;\n }\n\n public void setFulfillmentGroupItemDao(FulfillmentGroupItemDao fulfillmentGroupItemDao) {\n this.fulfillmentGroupItemDao = fulfillmentGroupItemDao;\n }\n\n public OrderItemService getOrderItemService() {\n return orderItemService;\n }\n\n public void setOrderItemService(OrderItemService orderItemService) {\n this.orderItemService = orderItemService;\n }\n\n public Order findOrderByOrderNumber(String orderNumber) {\n return orderDao.readOrderByOrderNumber(orderNumber);\n }\n\n protected Order updateOrder(Order order, Boolean priceOrder) throws PricingException {\n if (priceOrder) {\n order = pricingService.executePricing(order);\n }\n return persistOrder(order);\n }\n\n\n protected Order persistOrder(Order order) {\n return orderDao.save(order);\n }\n\n protected FulfillmentGroupItem createFulfillmentGroupItemFromOrderItem(OrderItem orderItem, FulfillmentGroup fulfillmentGroup, int quantity) {\n FulfillmentGroupItem fgi = fulfillmentGroupItemDao.create();\n fgi.setFulfillmentGroup(fulfillmentGroup);\n fgi.setOrderItem(orderItem);\n fgi.setQuantity(quantity);\n return fgi;\n }\n\n protected void removeOrderItemFromFullfillmentGroup(Order order, OrderItem orderItem) {\n List fulfillmentGroups = order.getFulfillmentGroups();\n for (FulfillmentGroup fulfillmentGroup : fulfillmentGroups) {\n Iterator itr = fulfillmentGroup.getFulfillmentGroupItems().iterator();\n while (itr.hasNext()) {\n FulfillmentGroupItem fulfillmentGroupItem = itr.next();\n if (fulfillmentGroupItem.getOrderItem().equals(orderItem)) {\n itr.remove();\n fulfillmentGroupItemDao.delete(fulfillmentGroupItem);\n }\n }\n }\n }\n\n protected DiscreteOrderItemRequest createDiscreteOrderItemRequest(DiscreteOrderItem discreteOrderItem) {\n DiscreteOrderItemRequest itemRequest = new DiscreteOrderItemRequest();\n itemRequest.setCategory(discreteOrderItem.getCategory());\n itemRequest.setProduct(discreteOrderItem.getProduct());\n itemRequest.setQuantity(discreteOrderItem.getQuantity());\n itemRequest.setSku(discreteOrderItem.getSku());\n \n if (discreteOrderItem.getPersonalMessage() != null) {\n PersonalMessage personalMessage = orderItemService.createPersonalMessage();\n try {\n BeanUtils.copyProperties(personalMessage, discreteOrderItem.getPersonalMessage());\n personalMessage.setId(null);\n } catch (IllegalAccessException e) {\n throw new RuntimeException(e);\n } catch (InvocationTargetException e) {\n throw new RuntimeException(e);\n }\n itemRequest.setPersonalMessage(personalMessage);\n }\n \n return itemRequest;\n }\n\n protected BundleOrderItemRequest createBundleOrderItemRequest(BundleOrderItem bundleOrderItem, List discreteOrderItemRequests) {\n BundleOrderItemRequest bundleOrderItemRequest = new BundleOrderItemRequest();\n bundleOrderItemRequest.setCategory(bundleOrderItem.getCategory());\n bundleOrderItemRequest.setName(bundleOrderItem.getName());\n bundleOrderItemRequest.setQuantity(bundleOrderItem.getQuantity());\n bundleOrderItemRequest.setDiscreteOrderItems(discreteOrderItemRequests);\n return bundleOrderItemRequest;\n }\n\n\n /**\n * Returns the order associated with the passed in orderId.\n *\n * @param orderId\n * @return\n */\n protected Order validateOrder(Long orderId) {\n if (orderId == null) {\n throw new IllegalArgumentException(\"orderId required when adding item to order.\");\n }\n\n Order order = findOrderById(orderId);\n if (order == null) {\n throw new IllegalArgumentException(\"No order found matching passed in orderId \" + orderId + \" while trying to addItemToOrder.\");\n }\n\n return order;\n }\n\n protected Product validateProduct(Long productId) {\n if (productId != null) {\n Product product = productDao.readProductById(productId);\n if (product == null) {\n throw new IllegalArgumentException(\"No product found matching passed in productId \" + productId + \" while trying to addItemToOrder.\");\n }\n return product;\n }\n return null;\n }\n\n protected Category determineCategory(Product product, Long categoryId) {\n Category category = null;\n if (categoryId != null) {\n category = categoryDao.readCategoryById(categoryId);\n }\n\n if (category == null && product != null) {\n category = product.getDefaultCategory();\n }\n return category;\n }\n\n protected Sku determineSku(Product product, Long skuId, Map attributeValues) {\n // Check whether the sku is correct given the product options.\n Sku sku = findSkuThatMatchesProductOptions(product, attributeValues);\n\n if (sku == null && skuId != null) {\n sku = skuDao.readSkuById(skuId);\n }\n\n if (sku == null && product != null) {\n // Set to the default sku\n sku = product.getDefaultSku();\n }\n return sku;\n }\n\n private boolean checkSkuForAttribute(Sku sku, String attributeName, String attributeValue) {\n if (sku.getSkuAttributes() == null || sku.getSkuAttributes().size() == 0) {\n for (SkuAttribute skuAttribute : sku.getSkuAttributes()) {\n if (attributeName.equals(skuAttribute.getName()) && attributeValue.equals(skuAttribute.getValue())) {\n return true;\n }\n }\n }\n return false;\n }\n\n private boolean checkSkuForMatch(Sku sku, Map attributeValuesForSku) {\n for (String attributeName : attributeValuesForSku.keySet()) {\n String attributeValue = attributeValuesForSku.get(attributeName);\n\n if (sku.getSkuAttributes() == null || sku.getSkuAttributes().size() == 0) {\n boolean attributeMatchFound = false;\n for (SkuAttribute skuAttribute : sku.getSkuAttributes()) {\n if (attributeName.equals(skuAttribute.getName()) && attributeValue.equals(skuAttribute.getValue())) {\n attributeMatchFound = true;\n break;\n }\n }\n if (attributeMatchFound) {\n continue;\n }\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Checks to make sure the correct SKU is still attached to the order.\n * For example, if you have the SKU for a Large, Red T-shirt in the\n * cart and your UI allows the user to change the one of the attributes\n * (e.g. red to black), then it is possible that the SKU needs to\n * be adjusted as well.\n */\n protected Sku findSkuThatMatchesProductOptions(Product product, Map attributeValues) {\n Map attributeValuesForSku = new HashMap();\n // Verify that required product-option values were set.\n //TODO: update to use the ProductOptionValues on Sku instead of the sku attribute\n /*\n if (product.getProductOptions() != null) {\n for (ProductOption productOption : product.getProductOptions()) {\n if (productOption.getRequired()) {\n if (attributeValues.get(productOption.getAttributeName()) == null) {\n throw new IllegalArgumentException(\"Unable to add to cart. Not all required options were provided.\");\n } else {\n attributeValuesForSku.put(productOption.getAttributeName(), attributeValues.get(productOption.getAttributeName()));\n }\n }\n }\n }\n */\n if (product.getSkus() != null) {\n for (Sku sku : product.getSkus()) {\n if (checkSkuForMatch(sku, attributeValuesForSku)) {\n return sku;\n }\n }\n }\n\n return null;\n }\n\n\n protected DiscreteOrderItem createDiscreteOrderItem(Sku sku, Product product, Category category, int quantity, Map itemAttributes) {\n DiscreteOrderItem item = (DiscreteOrderItem) orderItemDao.create(OrderItemType.DISCRETE);\n item.setSku(sku);\n item.setProduct(product);\n item.setQuantity(quantity);\n item.setCategory(category);\n\n if (itemAttributes != null && itemAttributes.size() > 0) {\n Map orderItemAttributes = new HashMap();\n item.setOrderItemAttributes(orderItemAttributes);\n\n for (String key : itemAttributes.keySet()) {\n String value = itemAttributes.get(key);\n OrderItemAttribute attribute = new OrderItemAttributeImpl();\n attribute.setName(key);\n attribute.setValue(value);\n attribute.setOrderItem(item);\n orderItemAttributes.put(key, attribute);\n }\n }\n\n item.updatePrices();\n item.assignFinalPrice();\n return item;\n }\n\n /**\n * Adds an item to the passed in order.\n *\n * The orderItemRequest can be sparsely populated.\n *\n * When priceOrder is false, the system will not reprice the order. This is more performant in\n * cases such as bulk adds where the repricing could be done for the last item only.\n *\n * @see OrderItemRequestDTO\n * @param orderItemRequestDTO\n * @param priceOrder\n * @return\n */\n @Override\n public Order addItemToOrder(Long orderId, OrderItemRequestDTO orderItemRequestDTO, boolean priceOrder) throws PricingException {\n\n if (orderItemRequestDTO.getQuantity() == null || orderItemRequestDTO.getQuantity() == 0) {\n LOG.debug(\"Not adding item to order because quantity is zero.\");\n return null;\n }\n\n Order order = validateOrder(orderId);\n Product product = validateProduct(orderItemRequestDTO.getProductId());\n Sku sku = determineSku(product, orderItemRequestDTO.getSkuId(), orderItemRequestDTO.getItemAttributes());\n Category category = determineCategory(product, orderItemRequestDTO.getCategoryId());\n\n if (product == null || ! (product instanceof ProductBundle)) {\n DiscreteOrderItem item = createDiscreteOrderItem(sku, product, category, orderItemRequestDTO.getQuantity(), orderItemRequestDTO.getItemAttributes());\n List orderItems = order.getOrderItems();\n orderItems.add(item);\n item.setOrder(order);\n return updateOrder(order, priceOrder);\n } else {\n ProductBundle bundle = (ProductBundle) product;\n BundleOrderItem bundleOrderItem = (BundleOrderItem) orderItemDao.create(OrderItemType.BUNDLE);\n bundleOrderItem.setQuantity(orderItemRequestDTO.getQuantity());\n bundleOrderItem.setCategory(category);\n bundleOrderItem.setSku(sku);\n bundleOrderItem.setName(product.getName());\n bundleOrderItem.setProductBundle(bundle);\n\n for (SkuBundleItem skuBundleItem : bundle.getSkuBundleItems()) {\n Product bundleProduct = skuBundleItem.getBundle();\n Sku bundleSku = skuBundleItem.getSku();\n\n Category bundleCategory = determineCategory(bundleProduct, orderItemRequestDTO.getCategoryId());\n\n DiscreteOrderItem bundleDiscreteItem = createDiscreteOrderItem(bundleSku, bundleProduct, bundleCategory, skuBundleItem.getQuantity(), orderItemRequestDTO.getItemAttributes());\n bundleDiscreteItem.setSkuBundleItem(skuBundleItem);\n bundleDiscreteItem.setBundleOrderItem(bundleOrderItem);\n bundleOrderItem.getDiscreteOrderItems().add(bundleDiscreteItem);\n }\n\n bundleOrderItem.updatePrices();\n bundleOrderItem.assignFinalPrice();\n\n List orderItems = order.getOrderItems();\n orderItems.add(bundleOrderItem);\n bundleOrderItem.setOrder(order);\n return updateOrder(order, priceOrder);\n }\n }\n\n public boolean getAutomaticallyMergeLikeItems() {\n return automaticallyMergeLikeItems;\n }\n\n public void setAutomaticallyMergeLikeItems(boolean automaticallyMergeLikeItems) {\n this.automaticallyMergeLikeItems = automaticallyMergeLikeItems;\n }\n}\n"},"message":{"kind":"string","value":"Fix integration test error.\n"},"old_file":{"kind":"string","value":"core/broadleaf-framework/src/main/java/org/broadleafcommerce/core/order/service/OrderServiceImpl.java"},"subject":{"kind":"string","value":"Fix integration test error."},"git_diff":{"kind":"string","value":"ore/broadleaf-framework/src/main/java/org/broadleafcommerce/core/order/service/OrderServiceImpl.java\n import org.broadleafcommerce.core.catalog.domain.Category;\n import org.broadleafcommerce.core.catalog.domain.Product;\n import org.broadleafcommerce.core.catalog.domain.ProductBundle;\nimport org.broadleafcommerce.core.catalog.domain.ProductOption;\n import org.broadleafcommerce.core.catalog.domain.Sku;\n import org.broadleafcommerce.core.catalog.domain.SkuAttribute;\n import org.broadleafcommerce.core.catalog.domain.SkuBundleItem;\n requestDTO.setItemAttributes(itemAttributes);\n \n Order order = addItemToOrder(orderId, requestDTO, priceOrder);\n if (order == null) {\n return null;\n }\n return findLastMatchingItem(order, skuId, productId);\n }\n \n \n private boolean bundleItemMatches(BundleOrderItem item1, BundleOrderItem item2) {\n if (item1.getSku() != null && item2.getSku() != null) {\n return item1.getSku().getId().equals(item1.getSku().getId());\n return item1.getSku().getId().equals(item2.getSku().getId());\n }\n \n // Otherwise, scan the items.\n } else {\n return false;\n }\n\n // If all of the quantities were consumed, this is a match.\n return skuMap.isEmpty();\n }\n\n return false;\n }\n\n return skuMap.isEmpty();\n }\n \n \n private OrderItem findLastMatchingBundleItem(Order order, BundleOrderItem itemToFind) {\n for (int i=(order.getOrderItems().size()-1); i > 0; i--) {\n for (int i=(order.getOrderItems().size()-1); i >= 0; i--) {\n OrderItem currentItem = (order.getOrderItems().get(i));\n if (currentItem instanceof BundleOrderItem) {\n if (bundleItemMatches((BundleOrderItem) currentItem, itemToFind)) {\n }\n \n private boolean checkSkuForMatch(Sku sku, Map attributeValuesForSku) {\n if (attributeValuesForSku == null || attributeValuesForSku.size() == 0) {\n return false;\n }\n\n for (String attributeName : attributeValuesForSku.keySet()) {\n String attributeValue = attributeValuesForSku.get(attributeName);\n \n }\n }\n */\n if (product.getSkus() != null) {\n if (product !=null && product.getSkus() != null) {\n for (Sku sku : product.getSkus()) {\n if (checkSkuForMatch(sku, attributeValuesForSku)) {\n return sku;\n Order order = validateOrder(orderId);\n Product product = validateProduct(orderItemRequestDTO.getProductId());\n Sku sku = determineSku(product, orderItemRequestDTO.getSkuId(), orderItemRequestDTO.getItemAttributes());\n if (sku == null) {\n return null;\n }\n Category category = determineCategory(product, orderItemRequestDTO.getCategoryId());\n \n if (product == null || ! (product instanceof ProductBundle)) {"}}},{"rowIdx":1951,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"9d3874f25070060c92aa89036f48d3582c074868"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"eBaoTech/pinpoint,Skkeem/pinpoint,breadval/pinpoint,KimTaehee/pinpoint,suraj-raturi/pinpoint,PerfGeeks/pinpoint,andyspan/pinpoint,87439247/pinpoint,InfomediaLtd/pinpoint,cit-lab/pinpoint,hcapitaine/pinpoint,hcapitaine/pinpoint,chenguoxi1985/pinpoint,jaehong-kim/pinpoint,andyspan/pinpoint,dawidmalina/pinpoint,naver/pinpoint,barneykim/pinpoint,PerfGeeks/pinpoint,sjmittal/pinpoint,denzelsN/pinpoint,emeroad/pinpoint,sbcoba/pinpoint,tsyma/pinpoint,suraj-raturi/pinpoint,philipz/pinpoint,KRDeNaT/pinpoint,KimTaehee/pinpoint,PerfGeeks/pinpoint,naver/pinpoint,nstopkimsk/pinpoint,shuvigoss/pinpoint,barneykim/pinpoint,jiaqifeng/pinpoint,philipz/pinpoint,krishnakanthpps/pinpoint,KimTaehee/pinpoint,sjmittal/pinpoint,sjmittal/pinpoint,koo-taejin/pinpoint,tsyma/pinpoint,emeroad/pinpoint,Skkeem/pinpoint,minwoo-jung/pinpoint,eBaoTech/pinpoint,citywander/pinpoint,eBaoTech/pinpoint,Allive1/pinpoint,cit-lab/pinpoint,masonmei/pinpoint,cijung/pinpoint,PerfGeeks/pinpoint,InfomediaLtd/pinpoint,PerfGeeks/pinpoint,citywander/pinpoint,gspandy/pinpoint,denzelsN/pinpoint,majinkai/pinpoint,jiaqifeng/pinpoint,denzelsN/pinpoint,barneykim/pinpoint,sbcoba/pinpoint,naver/pinpoint,sjmittal/pinpoint,gspandy/pinpoint,philipz/pinpoint,andyspan/pinpoint,nstopkimsk/pinpoint,cit-lab/pinpoint,PerfGeeks/pinpoint,wziyong/pinpoint,Allive1/pinpoint,sbcoba/pinpoint,majinkai/pinpoint,krishnakanthpps/pinpoint,minwoo-jung/pinpoint,Xylus/pinpoint,lioolli/pinpoint,lioolli/pinpoint,barneykim/pinpoint,KimTaehee/pinpoint,denzelsN/pinpoint,nstopkimsk/pinpoint,masonmei/pinpoint,suraj-raturi/pinpoint,Xylus/pinpoint,krishnakanthpps/pinpoint,jaehong-kim/pinpoint,wziyong/pinpoint,breadval/pinpoint,KRDeNaT/pinpoint,KRDeNaT/pinpoint,jaehong-kim/pinpoint,carpedm20/pinpoint,tsyma/pinpoint,coupang/pinpoint,denzelsN/pinpoint,Xylus/pinpoint,coupang/pinpoint,hcapitaine/pinpoint,InfomediaLtd/pinpoint,wziyong/pinpoint,naver/pinpoint,87439247/pinpoint,andyspan/pinpoint,krishnakanthpps/pinpoint,InfomediaLtd/pinpoint,philipz/pinpoint,chenguoxi1985/pinpoint,cijung/pinpoint,Allive1/pinpoint,chenguoxi1985/pinpoint,cijung/pinpoint,jaehong-kim/pinpoint,masonmei/pinpoint,citywander/pinpoint,minwoo-jung/pinpoint,emeroad/pinpoint,InfomediaLtd/pinpoint,breadval/pinpoint,shuvigoss/pinpoint,hcapitaine/pinpoint,tsyma/pinpoint,philipz/pinpoint,cit-lab/pinpoint,shuvigoss/pinpoint,dawidmalina/pinpoint,wziyong/pinpoint,Allive1/pinpoint,sbcoba/pinpoint,lioolli/pinpoint,coupang/pinpoint,andyspan/pinpoint,Xylus/pinpoint,lioolli/pinpoint,Skkeem/pinpoint,Skkeem/pinpoint,gspandy/pinpoint,wziyong/pinpoint,eBaoTech/pinpoint,krishnakanthpps/pinpoint,emeroad/pinpoint,koo-taejin/pinpoint,jiaqifeng/pinpoint,krishnakanthpps/pinpoint,masonmei/pinpoint,cijung/pinpoint,coupang/pinpoint,chenguoxi1985/pinpoint,hcapitaine/pinpoint,suraj-raturi/pinpoint,tsyma/pinpoint,Xylus/pinpoint,minwoo-jung/pinpoint,emeroad/pinpoint,jiaqifeng/pinpoint,majinkai/pinpoint,majinkai/pinpoint,shuvigoss/pinpoint,lioolli/pinpoint,InfomediaLtd/pinpoint,chenguoxi1985/pinpoint,citywander/pinpoint,chenguoxi1985/pinpoint,KimTaehee/pinpoint,jiaqifeng/pinpoint,eBaoTech/pinpoint,denzelsN/pinpoint,sbcoba/pinpoint,barneykim/pinpoint,barneykim/pinpoint,suraj-raturi/pinpoint,gspandy/pinpoint,majinkai/pinpoint,koo-taejin/pinpoint,jiaqifeng/pinpoint,naver/pinpoint,jaehong-kim/pinpoint,breadval/pinpoint,dawidmalina/pinpoint,majinkai/pinpoint,denzelsN/pinpoint,koo-taejin/pinpoint,carpedm20/pinpoint,KRDeNaT/pinpoint,lioolli/pinpoint,koo-taejin/pinpoint,andyspan/pinpoint,masonmei/pinpoint,carpedm20/pinpoint,sbcoba/pinpoint,dawidmalina/pinpoint,minwoo-jung/pinpoint,minwoo-jung/pinpoint,nstopkimsk/pinpoint,87439247/pinpoint,sjmittal/pinpoint,Skkeem/pinpoint,emeroad/pinpoint,Allive1/pinpoint,Xylus/pinpoint,gspandy/pinpoint,87439247/pinpoint,philipz/pinpoint,breadval/pinpoint,citywander/pinpoint,87439247/pinpoint,citywander/pinpoint,breadval/pinpoint,Skkeem/pinpoint,carpedm20/pinpoint,gspandy/pinpoint,KimTaehee/pinpoint,coupang/pinpoint,Allive1/pinpoint,KRDeNaT/pinpoint,koo-taejin/pinpoint,dawidmalina/pinpoint,carpedm20/pinpoint,nstopkimsk/pinpoint,eBaoTech/pinpoint,hcapitaine/pinpoint,shuvigoss/pinpoint,cit-lab/pinpoint,cit-lab/pinpoint,Xylus/pinpoint,cijung/pinpoint,masonmei/pinpoint,barneykim/pinpoint,87439247/pinpoint,dawidmalina/pinpoint,tsyma/pinpoint,suraj-raturi/pinpoint,jaehong-kim/pinpoint,shuvigoss/pinpoint,nstopkimsk/pinpoint,sjmittal/pinpoint,KRDeNaT/pinpoint,coupang/pinpoint,wziyong/pinpoint,cijung/pinpoint"},"new_contents":{"kind":"string","value":"package com.profiler.modifier.db.interceptor;\r\n\r\nimport java.util.Arrays;\r\nimport java.util.Collections;\r\nimport java.util.HashMap;\r\nimport java.util.Map;\r\n\r\nimport com.profiler.interceptor.*;\r\nimport com.profiler.logging.Logger;\r\n\r\nimport com.profiler.common.AnnotationKey;\r\nimport com.profiler.common.util.ParsingResult;\r\nimport com.profiler.context.Trace;\r\nimport com.profiler.context.TraceContext;\r\nimport com.profiler.interceptor.util.JDBCScope;\r\nimport com.profiler.logging.LoggerFactory;\r\nimport com.profiler.modifier.db.DatabaseInfo;\r\nimport com.profiler.util.MetaObject;\r\n\r\npublic class PreparedStatementExecuteQueryInterceptor implements SimpleAroundInterceptor, ByteCodeMethodDescriptorSupport, TraceContextSupport {\r\n\r\n private final Logger logger = LoggerFactory.getLogger(PreparedStatementExecuteQueryInterceptor.class.getName());\r\n private final boolean isDebug = logger.isDebugEnabled();\r\n\r\n private final MetaObject getSql = new MetaObject(\"__getSql\");\r\n private final MetaObject getUrl = new MetaObject(\"__getUrl\");\r\n private final MetaObject getBindValue = new MetaObject(\"__getBindValue\");\r\n private final MetaObject setBindValue = new MetaObject(\"__setBindValue\", Map.class);\r\n\r\n private MethodDescriptor descriptor;\r\n private TraceContext traceContext;\r\n\r\n @Override\r\n public void before(Object target, Object[] args) {\r\n if (isDebug) {\r\n logger.beforeInterceptor(target, args);\r\n }\r\n if (JDBCScope.isInternal()) {\r\n logger.debug(\"internal jdbc scope. skip trace\");\r\n return;\r\n }\r\n Trace trace = traceContext.currentTraceObject();\r\n if (trace == null) {\r\n return;\r\n }\r\n\r\n trace.traceBlockBegin();\r\n trace.markBeforeTime();\r\n try {\r\n DatabaseInfo databaseInfo = (DatabaseInfo) getUrl.invoke(target);\r\n\r\n trace.recordServiceType(databaseInfo.getExecuteQueryType());\r\n\r\n trace.recordEndPoint(databaseInfo.getMultipleHost());\r\n trace.recordDestinationId(databaseInfo.getDatabaseId());\r\n trace.recordDestinationAddress(databaseInfo.getHost());\r\n\r\n ParsingResult parsingResult = (ParsingResult) getSql.invoke(target);\r\n\r\n trace.recordSqlParsingResult(parsingResult);\r\n\r\n Map bindValue = getBindValue.invoke(target);\r\n String bindString = toBindVariable(bindValue);\r\n if (bindString != null && bindString.length() != 0) {\r\n trace.recordAttribute(AnnotationKey.SQL_BINDVALUE, bindString);\r\n }\r\n\r\n trace.recordApi(descriptor);\r\n// trace.recordApi(apiId);\r\n // clean 타이밍을 변경해야 될듯 하다.\r\n clean(target);\r\n\r\n\r\n } catch (Exception e) {\r\n if (logger.isWarnEnabled()) {\r\n logger.warn(e.getMessage(), e);\r\n }\r\n }\r\n\r\n }\r\n\r\n private void clean(Object target) {\r\n setBindValue.invoke(target, Collections.synchronizedMap(new HashMap()));\r\n }\r\n\r\n private String toBindVariable(Map bindValue) {\r\n String[] temp = new String[bindValue.size()];\r\n for (Object obj : bindValue.entrySet()) {\r\n Map.Entry entry = (Map.Entry) obj;\r\n Integer key = entry.getKey() - 1;\r\n if (temp.length < key) {\r\n continue;\r\n }\r\n temp[key] = entry.getValue();\r\n }\r\n\r\n return bindValueToString(temp);\r\n\r\n }\r\n\r\n private String bindValueToString(String[] temp) {\r\n if (temp == null) {\r\n return \"\";\r\n }\r\n StringBuilder sb = new StringBuilder();\r\n int end = temp.length - 1;\r\n for (int i = 0; i < temp.length; i++) {\r\n sb.append(temp[i]);\r\n if (i < end) {\r\n sb.append(\", \");\r\n }\r\n }\r\n return sb.toString();\r\n }\r\n\r\n @Override\r\n public void after(Object target, Object[] args, Object result) {\r\n if (isDebug) {\r\n logger.afterInterceptor(target, args, result);\r\n }\r\n if (JDBCScope.isInternal()) {\r\n return;\r\n }\r\n Trace trace = traceContext.currentTraceObject();\r\n if (trace == null) {\r\n return;\r\n }\r\n\r\n try {\r\n // TODO 일단 테스트로 실패일경우 종료 아닐경우 resultset fetch까지 계산. fetch count는 옵션으로 빼는게 좋을듯.\r\n trace.recordException(result);\r\n } catch (Exception e) {\r\n if (logger.isWarnEnabled()) {\r\n logger.warn(e.getMessage(), e);\r\n }\r\n } finally {\r\n trace.markAfterTime();\r\n trace.traceBlockEnd();\r\n }\r\n }\r\n\r\n @Override\r\n public void setMethodDescriptor(MethodDescriptor descriptor) {\r\n this.descriptor = descriptor;\r\n traceContext.cacheApi(descriptor);\r\n }\r\n\r\n\r\n @Override\r\n public void setTraceContext(TraceContext traceContext) {\r\n this.traceContext = traceContext;\r\n }\r\n}\r\n"},"new_file":{"kind":"string","value":"src/main/java/com/profiler/modifier/db/interceptor/PreparedStatementExecuteQueryInterceptor.java"},"old_contents":{"kind":"string","value":"package com.profiler.modifier.db.interceptor;\r\n\r\nimport java.util.Arrays;\r\nimport java.util.Collections;\r\nimport java.util.HashMap;\r\nimport java.util.Map;\r\n\r\nimport com.profiler.interceptor.*;\r\nimport com.profiler.logging.Logger;\r\n\r\nimport com.profiler.common.AnnotationKey;\r\nimport com.profiler.common.util.ParsingResult;\r\nimport com.profiler.context.Trace;\r\nimport com.profiler.context.TraceContext;\r\nimport com.profiler.interceptor.util.JDBCScope;\r\nimport com.profiler.logging.LoggerFactory;\r\nimport com.profiler.modifier.db.DatabaseInfo;\r\nimport com.profiler.util.MetaObject;\r\n\r\npublic class PreparedStatementExecuteQueryInterceptor implements SimpleAroundInterceptor, ByteCodeMethodDescriptorSupport, TraceContextSupport {\r\n\r\n private final Logger logger = LoggerFactory.getLogger(PreparedStatementExecuteQueryInterceptor.class.getName());\r\n private final boolean isDebug = logger.isDebugEnabled();\r\n\r\n private final MetaObject getSql = new MetaObject(\"__getSql\");\r\n private final MetaObject getUrl = new MetaObject(\"__getUrl\");\r\n private final MetaObject getBindValue = new MetaObject(\"__getBindValue\");\r\n private final MetaObject setBindValue = new MetaObject(\"__setBindValue\", Map.class);\r\n\r\n private MethodDescriptor descriptor;\r\n private TraceContext traceContext;\r\n\r\n @Override\r\n public void before(Object target, Object[] args) {\r\n if (isDebug) {\r\n logger.beforeInterceptor(target, args);\r\n }\r\n if (JDBCScope.isInternal()) {\r\n logger.debug(\"internal jdbc scope. skip trace\");\r\n return;\r\n }\r\n Trace trace = traceContext.currentTraceObject();\r\n if (trace == null) {\r\n return;\r\n }\r\n\r\n trace.traceBlockBegin();\r\n trace.markBeforeTime();\r\n try {\r\n DatabaseInfo databaseInfo = (DatabaseInfo) getUrl.invoke(target);\r\n\r\n trace.recordServiceType(databaseInfo.getExecuteQueryType());\r\n\r\n trace.recordEndPoint(databaseInfo.getMultipleHost());\r\n trace.recordDestinationId(databaseInfo.getDatabaseId());\r\n trace.recordDestinationAddress(databaseInfo.getHost());\r\n\r\n ParsingResult parsingResult = (ParsingResult) getSql.invoke(target);\r\n\r\n trace.recordSqlParsingResult(parsingResult);\r\n\r\n Map bindValue = getBindValue.invoke(target);\r\n String bindString = toBindVariable(bindValue);\r\n trace.recordAttribute(AnnotationKey.SQL_BINDVALUE, bindString);\r\n\r\n trace.recordApi(descriptor);\r\n// trace.recordApi(apiId);\r\n // clean 타이밍을 변경해야 될듯 하다.\r\n clean(target);\r\n\r\n\r\n } catch (Exception e) {\r\n if (logger.isWarnEnabled()) {\r\n logger.warn(e.getMessage(), e);\r\n }\r\n }\r\n\r\n }\r\n\r\n private void clean(Object target) {\r\n setBindValue.invoke(target, Collections.synchronizedMap(new HashMap()));\r\n }\r\n\r\n private String toBindVariable(Map bindValue) {\r\n String[] temp = new String[bindValue.size()];\r\n for (Object obj : bindValue.entrySet()) {\r\n Map.Entry entry = (Map.Entry) obj;\r\n Integer key = entry.getKey() - 1;\r\n if (temp.length < key) {\r\n continue;\r\n }\r\n temp[key] = entry.getValue();\r\n }\r\n\r\n return bindValueToString(temp);\r\n\r\n }\r\n\r\n private String bindValueToString(String[] temp) {\r\n if (temp == null) {\r\n return \"\";\r\n }\r\n StringBuilder sb = new StringBuilder();\r\n int end = temp.length - 1;\r\n for (int i = 0; i < temp.length; i++) {\r\n sb.append(temp[i]);\r\n if (i < end) {\r\n sb.append(\", \");\r\n }\r\n }\r\n return sb.toString();\r\n }\r\n\r\n @Override\r\n public void after(Object target, Object[] args, Object result) {\r\n if (isDebug) {\r\n logger.afterInterceptor(target, args, result);\r\n }\r\n if (JDBCScope.isInternal()) {\r\n return;\r\n }\r\n Trace trace = traceContext.currentTraceObject();\r\n if (trace == null) {\r\n return;\r\n }\r\n\r\n try {\r\n // TODO 일단 테스트로 실패일경우 종료 아닐경우 resultset fetch까지 계산. fetch count는 옵션으로 빼는게 좋을듯.\r\n trace.recordException(result);\r\n } catch (Exception e) {\r\n if (logger.isWarnEnabled()) {\r\n logger.warn(e.getMessage(), e);\r\n }\r\n } finally {\r\n trace.markAfterTime();\r\n trace.traceBlockEnd();\r\n }\r\n }\r\n\r\n @Override\r\n public void setMethodDescriptor(MethodDescriptor descriptor) {\r\n this.descriptor = descriptor;\r\n traceContext.cacheApi(descriptor);\r\n }\r\n\r\n\r\n @Override\r\n public void setTraceContext(TraceContext traceContext) {\r\n this.traceContext = traceContext;\r\n }\r\n}\r\n"},"message":{"kind":"string","value":"[강운덕] [LUCYSUS-1744] preparedstatement의 bind value 값이 없을 경우 레코딩을 하지 않도록 수정.\n\ngit-svn-id: 0b0b9d2345dd6c69dda6a7bc6c9d6f99a5385c2e@1598 84d0f5b1-2673-498c-a247-62c4ff18d310\n"},"old_file":{"kind":"string","value":"src/main/java/com/profiler/modifier/db/interceptor/PreparedStatementExecuteQueryInterceptor.java"},"subject":{"kind":"string","value":"[강운덕] [LUCYSUS-1744] preparedstatement의 bind value 값이 없을 경우 레코딩을 하지 않도록 수정."},"git_diff":{"kind":"string","value":"rc/main/java/com/profiler/modifier/db/interceptor/PreparedStatementExecuteQueryInterceptor.java\n \n Map bindValue = getBindValue.invoke(target);\n String bindString = toBindVariable(bindValue);\n trace.recordAttribute(AnnotationKey.SQL_BINDVALUE, bindString);\n if (bindString != null && bindString.length() != 0) {\n trace.recordAttribute(AnnotationKey.SQL_BINDVALUE, bindString);\n }\n \n trace.recordApi(descriptor);\n // trace.recordApi(apiId);"}}},{"rowIdx":1952,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"lgpl-2.1"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"fe368d1ac1390159a768c898c1914f246367bbb2"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"javachengwc/jforum3,0359xiaodong/jforum3,javachengwc/jforum3,shower1986/jforum,eclipse123/JForum,javachengwc/jforum3,eclipse123/JForum,mingyaaaa/jforum3,ippxie/jforum3,hafizullah/jforum3-maven,rafaelsteil/jforum3,mingyaaaa/jforum3,rafaelsteil/jforum3,ippxie/jforum3,eclipse123/JForum,mingyaaaa/jforum3,rafaelsteil/jforum3,shower1986/jforum,ippxie/jforum3,0359xiaodong/jforum3,0359xiaodong/jforum3,hafizullah/jforum3-maven"},"new_contents":{"kind":"string","value":"/*\n * Copyright (c) JForum Team. All rights reserved.\n *\n * The software in this package is published under the terms of the LGPL\n * license a copy of which has been included with this distribution in the\n * license.txt file.\n *\n * The JForum Project\n * http://www.jforum.net\n */\npackage net.jforum.actions;\n\n\n/**\n * @author Rafael Steil\n */\npublic class AdminActionsTestCase extends AdminTestCase {\n\n public AdminActionsTestCase() {\n super(AdminActions.class);\n }\n}\n"},"new_file":{"kind":"string","value":"src/test/java/net/jforum/actions/AdminActionsTestCase.java"},"old_contents":{"kind":"string","value":"/*\n * Copyright (c) JForum Team. All rights reserved.\n *\n * The software in this package is published under the terms of the LGPL\n * license a copy of which has been included with this distribution in the\n * license.txt file.\n *\n * The JForum Project\n * http://www.jforum.net\n */\npackage net.jforum.actions;\n\n\n/**\n * @author Rafael Steil\n */\npublic class AdminActionsTestCase extends AdminTestCase {\n\tpublic AdminActionsTestCase() {\n\t\tsuper(AdminActions.class);\n\t}\n}\n"},"message":{"kind":"string","value":"Small formatting\n"},"old_file":{"kind":"string","value":"src/test/java/net/jforum/actions/AdminActionsTestCase.java"},"subject":{"kind":"string","value":"Small formatting"},"git_diff":{"kind":"string","value":"rc/test/java/net/jforum/actions/AdminActionsTestCase.java\n * @author Rafael Steil\n */\n public class AdminActionsTestCase extends AdminTestCase {\n\tpublic AdminActionsTestCase() {\n\t\tsuper(AdminActions.class);\n\t}\n\n public AdminActionsTestCase() {\n super(AdminActions.class);\n }\n }"}}},{"rowIdx":1953,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"13447ce89916c22a5ba277bd729e1b28fe5df4ea"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"tascape/thx-ios,tascape/thx-ios"},"new_contents":{"kind":"string","value":"/*\n * Copyright 2016 tascape.\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.tascape.qa.th.ios.driver;\n\nimport com.tascape.qa.th.ios.model.UIA;\nimport org.libimobiledevice.ios.driver.binding.exceptions.SDKException;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport com.tascape.qa.th.SystemConfiguration;\nimport com.tascape.qa.th.Utils;\nimport com.tascape.qa.th.ios.comm.Instruments;\nimport com.tascape.qa.th.ios.model.DeviceOrientation;\nimport com.tascape.qa.th.ios.model.UIAAlert;\nimport com.tascape.qa.th.ios.model.UIAApplication;\nimport com.tascape.qa.th.ios.model.UIAElement;\nimport com.tascape.qa.th.ios.model.UIAException;\nimport com.tascape.qa.th.ios.model.UIATarget;\nimport com.tascape.qa.th.ios.model.UIAWindow;\nimport java.awt.Dimension;\nimport java.awt.geom.Point2D;\nimport java.awt.geom.Rectangle2D;\nimport java.util.List;\nimport org.apache.commons.lang3.StringUtils;\n\n/**\n *\n * @author linsong wang\n */\npublic class UiAutomationDevice extends LibIMobileDevice implements UIATarget, UIAApplication {\n private static final Logger LOG = LoggerFactory.getLogger(UiAutomationDevice.class);\n\n public static final String SYSPROP_TIMEOUT_SECOND = \"qa.th.driver.ios.TIMEOUT_SECOND\";\n\n public static final String TRACE_TEMPLATE = \"/Applications/Xcode.app/Contents/Applications/Instruments.app/Contents\"\n + \"/PlugIns/AutomationInstrument.xrplugin/Contents/Resources/Automation.tracetemplate\";\n\n public static final int TIMEOUT_SECOND\n = SystemConfiguration.getInstance().getIntProperty(SYSPROP_TIMEOUT_SECOND, 120);\n\n private Instruments instruments;\n\n private Dimension screenDimension;\n\n private String alertHandler = \"\";\n\n public UiAutomationDevice() throws SDKException {\n this(LibIMobileDevice.getAllUuids().get(0));\n }\n\n public UiAutomationDevice(String uuid) throws SDKException {\n super(uuid);\n }\n\n public void start(String appName, int delayMillis) throws Exception {\n if (instruments != null) {\n instruments.disconnect();\n } else {\n instruments = new Instruments(getUuid(), appName);\n }\n if (StringUtils.isNotEmpty(alertHandler)) {\n instruments.setPreTargetJavaScript(alertHandler);\n }\n instruments.connect();\n Utils.sleep(delayMillis, \"Wait for app to start\");\n long end = System.currentTimeMillis() + TIMEOUT_SECOND * 1000;\n while (end > System.currentTimeMillis()) {\n try {\n if (this.instruments.runJavaScript(\"window.logElement();\").stream()\n .filter(l -> l.contains(UIAWindow.class.getSimpleName())).findAny().isPresent()) {\n return;\n }\n } catch (Exception ex) {\n LOG.warn(ex.getMessage());\n Thread.sleep(5000);\n }\n }\n throw new UIAException(\"Cannot start app \");\n }\n\n public void stop() {\n if (instruments != null) {\n instruments.shutdown();\n }\n }\n\n public void setAlertHandler(String javaScript) {\n this.alertHandler = javaScript;\n }\n\n public List runJavaScript(String javaScript) throws UIAException {\n return instruments.runJavaScript(javaScript);\n }\n\n public List loadElementTree() throws UIAException {\n return instruments.runJavaScript(\"window.logElementTree();\");\n }\n\n /**\n * Gets the screen size in points.\n * http://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions\n *\n * @return the screen size in points\n *\n * @throws UIAException in case of any issue\n */\n public Dimension getDisplaySize() throws UIAException {\n if (screenDimension == null) {\n screenDimension = loadDisplaySize();\n }\n return screenDimension;\n }\n\n /**\n * Checks if an element exists on current UI, based on element type.\n *\n * @param sub-class of UIAElement\n * @param javaScript such as \"window.tabBars()['MainTabBar']\"\n * @param type type of uia element, such as UIATabBar\n *\n * @return true if element identified by javascript exists\n *\n * @throws UIAException in case of any issue\n */\n public boolean doesElementExist(String javaScript, Class type) throws UIAException {\n return doesElementExist(javaScript, type, null);\n }\n\n /**\n * Checks if an element exists on current UI, based on element type and name.\n *\n * @param sub-class of UIAElement\n * @param javaScript the javascript that uniquely identify the element, such as \"window.tabBars()['MainTabBar']\",\n * or \"window.elements()[1].buttons()[0]\"\n * @param type type of uia element, such as UIATabBar\n * @param name name of an element, such as \"MainTabBar\"\n *\n * @return true if element identified by javascript exists\n *\n * @throws UIAException in case of any issue\n */\n public boolean doesElementExist(String javaScript, Class type, String name) throws\n UIAException {\n String js = \"var e = \" + javaScript + \"; e.logElement();\";\n return instruments.runJavaScript(js).stream()\n .filter(line -> line.contains(type.getSimpleName()))\n .filter(line -> StringUtils.isEmpty(name) ? true : line.contains(name))\n .findFirst().isPresent();\n }\n\n /**\n * Checks if an element exists on current UI, based on element type and name. This method loads full element tree.\n *\n * @param sub-class of UIAElement\n * @param type type of uia element, such as UIATabBar\n * @param name name of an element, such as \"MainTabBar\"\n *\n * @return true if element identified by type and name exists, or false if timeout\n *\n * @throws UIAException in case of any issue\n */\n public boolean doesElementExist(Class type, String name) throws UIAException {\n return mainWindow().findElement(type, name) != null;\n }\n\n /**\n * Waits for an element exists on current UI, based on element type.\n *\n * @param sub-class of UIAElement\n * @param javaScript the javascript that uniquely identify the element, such as \"window.tabBars()['MainTabBar']\",\n * or \"window.elements()[1].buttons()[0]\"\n * @param type type of uia element, such as UIATabBar\n *\n * @return true if element identified by javascript exists, or false if timeout\n *\n * @throws UIAException in case of UIA issue\n * @throws java.lang.InterruptedException in case of interruption\n */\n public boolean waitForElement(String javaScript, Class type)\n throws UIAException, InterruptedException {\n return this.waitForElement(javaScript, type, null);\n }\n\n /**\n * Waits for an element exists on current UI, based on element type and name.\n *\n * @param sub-class of UIAElement\n * @param javaScript the javascript that uniquely identify the element, such as \"window.tabBars()['MainTabBar']\",\n * or \"window.elements()[1].buttons()[0]\"\n * @param type type of uia element, such as UIATabBar\n * @param name name of an element, such as \"MainTabBar\"\n *\n * @return true if element identified by javascript exists, or false if timeout\n *\n * @throws UIAException in case of UIA issue\n * @throws java.lang.InterruptedException in case of interruption\n */\n public boolean waitForElement(String javaScript, Class type, String name)\n throws UIAException, InterruptedException {\n long end = System.currentTimeMillis() + TIMEOUT_SECOND * 1000;\n while (System.currentTimeMillis() < end) {\n if (doesElementExist(javaScript, type, name)) {\n return true;\n }\n Utils.sleep(1000, \"wait for \" + type + \"[\" + name + \"]\");\n }\n return false;\n }\n\n /**\n * Waits for an element exists on current UI, based on element type and name. This method loads full element tree.\n *\n * @param sub-class of UIAElement\n * @param type type of uia element, such as UIATabBar\n * @param name name of an element, such as \"MainTabBar\"\n *\n * @return true if element identified by type and name exists, or false if timeout\n *\n * @throws UIAException in case of UIA issue\n * @throws java.lang.InterruptedException in case of interruption\n */\n public boolean waitForElement(Class type, String name) throws UIAException,\n InterruptedException {\n long end = System.currentTimeMillis() + TIMEOUT_SECOND * 1000;\n while (System.currentTimeMillis() < end) {\n try {\n if (mainWindow().findElement(type, name) != null) {\n return true;\n }\n } catch (Exception ex) {\n LOG.warn(\"{}\", ex.getMessage());\n Thread.sleep(10000);\n }\n Utils.sleep(5000, \"wait for \" + type.getSimpleName() + \"[\" + name + \"]\");\n }\n return false;\n }\n\n public String getElementName(String javaScript, Class type) throws UIAException {\n String js = \"var e = \" + javaScript + \"; e.logElement();\";\n String line = instruments.runJavaScript(js).stream()\n .filter(l -> l.contains(type.getSimpleName())).findFirst().get();\n return UIA.parseElement(line).name();\n }\n\n public String getElementValue(String javaScript, Class type) throws UIAException {\n String js = \"var e = \" + javaScript + \"; UIALogger.logMessage(e.value());\";\n return Instruments.getLogMessage(instruments.runJavaScript(js));\n }\n\n public void setTextField(String javaScript, String value) throws UIAException {\n String js = \"var e = \" + javaScript + \"; e.setValue('\" + value + \"');\";\n instruments.runJavaScript(js).forEach(l -> LOG.trace(l));\n }\n\n @Override\n public UIAWindow mainWindow() throws UIAException {\n List lines = loadElementTree();\n UIAWindow window = UIA.parseElementTree(lines);\n window.setInstruments(instruments);\n return window;\n }\n\n @Override\n public void deactivateAppForDuration(int duration) throws UIAException {\n instruments.runJavaScript(\"UIALogger.logMessage(target.deactivateAppForDuration(\" + duration + \"));\");\n }\n\n @Override\n public String model() throws UIAException {\n return Instruments.getLogMessage(instruments.runJavaScript(\"UIALogger.logMessage(target.model());\"));\n }\n\n @Override\n public String name() throws UIAException {\n return Instruments.getLogMessage(instruments.runJavaScript(\"UIALogger.logMessage(target.name());\"));\n }\n\n @Override\n public Rectangle2D.Float rect() throws UIAException {\n List lines = instruments.runJavaScript(\"UIALogger.logMessage(target.rect());\");\n throw new UnsupportedOperationException(\"Not supported yet.\");\n }\n\n @Override\n public String systemName() throws UIAException {\n return Instruments.getLogMessage(instruments.runJavaScript(\"UIALogger.logMessage(target.systemName());\"));\n }\n\n @Override\n public String systemVersion() throws UIAException {\n return Instruments.getLogMessage(instruments.runJavaScript(\"UIALogger.logMessage(target.systemVersion());\"));\n }\n\n @Override\n public DeviceOrientation deviceOrientation() throws UIAException {\n instruments.runJavaScript(\"UIALogger.logMessage(target.deviceOrientation());\");\n throw new UnsupportedOperationException(\"Not supported yet.\");\n }\n\n @Override\n public void setDeviceOrientation(DeviceOrientation orientation) throws UIAException {\n instruments.runJavaScript(\"target.setDeviceOrientation(\" + orientation.ordinal() + \");\");\n throw new UnsupportedOperationException(\"Not supported yet.\");\n }\n\n @Override\n public void setLocation(double latitude, double longitude) throws UIAException {\n instruments.runJavaScript(\"target.setLocation({latitude:\" + latitude + \", longitude:\" + longitude + \"});\");\n }\n\n @Override\n public void clickVolumeDown() throws UIAException {\n this.instruments.runJavaScript(\"target.clickVolumeDown();\");\n }\n\n @Override\n public void clickVolumeUp() throws UIAException {\n this.instruments.runJavaScript(\"target.clickVolumeUp();\");\n }\n\n @Override\n public void holdVolumeDown(int duration) throws UIAException {\n this.instruments.runJavaScript(\"target.holdVolumeDown(\" + duration + \");\");\n }\n\n @Override\n public void holdVolumeUp(int duration) throws UIAException {\n this.instruments.runJavaScript(\"target.holdVolumeUp(\" + duration + \");\");\n }\n\n @Override\n public void lockForDuration(int duration) throws UIAException {\n this.instruments.runJavaScript(\"target.lockForDuration(\" + duration + \");\");\n }\n\n @Override\n public void shake() throws UIAException {\n this.instruments.runJavaScript(\"target.shake();\");\n }\n\n public void dragHalfScreenUp() throws UIAException {\n Dimension dimension = this.getDisplaySize();\n this.dragFromToForDuration(new Point2D.Float(dimension.width / 2, dimension.height / 2),\n new Point2D.Float(dimension.width / 2, 0), 1);\n }\n\n public void dragHalfScreenDown() throws UIAException {\n Dimension dimension = this.getDisplaySize();\n this.dragFromToForDuration(new Point2D.Float(dimension.width / 2, dimension.height / 2),\n new Point2D.Float(dimension.width / 2, dimension.height), 1);\n }\n\n @Override\n public void dragFromToForDuration(Point2D.Float from, Point2D.Float to, int duration) throws UIAException {\n this.instruments.runJavaScript(\"target.dragFromToForDuration(\" + toCGString(from) + \", \"\n + toCGString(to) + \", \" + duration + \");\");\n }\n\n @Override\n public void dragFromToForDuration(UIAElement fromElement, UIAElement toElement, int duration) throws UIAException {\n this.dragFromToForDuration(fromElement.toJavaScript(), toElement.toJavaScript(), duration);\n }\n\n @Override\n public void dragFromToForDuration(String fromJavaScript, String toJavaScript, int duration) throws UIAException {\n this.instruments.runJavaScript(\"var e1 = \" + fromJavaScript + \"; var e2 = \" + toJavaScript + \"; \"\n + \"target.dragFromToForDuration(e1, e2, \" + duration + \");\");\n }\n\n @Override\n public void doubleTap(float x, float y) throws UIAException {\n this.instruments.runJavaScript(\"target.doubleTap(\" + toCGString(x, y) + \");\");\n }\n\n @Override\n public void doubleTap(UIAElement element) throws UIAException {\n this.doubleTap(element.toJavaScript());\n }\n\n @Override\n public void doubleTap(String javaScript) throws UIAException {\n this.instruments.runJavaScript(\"var e = \" + javaScript + \"; e.doubleTap();\");\n }\n\n @Override\n public void flickFromTo(Point2D.Float from, Point2D.Float to, int duration) throws UIAException {\n this.instruments.runJavaScript(\n \"target.flickFromTo(\" + toCGString(from) + \", \" + toCGString(to) + \", \" + duration + \");\");\n }\n\n @Override\n public void flickFromTo(UIAElement fromElement, UIAElement toElement, int duration) throws UIAException {\n this.flickFromTo(fromElement.toJavaScript(), toElement.toJavaScript(), duration);\n }\n\n @Override\n public void flickFromTo(String fromJavaScript, String toJavaScript, int duration) throws UIAException {\n this.instruments.runJavaScript(\"var e1 = \" + fromJavaScript + \"; var e2 = \" + toJavaScript + \"; \"\n + \"target.flickFromTo(e1, e2, \" + duration + \");\");\n }\n\n @Override\n public void pinchCloseFromToForDuration(Point2D.Float from, Point2D.Float to, int duration) throws UIAException {\n this.instruments.runJavaScript(\"target.pinchCloseFromToForDuration(\" + toCGString(from) + \", \"\n + toCGString(to) + \", \" + duration + \");\");\n }\n\n @Override\n public void pinchCloseFromToForDuration(UIAElement fromElement, UIAElement toElement, int duration) throws\n UIAException {\n this.pinchCloseFromToForDuration(fromElement.toJavaScript(), toElement.toJavaScript(), duration);\n }\n\n @Override\n public void pinchCloseFromToForDuration(String fromJavaScript, String toJavaScript, int duration) throws\n UIAException {\n this.instruments.runJavaScript(\"var e1 = \" + fromJavaScript + \"; var e2 = \" + toJavaScript + \"; \"\n + \"target.pinchCloseFromToForDuration(e1, e2, \" + duration + \");\");\n }\n\n @Override\n public void pinchOpenFromToForDuration(Point2D.Float from, Point2D.Float to, int duration) throws UIAException {\n this.instruments.runJavaScript(\"target.pinchOpenFromToForDuration(\" + toCGString(from) + \", \"\n + toCGString(to) + \", \" + duration + \");\");\n }\n\n @Override\n public void pinchOpenFromToForDuration(UIAElement fromElement, UIAElement toElement, int duration) throws\n UIAException {\n this.pinchOpenFromToForDuration(fromElement.toJavaScript(), toElement.toJavaScript(), duration);\n }\n\n @Override\n public void pinchOpenFromToForDuration(String fromJavaScript, String toJavaScript, int duration) throws UIAException {\n this.instruments.runJavaScript(\"var e1 = \" + fromJavaScript + \"; var e2 = \" + toJavaScript + \"; \"\n + \"target.pinchOpenFromToForDuration(e1, e2, \" + duration + \");\");\n }\n\n @Override\n public void tap(float x, float y) throws UIAException {\n this.instruments.runJavaScript(\"target.tap(\" + toCGString(x, y) + \");\");\n }\n\n public void tap(Class type, String name) throws UIAException {\n UIAElement element = this.mainWindow().findElement(type, name);\n this.tap(element);\n }\n\n @Override\n public void tap(UIAElement element) throws UIAException {\n this.tap(element.toJavaScript());\n }\n\n @Override\n public void tap(String javaScript) throws UIAException {\n this.instruments.runJavaScript(\"var e = \" + javaScript + \"; e.tap();\");\n }\n\n @Override\n public void touchAndHold(Point2D.Float point, int duration) throws UIAException {\n this.instruments.runJavaScript(\"target.touchAndHold(\" + toCGString(point) + \", \" + duration + \");\");\n }\n\n @Override\n public void touchAndHold(UIAElement element, int duration) throws UIAException {\n this.instruments.runJavaScript(\"var e = \" + element.toJavaScript() + \"; e.touchAndHold(e, \" + duration + \");\");\n }\n\n @Override\n public void touchAndHold(String javaScript, int duration) throws UIAException {\n this.instruments.runJavaScript(\"var e = \" + javaScript + \"; target.touchAndHold(e, \" + duration + \");\");\n }\n\n @Override\n public void popTimeout() throws UIAException {\n this.instruments.runJavaScript(\"target.popTimeout();\");\n }\n\n @Override\n public void pushTimeout(int timeoutValue) throws UIAException {\n this.instruments.runJavaScript(\"target.pushTimeout(\" + timeoutValue + \");\");\n }\n\n @Override\n public void setTimeout(int timeout) throws UIAException {\n this.instruments.runJavaScript(\"target.setTimeout(\" + timeout + \");\");\n }\n\n /**\n * Unsupported yet.\n *\n * @return int\n *\n * @throws UIAException in case of any issue\n */\n @Override\n public int timeout() throws UIAException {\n throw new UnsupportedOperationException(\"Not supported yet.\");\n }\n\n public void delay(int timeInterval) throws UIAException {\n this.instruments.runJavaScript(\"target.delay(\" + timeInterval + \");\");\n }\n\n /**\n * Unsupported yet.\n *\n * @param alert alert object\n *\n * @return true/false\n *\n * @throws UIAException in case of any issue\n */\n @Override\n public boolean onAlert(UIAAlert alert) throws UIAException {\n throw new UnsupportedOperationException(\"Not supported yet.\");\n }\n\n public void setAlertAutoDismiss() throws UIAException {\n this.alertHandler = \"UIATarget.onAlert = function onAlert(alert) {return false;}\";\n }\n\n public void logElementTree() throws UIAException {\n instruments.runJavaScript(\"window.logElementTree();\").forEach(l -> LOG.debug(l));\n }\n\n public Instruments getInstruments() {\n return instruments;\n }\n\n private Dimension loadDisplaySize() throws UIAException {\n List lines = this.instruments.runJavaScript(\"window.logElement();\");\n Dimension dimension = new Dimension();\n String line = lines.stream().filter((l) -> (l.startsWith(\"UIAWindow\"))).findFirst().get();\n if (StringUtils.isNotEmpty(line)) {\n String s = line.split(\"\\\\{\", 2)[1].replaceAll(\"\\\\{\", \"\").replaceAll(\"\\\\}\", \"\");\n String[] ds = s.split(\",\");\n dimension.setSize(Integer.parseInt(ds[2].trim()), Integer.parseInt(ds[3].trim()));\n }\n return dimension;\n }\n\n public static void main(String[] args) throws SDKException {\n UiAutomationDevice d = new UiAutomationDevice();\n try {\n d.start(\"Movies\", 5000);\n\n LOG.debug(\"model {}\", d.model());\n } catch (Throwable t) {\n LOG.error(\"\", t);\n } finally {\n d.stop();\n System.exit(0);\n }\n }\n}\n"},"new_file":{"kind":"string","value":"uia-test/src/main/java/com/tascape/qa/th/ios/driver/UiAutomationDevice.java"},"old_contents":{"kind":"string","value":"/*\n * Copyright 2016 tascape.\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.tascape.qa.th.ios.driver;\n\nimport com.tascape.qa.th.ios.model.UIA;\nimport org.libimobiledevice.ios.driver.binding.exceptions.SDKException;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport com.tascape.qa.th.SystemConfiguration;\nimport com.tascape.qa.th.Utils;\nimport com.tascape.qa.th.ios.comm.Instruments;\nimport com.tascape.qa.th.ios.model.DeviceOrientation;\nimport com.tascape.qa.th.ios.model.UIAAlert;\nimport com.tascape.qa.th.ios.model.UIAApplication;\nimport com.tascape.qa.th.ios.model.UIAElement;\nimport com.tascape.qa.th.ios.model.UIAException;\nimport com.tascape.qa.th.ios.model.UIATarget;\nimport com.tascape.qa.th.ios.model.UIAWindow;\nimport java.awt.Dimension;\nimport java.awt.geom.Point2D;\nimport java.awt.geom.Rectangle2D;\nimport java.util.List;\nimport org.apache.commons.lang3.StringUtils;\n\n/**\n *\n * @author linsong wang\n */\npublic class UiAutomationDevice extends LibIMobileDevice implements UIATarget, UIAApplication {\n private static final Logger LOG = LoggerFactory.getLogger(UiAutomationDevice.class);\n\n public static final String SYSPROP_TIMEOUT_SECOND = \"qa.th.driver.ios.TIMEOUT_SECOND\";\n\n public static final String TRACE_TEMPLATE = \"/Applications/Xcode.app/Contents/Applications/Instruments.app/Contents\"\n + \"/PlugIns/AutomationInstrument.xrplugin/Contents/Resources/Automation.tracetemplate\";\n\n public static final int TIMEOUT_SECOND\n = SystemConfiguration.getInstance().getIntProperty(SYSPROP_TIMEOUT_SECOND, 120);\n\n private Instruments instruments;\n\n private Dimension screenDimension;\n\n private String alertHandler = \"\";\n\n public UiAutomationDevice() throws SDKException {\n this(LibIMobileDevice.getAllUuids().get(0));\n }\n\n public UiAutomationDevice(String uuid) throws SDKException {\n super(uuid);\n }\n\n public void start(String appName, int delayMillis) throws Exception {\n if (instruments != null) {\n instruments.disconnect();\n } else {\n instruments = new Instruments(getUuid(), appName);\n }\n if (StringUtils.isNotEmpty(alertHandler)) {\n instruments.setPreTargetJavaScript(alertHandler);\n }\n instruments.connect();\n Utils.sleep(delayMillis, \"Wait for app to start\");\n long end = System.currentTimeMillis() + TIMEOUT_SECOND * 1000;\n while (end > System.currentTimeMillis()) {\n try {\n if (this.instruments.runJavaScript(\"window.logElement();\").stream()\n .filter(l -> l.contains(UIAWindow.class.getSimpleName())).findAny().isPresent()) {\n return;\n }\n } catch (Exception ex) {\n LOG.warn(ex.getMessage());\n Thread.sleep(5000);\n }\n }\n throw new UIAException(\"Cannot start app \");\n }\n\n public void stop() {\n if (instruments != null) {\n instruments.shutdown();\n }\n }\n\n public void setAlertHandler(String javaScript) {\n this.alertHandler = javaScript;\n }\n\n public List runJavaScript(String javaScript) throws UIAException {\n return instruments.runJavaScript(javaScript);\n }\n\n public List loadElementTree() throws UIAException {\n return instruments.runJavaScript(\"window.logElementTree();\");\n }\n\n /**\n * Gets the screen size in points.\n * http://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions\n *\n * @return the screen size in points\n *\n * @throws UIAException in case of any issue\n */\n public Dimension getDisplaySize() throws UIAException {\n if (screenDimension == null) {\n screenDimension = loadDisplaySize();\n }\n return screenDimension;\n }\n\n /**\n * Checks if an element exists on current UI, based on element type.\n *\n * @param sub-class of UIAElement\n * @param javaScript such as \"window.tabBars()['MainTabBar']\"\n * @param type type of uia element, such as UIATabBar\n *\n * @return true if element identified by javascript exists\n *\n * @throws UIAException in case of any issue\n */\n public boolean doesElementExist(String javaScript, Class type) throws UIAException {\n return doesElementExist(javaScript, type, null);\n }\n\n /**\n * Checks if an element exists on current UI, based on element type and name.\n *\n * @param sub-class of UIAElement\n * @param javaScript the javascript that uniquely identify the element, such as \"window.tabBars()['MainTabBar']\",\n * or \"window.elements()[1].buttons()[0]\"\n * @param type type of uia element, such as UIATabBar\n * @param name name of an element, such as \"MainTabBar\"\n *\n * @return true if element identified by javascript exists\n *\n * @throws UIAException in case of any issue\n */\n public boolean doesElementExist(String javaScript, Class type, String name) throws\n UIAException {\n String js = \"var e = \" + javaScript + \"; e.logElement();\";\n return instruments.runJavaScript(js).stream()\n .filter(line -> line.contains(type.getSimpleName()))\n .filter(line -> StringUtils.isEmpty(name) ? true : line.contains(name))\n .findFirst().isPresent();\n }\n\n /**\n * Checks if an element exists on current UI, based on element type and name. This method loads full element tree.\n *\n * @param sub-class of UIAElement\n * @param type type of uia element, such as UIATabBar\n * @param name name of an element, such as \"MainTabBar\"\n *\n * @return true if element identified by type and name exists, or false if timeout\n *\n * @throws UIAException in case of any issue\n */\n public boolean doesElementExist(Class type, String name) throws UIAException {\n return mainWindow().findElement(type, name) != null;\n }\n\n /**\n * Waits for an element exists on current UI, based on element type.\n *\n * @param sub-class of UIAElement\n * @param javaScript the javascript that uniquely identify the element, such as \"window.tabBars()['MainTabBar']\",\n * or \"window.elements()[1].buttons()[0]\"\n * @param type type of uia element, such as UIATabBar\n *\n * @return true if element identified by javascript exists, or false if timeout\n *\n * @throws UIAException in case of UIA issue\n * @throws java.lang.InterruptedException in case of interruption\n */\n public boolean waitForElement(String javaScript, Class type)\n throws UIAException, InterruptedException {\n return this.waitForElement(javaScript, type, null);\n }\n\n /**\n * Waits for an element exists on current UI, based on element type and name.\n *\n * @param sub-class of UIAElement\n * @param javaScript the javascript that uniquely identify the element, such as \"window.tabBars()['MainTabBar']\",\n * or \"window.elements()[1].buttons()[0]\"\n * @param type type of uia element, such as UIATabBar\n * @param name name of an element, such as \"MainTabBar\"\n *\n * @return true if element identified by javascript exists, or false if timeout\n *\n * @throws UIAException in case of UIA issue\n * @throws java.lang.InterruptedException in case of interruption\n */\n public boolean waitForElement(String javaScript, Class type, String name)\n throws UIAException, InterruptedException {\n long end = System.currentTimeMillis() + TIMEOUT_SECOND * 1000;\n while (System.currentTimeMillis() < end) {\n if (doesElementExist(javaScript, type, name)) {\n return true;\n }\n Utils.sleep(1000, \"wait for \" + type + \"[\" + name + \"]\");\n }\n return false;\n }\n\n /**\n * Waits for an element exists on current UI, based on element type and name. This method loads full element tree.\n *\n * @param sub-class of UIAElement\n * @param type type of uia element, such as UIATabBar\n * @param name name of an element, such as \"MainTabBar\"\n *\n * @return true if element identified by type and name exists, or false if timeout\n *\n * @throws UIAException in case of UIA issue\n * @throws java.lang.InterruptedException in case of interruption\n */\n public boolean waitForElement(Class type, String name) throws UIAException,\n InterruptedException {\n long end = System.currentTimeMillis() + TIMEOUT_SECOND * 1000;\n while (System.currentTimeMillis() < end) {\n try {\n if (mainWindow().findElement(type, name) != null) {\n return true;\n }\n } catch (Exception ex) {\n LOG.warn(\"{}\", ex.getMessage());\n Thread.sleep(10000);\n }\n Utils.sleep(5000, \"wait for \" + type.getSimpleName() + \"[\" + name + \"]\");\n }\n return false;\n }\n\n public String getElementName(String javaScript, Class type) throws UIAException {\n String js = \"var e = \" + javaScript + \"; e.logElement();\";\n String line = instruments.runJavaScript(js).stream()\n .filter(l -> l.contains(type.getSimpleName())).findFirst().get();\n return UIA.parseElement(line).name();\n }\n\n public String getElementValue(String javaScript, Class type) throws UIAException {\n String js = \"var e = \" + javaScript + \"; UIALogger.logMessage(e.value());\";\n return Instruments.getLogMessage(instruments.runJavaScript(js));\n }\n\n public void setTextField(String javaScript, String value) throws UIAException {\n String js = \"var e = \" + javaScript + \"; e.setValue('\" + value + \"');\";\n instruments.runJavaScript(js).forEach(l -> LOG.trace(l));\n }\n\n @Override\n public UIAWindow mainWindow() throws UIAException {\n List lines = loadElementTree();\n UIAWindow window = UIA.parseElementTree(lines);\n window.setInstruments(instruments);\n return window;\n }\n\n @Override\n public void deactivateAppForDuration(int duration) throws UIAException {\n instruments.runJavaScript(\"UIALogger.logMessage(target.deactivateAppForDuration(\" + duration + \"));\");\n }\n\n @Override\n public String model() throws UIAException {\n return Instruments.getLogMessage(instruments.runJavaScript(\"UIALogger.logMessage(target.model());\"));\n }\n\n @Override\n public String name() throws UIAException {\n return Instruments.getLogMessage(instruments.runJavaScript(\"UIALogger.logMessage(target.name());\"));\n }\n\n @Override\n public Rectangle2D.Float rect() throws UIAException {\n List lines = instruments.runJavaScript(\"UIALogger.logMessage(target.rect());\");\n throw new UnsupportedOperationException(\"Not supported yet.\");\n }\n\n @Override\n public String systemName() throws UIAException {\n return Instruments.getLogMessage(instruments.runJavaScript(\"UIALogger.logMessage(target.systemName());\"));\n }\n\n @Override\n public String systemVersion() throws UIAException {\n return Instruments.getLogMessage(instruments.runJavaScript(\"UIALogger.logMessage(target.systemVersion());\"));\n }\n\n @Override\n public DeviceOrientation deviceOrientation() throws UIAException {\n instruments.runJavaScript(\"UIALogger.logMessage(target.deviceOrientation());\");\n throw new UnsupportedOperationException(\"Not supported yet.\");\n }\n\n @Override\n public void setDeviceOrientation(DeviceOrientation orientation) throws UIAException {\n instruments.runJavaScript(\"target.setDeviceOrientation(\" + orientation.ordinal() + \");\");\n throw new UnsupportedOperationException(\"Not supported yet.\");\n }\n\n @Override\n public void setLocation(double latitude, double longitude) throws UIAException {\n instruments.runJavaScript(\"target.setLocation({latitude:\" + latitude + \", longitude:\" + longitude + \"});\");\n }\n\n @Override\n public void clickVolumeDown() throws UIAException {\n this.instruments.runJavaScript(\"target.clickVolumeDown();\");\n }\n\n @Override\n public void clickVolumeUp() throws UIAException {\n this.instruments.runJavaScript(\"target.clickVolumeUp();\");\n }\n\n @Override\n public void holdVolumeDown(int duration) throws UIAException {\n this.instruments.runJavaScript(\"target.holdVolumeDown(\" + duration + \");\");\n }\n\n @Override\n public void holdVolumeUp(int duration) throws UIAException {\n this.instruments.runJavaScript(\"target.holdVolumeUp(\" + duration + \");\");\n }\n\n @Override\n public void lockForDuration(int duration) throws UIAException {\n this.instruments.runJavaScript(\"target.lockForDuration(\" + duration + \");\");\n }\n\n @Override\n public void shake() throws UIAException {\n this.instruments.runJavaScript(\"target.shake();\");\n }\n\n public void dragHalfScreenUp() throws UIAException {\n Dimension dimension = this.getDisplaySize();\n this.dragFromToForDuration(new Point2D.Float(dimension.width / 2, dimension.height / 2),\n new Point2D.Float(dimension.width / 2, 0), 1);\n }\n\n public void dragHalfScreenDown() throws UIAException {\n Dimension dimension = this.getDisplaySize();\n this.dragFromToForDuration(new Point2D.Float(dimension.width / 2, dimension.height / 2),\n new Point2D.Float(dimension.width / 2, dimension.height), 1);\n }\n\n @Override\n public void dragFromToForDuration(Point2D.Float from, Point2D.Float to, int duration) throws UIAException {\n this.instruments.runJavaScript(\"target.dragFromToForDuration(\" + toCGString(from) + \", \"\n + toCGString(to) + \", \" + duration + \");\");\n }\n\n @Override\n public void dragFromToForDuration(UIAElement fromElement, UIAElement toElement, int duration) throws UIAException {\n this.dragFromToForDuration(fromElement.toJavaScript(), toElement.toJavaScript(), duration);\n }\n\n @Override\n public void dragFromToForDuration(String fromJavaScript, String toJavaScript, int duration) throws UIAException {\n this.instruments.runJavaScript(\"var e1 = \" + fromJavaScript + \"; var e2 = \" + toJavaScript + \"; \"\n + \"target.dragFromToForDuration(e1, e2, \" + duration + \");\");\n }\n\n @Override\n public void doubleTap(float x, float y) throws UIAException {\n this.instruments.runJavaScript(\"target.doubleTap(\" + toCGString(x, y) + \");\");\n }\n\n @Override\n public void doubleTap(UIAElement element) throws UIAException {\n this.doubleTap(element.toJavaScript());\n }\n\n @Override\n public void doubleTap(String javaScript) throws UIAException {\n this.instruments.runJavaScript(\"var e = \" + javaScript + \"; e.doubleTap();\");\n }\n\n @Override\n public void flickFromTo(Point2D.Float from, Point2D.Float to, int duration) throws UIAException {\n this.instruments.runJavaScript(\n \"target.flickFromTo(\" + toCGString(from) + \", \" + toCGString(to) + \", \" + duration + \");\");\n }\n\n @Override\n public void flickFromTo(UIAElement fromElement, UIAElement toElement, int duration) throws UIAException {\n this.flickFromTo(fromElement.toJavaScript(), toElement.toJavaScript(), duration);\n }\n\n @Override\n public void flickFromTo(String fromJavaScript, String toJavaScript, int duration) throws UIAException {\n this.instruments.runJavaScript(\"var e1 = \" + fromJavaScript + \"; var e2 = \" + toJavaScript + \"; \"\n + \"target.flickFromTo(e1, e2, \" + duration + \");\");\n }\n\n @Override\n public void pinchCloseFromToForDuration(Point2D.Float from, Point2D.Float to, int duration) throws UIAException {\n this.instruments.runJavaScript(\"target.pinchCloseFromToForDuration(\" + toCGString(from) + \", \"\n + toCGString(to) + \", \" + duration + \");\");\n }\n\n @Override\n public void pinchCloseFromToForDuration(UIAElement fromElement, UIAElement toElement, int duration) throws\n UIAException {\n this.pinchCloseFromToForDuration(fromElement.toJavaScript(), toElement.toJavaScript(), duration);\n }\n\n @Override\n public void pinchCloseFromToForDuration(String fromJavaScript, String toJavaScript, int duration) throws\n UIAException {\n this.instruments.runJavaScript(\"var e1 = \" + fromJavaScript + \"; var e2 = \" + toJavaScript + \"; \"\n + \"target.pinchCloseFromToForDuration(e1, e2, \" + duration + \");\");\n }\n\n @Override\n public void pinchOpenFromToForDuration(Point2D.Float from, Point2D.Float to, int duration) throws UIAException {\n this.instruments.runJavaScript(\"target.pinchOpenFromToForDuration(\" + toCGString(from) + \", \"\n + toCGString(to) + \", \" + duration + \");\");\n }\n\n @Override\n public void pinchOpenFromToForDuration(UIAElement fromElement, UIAElement toElement, int duration) throws\n UIAException {\n this.pinchOpenFromToForDuration(fromElement.toJavaScript(), toElement.toJavaScript(), duration);\n }\n\n @Override\n public void pinchOpenFromToForDuration(String fromJavaScript, String toJavaScript, int duration) throws UIAException {\n this.instruments.runJavaScript(\"var e1 = \" + fromJavaScript + \"; var e2 = \" + toJavaScript + \"; \"\n + \"target.pinchOpenFromToForDuration(e1, e2, \" + duration + \");\");\n }\n\n @Override\n public void tap(float x, float y) throws UIAException {\n this.instruments.runJavaScript(\"target.tap(\" + toCGString(x, y) + \");\");\n }\n\n public void tap(Class type, String name) throws UIAException {\n UIAElement element = this.mainWindow().findElement(type, name);\n this.tap(element);\n }\n\n @Override\n public void tap(UIAElement element) throws UIAException {\n this.tap(element.toJavaScript());\n }\n\n @Override\n public void tap(String javaScript) throws UIAException {\n this.instruments.runJavaScript(\"var e = \" + javaScript + \"; e.tap();\");\n }\n\n @Override\n public void touchAndHold(Point2D.Float point, int duration) throws UIAException {\n this.instruments.runJavaScript(\"target.touchAndHold(\" + toCGString(point) + \", \" + duration + \");\");\n }\n\n @Override\n public void touchAndHold(UIAElement element, int duration) throws UIAException {\n this.instruments.runJavaScript(\"var e = \" + element.toJavaScript() + \"; e.touchAndHold(e, \" + duration + \");\");\n }\n\n @Override\n public void touchAndHold(String javaScript, int duration) throws UIAException {\n this.instruments.runJavaScript(\"var e = \" + javaScript + \"; target.touchAndHold(e, \" + duration + \");\");\n }\n\n @Override\n public void popTimeout() throws UIAException {\n this.instruments.runJavaScript(\"target.popTimeout();\");\n }\n\n @Override\n public void pushTimeout(int timeoutValue) throws UIAException {\n this.instruments.runJavaScript(\"target.pushTimeout(\" + timeoutValue + \");\");\n }\n\n @Override\n public void setTimeout(int timeout) throws UIAException {\n this.instruments.runJavaScript(\"target.setTimeout(\" + timeout + \");\");\n }\n\n /**\n * Unsupported yet.\n *\n * @return int\n *\n * @throws UIAException in case of any issue\n */\n @Override\n public int timeout() throws UIAException {\n throw new UnsupportedOperationException(\"Not supported yet.\");\n }\n\n public void delay(int timeInterval) throws UIAException {\n this.instruments.runJavaScript(\"target.delay(\" + timeInterval + \");\");\n }\n\n /**\n * Unsupported yet.\n *\n * @param alert alert object\n *\n * @return true/false\n *\n * @throws UIAException in case of any issue\n */\n @Override\n public boolean onAlert(UIAAlert alert) throws UIAException {\n throw new UnsupportedOperationException(\"Not supported yet.\");\n }\n\n public void setAlertAutoDismiss() throws UIAException {\n this.alertHandler = \"UIATarget.onAlert = function onAlert(alert) {return false;}\";\n }\n\n public void logElementTree() throws UIAException {\n mainWindow().logElement().forEach(l -> LOG.debug(l));\n }\n\n public Instruments getInstruments() {\n return instruments;\n }\n\n private Dimension loadDisplaySize() throws UIAException {\n List lines = this.instruments.runJavaScript(\"window.logElement();\");\n Dimension dimension = new Dimension();\n String line = lines.stream().filter((l) -> (l.startsWith(\"UIAWindow\"))).findFirst().get();\n if (StringUtils.isNotEmpty(line)) {\n String s = line.split(\"\\\\{\", 2)[1].replaceAll(\"\\\\{\", \"\").replaceAll(\"\\\\}\", \"\");\n String[] ds = s.split(\",\");\n dimension.setSize(Integer.parseInt(ds[2].trim()), Integer.parseInt(ds[3].trim()));\n }\n return dimension;\n }\n\n public static void main(String[] args) throws SDKException {\n UiAutomationDevice d = new UiAutomationDevice();\n try {\n d.start(\"Movies\", 5000);\n\n LOG.debug(\"model {}\", d.model());\n } catch (Throwable t) {\n LOG.error(\"\", t);\n } finally {\n d.stop();\n System.exit(0);\n }\n }\n}\n"},"message":{"kind":"string","value":"disable parsing when logging element tree"},"old_file":{"kind":"string","value":"uia-test/src/main/java/com/tascape/qa/th/ios/driver/UiAutomationDevice.java"},"subject":{"kind":"string","value":"disable parsing when logging element tree"},"git_diff":{"kind":"string","value":"ia-test/src/main/java/com/tascape/qa/th/ios/driver/UiAutomationDevice.java\n }\n \n public void logElementTree() throws UIAException {\n mainWindow().logElement().forEach(l -> LOG.debug(l));\n instruments.runJavaScript(\"window.logElementTree();\").forEach(l -> LOG.debug(l));\n }\n \n public Instruments getInstruments() {"}}},{"rowIdx":1954,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"39c63c8dcfef9c3ebe8eecdc3f7428141b317fe8"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"googleinterns/BLETH,googleinterns/BLETH,googleinterns/BLETH"},"new_contents":{"kind":"string","value":"// Copyright 2019 Google LLC\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// https://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.google.research.bleth.servlets;\n\nimport com.google.appengine.api.datastore.DatastoreService;\nimport com.google.appengine.api.datastore.DatastoreServiceFactory;\nimport com.google.appengine.api.datastore.Entity;\nimport com.google.appengine.api.datastore.EntityNotFoundException;\nimport com.google.appengine.api.datastore.Key;\nimport com.google.appengine.api.datastore.KeyFactory;\nimport com.google.auto.value.AutoValue;\nimport com.google.cloud.tasks.v2.AppEngineHttpRequest;\nimport com.google.cloud.tasks.v2.CloudTasksClient;\nimport com.google.cloud.tasks.v2.HttpMethod;\nimport com.google.cloud.tasks.v2.QueueName;\nimport com.google.cloud.tasks.v2.Task;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Sets;\nimport com.google.gson.Gson;\nimport com.google.protobuf.ByteString;\nimport com.google.research.bleth.simulator.AwakenessStrategyFactory;\nimport com.google.research.bleth.simulator.MovementStrategyFactory;\nimport com.google.research.bleth.simulator.Schema;\n\nimport java.io.IOException;\nimport java.io.UnsupportedEncodingException;\nimport java.net.URLEncoder;\nimport java.nio.charset.StandardCharsets;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.logging.Logger;\nimport java.util.stream.Collectors;\nimport javax.servlet.annotation.WebServlet;\nimport javax.servlet.http.HttpServlet;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\n\n\n/**\n * A servlet used for enqueuing multiple tasks targeted at endpoint '/new-experiment-simulation',\n * in order to create and run a new experiment.\n */\n@WebServlet(\"/enqueue-experiment\")\npublic class EnqueueExperimentServlet extends HttpServlet {\n private static final DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();\n private static final Gson gson = new Gson();\n private static final MovementStrategyFactory.Type defaultMovementStrategy = MovementStrategyFactory.Type.RANDOM;\n private static final AwakenessStrategyFactory.Type defaultAwakenessStrategy = AwakenessStrategyFactory.Type.RANDOM;\n private static final String PROJECT_ID = \"bleth-2020\";\n private static final String LOCATION_ID = \"europe-west1\";\n private static final String QUEUE_ID = \"simulations-queue\";\n private static final String queueName = QueueName.of(PROJECT_ID, LOCATION_ID, QUEUE_ID).toString();\n private static final Logger log = Logger.getLogger(EnqueueExperimentServlet.class.getName());\n\n @Override\n public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {\n\n if (request.getServerName().equals(\"localhost\") && request.getServerPort() == 8080) {\n response.setContentType(\"text/plain;\");\n response.getWriter().println(\"Experiments are not yet supported on localhost.\");\n return;\n }\n\n log.info(\"Enqueue Experiment Servlet invoked.\");\n\n String experimentTitle = request.getParameter(\"experimentTitle\");\n int beaconsNum = Integer.parseInt(request.getParameter(\"beaconsNum\"));\n Set> configurations = createConfigurations(request);\n\n Entity experiment = new Entity(Schema.Experiment.entityKind);\n experiment.setProperty(Schema.Experiment.experimentTitle, experimentTitle);\n Key experimentId = datastore.put(experiment);\n log.info(\"A new experiment entity with id \" + KeyFactory.keyToString(experimentId) +\n \"was created and written to db.\");\n\n int legalConfigurationsCount = configurations.size();\n for (List configuration : configurations) {\n AppEngineHttpRequest httpRequest = toHttpRequest(configuration, beaconsNum, experimentId, experimentTitle);\n log.info(\"A new AppEngineHttpRequest was created: \" + httpRequest.toString());\n enqueueTask(httpRequest);\n log.info(\"A new Task was created and enqueued.\");\n }\n\n try {\n experiment = datastore.get(experimentId);\n experiment.setProperty(Schema.Experiment.simulationsLeft, legalConfigurationsCount);\n datastore.put(experiment);\n log.info(\"Experiment entity with id \" + KeyFactory.keyToString(experimentId) +\n \"was updated with simulationsLeft=\" + legalConfigurationsCount);\n } catch (EntityNotFoundException e) {\n response.setContentType(\"text/plain;\");\n response.getWriter().println(e.getMessage());\n }\n\n response.setContentType(\"text/plain;\");\n response.getWriter().println(legalConfigurationsCount + \" tasks have been added to queue.\");\n }\n\n /**\n * A class designated for storing numerical simulation parameters.\n * PropertyWrapper stores the property name and value as an atomic unit.\n */\n @AutoValue\n public static abstract class PropertyWrapper {\n public static PropertyWrapper create(String property, Number value) {\n return new AutoValue_EnqueueExperimentServlet_PropertyWrapper(property, value);\n }\n public abstract String property();\n public abstract Number value();\n }\n\n private Set> createConfigurations(HttpServletRequest request) {\n Set roundsNumValues = createIntValues(request, \"roundsNum\");\n Set rowsNumValues = createIntValues(request, \"rowsNum\");\n Set colsNumValues = createIntValues(request, \"colsNum\");\n Set observersNumValues = createIntValues(request, \"observersNum\");\n Set awakenessCycleValues = createIntValues(request, \"awakenessCycle\");\n Set awakenessDurationValues = createIntValues(request, \"awakenessDuration\");\n Set transmissionThresholdRadiusValues = createDoubleValues(request, \"transmissionThresholdRadius\");\n\n Set> configurations = Sets.cartesianProduct(\n roundsNumValues,\n rowsNumValues,\n colsNumValues,\n observersNumValues,\n awakenessCycleValues,\n awakenessDurationValues,\n transmissionThresholdRadiusValues\n );\n\n return configurations.stream().filter(this::validateArguments).collect(ImmutableSet.toImmutableSet());\n }\n\n private Set createIntValues(HttpServletRequest request, String parameter) {\n int lower = Integer.parseInt(request.getParameter(\"lower\" + upperCaseFirstChar(parameter)));\n int upper = Integer.parseInt(request.getParameter(\"upper\" + upperCaseFirstChar(parameter)));\n int step = Integer.parseInt(request.getParameter(\"step\" + upperCaseFirstChar(parameter)));\n Set values = new HashSet<>();\n for (int value = lower; value <= upper; value += step) {\n values.add(PropertyWrapper.create(parameter, value));\n }\n return ImmutableSet.copyOf(values);\n }\n\n private Set createDoubleValues(HttpServletRequest request, String parameter) {\n double lower = Double.parseDouble(request.getParameter(\"lower\" + upperCaseFirstChar(parameter)));\n double upper = Double.parseDouble(request.getParameter(\"upper\" + upperCaseFirstChar(parameter)));\n double step = Double.parseDouble(request.getParameter(\"step\" + upperCaseFirstChar(parameter)));\n Set values = new HashSet<>();\n for (double value = lower; value <= upper; value += step) {\n values.add(PropertyWrapper.create(parameter, value));\n }\n return ImmutableSet.copyOf(values);\n }\n\n private String upperCaseFirstChar(String s) {\n return s.substring(0, 1).toUpperCase() + s.substring(1);\n }\n\n private AppEngineHttpRequest toHttpRequest(List configuration,\n int beaconsNum, Key experimentId, String experimentTitle) throws UnsupportedEncodingException {\n Map bodyMap = new HashMap<>();\n bodyMap.put(Schema.SimulationMetadata.description,\n \"Simulation attached to experiment: \" + experimentTitle);\n bodyMap.put(Schema.SimulationMetadata.beaconsNum, String.valueOf(beaconsNum));\n bodyMap.put(Schema.SimulationMetadata.beaconMovementStrategy, defaultMovementStrategy.toString());\n bodyMap.put(Schema.SimulationMetadata.observerMovementStrategy, defaultMovementStrategy.toString());\n bodyMap.put(Schema.SimulationMetadata.observerAwakenessStrategy, defaultAwakenessStrategy.toString());\n bodyMap.put(Schema.ExperimentsToSimulations.experimentId, KeyFactory.keyToString(experimentId));\n configuration.forEach((propertyWrapper -> {\n bodyMap.put(propertyWrapper.property(), String.valueOf(propertyWrapper.value()));\n }));\n\n return AppEngineHttpRequest.newBuilder()\n .setRelativeUri(\"/new-experiment-simulation\")\n .setHttpMethod(HttpMethod.POST)\n .putHeaders(\"Content-Type\", \"application/x-www-form-urlencoded;charset=UTF-8;\")\n .setBody(ByteString.copyFromUtf8(toQueryString(bodyMap)))\n .build();\n }\n\n private String toQueryString(Map params) throws UnsupportedEncodingException {\n List keyValuePairs = new ArrayList<>();\n for (String param : params.keySet()) {\n keyValuePairs.add(URLEncoder.encode(param, StandardCharsets.UTF_8.toString()) + \"=\" +\n URLEncoder.encode(params.get(param), StandardCharsets.UTF_8.toString()));\n }\n return String.join(\"&\", keyValuePairs);\n }\n\n private boolean validateArguments(List configuration) {\n Map properties = configuration.stream()\n .collect(Collectors.toMap(PropertyWrapper::property, PropertyWrapper::value));\n\n boolean positiveDimensions = properties.get(Schema.SimulationMetadata.rowsNum).intValue() > 0 &&\n properties.get(Schema.SimulationMetadata.rowsNum).intValue() > 0;\n boolean positiveAgentsNumber = properties.get(Schema.SimulationMetadata.observersNum).intValue() > 0;\n boolean positiveCycleAndDuration = properties.get(Schema.SimulationMetadata.awakenessCycle).intValue() > 0 &&\n properties.get(Schema.SimulationMetadata.awakenessDuration).intValue() > 0;\n boolean positiveThresholdRadius = properties.get(Schema.SimulationMetadata.transmissionThresholdRadius).intValue() > 0;\n boolean positiveRoundsNumber = properties.get(Schema.SimulationMetadata.roundsNum).intValue() > 0;\n boolean cycleGreaterOrEqualDuration = properties.get(Schema.SimulationMetadata.awakenessCycle).intValue() >=\n properties.get(Schema.SimulationMetadata.awakenessDuration).intValue();\n\n return positiveDimensions && positiveAgentsNumber && positiveCycleAndDuration && positiveThresholdRadius\n && positiveRoundsNumber && cycleGreaterOrEqualDuration;\n }\n\n private void enqueueTask(AppEngineHttpRequest httpRequest) throws IOException {\n try (CloudTasksClient client = CloudTasksClient.create()) {\n Task task = Task.newBuilder()\n .setAppEngineHttpRequest(httpRequest)\n .build();\n\n client.createTask(queueName, task);\n }\n }\n}\n"},"new_file":{"kind":"string","value":"src/main/java/com/google/research/bleth/servlets/EnqueueExperimentServlet.java"},"old_contents":{"kind":"string","value":"// Copyright 2019 Google LLC\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// https://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.google.research.bleth.servlets;\n\nimport com.google.appengine.api.datastore.DatastoreService;\nimport com.google.appengine.api.datastore.DatastoreServiceFactory;\nimport com.google.appengine.api.datastore.Entity;\nimport com.google.appengine.api.datastore.EntityNotFoundException;\nimport com.google.appengine.api.datastore.Key;\nimport com.google.appengine.api.datastore.KeyFactory;\nimport com.google.auto.value.AutoValue;\nimport com.google.cloud.tasks.v2.AppEngineHttpRequest;\nimport com.google.cloud.tasks.v2.CloudTasksClient;\nimport com.google.cloud.tasks.v2.HttpMethod;\nimport com.google.cloud.tasks.v2.QueueName;\nimport com.google.cloud.tasks.v2.Task;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Sets;\nimport com.google.gson.Gson;\nimport com.google.protobuf.ByteString;\nimport com.google.research.bleth.simulator.AwakenessStrategyFactory;\nimport com.google.research.bleth.simulator.MovementStrategyFactory;\nimport com.google.research.bleth.simulator.Schema;\n\nimport java.io.IOException;\nimport java.io.UnsupportedEncodingException;\nimport java.net.URLEncoder;\nimport java.nio.charset.StandardCharsets;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.logging.Logger;\nimport java.util.stream.Collectors;\nimport javax.servlet.annotation.WebServlet;\nimport javax.servlet.http.HttpServlet;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\n\n\n/**\n * A servlet used for enqueuing multiple tasks targeted at endpoint '/new-experiment-simulation',\n * in order to create and run a new experiment.\n */\n@WebServlet(\"/enqueue-experiment\")\npublic class EnqueueExperimentServlet extends HttpServlet {\n private static final DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();\n private static final Gson gson = new Gson();\n private static final MovementStrategyFactory.Type defaultMovementStrategy = MovementStrategyFactory.Type.RANDOM;\n private static final AwakenessStrategyFactory.Type defaultAwakenessStrategy = AwakenessStrategyFactory.Type.RANDOM;\n private static final String PROJECT_ID = \"bleth-2020\";\n private static final String LOCATION_ID = \"europe-west1\";\n private static final String QUEUE_ID = \"simulations-queue\";\n private static final String queueName = QueueName.of(PROJECT_ID, LOCATION_ID, QUEUE_ID).toString();\n private static final Logger log = Logger.getLogger(EnqueueExperimentServlet.class.getName());\n\n @Override\n public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {\n\n if (request.getServerName().equals(\"localhost\") && request.getServerPort() == 8080) {\n response.setContentType(\"text/plain;\");\n response.getWriter().println(\"Experiments are not yet supported on localhost.\");\n return;\n }\n\n log.info(\"Enqueue Experiment Servlet invoked.\");\n\n String experimentTitle = request.getParameter(\"experimentTitle\");\n int beaconsNum = Integer.parseInt(request.getParameter(\"beaconsNum\"));\n Set> configurations = createConfigurations(request);\n\n Entity experiment = new Entity(Schema.Experiment.entityKind);\n experiment.setProperty(Schema.Experiment.experimentTitle, experimentTitle);\n Key experimentId = datastore.put(experiment);\n log.info(\"A new experiment entity with id \" + KeyFactory.keyToString(experimentId) +\n \"was created and written to db.\");\n\n int legalConfigurationsCount = configurations.size();\n for (List configuration : configurations) {\n AppEngineHttpRequest httpRequest = toHttpRequest(configuration, beaconsNum, experimentId, experimentTitle);\n log.info(\"A new AppEngineHttpRequest was created: \" + httpRequest.toString());\n enqueueTask(httpRequest);\n log.info(\"A new Task was created and enqueued.\");\n }\n\n try {\n experiment = datastore.get(experimentId);\n experiment.setProperty(Schema.Experiment.simulationsLeft, legalConfigurationsCount);\n datastore.put(experiment);\n log.info(\"Experiment entity with id \" + KeyFactory.keyToString(experimentId) +\n \"was updated with simulationsLeft=\" + legalConfigurationsCount);\n } catch (EntityNotFoundException e) {\n response.setContentType(\"text/plain;\");\n response.getWriter().println(e.getMessage());\n }\n\n response.setContentType(\"text/plain;\");\n response.getWriter().println(legalConfigurationsCount + \" tasks have been added to queue.\");\n }\n\n /**\n * A class designated for storing numerical simulation parameters.\n * PropertyWrapper stores the property name and value as an atomic unit.\n */\n @AutoValue\n public static abstract class PropertyWrapper {\n public static PropertyWrapper create(String property, Number value) {\n return new AutoValue_EnqueueExperimentServlet_PropertyWrapper(property, value);\n }\n public abstract String property();\n public abstract Number value();\n }\n\n private Set> createConfigurations(HttpServletRequest request) {\n Set roundsNumValues = createIntValues(request, \"roundsNum\");\n Set rowsNumValues = createIntValues(request, \"rowsNum\");\n Set colsNumValues = createIntValues(request, \"colsNum\");\n Set observersNumValues = createIntValues(request, \"observersNum\");\n Set awakenessCycleValues = createIntValues(request, \"awakenessCycle\");\n Set awakenessDurationValues = createIntValues(request, \"awakenessDuration\");\n Set transmissionThresholdRadiusValues = createDoubleValues(request, \"transmissionThresholdRadius\");\n\n Set> configurations = Sets.cartesianProduct(\n roundsNumValues,\n rowsNumValues,\n colsNumValues,\n observersNumValues,\n awakenessCycleValues,\n awakenessDurationValues,\n transmissionThresholdRadiusValues\n );\n\n return configurations.stream().filter(this::validateArguments).collect(ImmutableSet.toImmutableSet());\n }\n\n private Set createIntValues(HttpServletRequest request, String parameter) {\n int lower = Integer.parseInt(request.getParameter(\"lower\" + upperCaseFirstChar(parameter)));\n int upper = Integer.parseInt(request.getParameter(\"upper\" + upperCaseFirstChar(parameter)));\n int step = Integer.parseInt(request.getParameter(\"step\" + upperCaseFirstChar(parameter)));\n Set values = new HashSet<>();\n for (int value = lower; value <= upper; value += step) {\n values.add(PropertyWrapper.create(parameter, value));\n }\n return ImmutableSet.copyOf(values);\n }\n\n private Set createDoubleValues(HttpServletRequest request, String parameter) {\n double lower = Double.parseDouble(request.getParameter(\"lower\" + upperCaseFirstChar(parameter)));\n double upper = Double.parseDouble(request.getParameter(\"upper\" + upperCaseFirstChar(parameter)));\n double step = Double.parseDouble(request.getParameter(\"step\" + upperCaseFirstChar(parameter)));\n Set values = new HashSet<>();\n for (double value = lower; value <= upper; value += step) {\n values.add(PropertyWrapper.create(parameter, value));\n }\n return ImmutableSet.copyOf(values);\n }\n\n private String upperCaseFirstChar(String s) {\n return s.substring(0, 1).toUpperCase() + s.substring(1);\n }\n\n private AppEngineHttpRequest toHttpRequest(List configuration,\n int beaconsNum, Key experimentId, String experimentTitle) throws UnsupportedEncodingException {\n Map bodyMap = new HashMap<>();\n bodyMap.put(Schema.SimulationMetadata.description,\n \"Simulation attached to experiment: \" + experimentTitle);\n bodyMap.put(Schema.SimulationMetadata.beaconsNum, String.valueOf(beaconsNum));\n bodyMap.put(Schema.SimulationMetadata.beaconMovementStrategy, defaultMovementStrategy.toString());\n bodyMap.put(Schema.SimulationMetadata.observerMovementStrategy, defaultMovementStrategy.toString());\n bodyMap.put(Schema.SimulationMetadata.observerAwakenessStrategy, defaultAwakenessStrategy.toString());\n bodyMap.put(Schema.ExperimentsToSimulations.experimentId, KeyFactory.keyToString(experimentId));\n configuration.forEach((propertyWrapper -> {\n bodyMap.put(propertyWrapper.property(), String.valueOf(propertyWrapper.value()));\n }));\n\n return AppEngineHttpRequest.newBuilder()\n .setRelativeUri(\"/new-experiment-simulation\")\n .setHttpMethod(HttpMethod.POST)\n .putHeaders(\"Content-Type\", \"application/x-www-form-urlencoded;charset=UTF-8;\")\n .setBody(ByteString.copyFromUtf8(toQueryString(bodyMap)))\n .build();\n }\n\n private String toQueryString(Map params) throws UnsupportedEncodingException {\n List keyValuePairs = new ArrayList<>();\n for (String param : params.keySet()) {\n keyValuePairs.add(URLEncoder.encode(param, StandardCharsets.UTF_8.toString()) + \"=\" +\n URLEncoder.encode(params.get(param), StandardCharsets.UTF_8.toString()));\n }\n return String.join(\"&\", keyValuePairs);\n }\n\n private boolean validateArguments(List configuration) {\n Map properties = configuration.stream()\n .collect(Collectors.toMap(PropertyWrapper::property, PropertyWrapper::value));\n\n boolean nonPositiveDimensions = properties.get(Schema.SimulationMetadata.rowsNum).intValue() <= 0 ||\n properties.get(Schema.SimulationMetadata.rowsNum).intValue() <= 0;\n boolean nonPositiveAgentsNumber = properties.get(Schema.SimulationMetadata.observersNum).intValue() <= 0;\n boolean nonPositiveCycleAndDuration = properties.get(Schema.SimulationMetadata.awakenessCycle).intValue() <= 0 ||\n properties.get(Schema.SimulationMetadata.awakenessDuration).intValue() <= 0;\n boolean nonPositiveThresholdRadius = properties.get(Schema.SimulationMetadata.transmissionThresholdRadius).intValue() <= 0;\n boolean nonPositiveRoundsNumber = properties.get(Schema.SimulationMetadata.roundsNum).intValue() <= 0;\n boolean durationGreaterThanCycle = properties.get(Schema.SimulationMetadata.awakenessCycle).intValue() <\n properties.get(Schema.SimulationMetadata.awakenessDuration).intValue();\n\n return !nonPositiveDimensions && !nonPositiveAgentsNumber && !nonPositiveCycleAndDuration && !nonPositiveThresholdRadius\n && !nonPositiveRoundsNumber && !durationGreaterThanCycle;\n }\n\n private void enqueueTask(AppEngineHttpRequest httpRequest) throws IOException {\n try (CloudTasksClient client = CloudTasksClient.create()) {\n Task task = Task.newBuilder()\n .setAppEngineHttpRequest(httpRequest)\n .build();\n\n client.createTask(queueName, task);\n }\n }\n}\n"},"message":{"kind":"string","value":"modify validateArguments() to use positive conditions.\n"},"old_file":{"kind":"string","value":"src/main/java/com/google/research/bleth/servlets/EnqueueExperimentServlet.java"},"subject":{"kind":"string","value":"modify validateArguments() to use positive conditions."},"git_diff":{"kind":"string","value":"rc/main/java/com/google/research/bleth/servlets/EnqueueExperimentServlet.java\n Map properties = configuration.stream()\n .collect(Collectors.toMap(PropertyWrapper::property, PropertyWrapper::value));\n \n boolean nonPositiveDimensions = properties.get(Schema.SimulationMetadata.rowsNum).intValue() <= 0 ||\n properties.get(Schema.SimulationMetadata.rowsNum).intValue() <= 0;\n boolean nonPositiveAgentsNumber = properties.get(Schema.SimulationMetadata.observersNum).intValue() <= 0;\n boolean nonPositiveCycleAndDuration = properties.get(Schema.SimulationMetadata.awakenessCycle).intValue() <= 0 ||\n properties.get(Schema.SimulationMetadata.awakenessDuration).intValue() <= 0;\n boolean nonPositiveThresholdRadius = properties.get(Schema.SimulationMetadata.transmissionThresholdRadius).intValue() <= 0;\n boolean nonPositiveRoundsNumber = properties.get(Schema.SimulationMetadata.roundsNum).intValue() <= 0;\n boolean durationGreaterThanCycle = properties.get(Schema.SimulationMetadata.awakenessCycle).intValue() <\n boolean positiveDimensions = properties.get(Schema.SimulationMetadata.rowsNum).intValue() > 0 &&\n properties.get(Schema.SimulationMetadata.rowsNum).intValue() > 0;\n boolean positiveAgentsNumber = properties.get(Schema.SimulationMetadata.observersNum).intValue() > 0;\n boolean positiveCycleAndDuration = properties.get(Schema.SimulationMetadata.awakenessCycle).intValue() > 0 &&\n properties.get(Schema.SimulationMetadata.awakenessDuration).intValue() > 0;\n boolean positiveThresholdRadius = properties.get(Schema.SimulationMetadata.transmissionThresholdRadius).intValue() > 0;\n boolean positiveRoundsNumber = properties.get(Schema.SimulationMetadata.roundsNum).intValue() > 0;\n boolean cycleGreaterOrEqualDuration = properties.get(Schema.SimulationMetadata.awakenessCycle).intValue() >=\n properties.get(Schema.SimulationMetadata.awakenessDuration).intValue();\n \n return !nonPositiveDimensions && !nonPositiveAgentsNumber && !nonPositiveCycleAndDuration && !nonPositiveThresholdRadius\n && !nonPositiveRoundsNumber && !durationGreaterThanCycle;\n return positiveDimensions && positiveAgentsNumber && positiveCycleAndDuration && positiveThresholdRadius\n && positiveRoundsNumber && cycleGreaterOrEqualDuration;\n }\n \n private void enqueueTask(AppEngineHttpRequest httpRequest) throws IOException {"}}},{"rowIdx":1955,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"a724cc43215a0edb6c0bdb9bdfeb503a4bf06343"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"Wisser/Jailer,Wisser/Jailer,Wisser/Jailer"},"new_contents":{"kind":"string","value":"/*\n * Copyright 2007 - 2017 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * 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 net.sf.jailer.datamodel;\n\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.PrintWriter;\nimport java.net.MalformedURLException;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.net.URL;\nimport java.text.SimpleDateFormat;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.SortedSet;\nimport java.util.TreeMap;\nimport java.util.TreeSet;\n\nimport org.apache.log4j.Logger;\n\nimport net.sf.jailer.ExecutionContext;\nimport net.sf.jailer.JailerVersion;\nimport net.sf.jailer.database.Session;\nimport net.sf.jailer.datamodel.filter_template.Clause;\nimport net.sf.jailer.datamodel.filter_template.FilterTemplate;\nimport net.sf.jailer.extractionmodel.ExtractionModel;\nimport net.sf.jailer.extractionmodel.ExtractionModel.AdditionalSubject;\nimport net.sf.jailer.restrictionmodel.RestrictionModel;\nimport net.sf.jailer.subsetting.ScriptFormat;\nimport net.sf.jailer.util.CsvFile;\nimport net.sf.jailer.util.CsvFile.LineFilter;\nimport net.sf.jailer.util.LayoutStorage;\nimport net.sf.jailer.util.PrintUtil;\nimport net.sf.jailer.util.SqlUtil;\n\n/**\n * Relational data model.\n * \n * @author Ralf Wisser\n */\npublic class DataModel {\n\n\tpublic static final String TABLE_CSV_FILE = \"table.csv\";\n\tpublic static final String MODELNAME_CSV_FILE = \"modelname.csv\";\n\n\t/**\n * Maps table-names to tables.\n */\n private Map tables = new HashMap();\n \n\t/**\n * Maps table display names to tables.\n */\n private Map tablesByDisplayName = new HashMap();\n \n\t/**\n * Maps tables to display names.\n */\n private Map displayName = new HashMap();\n \n /**\n * Maps association-names to associations;\n */\n public Map namedAssociations = new TreeMap();\n \n /**\n * The restriction model.\n */\n private RestrictionModel restrictionModel;\n \n /**\n * Internal version number. Incremented on each modification.\n */\n public long version = 0;\n\n\t/**\n\t * The execution context.\n\t */\n\tprivate final ExecutionContext executionContext;\n\t\n\t/**\n * Default model name.\n */\n\tpublic static final String DEFAULT_NAME = \"New Model\";\n\n /**\n * For creation of primary-keys.\n */\n private final PrimaryKeyFactory primaryKeyFactory;\n\n /**\n * Gets name of data model folder.\n */\n public static String getDatamodelFolder(ExecutionContext executionContext) {\n \treturn executionContext.getQualifiedDatamodelFolder();\n }\n\n /**\n * Gets name of file containing the table definitions.\n */\n public static String getTablesFile(ExecutionContext executionContext) {\n \treturn getDatamodelFolder(executionContext) + File.separator + TABLE_CSV_FILE;\n }\n\n /**\n * Gets name of file containing the model name\n */\n public static String getModelNameFile(ExecutionContext executionContext) {\n \treturn getDatamodelFolder(executionContext) + File.separator + MODELNAME_CSV_FILE;\n }\n\n /**\n * Gets name of file containing the display names.\n */\n public static String getDisplayNamesFile(ExecutionContext executionContext) {\n \treturn getDatamodelFolder(executionContext) + File.separator + \"displayname.csv\";\n }\n\n /**\n * Gets name of file containing the column definitions.\n */\n public static String getColumnsFile(ExecutionContext executionContext) {\n \treturn getDatamodelFolder(executionContext) + File.separator + \"column.csv\";\n }\n\n /**\n * Gets name of file containing the association definitions.\n */\n\tpublic static String getAssociationsFile(ExecutionContext executionContext) {\n\t\treturn getDatamodelFolder(executionContext) + File.separator + \"association.csv\";\n\t}\n\t\n\t/**\n\t * List of tables to be excluded from deletion.\n\t */\n\tpublic static String getExcludeFromDeletionFile(ExecutionContext executionContext) {\n\t\treturn getDatamodelFolder(executionContext) + File.separator + \"exclude-from-deletion.csv\";\n\t}\n\t\n\t/**\n * Name of file containing the version number.\n */\n public static String getVersionFile(ExecutionContext executionContext) {\n \treturn getDatamodelFolder(executionContext) + File.separator + \"version.csv\";\n \t}\n\n /**\n\t * Export modus, SQL or XML. (GUI support).\n\t */\n\tprivate String exportModus;\n\t\n\t/**\n\t * Holds XML settings for exportation into XML files.\n\t */\n\tpublic static class XmlSettings {\n\t\tpublic String datePattern = \"yyyy-MM-dd\";\n\t\tpublic String timestampPattern = \"yyyy-MM-dd-HH.mm.ss\";\n\t\tpublic String rootTag = \"rowset\";\n\t}\n\n\t/**\n\t * XML settings for exportation into XML files.\n\t */\n\tprivate XmlSettings xmlSettings = new XmlSettings();\n\n\t/**\n\t * Name of the model.\n\t */\n\tprivate String name;\n\n\t/**\n\t * Time of last modification.\n\t */\n\tprivate Long lastModified;\n\t\n\t/**\n\t * The logger.\n\t */\n\tprivate static final Logger _log = Logger.getLogger(DataModel.class);\n\n\t/**\n * Gets a table by name.\n * \n * @param name the name of the table\n * @return the table or null iff no table with the name exists\n */\n public Table getTable(String name) {\n return tables.get(name);\n }\n\n /**\n * Gets a table by display name.\n * \n * @param displayName the display name of the table\n * @return the table or null iff no table with the display name exists\n */\n public Table getTableByDisplayName(String displayName) {\n return tablesByDisplayName.get(displayName);\n }\n\n\t/**\n\t * Gets name of the model.\n\t * \n\t * @return name of the model\n\t */\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\t/**\n\t * Gets time of last modification.\n\t * \n\t * @return time of last modification\n\t */\n\tpublic Long getLastModified() {\n\t\treturn lastModified;\n\t}\n\n /**\n * Gets display name of a table\n * \n * @param table the table\n * @return the display name of the table\n */\n public String getDisplayName(Table table) {\n String displayName = this.displayName.get(table);\n if (displayName == null) {\n \treturn table.getName();\n }\n return displayName;\n }\n\n /**\n * Gets all tables.\n * \n * @return a collection of all tables\n */\n public Collection getTables() {\n return tables.values();\n }\n \n /**\n * Reads in table.csv and association.csv\n * and builds the relational data model.\n */\n public DataModel(PrimaryKeyFactory primaryKeyFactory, Map sourceSchemaMapping, ExecutionContext executionContext) throws IOException {\n this(null, null, sourceSchemaMapping, null, primaryKeyFactory, executionContext, false);\n }\n\n /**\n * Reads in table.csv and association.csv\n * and builds the relational data model.\n */\n public DataModel(ExecutionContext executionContext) throws IOException {\n this(null, null, new PrimaryKeyFactory(), executionContext);\n }\n\n /**\n * Reads in table.csv and association.csv\n * and builds the relational data model.\n */\n public DataModel(Map sourceSchemaMapping, ExecutionContext executionContext, boolean failOnMissingTables) throws IOException {\n this(null, null, sourceSchemaMapping, null, new PrimaryKeyFactory(), executionContext, failOnMissingTables);\n }\n\n /**\n * Reads in table.csv and association.csv\n * and builds the relational data model.\n * \n * @param additionalTablesFile table file to read too\n * @param additionalAssociationsFile association file to read too\n */\n public DataModel(String additionalTablesFile, String additionalAssociationsFile, PrimaryKeyFactory primaryKeyFactory, ExecutionContext executionContext) throws IOException {\n \tthis(additionalTablesFile, additionalAssociationsFile, new HashMap(), null, primaryKeyFactory, executionContext, false);\n }\n\n /**\n * Reads in table.csv and association.csv\n * and builds the relational data model.\n * \n * @param additionalTablesFile table file to read too\n * @param additionalAssociationsFile association file to read too\n */\n public DataModel(String additionalTablesFile, String additionalAssociationsFile, ExecutionContext executionContext) throws IOException {\n \tthis(additionalTablesFile, additionalAssociationsFile, new HashMap(), null, new PrimaryKeyFactory(), executionContext, false);\n }\n\n /**\n * Reads in table.csv and association.csv\n * and builds the relational data model.\n * \n * @param additionalTablesFile table file to read too\n * @param additionalAssociationsFile association file to read too\n */\n public DataModel(String additionalTablesFile, String additionalAssociationsFile, Map sourceSchemaMapping, LineFilter assocFilter, ExecutionContext executionContext) throws IOException {\n \tthis(additionalTablesFile, additionalAssociationsFile, sourceSchemaMapping, assocFilter, new PrimaryKeyFactory(), executionContext, false);\n }\n\n /**\n * Reads in table.csv and association.csv\n * and builds the relational data model.\n * \n * @param additionalTablesFile table file to read too\n * @param additionalAssociationsFile association file to read too\n * @throws IOException \n */\n public DataModel(String additionalTablesFile, String additionalAssociationsFile, Map sourceSchemaMapping, LineFilter assocFilter, PrimaryKeyFactory primaryKeyFactory, ExecutionContext executionContext, boolean failOnMissingTables) throws IOException {\n \tthis.executionContext = executionContext;\n \tthis.primaryKeyFactory = primaryKeyFactory;\n \ttry {\n\t\t\tList excludeFromDeletion = new ArrayList();\n\t\t\tPrintUtil.loadTableList(excludeFromDeletion, openModelFile(new File(DataModel.getExcludeFromDeletionFile(executionContext)), executionContext));\n\n\t \t// tables\n\t \tFile tabFile = new File(getTablesFile(executionContext));\n\t\t\tInputStream nTablesFile = openModelFile(tabFile, executionContext);\n\t\t\tif (failOnMissingTables && nTablesFile == null) {\n\t\t\t\tthrow new RuntimeException(\"Datamodel not found: \" + executionContext.getDataModelURL());\n\t\t\t}\n\t\t\tCsvFile tablesFile = new CsvFile(nTablesFile, null, tabFile.getPath(), null);\n\t List tableList = new ArrayList(tablesFile.getLines());\n\t if (additionalTablesFile != null) {\n\t tableList.addAll(new CsvFile(new File(additionalTablesFile)).getLines());\n\t }\n\t for (CsvFile.Line line: tableList) {\n\t boolean defaultUpsert = \"Y\".equalsIgnoreCase(line.cells.get(1));\n\t List pk = new ArrayList();\n\t int j;\n\t for (j = 2; j < line.cells.size() && line.cells.get(j).toString().length() > 0; ++j) {\n\t String col = line.cells.get(j).trim();\n\t try {\n\t \tpk.add(Column.parse(col));\n\t } catch (Exception e) {\n\t \tthrow new RuntimeException(\"unable to load table '\" + line.cells.get(0) + \"'. \" + line.location, e);\n\t }\n\t }\n\t String mappedSchemaTableName = SqlUtil.mappedSchema(sourceSchemaMapping, line.cells.get(0));\n\t\t\t\tTable table = new Table(mappedSchemaTableName, primaryKeyFactory.createPrimaryKey(pk), defaultUpsert, excludeFromDeletion.contains(mappedSchemaTableName));\n\t\t\t\ttable.setAuthor(line.cells.get(j + 1));\n\t\t\t\ttable.setOriginalName(line.cells.get(0));\n\t\t\t\tif (tables.containsKey(mappedSchemaTableName)) {\n\t\t\t\t\tif (additionalTablesFile == null) {\n\t\t\t\t\t\tthrow new RuntimeException(\"Duplicate table name '\" + mappedSchemaTableName + \"'\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t tables.put(mappedSchemaTableName, table);\n\t }\n\t \n\t // columns\n\t File colFile = new File(getColumnsFile(executionContext));\n\t\t\tInputStream is = openModelFile(colFile, executionContext);\n\t if (is != null) {\n\t\t \tCsvFile columnsFile = new CsvFile(is, null, colFile.getPath(), null);\n\t\t List columnsList = new ArrayList(columnsFile.getLines());\n\t\t for (CsvFile.Line line: columnsList) {\n\t\t List columns = new ArrayList();\n\t\t for (int j = 1; j < line.cells.size() && line.cells.get(j).toString().length() > 0; ++j) {\n\t\t String col = line.cells.get(j).trim();\n\t\t try {\n\t\t \tcolumns.add(Column.parse(col));\n\t\t } catch (Exception e) {\n\t\t \t// ignore\n\t\t\t\t\t\t}\n\t\t }\n\t\t Table table = tables.get(SqlUtil.mappedSchema(sourceSchemaMapping, line.cells.get(0)));\n\t\t if (table != null) {\n\t\t \ttable.setColumns(columns);\n\t\t }\n\t\t }\n\t }\n\t \n\t // associations\n\t File assFile = new File(getAssociationsFile(executionContext));\n\t\t\tList associationList = new ArrayList(new CsvFile(openModelFile(assFile, executionContext), null, assFile.getPath(), assocFilter).getLines());\n\t if (additionalAssociationsFile != null) {\n\t associationList.addAll(new CsvFile(new File(additionalAssociationsFile)).getLines());\n\t }\n\t for (CsvFile.Line line: associationList) {\n\t String location = line.location;\n\t try {\n\t \tString associationLoadFailedMessage = \"Unable to load association from \" + line.cells.get(0) + \" to \" + line.cells.get(1) + \" on \" + line.cells.get(4) + \" because: \";\n\t Table tableA = (Table) tables.get(SqlUtil.mappedSchema(sourceSchemaMapping, line.cells.get(0)));\n\t if (tableA == null) {\n\t continue;\n//\t throw new RuntimeException(associationLoadFailedMessage + \"Table '\" + line.cells.get(0) + \"' not found\");\n\t }\n\t Table tableB = (Table) tables.get(SqlUtil.mappedSchema(sourceSchemaMapping, line.cells.get(1)));\n\t if (tableB == null) {\n\t \tcontinue;\n//\t \tthrow new RuntimeException(associationLoadFailedMessage + \"Table '\" + line.cells.get(1) + \"' not found\");\n\t }\n\t boolean insertSourceBeforeDestination = \"A\".equalsIgnoreCase(line.cells.get(2)); \n\t boolean insertDestinationBeforeSource = \"B\".equalsIgnoreCase(line.cells.get(2));\n\t Cardinality cardinality = Cardinality.parse(line.cells.get(3).trim());\n\t if (cardinality == null) {\n\t \tcardinality = Cardinality.MANY_TO_MANY;\n\t }\n\t String joinCondition = line.cells.get(4);\n\t String name = line.cells.get(5);\n\t if (\"\".equals(name)) {\n\t name = null;\n\t }\n\t if (name == null) {\n\t throw new RuntimeException(associationLoadFailedMessage + \"Association name missing (column 6 is empty, each association must have an unique name)\");\n\t }\n\t String author = line.cells.get(6);\n\t Association associationA = new Association(tableA, tableB, insertSourceBeforeDestination, insertDestinationBeforeSource, joinCondition, this, false, cardinality, author);\n\t Association associationB = new Association(tableB, tableA, insertDestinationBeforeSource, insertSourceBeforeDestination, joinCondition, this, true, cardinality.reverse(), author);\n\t associationA.reversalAssociation = associationB;\n\t associationB.reversalAssociation = associationA;\n\t tableA.associations.add(associationA);\n\t tableB.associations.add(associationB);\n\t if (name != null) {\n\t if (namedAssociations.put(name, associationA) != null) {\n\t throw new RuntimeException(\"duplicate association name: \" + name);\n\t }\n\t associationA.setName(name);\n\t name = \"inverse-\" + name;\n\t if (namedAssociations.put(name, associationB) != null) {\n\t throw new RuntimeException(\"duplicate association name: \" + name);\n\t }\n\t associationB.setName(name);\n\t }\n\t } catch (Exception e) {\n\t throw new RuntimeException(location + \": \" + e.getMessage(), e);\n\t }\n\t }\n\t initDisplayNames();\n\t initTableOrdinals();\n\t \n\t // model name\n\t File nameFile = new File(getModelNameFile(executionContext));\n\t name = DEFAULT_NAME;\n\t \tlastModified = null;\n\t try {\n\t \tlastModified = nameFile.lastModified();\n\t\t if (nameFile.exists()) {\n\t\t \tList nameList = new ArrayList(new CsvFile(nameFile).getLines());\n\t\t \tif (nameList.size() > 0) {\n\t\t \t\tCsvFile.Line line = nameList.get(0);\n\t\t \t\tname = line.cells.get(0);\n\t\t \t\tlastModified = Long.parseLong(line.cells.get(1));\n\t\t \t}\n\t\t }\n\t } catch (Throwable t) {\n\t \t// keep defaults\n\t }\n \t} catch (IOException e) {\n \t\t_log.error(\"failed to load data-model \" + getDatamodelFolder(executionContext) + File.separator, e);\n \t\tthrow e;\n \t}\n }\n\n private final List
tableList = new ArrayList
();\n\tprivate final List filterTemplates = new ArrayList();\n \n /**\n * Initializes table ordinals.\n */\n private void initTableOrdinals() {\n \tfor (Table table: getSortedTables()) {\n \t\ttable.ordinal = tableList.size();\n \t\ttableList.add(table);\n \t}\n\t}\n\n\t/**\n * Initializes display names.\n */\n private void initDisplayNames() throws IOException {\n \tSet unqualifiedNames = new HashSet();\n \tSet nonUniqueUnqualifiedNames = new HashSet();\n \t\n \tfor (Table table: getTables()) {\n \t\tString uName = table.getUnqualifiedName();\n \t\tif (unqualifiedNames.contains(uName)) {\n \t\t\tnonUniqueUnqualifiedNames.add(uName);\n \t\t} else {\n \t\t\tunqualifiedNames.add(uName);\n \t\t}\n \t}\n\n \tfor (Table table: getTables()) {\n \t\tString uName = table.getUnqualifiedName();\n \t\tif (uName != null && uName.length() > 0) {\n char fc = uName.charAt(0);\n if (!Character.isLetterOrDigit(fc) && fc != '_') {\n String fcStr = Character.toString(fc);\n if (uName.startsWith(fcStr) && uName.endsWith(fcStr)) {\n uName = uName.substring(1, uName.length() -1);\n }\n }\n \t\t}\n \t\tString schema = table.getSchema(null);\n \t\tString displayName;\n \t\tif (nonUniqueUnqualifiedNames.contains(uName) && schema != null) {\n \t\t\tdisplayName = uName + \" (\" + schema + \")\";\n \t\t} else {\n \t\t\tdisplayName = uName;\n \t\t}\n \t\tthis.displayName.put(table, displayName);\n \t\ttablesByDisplayName.put(displayName, table);\n \t}\n \t\n \tMap userDefinedDisplayNames = new TreeMap();\n File dnFile = new File(DataModel.getDisplayNamesFile(executionContext));\n if (dnFile.exists()) {\n \tfor (CsvFile.Line dnl: new CsvFile(dnFile).getLines()) {\n \t\tuserDefinedDisplayNames.put(dnl.cells.get(0), dnl.cells.get(1));\n \t}\n }\n \n \tfor (Map.Entry e: userDefinedDisplayNames.entrySet()) {\n \t\tTable table = getTable(e.getKey());\n \t\tif (table != null && !tablesByDisplayName.containsKey(e.getValue())) {\n \t\t\tString displayName = getDisplayName(table);\n \t\tthis.displayName.remove(table);\n \t\tif (displayName != null) {\n \t\t\ttablesByDisplayName.remove(displayName);\n \t\t}\n \t\tthis.displayName.put(table, e.getValue());\n \t\ttablesByDisplayName.put(e.getValue(), table);\n \t\t}\n \t}\n }\n \n /**\n * Gets the primary-key to be used for the entity-table.\n *\n * @param session for null value guessing\n * @return the universal primary key\n */\n PrimaryKey getUniversalPrimaryKey(Session session) {\n return primaryKeyFactory.getUniversalPrimaryKey(session);\n }\n\n /**\n * Gets the primary-key to be used for the entity-table.\n * \n * @return the universal primary key\n */\n PrimaryKey getUniversalPrimaryKey() {\n return getUniversalPrimaryKey(null);\n }\n\n /**\n * Gets the restriction model.\n * \n * @return the restriction model\n */\n public RestrictionModel getRestrictionModel() {\n return restrictionModel;\n }\n\n /**\n * Sets the restriction model.\n * \n * @param restrictionModel the restriction model\n */\n public void setRestrictionModel(RestrictionModel restrictionModel) {\n this.restrictionModel = restrictionModel;\n\t\t++version;\n }\n\n /**\n * Gets all independent tables\n * (i.e. tables which don't depend on other tables in the set)\n * of a given table-set.\n * \n * @param tableSet the table-set\n * @return the sub-set of independent tables of the table-set\n */\n public Set
getIndependentTables(Set
tableSet) {\n \treturn getIndependentTables(tableSet, null);\n }\n \n /**\n * Gets all independent tables\n * (i.e. tables which don't depend on other tables in the set)\n * of a given table-set.\n * \n * @param tableSet the table-set\n * @param associations the associations to consider, null for all associations\n * @return the sub-set of independent tables of the table-set\n */\n public Set
getIndependentTables(Set
tableSet, Set associations) {\n Set
independentTables = new HashSet
();\n \n for (Table table: tableSet) {\n boolean depends = false;\n for (Association a: table.associations) {\n \tif (associations == null || associations.contains(a)) {\n\t if (tableSet.contains(a.destination)) {\n\t if (a.getJoinCondition() != null) {\n\t if (a.isInsertDestinationBeforeSource()) {\n\t depends = true;\n\t break;\n\t }\n\t }\n\t }\n }\n }\n if (!depends) {\n independentTables.add(table);\n }\n }\n return independentTables;\n }\n\n /**\n * Transposes the data-model.\n */\n public void transpose() {\n if (getRestrictionModel() != null) {\n getRestrictionModel().transpose();\n }\n\t\t++version;\n }\n \n /**\n * Stringifies the data model.\n */\n public String toString() {\n List
sortedTables;\n sortedTables = getSortedTables();\n StringBuffer str = new StringBuffer();\n if (restrictionModel != null) {\n str.append(\"restricted by: \" + restrictionModel + \"\\n\");\n }\n for (Table table: sortedTables) {\n str.append(table);\n if (printClosures) {\n str.append(\" closure =\");\n str.append(new PrintUtil().tableSetAsString(table.closure(true)) + \"\\n\\n\");\n }\n }\n return str.toString();\n }\n\n /**\n * Gets list of tables sorted by name.\n * \n * @return list of tables sorted by name\n */\n\tpublic List
getSortedTables() {\n\t\tList
sortedTables;\n\t\tsortedTables = new ArrayList
(getTables());\n Collections.sort(sortedTables, new Comparator
() {\n public int compare(Table o1, Table o2) {\n return o1.getName().compareTo(o2.getName());\n }\n });\n\t\treturn sortedTables;\n\t}\n\n /**\n * Printing-mode.\n */\n public static boolean printClosures = false;\n\n /**\n * Normalizes a set of tables.\n * \n * @param tables set of tables\n * @return set of all tables from this model for which a table with same name exists in tables \n */\n public Set
normalize(Set
tables) {\n Set
result = new HashSet
();\n for (Table table: tables) {\n result.add(getTable(table.getName()));\n }\n return result;\n }\n\n /**\n * Assigns a unique ID to each association.\n */\n\tpublic void assignAssociationIDs() {\n\t\tint n = 1;\n\t\tfor (Map.Entry e: namedAssociations.entrySet()) {\n\t\t\te.getValue().id = n++;\n\t\t}\n\t}\n\n /**\n\t * Gets export modus, SQL or XML. (GUI support).\n\t */\n\tpublic String getExportModus() {\n\t\treturn exportModus;\n\t}\n\t\n /**\n\t * Sets export modus, SQL or XML. (GUI support).\n\t */\n\tpublic void setExportModus(String modus) {\n\t\texportModus = modus;\n\t\t++version;\n\t}\n\n\t/**\n\t * Gets XML settings for exportation into XML files.\n\t */\n\tpublic XmlSettings getXmlSettings() {\n\t\treturn xmlSettings;\n\t}\n\n\t/**\n\t * Sets XML settings for exportation into XML files.\n\t */\n\tpublic void setXmlSettings(XmlSettings xmlSettings) {\n\t\tthis.xmlSettings = xmlSettings;\n\t\t++version;\n\t}\n\n /**\n * Gets internal version number. Incremented on each modification.\n * \n * @return internal version number. Incremented on each modification.\n */\n public long getVersion() {\n \treturn version;\n }\n \n /**\n * Thrown if a table has no primary key.\n */\n public static class NoPrimaryKeyException extends RuntimeException {\n\t\tprivate static final long serialVersionUID = 4523935351640139649L;\n\t\tpublic final Table table;\n \tpublic NoPrimaryKeyException(Table table) {\n\t\t\tsuper(\"Table '\" + table.getName() + \"' has no primary key\");\n\t\t\tthis.table = table;\n\t\t}\n }\n\n /**\n * Checks whether all tables in the closure of a given subject have primary keys.\n * \n * @param subject the subject\n * @throws NoPrimaryKeyException if a table has no primary key\n */\n public void checkForPrimaryKey(Set
subjects, boolean forDeletion) throws NoPrimaryKeyException {\n \tSet
checked = new HashSet
();\n \tfor (Table subject: subjects) {\n\t \tSet
toCheck = new HashSet
(subject.closure(checked, true));\n\t \tif (forDeletion) {\n\t \t\tSet
border = new HashSet
();\n\t \t\tfor (Table table: toCheck) {\n\t \t\t\tfor (Association a: table.associations) {\n\t \t\t\t\tif (!a.reversalAssociation.isIgnored()) {\n\t \t\t\t\t\tborder.add(a.destination);\n\t \t\t\t\t}\n\t \t\t\t}\n\t \t\t}\n\t \t\ttoCheck.addAll(border);\n\t \t}\n\t \tfor (Table table: toCheck) {\n\t \t\tif (table.primaryKey.getColumns().isEmpty()) {\n\t \t\t\tthrow new NoPrimaryKeyException(table);\n\t \t\t}\n\t \t}\n\t \tchecked.addAll(toCheck);\n \t}\n }\n\n /**\n * Gets all parameters which occur in subject condition, association restrictions or XML templates.\n * \n * @param subjectCondition the subject condition\n * @return all parameters which occur in subject condition, association restrictions or XML templates\n */\n public SortedSet getParameters(String subjectCondition, List additionalSubjects) {\n \tSortedSet parameters = new TreeSet();\n \t\n \tParameterHandler.collectParameter(subjectCondition, parameters);\n \tif (additionalSubjects != null) {\n \t\tfor (AdditionalSubject as: additionalSubjects) {\n \t\t\tParameterHandler.collectParameter(as.getCondition(), parameters);\n \t\t}\n \t}\n \tfor (Association a: namedAssociations.values()) {\n \t\tString r = a.getRestrictionCondition();\n \t\tif (r != null) {\n \t\t\tParameterHandler.collectParameter(r, parameters);\n \t\t}\n \t}\n \tfor (Table t: getTables()) {\n \t\tString r = t.getXmlTemplate();\n \t\tif (r != null) {\n \t\t\tParameterHandler.collectParameter(r, parameters);\n \t\t}\n \t\tfor (Column c: t.getColumns()) {\n \t\t\tif (c.getFilterExpression() != null) {\n \t\t\t\tParameterHandler.collectParameter(c.getFilterExpression(), parameters);\n \t\t\t}\n \t\t}\n \t}\n \treturn parameters;\n }\n\n private static InputStream openModelFile(File file, ExecutionContext executionContext) {\n \ttry {\n\t\t\tURL dataModelURL = executionContext.getDataModelURL();\n\t\t\tURI uri = dataModelURL.toURI();\n\t\t\tURI resolved = new URI(uri.toString() + file.getName()); // uri.resolve(file.getName());\n\t\t\treturn resolved.toURL().openStream();\n\t\t} catch (MalformedURLException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t} catch (IOException e) {\n\t\t\treturn null;\n\t\t} catch (URISyntaxException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n }\n \n /**\n * Gets {@link #getLastModified()} as String.\n * \n * @return {@link #getLastModified()} as String\n */\n\tpublic String getLastModifiedAsString() {\n\t\ttry {\n\t\t\treturn SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.MEDIUM, SimpleDateFormat.MEDIUM).format(new Date(getLastModified()));\n\t\t} catch (Throwable t) {\n\t\t\treturn \"\";\n\t\t}\n\t}\n\n\t/**\n\t * Saves the data model.\n\t * \n\t * @param file the file name\n\t * @param stable \n\t * @param stable the subject table\n\t * @param subjectCondition \n\t * @param scriptFormat\n\t * @param positions table positions or null\n\t * @param additionalSubjects \n\t */\n\tpublic void save(String file, Table stable, String subjectCondition, ScriptFormat scriptFormat, List restrictionDefinitions, Map> positions, List additionalSubjects, String currentModelSubfolder) throws FileNotFoundException {\n\t\tFile extractionModel = new File(file);\n\t\tPrintWriter out = new PrintWriter(extractionModel);\n\t\tout.println(\"# subject; condition\");\n\t\tout.println(CsvFile.encodeCell(\"\" + stable.getName()) + \"; \" + CsvFile.encodeCell(subjectCondition));\n\t\tsaveRestrictions(out, restrictionDefinitions);\n\t\tsaveXmlMapping(out);\n\t\tout.println();\n\t\tout.println(CsvFile.BLOCK_INDICATOR + \"datamodelfolder\");\n\t\tif (currentModelSubfolder != null) {\n\t\t\tout.println(currentModelSubfolder);\n\t\t}\n\t\tout.println();\n\t\tout.println(CsvFile.BLOCK_INDICATOR + \"additional subjects\");\n\t\tfor (AdditionalSubject as: additionalSubjects) {\n\t\t\tout.println(CsvFile.encodeCell(\"\" + as.getSubject().getName()) + \"; \" + CsvFile.encodeCell(as.getCondition()) + \";\");\n\t\t}\n\t\tout.println();\n\t\tout.println(CsvFile.BLOCK_INDICATOR + \"export modus\");\n\t\tout.println(scriptFormat);\n\t\tout.println();\n\t\tout.println(CsvFile.BLOCK_INDICATOR + \"xml settings\");\n\t\tout.println(CsvFile.encodeCell(getXmlSettings().datePattern) + \";\" + \n\t\t\t CsvFile.encodeCell(getXmlSettings().timestampPattern) + \";\" +\n\t\t\t CsvFile.encodeCell(getXmlSettings().rootTag));\n\t\tout.println(CsvFile.BLOCK_INDICATOR + \"xml column mapping\");\n\t\tfor (Table table: getTables()) {\n\t\t\tString xmlMapping = table.getXmlTemplate();\n\t\t\tif (xmlMapping != null) {\n\t\t\t\tout.println(CsvFile.encodeCell(table.getName()) + \"; \" + CsvFile.encodeCell(xmlMapping));\n\t\t\t}\n\t\t}\n\t\tout.println(CsvFile.BLOCK_INDICATOR + \"upserts\");\n\t\tfor (Table table: getTables()) {\n\t\t\tif (table.upsert != null) {\n\t\t\t\tout.println(CsvFile.encodeCell(table.getName()) + \"; \" + CsvFile.encodeCell(table.upsert.toString()));\n\t\t\t}\n\t\t}\n\t\tout.println(CsvFile.BLOCK_INDICATOR + \"exclude from deletion\");\n\t\tfor (Table table: getTables()) {\n\t\t\tif (table.excludeFromDeletion != null) {\n\t\t\t\tout.println(CsvFile.encodeCell(table.getName()) + \"; \" + CsvFile.encodeCell(table.excludeFromDeletion.toString()));\n\t\t\t}\n\t\t}\n\t\tsaveFilters(out);\n\t\tsaveFilterTemplates(out);\n\t\tout.println();\n\t\tif (positions == null) {\n\t\t\tLayoutStorage.store(out);\n\t\t} else {\n\t\t\tLayoutStorage.store(out, positions);\n\t\t}\n\t\t\n\t\tout.println();\n\t\tout.println(CsvFile.BLOCK_INDICATOR + \"known\");\n\t\tfor (Association a: namedAssociations.values()) {\n\t\t\tif (!a.reversed) {\n\t\t\t\tout.println(CsvFile.encodeCell(a.getName()));\n\t\t\t}\n\t\t}\n\t\t\n\t\tout.println();\n\t\tout.println(CsvFile.BLOCK_INDICATOR + \"version\");\n\t\tout.println(JailerVersion.VERSION);\n\t\tout.close();\n\t}\n\t\n\t/**\n\t * Saves xml mappings.\n\t * \n\t * @param out to save xml mappings into\n\t */\n\tprivate void saveXmlMapping(PrintWriter out) {\n\t\tout.println();\n\t\tout.println(CsvFile.BLOCK_INDICATOR + \"xml-mapping\");\n\t\tfor (Table table: getTables()) {\n\t\t\tfor (Association a: table.associations) {\n\t\t\t\tString name = a.getName();\n\t\t\t\tString tag = a.getAggregationTagName();\n\t\t\t\tString aggregation = a.getAggregationSchema().name();\n\t\t\t\tout.println(CsvFile.encodeCell(name) + \";\" + CsvFile.encodeCell(tag) + \";\" + CsvFile.encodeCell(aggregation));\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Saves restrictions only.\n\t * \n\t * @param out to save restrictions into\n\t * @param restrictionDefinitions \n\t */\n\tprivate void saveRestrictions(PrintWriter out, List restrictionDefinitions) {\n\t\tout.println();\n\t\tout.println(\"# association; ; restriction-condition\");\n\t\tfor (RestrictionDefinition rd: restrictionDefinitions) {\n\t\t\tString condition = rd.isIgnored? \"ignore\" : rd.condition;\n\t\t\tif (rd.name == null || rd.name.trim().length() == 0) {\n\t\t\t\tout.println(CsvFile.encodeCell(rd.from.getName()) + \"; \" + CsvFile.encodeCell(rd.to.getName()) + \"; \" + CsvFile.encodeCell(condition));\n\t\t\t} else {\n\t\t\t\tout.println(CsvFile.encodeCell(rd.name) + \"; ; \" + CsvFile.encodeCell(condition));\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Saves restrictions only.\n\t * \n\t * @param file to save restrictions into\n\t */\n\tpublic void saveRestrictions(File file, List restrictionDefinitions) throws FileNotFoundException {\n\t\tPrintWriter out = new PrintWriter(file);\n\t\tsaveRestrictions(out, restrictionDefinitions);\n\t\tout.close();\n\t}\n\n\t/**\n\t * Saves filters.\n\t * \n\t * @param out to save filters into\n\t */\n\tprivate void saveFilters(PrintWriter out) {\n\t\tout.println();\n\t\tout.println(CsvFile.BLOCK_INDICATOR + \"filters\");\n\t\tfor (Table table: getTables()) {\n\t\t\tfor (Column c: table.getColumns()) {\n\t\t\t\tif (c.getFilter() != null && !c.getFilter().isDerived()) {\n\t\t\t\t\tout.println(CsvFile.encodeCell(table.getName()) + \";\" + CsvFile.encodeCell(c.name) + \";\" + CsvFile.encodeCell(c.getFilter().getExpression())\n\t\t\t\t\t+ \";\" + CsvFile.encodeCell(c.getFilter().isApplyAtExport()? \"Export\" : \"Import\")\n\t\t\t\t\t+ \";\" + CsvFile.encodeCell(c.getFilter().getType() == null? \"\" : c.getFilter().getType()));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\n\t/**\n\t * Saves filter templates.\n\t * \n\t * @param out to save filters into\n\t */\n\tprivate void saveFilterTemplates(PrintWriter out) {\n\t\tout.println();\n\t\tout.println(CsvFile.BLOCK_INDICATOR + \"filter templates\");\n\t\tfor (FilterTemplate template: getFilterTemplates()) {\n\t\t\tout.println(\"T;\"\n\t\t\t\t\t+ CsvFile.encodeCell(template.getName()) + \";\"\n\t\t\t\t\t+ CsvFile.encodeCell(template.getExpression()) + \";\"\n\t\t\t\t\t+ CsvFile.encodeCell(template.isEnabled()? \"enabled\" : \"disabled\") + \";\"\n\t\t\t\t\t+ CsvFile.encodeCell(template.isApplyAtExport()? \"Export\" : \"Import\") + \";\"\n\t\t\t\t\t+ CsvFile.encodeCell(template.getType() == null? \"\" : template.getType()) + \";\");\n\t\t\tfor (Clause clause: template.getClauses()) {\n\t\t\t\tout.println(\"C;\"\n\t\t\t\t\t\t+ CsvFile.encodeCell(clause.getSubject().name()) + \";\"\n\t\t\t\t\t\t+ CsvFile.encodeCell(clause.getPredicate().name()) + \";\"\n\t\t\t\t\t\t+ CsvFile.encodeCell(clause.getObject()) + \";\");\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Gets table by {@link Table#getOrdinal()}.\n\t * \n\t * @param ordinal the ordinal\n\t * @return the table\n\t */\n\tpublic Table getTableByOrdinal(int ordinal) {\n\t\treturn tableList.get(ordinal);\n\t}\n\n\t/**\n\t * Gets the {@link FilterTemplate}s ordered by priority.\n\t * \n\t * @return template list\n\t */\n\tpublic List getFilterTemplates() {\n\t\treturn filterTemplates;\n\t}\n\n\tprivate Map> sToDMaps = new HashMap>();\n\t\n /**\n * Removes all derived filters and renews them.\n */\n public void deriveFilters() {\n \tsToDMaps.clear();\n\t\tfor (Table table: getTables()) {\n\t\t\tfor (Column column: table.getColumns()) {\n\t\t\t\tFilter filter = column.getFilter();\n\t\t\t\tif (filter != null && filter.isDerived()) {\n\t\t\t\t\tcolumn.setFilter(null);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tSet pkNames = new HashSet();\n\t\tfor (Table table: getTables()) {\n\t\t\tpkNames.clear();\n\t\t\tfor (Column column: table.primaryKey.getColumns()) {\n\t\t\t\tpkNames.add(column.name);\n\t\t\t}\n\t\t\tfor (Column column: table.getColumns()) {\n\t\t\t\tif (pkNames.contains(column.name)) {\n\t\t\t\t\tFilter filter = column.getFilter();\n\t\t\t\t\tif (filter != null && !filter.isDerived()) {\n\t\t\t\t\t\tList aTo = new ArrayList();\n\t\t\t\t\t\tderiveFilter(table, column, filter, new PKColumnFilterSource(table, column), aTo, null);\n\t\t\t\t\t\tif (!aTo.isEmpty()) {\n\t\t\t\t\t\t\tCollections.sort(aTo);\n\t\t\t\t\t\t\tfilter.setAppliedTo(aTo);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t// apply templates\n\t\tfor (FilterTemplate template: getFilterTemplates()) {\n\t\t\tif (template.isEnabled()) {\n\t\t\t\tfor (Table table: getTables()) {\n\t\t\t\t\tfor (Column column: table.getColumns()) {\n\t\t\t\t\t\tif (column.getFilter() == null && template.matches(table, column)) {\n\t\t\t\t\t\t\tFilter filter = new Filter(template.getExpression(), template.getType(), true, template);\n\t\t\t\t\t\t\tfilter.setApplyAtExport(template.isApplyAtExport());\n\t\t\t\t\t\t\tcolumn.setFilter(filter);\n\t\t\t\t\t\t\tList aTo = new ArrayList();\n\t\t\t\t\t\t\tderiveFilter(table, column, filter, new PKColumnFilterSource(table, column), aTo, template);\n\t\t\t\t\t\t\tif (!aTo.isEmpty()) {\n\t\t\t\t\t\t\t\tCollections.sort(aTo);\n\t\t\t\t\t\t\t\tfilter.setAppliedTo(aTo);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tsToDMaps.clear();\n\t}\n\n\tprivate void deriveFilter(Table table, Column column, Filter filter, FilterSource filterSource, List aTo, FilterSource overwriteForSource) {\n\t\tfor (Association association: table.associations) {\n\t\t\tif (association.isInsertSourceBeforeDestination()) {\n\t\t\t\tMap sToDMap = sToDMaps.get(association);\n\t\t\t\tif (sToDMap == null) {\n\t\t\t\t\tsToDMap = association.createSourceToDestinationKeyMapping();\n\t\t\t\t\tsToDMaps.put(association, sToDMap);\n\t\t\t\t}\n\t\t\t\tColumn destColumn = sToDMap.get(column);\n\t\t\t\tif (destColumn != null && (destColumn.getFilter() == null || overwriteForSource != null && destColumn.getFilter().getFilterSource() == overwriteForSource)) {\n\t\t\t\t\tFilter newFilter = new Filter(filter.getExpression(), filter.getType(), true, filterSource);\n\t\t\t\t\tnewFilter.setApplyAtExport(filter.isApplyAtExport());\n\t\t\t\t\tdestColumn.setFilter(newFilter);\n\t\t\t\t\taTo.add(association.destination.getName() + \".\" + destColumn.name);\n\t\t\t\t\tderiveFilter(association.destination, destColumn, filter, filterSource, aTo, overwriteForSource);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n}\n"},"new_file":{"kind":"string","value":"src/main/engine/net/sf/jailer/datamodel/DataModel.java"},"old_contents":{"kind":"string","value":"/*\n * Copyright 2007 - 2017 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * 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 net.sf.jailer.datamodel;\n\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.PrintWriter;\nimport java.net.MalformedURLException;\nimport java.net.URISyntaxException;\nimport java.text.SimpleDateFormat;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.SortedSet;\nimport java.util.TreeMap;\nimport java.util.TreeSet;\n\nimport org.apache.log4j.Logger;\n\nimport net.sf.jailer.ExecutionContext;\nimport net.sf.jailer.JailerVersion;\nimport net.sf.jailer.database.Session;\nimport net.sf.jailer.datamodel.filter_template.Clause;\nimport net.sf.jailer.datamodel.filter_template.FilterTemplate;\nimport net.sf.jailer.extractionmodel.ExtractionModel;\nimport net.sf.jailer.extractionmodel.ExtractionModel.AdditionalSubject;\nimport net.sf.jailer.restrictionmodel.RestrictionModel;\nimport net.sf.jailer.subsetting.ScriptFormat;\nimport net.sf.jailer.util.CsvFile;\nimport net.sf.jailer.util.CsvFile.LineFilter;\nimport net.sf.jailer.util.LayoutStorage;\nimport net.sf.jailer.util.PrintUtil;\nimport net.sf.jailer.util.SqlUtil;\n\n/**\n * Relational data model.\n * \n * @author Ralf Wisser\n */\npublic class DataModel {\n\n\tpublic static final String TABLE_CSV_FILE = \"table.csv\";\n\tpublic static final String MODELNAME_CSV_FILE = \"modelname.csv\";\n\n\t/**\n * Maps table-names to tables.\n */\n private Map tables = new HashMap();\n \n\t/**\n * Maps table display names to tables.\n */\n private Map tablesByDisplayName = new HashMap();\n \n\t/**\n * Maps tables to display names.\n */\n private Map displayName = new HashMap();\n \n /**\n * Maps association-names to associations;\n */\n public Map namedAssociations = new TreeMap();\n \n /**\n * The restriction model.\n */\n private RestrictionModel restrictionModel;\n \n /**\n * Internal version number. Incremented on each modification.\n */\n public long version = 0;\n\n\t/**\n\t * The execution context.\n\t */\n\tprivate final ExecutionContext executionContext;\n\t\n\t/**\n * Default model name.\n */\n\tpublic static final String DEFAULT_NAME = \"New Model\";\n\n /**\n * For creation of primary-keys.\n */\n private final PrimaryKeyFactory primaryKeyFactory;\n\n /**\n * Gets name of data model folder.\n */\n public static String getDatamodelFolder(ExecutionContext executionContext) {\n \treturn executionContext.getQualifiedDatamodelFolder();\n }\n\n /**\n * Gets name of file containing the table definitions.\n */\n public static String getTablesFile(ExecutionContext executionContext) {\n \treturn getDatamodelFolder(executionContext) + File.separator + TABLE_CSV_FILE;\n }\n\n /**\n * Gets name of file containing the model name\n */\n public static String getModelNameFile(ExecutionContext executionContext) {\n \treturn getDatamodelFolder(executionContext) + File.separator + MODELNAME_CSV_FILE;\n }\n\n /**\n * Gets name of file containing the display names.\n */\n public static String getDisplayNamesFile(ExecutionContext executionContext) {\n \treturn getDatamodelFolder(executionContext) + File.separator + \"displayname.csv\";\n }\n\n /**\n * Gets name of file containing the column definitions.\n */\n public static String getColumnsFile(ExecutionContext executionContext) {\n \treturn getDatamodelFolder(executionContext) + File.separator + \"column.csv\";\n }\n\n /**\n * Gets name of file containing the association definitions.\n */\n\tpublic static String getAssociationsFile(ExecutionContext executionContext) {\n\t\treturn getDatamodelFolder(executionContext) + File.separator + \"association.csv\";\n\t}\n\t\n\t/**\n\t * List of tables to be excluded from deletion.\n\t */\n\tpublic static String getExcludeFromDeletionFile(ExecutionContext executionContext) {\n\t\treturn getDatamodelFolder(executionContext) + File.separator + \"exclude-from-deletion.csv\";\n\t}\n\t\n\t/**\n * Name of file containing the version number.\n */\n public static String getVersionFile(ExecutionContext executionContext) {\n \treturn getDatamodelFolder(executionContext) + File.separator + \"version.csv\";\n \t}\n\n /**\n\t * Export modus, SQL or XML. (GUI support).\n\t */\n\tprivate String exportModus;\n\t\n\t/**\n\t * Holds XML settings for exportation into XML files.\n\t */\n\tpublic static class XmlSettings {\n\t\tpublic String datePattern = \"yyyy-MM-dd\";\n\t\tpublic String timestampPattern = \"yyyy-MM-dd-HH.mm.ss\";\n\t\tpublic String rootTag = \"rowset\";\n\t}\n\n\t/**\n\t * XML settings for exportation into XML files.\n\t */\n\tprivate XmlSettings xmlSettings = new XmlSettings();\n\n\t/**\n\t * Name of the model.\n\t */\n\tprivate String name;\n\n\t/**\n\t * Time of last modification.\n\t */\n\tprivate Long lastModified;\n\t\n\t/**\n\t * The logger.\n\t */\n\tprivate static final Logger _log = Logger.getLogger(DataModel.class);\n\n\t/**\n * Gets a table by name.\n * \n * @param name the name of the table\n * @return the table or null iff no table with the name exists\n */\n public Table getTable(String name) {\n return tables.get(name);\n }\n\n /**\n * Gets a table by display name.\n * \n * @param displayName the display name of the table\n * @return the table or null iff no table with the display name exists\n */\n public Table getTableByDisplayName(String displayName) {\n return tablesByDisplayName.get(displayName);\n }\n\n\t/**\n\t * Gets name of the model.\n\t * \n\t * @return name of the model\n\t */\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\t/**\n\t * Gets time of last modification.\n\t * \n\t * @return time of last modification\n\t */\n\tpublic Long getLastModified() {\n\t\treturn lastModified;\n\t}\n\n /**\n * Gets display name of a table\n * \n * @param table the table\n * @return the display name of the table\n */\n public String getDisplayName(Table table) {\n String displayName = this.displayName.get(table);\n if (displayName == null) {\n \treturn table.getName();\n }\n return displayName;\n }\n\n /**\n * Gets all tables.\n * \n * @return a collection of all tables\n */\n public Collection
getTables() {\n return tables.values();\n }\n \n /**\n * Reads in table.csv and association.csv\n * and builds the relational data model.\n */\n public DataModel(PrimaryKeyFactory primaryKeyFactory, Map sourceSchemaMapping, ExecutionContext executionContext) throws IOException {\n this(null, null, sourceSchemaMapping, null, primaryKeyFactory, executionContext, false);\n }\n\n /**\n * Reads in table.csv and association.csv\n * and builds the relational data model.\n */\n public DataModel(ExecutionContext executionContext) throws IOException {\n this(null, null, new PrimaryKeyFactory(), executionContext);\n }\n\n /**\n * Reads in table.csv and association.csv\n * and builds the relational data model.\n */\n public DataModel(Map sourceSchemaMapping, ExecutionContext executionContext, boolean failOnMissingTables) throws IOException {\n this(null, null, sourceSchemaMapping, null, new PrimaryKeyFactory(), executionContext, failOnMissingTables);\n }\n\n /**\n * Reads in table.csv and association.csv\n * and builds the relational data model.\n * \n * @param additionalTablesFile table file to read too\n * @param additionalAssociationsFile association file to read too\n */\n public DataModel(String additionalTablesFile, String additionalAssociationsFile, PrimaryKeyFactory primaryKeyFactory, ExecutionContext executionContext) throws IOException {\n \tthis(additionalTablesFile, additionalAssociationsFile, new HashMap(), null, primaryKeyFactory, executionContext, false);\n }\n\n /**\n * Reads in table.csv and association.csv\n * and builds the relational data model.\n * \n * @param additionalTablesFile table file to read too\n * @param additionalAssociationsFile association file to read too\n */\n public DataModel(String additionalTablesFile, String additionalAssociationsFile, ExecutionContext executionContext) throws IOException {\n \tthis(additionalTablesFile, additionalAssociationsFile, new HashMap(), null, new PrimaryKeyFactory(), executionContext, false);\n }\n\n /**\n * Reads in table.csv and association.csv\n * and builds the relational data model.\n * \n * @param additionalTablesFile table file to read too\n * @param additionalAssociationsFile association file to read too\n */\n public DataModel(String additionalTablesFile, String additionalAssociationsFile, Map sourceSchemaMapping, LineFilter assocFilter, ExecutionContext executionContext) throws IOException {\n \tthis(additionalTablesFile, additionalAssociationsFile, sourceSchemaMapping, assocFilter, new PrimaryKeyFactory(), executionContext, false);\n }\n\n /**\n * Reads in table.csv and association.csv\n * and builds the relational data model.\n * \n * @param additionalTablesFile table file to read too\n * @param additionalAssociationsFile association file to read too\n * @throws IOException \n */\n public DataModel(String additionalTablesFile, String additionalAssociationsFile, Map sourceSchemaMapping, LineFilter assocFilter, PrimaryKeyFactory primaryKeyFactory, ExecutionContext executionContext, boolean failOnMissingTables) throws IOException {\n \tthis.executionContext = executionContext;\n \tthis.primaryKeyFactory = primaryKeyFactory;\n \ttry {\n\t\t\tList excludeFromDeletion = new ArrayList();\n\t\t\tPrintUtil.loadTableList(excludeFromDeletion, openModelFile(new File(DataModel.getExcludeFromDeletionFile(executionContext)), executionContext));\n\n\t \t// tables\n\t \tFile tabFile = new File(getTablesFile(executionContext));\n\t\t\tInputStream nTablesFile = openModelFile(tabFile, executionContext);\n\t\t\tif (failOnMissingTables && nTablesFile == null) {\n\t\t\t\tthrow new RuntimeException(\"Datamodel not found: \" + executionContext.getDataModelURL());\n\t\t\t}\n\t\t\tCsvFile tablesFile = new CsvFile(nTablesFile, null, tabFile.getPath(), null);\n\t List tableList = new ArrayList(tablesFile.getLines());\n\t if (additionalTablesFile != null) {\n\t tableList.addAll(new CsvFile(new File(additionalTablesFile)).getLines());\n\t }\n\t for (CsvFile.Line line: tableList) {\n\t boolean defaultUpsert = \"Y\".equalsIgnoreCase(line.cells.get(1));\n\t List pk = new ArrayList();\n\t int j;\n\t for (j = 2; j < line.cells.size() && line.cells.get(j).toString().length() > 0; ++j) {\n\t String col = line.cells.get(j).trim();\n\t try {\n\t \tpk.add(Column.parse(col));\n\t } catch (Exception e) {\n\t \tthrow new RuntimeException(\"unable to load table '\" + line.cells.get(0) + \"'. \" + line.location, e);\n\t }\n\t }\n\t String mappedSchemaTableName = SqlUtil.mappedSchema(sourceSchemaMapping, line.cells.get(0));\n\t\t\t\tTable table = new Table(mappedSchemaTableName, primaryKeyFactory.createPrimaryKey(pk), defaultUpsert, excludeFromDeletion.contains(mappedSchemaTableName));\n\t\t\t\ttable.setAuthor(line.cells.get(j + 1));\n\t\t\t\ttable.setOriginalName(line.cells.get(0));\n\t\t\t\tif (tables.containsKey(mappedSchemaTableName)) {\n\t\t\t\t\tif (additionalTablesFile == null) {\n\t\t\t\t\t\tthrow new RuntimeException(\"Duplicate table name '\" + mappedSchemaTableName + \"'\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t tables.put(mappedSchemaTableName, table);\n\t }\n\t \n\t // columns\n\t File colFile = new File(getColumnsFile(executionContext));\n\t\t\tInputStream is = openModelFile(colFile, executionContext);\n\t if (is != null) {\n\t\t \tCsvFile columnsFile = new CsvFile(is, null, colFile.getPath(), null);\n\t\t List columnsList = new ArrayList(columnsFile.getLines());\n\t\t for (CsvFile.Line line: columnsList) {\n\t\t List columns = new ArrayList();\n\t\t for (int j = 1; j < line.cells.size() && line.cells.get(j).toString().length() > 0; ++j) {\n\t\t String col = line.cells.get(j).trim();\n\t\t try {\n\t\t \tcolumns.add(Column.parse(col));\n\t\t } catch (Exception e) {\n\t\t \t// ignore\n\t\t\t\t\t\t}\n\t\t }\n\t\t Table table = tables.get(SqlUtil.mappedSchema(sourceSchemaMapping, line.cells.get(0)));\n\t\t if (table != null) {\n\t\t \ttable.setColumns(columns);\n\t\t }\n\t\t }\n\t }\n\t \n\t // associations\n\t File assFile = new File(getAssociationsFile(executionContext));\n\t\t\tList associationList = new ArrayList(new CsvFile(openModelFile(assFile, executionContext), null, assFile.getPath(), assocFilter).getLines());\n\t if (additionalAssociationsFile != null) {\n\t associationList.addAll(new CsvFile(new File(additionalAssociationsFile)).getLines());\n\t }\n\t for (CsvFile.Line line: associationList) {\n\t String location = line.location;\n\t try {\n\t \tString associationLoadFailedMessage = \"Unable to load association from \" + line.cells.get(0) + \" to \" + line.cells.get(1) + \" on \" + line.cells.get(4) + \" because: \";\n\t Table tableA = (Table) tables.get(SqlUtil.mappedSchema(sourceSchemaMapping, line.cells.get(0)));\n\t if (tableA == null) {\n\t continue;\n//\t throw new RuntimeException(associationLoadFailedMessage + \"Table '\" + line.cells.get(0) + \"' not found\");\n\t }\n\t Table tableB = (Table) tables.get(SqlUtil.mappedSchema(sourceSchemaMapping, line.cells.get(1)));\n\t if (tableB == null) {\n\t \tcontinue;\n//\t \tthrow new RuntimeException(associationLoadFailedMessage + \"Table '\" + line.cells.get(1) + \"' not found\");\n\t }\n\t boolean insertSourceBeforeDestination = \"A\".equalsIgnoreCase(line.cells.get(2)); \n\t boolean insertDestinationBeforeSource = \"B\".equalsIgnoreCase(line.cells.get(2));\n\t Cardinality cardinality = Cardinality.parse(line.cells.get(3).trim());\n\t if (cardinality == null) {\n\t \tcardinality = Cardinality.MANY_TO_MANY;\n\t }\n\t String joinCondition = line.cells.get(4);\n\t String name = line.cells.get(5);\n\t if (\"\".equals(name)) {\n\t name = null;\n\t }\n\t if (name == null) {\n\t throw new RuntimeException(associationLoadFailedMessage + \"Association name missing (column 6 is empty, each association must have an unique name)\");\n\t }\n\t String author = line.cells.get(6);\n\t Association associationA = new Association(tableA, tableB, insertSourceBeforeDestination, insertDestinationBeforeSource, joinCondition, this, false, cardinality, author);\n\t Association associationB = new Association(tableB, tableA, insertDestinationBeforeSource, insertSourceBeforeDestination, joinCondition, this, true, cardinality.reverse(), author);\n\t associationA.reversalAssociation = associationB;\n\t associationB.reversalAssociation = associationA;\n\t tableA.associations.add(associationA);\n\t tableB.associations.add(associationB);\n\t if (name != null) {\n\t if (namedAssociations.put(name, associationA) != null) {\n\t throw new RuntimeException(\"duplicate association name: \" + name);\n\t }\n\t associationA.setName(name);\n\t name = \"inverse-\" + name;\n\t if (namedAssociations.put(name, associationB) != null) {\n\t throw new RuntimeException(\"duplicate association name: \" + name);\n\t }\n\t associationB.setName(name);\n\t }\n\t } catch (Exception e) {\n\t throw new RuntimeException(location + \": \" + e.getMessage(), e);\n\t }\n\t }\n\t initDisplayNames();\n\t initTableOrdinals();\n\t \n\t // model name\n\t File nameFile = new File(getModelNameFile(executionContext));\n\t name = DEFAULT_NAME;\n\t \tlastModified = null;\n\t try {\n\t \tlastModified = nameFile.lastModified();\n\t\t if (nameFile.exists()) {\n\t\t \tList nameList = new ArrayList(new CsvFile(nameFile).getLines());\n\t\t \tif (nameList.size() > 0) {\n\t\t \t\tCsvFile.Line line = nameList.get(0);\n\t\t \t\tname = line.cells.get(0);\n\t\t \t\tlastModified = Long.parseLong(line.cells.get(1));\n\t\t \t}\n\t\t }\n\t } catch (Throwable t) {\n\t \t// keep defaults\n\t }\n \t} catch (IOException e) {\n \t\t_log.error(\"failed to load data-model \" + getDatamodelFolder(executionContext) + File.separator, e);\n \t\tthrow e;\n \t}\n }\n\n private final List
tableList = new ArrayList
();\n\tprivate final List filterTemplates = new ArrayList();\n \n /**\n * Initializes table ordinals.\n */\n private void initTableOrdinals() {\n \tfor (Table table: getSortedTables()) {\n \t\ttable.ordinal = tableList.size();\n \t\ttableList.add(table);\n \t}\n\t}\n\n\t/**\n * Initializes display names.\n */\n private void initDisplayNames() throws IOException {\n \tSet unqualifiedNames = new HashSet();\n \tSet nonUniqueUnqualifiedNames = new HashSet();\n \t\n \tfor (Table table: getTables()) {\n \t\tString uName = table.getUnqualifiedName();\n \t\tif (unqualifiedNames.contains(uName)) {\n \t\t\tnonUniqueUnqualifiedNames.add(uName);\n \t\t} else {\n \t\t\tunqualifiedNames.add(uName);\n \t\t}\n \t}\n\n \tfor (Table table: getTables()) {\n \t\tString uName = table.getUnqualifiedName();\n \t\tif (uName != null && uName.length() > 0) {\n char fc = uName.charAt(0);\n if (!Character.isLetterOrDigit(fc) && fc != '_') {\n String fcStr = Character.toString(fc);\n if (uName.startsWith(fcStr) && uName.endsWith(fcStr)) {\n uName = uName.substring(1, uName.length() -1);\n }\n }\n \t\t}\n \t\tString schema = table.getSchema(null);\n \t\tString displayName;\n \t\tif (nonUniqueUnqualifiedNames.contains(uName) && schema != null) {\n \t\t\tdisplayName = uName + \" (\" + schema + \")\";\n \t\t} else {\n \t\t\tdisplayName = uName;\n \t\t}\n \t\tthis.displayName.put(table, displayName);\n \t\ttablesByDisplayName.put(displayName, table);\n \t}\n \t\n \tMap userDefinedDisplayNames = new TreeMap();\n File dnFile = new File(DataModel.getDisplayNamesFile(executionContext));\n if (dnFile.exists()) {\n \tfor (CsvFile.Line dnl: new CsvFile(dnFile).getLines()) {\n \t\tuserDefinedDisplayNames.put(dnl.cells.get(0), dnl.cells.get(1));\n \t}\n }\n \n \tfor (Map.Entry e: userDefinedDisplayNames.entrySet()) {\n \t\tTable table = getTable(e.getKey());\n \t\tif (table != null && !tablesByDisplayName.containsKey(e.getValue())) {\n \t\t\tString displayName = getDisplayName(table);\n \t\tthis.displayName.remove(table);\n \t\tif (displayName != null) {\n \t\t\ttablesByDisplayName.remove(displayName);\n \t\t}\n \t\tthis.displayName.put(table, e.getValue());\n \t\ttablesByDisplayName.put(e.getValue(), table);\n \t\t}\n \t}\n }\n \n /**\n * Gets the primary-key to be used for the entity-table.\n *\n * @param session for null value guessing\n * @return the universal primary key\n */\n PrimaryKey getUniversalPrimaryKey(Session session) {\n return primaryKeyFactory.getUniversalPrimaryKey(session);\n }\n\n /**\n * Gets the primary-key to be used for the entity-table.\n * \n * @return the universal primary key\n */\n PrimaryKey getUniversalPrimaryKey() {\n return getUniversalPrimaryKey(null);\n }\n\n /**\n * Gets the restriction model.\n * \n * @return the restriction model\n */\n public RestrictionModel getRestrictionModel() {\n return restrictionModel;\n }\n\n /**\n * Sets the restriction model.\n * \n * @param restrictionModel the restriction model\n */\n public void setRestrictionModel(RestrictionModel restrictionModel) {\n this.restrictionModel = restrictionModel;\n\t\t++version;\n }\n\n /**\n * Gets all independent tables\n * (i.e. tables which don't depend on other tables in the set)\n * of a given table-set.\n * \n * @param tableSet the table-set\n * @return the sub-set of independent tables of the table-set\n */\n public Set
getIndependentTables(Set
tableSet) {\n \treturn getIndependentTables(tableSet, null);\n }\n \n /**\n * Gets all independent tables\n * (i.e. tables which don't depend on other tables in the set)\n * of a given table-set.\n * \n * @param tableSet the table-set\n * @param associations the associations to consider, null for all associations\n * @return the sub-set of independent tables of the table-set\n */\n public Set
getIndependentTables(Set
tableSet, Set associations) {\n Set
independentTables = new HashSet
();\n \n for (Table table: tableSet) {\n boolean depends = false;\n for (Association a: table.associations) {\n \tif (associations == null || associations.contains(a)) {\n\t if (tableSet.contains(a.destination)) {\n\t if (a.getJoinCondition() != null) {\n\t if (a.isInsertDestinationBeforeSource()) {\n\t depends = true;\n\t break;\n\t }\n\t }\n\t }\n }\n }\n if (!depends) {\n independentTables.add(table);\n }\n }\n return independentTables;\n }\n\n /**\n * Transposes the data-model.\n */\n public void transpose() {\n if (getRestrictionModel() != null) {\n getRestrictionModel().transpose();\n }\n\t\t++version;\n }\n \n /**\n * Stringifies the data model.\n */\n public String toString() {\n List
sortedTables;\n sortedTables = getSortedTables();\n StringBuffer str = new StringBuffer();\n if (restrictionModel != null) {\n str.append(\"restricted by: \" + restrictionModel + \"\\n\");\n }\n for (Table table: sortedTables) {\n str.append(table);\n if (printClosures) {\n str.append(\" closure =\");\n str.append(new PrintUtil().tableSetAsString(table.closure(true)) + \"\\n\\n\");\n }\n }\n return str.toString();\n }\n\n /**\n * Gets list of tables sorted by name.\n * \n * @return list of tables sorted by name\n */\n\tpublic List
getSortedTables() {\n\t\tList
sortedTables;\n\t\tsortedTables = new ArrayList
(getTables());\n Collections.sort(sortedTables, new Comparator
() {\n public int compare(Table o1, Table o2) {\n return o1.getName().compareTo(o2.getName());\n }\n });\n\t\treturn sortedTables;\n\t}\n\n /**\n * Printing-mode.\n */\n public static boolean printClosures = false;\n\n /**\n * Normalizes a set of tables.\n * \n * @param tables set of tables\n * @return set of all tables from this model for which a table with same name exists in tables \n */\n public Set
normalize(Set
tables) {\n Set
result = new HashSet
();\n for (Table table: tables) {\n result.add(getTable(table.getName()));\n }\n return result;\n }\n\n /**\n * Assigns a unique ID to each association.\n */\n\tpublic void assignAssociationIDs() {\n\t\tint n = 1;\n\t\tfor (Map.Entry e: namedAssociations.entrySet()) {\n\t\t\te.getValue().id = n++;\n\t\t}\n\t}\n\n /**\n\t * Gets export modus, SQL or XML. (GUI support).\n\t */\n\tpublic String getExportModus() {\n\t\treturn exportModus;\n\t}\n\t\n /**\n\t * Sets export modus, SQL or XML. (GUI support).\n\t */\n\tpublic void setExportModus(String modus) {\n\t\texportModus = modus;\n\t\t++version;\n\t}\n\n\t/**\n\t * Gets XML settings for exportation into XML files.\n\t */\n\tpublic XmlSettings getXmlSettings() {\n\t\treturn xmlSettings;\n\t}\n\n\t/**\n\t * Sets XML settings for exportation into XML files.\n\t */\n\tpublic void setXmlSettings(XmlSettings xmlSettings) {\n\t\tthis.xmlSettings = xmlSettings;\n\t\t++version;\n\t}\n\n /**\n * Gets internal version number. Incremented on each modification.\n * \n * @return internal version number. Incremented on each modification.\n */\n public long getVersion() {\n \treturn version;\n }\n \n /**\n * Thrown if a table has no primary key.\n */\n public static class NoPrimaryKeyException extends RuntimeException {\n\t\tprivate static final long serialVersionUID = 4523935351640139649L;\n\t\tpublic final Table table;\n \tpublic NoPrimaryKeyException(Table table) {\n\t\t\tsuper(\"Table '\" + table.getName() + \"' has no primary key\");\n\t\t\tthis.table = table;\n\t\t}\n }\n\n /**\n * Checks whether all tables in the closure of a given subject have primary keys.\n * \n * @param subject the subject\n * @throws NoPrimaryKeyException if a table has no primary key\n */\n public void checkForPrimaryKey(Set
subjects, boolean forDeletion) throws NoPrimaryKeyException {\n \tSet
checked = new HashSet
();\n \tfor (Table subject: subjects) {\n\t \tSet
toCheck = new HashSet
(subject.closure(checked, true));\n\t \tif (forDeletion) {\n\t \t\tSet
border = new HashSet
();\n\t \t\tfor (Table table: toCheck) {\n\t \t\t\tfor (Association a: table.associations) {\n\t \t\t\t\tif (!a.reversalAssociation.isIgnored()) {\n\t \t\t\t\t\tborder.add(a.destination);\n\t \t\t\t\t}\n\t \t\t\t}\n\t \t\t}\n\t \t\ttoCheck.addAll(border);\n\t \t}\n\t \tfor (Table table: toCheck) {\n\t \t\tif (table.primaryKey.getColumns().isEmpty()) {\n\t \t\t\tthrow new NoPrimaryKeyException(table);\n\t \t\t}\n\t \t}\n\t \tchecked.addAll(toCheck);\n \t}\n }\n\n /**\n * Gets all parameters which occur in subject condition, association restrictions or XML templates.\n * \n * @param subjectCondition the subject condition\n * @return all parameters which occur in subject condition, association restrictions or XML templates\n */\n public SortedSet getParameters(String subjectCondition, List additionalSubjects) {\n \tSortedSet parameters = new TreeSet();\n \t\n \tParameterHandler.collectParameter(subjectCondition, parameters);\n \tif (additionalSubjects != null) {\n \t\tfor (AdditionalSubject as: additionalSubjects) {\n \t\t\tParameterHandler.collectParameter(as.getCondition(), parameters);\n \t\t}\n \t}\n \tfor (Association a: namedAssociations.values()) {\n \t\tString r = a.getRestrictionCondition();\n \t\tif (r != null) {\n \t\t\tParameterHandler.collectParameter(r, parameters);\n \t\t}\n \t}\n \tfor (Table t: getTables()) {\n \t\tString r = t.getXmlTemplate();\n \t\tif (r != null) {\n \t\t\tParameterHandler.collectParameter(r, parameters);\n \t\t}\n \t\tfor (Column c: t.getColumns()) {\n \t\t\tif (c.getFilterExpression() != null) {\n \t\t\t\tParameterHandler.collectParameter(c.getFilterExpression(), parameters);\n \t\t\t}\n \t\t}\n \t}\n \treturn parameters;\n }\n\n private static InputStream openModelFile(File file, ExecutionContext executionContext) {\n \ttry {\n\t\t\treturn executionContext.getDataModelURL().toURI().resolve(file.getName()).toURL().openStream();\n\t\t} catch (MalformedURLException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t} catch (IOException e) {\n\t\t\treturn null;\n\t\t} catch (URISyntaxException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n }\n \n /**\n * Gets {@link #getLastModified()} as String.\n * \n * @return {@link #getLastModified()} as String\n */\n\tpublic String getLastModifiedAsString() {\n\t\ttry {\n\t\t\treturn SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.MEDIUM, SimpleDateFormat.MEDIUM).format(new Date(getLastModified()));\n\t\t} catch (Throwable t) {\n\t\t\treturn \"\";\n\t\t}\n\t}\n\n\t/**\n\t * Saves the data model.\n\t * \n\t * @param file the file name\n\t * @param stable \n\t * @param stable the subject table\n\t * @param subjectCondition \n\t * @param scriptFormat\n\t * @param positions table positions or null\n\t * @param additionalSubjects \n\t */\n\tpublic void save(String file, Table stable, String subjectCondition, ScriptFormat scriptFormat, List restrictionDefinitions, Map> positions, List additionalSubjects, String currentModelSubfolder) throws FileNotFoundException {\n\t\tFile extractionModel = new File(file);\n\t\tPrintWriter out = new PrintWriter(extractionModel);\n\t\tout.println(\"# subject; condition\");\n\t\tout.println(CsvFile.encodeCell(\"\" + stable.getName()) + \"; \" + CsvFile.encodeCell(subjectCondition));\n\t\tsaveRestrictions(out, restrictionDefinitions);\n\t\tsaveXmlMapping(out);\n\t\tout.println();\n\t\tout.println(CsvFile.BLOCK_INDICATOR + \"datamodelfolder\");\n\t\tif (currentModelSubfolder != null) {\n\t\t\tout.println(currentModelSubfolder);\n\t\t}\n\t\tout.println();\n\t\tout.println(CsvFile.BLOCK_INDICATOR + \"additional subjects\");\n\t\tfor (AdditionalSubject as: additionalSubjects) {\n\t\t\tout.println(CsvFile.encodeCell(\"\" + as.getSubject().getName()) + \"; \" + CsvFile.encodeCell(as.getCondition()) + \";\");\n\t\t}\n\t\tout.println();\n\t\tout.println(CsvFile.BLOCK_INDICATOR + \"export modus\");\n\t\tout.println(scriptFormat);\n\t\tout.println();\n\t\tout.println(CsvFile.BLOCK_INDICATOR + \"xml settings\");\n\t\tout.println(CsvFile.encodeCell(getXmlSettings().datePattern) + \";\" + \n\t\t\t CsvFile.encodeCell(getXmlSettings().timestampPattern) + \";\" +\n\t\t\t CsvFile.encodeCell(getXmlSettings().rootTag));\n\t\tout.println(CsvFile.BLOCK_INDICATOR + \"xml column mapping\");\n\t\tfor (Table table: getTables()) {\n\t\t\tString xmlMapping = table.getXmlTemplate();\n\t\t\tif (xmlMapping != null) {\n\t\t\t\tout.println(CsvFile.encodeCell(table.getName()) + \"; \" + CsvFile.encodeCell(xmlMapping));\n\t\t\t}\n\t\t}\n\t\tout.println(CsvFile.BLOCK_INDICATOR + \"upserts\");\n\t\tfor (Table table: getTables()) {\n\t\t\tif (table.upsert != null) {\n\t\t\t\tout.println(CsvFile.encodeCell(table.getName()) + \"; \" + CsvFile.encodeCell(table.upsert.toString()));\n\t\t\t}\n\t\t}\n\t\tout.println(CsvFile.BLOCK_INDICATOR + \"exclude from deletion\");\n\t\tfor (Table table: getTables()) {\n\t\t\tif (table.excludeFromDeletion != null) {\n\t\t\t\tout.println(CsvFile.encodeCell(table.getName()) + \"; \" + CsvFile.encodeCell(table.excludeFromDeletion.toString()));\n\t\t\t}\n\t\t}\n\t\tsaveFilters(out);\n\t\tsaveFilterTemplates(out);\n\t\tout.println();\n\t\tif (positions == null) {\n\t\t\tLayoutStorage.store(out);\n\t\t} else {\n\t\t\tLayoutStorage.store(out, positions);\n\t\t}\n\t\t\n\t\tout.println();\n\t\tout.println(CsvFile.BLOCK_INDICATOR + \"known\");\n\t\tfor (Association a: namedAssociations.values()) {\n\t\t\tif (!a.reversed) {\n\t\t\t\tout.println(CsvFile.encodeCell(a.getName()));\n\t\t\t}\n\t\t}\n\t\t\n\t\tout.println();\n\t\tout.println(CsvFile.BLOCK_INDICATOR + \"version\");\n\t\tout.println(JailerVersion.VERSION);\n\t\tout.close();\n\t}\n\t\n\t/**\n\t * Saves xml mappings.\n\t * \n\t * @param out to save xml mappings into\n\t */\n\tprivate void saveXmlMapping(PrintWriter out) {\n\t\tout.println();\n\t\tout.println(CsvFile.BLOCK_INDICATOR + \"xml-mapping\");\n\t\tfor (Table table: getTables()) {\n\t\t\tfor (Association a: table.associations) {\n\t\t\t\tString name = a.getName();\n\t\t\t\tString tag = a.getAggregationTagName();\n\t\t\t\tString aggregation = a.getAggregationSchema().name();\n\t\t\t\tout.println(CsvFile.encodeCell(name) + \";\" + CsvFile.encodeCell(tag) + \";\" + CsvFile.encodeCell(aggregation));\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Saves restrictions only.\n\t * \n\t * @param out to save restrictions into\n\t * @param restrictionDefinitions \n\t */\n\tprivate void saveRestrictions(PrintWriter out, List restrictionDefinitions) {\n\t\tout.println();\n\t\tout.println(\"# association; ; restriction-condition\");\n\t\tfor (RestrictionDefinition rd: restrictionDefinitions) {\n\t\t\tString condition = rd.isIgnored? \"ignore\" : rd.condition;\n\t\t\tif (rd.name == null || rd.name.trim().length() == 0) {\n\t\t\t\tout.println(CsvFile.encodeCell(rd.from.getName()) + \"; \" + CsvFile.encodeCell(rd.to.getName()) + \"; \" + CsvFile.encodeCell(condition));\n\t\t\t} else {\n\t\t\t\tout.println(CsvFile.encodeCell(rd.name) + \"; ; \" + CsvFile.encodeCell(condition));\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Saves restrictions only.\n\t * \n\t * @param file to save restrictions into\n\t */\n\tpublic void saveRestrictions(File file, List restrictionDefinitions) throws FileNotFoundException {\n\t\tPrintWriter out = new PrintWriter(file);\n\t\tsaveRestrictions(out, restrictionDefinitions);\n\t\tout.close();\n\t}\n\n\t/**\n\t * Saves filters.\n\t * \n\t * @param out to save filters into\n\t */\n\tprivate void saveFilters(PrintWriter out) {\n\t\tout.println();\n\t\tout.println(CsvFile.BLOCK_INDICATOR + \"filters\");\n\t\tfor (Table table: getTables()) {\n\t\t\tfor (Column c: table.getColumns()) {\n\t\t\t\tif (c.getFilter() != null && !c.getFilter().isDerived()) {\n\t\t\t\t\tout.println(CsvFile.encodeCell(table.getName()) + \";\" + CsvFile.encodeCell(c.name) + \";\" + CsvFile.encodeCell(c.getFilter().getExpression())\n\t\t\t\t\t+ \";\" + CsvFile.encodeCell(c.getFilter().isApplyAtExport()? \"Export\" : \"Import\")\n\t\t\t\t\t+ \";\" + CsvFile.encodeCell(c.getFilter().getType() == null? \"\" : c.getFilter().getType()));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\n\t/**\n\t * Saves filter templates.\n\t * \n\t * @param out to save filters into\n\t */\n\tprivate void saveFilterTemplates(PrintWriter out) {\n\t\tout.println();\n\t\tout.println(CsvFile.BLOCK_INDICATOR + \"filter templates\");\n\t\tfor (FilterTemplate template: getFilterTemplates()) {\n\t\t\tout.println(\"T;\"\n\t\t\t\t\t+ CsvFile.encodeCell(template.getName()) + \";\"\n\t\t\t\t\t+ CsvFile.encodeCell(template.getExpression()) + \";\"\n\t\t\t\t\t+ CsvFile.encodeCell(template.isEnabled()? \"enabled\" : \"disabled\") + \";\"\n\t\t\t\t\t+ CsvFile.encodeCell(template.isApplyAtExport()? \"Export\" : \"Import\") + \";\"\n\t\t\t\t\t+ CsvFile.encodeCell(template.getType() == null? \"\" : template.getType()) + \";\");\n\t\t\tfor (Clause clause: template.getClauses()) {\n\t\t\t\tout.println(\"C;\"\n\t\t\t\t\t\t+ CsvFile.encodeCell(clause.getSubject().name()) + \";\"\n\t\t\t\t\t\t+ CsvFile.encodeCell(clause.getPredicate().name()) + \";\"\n\t\t\t\t\t\t+ CsvFile.encodeCell(clause.getObject()) + \";\");\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Gets table by {@link Table#getOrdinal()}.\n\t * \n\t * @param ordinal the ordinal\n\t * @return the table\n\t */\n\tpublic Table getTableByOrdinal(int ordinal) {\n\t\treturn tableList.get(ordinal);\n\t}\n\n\t/**\n\t * Gets the {@link FilterTemplate}s ordered by priority.\n\t * \n\t * @return template list\n\t */\n\tpublic List getFilterTemplates() {\n\t\treturn filterTemplates;\n\t}\n\n\tprivate Map> sToDMaps = new HashMap>();\n\t\n /**\n * Removes all derived filters and renews them.\n */\n public void deriveFilters() {\n \tsToDMaps.clear();\n\t\tfor (Table table: getTables()) {\n\t\t\tfor (Column column: table.getColumns()) {\n\t\t\t\tFilter filter = column.getFilter();\n\t\t\t\tif (filter != null && filter.isDerived()) {\n\t\t\t\t\tcolumn.setFilter(null);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tSet pkNames = new HashSet();\n\t\tfor (Table table: getTables()) {\n\t\t\tpkNames.clear();\n\t\t\tfor (Column column: table.primaryKey.getColumns()) {\n\t\t\t\tpkNames.add(column.name);\n\t\t\t}\n\t\t\tfor (Column column: table.getColumns()) {\n\t\t\t\tif (pkNames.contains(column.name)) {\n\t\t\t\t\tFilter filter = column.getFilter();\n\t\t\t\t\tif (filter != null && !filter.isDerived()) {\n\t\t\t\t\t\tList aTo = new ArrayList();\n\t\t\t\t\t\tderiveFilter(table, column, filter, new PKColumnFilterSource(table, column), aTo, null);\n\t\t\t\t\t\tif (!aTo.isEmpty()) {\n\t\t\t\t\t\t\tCollections.sort(aTo);\n\t\t\t\t\t\t\tfilter.setAppliedTo(aTo);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t// apply templates\n\t\tfor (FilterTemplate template: getFilterTemplates()) {\n\t\t\tif (template.isEnabled()) {\n\t\t\t\tfor (Table table: getTables()) {\n\t\t\t\t\tfor (Column column: table.getColumns()) {\n\t\t\t\t\t\tif (column.getFilter() == null && template.matches(table, column)) {\n\t\t\t\t\t\t\tFilter filter = new Filter(template.getExpression(), template.getType(), true, template);\n\t\t\t\t\t\t\tfilter.setApplyAtExport(template.isApplyAtExport());\n\t\t\t\t\t\t\tcolumn.setFilter(filter);\n\t\t\t\t\t\t\tList aTo = new ArrayList();\n\t\t\t\t\t\t\tderiveFilter(table, column, filter, new PKColumnFilterSource(table, column), aTo, template);\n\t\t\t\t\t\t\tif (!aTo.isEmpty()) {\n\t\t\t\t\t\t\t\tCollections.sort(aTo);\n\t\t\t\t\t\t\t\tfilter.setAppliedTo(aTo);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tsToDMaps.clear();\n\t}\n\n\tprivate void deriveFilter(Table table, Column column, Filter filter, FilterSource filterSource, List aTo, FilterSource overwriteForSource) {\n\t\tfor (Association association: table.associations) {\n\t\t\tif (association.isInsertSourceBeforeDestination()) {\n\t\t\t\tMap sToDMap = sToDMaps.get(association);\n\t\t\t\tif (sToDMap == null) {\n\t\t\t\t\tsToDMap = association.createSourceToDestinationKeyMapping();\n\t\t\t\t\tsToDMaps.put(association, sToDMap);\n\t\t\t\t}\n\t\t\t\tColumn destColumn = sToDMap.get(column);\n\t\t\t\tif (destColumn != null && (destColumn.getFilter() == null || overwriteForSource != null && destColumn.getFilter().getFilterSource() == overwriteForSource)) {\n\t\t\t\t\tFilter newFilter = new Filter(filter.getExpression(), filter.getType(), true, filterSource);\n\t\t\t\t\tnewFilter.setApplyAtExport(filter.isApplyAtExport());\n\t\t\t\t\tdestColumn.setFilter(newFilter);\n\t\t\t\t\taTo.add(association.destination.getName() + \".\" + destColumn.name);\n\t\t\t\t\tderiveFilter(association.destination, destColumn, filter, filterSource, aTo, overwriteForSource);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n}\n"},"message":{"kind":"string","value":"api documentation\n\ngit-svn-id: 623b1913a4f912b976453f456c127dcd8e933919@1251 3dd849cd-670e-4645-a7cd-dd197c8d0e81\n"},"old_file":{"kind":"string","value":"src/main/engine/net/sf/jailer/datamodel/DataModel.java"},"subject":{"kind":"string","value":"api documentation"},"git_diff":{"kind":"string","value":"rc/main/engine/net/sf/jailer/datamodel/DataModel.java\n import java.io.InputStream;\n import java.io.PrintWriter;\n import java.net.MalformedURLException;\nimport java.net.URI;\n import java.net.URISyntaxException;\nimport java.net.URL;\n import java.text.SimpleDateFormat;\n import java.util.ArrayList;\n import java.util.Collection;\n \n private static InputStream openModelFile(File file, ExecutionContext executionContext) {\n \ttry {\n\t\t\treturn executionContext.getDataModelURL().toURI().resolve(file.getName()).toURL().openStream();\n\t\t\tURL dataModelURL = executionContext.getDataModelURL();\n\t\t\tURI uri = dataModelURL.toURI();\n\t\t\tURI resolved = new URI(uri.toString() + file.getName()); // uri.resolve(file.getName());\n\t\t\treturn resolved.toURL().openStream();\n \t\t} catch (MalformedURLException e) {\n \t\t\tthrow new RuntimeException(e);\n \t\t} catch (IOException e) {"}}},{"rowIdx":1956,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"f1781edab0e12ceaf75c8ad22803e6fab44e3036"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"jacopofar/fleximatcher-web-interface,jacopofar/fleximatcher-rest-interface,jacopofar/fleximatcher-web-interface,jacopofar/fleximatcher-rest-interface,jacopofar/fleximatcher-rest-interface,jacopofar/fleximatcher-web-interface,jacopofar/fleximatcher-rest-interface"},"new_contents":{"kind":"string","value":"package com.github.jacopofar.fleximatcherwebinterface;\n\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.github.jacopofar.fleximatcher.FlexiMatcher;\nimport com.github.jacopofar.fleximatcher.annotations.MatchingResults;\nimport com.github.jacopofar.fleximatcher.annotations.TextAnnotation;\nimport com.github.jacopofar.fleximatcher.importer.FileTagLoader;\nimport com.github.jacopofar.fleximatcherwebinterface.messages.ParseRequestPayload;\nimport com.github.jacopofar.fleximatcherwebinterface.messages.TagRulePayload;\nimport org.json.JSONException;\nimport org.json.JSONObject;\nimport spark.Response;\n\nimport javax.servlet.ServletOutputStream;\nimport java.io.IOException;\nimport java.util.LinkedList;\n\nimport static spark.Spark.*;\n\n/**\n * A simple example just showing some basic functionality\n */\npublic class Fwi {\n private static FlexiMatcher fm;\n private static int tagCount=0;\n\n public static void main(String[] args) throws IOException {\n\n System.out.println(\"starting matcher...\");\n fm = new FlexiMatcher();\n System.setProperty(\"org.slf4j.simpleLogger.defaultLogLevel\", \"info\");\n /*\n fm.bind(\"it-pos\", new ItPosRuleFactory(im));\n fm.bind(\"it-token\", new ItTokenRuleFactory(im));\n fm.bind(\"it-verb-conjugated\", new ItSpecificVerbRuleFactory(im));\n fm.bind(\"it-verb-form\", new ItVerbFormRuleFactory(im));\n */\n String fname=\"rule_list.tsv\";\n FileTagLoader.readTagsFromTSV(fname, fm);\n\n\n\n staticFiles.externalLocation(\"static\");\n\n //staticFiles.externalLocation(\"/static\");\n // port(5678); <- Uncomment this if you want spark to listen to port 5678 in stead of the default 4567\n\n get(\"/parse\", (request, response) -> {\n\n String text = request.queryMap().get(\"text\").value();\n String pattern = request.queryMap().get(\"pattern\").value();\n System.out.println(text+\" -- \"+pattern);\n\n MatchingResults results;\n JSONObject retVal = new JSONObject();\n long start=System.currentTimeMillis();\n results = fm.matches(text, pattern, FlexiMatcher.getDefaultAnnotator(), true, false, true);\n retVal.put(\"time_to_parse\", System.currentTimeMillis()-start);\n retVal.put(\"is_matching\", results.isMatching());\n retVal.put(\"empty_match\", results.isEmptyMatch());\n for(LinkedList interpretation:results.getAnnotations().get()){\n JSONObject addMe = new JSONObject();\n\n for(TextAnnotation v:interpretation){\n addMe.append(\"annotations\", new JSONObject(v.toJSON()));\n }\n retVal.append(\"interpretations\", addMe);\n }\n return sendJSON(response, retVal);\n\n });\n\n\n put(\"/tagrule\", (request, response) -> {\n ObjectMapper mapper = new ObjectMapper();\n TagRulePayload newPost = mapper.readValue(request.body(), TagRulePayload.class);\n if(newPost.errorMessages().size() != 0){\n response.status(400);\n return \"invalid request body. Errors: \" + newPost.errorMessages() ;\n }\n System.out.println(\"RULE TO BE CREATED: \" + newPost.toString());\n fm.addTagRule(newPost.getTag(),newPost.getPattern(), newPost.getIdentifier(),newPost.getAnnotationTemplate());\n return \"rule created: \" + newPost.toString();\n });\n\n post(\"/parse\", (request, response) -> {\n ObjectMapper mapper = new ObjectMapper();\n ParseRequestPayload newPost = mapper.readValue(request.body(), ParseRequestPayload.class);\n if(newPost.errorMessages().size() != 0){\n response.status(400);\n return \"invalid request body. Errors: \" + newPost.errorMessages() ;\n }\n\n\n MatchingResults results;\n JSONObject retVal = new JSONObject();\n long start=System.currentTimeMillis();\n //TODO allow the request to specify parsing flags\n results = fm.matches(newPost.getText(),newPost.getPattern(),FlexiMatcher.getDefaultAnnotator(), true, false, true);\n\n retVal.put(\"time_to_parse\", System.currentTimeMillis()-start);\n retVal.put(\"is_matching\", results.isMatching());\n retVal.put(\"empty_match\", results.isEmptyMatch());\n if(results.isMatching()){\n for(LinkedList interpretation:results.getAnnotations().get()){\n JSONObject addMe = new JSONObject();\n\n for(TextAnnotation v:interpretation){\n addMe.append(\"annotations\", new JSONObject(v.toJSON()));\n }\n retVal.append(\"interpretations\", addMe);\n }\n }\n return sendJSON(response, retVal);\n });\n\n exception(Exception.class, (exception, request, response) -> {\n //show the exceptions using stdout\n System.out.println(\"Exception:\");\n exception.printStackTrace(System.out);\n\n response.body(exception.getMessage());\n });\n\n /**\n * Delete a specific tag rule\n * */\n delete(\"/tagrule/:tagname/:tag_identifier\", (request, response) -> {\n if(fm.removeTagRule(request.params(\":tagname\"), request.params(\":tag_identifier\"))){\n response.status(200);\n return \"rule removed\";\n }\n else {\n response.status(404);\n return \"rule not found\";\n }\n });\n\n /**\n * List the known tags\n * */\n get(\"/tags\", (request, response) -> {\n response.type(\"application/json\");\n ServletOutputStream os = response.raw().getOutputStream();\n os.write(\"[\".getBytes());\n final boolean[] first = {true};\n fm.getTagNames().forEach( tn -> {\n try {\n if(!first[0]) os.write(\",\".getBytes());\n first[0] = false;\n os.write(JSONObject.quote(tn).getBytes());\n } catch (IOException e) {\n e.printStackTrace();\n }\n });\n os.write(\"]\".getBytes());\n\n os.flush();\n os.close();\n return response.raw();\n\n });\n\n /**\n * Define the known rules for a tag\n * */\n get(\"/tag/:tagname\", (request, response) -> {\n response.type(\"application/json\");\n ServletOutputStream os = response.raw().getOutputStream();\n os.write(\"[\".getBytes());\n final boolean[] first = {true};\n fm.getTagDefinitions(request.params(\":tagname\")).forEach( td -> {\n try {\n if(!first[0]) os.write(\",\".getBytes());\n first[0] = false;\n JSONObject jo = new JSONObject();\n jo.put(\"id\", td.getIdentifier());\n jo.put(\"pattern\", td.getPattern());\n os.write(jo.toString().getBytes());\n } catch (IOException e) {\n e.printStackTrace();\n } catch (JSONException e) {\n //can never happen, key is hardcoded and not null\n e.printStackTrace();\n }\n });\n os.write(\"]\".getBytes());\n\n os.flush();\n os.close();\n return response.raw();\n\n });\n\n\n }\n\n private static String sendJSON(Response r, JSONObject obj) {\n r.type(\"application/json\");\n return obj.toString();\n }\n}"},"new_file":{"kind":"string","value":"src/main/java/com/github/jacopofar/fleximatcherwebinterface/Fwi.java"},"old_contents":{"kind":"string","value":"package com.github.jacopofar.fleximatcherwebinterface;\n\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.github.jacopofar.fleximatcher.FlexiMatcher;\nimport com.github.jacopofar.fleximatcher.annotations.MatchingResults;\nimport com.github.jacopofar.fleximatcher.annotations.TextAnnotation;\nimport com.github.jacopofar.fleximatcher.importer.FileTagLoader;\nimport com.github.jacopofar.fleximatcherwebinterface.messages.ParseRequestPayload;\nimport com.github.jacopofar.fleximatcherwebinterface.messages.TagRulePayload;\nimport org.json.JSONObject;\nimport spark.Response;\n\nimport javax.servlet.ServletOutputStream;\nimport java.io.IOException;\nimport java.util.LinkedList;\n\nimport static spark.Spark.*;\n\n/**\n * A simple example just showing some basic functionality\n */\npublic class Fwi {\n private static FlexiMatcher fm;\n private static int tagCount=0;\n\n public static void main(String[] args) throws IOException {\n\n System.out.println(\"starting matcher...\");\n fm = new FlexiMatcher();\n System.setProperty(\"org.slf4j.simpleLogger.defaultLogLevel\", \"info\");\n /*\n fm.bind(\"it-pos\", new ItPosRuleFactory(im));\n fm.bind(\"it-token\", new ItTokenRuleFactory(im));\n fm.bind(\"it-verb-conjugated\", new ItSpecificVerbRuleFactory(im));\n fm.bind(\"it-verb-form\", new ItVerbFormRuleFactory(im));\n */\n String fname=\"rule_list.tsv\";\n FileTagLoader.readTagsFromTSV(fname, fm);\n\n\n\n staticFiles.externalLocation(\"static\");\n\n //staticFiles.externalLocation(\"/static\");\n // port(5678); <- Uncomment this if you want spark to listen to port 5678 in stead of the default 4567\n\n get(\"/parse\", (request, response) -> {\n\n String text = request.queryMap().get(\"text\").value();\n String pattern = request.queryMap().get(\"pattern\").value();\n System.out.println(text+\" -- \"+pattern);\n\n MatchingResults results;\n JSONObject retVal = new JSONObject();\n long start=System.currentTimeMillis();\n results = fm.matches(text, pattern, FlexiMatcher.getDefaultAnnotator(), true, false, true);\n retVal.put(\"time_to_parse\", System.currentTimeMillis()-start);\n retVal.put(\"is_matching\", results.isMatching());\n retVal.put(\"empty_match\", results.isEmptyMatch());\n for(LinkedList interpretation:results.getAnnotations().get()){\n JSONObject addMe = new JSONObject();\n\n for(TextAnnotation v:interpretation){\n addMe.append(\"annotations\", new JSONObject(v.toJSON()));\n }\n retVal.append(\"interpretations\", addMe);\n }\n return sendJSON(response, retVal);\n\n });\n\n\n put(\"/tagrule\", (request, response) -> {\n ObjectMapper mapper = new ObjectMapper();\n TagRulePayload newPost = mapper.readValue(request.body(), TagRulePayload.class);\n if(newPost.errorMessages().size() != 0){\n response.status(400);\n return \"invalid request body. Errors: \" + newPost.errorMessages() ;\n }\n System.out.println(\"RULE TO BE CREATED: \" + newPost.toString());\n fm.addTagRule(newPost.getTag(),newPost.getPattern(), newPost.getIdentifier(),newPost.getAnnotationTemplate());\n return \"rule created: \" + newPost.toString();\n });\n\n post(\"/parse\", (request, response) -> {\n ObjectMapper mapper = new ObjectMapper();\n ParseRequestPayload newPost = mapper.readValue(request.body(), ParseRequestPayload.class);\n if(newPost.errorMessages().size() != 0){\n response.status(400);\n return \"invalid request body. Errors: \" + newPost.errorMessages() ;\n }\n\n\n MatchingResults results;\n JSONObject retVal = new JSONObject();\n long start=System.currentTimeMillis();\n //TODO allow the request to specify parsing flags\n results = fm.matches(newPost.getText(),newPost.getPattern(),FlexiMatcher.getDefaultAnnotator(), true, false, true);\n\n retVal.put(\"time_to_parse\", System.currentTimeMillis()-start);\n retVal.put(\"is_matching\", results.isMatching());\n retVal.put(\"empty_match\", results.isEmptyMatch());\n if(results.isMatching()){\n for(LinkedList interpretation:results.getAnnotations().get()){\n JSONObject addMe = new JSONObject();\n\n for(TextAnnotation v:interpretation){\n addMe.append(\"annotations\", new JSONObject(v.toJSON()));\n }\n retVal.append(\"interpretations\", addMe);\n }\n }\n return sendJSON(response, retVal);\n });\n\n exception(Exception.class, (exception, request, response) -> {\n //show the exceptions using stdout\n System.out.println(\"Exception:\");\n exception.printStackTrace(System.out);\n\n response.body(exception.getMessage());\n });\n\n /**\n * Delete a specific tag rule\n * */\n delete(\"/tagrule/:tagname/:tag_identifier\", (request, response) -> {\n if(fm.removeTagRule(request.params(\":tagname\"), request.params(\":tag_identifier\"))){\n response.status(200);\n return \"rule removed\";\n }\n else {\n response.status(404);\n return \"rule not found\";\n }\n });\n\n /**\n * List the known tags\n * */\n get(\"/tags\", (request, response) -> {\n response.type(\"application/json\");\n ServletOutputStream os = response.raw().getOutputStream();\n os.write(\"[\".getBytes());\n final boolean[] first = {true};\n fm.getTagNames().forEach( tn -> {\n try {\n if(!first[0]) os.write(\",\".getBytes());\n first[0] = false;\n os.write(JSONObject.quote(tn).getBytes());\n } catch (IOException e) {\n e.printStackTrace();\n }\n });\n os.write(\"]\".getBytes());\n\n os.flush();\n os.close();\n return response.raw();\n\n });\n\n }\n\n private static String sendJSON(Response r, JSONObject obj) {\n r.type(\"application/json\");\n return obj.toString();\n }\n}"},"message":{"kind":"string","value":"add tag definitions endpoint\n"},"old_file":{"kind":"string","value":"src/main/java/com/github/jacopofar/fleximatcherwebinterface/Fwi.java"},"subject":{"kind":"string","value":"add tag definitions endpoint"},"git_diff":{"kind":"string","value":"rc/main/java/com/github/jacopofar/fleximatcherwebinterface/Fwi.java\n import com.github.jacopofar.fleximatcher.importer.FileTagLoader;\n import com.github.jacopofar.fleximatcherwebinterface.messages.ParseRequestPayload;\n import com.github.jacopofar.fleximatcherwebinterface.messages.TagRulePayload;\nimport org.json.JSONException;\n import org.json.JSONObject;\n import spark.Response;\n \n \n });\n \n /**\n * Define the known rules for a tag\n * */\n get(\"/tag/:tagname\", (request, response) -> {\n response.type(\"application/json\");\n ServletOutputStream os = response.raw().getOutputStream();\n os.write(\"[\".getBytes());\n final boolean[] first = {true};\n fm.getTagDefinitions(request.params(\":tagname\")).forEach( td -> {\n try {\n if(!first[0]) os.write(\",\".getBytes());\n first[0] = false;\n JSONObject jo = new JSONObject();\n jo.put(\"id\", td.getIdentifier());\n jo.put(\"pattern\", td.getPattern());\n os.write(jo.toString().getBytes());\n } catch (IOException e) {\n e.printStackTrace();\n } catch (JSONException e) {\n //can never happen, key is hardcoded and not null\n e.printStackTrace();\n }\n });\n os.write(\"]\".getBytes());\n\n os.flush();\n os.close();\n return response.raw();\n\n });\n\n\n }\n \n private static String sendJSON(Response r, JSONObject obj) {"}}},{"rowIdx":1957,"cells":{"lang":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"d91188e4adafedc478cb0af78c754d306dec6840"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"hirokiosame/search.js,hirokiosame/search.js"},"new_contents":{"kind":"string","value":"/** @license Search.js 0.0.1\n * (c) 2013 Hiroki Osame\n * Search.js may be freely distributed under the MIT license.\n */\n\n;var VisualSearch = (function($, _){\n\n\t//Autocomplete - Category Add-On\n\t$.widget(\"ui.autocomplete\", $.ui.autocomplete, {\n\t\t_renderMenu: function( ul, items ) {\n\t\t\tvar that = this,\n\t\t\tcurrentCategory = \"\";\n\t\t\t$.each( items, function( index, item ) {\n\t\t\t\tif( item.category && item.category != currentCategory ) {\n\t\t\t\t\tul.append( \"
  • \" + item.category + \"
  • \" );\n\t\t\t\t\tcurrentCategory = item.category;\n\t\t\t\t}\n\n\t\t\t\t//To differentiate categories\n\t\t\t\tvar dom = that._renderItemData(ul, item);\n\t\t\t\tif(item.category && item.category == currentCategory){\n\t\t\t\t\tdom.children().addClass(\"category-child\");\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t});\n\n\t//jQuery - Get Caret Position\n\t$.fn.getCursorPosition = function() {\n\t\tvar position = 0;\n\t\tvar input = this.get(0);\n\n\t\tif (document.selection) { // IE\n\t\t\tinput.focus();\n\t\t\tvar sel\t\t= document.selection.createRange();\n\t\t\tvar selLen\t= document.selection.createRange().text.length;\n\t\t\tsel.moveStart('character', -input.value.length);\n\t\t\tposition\t= sel.text.length - selLen;\n\t\t} else if (input && $(input).is(':visible') && input.selectionStart != null) { // Firefox/Safari\n\t\t\tposition = input.selectionStart;\n\t\t}\n\n\t\treturn position;\n\t}\n\n\t//Underscore - Transpose Objects\n\t_.transpose = function(array) {\n\t\tvar keys = _.union.apply(_, _.map(array, _.keys)),\n\t\tresult = {};\n\t\tfor (var i=0, l=keys.length; i\").css({\n\t\t\t\t\t\t\t\tposition: 'absolute',\n\t\t\t\t\t\t\t\ttop: -9999,\n\t\t\t\t\t\t\t\tleft: -9999,\n\t\t\t\t\t\t\t\twidth: 'auto',\n\t\t\t\t\t\t\t\tfontSize: input.css('fontSize'),\n\t\t\t\t\t\t\t\tfontFamily: input.css('fontFamily'),\n\t\t\t\t\t\t\t\tfontWeight: input.css('fontWeight'),\n\t\t\t\t\t\t\t\tletterSpacing: input.css('letterSpacing'),\n\t\t\t\t\t\t\t\t\"text-transform\": input.css('text-transform'),\n\t\t\t\t\t\t\t\twhiteSpace: 'nowrap'\n\t\t\t\t\t\t\t}).text($(this).val()).insertAfter(this),\n\t\t\t\t\tnewWidth = shadow.width()+20;\n\n\t\t\t\tif( input.width() < newWidth && newWidth < containerwidth){\n\t\t\t\t\tinput.css(\"width\", newWidth);\n\t\t\t\t}\n\t\t\t\tshadow.remove();\n\t\t\t});\n\t\t},\n\n\t\trender : function(){\n\t\t\tvar self\t\t\t= this,\n\t\t\t\ttemplate\t\t= $(VS.template['search_box'](this.options)),\n\t\t\t\tplaceholder\t\t= $('.VS-placeholder', template);\n\t\t\t\tthis.parameterViews = [];\n\n\t\t\tif (this.searchQuery.length) {\n\t\t\t\tplaceholder.hide();\n\n\t\t\t\t$('.VS-search-inner', template).append(this.searchQuery.map(function(parameter){\n\t\t\t\t\tvar parameterView = new VS.ParameterView({\n\t\t\t\t\t\tmodel : parameter\n\t\t\t\t\t}).render().el;\n\n\t\t\t\t\tself.parameterViews.push(parameterView);\n\t\t\t\t\treturn parameterView;\n\t\t\t\t}));\n\n\t\t\t} else {\n\t\t\t\tplaceholder.show();\n\t\t\t}\n\n\t\t\tthis.$el.html(template);\n\n\t\t\treturn this;\n\t\t},\n\n\t\tclickBox: function(e, index){\n\t\t\tif(\t!$(e.target).is('.VS-search-box, .VS-search-inner, .VS-placeholder') ) return;\n\n\t\t\tvar self = this;\n\n\t\t\tfor( var i in this.parameterViews ){\n\t\t\t\tvar parameterView = $(this.parameterViews[i]);\n\n\t\t\t\t//If the row the cursor is on is done iterating, stop loop.\n\t\t\t\tif( parameterView.offset().top > e.pageY ) break;\n\n\t\t\t\t//If row is above the row clicked on, continue\n\t\t\t\tif( parameterView.offset().top+parameterView.height() < e.pageY ) continue;\n\n\t\t\t\tif( e.pageX < parameterView.offset().left ){\n\t\t\t\t\treturn _.delay(function(){ self.newParam({}, i); });\n\t\t\t\t}\n\t\t\t}\n\t\t\ti = ( i == this.parameterViews.length-1 ) ? this.parameterViews.length : i;\n\n\t\t\t_.delay(function(){ self.newParam({}, i); });\n\t\t},\n\t\tnewParam: function(parameter, index){\n\t\t\tvar paremeter = new VS.Parameter(parameter);\n\t\t\tthis.searchQuery.add(paremeter, {at: index || null});\n\t\t},\n\t\tunselect: function(e){\n\t\t\tthis.searchQuery.invoke('set', {'selected': false});\n\t\t},\n\t\tclearSearch : function(e){\n\t\t\tthis.searchQuery.reset();\n\t\t},\n\t\thighlightSearch: function(e){\n\t\t\tif(!$(e.target).is(\"input, .search_parameter\")) return;\n\t\t\tthis.searchQuery.invoke('set', {'selected': true});\n\t\t},\n\t\tinputkeydown: function(e){\n\t\t\tvar self = this,\n\t\t\t\teditNext = function(){\n\t\t\t\t\tvar selected = self.searchQuery.getEditing()[0],\n\t\t\t\t\t\tediting = selected.get('editing');\n\n\t\t\t\t\tif( editing===2 ){\n\t\t\t\t\t\tvar index = self.searchQuery.indexOf(selected);\n\t\t\t\t\t\tselected.set(\"editing\", false);\n\t\t\t\t\t\tself.newParam({}, index+1);\n\t\t\t\t\t}else\n\t\t\t\t\tif(editing===false){\n\t\t\t\t\t\tvar index = self.searchQuery.indexOf(selected);\n\t\t\t\t\t\tselected.destroy();\n\t\t\t\t\t\tvar select = self.searchQuery.at(index);\n\t\t\t\t\t\tif(select){\n\t\t\t\t\t\t\tselect.set(\"editing\", 0);\n\t\t\t\t\t\t}\n\t\t\t\t\t}else\n\t\t\t\t\t{\n\t\t\t\t\t\tselected.set(\"editing\", editing+1);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\teditPrevious = function(){\n\t\t\t\t\tvar selected = self.searchQuery.getEditing()[0],\n\t\t\t\t\t\tediting = selected.get('editing');\n\n\t\t\t\t\t//If editing, make a new parameter before\n\t\t\t\t\tif( editing===0 ){\n\t\t\t\t\t\tvar index = self.searchQuery.indexOf(selected);\n\t\t\t\t\t\tselected.set(\"editing\", false);\n\t\t\t\t\t\tself.newParam({}, index);\n\t\t\t\t\t}else\n\n\t\t\t\t\t//If New Parameter\n\t\t\t\t\tif( editing===false ){\n\t\t\t\t\t\tvar index = self.searchQuery.indexOf(selected);\n\t\t\t\t\t\tselected.destroy();\n\t\t\t\t\t\tif( self.searchQuery.at(index-1) ){\tself.searchQuery.at(index-1).set(\"editing\", 2);\t}\n\t\t\t\t\t}else\n\t\t\t\t\t{\n\t\t\t\t\t\tselected.set(\"editing\", editing-1);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tkeys = {\n\t\t\t\t\t//Left\n\t\t\t\t\t37: function(){\n\t\t\t\t\t\tif( $(e.target).getCursorPosition()==0 ){ editPrevious(); }\n\t\t\t\t\t},\n\n\t\t\t\t\t//Right\n\t\t\t\t\t39: function(){\n\t\t\t\t\t\tvar input = $(e.target);\n\t\t\t\t\t\tif( input.getCursorPosition()==input.val().length ){ editNext(); }\n\t\t\t\t\t},\n\n\t\t\t\t\t//Delete\n\t\t\t\t\t8: function(){\n\t\t\t\t\t\tvar input = $(e.target);\n\t\t\t\t\t\tif( input.getCursorPosition()===0 &&\n\t\t\t\t\t\t\tinput.get(0).selectionStart === input.get(0).selectionEnd //Only Webkit, no IE\n\t\t\t\t\t\t){ editPrevious(); return false; }\n\t\t\t\t\t},\n\n\t\t\t\t\t//Tab\n\t\t\t\t\t9: function(){\n\t\t\t\t\t\tif( e.shiftKey ){\n\t\t\t\t\t\t\te.preventDefault();\n\t\t\t\t\t\t\teditPrevious();\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\te.preventDefault();\n\t\t\t\t\t\t\teditNext();\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\n\t\t\t\t\t//Enter\n\t\t\t\t\t13: function(){\n\t\t\t\t\t\t$(e.target).blur();\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\treturn (keys[e.keyCode]) ? keys[e.keyCode]() : null;\n\t\t},\n\t\tkeydown: function(e){\n\t\t\t//Check if Parameters are selected\n\t\t\tif( !e || $(\".VS-search .selected\").length===0 ){ return; }\n\t\t\tif( [8, 37, 38, 39, 40].indexOf(e.keyCode)!=-1 ){ return false; }\n\t\t},\n\t\tbindKeys: function(e){\n\t\t\t//Check if Parameters are selected\n\t\t\tif( !e || $(\".VS-search .selected\").length===0 ){ return; }\n\n\t\t\tvar self = this,\n\t\t\t\tkeys = {\n\t\t\t\t\t//Delete\n\t\t\t\t\t8: function(){\n\t\t\t\t\t\tvar selected = self.searchQuery.where({'selected': true});\n\t\t\t\t\t\tselected.forEach(function(e){\n\t\t\t\t\t\t\te.destroy();\n\t\t\t\t\t\t});\n\t\t\t\t\t},\n\n\t\t\t\t\t//Enter - Start Editing\n\t\t\t\t\t13: function(){\n\t\t\t\t\t\tvar selected = self.searchQuery.where({'selected': true});\n\t\t\t\t\t\tselected[0].set(\"editing\", 0);\n\t\t\t\t\t},\n\n\t\t\t\t\t//Right 39\n\t\t\t\t\t39: function(){\n\t\t\t\t\t\tvar selected = self.searchQuery.where({'selected': true}),\n\t\t\t\t\t\t\tindex = self.searchQuery.indexOf(_.last(selected)),\n\t\t\t\t\t\t\tmoveTo = self.searchQuery.at(index+1);\n\n\t\t\t\t\t\tself.unselect();\n\t\t\t\t\t\tif(moveTo){\n\t\t\t\t\t\t\tmoveTo.set(\"selected\", true);\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\tvar paremeter = new VS.Parameter();\n\t\t\t\t\t\t\tself.searchQuery.add(paremeter, {at: index+1});\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\n\t\t\t\t\t//Left 37\n\t\t\t\t\t37: function(){\n\t\t\t\t\t\tvar selected = self.searchQuery.where({'selected': true}),\n\t\t\t\t\t\t\tindex = self.searchQuery.indexOf(_.first(selected)),\n\t\t\t\t\t\t\tmoveTo = self.searchQuery.at(index-1);\n\n\t\t\t\t\t\tself.unselect();\n\t\t\t\t\t\tif(index === -1){\n\t\t\t\t\t\t\tself.searchQuery.at(self.searchQuery.length-1).set(\"selected\", true);\n\t\t\t\t\t\t}else if(moveTo){\n\t\t\t\t\t\t\tmoveTo.set(\"selected\", true);\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\tvar paremeter = new VS.Parameter();\n\t\t\t\t\t\t\tself.searchQuery.add(paremeter, {at: 0});\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\n\t\t\t\t\t//Up 38\n\t\t\t\t\t38: function(){\n\t\t\t\t\t\tself.unselect();\n\t\t\t\t\t\t_.first(self.searchQuery.models).set(\"selected\", true);\n\t\t\t\t\t},\n\n\t\t\t\t\t//Down 40\n\t\t\t\t\t40: function(){\n\t\t\t\t\t\tself.unselect();\n\t\t\t\t\t\t_.last(self.searchQuery.models).set(\"selected\", true);\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\treturn (keys[e.keyCode]) ? keys[e.keyCode]() : null;\n\n\t\t\t/*\n\t\t\t//Cntrl+A - Select All\n\t\t\tself.searchQuery.invoke('set', {'selected': true});\n\t\t\treturn false;\n\t\t\t*/\n\t\t}\n\t});\n\n\n\t/* Templates */\n\tVS.template = \n\t{\n\t\t'search_box': _.template('
    \\n
    \\n
    \\n
    <%= placeholder %>
    \\n
    \\n
    \\n
    \\n
    '),\n\t\t'search_parameter': _.template('
    <%- model.get(\\'key\\') %>
    <%- model.get(\\'operator\\') %>
    <%- model.get(\\'value\\') %>
    ')\n\t};\n\n\n\t/* Parameter View */\n\tVS.ParameterView = Backbone.View.extend({\n\n\t\tclassName : 'search_parameter',\n\t\t\n\t\tevents : {\n\t\t\t'focus input'\t: 'inputFocused',\n\t\t\t'blur input'\t: 'inputBlurred',\n\t\t\t'click'\t\t\t: 'click',\n\t\t\t'click div.VS-icon-cancel': 'delete',\n\t\t\t'keydown input'\t\t\t\t: 'keydown',\n\t\t},\n\n\t\trender : function() {\n\t\t\tvar self = this,\n\t\t\t\tparameters = this.model.collection.parameters;\n\t\t\t\ttemplate = $(VS.template['search_parameter']({model: this.model}));\n\n\t\t\tthis.$el.html(template);\n\t\t\tthis.key = {\n\t\t\t\tdom: $(\"\").attr({\n\t\t\t\t\tautocomplete:\t\"off\",\n\t\t\t\t\ttype:\t\t\t\"text\",\n\t\t\t\t\tname:\t\t\t\"key\",\n\t\t\t\t\tvalue: this.model.get('key')\n\t\t\t\t}),\n\t\t\t\tautocomplete: {\n\t\t\t\t\tminLength : 0,\n\t\t\t\t\tdelay : 0,\n\t\t\t\t\tsource: parameters.category,\n\t\t\t\t\tselect: function( e, ui ) {\n\t\t\t\t\t\tthis.value = ui.item.value;\n\t\t\t\t\t\t$(this).blur();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\t\t\tthis.operator = {\n\t\t\t\tdom: $(\"\").attr({\n\t\t\t\t\tautocomplete:\t\"off\",\n\t\t\t\t\tname:\t\t\t\"operator\",\n\t\t\t\t\tplaceholder: \"==\",\n\t\t\t\t\tvalue: \tthis.model.get(\"operator\"),\n\t\t\t\t\tsize: \"2\"\n\t\t\t\t}),\n\t\t\t\tautocomplete: {\n\t\t\t\t\tminLength : 0,\n\t\t\t\t\tdelay : 0,\n\t\t\t\t\tsource: function(req, res){\n\t\t\t\t\t\tvar key \t= self.model.get('key'),\n\t\t\t\t\t\t\ti = parameters.key.indexOf(key);\n\t\t\t\t\t\tif(parameters.operators[i]){\n\t\t\t\t\t\t\tres(parameters.operators[i]);\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\tres([\"==\", \"!=\", \"<\", \">\", \"≤\", \"≥\"]);\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tselect: function( e, ui ) {\n\t\t\t\t\t\tthis.value = ui.item.value;\n\t\t\t\t\t\t$(this).blur();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\t\t\tthis.value = {\n\t\t\t\tdom: $(\"\").attr({\n\t\t\t\t\tautocomplete:\t\"off\",\n\t\t\t\t\tname:\t\t\t\"value\",\n\t\t\t\t\tvalue: \t\t\tthis.model.get(\"value\"),\n\t\t\t\t\tplaceholder:\tthis.model.get(\"placeholder\"),\n\t\t\t\t\ttype:\t\t\tthis.model.get(\"type\"),\n\t\t\t\t\tmin:\t\t\tthis.model.get(\"min\"),\n\t\t\t\t\tmax:\t\t\tthis.model.get(\"max\"),\n\t\t\t\t\tmaxlength:\t\tthis.model.get(\"maxlength\"),\n\t\t\t\t\tsize:\t\t\tthis.model.has(\"value\") ? this.model.get(\"value\").length : 10,\n\t\t\t\t}),\n\t\t\t\tautocomplete: {\n\t\t\t\t\tminLength : 0,\n\t\t\t\t\tdelay : 0,\n\t\t\t\t\tsource: function(req, res){\n\t\t\t\t\t\tvar key \t= self.model.get('key'),\n\t\t\t\t\t\t\ti = parameters.key.indexOf(key);\n\t\t\t\t\t\tres(parameters.values[i]);\n\t\t\t\t\t},\n\t\t\t\t\tselect: function( e, ui ) {\n\t\t\t\t\t\tthis.value = ui.item.value;\n\t\t\t\t\t\t$(this).blur();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tif( !this.model.has('key') || this.model.get('editing')===0 ){\n\t\t\t\tthis.autocomplete(\n\t\t\t\t\tthis.$(\"div.key\").html(this.key.dom).children(),\n\t\t\t\t\tthis.key.autocomplete\n\t\t\t\t).focus(0);\n\t\t\t}else{\n\t\t\t\tif( !this.model.has('operator') || this.model.get('editing')===1 ){\n\t\t\t\t\tthis.autocomplete(\n\t\t\t\t\t\tthis.$(\"div.operator\").html(this.operator.dom).children(),\n\t\t\t\t\t\tthis.operator.autocomplete\n\t\t\t\t\t).focus(0);\n\t\t\t\t}else{\n\t\t\t\t\tif( !this.model.has('value') || this.model.get('editing')===2 ){\n\t\t\t\t\t\tthis.autocomplete(\n\t\t\t\t\t\t\tthis.$(\"div.value\").html(this.value.dom).children(),\n\t\t\t\t\t\t\tthis.value.autocomplete\n\t\t\t\t\t\t).focus(0);\n\t\t\t\t\t}else{\n\t\t\t\t\t\t//All fields must be completed in order to be selected\n\t\t\t\t\t\tif( this.model.get('selected') ){\n\t\t\t\t\t\t\tthis.$el.addClass(\"selected\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn this;\n\t\t},\n\t\tinputFocused: function(e){\n\t\t\t$(e.target).autocomplete(\"search\", \"\");\n\t\t},\n\t\tinputBlurred: function(e){\n\t\t\tvar input = $(e.target),\n\t\t\t\tediting = this.model.get('editing');\n\n\t\t\tvar update;\n\t\t\t(update = {\n\t\t\t\t'editing': ( editing<2 ) ? editing+1 : null\n\t\t\t})[input.attr(\"name\")] = input.val();\n\n\t\t\t/*\n\t\t\t//Value didn't change and isn't operator\n\t\t\tif(\n\t\t\t\tthis.model.get(input.attr(\"name\"))==input.val() &&\n\t\t\t\tediting!=1\n\t\t\t){\n\t\t\t\tupdate['editing'] = null;\n\t\t\t}\n\t\t\t*/\n\t\t\tthis.model.set(update);\n\t\t},\n\t\tclick: function(e){\n\t\t\tif( e.target.localName==\"input\" ) return;\n\n\t\t\tvar clicked = this.model.clicked;\n\n\t\t\tclearTimeout(clicked.timeout);\n\t\t\tclicked.timeout = setTimeout(function(){\n\t\t\t\tclicked.count = 0;\n\t\t\t}, 300);\n\t\t\t\n\t\t\tif(clicked.count>0){\n\t\t\t\tthis.dblclick(e);\n\t\t\t}else{\n\t\t\t\t//Single Click\n\t\t\t\tvar self = this;\n\t\t\t\t_.delay(function(){\n\t\t\t\t\tself.model.set('selected', true);\n\t\t\t\t});\n\t\t\t}\n\t\t\tclicked.count++;\n\t\t},\n\t\tdblclick: function(e){\n\t\t\tvar target = $(e.target);\n\t\t\tif( target.is(\"div.key\") ){\n\t\t\t\tthis.model.set(\"editing\", 0);\n\t\t\t}else if( target.is(\"div.operator\") ){\n\t\t\t\tthis.model.set(\"editing\", 1);\n\t\t\t}else if( target.is(\"div.value\") ){\n\t\t\t\tthis.model.set(\"editing\", 2);\n\t\t\t}\n\t\t},\n\t\tdelete: function(){\n\t\t\tthis.model.destroy();\n\t\t},\n\t\tautocomplete: function(target, options){\n\t\t\ttarget.autocomplete(options).autocomplete('widget').addClass('VS-interface');\n\t\t\treturn target;\n\t\t},\n\t\tkeydown : function(e) {\n\n\n\t\t}\n\t});\n\n\n\t/* Parameter Model */\n\tVS.Parameter = Backbone.Model.extend({\n\n\t\t//Default Parameters\n\t\tdefaults: {\n\t\t\tkey: null,\t\t\t//Name of Parameter\n\t\t\tvalue: null,\t\t//Value of Parameter\n\t\t\tplaceholder: \"\",\t//Value of Placeholder\n\t\t\ttype: \"text\",\t\t//Text, Number, Date, etc.\n\t\t\toperator: null,\t\t//=, !=, ≤, ≥\n\t\t\tmaxlength: null,\n\n\t\t\t//Optional Parameter for Number/Date\n\t\t\tmax: null,\n\t\t\tmin: null,\n\n\t\t\tselected: false,\n\t\t\tediting: false\n\t\t},\n\t\tinitialize: function(model){\n\t\t\tthis.setType();\n\n\t\t\t//Bind Events\n\t\t\tthis.on({\n\t\t\t\t\"change:key change:operator change:value\": function(model, changedVal){\n\n\t\t\t\t\t//Delete if Blank\n\t\t\t\t\tif(!changedVal){ return model.destroy(); }\n\n\t\t\t\t\t//If \"key\" was changed\n\t\t\t\t\tif(model.hasChanged(\"key\")){\n\t\t\t\t\t\tmodel.setType();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t\tincomplete: function(){\n\t\t\treturn !(this.has('key') && this.has('operator') && this.has('value'));\n\t\t},\n\t\tclicked: {\n\t\t\tcount: 0,\n\t\t\ttimeout: null\n\t\t},\n\t\tsetType: function(){\n\t\t\tvar key = this.get('key');\n\t\t\tif(!key) return;\n\t\t\tvar collection = this.collection,\n\t\t\t\ti = collection.parameters.key.indexOf(key);\n\n\t\t\t//Kill if the parameter doesn't exist?\n\t\t\tif(collection.strict && i === -1 ){\n\t\t\t\treturn this.destroy();\n\t\t\t}else\n\n\t\t\t//If exists\n\t\t\tif(i!==-1){\n\t\t\t\tthis.set({\n\t\t\t\t\t\"type\": collection.parameters.type[i],\n\t\t\t\t\t\"placeholder\": collection.parameters.placeholder[i],\n\t\t\t\t\t\"min\": collection.parameters.min[i],\n\t\t\t\t\t\"max\": collection.parameters.max[i]\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t});\n\n\n\t/* Collection of Parameters */\n\tVS.SearchQuery = Backbone.Collection.extend({\n\t\tmodel : VS.Parameter,\n\t\tinitialize: function(models, options){\n\t\t\t_.extend(this, options);\n\n\t\t\t//Transpose\n\t\t\tthis.parameters = _.transpose(this.parameters);\n\n\t\t\t//Organize Labels into Categories\n\t\t\tfor( var i in this.parameters.key){\n\t\t\t\tthis.parameters.category[i] = { label: this.parameters.key[i], category: this.parameters.category[i]}\n\t\t\t}\n\t\t},\n\t\tgetEditing: function(){\n\t\t\treturn _.filter(this.models, function(model){\n\t\t\t\treturn $.isNumeric(model.get('editing')) || model.incomplete();\n\t\t\t});\n\t\t},\n\t\tgetComplete: function(){\n\t\t\treturn _.filter(this.models, function(model){\n\t\t\t\treturn !model.incomplete();\n\t\t\t});\t\t\n\t\t}\n\t});\n\n\treturn VS;\n})(jQuery, _);\n"},"new_file":{"kind":"string","value":"lib/js/search.js"},"old_contents":{"kind":"string","value":"/** @license Search.js 0.0.1\n * (c) 2013 Hiroki Osame\n * Search.js may be freely distributed under the MIT license.\n */\n\n;var VisualSearch = (function($, _){\n\n\t//Autocomplete - Category Add-On\n\t$.widget(\"ui.autocomplete\", $.ui.autocomplete, {\n\t\t_renderMenu: function( ul, items ) {\n\t\t\tvar that = this,\n\t\t\tcurrentCategory = \"\";\n\t\t\t$.each( items, function( index, item ) {\n\t\t\t\tif( item.category && item.category != currentCategory ) {\n\t\t\t\t\tul.append( \"
  • \" + item.category + \"
  • \" );\n\t\t\t\t\tcurrentCategory = item.category;\n\t\t\t\t}\n\n\t\t\t\t//To differentiate categories\n\t\t\t\tvar dom = that._renderItemData(ul, item);\n\t\t\t\tif(item.category && item.category == currentCategory){\n\t\t\t\t\tdom.children().addClass(\"category-child\");\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t});\n\n\t//jQuery - Get Caret Position\n\t$.fn.getCursorPosition = function() {\n\t\tvar position = 0;\n\t\tvar input = this.get(0);\n\n\t\tif (document.selection) { // IE\n\t\t\tinput.focus();\n\t\t\tvar sel\t\t= document.selection.createRange();\n\t\t\tvar selLen\t= document.selection.createRange().text.length;\n\t\t\tsel.moveStart('character', -input.value.length);\n\t\t\tposition\t= sel.text.length - selLen;\n\t\t} else if (input && $(input).is(':visible') && input.selectionStart != null) { // Firefox/Safari\n\t\t\tposition = input.selectionStart;\n\t\t}\n\n\t\treturn position;\n\t}\n\n\t//Underscore - Transpose Objects\n\t_.transpose = function(array) {\n\t\tvar keys = _.union.apply(_, _.map(array, _.keys)),\n\t\tresult = {};\n\t\tfor (var i=0, l=keys.length; i\").css({\n\t\t\t\t\t\t\t\tposition: 'absolute',\n\t\t\t\t\t\t\t\ttop: -9999,\n\t\t\t\t\t\t\t\tleft: -9999,\n\t\t\t\t\t\t\t\twidth: 'auto',\n\t\t\t\t\t\t\t\tfontSize: input.css('fontSize'),\n\t\t\t\t\t\t\t\tfontFamily: input.css('fontFamily'),\n\t\t\t\t\t\t\t\tfontWeight: input.css('fontWeight'),\n\t\t\t\t\t\t\t\tletterSpacing: input.css('letterSpacing'),\n\t\t\t\t\t\t\t\t\"text-transform\": input.css('text-transform'),\n\t\t\t\t\t\t\t\twhiteSpace: 'nowrap'\n\t\t\t\t\t\t\t}).text($(this).val()).insertAfter(this),\n\t\t\t\t\tnewWidth = shadow.width()+20;\n\n\t\t\t\tif( input.width() < newWidth && newWidth < containerwidth){\n\t\t\t\t\tinput.css(\"width\", newWidth);\n\t\t\t\t}\n\t\t\t\tshadow.remove();\n\t\t\t});\n\t\t},\n\n\t\trender : function(){\n\t\t\tvar self\t\t\t= this,\n\t\t\t\ttemplate\t\t= $(VS.template['search_box'](this.options)),\n\t\t\t\tplaceholder\t\t= $('.VS-placeholder', template);\n\t\t\t\tthis.parameterViews = [];\n\n\t\t\tif (this.searchQuery.length) {\n\t\t\t\tplaceholder.hide();\n\n\t\t\t\t$('.VS-search-inner', template).append(this.searchQuery.map(function(parameter){\n\t\t\t\t\tvar parameterView = new VS.ParameterView({\n\t\t\t\t\t\tmodel : parameter\n\t\t\t\t\t}).render().el;\n\n\t\t\t\t\tself.parameterViews.push(parameterView);\n\t\t\t\t\treturn parameterView;\n\t\t\t\t}));\n\n\t\t\t} else {\n\t\t\t\tplaceholder.show();\n\t\t\t}\n\n\t\t\tthis.$el.html(template);\n\n\t\t\treturn this;\n\t\t},\n\n\t\tclickBox: function(e, index){\n\t\t\tif(\t!$(e.target).is('.VS-search-box, .VS-search-inner, .VS-placeholder') ) return;\n\n\t\t\tvar self = this;\n\n\t\t\tfor( var i in this.parameterViews ){\n\t\t\t\tvar parameterView = $(this.parameterViews[i]);\n\n\t\t\t\t//If the row the cursor is on is done iterating, stop loop.\n\t\t\t\tif( parameterView.offset().top > e.pageY ) break;\n\n\t\t\t\t//If row is above the row clicked on, continue\n\t\t\t\tif( parameterView.offset().top+parameterView.height() < e.pageY ) continue;\n\n\t\t\t\tif( e.pageX < parameterView.offset().left ){\n\t\t\t\t\treturn _.delay(function(){ self.newParam({}, i); });\n\t\t\t\t}\n\t\t\t}\n\t\t\ti = ( i == this.parameterViews.length-1 ) ? this.parameterViews.length : i;\n\n\t\t\t_.delay(function(){ self.newParam({}, i); });\n\t\t},\n\t\tnewParam: function(parameter, index){\n\t\t\tvar paremeter = new VS.Parameter(parameter);\n\t\t\tthis.searchQuery.add(paremeter, {at: index || null});\n\t\t},\n\t\tunselect: function(e){\n\t\t\tthis.searchQuery.invoke('set', {'selected': false});\n\t\t},\n\t\tclearSearch : function(e){\n\t\t\tthis.searchQuery.reset();\n\t\t},\n\t\thighlightSearch: function(e){\n\t\t\tif(!$(e.target).is(\"input, .search_parameter\")) return;\n\t\t\tthis.searchQuery.invoke('set', {'selected': true});\n\t\t},\n\t\tinputkeydown: function(e){\n\t\t\tvar self = this,\n\t\t\t\teditNext = function(){\n\t\t\t\t\tvar selected = self.searchQuery.getEditing()[0],\n\t\t\t\t\t\tediting = selected.get('editing');\n\n\t\t\t\t\tif( editing===2 ){\n\t\t\t\t\t\tvar index = self.searchQuery.indexOf(selected);\n\t\t\t\t\t\tselected.set(\"editing\", false);\n\t\t\t\t\t\tself.newParam({}, index+1);\n\t\t\t\t\t}else\n\t\t\t\t\tif(editing===false){\n\t\t\t\t\t\tvar index = self.searchQuery.indexOf(selected);\n\t\t\t\t\t\tselected.destroy();\n\t\t\t\t\t\tvar select = self.searchQuery.at(index);\n\t\t\t\t\t\tif(select){\n\t\t\t\t\t\t\tselect.set(\"editing\", 0);\n\t\t\t\t\t\t}\n\t\t\t\t\t}else\n\t\t\t\t\t{\n\t\t\t\t\t\tselected.set(\"editing\", editing+1);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\teditPrevious = function(){\n\t\t\t\t\tvar selected = self.searchQuery.getEditing()[0],\n\t\t\t\t\t\tediting = selected.get('editing');\n\n\t\t\t\t\t//If editing, make a new parameter before\n\t\t\t\t\tif( editing===0 ){\n\t\t\t\t\t\tvar index = self.searchQuery.indexOf(selected);\n\t\t\t\t\t\tselected.set(\"editing\", false);\n\t\t\t\t\t\tself.newParam({}, index);\n\t\t\t\t\t}else\n\n\t\t\t\t\t//If New Parameter\n\t\t\t\t\tif( editing===false ){\n\t\t\t\t\t\tvar index = self.searchQuery.indexOf(selected);\n\t\t\t\t\t\tselected.destroy();\n\t\t\t\t\t\tif( self.searchQuery.at(index-1) ){\tself.searchQuery.at(index-1).set(\"editing\", 2);\t}\n\t\t\t\t\t}else\n\t\t\t\t\t{\n\t\t\t\t\t\tselected.set(\"editing\", editing-1);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tkeys = {\n\t\t\t\t\t//Left\n\t\t\t\t\t37: function(){\n\t\t\t\t\t\tif( $(e.target).getCursorPosition()==0 ){ editPrevious(); }\n\t\t\t\t\t},\n\n\t\t\t\t\t//Right\n\t\t\t\t\t39: function(){\n\t\t\t\t\t\tvar input = $(e.target);\n\t\t\t\t\t\tif( input.getCursorPosition()==input.val().length ){ editNext(); }\n\t\t\t\t\t},\n\n\t\t\t\t\t//Delete\n\t\t\t\t\t8: function(){\n\t\t\t\t\t\tvar input = $(e.target);\n\t\t\t\t\t\tif( input.getCursorPosition()===0 &&\n\t\t\t\t\t\t\tinput.get(0).selectionStart === input.get(0).selectionEnd //Only Webkit, no IE\n\t\t\t\t\t\t){ editPrevious(); return false; }\n\t\t\t\t\t},\n\n\t\t\t\t\t//Tab\n\t\t\t\t\t9: function(){\n\t\t\t\t\t\tif( e.shiftKey ){\n\t\t\t\t\t\t\te.preventDefault();\n\t\t\t\t\t\t\teditPrevious();\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\te.preventDefault();\n\t\t\t\t\t\t\teditNext();\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\n\t\t\t\t\t//Enter\n\t\t\t\t\t13: function(){\n\t\t\t\t\t\t$(e.target).blur();\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\treturn (keys[e.keyCode]) ? keys[e.keyCode]() : null;\n\t\t},\n\t\tkeydown: function(e){\n\t\t\t//Check if Parameters are selected\n\t\t\tif( !e || $(\".VS-search .selected\").length===0 ){ return; }\n\t\t\tif( [8, 37, 38, 39, 40].indexOf(e.keyCode)!=-1 ){ return false; }\n\t\t},\n\t\tbindKeys: function(e){\n\t\t\t//Check if Parameters are selected\n\t\t\tif( !e || $(\".VS-search .selected\").length===0 ){ return; }\n\n\t\t\tvar self = this,\n\t\t\t\tkeys = {\n\t\t\t\t\t//Delete\n\t\t\t\t\t8: function(){\n\t\t\t\t\t\tvar selected = self.searchQuery.where({'selected': true});\n\t\t\t\t\t\tselected.forEach(function(e){\n\t\t\t\t\t\t\te.destroy();\n\t\t\t\t\t\t});\n\t\t\t\t\t},\n\n\t\t\t\t\t//Enter - Start Editing\n\t\t\t\t\t13: function(){\n\t\t\t\t\t\tvar selected = self.searchQuery.where({'selected': true});\n\t\t\t\t\t\tselected[0].set(\"editing\", 0);\n\t\t\t\t\t},\n\n\t\t\t\t\t//Right 39\n\t\t\t\t\t39: function(){\n\t\t\t\t\t\tvar selected = self.searchQuery.where({'selected': true}),\n\t\t\t\t\t\t\tindex = self.searchQuery.indexOf(_.last(selected)),\n\t\t\t\t\t\t\tmoveTo = self.searchQuery.at(index+1);\n\n\t\t\t\t\t\tself.unselect();\n\t\t\t\t\t\tif(moveTo){\n\t\t\t\t\t\t\tmoveTo.set(\"selected\", true);\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\tvar paremeter = new VS.Parameter();\n\t\t\t\t\t\t\tself.searchQuery.add(paremeter, {at: index+1});\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\n\t\t\t\t\t//Left 37\n\t\t\t\t\t37: function(){\n\t\t\t\t\t\tvar selected = self.searchQuery.where({'selected': true}),\n\t\t\t\t\t\t\tindex = self.searchQuery.indexOf(_.first(selected)),\n\t\t\t\t\t\t\tmoveTo = self.searchQuery.at(index-1);\n\n\t\t\t\t\t\tself.unselect();\n\t\t\t\t\t\tif(index === -1){\n\t\t\t\t\t\t\tself.searchQuery.at(self.searchQuery.length-1).set(\"selected\", true);\n\t\t\t\t\t\t}else if(moveTo){\n\t\t\t\t\t\t\tmoveTo.set(\"selected\", true);\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\tvar paremeter = new VS.Parameter();\n\t\t\t\t\t\t\tself.searchQuery.add(paremeter, {at: 0});\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\n\t\t\t\t\t//Up 38\n\t\t\t\t\t38: function(){\n\t\t\t\t\t\tself.unselect();\n\t\t\t\t\t\t_.first(self.searchQuery.models).set(\"selected\", true);\n\t\t\t\t\t},\n\n\t\t\t\t\t//Down 40\n\t\t\t\t\t40: function(){\n\t\t\t\t\t\tself.unselect();\n\t\t\t\t\t\t_.last(self.searchQuery.models).set(\"selected\", true);\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\treturn (keys[e.keyCode]) ? keys[e.keyCode]() : null;\n\n\t\t\t/*\n\t\t\t//Cntrl+A - Select All\n\t\t\tself.searchQuery.invoke('set', {'selected': true});\n\t\t\treturn false;\n\t\t\t*/\n\t\t}\n\t});\n\n\n\t/* Templates */\n\tVS.template = \n\t{\n\t\t'search_box': _.template('
    \\n
    \\n
    \\n
    <%= placeholder %>
    \\n
    \\n
    \\n
    \\n
    '),\n\t\t'search_parameter': _.template('
    <%- model.get(\\'key\\') %>
    <%- model.get(\\'operator\\') %>
    <%- model.get(\\'value\\') %>
    ')\n\t};\n\n\n\t/* Parameter View */\n\tVS.ParameterView = Backbone.View.extend({\n\n\t\tclassName : 'search_parameter',\n\t\t\n\t\tevents : {\n\t\t\t'focus input'\t: 'inputFocused',\n\t\t\t'blur input'\t: 'inputBlurred',\n\t\t\t'click'\t\t\t: 'click',\n\t\t\t'click div.VS-icon-cancel': 'delete',\n\t\t\t'keydown input'\t\t\t\t: 'keydown',\n\t\t},\n\n\t\trender : function() {\n\t\t\tvar self = this,\n\t\t\t\tparameters = this.model.collection.parameters;\n\t\t\t\ttemplate = $(VS.template['search_parameter']({model: this.model}));\n\n\t\t\tthis.$el.html(template);\n\t\t\tthis.key = {\n\t\t\t\tdom: $(\"\").attr({\n\t\t\t\t\tautocomplete:\t\"off\",\n\t\t\t\t\ttype:\t\t\t\"text\",\n\t\t\t\t\tname:\t\t\t\"key\",\n\t\t\t\t\tvalue: this.model.get('key')\n\t\t\t\t}),\n\t\t\t\tautocomplete: {\n\t\t\t\t\tminLength : 0,\n\t\t\t\t\tdelay : 0,\n\t\t\t\t\tsource: parameters.category,\n\t\t\t\t\tselect: function( e, ui ) {\n\t\t\t\t\t\tthis.value = ui.item.value;\n\t\t\t\t\t\t$(this).blur();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\t\t\tthis.operator = {\n\t\t\t\tdom: $(\"\").attr({\n\t\t\t\t\tautocomplete:\t\"off\",\n\t\t\t\t\tname:\t\t\t\"operator\",\n\t\t\t\t\tplaceholder: \"==\",\n\t\t\t\t\tvalue: \tthis.model.get(\"operator\"),\n\t\t\t\t\tsize: \"2\"\n\t\t\t\t}),\n\t\t\t\tautocomplete: {\n\t\t\t\t\tminLength : 0,\n\t\t\t\t\tdelay : 0,\n\t\t\t\t\tsource: function(req, res){\n\t\t\t\t\t\tvar key \t= self.model.get('key'),\n\t\t\t\t\t\t\ti = parameters.key.indexOf(key);\n\t\t\t\t\t\tif(parameters.operators[i]){\n\t\t\t\t\t\t\tres(parameters.operators[i]);\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\tres([\"==\", \"!=\", \"<\", \">\", \"≤\", \"≥\"]);\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tselect: function( e, ui ) {\n\t\t\t\t\t\tthis.value = ui.item.value;\n\t\t\t\t\t\t$(this).blur();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\t\t\tthis.value = {\n\t\t\t\tdom: $(\"\").attr({\n\t\t\t\t\tautocomplete:\t\"off\",\n\t\t\t\t\tname:\t\t\t\"value\",\n\t\t\t\t\tvalue: \t\t\tthis.model.get(\"value\"),\n\t\t\t\t\tplaceholder:\tthis.model.get(\"placeholder\"),\n\t\t\t\t\ttype:\t\t\tthis.model.get(\"type\"),\n\t\t\t\t\tmin:\t\t\tthis.model.get(\"min\"),\n\t\t\t\t\tmax:\t\t\tthis.model.get(\"max\"),\n\t\t\t\t\tmaxlength:\t\tthis.model.get(\"maxlength\"),\n\t\t\t\t\tsize:\t\t\tthis.model.has(\"value\") ? this.model.get(\"value\").length : 10,\n\t\t\t\t}),\n\t\t\t\tautocomplete: {\n\t\t\t\t\tminLength : 0,\n\t\t\t\t\tdelay : 0,\n\t\t\t\t\tsource: function(req, res){\n\t\t\t\t\t\tvar key \t= self.model.get('key'),\n\t\t\t\t\t\t\ti = parameters.key.indexOf(key);\n\t\t\t\t\t\tres(parameters.values[i]);\n\t\t\t\t\t},\n\t\t\t\t\tselect: function( e, ui ) {\n\t\t\t\t\t\tthis.value = ui.item.value;\n\t\t\t\t\t\t$(this).blur();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tif( !this.model.has('key') || this.model.get('editing')===0 ){\n\t\t\t\tthis.autocomplete(\n\t\t\t\t\tthis.$(\"div.key\").html(this.key.dom).children(),\n\t\t\t\t\tthis.key.autocomplete\n\t\t\t\t).focus(0);\n\t\t\t}else{\n\t\t\t\tif( !this.model.has('operator') || this.model.get('editing')===1 ){\n\t\t\t\t\tthis.autocomplete(\n\t\t\t\t\t\tthis.$(\"div.operator\").html(this.operator.dom).children(),\n\t\t\t\t\t\tthis.operator.autocomplete\n\t\t\t\t\t).focus(0);\n\t\t\t\t}else{\n\t\t\t\t\tif( !this.model.has('value') || this.model.get('editing')===2 ){\n\t\t\t\t\t\tthis.autocomplete(\n\t\t\t\t\t\t\tthis.$(\"div.value\").html(this.value.dom).children(),\n\t\t\t\t\t\t\tthis.value.autocomplete\n\t\t\t\t\t\t).focus(0);\n\t\t\t\t\t}else{\n\t\t\t\t\t\t//All fields must be completed in order to be selected\n\t\t\t\t\t\tif( this.model.get('selected') ){\n\t\t\t\t\t\t\tthis.$el.addClass(\"selected\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn this;\n\t\t},\n\t\tinputFocused: function(e){\n\t\t\t$(e.target).autocomplete(\"search\", \"\");\n\t\t},\n\t\tinputBlurred: function(e){\n\t\t\treturn;\n\t\t\tvar input = $(e.target),\n\t\t\t\tediting = this.model.get('editing');\n\n\t\t\tvar update;\n\t\t\t(update = {\n\t\t\t\t'editing': ( editing<2 ) ? editing+1 : null\n\t\t\t})[input.attr(\"name\")] = input.val();\n\n\t\t\t/*\n\t\t\t//Value didn't change and isn't operator\n\t\t\tif(\n\t\t\t\tthis.model.get(input.attr(\"name\"))==input.val() &&\n\t\t\t\tediting!=1\n\t\t\t){\n\t\t\t\tupdate['editing'] = null;\n\t\t\t}\n\t\t\t*/\n\t\t\tthis.model.set(update);\n\t\t},\n\t\tclick: function(e){\n\t\t\tif( e.target.localName==\"input\" ) return;\n\n\t\t\tvar clicked = this.model.clicked;\n\n\t\t\tclearTimeout(clicked.timeout);\n\t\t\tclicked.timeout = setTimeout(function(){\n\t\t\t\tclicked.count = 0;\n\t\t\t}, 300);\n\t\t\t\n\t\t\tif(clicked.count>0){\n\t\t\t\tthis.dblclick(e);\n\t\t\t}else{\n\t\t\t\t//Single Click\n\t\t\t\tvar self = this;\n\t\t\t\t_.delay(function(){\n\t\t\t\t\tself.model.set('selected', true);\n\t\t\t\t});\n\t\t\t}\n\t\t\tclicked.count++;\n\t\t},\n\t\tdblclick: function(e){\n\t\t\tvar target = $(e.target);\n\t\t\tif( target.is(\"div.key\") ){\n\t\t\t\tthis.model.set(\"editing\", 0);\n\t\t\t}else if( target.is(\"div.operator\") ){\n\t\t\t\tthis.model.set(\"editing\", 1);\n\t\t\t}else if( target.is(\"div.value\") ){\n\t\t\t\tthis.model.set(\"editing\", 2);\n\t\t\t}\n\t\t},\n\t\tdelete: function(){\n\t\t\tthis.model.destroy();\n\t\t},\n\t\tautocomplete: function(target, options){\n\t\t\ttarget.autocomplete(options).autocomplete('widget').addClass('VS-interface');\n\t\t\treturn target;\n\t\t},\n\t\tkeydown : function(e) {\n\n\n\t\t}\n\t});\n\n\n\t/* Parameter Model */\n\tVS.Parameter = Backbone.Model.extend({\n\n\t\t//Default Parameters\n\t\tdefaults: {\n\t\t\tkey: null,\t\t\t//Name of Parameter\n\t\t\tvalue: null,\t\t//Value of Parameter\n\t\t\tplaceholder: \"\",\t//Value of Placeholder\n\t\t\ttype: \"text\",\t\t//Text, Number, Date, etc.\n\t\t\toperator: null,\t\t//=, !=, ≤, ≥\n\t\t\tmaxlength: null,\n\n\t\t\t//Optional Parameter for Number/Date\n\t\t\tmax: null,\n\t\t\tmin: null,\n\n\t\t\tselected: false,\n\t\t\tediting: false\n\t\t},\n\t\tinitialize: function(model){\n\t\t\tthis.setType();\n\n\t\t\t//Bind Events\n\t\t\tthis.on({\n\t\t\t\t\"change:key change:operator change:value\": function(model, changedVal){\n\n\t\t\t\t\t//Delete if Blank\n\t\t\t\t\tif(!changedVal){ return model.destroy(); }\n\n\t\t\t\t\t//If \"key\" was changed\n\t\t\t\t\tif(model.hasChanged(\"key\")){\n\t\t\t\t\t\tmodel.setType();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t\tincomplete: function(){\n\t\t\treturn !(this.has('key') && this.has('operator') && this.has('value'));\n\t\t},\n\t\tclicked: {\n\t\t\tcount: 0,\n\t\t\ttimeout: null\n\t\t},\n\t\tsetType: function(){\n\t\t\tvar key = this.get('key');\n\t\t\tif(!key) return;\n\t\t\tvar collection = this.collection,\n\t\t\t\ti = collection.parameters.key.indexOf(key);\n\n\t\t\t//Kill if the parameter doesn't exist?\n\t\t\tif(collection.strict && i === -1 ){\n\t\t\t\treturn this.destroy();\n\t\t\t}else\n\n\t\t\t//If exists\n\t\t\tif(i!==-1){\n\t\t\t\tthis.set({\n\t\t\t\t\t\"type\": collection.parameters.type[i],\n\t\t\t\t\t\"placeholder\": collection.parameters.placeholder[i],\n\t\t\t\t\t\"min\": collection.parameters.min[i],\n\t\t\t\t\t\"max\": collection.parameters.max[i]\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t});\n\n\n\t/* Collection of Parameters */\n\tVS.SearchQuery = Backbone.Collection.extend({\n\t\tmodel : VS.Parameter,\n\t\tinitialize: function(models, options){\n\t\t\t_.extend(this, options);\n\n\t\t\t//Transpose\n\t\t\tthis.parameters = _.transpose(this.parameters);\n\n\t\t\t//Organize Labels into Categories\n\t\t\tfor( var i in this.parameters.key){\n\t\t\t\tthis.parameters.category[i] = { label: this.parameters.key[i], category: this.parameters.category[i]}\n\t\t\t}\n\t\t},\n\t\tgetEditing: function(){\n\t\t\treturn _.filter(this.models, function(model){\n\t\t\t\treturn $.isNumeric(model.get('editing')) || model.incomplete();\n\t\t\t});\n\t\t},\n\t\tgetComplete: function(){\n\t\t\treturn _.filter(this.models, function(model){\n\t\t\t\treturn !model.incomplete();\n\t\t\t});\t\t\n\t\t}\n\t});\n\n\treturn VS;\n})(jQuery, _);\n"},"message":{"kind":"string","value":"fix 2\n"},"old_file":{"kind":"string","value":"lib/js/search.js"},"subject":{"kind":"string","value":"fix 2"},"git_diff":{"kind":"string","value":"ib/js/search.js\n \t\t\t$(e.target).autocomplete(\"search\", \"\");\n \t\t},\n \t\tinputBlurred: function(e){\n\t\t\treturn;\n \t\t\tvar input = $(e.target),\n \t\t\t\tediting = this.model.get('editing');\n "}}},{"rowIdx":1958,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"08be74178a5725dc977b796384383ee38ae134d5"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"reactivex/rxjava,artem-zinnatullin/RxJava,NiteshKant/RxJava,akarnokd/RxJava,artem-zinnatullin/RxJava,ReactiveX/RxJava,reactivex/rxjava,NiteshKant/RxJava,ReactiveX/RxJava,akarnokd/RxJava"},"new_contents":{"kind":"string","value":"/**\n * Copyright (c) 2016-present, RxJava Contributors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in\n * compliance with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the License is\n * distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See\n * the License for the specific language governing permissions and limitations under the License.\n */\n\npackage io.reactivex.internal.schedulers;\n\nimport static org.junit.Assert.*;\n\nimport io.reactivex.schedulers.AbstractSchedulerTests;\nimport java.util.concurrent.*;\n\nimport org.junit.Test;\n\nimport io.reactivex.*;\nimport io.reactivex.Scheduler.Worker;\nimport io.reactivex.disposables.*;\nimport io.reactivex.internal.functions.Functions;\nimport io.reactivex.internal.schedulers.SingleScheduler.ScheduledWorker;\nimport io.reactivex.schedulers.Schedulers;\n\npublic class SingleSchedulerTest extends AbstractSchedulerTests {\n\n @Test\n public void shutdownRejects() {\n final int[] calls = { 0 };\n\n Runnable r = new Runnable() {\n @Override\n public void run() {\n calls[0]++;\n }\n };\n\n Scheduler s = new SingleScheduler();\n s.shutdown();\n\n assertEquals(Disposables.disposed(), s.scheduleDirect(r));\n\n assertEquals(Disposables.disposed(), s.scheduleDirect(r, 1, TimeUnit.SECONDS));\n\n assertEquals(Disposables.disposed(), s.schedulePeriodicallyDirect(r, 1, 1, TimeUnit.SECONDS));\n\n Worker w = s.createWorker();\n ((ScheduledWorker)w).executor.shutdownNow();\n\n assertEquals(Disposables.disposed(), w.schedule(r));\n\n assertEquals(Disposables.disposed(), w.schedule(r, 1, TimeUnit.SECONDS));\n\n assertEquals(Disposables.disposed(), w.schedulePeriodically(r, 1, 1, TimeUnit.SECONDS));\n\n assertEquals(0, calls[0]);\n\n w.dispose();\n\n assertTrue(w.isDisposed());\n }\n\n @Test\n public void startRace() {\n final Scheduler s = new SingleScheduler();\n for (int i = 0; i < 500; i++) {\n s.shutdown();\n\n Runnable r1 = new Runnable() {\n @Override\n public void run() {\n s.start();\n }\n };\n\n TestHelper.race(r1, r1);\n }\n }\n\n @Test(timeout = 1000)\n public void runnableDisposedAsync() throws Exception {\n final Scheduler s = Schedulers.single();\n Disposable d = s.scheduleDirect(Functions.EMPTY_RUNNABLE);\n\n while (!d.isDisposed()) {\n Thread.sleep(1);\n }\n }\n\n @Test(timeout = 1000)\n public void runnableDisposedAsyncCrash() throws Exception {\n final Scheduler s = Schedulers.single();\n\n Disposable d = s.scheduleDirect(new Runnable() {\n @Override\n public void run() {\n throw new IllegalStateException();\n }\n });\n\n while (!d.isDisposed()) {\n Thread.sleep(1);\n }\n }\n\n @Test(timeout = 1000)\n public void runnableDisposedAsyncTimed() throws Exception {\n final Scheduler s = Schedulers.single();\n\n Disposable d = s.scheduleDirect(Functions.EMPTY_RUNNABLE, 1, TimeUnit.MILLISECONDS);\n\n while (!d.isDisposed()) {\n Thread.sleep(1);\n }\n }\n\n @Override protected Scheduler getScheduler() {\n return Schedulers.single();\n }\n\n}\n"},"new_file":{"kind":"string","value":"src/test/java/io/reactivex/internal/schedulers/SingleSchedulerTest.java"},"old_contents":{"kind":"string","value":"/**\n * Copyright (c) 2016-present, RxJava Contributors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in\n * compliance with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the License is\n * distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See\n * the License for the specific language governing permissions and limitations under the License.\n */\n\npackage io.reactivex.internal.schedulers;\n\nimport static org.junit.Assert.*;\n\nimport java.util.concurrent.*;\n\nimport org.junit.Test;\n\nimport io.reactivex.*;\nimport io.reactivex.Scheduler.Worker;\nimport io.reactivex.disposables.*;\nimport io.reactivex.internal.disposables.SequentialDisposable;\nimport io.reactivex.internal.functions.Functions;\nimport io.reactivex.internal.schedulers.SingleScheduler.ScheduledWorker;\nimport io.reactivex.schedulers.Schedulers;\n\npublic class SingleSchedulerTest {\n\n @Test\n public void shutdownRejects() {\n final int[] calls = { 0 };\n\n Runnable r = new Runnable() {\n @Override\n public void run() {\n calls[0]++;\n }\n };\n\n Scheduler s = new SingleScheduler();\n s.shutdown();\n\n assertEquals(Disposables.disposed(), s.scheduleDirect(r));\n\n assertEquals(Disposables.disposed(), s.scheduleDirect(r, 1, TimeUnit.SECONDS));\n\n assertEquals(Disposables.disposed(), s.schedulePeriodicallyDirect(r, 1, 1, TimeUnit.SECONDS));\n\n Worker w = s.createWorker();\n ((ScheduledWorker)w).executor.shutdownNow();\n\n assertEquals(Disposables.disposed(), w.schedule(r));\n\n assertEquals(Disposables.disposed(), w.schedule(r, 1, TimeUnit.SECONDS));\n\n assertEquals(Disposables.disposed(), w.schedulePeriodically(r, 1, 1, TimeUnit.SECONDS));\n\n assertEquals(0, calls[0]);\n\n w.dispose();\n\n assertTrue(w.isDisposed());\n }\n\n @Test\n public void startRace() {\n final Scheduler s = new SingleScheduler();\n for (int i = 0; i < 500; i++) {\n s.shutdown();\n\n Runnable r1 = new Runnable() {\n @Override\n public void run() {\n s.start();\n }\n };\n\n TestHelper.race(r1, r1);\n }\n }\n\n @Test(timeout = 1000)\n public void runnableDisposedAsync() throws Exception {\n final Scheduler s = Schedulers.single();\n Disposable d = s.scheduleDirect(Functions.EMPTY_RUNNABLE);\n\n while (!d.isDisposed()) {\n Thread.sleep(1);\n }\n }\n\n @Test(timeout = 1000)\n public void runnableDisposedAsyncCrash() throws Exception {\n final Scheduler s = Schedulers.single();\n\n Disposable d = s.scheduleDirect(new Runnable() {\n @Override\n public void run() {\n throw new IllegalStateException();\n }\n });\n\n while (!d.isDisposed()) {\n Thread.sleep(1);\n }\n }\n\n @Test(timeout = 1000)\n public void runnableDisposedAsyncTimed() throws Exception {\n final Scheduler s = Schedulers.single();\n\n Disposable d = s.scheduleDirect(Functions.EMPTY_RUNNABLE, 1, TimeUnit.MILLISECONDS);\n\n while (!d.isDisposed()) {\n Thread.sleep(1);\n }\n }\n\n @Test(timeout = 10000)\n public void schedulePeriodicallyDirectZeroPeriod() throws Exception {\n Scheduler s = Schedulers.single();\n\n for (int initial = 0; initial < 2; initial++) {\n final CountDownLatch cdl = new CountDownLatch(1);\n\n final SequentialDisposable sd = new SequentialDisposable();\n\n try {\n sd.replace(s.schedulePeriodicallyDirect(new Runnable() {\n int count;\n @Override\n public void run() {\n if (++count == 10) {\n sd.dispose();\n cdl.countDown();\n }\n }\n }, initial, 0, TimeUnit.MILLISECONDS));\n\n assertTrue(\"\" + initial, cdl.await(5, TimeUnit.SECONDS));\n } finally {\n sd.dispose();\n }\n }\n }\n\n @Test(timeout = 10000)\n public void schedulePeriodicallyZeroPeriod() throws Exception {\n Scheduler s = Schedulers.single();\n\n for (int initial = 0; initial < 2; initial++) {\n\n final CountDownLatch cdl = new CountDownLatch(1);\n\n final SequentialDisposable sd = new SequentialDisposable();\n\n Scheduler.Worker w = s.createWorker();\n\n try {\n sd.replace(w.schedulePeriodically(new Runnable() {\n int count;\n @Override\n public void run() {\n if (++count == 10) {\n sd.dispose();\n cdl.countDown();\n }\n }\n }, initial, 0, TimeUnit.MILLISECONDS));\n\n assertTrue(\"\" + initial, cdl.await(5, TimeUnit.SECONDS));\n } finally {\n sd.dispose();\n w.dispose();\n }\n }\n }\n}\n"},"message":{"kind":"string","value":"Refactoring SingleSchedulerTest. Now it extends AbstractSchedulerTests, so redundant tests could be removed in favor of abstract tests. (#5462)\n\n"},"old_file":{"kind":"string","value":"src/test/java/io/reactivex/internal/schedulers/SingleSchedulerTest.java"},"subject":{"kind":"string","value":"Refactoring SingleSchedulerTest. Now it extends AbstractSchedulerTests, so redundant tests could be removed in favor of abstract tests. (#5462)"},"git_diff":{"kind":"string","value":"rc/test/java/io/reactivex/internal/schedulers/SingleSchedulerTest.java\n \n import static org.junit.Assert.*;\n \nimport io.reactivex.schedulers.AbstractSchedulerTests;\n import java.util.concurrent.*;\n \n import org.junit.Test;\n import io.reactivex.*;\n import io.reactivex.Scheduler.Worker;\n import io.reactivex.disposables.*;\nimport io.reactivex.internal.disposables.SequentialDisposable;\n import io.reactivex.internal.functions.Functions;\n import io.reactivex.internal.schedulers.SingleScheduler.ScheduledWorker;\n import io.reactivex.schedulers.Schedulers;\n \npublic class SingleSchedulerTest {\npublic class SingleSchedulerTest extends AbstractSchedulerTests {\n \n @Test\n public void shutdownRejects() {\n }\n }\n \n @Test(timeout = 10000)\n public void schedulePeriodicallyDirectZeroPeriod() throws Exception {\n Scheduler s = Schedulers.single();\n\n for (int initial = 0; initial < 2; initial++) {\n final CountDownLatch cdl = new CountDownLatch(1);\n\n final SequentialDisposable sd = new SequentialDisposable();\n\n try {\n sd.replace(s.schedulePeriodicallyDirect(new Runnable() {\n int count;\n @Override\n public void run() {\n if (++count == 10) {\n sd.dispose();\n cdl.countDown();\n }\n }\n }, initial, 0, TimeUnit.MILLISECONDS));\n\n assertTrue(\"\" + initial, cdl.await(5, TimeUnit.SECONDS));\n } finally {\n sd.dispose();\n }\n }\n @Override protected Scheduler getScheduler() {\n return Schedulers.single();\n }\n \n @Test(timeout = 10000)\n public void schedulePeriodicallyZeroPeriod() throws Exception {\n Scheduler s = Schedulers.single();\n\n for (int initial = 0; initial < 2; initial++) {\n\n final CountDownLatch cdl = new CountDownLatch(1);\n\n final SequentialDisposable sd = new SequentialDisposable();\n\n Scheduler.Worker w = s.createWorker();\n\n try {\n sd.replace(w.schedulePeriodically(new Runnable() {\n int count;\n @Override\n public void run() {\n if (++count == 10) {\n sd.dispose();\n cdl.countDown();\n }\n }\n }, initial, 0, TimeUnit.MILLISECONDS));\n\n assertTrue(\"\" + initial, cdl.await(5, TimeUnit.SECONDS));\n } finally {\n sd.dispose();\n w.dispose();\n }\n }\n }\n }"}}},{"rowIdx":1959,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"lgpl-2.1"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"ed673f0e4e84d75302cfa1005f9043ee7d90c942"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"godbyk/vrjuggler-upstream-old,vrjuggler/vrjuggler,MichaelMcDonnell/vrjuggler,vancegroup-mirrors/vrjuggler,vrjuggler/vrjuggler,vrjuggler/vrjuggler,MichaelMcDonnell/vrjuggler,MichaelMcDonnell/vrjuggler,MichaelMcDonnell/vrjuggler,LiuKeHua/vrjuggler,godbyk/vrjuggler-upstream-old,vrjuggler/vrjuggler,godbyk/vrjuggler-upstream-old,LiuKeHua/vrjuggler,vancegroup-mirrors/vrjuggler,vrjuggler/vrjuggler,LiuKeHua/vrjuggler,LiuKeHua/vrjuggler,vancegroup-mirrors/vrjuggler,godbyk/vrjuggler-upstream-old,MichaelMcDonnell/vrjuggler,godbyk/vrjuggler-upstream-old,LiuKeHua/vrjuggler,MichaelMcDonnell/vrjuggler,LiuKeHua/vrjuggler,LiuKeHua/vrjuggler,MichaelMcDonnell/vrjuggler,vancegroup-mirrors/vrjuggler,vrjuggler/vrjuggler,vrjuggler/vrjuggler,vancegroup-mirrors/vrjuggler,vancegroup-mirrors/vrjuggler,MichaelMcDonnell/vrjuggler,LiuKeHua/vrjuggler,godbyk/vrjuggler-upstream-old,vrjuggler/vrjuggler"},"new_contents":{"kind":"string","value":"/***************** ****************\n * Tweek\n *\n * -----------------------------------------------------------------\n * File: $RCSfile$\n * Date modified: $Date$\n * Version: $Revision$\n * -----------------------------------------------------------------\n ***************** *****************/\n\n/*************** **************\n *\n * VR Juggler is (C) Copyright 1998, 1999, 2000, 2001 by Iowa State University\n *\n * Original Authors:\n * Allen Bierbaum, Christopher Just,\n * Patrick Hartling, Kevin Meinert,\n * Carolina Cruz-Neira, Albert Baker\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n *\n *************** ***************/\n\npackage org.vrjuggler.tweek.treeviewer;\n\nimport java.awt.*;\nimport javax.swing.*;\nimport javax.swing.event.TreeSelectionEvent;\nimport javax.swing.event.TreeSelectionListener;\nimport javax.swing.tree.*;\nimport org.vrjuggler.tweek.beans.*;\n\n\n/**\n *\n * @version $Revision$\n *\n * @see org.vrjuggler.tweek.treeviewer.BeanTree\n */\npublic class BeanTreeViewer extends DefaultBeanModelViewer\n{\n // ========================================================================\n // Public methods.\n // ========================================================================\n\n /**\n * Constructs the split pane. This just fills in panels for the left and\n * right sides of this JSplitPane. For the left pane, a blank JPanel is\n * For the right pane, the default (no-Bean-selected) JPanel is shown.\n * used. This is done primarily to keep the GUI from looking nasty before\n * the full GUI initialization is done.\n */\n public BeanTreeViewer ()\n {\n JPanel empty_left = new JPanel();\n empty_left.setBackground(Color.white);\n empty_left.setMinimumSize(new Dimension(125, 200));\n viewer.add(empty_left, JSplitPane.LEFT);\n viewer.add(m_default_bean_panel, JSplitPane.RIGHT);\n viewer.setDividerSize(5);\n }\n\n public void initDataModel (BeanTreeModel model)\n {\n m_bean_tree = new BeanTree(model);\n }\n\n /**\n * Component initialization.\n */\n public void initGUI ()\n {\n try\n {\n jbInit();\n }\n catch(Exception e)\n {\n e.printStackTrace();\n }\n }\n\n public void refreshDataModel (BeanTreeModel model)\n {\n model.nodeStructureChanged((TreeNode) model.getRoot());\n }\n\n public JComponent getViewer ()\n {\n return viewer;\n }\n\n /**\n * Extension of javax.swing.event.TreeSelectionListener used with BeanTree\n * objects. This class assumes that the BeanTree leaves contain instances\n * of PanelBean objects. It knows how to instantiate JavaBeans and thus\n * allows delayed loading of Beans. In addition, it requires that a\n * JSplitPane is used as the container for the BeanTree where the BeanTree\n * is the left member of the split pane. The Beans are displayed in the\n * right member.\n */\n protected class BeanSelectionListener implements TreeSelectionListener\n {\n /**\n * Implementation of the TreeSelectionListener.valueChanged() method.\n * This is called when the user clicks on an element of the BeanTree\n * object associated with this object. If the element is a branch, the\n * default panel is displayed.\n */\n public void valueChanged (TreeSelectionEvent e)\n {\n DefaultMutableTreeNode node =\n (DefaultMutableTreeNode) m_bean_tree.getLastSelectedPathComponent();\n\n if ( node != null )\n {\n Object node_info = node.getUserObject();\n\n // The selected node is a leaf, so the contained JavaBean will be\n // displayed.\n if ( node.isLeaf() )\n {\n PanelBean bp = (PanelBean) node_info;\n\n try\n {\n // Check if the selected Bean has been instantiated yet. If\n // not, get an instance so that it may be displayed.\n if ( ! bp.isInstantiated() )\n {\n bp.instantiate();\n }\n\n // Add the Bean to the right element of the split pane.\n if ( m_last_panel != null )\n {\n fireBeanUnfocusEvent(m_last_panel);\n }\n\n fireBeanFocusEvent(bp);\n m_last_panel = bp;\n viewer.add(bp.getComponent(), JSplitPane.RIGHT);\n }\n catch (org.vrjuggler.tweek.beans.loader.BeanInstantiationException inst_ex)\n {\n JOptionPane.showMessageDialog(null, inst_ex.getMessage(),\n \"Instantiation Failure\",\n JOptionPane.ERROR_MESSAGE);\n }\n }\n // The selected element is a branch, so display the default panel in\n // the right side of the split pane.\n else\n {\n if ( m_last_panel != null )\n {\n fireBeanUnfocusEvent(m_last_panel);\n m_last_panel = null;\n }\n\n viewer.add(m_default_bean_panel, JSplitPane.RIGHT);\n }\n }\n }\n\n private PanelBean m_last_panel = null;\n }\n\n // ========================================================================\n // Private methods.\n // ========================================================================\n\n /**\n * Initializes the GUI sub-components and the attributes of this component.\n * This method was initially generated by JBuilder and is needed for\n * JBuilder to extract information about the configuration of this GUI\n * component.\n */\n private void jbInit() throws Exception\n {\n m_default_bean_panel.setBackground(Color.white);\n m_default_bean_panel.setLayout(m_default_bean_panel_layout);\n\n // Put together the BeanTree displaying the JavaBeans.\n m_bean_tree.addTreeSelectionListener(new BeanSelectionListener());\n m_bean_tree.setScrollsOnExpand(true);\n m_bean_tree_pane.getViewport().add(m_bean_tree, null);\n\n m_title_panel_label.setFont(new java.awt.Font(\"Dialog\", 1, 24));\n m_title_panel_label.setForeground(Color.white);\n m_title_panel_label.setText(\"Tweek!\");\n m_title_panel.setBackground(Color.black);\n m_title_panel.setLayout(m_title_panel_layout);\n m_title_panel.add(m_title_panel_label, null);\n\n m_default_bean_panel.add(m_title_panel, BorderLayout.NORTH);\n\n viewer.add(m_default_bean_panel, JSplitPane.RIGHT);\n viewer.add(m_bean_tree_pane, JSplitPane.LEFT);\n }\n\n // ========================================================================\n // Private data members.\n // ========================================================================\n\n private JSplitPane viewer = new JSplitPane();\n\n // The tree holding the bean hierarchy.\n private JScrollPane m_bean_tree_pane = new JScrollPane();\n private BeanTree m_bean_tree = null;\n\n // Contents of the default panel shown in the right side of the split pane.\n private JPanel m_default_bean_panel = new JPanel();\n private BorderLayout m_default_bean_panel_layout = new BorderLayout();\n private JPanel m_title_panel = new JPanel();\n private FlowLayout m_title_panel_layout = new FlowLayout();\n private JLabel m_title_panel_label = new JLabel();\n}\n"},"new_file":{"kind":"string","value":"modules/tweek/java/org/vrjuggler/tweek/treeviewer/BeanTreeViewer.java"},"old_contents":{"kind":"string","value":"/***************** ****************\n * Tweek\n *\n * -----------------------------------------------------------------\n * File: $RCSfile$\n * Date modified: $Date$\n * Version: $Revision$\n * -----------------------------------------------------------------\n ***************** *****************/\n\n/*************** **************\n *\n * VR Juggler is (C) Copyright 1998, 1999, 2000, 2001 by Iowa State University\n *\n * Original Authors:\n * Allen Bierbaum, Christopher Just,\n * Patrick Hartling, Kevin Meinert,\n * Carolina Cruz-Neira, Albert Baker\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n *\n *************** ***************/\n\npackage org.vrjuggler.tweek.treeviewer;\n\nimport java.awt.*;\nimport javax.swing.*;\nimport javax.swing.event.TreeSelectionEvent;\nimport javax.swing.event.TreeSelectionListener;\nimport javax.swing.tree.*;\nimport org.vrjuggler.tweek.beans.*;\n\n\n/**\n *\n * @version $Revision$\n *\n * @see org.vrjuggler.tweek.treeviewer.BeanTree\n */\npublic class BeanTreeViewer extends DefaultBeanModelViewer\n{\n // ========================================================================\n // Public methods.\n // ========================================================================\n\n /**\n * Constructs the split pane. This just fills in panels for the left and\n * right sides of this JSplitPane. For the left pane, a blank JPanel is\n * For the right pane, the default (no-Bean-selected) JPanel is shown.\n * used. This is done primarily to keep the GUI from looking nasty before\n * the full GUI initialization is done.\n */\n public BeanTreeViewer ()\n {\n JPanel empty_left = new JPanel();\n empty_left.setBackground(Color.white);\n empty_left.setMinimumSize(new Dimension(125, 200));\n viewer.add(empty_left, JSplitPane.LEFT);\n viewer.add(m_default_bean_panel, JSplitPane.RIGHT);\n viewer.setDividerSize(5);\n }\n\n public void initDataModel (BeanTreeModel model)\n {\n m_bean_tree = new BeanTree(model);\n }\n\n /**\n * Component initialization.\n */\n public void initGUI ()\n {\n try\n {\n jbInit();\n }\n catch(Exception e)\n {\n e.printStackTrace();\n }\n }\n\n public void refreshDataModel (BeanTreeModel model)\n {\n /* Nothing to do. */ ;\n }\n\n public JComponent getViewer ()\n {\n return viewer;\n }\n\n /**\n * Extension of javax.swing.event.TreeSelectionListener used with BeanTree\n * objects. This class assumes that the BeanTree leaves contain instances\n * of PanelBean objects. It knows how to instantiate JavaBeans and thus\n * allows delayed loading of Beans. In addition, it requires that a\n * JSplitPane is used as the container for the BeanTree where the BeanTree\n * is the left member of the split pane. The Beans are displayed in the\n * right member.\n */\n protected class BeanSelectionListener implements TreeSelectionListener\n {\n /**\n * Implementation of the TreeSelectionListener.valueChanged() method.\n * This is called when the user clicks on an element of the BeanTree\n * object associated with this object. If the element is a branch, the\n * default panel is displayed.\n */\n public void valueChanged (TreeSelectionEvent e)\n {\n DefaultMutableTreeNode node =\n (DefaultMutableTreeNode) m_bean_tree.getLastSelectedPathComponent();\n\n if ( node != null )\n {\n Object node_info = node.getUserObject();\n\n // The selected node is a leaf, so the contained JavaBean will be\n // displayed.\n if ( node.isLeaf() )\n {\n PanelBean bp = (PanelBean) node_info;\n\n try\n {\n // Check if the selected Bean has been instantiated yet. If\n // not, get an instance so that it may be displayed.\n if ( ! bp.isInstantiated() )\n {\n bp.instantiate();\n }\n\n // Add the Bean to the right element of the split pane.\n if ( m_last_panel != null )\n {\n fireBeanUnfocusEvent(m_last_panel);\n }\n\n fireBeanFocusEvent(bp);\n m_last_panel = bp;\n viewer.add(bp.getComponent(), JSplitPane.RIGHT);\n }\n catch (org.vrjuggler.tweek.beans.loader.BeanInstantiationException inst_ex)\n {\n JOptionPane.showMessageDialog(null, inst_ex.getMessage(),\n \"Instantiation Failure\",\n JOptionPane.ERROR_MESSAGE);\n }\n }\n // The selected element is a branch, so display the default panel in\n // the right side of the split pane.\n else\n {\n if ( m_last_panel != null )\n {\n fireBeanUnfocusEvent(m_last_panel);\n m_last_panel = null;\n }\n\n viewer.add(m_default_bean_panel, JSplitPane.RIGHT);\n }\n }\n }\n\n private PanelBean m_last_panel = null;\n }\n\n // ========================================================================\n // Private methods.\n // ========================================================================\n\n /**\n * Initializes the GUI sub-components and the attributes of this component.\n * This method was initially generated by JBuilder and is needed for\n * JBuilder to extract information about the configuration of this GUI\n * component.\n */\n private void jbInit() throws Exception\n {\n m_default_bean_panel.setBackground(Color.white);\n m_default_bean_panel.setLayout(m_default_bean_panel_layout);\n\n // Put together the BeanTree displaying the JavaBeans.\n m_bean_tree.addTreeSelectionListener(new BeanSelectionListener());\n m_bean_tree.setScrollsOnExpand(true);\n m_bean_tree_pane.getViewport().add(m_bean_tree, null);\n\n m_title_panel_label.setFont(new java.awt.Font(\"Dialog\", 1, 24));\n m_title_panel_label.setForeground(Color.white);\n m_title_panel_label.setText(\"Tweek!\");\n m_title_panel.setBackground(Color.black);\n m_title_panel.setLayout(m_title_panel_layout);\n m_title_panel.add(m_title_panel_label, null);\n\n m_default_bean_panel.add(m_title_panel, BorderLayout.NORTH);\n\n viewer.add(m_default_bean_panel, JSplitPane.RIGHT);\n viewer.add(m_bean_tree_pane, JSplitPane.LEFT);\n }\n\n // ========================================================================\n // Private data members.\n // ========================================================================\n\n private JSplitPane viewer = new JSplitPane();\n\n // The tree holding the bean hierarchy.\n private JScrollPane m_bean_tree_pane = new JScrollPane();\n private BeanTree m_bean_tree = null;\n\n // Contents of the default panel shown in the right side of the split pane.\n private JPanel m_default_bean_panel = new JPanel();\n private BorderLayout m_default_bean_panel_layout = new BorderLayout();\n private JPanel m_title_panel = new JPanel();\n private FlowLayout m_title_panel_layout = new FlowLayout();\n private JLabel m_title_panel_label = new JLabel();\n}\n"},"message":{"kind":"string","value":"SF Bug#:\t484422\n\nFixed the bug wherein the BeanTreeViewer's JTree would not refresh\nproperly if no Beans were loaded at initialization. The cause of this\nis not entirely clear to me yet, but this simple change seems to fix\nit. It may be worthwhile to revisit this in the future in case this\nchange is not the most optimal solution.\n\n\ngit-svn-id: 769d22dfa2d22aad706b9a451492fb87c0735f19@7253 08b38cba-cd3b-11de-854e-f91c5b6e4272\n"},"old_file":{"kind":"string","value":"modules/tweek/java/org/vrjuggler/tweek/treeviewer/BeanTreeViewer.java"},"subject":{"kind":"string","value":"SF Bug#:\t484422"},"git_diff":{"kind":"string","value":"odules/tweek/java/org/vrjuggler/tweek/treeviewer/BeanTreeViewer.java\n \n public void refreshDataModel (BeanTreeModel model)\n {\n /* Nothing to do. */ ;\n model.nodeStructureChanged((TreeNode) model.getRoot());\n }\n \n public JComponent getViewer ()"}}},{"rowIdx":1960,"cells":{"lang":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"239619b259f271095ed2f6dcd173ce05f2e43a68"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"UKHomeOffice/removals_integration,UKHomeOffice/removals_integration"},"new_contents":{"kind":"string","value":"\"use strict\";\nvar model = rewire('../../api/models/Movement');\nvar Promise = require('bluebird');\n\ndescribe('INTEGRATION MovementModel', () => {\n it('should get the fixtures', () =>\n expect(Movement.find()).to.eventually.have.length(5)\n );\n});\n\ndescribe('UNIT MovementModel', () => {\n describe('setNormalisedRelationships', () => {\n var method = Promise.promisify(model.__get__('setNormalisedRelationships'));\n\n var record = {\n active_male_centre: 'fooo',\n active_female_centre: 'rra',\n centre: 123,\n active: true\n };\n\n it('should delete the records relationships if its not active', () => {\n var record = {\n active_male_centre: 'fooo',\n active_female_centre: 'rra',\n active: false\n };\n return method(record)\n .then(() =>\n expect(record).to.eql({\n active: false\n })\n );\n });\n\n it('should set the correct normalised values for a male detainee', () => {\n var Detainee = {findOne: sinon.stub().resolves({gender: \"male\"})};\n model.__set__('Detainee', Detainee);\n return method(record)\n .then(() =>\n expect(record.active_male_centre).to.eql(123)\n )\n });\n\n it('should set the correct normalised values for a female detainee', () => {\n var Detainee = {findOne: sinon.stub().resolves({gender: \"female\"})};\n model.__set__('Detainee', Detainee);\n return method(record)\n .then(() =>\n expect(record.active_female_centre).to.eql(123)\n )\n });\n });\n})\n"},"new_file":{"kind":"string","value":"test/unit/models/Movement.test.js"},"old_contents":{"kind":"string","value":"\"use strict\";\n\ndescribe('INTEGRATION MovementModel', () => {\n it('should get the fixtures', () =>\n expect(Movement.find()).to.eventually.have.length(5)\n );\n});\n"},"message":{"kind":"string","value":"unit test Movement.setNormalisedRelationships with rewire\n"},"old_file":{"kind":"string","value":"test/unit/models/Movement.test.js"},"subject":{"kind":"string","value":"unit test Movement.setNormalisedRelationships with rewire"},"git_diff":{"kind":"string","value":"est/unit/models/Movement.test.js\n \"use strict\";\nvar model = rewire('../../api/models/Movement');\nvar Promise = require('bluebird');\n \n describe('INTEGRATION MovementModel', () => {\n it('should get the fixtures', () =>\n expect(Movement.find()).to.eventually.have.length(5)\n );\n });\n\ndescribe('UNIT MovementModel', () => {\n describe('setNormalisedRelationships', () => {\n var method = Promise.promisify(model.__get__('setNormalisedRelationships'));\n\n var record = {\n active_male_centre: 'fooo',\n active_female_centre: 'rra',\n centre: 123,\n active: true\n };\n\n it('should delete the records relationships if its not active', () => {\n var record = {\n active_male_centre: 'fooo',\n active_female_centre: 'rra',\n active: false\n };\n return method(record)\n .then(() =>\n expect(record).to.eql({\n active: false\n })\n );\n });\n\n it('should set the correct normalised values for a male detainee', () => {\n var Detainee = {findOne: sinon.stub().resolves({gender: \"male\"})};\n model.__set__('Detainee', Detainee);\n return method(record)\n .then(() =>\n expect(record.active_male_centre).to.eql(123)\n )\n });\n\n it('should set the correct normalised values for a female detainee', () => {\n var Detainee = {findOne: sinon.stub().resolves({gender: \"female\"})};\n model.__set__('Detainee', Detainee);\n return method(record)\n .then(() =>\n expect(record.active_female_centre).to.eql(123)\n )\n });\n });\n})"}}},{"rowIdx":1961,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"5936e4f3a8ded2d51546875562daaa200a4603ad"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"masaki-yamakawa/geode,jdeppe-pivotal/geode,smgoller/geode,smgoller/geode,jdeppe-pivotal/geode,jdeppe-pivotal/geode,jdeppe-pivotal/geode,jdeppe-pivotal/geode,masaki-yamakawa/geode,jdeppe-pivotal/geode,smgoller/geode,masaki-yamakawa/geode,smgoller/geode,smgoller/geode,smgoller/geode,masaki-yamakawa/geode,smgoller/geode,masaki-yamakawa/geode,masaki-yamakawa/geode,jdeppe-pivotal/geode,masaki-yamakawa/geode"},"new_contents":{"kind":"string","value":"/*\n * Licensed to the Apache Software Foundation (ASF) under one or more contributor license\n * agreements. See the NOTICE file distributed with this work for additional information regarding\n * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance with the License. You may obtain a\n * 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 distributed under the License\n * is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express\n * or implied. See the License for the specific language governing permissions and limitations under\n * the License.\n */\npackage org.apache.geode.internal.cache;\n\nimport static java.util.Arrays.asList;\nimport static java.util.Collections.emptySet;\nimport static java.util.concurrent.TimeUnit.MILLISECONDS;\nimport static org.apache.geode.cache.Region.SEPARATOR;\nimport static org.apache.geode.cache.RegionShortcut.PARTITION;\nimport static org.apache.geode.cache.RegionShortcut.PARTITION_PERSISTENT;\nimport static org.apache.geode.cache.RegionShortcut.REPLICATE;\nimport static org.apache.geode.cache.client.PoolFactory.DEFAULT_READ_TIMEOUT;\nimport static org.apache.geode.cache.client.PoolFactory.DEFAULT_SUBSCRIPTION_ACK_INTERVAL;\nimport static org.apache.geode.cache.client.PoolFactory.DEFAULT_SUBSCRIPTION_ENABLED;\nimport static org.apache.geode.cache.client.PoolFactory.DEFAULT_SUBSCRIPTION_REDUNDANCY;\nimport static org.apache.geode.distributed.ConfigurationProperties.LOCATORS;\nimport static org.apache.geode.internal.cache.AbstractCacheServer.MAXIMUM_TIME_BETWEEN_PINGS_PROPERTY;\nimport static org.apache.geode.test.awaitility.GeodeAwaitility.await;\nimport static org.apache.geode.test.awaitility.GeodeAwaitility.getTimeout;\nimport static org.apache.geode.test.dunit.IgnoredException.addIgnoredException;\nimport static org.apache.geode.test.dunit.VM.getController;\nimport static org.apache.geode.test.dunit.VM.getHostName;\nimport static org.apache.geode.test.dunit.VM.getVM;\nimport static org.apache.geode.test.dunit.VM.getVMId;\nimport static org.apache.geode.test.dunit.rules.DistributedRule.getDistributedSystemProperties;\nimport static org.apache.geode.test.dunit.rules.DistributedRule.getLocators;\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.assertj.core.api.Assertions.catchThrowable;\nimport static org.mockito.Mockito.mock;\n\nimport java.io.DataInput;\nimport java.io.DataOutput;\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.Serializable;\nimport java.net.ConnectException;\nimport java.net.SocketException;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.Set;\nimport java.util.concurrent.CountDownLatch;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.concurrent.atomic.AtomicReference;\nimport java.util.function.Consumer;\n\nimport junitparams.JUnitParamsRunner;\nimport junitparams.Parameters;\nimport junitparams.naming.TestCaseName;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.experimental.categories.Category;\nimport org.junit.runner.RunWith;\n\nimport org.apache.geode.DataSerializable;\nimport org.apache.geode.DataSerializer;\nimport org.apache.geode.cache.CacheFactory;\nimport org.apache.geode.cache.CacheWriterException;\nimport org.apache.geode.cache.DataPolicy;\nimport org.apache.geode.cache.DiskStore;\nimport org.apache.geode.cache.EntryEvent;\nimport org.apache.geode.cache.LowMemoryException;\nimport org.apache.geode.cache.Operation;\nimport org.apache.geode.cache.PartitionAttributesFactory;\nimport org.apache.geode.cache.Region;\nimport org.apache.geode.cache.Region.Entry;\nimport org.apache.geode.cache.RegionDestroyedException;\nimport org.apache.geode.cache.RegionFactory;\nimport org.apache.geode.cache.RegionShortcut;\nimport org.apache.geode.cache.Scope;\nimport org.apache.geode.cache.TimeoutException;\nimport org.apache.geode.cache.client.ClientCacheFactory;\nimport org.apache.geode.cache.client.ClientRegionFactory;\nimport org.apache.geode.cache.client.ClientRegionShortcut;\nimport org.apache.geode.cache.client.PoolFactory;\nimport org.apache.geode.cache.client.PoolManager;\nimport org.apache.geode.cache.client.ServerConnectivityException;\nimport org.apache.geode.cache.client.ServerOperationException;\nimport org.apache.geode.cache.client.internal.InternalClientCache;\nimport org.apache.geode.cache.persistence.PartitionOfflineException;\nimport org.apache.geode.cache.query.CqAttributes;\nimport org.apache.geode.cache.query.CqAttributesFactory;\nimport org.apache.geode.cache.query.CqEvent;\nimport org.apache.geode.cache.query.CqListener;\nimport org.apache.geode.cache.query.CqQuery;\nimport org.apache.geode.cache.query.SelectResults;\nimport org.apache.geode.cache.query.Struct;\nimport org.apache.geode.cache.server.CacheServer;\nimport org.apache.geode.cache.util.CacheListenerAdapter;\nimport org.apache.geode.cache.util.CacheWriterAdapter;\nimport org.apache.geode.distributed.DistributedSystemDisconnectedException;\nimport org.apache.geode.distributed.OplogCancelledException;\nimport org.apache.geode.internal.cache.persistence.DiskRecoveryStore;\nimport org.apache.geode.internal.cache.tier.sockets.VersionedObjectList;\nimport org.apache.geode.internal.cache.versions.VersionTag;\nimport org.apache.geode.test.dunit.AsyncInvocation;\nimport org.apache.geode.test.dunit.VM;\nimport org.apache.geode.test.dunit.rules.DistributedExecutorServiceRule;\nimport org.apache.geode.test.dunit.rules.DistributedRestoreSystemProperties;\nimport org.apache.geode.test.dunit.rules.DistributedRule;\nimport org.apache.geode.test.junit.categories.ClientServerTest;\nimport org.apache.geode.test.junit.categories.ClientSubscriptionTest;\nimport org.apache.geode.test.junit.rules.serializable.SerializableTemporaryFolder;\n\n/**\n * Tests putAll for c/s. Also tests removeAll\n *\n * @since GemFire 5.0.23\n */\n@Category({ClientServerTest.class, ClientSubscriptionTest.class})\n@RunWith(JUnitParamsRunner.class)\n@SuppressWarnings(\"serial,NumericCastThatLosesPrecision\")\npublic class PutAllClientServerDistributedTest implements Serializable {\n\n private static final long TIMEOUT_MILLIS_LONG = getTimeout().toMillis();\n private static final int TIMEOUT_MILLIS_INTEGER = (int) TIMEOUT_MILLIS_LONG;\n private static final String TIMEOUT_MILLIS_STRING = String.valueOf(TIMEOUT_MILLIS_LONG);\n\n private static final int ONE_HUNDRED = 100;\n private static final int ONE_THOUSAND = 1000;\n private static final InternalCache DUMMY_CACHE = mock(InternalCache.class);\n private static final InternalClientCache DUMMY_CLIENT_CACHE = mock(InternalClientCache.class);\n private static final Counter DUMMY_COUNTER = new Counter(\"dummy\");\n private static final Action EMPTY_INTEGER_ACTION =\n new Action<>(null, emptyConsumer());\n\n private static final AtomicReference VALUE = new AtomicReference<>();\n private static final AtomicReference LATCH = new AtomicReference<>();\n private static final AtomicReference BEFORE = new AtomicReference<>();\n private static final AtomicReference AFTER = new AtomicReference<>();\n private static final AtomicReference COUNTER = new AtomicReference<>();\n\n private static final AtomicReference CACHE = new AtomicReference<>();\n private static final AtomicReference CLIENT_CACHE = new AtomicReference<>();\n private static final AtomicReference DISK_DIR = new AtomicReference<>();\n\n private String regionName;\n private String hostName;\n private String poolName;\n private String diskStoreName;\n private String keyPrefix;\n private String locators;\n\n private VM server1;\n private VM server2;\n private VM client1;\n private VM client2;\n\n @Rule\n public DistributedRule distributedRule = new DistributedRule();\n @Rule\n public DistributedExecutorServiceRule executorServiceRule = new DistributedExecutorServiceRule();\n @Rule\n public DistributedRestoreSystemProperties restoreProps = new DistributedRestoreSystemProperties();\n @Rule\n public SerializableTemporaryFolder temporaryFolder = new SerializableTemporaryFolder();\n\n @Before\n public void setUp() {\n regionName = getClass().getSimpleName();\n hostName = getHostName();\n poolName = \"testPool\";\n diskStoreName = \"ds1\";\n keyPrefix = \"prefix-\";\n locators = getLocators();\n\n server1 = getVM(0);\n server2 = getVM(1);\n client1 = getVM(2);\n client2 = getVM(3);\n\n for (VM vm : asList(getController(), client1, client2, server1, server2)) {\n vm.invoke(() -> {\n VALUE.set(null);\n COUNTER.set(null);\n LATCH.set(new CountDownLatch(0));\n BEFORE.set(new CountDownLatch(0));\n AFTER.set(new CountDownLatch(0));\n CACHE.set(DUMMY_CACHE);\n CLIENT_CACHE.set(DUMMY_CLIENT_CACHE);\n DISK_DIR.set(temporaryFolder.newFolder(\"diskDir-\" + getVMId()).getAbsoluteFile());\n System.setProperty(MAXIMUM_TIME_BETWEEN_PINGS_PROPERTY, TIMEOUT_MILLIS_STRING);\n });\n }\n\n addIgnoredException(ConnectException.class);\n addIgnoredException(PutAllPartialResultException.class);\n addIgnoredException(RegionDestroyedException.class);\n addIgnoredException(ServerConnectivityException.class);\n addIgnoredException(SocketException.class);\n addIgnoredException(\"Broken pipe\");\n addIgnoredException(\"Connection reset\");\n addIgnoredException(\"Unexpected IOException\");\n }\n\n @After\n public void tearDown() {\n for (VM vm : asList(getController(), client1, client2, server1, server2)) {\n vm.invoke(() -> {\n countDown(LATCH);\n countDown(BEFORE);\n countDown(AFTER);\n closeClientCache();\n closeCache();\n PoolManager.close();\n DISK_DIR.set(null);\n });\n }\n }\n\n /**\n * Tests putAll to one server.\n */\n @Test\n public void testOneServer() throws Exception {\n int serverPort = server1.invoke(() -> new ServerBuilder()\n .regionShortcut(REPLICATE)\n .create());\n\n client1.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort)\n .subscriptionAckInterval()\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n client2.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort)\n .subscriptionAckInterval()\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n region.registerInterest(\"ALL_KEYS\");\n });\n\n client1.invoke(() -> {\n getClientCache()\n .createClientRegionFactory(ClientRegionShortcut.LOCAL)\n .create(\"localsave\");\n\n Region region = getClientCache().getRegion(regionName);\n doPutAll(region, \"key-\", ONE_HUNDRED);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n });\n\n client1.invoke(() -> {\n BEFORE.set(new CountDownLatch(1));\n AFTER.set(new CountDownLatch(1));\n });\n\n AsyncInvocation createCqInClient1 = client1.invokeAsync(() -> {\n // create a CQ for key 10-20\n Region localSaveRegion = getClientCache().getRegion(\"localsave\");\n\n CqAttributesFactory cqAttributesFactory = new CqAttributesFactory();\n cqAttributesFactory.addCqListener(new CountingCqListener<>(localSaveRegion));\n CqAttributes cqAttributes = cqAttributesFactory.create();\n\n String cqName = \"EOInfoTracker\";\n String query = String.join(\" \",\n \"SELECT ALL * FROM \" + SEPARATOR + regionName + \" ii\",\n \"WHERE ii.getTicker() >= '10' and ii.getTicker() < '20'\");\n\n CqQuery cqQuery = getClientCache().getQueryService().newCq(cqName, query, cqAttributes);\n\n SelectResults results = cqQuery.executeWithInitialResults();\n List resultsAsList = results.asList();\n for (int i = 0; i < resultsAsList.size(); i++) {\n Struct struct = resultsAsList.get(i);\n TickerData tickerData = (TickerData) struct.get(\"value\");\n localSaveRegion.put(\"key-\" + i, tickerData);\n }\n\n countDown(BEFORE);\n awaitLatch(AFTER);\n\n cqQuery.close();\n });\n\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"key-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n }\n });\n\n // verify CQ is ready\n client1.invoke(() -> {\n awaitLatch(BEFORE);\n\n Region localSaveRegion = getClientCache().getRegion(\"localsave\");\n await().untilAsserted(() -> assertThat(localSaveRegion.size()).isGreaterThan(0));\n });\n\n // verify registerInterest result at client2\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.size()).isEqualTo(ONE_HUNDRED));\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"key-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n }\n\n // then do update for key 10-20 to trigger CQ at server2\n // destroy key 10-14 to simulate create/update mix case\n region.removeAll(asList(\"key-10\", \"key-11\", \"key-12\", \"key-13\", \"key-14\"));\n assertThat(region.get(\"key-10\")).isNull();\n assertThat(region.get(\"key-11\")).isNull();\n assertThat(region.get(\"key-12\")).isNull();\n assertThat(region.get(\"key-13\")).isNull();\n assertThat(region.get(\"key-14\")).isNull();\n });\n\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n Map map = new LinkedHashMap<>();\n for (int i = 10; i < 20; i++) {\n map.put(\"key-\" + i, new TickerData(i * 10));\n }\n region.putAll(map);\n });\n\n // verify CQ result at client1\n client1.invoke(() -> {\n Region localSaveRegion = getClientCache().getRegion(\"localsave\");\n\n for (int i = 10; i < 20; i++) {\n String key = \"key-\" + i;\n int price = i * 10;\n await().untilAsserted(() -> {\n TickerData tickerData = localSaveRegion.get(key);\n assertThat(tickerData.getPrice()).isEqualTo(price);\n });\n }\n\n countDown(AFTER);\n });\n\n createCqInClient1.await();\n\n // Test Exception handling\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n\n Throwable thrown = catchThrowable(() -> region.putAll(null));\n assertThat(thrown).isInstanceOf(NullPointerException.class);\n\n region.localDestroyRegion();\n\n Map puts = new LinkedHashMap<>();\n for (int i = 1; i < 21; i++) {\n puts.put(\"key-\" + i, null);\n }\n\n thrown = catchThrowable(() -> region.putAll(puts));\n assertThat(thrown).isInstanceOf(RegionDestroyedException.class);\n\n thrown = catchThrowable(() -> region.removeAll(asList(\"key-10\", \"key-11\")));\n assertThat(thrown).isInstanceOf(RegionDestroyedException.class);\n });\n }\n\n /**\n * Tests putAll afterUpdate event contained oldValue.\n */\n @Test\n public void testOldValueInEvent() {\n // set notifyBySubscription=false to test local-invalidates\n int serverPort1 = server1.invoke(() -> new ServerBuilder()\n .regionShortcut(REPLICATE)\n .create());\n int serverPort2 = server2.invoke(() -> new ServerBuilder()\n .regionShortcut(REPLICATE)\n .create());\n\n client1.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort1)\n .subscriptionAckInterval()\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n client2.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort2)\n .subscriptionAckInterval()\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n\n client2.invoke(() -> {\n LATCH.set(new CountDownLatch(1));\n\n Region region = getClientCache().getRegion(regionName);\n region.getAttributesMutator()\n .addCacheListener(new ActionCacheListener<>(new Action<>(Operation.UPDATE,\n event -> {\n assertThat(event.getOldValue()).isNotNull();\n VALUE.set(event.getOldValue());\n countDown(LATCH);\n })));\n region.registerInterest(\"ALL_KEYS\");\n });\n\n client1.invoke(() -> {\n LATCH.set(new CountDownLatch(1));\n\n Region region = getClientCache().getRegion(regionName);\n region.getAttributesMutator()\n .addCacheListener(new ActionCacheListener<>(new Action<>(Operation.UPDATE,\n event -> {\n assertThat(event.getOldValue()).isNotNull();\n VALUE.set(event.getOldValue());\n countDown(LATCH);\n })));\n\n // create keys\n doPutAll(region, keyPrefix, ONE_HUNDRED);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n\n // update keys\n doPutAll(region, keyPrefix, ONE_HUNDRED);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n });\n\n // the local PUTALL_UPDATE event should contain old value\n client1.invoke(() -> {\n awaitLatch(LATCH);\n assertThat(VALUE.get()).isInstanceOf(TickerData.class);\n });\n\n client2.invoke(() -> {\n awaitLatch(LATCH);\n assertThat(VALUE.get()).isInstanceOf(TickerData.class);\n });\n }\n\n /**\n * Create PR without redundancy on 2 servers with lucene index. Feed some key s. From a client, do\n * removeAll on keys in server1. During the removeAll, restart server1 and trigger the removeAll\n * to retry. The retried removeAll should return the version tag of tombstones. Do removeAll again\n * on the same key, it should get the version tag again.\n */\n @Test\n public void shouldReturnVersionTagOfTombstoneVersionWhenRemoveAllRetried() {\n // set notifyBySubscription=false to test local-invalidates\n int serverPort1 = server1.invoke(() -> new ServerBuilder()\n .regionShortcut(PARTITION_PERSISTENT)\n .create());\n\n client1.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort1)\n .create());\n\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n doPutAll(region, \"key-\", ONE_HUNDRED);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n });\n\n // verify cache server 1, its data is from client\n server1.invoke(() -> {\n assertThat(getCache().getRegion(regionName).size()).isEqualTo(ONE_HUNDRED);\n });\n\n VersionedObjectList versions = client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n VersionedObjectList versionsToReturn = doRemoveAll(region, \"key-\", ONE_HUNDRED);\n assertThat(region.size()).isZero();\n return versionsToReturn;\n });\n\n // client1 removeAll again\n VersionedObjectList versionsAfterRetry = client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n VersionedObjectList versionsToReturn = doRemoveAll(region, \"key-\", ONE_HUNDRED);\n assertThat(region.size()).isZero();\n return versionsToReturn;\n });\n\n // noinspection rawtypes\n List versionTags = versions.getVersionTags();\n // noinspection rawtypes\n List versionTagsAfterRetry = versionsAfterRetry.getVersionTags();\n assertThat(versionTags)\n .hasSameSizeAs(versionTagsAfterRetry)\n .containsAll(versionTagsAfterRetry);\n }\n\n /**\n * Tests putAll and removeAll to 2 servers. Use Case: 1) putAll from a single-threaded client to a\n * replicated region 2) putAll from a multi-threaded client to a replicated region 3)\n */\n @Test\n public void test2Server() throws Exception {\n int serverPort1 = server1.invoke(() -> new ServerBuilder()\n .regionShortcut(REPLICATE)\n .create());\n int serverPort2 = server2.invoke(() -> new ServerBuilder()\n .regionShortcut(REPLICATE)\n .create());\n\n client1.invoke(() -> new ClientBuilder()\n .registerInterest(true)\n .serverPorts(serverPort1)\n .subscriptionAckInterval()\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n client2.invoke(() -> new ClientBuilder()\n .registerInterest(true)\n .serverPorts(serverPort2)\n .subscriptionAckInterval()\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n\n // client1 putAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n doPutAll(region, \"key-\", ONE_HUNDRED);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"key-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n }\n });\n\n // verify cache server 1\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator().setCacheWriter(new CountingCacheWriter<>());\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"key-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n }\n });\n\n // verify cache server 2\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator().setCacheWriter(new CountingCacheWriter<>());\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"key-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n }\n });\n\n // client2 verify putAll\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.size()).isEqualTo(ONE_HUNDRED));\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n Entry regionEntry = region.getEntry(\"key-\" + i);\n assertThat(regionEntry.getValue()).isNull();\n }\n });\n\n // client1 removeAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n doRemoveAll(region, \"key-\", ONE_HUNDRED);\n assertThat(region.size()).isZero();\n });\n\n // verify removeAll cache server 1\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n assertThat(region.size()).isZero();\n\n CountingCacheWriter countingCacheWriter =\n (CountingCacheWriter) region.getAttributes().getCacheWriter();\n assertThat(countingCacheWriter.getDestroys()).isEqualTo(ONE_HUNDRED);\n });\n\n // verify removeAll cache server 2\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n assertThat(region.size()).isZero();\n\n CountingCacheWriter countingCacheWriter =\n (CountingCacheWriter) region.getAttributes().getCacheWriter();\n // beforeDestroys are only triggered at server1 since removeAll is submitted from client1\n assertThat(countingCacheWriter.getDestroys()).isZero();\n });\n\n // client2 verify removeAll\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.size()).isZero());\n });\n\n // async putAll1 from client1\n AsyncInvocation putAll1InClient1 = client1.invokeAsync(\n () -> doPutAll(getClientCache().getRegion(regionName), \"async1key-\", ONE_HUNDRED));\n\n // async putAll2 from client1\n AsyncInvocation putAll2InClient1 = client1.invokeAsync(\n () -> doPutAll(getClientCache().getRegion(regionName), \"async2key-\", ONE_HUNDRED));\n\n putAll1InClient1.await();\n putAll2InClient1.await();\n\n // verify client 1 for async keys\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED * 2);\n\n long timeStamp1 = 0;\n long timeStamp2 = 0;\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"async1key-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n assertThat(tickerData.getTimeStamp()).isGreaterThanOrEqualTo(timeStamp1);\n timeStamp1 = tickerData.getTimeStamp();\n\n tickerData = region.getEntry(\"async2key-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n assertThat(tickerData.getTimeStamp()).isGreaterThanOrEqualTo(timeStamp2);\n timeStamp2 = tickerData.getTimeStamp();\n }\n });\n\n // verify cache server 1 for async keys\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED * 2);\n\n long timeStamp1 = 0;\n long timeStamp2 = 0;\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"async1key-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n assertThat(tickerData.getTimeStamp()).isGreaterThanOrEqualTo(timeStamp1);\n timeStamp1 = tickerData.getTimeStamp();\n\n tickerData = region.getEntry(\"async2key-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n assertThat(tickerData.getTimeStamp()).isGreaterThanOrEqualTo(timeStamp2);\n timeStamp2 = tickerData.getTimeStamp();\n }\n });\n\n // verify cache server 2 for async keys\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED * 2);\n\n long timeStamp1 = 0;\n long timeStamp2 = 0;\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"async1key-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n assertThat(tickerData.getTimeStamp()).isGreaterThanOrEqualTo(timeStamp1);\n timeStamp1 = tickerData.getTimeStamp();\n\n tickerData = region.getEntry(\"async2key-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n assertThat(tickerData.getTimeStamp()).isGreaterThanOrEqualTo(timeStamp2);\n timeStamp2 = tickerData.getTimeStamp();\n }\n });\n\n // client2 verify async putAll\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.size()).isEqualTo(ONE_HUNDRED * 2));\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n Entry regionEntry = region.getEntry(\"async1key-\" + i);\n assertThat(regionEntry.getValue()).isNull();\n }\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n Entry regionEntry = region.getEntry(\"async2key-\" + i);\n assertThat(regionEntry.getValue()).isNull();\n }\n });\n\n // async removeAll1 from client1\n AsyncInvocation removeAll1InClient1 = client1.invokeAsync(() -> {\n doRemoveAll(getClientCache().getRegion(regionName), \"async1key-\", ONE_HUNDRED);\n });\n\n // async removeAll2 from client1\n AsyncInvocation removeAll2InClient1 = client1.invokeAsync(() -> {\n doRemoveAll(getClientCache().getRegion(regionName), \"async2key-\", ONE_HUNDRED);\n });\n\n removeAll1InClient1.await();\n removeAll2InClient1.await();\n\n // client1 removeAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n doRemoveAll(region, \"key-\", ONE_HUNDRED);\n assertThat(region.size()).isZero();\n });\n\n // verify async removeAll cache server 1\n server1.invoke(() -> {\n assertThat(getCache().getRegion(regionName).size()).isZero();\n });\n\n // verify async removeAll cache server 2\n server2.invoke(() -> {\n assertThat(getCache().getRegion(regionName).size()).isZero();\n });\n\n // client2 verify async removeAll\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.size()).isZero());\n });\n\n // server1 execute P2P putAll\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n doPutAll(region, \"p2pkey-\", ONE_HUNDRED);\n\n long timeStamp = 0;\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"p2pkey-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n assertThat(tickerData.getTimeStamp()).isGreaterThanOrEqualTo(timeStamp);\n timeStamp = tickerData.getTimeStamp();\n }\n });\n\n // verify cache server 2 for p2p keys\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n\n long timeStamp = 0;\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"p2pkey-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n assertThat(tickerData.getTimeStamp()).isGreaterThanOrEqualTo(timeStamp);\n timeStamp = tickerData.getTimeStamp();\n }\n });\n\n // client2 verify p2p putAll\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.size()).isEqualTo(ONE_HUNDRED));\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n Entry regionEntry = region.getEntry(\"p2pkey-\" + i);\n assertThat(regionEntry.getValue()).isNull();\n }\n });\n\n // client1 verify p2p putAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.size()).isEqualTo(ONE_HUNDRED));\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n Entry regionEntry = region.getEntry(\"p2pkey-\" + i);\n assertThat(regionEntry.getValue()).isNull();\n }\n });\n\n // server1 execute P2P removeAll\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n doRemoveAll(region, \"p2pkey-\", ONE_HUNDRED);\n assertThat(region.size()).isZero();\n });\n\n // verify p2p removeAll cache server 2\n server2.invoke(() -> {\n assertThat(getCache().getRegion(regionName).size()).isZero();\n });\n\n // client2 verify p2p removeAll\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.size()).isZero());\n });\n\n // client1 verify p2p removeAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.size()).isZero());\n });\n\n // execute putAll on client2 for key 0-10\n client2.invoke(() -> doPutAll(getClientCache().getRegion(regionName), \"key-\", 10));\n\n // verify client1 for local invalidate\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n for (int i = 0; i < 10; i++) {\n String key = \"key-\" + i;\n\n await(\"entry with null value exists for \" + key).until(() -> {\n Entry regionEntry = region.getEntry(key);\n return regionEntry != null && regionEntry.getValue() == null;\n });\n\n // local invalidate will set the value to null\n TickerData tickerData = region.getEntry(\"key-\" + i).getValue();\n assertThat(tickerData).isNull();\n }\n });\n }\n\n @Test\n @Parameters({\"true\", \"false\"})\n @TestCaseName(\"{method}(concurrencyChecksEnabled={0})\")\n public void test2NormalServer(boolean concurrencyChecksEnabled) {\n Properties config = getDistributedSystemProperties();\n config.setProperty(LOCATORS, locators);\n\n // set notifyBySubscription=false to test local-invalidates\n int serverPort1 = server1.invoke(() -> {\n createCache(new CacheFactory(config));\n return createServerRegion(regionName, concurrencyChecksEnabled);\n });\n int serverPort2 = server2.invoke(() -> {\n createCache(new CacheFactory(config));\n return createServerRegion(regionName, concurrencyChecksEnabled);\n });\n\n client1.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort1)\n .create());\n client2.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort2)\n .create());\n\n // test case 1: putAll and removeAll to server1\n\n // client1 add listener and putAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n doPutAll(region, \"case1-\", ONE_HUNDRED);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"case1-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n }\n\n region.put(String.valueOf(ONE_HUNDRED), new TickerData());\n });\n\n // verify cache server 1\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator().setCacheWriter(new CountingCacheWriter<>());\n\n region.localDestroy(String.valueOf(ONE_HUNDRED));\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"case1-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n }\n });\n\n // verify cache server 2\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator().setCacheWriter(new CountingCacheWriter<>());\n // normal policy will not distribute create events\n assertThat(region.size()).isZero();\n });\n\n // client1 removeAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED + 1);\n\n // do removeAll with some keys not exist\n doRemoveAll(region, \"case1-\", ONE_HUNDRED * 2);\n assertThat(region.size()).isEqualTo(1);\n\n region.localDestroy(String.valueOf(ONE_HUNDRED));\n });\n\n // verify removeAll cache server 1\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n assertThat(region.size()).isZero();\n\n CountingCacheWriter countingCacheWriter =\n (CountingCacheWriter) region.getAttributes().getCacheWriter();\n assertThat(countingCacheWriter.getDestroys()).isEqualTo(ONE_HUNDRED);\n });\n\n // verify removeAll cache server 2\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n assertThat(region.size()).isZero();\n\n CountingCacheWriter countingCacheWriter =\n (CountingCacheWriter) region.getAttributes().getCacheWriter();\n // beforeDestroys are only triggered at server1 since the removeAll is submitted from client1\n assertThat(countingCacheWriter.getDestroys()).isZero();\n });\n\n // client2 verify removeAll\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.size()).isZero());\n });\n\n // test case 2: putAll to server1, removeAll to server2\n\n // client1 add listener and putAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n doPutAll(region, \"case2-\", ONE_HUNDRED);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"case2-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n }\n });\n\n // verify cache server 1\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"case2-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n }\n });\n\n // verify cache server 2\n server2.invoke(() -> {\n // normal policy will not distribute create events\n assertThat(getCache().getRegion(regionName).size()).isZero();\n });\n\n // client1 removeAll\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n doRemoveAll(region, \"case2-\", ONE_HUNDRED);\n assertThat(region.size()).isZero();\n });\n\n // verify removeAll cache server 1\n server1.invoke(() -> {\n assertThat(getCache().getRegion(regionName).size()).isEqualTo(100);\n });\n\n // verify removeAll cache server 2\n server2.invoke(() -> {\n assertThat(getCache().getRegion(regionName).size()).isZero();\n });\n\n // client1 verify removeAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.size()).isEqualTo(100));\n doRemoveAll(region, \"case2-\", ONE_HUNDRED);\n });\n\n // test case 3: removeAll a list with duplicated keys\n\n // put 3 keys then removeAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n region.put(\"case3-1\", new TickerData());\n region.put(\"case3-2\", new TickerData());\n region.put(\"case3-3\", new TickerData());\n assertThat(region.size()).isEqualTo(3);\n\n Collection keys = new ArrayList<>();\n keys.add(\"case3-1\");\n keys.add(\"case3-2\");\n keys.add(\"case3-3\");\n keys.add(\"case3-1\");\n region.removeAll(keys);\n assertThat(region.size()).isZero();\n });\n\n // verify cache server 1\n server1.invoke(() -> {\n assertThat(getCache().getRegion(regionName).size()).isZero();\n });\n }\n\n @Test\n @Parameters({\"PARTITION,1\", \"PARTITION,0\", \"REPLICATE,0\"})\n @TestCaseName(\"{method}(isPR={0}, redundantCopies={1})\")\n public void testPRServerRVDuplicatedKeys(RegionShortcut regionShortcut, int redundantCopies) {\n int serverPort1 = server1.invoke(() -> new ServerBuilder()\n .redundantCopies(redundantCopies)\n .regionShortcut(regionShortcut)\n .create());\n int serverPort2 = server2.invoke(() -> new ServerBuilder()\n .redundantCopies(redundantCopies)\n .regionShortcut(regionShortcut)\n .create());\n\n client1.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort1)\n .create());\n client2.invoke(() -> new ClientBuilder()\n .registerInterest(true)\n .serverPorts(serverPort2)\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n\n // client1 add listener and putAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n doPutAll(region, \"key-\", ONE_HUNDRED);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"key-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n }\n });\n\n // test case 3: removeAll a list with duplicated keys\n\n // put 3 keys then removeAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n region.put(\"case3-1\", new TickerData());\n region.put(\"case3-2\", new TickerData());\n region.put(\"case3-3\", new TickerData());\n });\n\n // verify cache server 2\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n\n await().untilAsserted(() -> {\n Entry regionEntry = region.getEntry(\"case3-1\");\n assertThat(regionEntry).isNotNull();\n\n regionEntry = region.getEntry(\"case3-2\");\n assertThat(regionEntry).isNotNull();\n\n regionEntry = region.getEntry(\"case3-3\");\n assertThat(regionEntry).isNotNull();\n });\n });\n\n // put 3 keys then removeAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n\n Collection keys = new ArrayList<>();\n keys.add(\"case3-1\");\n keys.add(\"case3-2\");\n keys.add(\"case3-3\");\n keys.add(\"case3-1\");\n region.removeAll(keys);\n\n Entry regionEntry = region.getEntry(\"case3-1\");\n assertThat(regionEntry).isNull();\n\n regionEntry = region.getEntry(\"case3-2\");\n assertThat(regionEntry).isNull();\n\n regionEntry = region.getEntry(\"case3-3\");\n assertThat(regionEntry).isNull();\n });\n\n // verify cache server 1\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n\n Entry regionEntry = region.getEntry(\"case3-1\");\n assertThat(regionEntry).isNull();\n\n regionEntry = region.getEntry(\"case3-2\");\n assertThat(regionEntry).isNull();\n\n regionEntry = region.getEntry(\"case3-3\");\n assertThat(regionEntry).isNull();\n });\n\n // verify cache server 2\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n\n Entry regionEntry = region.getEntry(\"case3-1\");\n assertThat(regionEntry).isNull();\n\n regionEntry = region.getEntry(\"case3-2\");\n assertThat(regionEntry).isNull();\n\n regionEntry = region.getEntry(\"case3-3\");\n assertThat(regionEntry).isNull();\n });\n\n // verify cache server 2\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n\n await().untilAsserted(() -> {\n Entry regionEntry = region.getEntry(\"case3-1\");\n assertThat(regionEntry).isNull();\n\n regionEntry = region.getEntry(\"case3-2\");\n assertThat(regionEntry).isNull();\n\n regionEntry = region.getEntry(\"case3-3\");\n assertThat(regionEntry).isNull();\n });\n });\n }\n\n /**\n * Bug: Data inconsistency between client/server with HA (Object is missing in client cache)\n *\n *

    \n * This is a known issue for persist region with HA.\n *

      \n *
    • client1 sends putAll key1,key2 to server1\n *
    • server1 applied the key1 locally, but the putAll failed due to CacheClosedException? (HA\n * test).\n *
    • Then client1 will not have key1. But when server1 is restarted, it recovered key1 from\n * persistence.\n *
    • Then data mismatch btw client and server.\n *
    \n *\n *

    \n * There's a known issue which can be improved by changing the test:\n *

      \n *
    • edge_14640 sends a putAll to servers. But the server is shutdown due to HA test. However at\n * that time, the putAll might have put the key into local cache.\n *
    • When the server is restarted, the servers will have the key, other clients will also have\n * the key (due to register interest), but the calling client (i.e. edge_14640) will not have the\n * key, unless it's restarted.\n *
    \n *\n *
    \n   * In above scenario, even changing redundantCopies to 1 will not help. This is the known issue. To improve the test, we should let all the clients restart before doing verification.\n   * How to verify the result falls into above scenario?\n   * 1) errors.txt, the edge_14640 has inconsistent cache compared with server's snapshot.\n   * 2) grep Object_82470 *.log and found the mismatched key is originated from 14640.\n   * 
    \n */\n @Test\n @Parameters({\"true\", \"false\"})\n @TestCaseName(\"{method}(singleHop={0})\")\n public void clientPutAllIsMissingKeyUntilShutdownServerRestarts(boolean singleHop) {\n int serverPort1 = server1.invoke(() -> new ServerBuilder()\n .regionShortcut(PARTITION_PERSISTENT)\n .create());\n server2.invoke(() -> new ServerBuilder()\n .regionShortcut(PARTITION_PERSISTENT)\n .create());\n\n client1.invoke(() -> new ClientBuilder()\n .prSingleHopEnabled(singleHop)\n .serverPorts(serverPort1)\n .create());\n client2.invoke(() -> new ClientBuilder()\n .prSingleHopEnabled(singleHop)\n .serverPorts(serverPort1)\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n\n // client2 add listener\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n region.registerInterest(\"ALL_KEYS\");\n });\n\n // put 3 keys then removeAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n\n // do putAll to create all buckets\n doPutAll(region, \"key-\", ONE_HUNDRED);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n });\n\n server2.invoke(() -> getCache().close());\n\n // putAll from client again\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n\n String message =\n String.format(\"Region %s putAll at server applied partial keys due to exception.\",\n region.getFullPath());\n\n Throwable thrown = catchThrowable(() -> doPutAll(region, keyPrefix, ONE_HUNDRED));\n\n assertThat(thrown)\n .isInstanceOf(ServerOperationException.class)\n .hasMessageContaining(message)\n .getCause()\n .isInstanceOf(PartitionOfflineException.class);\n\n assertThat(region.size()).isEqualTo(ONE_HUNDRED * 3 / 2);\n\n int count = 0;\n for (int i = 0; i < ONE_HUNDRED; i++) {\n VersionTag tag = ((InternalRegion) region).getVersionTag(keyPrefix + i);\n if (tag != null && 1 == tag.getEntryVersion()) {\n count++;\n }\n }\n\n assertThat(count).isEqualTo(ONE_HUNDRED / 2);\n\n message = String.format(\n \"Region %s removeAll at server applied partial keys due to exception.\",\n region.getFullPath());\n\n thrown = catchThrowable(() -> doRemoveAll(region, keyPrefix, ONE_HUNDRED));\n\n assertThat(thrown)\n .isInstanceOf(ServerOperationException.class)\n .hasMessageContaining(message)\n .getCause()\n .isInstanceOf(PartitionOfflineException.class);\n\n // putAll only created 50 entries, removeAll removed them. So 100 entries are all NULL\n for (int i = 0; i < ONE_HUNDRED; i++) {\n Entry regionEntry = region.getEntry(keyPrefix + i);\n assertThat(regionEntry).isNull();\n }\n });\n\n // verify entries from client2\n client2.invoke(() -> await().untilAsserted(() -> {\n Region region = getClientCache().getRegion(regionName);\n for (int i = 0; i < ONE_HUNDRED; i++) {\n Entry regionEntry = region.getEntry(keyPrefix + i);\n assertThat(regionEntry).isNull();\n }\n }));\n }\n\n /**\n * Tests putAll to 2 PR servers.\n */\n @Test\n public void testPRServer() throws Exception {\n // set means to test local-invalidates\n int serverPort1 = server1.invoke(() -> new ServerBuilder()\n .redundantCopies(1)\n .regionShortcut(PARTITION)\n .create());\n int serverPort2 = server2.invoke(() -> new ServerBuilder()\n .redundantCopies(1)\n .regionShortcut(PARTITION)\n .create());\n\n client1.invoke(() -> new ClientBuilder()\n .registerInterest(true)\n .serverPorts(serverPort1)\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n client2.invoke(() -> new ClientBuilder()\n .registerInterest(true)\n .serverPorts(serverPort2)\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n\n // client1 putAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n doPutAll(region, \"key-\", ONE_HUNDRED);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"key-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n }\n });\n\n // verify cache server 1\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator().setCacheWriter(new CountingCacheWriter<>());\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"key-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n }\n });\n\n // verify cache server 2\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator().setCacheWriter(new CountingCacheWriter<>());\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"key-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n }\n });\n\n // verify client2\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.size()).isEqualTo(ONE_HUNDRED));\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n Entry regionEntry = region.getEntry(\"key-\" + i);\n assertThat(regionEntry.getValue()).isNull();\n }\n });\n\n // client1 removeAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n doRemoveAll(region, \"key-\", ONE_HUNDRED);\n assertThat(region.size()).isZero();\n });\n\n // verify removeAll cache server 1\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n assertThat(region.size()).isZero();\n\n CountingCacheWriter countingCacheWriter =\n (CountingCacheWriter) region.getAttributes().getCacheWriter();\n // beforeDestroys are only triggered at primary buckets.\n // server1 and server2 each holds half of buckets\n assertThat(countingCacheWriter.getDestroys()).isEqualTo(ONE_HUNDRED / 2);\n });\n\n // verify removeAll cache server 2\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n assertThat(region.size()).isZero();\n\n CountingCacheWriter countingCacheWriter =\n (CountingCacheWriter) region.getAttributes().getCacheWriter();\n // beforeDestroys are only triggered at primary buckets.\n // server1 and server2 each holds half of buckets\n assertThat(countingCacheWriter.getDestroys()).isEqualTo(ONE_HUNDRED / 2);\n });\n\n // client2 verify removeAll\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.size()).isZero());\n });\n\n // Execute client putAll from multithread client\n\n // async putAll1 from client1\n AsyncInvocation putAll1InClient1 = client1.invokeAsync(\n () -> doPutAll(getClientCache().getRegion(regionName), \"async1key-\", ONE_HUNDRED));\n\n // async putAll2 from client1\n AsyncInvocation putAll2InClient1 = client1.invokeAsync(\n () -> doPutAll(getClientCache().getRegion(regionName), \"async2key-\", ONE_HUNDRED));\n\n putAll1InClient1.await();\n putAll2InClient1.await();\n\n // verify client 1 for async keys\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED * 2);\n\n long timeStamp1 = 0;\n long timeStamp2 = 0;\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"async1key-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n assertThat(tickerData.getTimeStamp()).isGreaterThanOrEqualTo(timeStamp1);\n timeStamp1 = tickerData.getTimeStamp();\n\n tickerData = region.getEntry(\"async2key-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n assertThat(tickerData.getTimeStamp()).isGreaterThanOrEqualTo(timeStamp2);\n timeStamp2 = tickerData.getTimeStamp();\n }\n });\n\n // verify cache server 2 for async keys\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n\n long timeStamp1 = 0;\n long timeStamp2 = 0;\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"async1key-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n assertThat(tickerData.getTimeStamp()).isGreaterThanOrEqualTo(timeStamp1);\n timeStamp1 = tickerData.getTimeStamp();\n\n tickerData = region.getEntry(\"async2key-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n assertThat(tickerData.getTimeStamp()).isGreaterThanOrEqualTo(timeStamp2);\n timeStamp2 = tickerData.getTimeStamp();\n }\n });\n\n // client2 verify async putAll\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.size()).isEqualTo(ONE_HUNDRED * 2));\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n Entry regionEntry = region.getEntry(\"async1key-\" + i);\n assertThat(regionEntry.getValue()).isNull();\n }\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n Entry regionEntry = region.getEntry(\"async2key-\" + i);\n assertThat(regionEntry.getValue()).isNull();\n }\n });\n\n // async removeAll1 from client1\n AsyncInvocation removeAll1InClient1 = client1.invokeAsync(() -> {\n doRemoveAll(getClientCache().getRegion(regionName), \"async1key-\", ONE_HUNDRED);\n });\n\n // async removeAll2 from client1\n AsyncInvocation removeAll2InClient1 = client1.invokeAsync(() -> {\n doRemoveAll(getClientCache().getRegion(regionName), \"async2key-\", ONE_HUNDRED);\n });\n\n removeAll1InClient1.await();\n removeAll2InClient1.await();\n\n // client1 removeAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n doRemoveAll(region, \"key-\", ONE_HUNDRED);\n assertThat(region.size()).isZero();\n });\n\n // verify async removeAll cache server 1\n server1.invoke(() -> {\n assertThat(getCache().getRegion(regionName).size()).isZero();\n });\n\n // verify async removeAll cache server 2\n server2.invoke(() -> {\n assertThat(getCache().getRegion(regionName).size()).isZero();\n });\n\n // client2 verify async removeAll\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.size()).isZero());\n });\n\n // server1 execute P2P putAll\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n doPutAll(region, \"p2pkey-\", ONE_HUNDRED);\n\n long timeStamp = 0;\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"p2pkey-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n assertThat(tickerData.getTimeStamp()).isGreaterThanOrEqualTo(timeStamp);\n timeStamp = tickerData.getTimeStamp();\n }\n });\n\n // verify cache server 2 for async keys\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n\n long timeStamp = 0;\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"p2pkey-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n assertThat(tickerData.getTimeStamp()).isGreaterThanOrEqualTo(timeStamp);\n timeStamp = tickerData.getTimeStamp();\n }\n });\n\n // client2 verify p2p putAll\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.size()).isEqualTo(ONE_HUNDRED));\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n Entry regionEntry = region.getEntry(\"p2pkey-\" + i);\n assertThat(regionEntry.getValue()).isNull();\n }\n });\n\n // client1 verify p2p putAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.size()).isEqualTo(ONE_HUNDRED));\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n Entry regionEntry = region.getEntry(\"p2pkey-\" + i);\n assertThat(regionEntry.getValue()).isNull();\n }\n });\n\n // server1 execute P2P removeAll\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n doRemoveAll(region, \"p2pkey-\", ONE_HUNDRED);\n assertThat(region.size()).isZero();\n });\n\n // verify p2p removeAll cache server 2\n server2.invoke(() -> {\n assertThat(getCache().getRegion(regionName).size()).isZero();\n });\n\n // client2 verify p2p removeAll\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.size()).isZero());\n });\n\n // client1 verify p2p removeAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.size()).isZero());\n });\n\n // execute putAll on client2 for key 0-10\n client2.invoke(() -> doPutAll(getClientCache().getRegion(regionName), \"key-\", 10));\n\n // verify client1 for local invalidate\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n\n for (int i = 0; i < 10; i++) {\n String key = \"key-\" + i;\n\n await().until(() -> {\n Entry regionEntry = region.getEntry(key);\n return regionEntry != null && regionEntry.getValue() == null;\n });\n\n // local invalidate will set the value to null\n TickerData tickerData = region.getEntry(\"key-\" + i).getValue();\n assertThat(tickerData).isNull();\n }\n });\n }\n\n /**\n * Checks to see if a client does a destroy that throws an exception from CacheWriter\n * beforeDestroy that the size of the region is still correct. See bug 51583.\n */\n @Test\n public void testClientDestroyOfUncreatedEntry() {\n // set means to test local-invalidates\n int serverPort1 = server1.invoke(() -> new ServerBuilder()\n .regionShortcut(REPLICATE)\n .create());\n\n client1.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort1)\n .create());\n\n // server1 add cacheWriter\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n // Install cacheWriter that causes the very first destroy to fail\n region.getAttributesMutator()\n .setCacheWriter(new ActionCacheWriter<>(new Action<>(Operation.DESTROY,\n destroys -> {\n if (destroys >= 0) {\n throw new CacheWriterException(\"Expected by test\");\n }\n })));\n assertThat(region.size()).isZero();\n });\n\n // client1 destroy\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n Throwable thrown = catchThrowable(() -> region.destroy(\"bogusKey\"));\n assertThat(thrown)\n .isInstanceOf(ServerOperationException.class)\n .hasCauseInstanceOf(CacheWriterException.class);\n });\n\n server1.invoke(() -> {\n assertThat(getCache().getRegion(regionName).size()).isZero();\n });\n }\n\n /**\n * Tests partial key putAll and removeAll to 2 servers with local region\n */\n @Test\n public void testPartialKeyInLocalRegion() {\n // set means to test local-invalidates\n int serverPort1 = server1.invoke(() -> new ServerBuilder()\n .regionShortcut(REPLICATE)\n .create());\n server2.invoke(() -> new ServerBuilder()\n .regionShortcut(REPLICATE)\n .create());\n\n client1.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort1)\n .create());\n client2.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort1)\n .subscriptionAckInterval()\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n\n // server1 add cacheWriter\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n // let the server to trigger exception after created 15 keys\n region.getAttributesMutator()\n .setCacheWriter(new ActionCacheWriter<>(new Action<>(Operation.CREATE,\n creates -> {\n if (creates >= 15) {\n throw new CacheWriterException(\"Expected by test\");\n }\n })));\n });\n\n // client2 register interest\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n region.registerInterest(\"ALL_KEYS\");\n });\n\n // client1 putAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n\n String message =\n String.format(\"Region %s putAll at server applied partial keys due to exception.\",\n region.getFullPath());\n\n Throwable thrown = catchThrowable(() -> doPutAll(region, \"key-\", ONE_HUNDRED));\n\n assertThat(thrown)\n .isInstanceOf(ServerOperationException.class)\n .hasMessageContaining(message)\n .getCause()\n .isInstanceOf(CacheWriterException.class);\n });\n\n await().untilAsserted(() -> {\n assertThat(client1.invoke(() -> getClientCache().getRegion(regionName).size())).isEqualTo(15);\n assertThat(client2.invoke(() -> getClientCache().getRegion(regionName).size())).isEqualTo(15);\n assertThat(server1.invoke(() -> getCache().getRegion(regionName).size())).isEqualTo(15);\n assertThat(server2.invoke(() -> getCache().getRegion(regionName).size())).isEqualTo(15);\n });\n\n int sizeOnServer1 = server1.invoke(() -> getCache().getRegion(regionName).size());\n\n // server1 add cacheWriter\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n // let the server to trigger exception after created 15 keys\n region.getAttributesMutator()\n .setCacheWriter(new ActionCacheWriter<>(new Action<>(Operation.CREATE,\n creates -> {\n if (creates >= 15) {\n throw new CacheWriterException(\"Expected by test\");\n }\n })));\n });\n\n // server2 add listener and putAll\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n Throwable thrown = catchThrowable(() -> doPutAll(region, \"key-\" + \"again:\", ONE_HUNDRED));\n assertThat(thrown).isInstanceOf(CacheWriterException.class);\n });\n\n int sizeOnServer2 = server2.invoke(() -> getCache().getRegion(regionName).size());\n assertThat(sizeOnServer2).isEqualTo(sizeOnServer1 + 15);\n\n await().untilAsserted(() -> {\n // client 1 did not register interest\n assertThat(client1.invoke(() -> getClientCache().getRegion(regionName).size())).isEqualTo(15);\n assertThat(client2.invoke(() -> getClientCache().getRegion(regionName).size()))\n .isEqualTo(15 * 2);\n assertThat(server1.invoke(() -> getCache().getRegion(regionName).size())).isEqualTo(15 * 2);\n assertThat(server2.invoke(() -> getCache().getRegion(regionName).size())).isEqualTo(15 * 2);\n });\n\n // server1 add cacheWriter\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n // server triggers exception after destroying 5 keys\n region.getAttributesMutator()\n .setCacheWriter(new ActionCacheWriter<>(new Action<>(Operation.DESTROY,\n creates -> {\n if (creates >= 5) {\n throw new CacheWriterException(\"Expected by test\");\n }\n })));\n });\n\n // client1 removeAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n\n String message =\n String.format(\"Region %s removeAll at server applied partial keys due to exception.\",\n region.getFullPath());\n\n Throwable thrown = catchThrowable(() -> doRemoveAll(region, \"key-\", ONE_HUNDRED));\n\n assertThat(thrown)\n .isInstanceOf(ServerOperationException.class)\n .hasMessageContaining(message)\n .getCause()\n .isInstanceOf(CacheWriterException.class);\n });\n\n await().untilAsserted(() -> {\n // client 1 did not register interest\n assertThat(client1.invoke(() -> getClientCache().getRegion(regionName).size()))\n .isEqualTo(15 - 5);\n assertThat(client2.invoke(() -> getClientCache().getRegion(regionName).size()))\n .isEqualTo(15 * 2 - 5);\n assertThat(server1.invoke(() -> getCache().getRegion(regionName).size()))\n .isEqualTo(15 * 2 - 5);\n assertThat(server2.invoke(() -> getCache().getRegion(regionName).size()))\n .isEqualTo(15 * 2 - 5);\n });\n\n // server1 add cacheWriter\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n // server triggers exception after destroying 5 keys\n region.getAttributesMutator()\n .setCacheWriter(new ActionCacheWriter<>(new Action<>(Operation.DESTROY,\n ops -> {\n if (ops >= 5) {\n throw new CacheWriterException(\"Expected by test\");\n }\n })));\n });\n\n // server2 add listener and removeAll\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n Throwable thrown = catchThrowable(() -> doRemoveAll(region, \"key-\" + \"again:\", ONE_HUNDRED));\n assertThat(thrown).isInstanceOf(CacheWriterException.class);\n });\n\n await().untilAsserted(() -> {\n // client 1 did not register interest\n assertThat(client1.invoke(() -> getClientCache().getRegion(regionName).size()))\n .isEqualTo(15 - 5);\n assertThat(client2.invoke(() -> getClientCache().getRegion(regionName).size()))\n .isEqualTo(15 * 2 - 5 - 5);\n assertThat(server1.invoke(() -> getCache().getRegion(regionName).size()))\n .isEqualTo(15 * 2 - 5 - 5);\n assertThat(server2.invoke(() -> getCache().getRegion(regionName).size()))\n .isEqualTo(15 * 2 - 5 - 5);\n });\n }\n\n /**\n * Verify all the possible exceptions a putAll/put/removeAll/destroy could return\n */\n @Test\n public void testPutAllReturnsExceptions() {\n // set means to test local-invalidates\n int serverPort1 = server1.invoke(() -> new ServerBuilder()\n .regionShortcut(REPLICATE)\n .create());\n server2.invoke(() -> new ServerBuilder()\n .regionShortcut(REPLICATE)\n .create());\n\n client1.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort1)\n .create());\n\n // server1 add cacheWriter\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n // let the server to trigger exception after created 15 keys\n region.getAttributesMutator()\n .setCacheWriter(new ActionCacheWriter<>(new Action<>(Operation.CREATE,\n creates -> {\n if (creates >= 15) {\n throw new CacheWriterException(\"Expected by test\");\n }\n })));\n\n Throwable thrown = catchThrowable(() -> doPutAll(region, \"key-\", ONE_HUNDRED));\n assertThat(thrown).isInstanceOf(CacheWriterException.class);\n\n thrown = catchThrowable(() -> region.put(\"dummyKey\", new TickerData(0)));\n assertThat(thrown).isInstanceOf(CacheWriterException.class);\n });\n\n // client1 putAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n\n String message =\n String.format(\"Region %s putAll at server applied partial keys due to exception.\",\n region.getFullPath());\n\n Throwable thrown = catchThrowable(() -> doPutAll(region, \"key-\", ONE_HUNDRED));\n\n assertThat(thrown)\n .isInstanceOf(ServerOperationException.class)\n .hasMessageContaining(message)\n .hasCauseInstanceOf(CacheWriterException.class);\n\n thrown = catchThrowable(() -> region.put(\"dummyKey\", new TickerData(0)));\n assertThat(thrown)\n .isInstanceOf(ServerOperationException.class)\n .hasCauseInstanceOf(CacheWriterException.class);\n });\n\n // let server1 to throw CancelException\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n // let the server to trigger exception after created 15 keys\n region.getAttributesMutator()\n .setCacheWriter(new ActionCacheWriter<>(new Action<>(Operation.CREATE,\n creates -> {\n throw new OplogCancelledException(\"Expected by test\");\n })));\n\n Throwable thrown = catchThrowable(() -> doPutAll(region, \"key-\", ONE_HUNDRED));\n assertThat(thrown).isInstanceOf(OplogCancelledException.class);\n\n thrown = catchThrowable(() -> region.put(\"dummyKey\", new TickerData(0)));\n assertThat(thrown).isInstanceOf(OplogCancelledException.class);\n });\n\n // client1 putAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n\n Throwable thrown = catchThrowable(() -> doPutAll(region, \"key-\", ONE_HUNDRED));\n assertThat(thrown)\n .isInstanceOf(ServerConnectivityException.class)\n .hasCauseInstanceOf(OplogCancelledException.class);\n\n thrown = catchThrowable(() -> region.put(\"dummyKey\", new TickerData(0)));\n assertThat(thrown)\n .isInstanceOf(ServerConnectivityException.class)\n .hasCauseInstanceOf(OplogCancelledException.class);\n });\n\n // let server1 to throw LowMemoryException\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n // let the server to trigger exception after created 15 keys\n region.getAttributesMutator()\n .setCacheWriter(new ActionCacheWriter<>(new Action<>(Operation.CREATE,\n creates -> {\n throw new LowMemoryException(\"Testing\", emptySet());\n })));\n\n Throwable thrown = catchThrowable(() -> doPutAll(region, \"key-\", ONE_HUNDRED));\n assertThat(thrown).isInstanceOf(LowMemoryException.class);\n\n thrown = catchThrowable(() -> region.put(\"dummyKey\", new TickerData(0)));\n assertThat(thrown).isInstanceOf(LowMemoryException.class);\n });\n\n // client1 putAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n\n Throwable thrown = catchThrowable(() -> doPutAll(region, \"key-\", ONE_HUNDRED));\n assertThat(thrown)\n .isInstanceOf(ServerOperationException.class)\n .getCause()\n .isInstanceOf(LowMemoryException.class);\n\n thrown = catchThrowable(() -> region.put(\"dummyKey\", new TickerData(0)));\n assertThat(thrown)\n .isInstanceOf(ServerOperationException.class)\n .getCause()\n .isInstanceOf(LowMemoryException.class);\n });\n\n // let server1 to throw TimeoutException\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n // let the server to trigger exception after created 15 keys\n region.getAttributesMutator()\n .setCacheWriter(new ActionCacheWriter<>(new Action<>(Operation.CREATE,\n creates -> {\n throw new TimeoutException(\"Testing\");\n })));\n\n Map map = new LinkedHashMap<>();\n for (int i = 0; i < ONE_HUNDRED; i++) {\n map.put(keyPrefix + i, new TickerData(i));\n }\n\n Throwable thrown = catchThrowable(() -> region.putAll(map));\n assertThat(thrown)\n .isInstanceOf(TimeoutException.class)\n .hasNoCause();\n\n thrown = catchThrowable(() -> region.put(\"dummyKey\", new TickerData(0)));\n assertThat(thrown)\n .isInstanceOf(TimeoutException.class)\n .hasNoCause();\n\n thrown = catchThrowable(() -> doPutAll(region, \"key-\", ONE_HUNDRED));\n assertThat(thrown)\n .isInstanceOf(TimeoutException.class)\n .hasNoCause();\n\n thrown = catchThrowable(() -> region.put(\"dummyKey\", new TickerData(0)));\n assertThat(thrown)\n .isInstanceOf(TimeoutException.class)\n .hasNoCause();\n });\n\n // client1 putAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n\n Map map = new LinkedHashMap<>();\n for (int i = 0; i < ONE_HUNDRED; i++) {\n map.put(keyPrefix + i, new TickerData(i));\n }\n\n Throwable thrown = catchThrowable(() -> region.putAll(map));\n assertThat(thrown)\n .isInstanceOf(ServerOperationException.class)\n .hasCauseInstanceOf(TimeoutException.class);\n\n thrown = catchThrowable(() -> region.put(\"dummyKey\", new TickerData(0)));\n assertThat(thrown)\n .isInstanceOf(ServerOperationException.class)\n .hasCauseInstanceOf(TimeoutException.class);\n\n thrown = catchThrowable(() -> doPutAll(region, \"key-\", ONE_HUNDRED));\n assertThat(thrown)\n .isInstanceOf(ServerOperationException.class)\n .hasCauseInstanceOf(TimeoutException.class);\n\n thrown = catchThrowable(() -> region.put(\"dummyKey\", new TickerData(0)));\n assertThat(thrown)\n .isInstanceOf(ServerOperationException.class)\n .hasCauseInstanceOf(TimeoutException.class);\n });\n }\n\n /**\n * Tests partial key putAll to 2 PR servers, because putting data at server side is different\n * between PR and LR. PR does it in postPutAll. It's not running in singleHop putAll\n */\n @Test\n public void testPartialKeyInPR() throws Exception {\n // set means to test local-invalidates\n int serverPort1 = server1.invoke(() -> new ServerBuilder()\n .regionShortcut(PARTITION_PERSISTENT)\n .create());\n int serverPort2 = server2.invoke(() -> new ServerBuilder()\n .regionShortcut(PARTITION_PERSISTENT)\n .create());\n\n for (VM clientVM : asList(client1, client2)) {\n clientVM.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort1, serverPort2)\n .subscriptionAckInterval()\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n }\n\n // server1 add slow listener\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator().addCacheListener(new SlowCacheListener<>());\n });\n\n // server2 add slow listener\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator()\n .addCacheListener(new SlowCountingCacheListener<>(new Action<>(Operation.CREATE,\n creates -> executorServiceRule.submit(() -> closeCacheConditionally(creates, 10)))));\n });\n\n // client2 add listener\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n region.getAttributesMutator().addCacheListener(new SlowCacheListener<>());\n region.registerInterest(\"ALL_KEYS\");\n });\n\n // client1 add listener and putAll\n AsyncInvocation registerInterestAndPutAllInClient1 = client1.invokeAsync(() -> {\n Region region = getClientCache().getRegion(regionName);\n region.getAttributesMutator().addCacheListener(new SlowCacheListener<>());\n region.registerInterest(\"ALL_KEYS\");\n\n String message =\n String.format(\"Region %s putAll at server applied partial keys due to exception.\",\n region.getFullPath());\n\n Throwable thrown = catchThrowable(() -> doPutAll(region, \"Key-\", ONE_HUNDRED));\n\n assertThat(thrown)\n .isInstanceOf(ServerOperationException.class)\n .hasMessageContaining(message)\n .getCause()\n .isInstanceOf(PartitionOfflineException.class);\n });\n\n // server2 will closeCache after created 10 keys\n\n registerInterestAndPutAllInClient1.await();\n\n int sizeOnClient1 = client1.invoke(() -> getClientCache().getRegion(regionName).size());\n // client2Size maybe more than client1Size\n int sizeOnClient2 = client2.invoke(() -> getClientCache().getRegion(regionName).size());\n\n // restart server2\n server2.invoke(() -> {\n new ServerBuilder().regionShortcut(PARTITION_PERSISTENT).create();\n });\n\n await().untilAsserted(() -> {\n assertThat(server1.invoke(() -> getCache().getRegion(regionName).size()))\n .isEqualTo(sizeOnClient2);\n assertThat(server2.invoke(() -> getCache().getRegion(regionName).size()))\n .isEqualTo(sizeOnClient2);\n });\n\n // close a server to re-run the test\n server2.invoke(() -> getCache().close());\n int sizeOnServer1 = server1.invoke(() -> getCache().getRegion(regionName).size());\n\n // client1 does putAll again\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n\n String message =\n String.format(\"Region %s putAll at server applied partial keys due to exception.\",\n region.getFullPath());\n\n Throwable thrown = catchThrowable(() -> doPutAll(region, \"key-\" + \"again:\", ONE_HUNDRED));\n\n assertThat(thrown)\n .isInstanceOf(ServerOperationException.class)\n .hasMessageContaining(message)\n .getCause()\n .isInstanceOf(PartitionOfflineException.class);\n });\n\n int newSizeOnServer1 = server1.invoke(() -> getCache().getRegion(regionName).size());\n int newSizeOnClient1 = client1.invoke(() -> getClientCache().getRegion(regionName).size());\n int newSizeOnClient2 = client2.invoke(() -> getClientCache().getRegion(regionName).size());\n\n assertThat(newSizeOnServer1).isEqualTo(sizeOnServer1 + ONE_HUNDRED / 2);\n assertThat(newSizeOnClient1).isEqualTo(sizeOnClient1 + ONE_HUNDRED / 2);\n assertThat(newSizeOnClient2).isEqualTo(sizeOnClient2 + ONE_HUNDRED / 2);\n\n // restart server2\n server2.invoke(() -> {\n new ServerBuilder().regionShortcut(PARTITION_PERSISTENT).create();\n });\n sizeOnServer1 = server1.invoke(() -> getCache().getRegion(regionName).size());\n int sizeOnServer2 = server2.invoke(() -> getCache().getRegion(regionName).size());\n assertThat(sizeOnServer2).isEqualTo(sizeOnServer1);\n\n // server1 execute P2P putAll\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n // let the server to trigger exception after created 15 keys\n region.getAttributesMutator()\n .setCacheWriter(new ActionCacheWriter<>(new Action<>(Operation.CREATE,\n creates -> {\n if (creates >= 15) {\n throw new CacheWriterException(\"Expected by test\");\n }\n })));\n });\n\n // server2 add listener and putAll\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n Throwable thrown =\n catchThrowable(() -> doPutAll(region, \"key-\" + \"once again:\", ONE_HUNDRED));\n assertThat(thrown)\n .isInstanceOf(CacheWriterException.class)\n .hasMessageContaining(\"Expected by test\");\n });\n\n newSizeOnServer1 = server1.invoke(() -> getCache().getRegion(regionName).size());\n int newSizeOnServer2 = server2.invoke(() -> getCache().getRegion(regionName).size());\n assertThat(newSizeOnServer1).isEqualTo(sizeOnServer1 + 15);\n assertThat(newSizeOnServer2).isEqualTo(sizeOnServer2 + 15);\n }\n\n /**\n * Tests partial key putAll to 2 PR servers, because putting data at server side is different\n * between PR and LR. PR does it in postPutAll. This is a singlehop putAll test.\n */\n @Test\n public void testPartialKeyInPRSingleHop() throws Exception {\n // set means to test local-invalidates\n int serverPort1 = server1.invoke(() -> new ServerBuilder()\n .regionShortcut(PARTITION_PERSISTENT)\n .create());\n int serverPort2 = server2.invoke(() -> new ServerBuilder()\n .regionShortcut(PARTITION_PERSISTENT)\n .create());\n\n client1.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort1, serverPort2)\n .create());\n client2.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort1, serverPort2)\n .subscriptionAckInterval()\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n\n // client2 add listener\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n region.registerInterest(\"ALL_KEYS\");\n });\n\n // do some putAll to get ClientMetaData for future putAll\n client1.invoke(() -> doPutAll(getClientCache().getRegion(regionName), \"key-\", ONE_HUNDRED));\n\n await().untilAsserted(() -> {\n assertThat(client1.invoke(() -> getClientCache().getRegion(regionName).size()))\n .isEqualTo(ONE_HUNDRED);\n assertThat(client2.invoke(() -> getClientCache().getRegion(regionName).size()))\n .isEqualTo(ONE_HUNDRED);\n assertThat(server1.invoke(() -> getCache().getRegion(regionName).size()))\n .isEqualTo(ONE_HUNDRED);\n assertThat(server2.invoke(() -> getCache().getRegion(regionName).size()))\n .isEqualTo(ONE_HUNDRED);\n });\n\n // server1 add slow listener\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator().addCacheListener(new SlowCacheListener<>());\n });\n\n // add a listener that will close the cache at the 10th update\n\n // server2 add slow listener\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator()\n .addCacheListener(new SlowCountingCacheListener<>(new Action<>(Operation.CREATE,\n creates -> executorServiceRule.submit(() -> closeCacheConditionally(creates, 10)))));\n });\n\n // client1 add listener and putAll\n AsyncInvocation addListenerAndPutAllInClient1 = client1.invokeAsync(() -> {\n Region region = getClientCache().getRegion(regionName);\n\n String message =\n String.format(\"Region %s putAll at server applied partial keys due to exception.\",\n region.getFullPath());\n\n Throwable thrown = catchThrowable(() -> doPutAll(region, keyPrefix, ONE_HUNDRED));\n\n assertThat(thrown)\n .isInstanceOf(ServerOperationException.class)\n .hasMessageContaining(message)\n .getCause()\n .isInstanceOf(PartitionOfflineException.class);\n });\n\n // server2 will closeCache after creating 10 keys\n\n addListenerAndPutAllInClient1.await();\n\n // restart server2\n server2.invoke(() -> {\n new ServerBuilder().regionShortcut(PARTITION_PERSISTENT).create();\n });\n\n // Test Case1: Trigger singleHop putAll. Stop server2 in middle.\n // ONE_HUNDRED_ENTRIES/2 + X keys will be created at servers. i.e. X keys at server2,\n // ONE_HUNDRED_ENTRIES/2 keys at server1.\n // The client should receive a PartialResultException due to PartitionOffline\n\n // close a server to re-run the test\n server2.invoke(() -> getCache().close());\n\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n\n String message =\n String.format(\"Region %s putAll at server applied partial keys due to exception.\",\n region.getFullPath());\n\n Throwable thrown = catchThrowable(() -> doPutAll(region, keyPrefix + \"again:\", ONE_HUNDRED));\n\n assertThat(thrown)\n .isInstanceOf(ServerOperationException.class)\n .hasMessageContaining(message)\n .getCause()\n .isInstanceOf(PartitionOfflineException.class);\n });\n\n // Test Case 2: based on case 1, but this time, there should be no X keys\n // created on server2.\n\n // restart server2\n server2.invoke(() -> {\n new ServerBuilder().regionShortcut(PARTITION_PERSISTENT).create();\n });\n\n // add a cacheWriter for server to fail putAll after it created cacheWriterAllowedKeyNum keys\n int throwAfterNumberCreates = 16;\n\n // server1 add cacheWriter to throw exception after created some keys\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator()\n .setCacheWriter(new ActionCacheWriter<>(new Action<>(Operation.CREATE,\n creates -> {\n if (creates >= throwAfterNumberCreates) {\n throw new CacheWriterException(\"Expected by test\");\n }\n })));\n });\n\n // client1 does putAll once more\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n\n String message =\n String.format(\"Region %s putAll at server applied partial keys due to exception.\",\n region.getFullPath());\n\n Throwable thrown =\n catchThrowable(() -> doPutAll(region, keyPrefix + \"once more:\", ONE_HUNDRED));\n\n assertThat(thrown)\n .isInstanceOf(ServerOperationException.class)\n .hasMessageContaining(message)\n .getCause()\n .isInstanceOf(CacheWriterException.class)\n .hasMessageContaining(\"Expected by test\");\n });\n }\n\n /**\n * Set redundancy=1 to see if retry succeeded after PRE This is a singlehop putAll test.\n */\n @Test\n public void testPartialKeyInPRSingleHopWithRedundancy() throws Exception {\n // set means to test local-invalidates\n int serverPort1 = server1.invoke(() -> new ServerBuilder()\n .redundantCopies(1)\n .regionShortcut(PARTITION_PERSISTENT)\n .create());\n int serverPort2 = server2.invoke(() -> new ServerBuilder()\n .redundantCopies(1)\n .regionShortcut(PARTITION_PERSISTENT)\n .create());\n\n client1.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort1, serverPort2)\n .subscriptionAckInterval()\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n client2.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort1, serverPort2)\n .subscriptionAckInterval()\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n\n // client2 add listener\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n region.registerInterest(\"ALL_KEYS\");\n });\n\n // do some putAll to get ClientMetaData for future putAll\n client1.invoke(() -> doPutAll(getClientCache().getRegion(regionName), \"key-\", ONE_HUNDRED));\n\n await().untilAsserted(() -> {\n assertThat(client1.invoke(() -> getClientCache().getRegion(regionName).size()))\n .isEqualTo(ONE_HUNDRED);\n assertThat(client2.invoke(() -> getClientCache().getRegion(regionName).size()))\n .isEqualTo(ONE_HUNDRED);\n assertThat(server1.invoke(() -> getCache().getRegion(regionName).size()))\n .isEqualTo(ONE_HUNDRED);\n assertThat(server2.invoke(() -> getCache().getRegion(regionName).size()))\n .isEqualTo(ONE_HUNDRED);\n });\n\n // server1 add slow listener\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator().addCacheListener(new SlowCacheListener<>());\n });\n\n // server2 add slow listener\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator()\n .addCacheListener(new SlowCountingCacheListener<>(new Action<>(Operation.CREATE,\n creates -> executorServiceRule.submit(() -> closeCacheConditionally(creates, 10)))));\n });\n\n // client1 add listener and putAll\n AsyncInvocation registerInterestAndPutAllInClient1 = client1.invokeAsync(() -> {\n Region region = getClientCache().getRegion(regionName);\n region.registerInterest(\"ALL_KEYS\");\n\n // create keys\n doPutAll(region, keyPrefix, ONE_HUNDRED);\n });\n\n // server2 will closeCache after created 10 keys\n\n registerInterestAndPutAllInClient1.await();\n\n int sizeOnClient1 = client1.invoke(() -> getClientCache().getRegion(regionName).size());\n int sizeOnClient2 = client2.invoke(() -> getClientCache().getRegion(regionName).size());\n int sizeOnServer1 = server1.invoke(() -> getCache().getRegion(regionName).size());\n // putAll should succeed after retry\n assertThat(sizeOnClient1).isEqualTo(sizeOnServer1);\n assertThat(sizeOnClient2).isEqualTo(sizeOnServer1);\n\n // restart server2\n server2.invoke(() -> {\n new ServerBuilder()\n .redundantCopies(1)\n .regionShortcut(PARTITION_PERSISTENT)\n .create();\n });\n\n sizeOnServer1 = server1.invoke(() -> getCache().getRegion(regionName).size());\n int sizeOnServer2 = server2.invoke(() -> getCache().getRegion(regionName).size());\n assertThat(sizeOnServer1).isEqualTo(sizeOnClient2);\n assertThat(sizeOnServer2).isEqualTo(sizeOnClient2);\n\n // close a server to re-run the test\n server2.invoke(() -> getCache().close());\n\n // client1 does putAll again\n client1.invoke(\n () -> doPutAll(getClientCache().getRegion(regionName), keyPrefix + \"again:\", ONE_HUNDRED));\n\n int newSizeOnServer1 = server1.invoke(() -> getCache().getRegion(regionName).size());\n int newSizeOnClient1 = client1.invoke(() -> getClientCache().getRegion(regionName).size());\n int newSizeOnClient2 = client2.invoke(() -> getClientCache().getRegion(regionName).size());\n\n // putAll should succeed, all the numbers should match\n assertThat(newSizeOnClient1).isEqualTo(newSizeOnServer1);\n assertThat(newSizeOnClient2).isEqualTo(newSizeOnServer1);\n }\n\n /**\n * The purpose of this test is to validate that when two servers of three in a cluster configured\n * with a client doing singlehop, that the client gets afterCreate messages for each entry in the\n * putall. Further, we also check that the region size is correct on the remaining server.\n */\n @Test\n public void testEventIdOutOfOrderInPartitionRegionSingleHop() {\n VM server3 = client2;\n\n int serverPort1 = server1.invoke(() -> new ServerBuilder()\n .regionShortcut(PARTITION)\n .create());\n int serverPort2 = server2.invoke(() -> new ServerBuilder()\n .regionShortcut(PARTITION)\n .create());\n int serverPort3 = server3.invoke(() -> new ServerBuilder()\n .regionShortcut(PARTITION)\n .create());\n\n client1.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort1, serverPort2, serverPort3)\n .subscriptionAckInterval()\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n\n // do some putAll to get ClientMetaData for future putAll\n client1.invoke(() -> {\n // register interest and add listener\n Region region = getClientCache().getRegion(regionName);\n doPutAll(getClientCache().getRegion(regionName), \"key-\", ONE_HUNDRED);\n\n COUNTER.set(new Counter(\"client1\"));\n region.getAttributesMutator()\n .addCacheListener(new CountingCacheListener<>(COUNTER.get()));\n region.registerInterest(\"ALL_KEYS\");\n });\n\n // server1 and server2 will closeCache after created 10 keys\n // server1 add slow listener\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator()\n .addCacheListener(new SlowCountingCacheListener<>(new Action<>(Operation.CREATE,\n creates -> closeCacheConditionally(creates, 10))));\n });\n\n // server2 add slow listener\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator()\n .addCacheListener(new SlowCountingCacheListener<>(new Action<>(Operation.CREATE,\n creates -> closeCacheConditionally(creates, 20))));\n });\n\n // server3 add slow listener\n server3.invoke(() -> {\n COUNTER.set(new Counter(\"server3\"));\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator()\n .addCacheListener(new SlowCountingCacheListener<>(COUNTER.get()));\n });\n\n // client1 add listener and putAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n doPutAll(region, keyPrefix, ONE_HUNDRED);\n\n assertThat(COUNTER.get().getCreates()).isEqualTo(100);\n assertThat(COUNTER.get().getUpdates()).isZero();\n });\n\n // server3 print counter\n server3.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n\n assertThat(region.size())\n .describedAs(\"Should have 100 entries plus 3 to 4 buckets worth of entries\")\n .isIn(ONE_HUNDRED + 3 * ONE_HUNDRED / 10, ONE_HUNDRED + 4 * ONE_HUNDRED / 10);\n assertThat(COUNTER.get().getUpdates()).isZero();\n verifyPutAll(region, keyPrefix);\n });\n }\n\n /**\n * The purpose of this test is to validate that when two servers of three in a cluster configured\n * with a client doing singlehop, that the client which registered interest gets afterCreate\n * messages for each\n * entry in the putall.\n * Further, we also check that the region size is correct on the remaining server.\n *\n * When the client has finished registerInterest to build the subscription queue, the servers\n * should guarantee all the afterCreate events arrive.\n *\n */\n @Test\n public void testEventIdOutOfOrderInPartitionRegionSingleHopFromClientRegisteredInterest() {\n VM server3 = client2;\n\n int serverPort1 = server1.invoke(() -> new ServerBuilder()\n .regionShortcut(PARTITION)\n .create());\n\n int serverPort2 = server2.invoke(() -> new ServerBuilder()\n .regionShortcut(PARTITION)\n .create());\n\n int serverPort3 = server3.invoke(() -> new ServerBuilder()\n .regionShortcut(PARTITION)\n .create());\n\n client1.invoke(() -> new ClientBuilder()\n .prSingleHopEnabled(true)\n .serverPorts(serverPort1, serverPort2, serverPort3)\n .subscriptionAckInterval()\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n\n new ClientBuilder()\n .prSingleHopEnabled(true)\n .serverPorts(serverPort1, serverPort2, serverPort3)\n .subscriptionAckInterval()\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create();\n\n Region myRegion = getClientCache().getRegion(regionName);\n myRegion.registerInterest(\"ALL_KEYS\");\n\n // do some putAll to get ClientMetaData for future putAll\n client1.invoke(() -> doPutAll(getClientCache().getRegion(regionName), \"key-\", ONE_HUNDRED));\n await().until(() -> myRegion.size() == ONE_HUNDRED);\n\n // register interest and add listener\n Counter clientCounter = new Counter(\"client\");\n myRegion.getAttributesMutator().addCacheListener(new CountingCacheListener<>(clientCounter));\n\n // server1 and server2 will closeCache after created 10 keys\n // server1 add slow listener\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator()\n .addCacheListener(new SlowCountingCacheListener<>(new Action<>(Operation.CREATE,\n creates -> closeCacheConditionally(creates, 10))));\n });\n\n // server2 add slow listener\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator()\n .addCacheListener(new SlowCountingCacheListener<>(new Action<>(Operation.CREATE,\n creates -> closeCacheConditionally(creates, 20))));\n });\n\n // server3 add slow listener\n server3.invoke(() -> {\n COUNTER.set(new Counter(\"server3\"));\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator()\n .addCacheListener(new SlowCountingCacheListener<>(COUNTER.get()));\n });\n\n // client1 add listener and putAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n doPutAll(region, keyPrefix, ONE_HUNDRED); // fails in GEODE-7812\n });\n\n await().untilAsserted(() -> assertThat(clientCounter.getCreates()).isEqualTo(ONE_HUNDRED));\n assertThat(clientCounter.getUpdates()).isZero();\n\n // server1 and server2 will closeCache after created 10 keys\n // server3 print counter\n server3.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n\n assertThat(region.size())\n .describedAs(\"Should have 100 entries plus 3 to 4 buckets worth of entries\")\n .isIn(ONE_HUNDRED + 3 * (ONE_HUNDRED) / 10, ONE_HUNDRED + 4 * (ONE_HUNDRED) / 10);\n assertThat(COUNTER.get().getUpdates()).isZero();\n verifyPutAll(region, keyPrefix);\n\n });\n\n }\n\n /**\n * Tests while putAll to 2 distributed servers, one server failed over Add a listener to slow down\n * the processing of putAll\n */\n @Test\n public void test2FailOverDistributedServer() throws Exception {\n // set notifyBySubscription=true to test register interest\n int serverPort1 = server1.invoke(() -> new ServerBuilder()\n .regionShortcut(REPLICATE)\n .create());\n int serverPort2 = server2.invoke(() -> new ServerBuilder()\n .regionShortcut(REPLICATE)\n .create());\n\n client1.invoke(() -> new ClientBuilder()\n .registerInterest(true)\n .serverPorts(serverPort1, serverPort2)\n .subscriptionAckInterval()\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n client2.invoke(() -> new ClientBuilder()\n .registerInterest(true)\n .serverPorts(serverPort1, serverPort2)\n .subscriptionAckInterval()\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n\n // server1 add slow listener\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator().addCacheListener(new SlowCacheListener<>());\n });\n\n // server2 add slow listener\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator().addCacheListener(new SlowCacheListener<>());\n });\n\n // client1 registerInterest\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n region.registerInterest(\"ALL_KEYS\");\n });\n\n // client2 registerInterest\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n region.registerInterest(\"ALL_KEYS\");\n });\n\n // async putAll1 from client1\n AsyncInvocation putAllInClient1 = client1.invokeAsync(() -> {\n try {\n doPutAll(getClientCache().getRegion(regionName), \"async1key-\", ONE_HUNDRED);\n } catch (ServerConnectivityException ignore) {\n // stopping the cache server will cause ServerConnectivityException\n // in the client if it hasn't completed performing the 100 puts yet\n }\n });\n\n // stop cache server 1\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.get(\"async1key-1\")).isNotNull());\n stopCacheServer(serverPort1);\n });\n\n putAllInClient1.await();\n\n // verify cache server 2 for async keys\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n\n long timeStamp = 0;\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"async1key-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n assertThat(tickerData.getTimeStamp()).isGreaterThanOrEqualTo(timeStamp);\n timeStamp = tickerData.getTimeStamp();\n }\n });\n }\n\n /**\n * Tests while putAll timeout's exception\n */\n @Test\n public void testClientTimeOut() {\n // set notifyBySubscription=true to test register interest\n int serverPort1 = server1.invoke(() -> new ServerBuilder()\n .regionShortcut(REPLICATE)\n .create());\n int serverPort2 = server2.invoke(() -> new ServerBuilder()\n .regionShortcut(REPLICATE)\n .create());\n\n client1.invoke(() -> new ClientBuilder()\n .readTimeoutMillis(DEFAULT_READ_TIMEOUT)\n .registerInterest(true)\n .serverPorts(serverPort1, serverPort2)\n .subscriptionAckInterval()\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n client2.invoke(() -> new ClientBuilder()\n .readTimeoutMillis(DEFAULT_READ_TIMEOUT)\n .registerInterest(true)\n .serverPorts(serverPort1, serverPort2)\n .subscriptionAckInterval()\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n\n // server1 add slow listener\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator().addCacheListener(new SlowCacheListener<>());\n });\n\n // server2 add slow listener\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator().addCacheListener(new SlowCacheListener<>());\n });\n\n // client1 execute putAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n Throwable thrown = catchThrowable(() -> doPutAll(region, \"key-\", ONE_THOUSAND));\n assertThat(thrown).isInstanceOf(ServerConnectivityException.class);\n });\n }\n\n /**\n * Tests while putAll timeout at endpoint1 and switch to endpoint2\n */\n @Test\n public void testEndPointSwitch() {\n // set notifyBySubscription=true to test register interest\n int serverPort1 = server1.invoke(() -> new ServerBuilder()\n .regionShortcut(REPLICATE)\n .create());\n int serverPort2 = server2.invoke(() -> new ServerBuilder()\n .regionShortcut(REPLICATE)\n .create());\n\n client1.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort1, serverPort2)\n .create());\n client2.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort1, serverPort2)\n .subscriptionAckInterval()\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n\n // only add slow listener to server1, because we wish it to succeed\n\n // server1 add slow listener\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator().addCacheListener(new SlowCacheListener<>());\n });\n\n // only register interest on client2\n // client2 registerInterest\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n region.registerInterest(\"ALL_KEYS\");\n });\n\n // putAll from client1\n client1.invoke(() -> doPutAll(getClientCache().getRegion(regionName), keyPrefix, ONE_HUNDRED));\n\n // verify Bridge client2 for keys arrived finally\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.size()).isEqualTo(ONE_HUNDRED));\n });\n }\n\n /**\n * Tests while putAll to 2 distributed servers, one server failed over Add a listener to slow down\n * the processing of putAll\n */\n @Test\n public void testHADRFailOver() throws Exception {\n addIgnoredException(DistributedSystemDisconnectedException.class);\n\n // set notifyBySubscription=true to test register interest\n int serverPort1 = server1.invoke(() -> new ServerBuilder()\n .regionShortcut(REPLICATE)\n .create());\n int serverPort2 = server2.invoke(() -> new ServerBuilder()\n .regionShortcut(REPLICATE)\n .create());\n\n client1.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort1, serverPort2)\n .subscriptionEnabled(true)\n .subscriptionAckInterval()\n .subscriptionRedundancy()\n .create());\n client2.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort1, serverPort2)\n .subscriptionAckInterval()\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n\n // client1 registerInterest\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n region.registerInterest(\"ALL_KEYS\");\n });\n\n // client2 registerInterest\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n region.registerInterest(\"ALL_KEYS\");\n });\n\n // async putAll1 from server2\n AsyncInvocation putAllInServer2 = server2\n .invokeAsync(() -> doPutAll(getCache().getRegion(regionName), \"server2-key-\", ONE_HUNDRED));\n\n // async putAll1 from client1\n AsyncInvocation putAllInClient1 = client1.invokeAsync(\n () -> doPutAll(getClientCache().getRegion(regionName), \"client1-key-\", ONE_HUNDRED));\n\n // stop cache server 1\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n await().untilAsserted(() -> {\n assertThat(region.get(\"server2-key-1\")).isNotNull();\n assertThat(region.get(\"client1-key-1\")).isNotNull();\n });\n stopCacheServer(serverPort1);\n });\n\n putAllInServer2.await();\n putAllInClient1.await();\n\n // verify Bridge client2 for async keys\n client2.invokeAsync(() -> {\n Region region = getClientCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.size()).isEqualTo(ONE_HUNDRED * 2));\n });\n }\n\n @Test\n public void testVersionsOnClientsWithNotificationsOnly() {\n // set notifyBySubscription=true to test register interest\n int serverPort1 = server1.invoke(() -> new ServerBuilder()\n .regionShortcut(PARTITION)\n .create());\n int serverPort2 = server2.invoke(() -> new ServerBuilder()\n .regionShortcut(PARTITION)\n .create());\n\n // set queueRedundancy=1\n client1.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort1)\n .create());\n client2.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort2)\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n\n // client1 putAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n doPutAll(region, \"key-\", ONE_HUNDRED * 2);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED * 2);\n });\n\n // client2 versions collection\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n region.registerInterest(\"ALL_KEYS\");\n });\n\n // client1 versions collection\n List> client1Versions = client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED * 2);\n\n RegionMap entries = ((DiskRecoveryStore) region).getRegionMap();\n List> versions = new ArrayList<>();\n for (Object key : entries.keySet()) {\n RegionEntry regionEntry = entries.getEntry(key);\n VersionTag tag = regionEntry.getVersionStamp().asVersionTag();\n versions.add(tag);\n }\n\n return versions;\n });\n\n // client2 versions collection\n List> client2Versions = client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED * 2);\n\n RegionMap entries = ((DiskRecoveryStore) region).getRegionMap();\n List> versions = new ArrayList<>();\n for (Object key : entries.keySet()) {\n RegionEntry regionEntry = entries.getEntry(key);\n VersionTag tag = regionEntry.getVersionStamp().asVersionTag();\n versions.add(tag);\n }\n\n return versions;\n });\n\n assertThat(client1Versions.size()).isEqualTo(ONE_HUNDRED * 2);\n\n for (VersionTag tag : client1Versions) {\n assertThat(client2Versions).contains(tag);\n }\n }\n\n /**\n * basically same test as testVersionsOnClientsWithNotificationsOnly but also do a removeAll\n */\n @Test\n public void testRAVersionsOnClientsWithNotificationsOnly() {\n // set notifyBySubscription=true to test register interest\n int serverPort1 = server1.invoke(() -> new ServerBuilder()\n .regionShortcut(PARTITION)\n .create());\n int serverPort2 = server2.invoke(() -> new ServerBuilder()\n .regionShortcut(PARTITION)\n .create());\n\n // set queueRedundancy=1\n client1.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort1)\n .create());\n client2.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort2)\n .subscriptionEnabled(true)\n .create());\n\n // client1 putAll+removeAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n\n doPutAll(region, \"key-\", ONE_HUNDRED * 2);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED * 2);\n\n doRemoveAll(region, \"key-\", ONE_HUNDRED);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n });\n\n // client2 versions collection\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n region.registerInterest(\"ALL_KEYS\");\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n });\n\n // client1 versions collection\n List> client1RAVersions = client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n\n RegionMap entries = ((DiskRecoveryStore) region).getRegionMap();\n assertThat(entries.size()).isEqualTo(ONE_HUNDRED * 2);\n\n List> versions = new ArrayList<>();\n for (Object key : entries.keySet()) {\n RegionEntry regionEntry = entries.getEntry(key);\n VersionTag tag = regionEntry.getVersionStamp().asVersionTag();\n versions.add(tag);\n }\n return versions;\n });\n\n // client2 versions collection\n List> client2RAVersions = client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n\n RegionMap entries = ((DiskRecoveryStore) region).getRegionMap();\n assertThat(entries.size()).isEqualTo(ONE_HUNDRED * 2);\n\n List> versions = new ArrayList<>();\n for (Object key : entries.keySet()) {\n RegionEntry regionEntry = entries.getEntry(key);\n VersionTag tag = regionEntry.getVersionStamp().asVersionTag();\n versions.add(tag);\n }\n return versions;\n });\n\n assertThat(client1RAVersions.size()).isEqualTo(ONE_HUNDRED * 2);\n\n for (VersionTag tag : client1RAVersions) {\n assertThat(client2RAVersions).contains(tag);\n }\n }\n\n @Test\n public void testVersionsOnServersWithNotificationsOnly() {\n VM server3 = client2;\n\n // set notifyBySubscription=true to test register interest\n server1.invoke(() -> new ServerBuilder()\n .redundantCopies(1)\n .regionShortcut(PARTITION)\n .create());\n server2.invoke(() -> new ServerBuilder()\n .redundantCopies(1)\n .regionShortcut(PARTITION)\n .create());\n int serverPort3 = server3.invoke(() -> new ServerBuilder()\n .redundantCopies(1)\n .regionShortcut(PARTITION)\n .create());\n\n client1.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort3)\n .subscriptionEnabled(true)\n .create());\n\n // client2 versions collection\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n region.registerInterest(\"ALL_KEYS\");\n });\n\n // client1 putAll\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n doPutAll(region, \"key-\", ONE_HUNDRED * 2);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED * 2);\n });\n\n // server1 versions collection\n List expectedVersions = server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED * 2);\n\n PartitionedRegionDataStore dataStore = ((PartitionedRegion) region).getDataStore();\n Set buckets = dataStore.getAllLocalPrimaryBucketRegions();\n\n List versions = new ArrayList<>();\n for (BucketRegion bucketRegion : buckets) {\n RegionMap entries = bucketRegion.entries;\n for (Object key : entries.keySet()) {\n RegionEntry regionEntry = entries.getEntry(key);\n VersionTag tag = regionEntry.getVersionStamp().asVersionTag();\n versions.add(key + \" \" + tag);\n }\n }\n return versions;\n });\n\n // client1 versions collection\n List actualVersions = client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n\n // Let client be updated with all keys.\n await().untilAsserted(() -> assertThat(region.size()).isEqualTo(ONE_HUNDRED * 2));\n\n RegionMap entries = ((DiskRecoveryStore) region).getRegionMap();\n List versions = new ArrayList<>();\n for (Object key : entries.keySet()) {\n RegionEntry regionEntry = entries.getEntry(key);\n VersionTag tag = regionEntry.getVersionStamp().asVersionTag();\n tag.setMemberID(null);\n versions.add(key + \" \" + tag);\n }\n return versions;\n });\n\n assertThat(actualVersions).hasSize(ONE_HUNDRED * 2);\n\n for (String keyTag : expectedVersions) {\n assertThat(actualVersions).contains(keyTag);\n }\n }\n\n /**\n * Same test as testVersionsOnServersWithNotificationsOnly but also does a removeAll\n */\n @Test\n public void testRAVersionsOnServersWithNotificationsOnly() {\n VM server3 = client2;\n\n // set notifyBySubscription=true to test register interest\n server1.invoke(() -> new ServerBuilder()\n .redundantCopies(1)\n .regionShortcut(PARTITION)\n .create());\n server2.invoke(() -> new ServerBuilder()\n .redundantCopies(1)\n .regionShortcut(PARTITION)\n .create());\n int serverPort3 = server3.invoke(() -> new ServerBuilder()\n .redundantCopies(1)\n .regionShortcut(PARTITION)\n .create());\n\n client1.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort3)\n .subscriptionEnabled(true)\n .create());\n\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n region.registerInterest(\"ALL_KEYS\");\n });\n\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n\n doPutAll(region, \"key-\", ONE_HUNDRED * 2);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED * 2);\n\n doRemoveAll(region, \"key-\", ONE_HUNDRED);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n });\n\n List expectedRAVersions = server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n\n PartitionedRegionDataStore dataStore = ((PartitionedRegion) region).getDataStore();\n Set buckets = dataStore.getAllLocalPrimaryBucketRegions();\n\n List versions = new ArrayList<>();\n for (BucketRegion bucketRegion : buckets) {\n RegionMap entries = bucketRegion.entries;\n for (Object key : entries.keySet()) {\n RegionEntry regionEntry = entries.getEntry(key);\n VersionTag tag = regionEntry.getVersionStamp().asVersionTag();\n versions.add(key + \" \" + tag);\n }\n }\n return versions;\n });\n\n List actualRAVersions = client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n\n // Let client be updated with all keys.\n RegionMap entries = ((DiskRecoveryStore) region).getRegionMap();\n\n await().untilAsserted(() -> {\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n assertThat(entries.size()).isEqualTo(ONE_HUNDRED * 2);\n });\n\n List versions = new ArrayList<>();\n for (Object key : entries.keySet()) {\n RegionEntry regionEntry = entries.getEntry(key);\n VersionTag tag = regionEntry.getVersionStamp().asVersionTag();\n tag.setMemberID(null);\n versions.add(key + \" \" + tag);\n }\n return versions;\n });\n\n assertThat(actualRAVersions).hasSize(ONE_HUNDRED * 2);\n\n for (String keyTag : expectedRAVersions) {\n assertThat(actualRAVersions).contains(keyTag);\n }\n }\n\n @Test\n public void testVersionsOnReplicasAfterPutAllAndRemoveAll() {\n // set notifyBySubscription=true to test register interest\n int serverPort1 = server1.invoke(() -> new ServerBuilder()\n .regionShortcut(REPLICATE)\n .create());\n server2.invoke(() -> new ServerBuilder()\n .regionShortcut(REPLICATE)\n .create());\n\n client1.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort1)\n .create());\n\n // client1 putAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n\n doPutAll(region, \"key-\", ONE_HUNDRED * 2);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED * 2);\n\n doRemoveAll(region, \"key-\", ONE_HUNDRED);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n });\n\n // client1 versions collection\n List> client1Versions = server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n\n RegionMap entries = ((DiskRecoveryStore) region).getRegionMap();\n assertThat(entries.size()).isEqualTo(ONE_HUNDRED * 2);\n\n List> versions = new ArrayList<>();\n for (Object key : entries.keySet()) {\n RegionEntry regionEntry = entries.getEntry(key);\n VersionTag tag = regionEntry.getVersionStamp().asVersionTag();\n versions.add(tag);\n }\n return versions;\n });\n\n // client2 versions collection\n List> client2Versions = server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n\n RegionMap entries = ((DiskRecoveryStore) region).getRegionMap();\n assertThat(entries.size()).isEqualTo(ONE_HUNDRED * 2);\n\n List> versions = new ArrayList<>();\n for (Object key : entries.keySet()) {\n RegionEntry regionEntry = entries.getEntry(key);\n versions.add(regionEntry.getVersionStamp().asVersionTag());\n }\n return versions;\n });\n\n assertThat(client1Versions.size()).isEqualTo(ONE_HUNDRED * 2);\n\n for (VersionTag tag : client2Versions) {\n tag.setMemberID(null);\n assertThat(client1Versions).contains(tag);\n }\n }\n\n private void createCache(CacheFactory cacheFactory) {\n CACHE.set((InternalCache) cacheFactory.create());\n }\n\n private InternalCache getCache() {\n return CACHE.get();\n }\n\n private void closeCache() {\n CACHE.getAndSet(DUMMY_CACHE).close();\n }\n\n private void createClientCache(ClientCacheFactory clientCacheFactory) {\n CLIENT_CACHE.set((InternalClientCache) clientCacheFactory.create());\n }\n\n private InternalClientCache getClientCache() {\n return CLIENT_CACHE.get();\n }\n\n private void closeClientCache() {\n CLIENT_CACHE.getAndSet(DUMMY_CLIENT_CACHE).close(false);\n }\n\n private File[] getDiskDirs() {\n return new File[] {DISK_DIR.get()};\n }\n\n private int createServerRegion(String regionName, boolean concurrencyChecksEnabled)\n throws IOException {\n getCache().createRegionFactory()\n .setConcurrencyChecksEnabled(concurrencyChecksEnabled)\n .setScope(Scope.DISTRIBUTED_ACK)\n .setDataPolicy(DataPolicy.NORMAL)\n .create(regionName);\n\n CacheServer cacheServer = getCache().addCacheServer();\n cacheServer.setPort(0);\n cacheServer.start();\n return cacheServer.getPort();\n }\n\n private void doPutAll(Map region, String keyPrefix, int entryCount) {\n Map map = new LinkedHashMap<>();\n for (int i = 0; i < entryCount; i++) {\n map.put(keyPrefix + i, new TickerData(i));\n }\n region.putAll(map);\n }\n\n private void verifyPutAll(Map region, String keyPrefix) {\n for (int i = 0; i < ONE_HUNDRED; i++) {\n assertThat(region.containsKey(keyPrefix + i)).isTrue();\n }\n }\n\n private VersionedObjectList doRemoveAll(Region region, String keyPrefix,\n int entryCount) {\n InternalRegion internalRegion = (InternalRegion) region;\n\n InternalEntryEvent event =\n EntryEventImpl.create(internalRegion, Operation.REMOVEALL_DESTROY, null, null,\n null, false, internalRegion.getMyId());\n event.disallowOffHeapValues();\n\n Collection keys = new ArrayList<>();\n for (int i = 0; i < entryCount; i++) {\n keys.add(keyPrefix + i);\n }\n\n DistributedRemoveAllOperation removeAllOp =\n new DistributedRemoveAllOperation(event, keys.size(), false);\n\n return internalRegion.basicRemoveAll(keys, removeAllOp, null);\n }\n\n /**\n * Stops the cache server specified by port\n */\n private void stopCacheServer(int port) {\n boolean foundServer = false;\n for (CacheServer cacheServer : getCache().getCacheServers()) {\n if (cacheServer.getPort() == port) {\n cacheServer.stop();\n assertThat(cacheServer.isRunning()).isFalse();\n foundServer = true;\n break;\n }\n }\n assertThat(foundServer).isTrue();\n }\n\n private void closeCacheConditionally(int ops, int threshold) {\n if (ops == threshold) {\n getCache().close();\n }\n }\n\n private static Consumer emptyConsumer() {\n return input -> {\n // nothing\n };\n }\n\n private static void sleep() {\n try {\n Thread.sleep(50);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n }\n\n @SuppressWarnings(\"unchecked\")\n private static T cast(Object object) {\n return (T) object;\n }\n\n private static void awaitLatch(AtomicReference latch)\n throws InterruptedException {\n latch.get().await(TIMEOUT_MILLIS_LONG, MILLISECONDS);\n }\n\n private static void countDown(AtomicReference latch) {\n latch.get().countDown();\n }\n\n private class ServerBuilder {\n\n private int redundantCopies;\n private RegionShortcut regionShortcut;\n\n private ServerBuilder redundantCopies(int redundantCopies) {\n this.redundantCopies = redundantCopies;\n return this;\n }\n\n private ServerBuilder regionShortcut(RegionShortcut regionShortcut) {\n this.regionShortcut = regionShortcut;\n return this;\n }\n\n private int create() throws IOException {\n assertThat(regionShortcut).isNotNull();\n\n Properties config = getDistributedSystemProperties();\n config.setProperty(LOCATORS, locators);\n\n createCache(new CacheFactory(config));\n\n // In this test, no cacheLoader should be defined, otherwise, it will create a value for\n // destroyed key\n\n RegionFactory regionFactory =\n getCache().createRegionFactory(regionShortcut);\n if (regionShortcut.isPartition()) {\n regionFactory.setPartitionAttributes(new PartitionAttributesFactory()\n .setRedundantCopies(redundantCopies)\n .setTotalNumBuckets(10)\n .create());\n }\n\n // create diskStore if required\n if (regionShortcut.isPersistent()) {\n DiskStore diskStore = getCache().findDiskStore(diskStoreName);\n if (diskStore == null) {\n getCache().createDiskStoreFactory()\n .setDiskDirs(getDiskDirs())\n .create(diskStoreName);\n }\n regionFactory.setDiskStoreName(diskStoreName);\n\n } else {\n // enable concurrency checks (not for disk now - disk doesn't support versions yet)\n regionFactory.setConcurrencyChecksEnabled(true);\n }\n\n regionFactory.create(regionName);\n\n CacheServer cacheServer = getCache().addCacheServer();\n cacheServer.setMaxThreads(0);\n cacheServer.setPort(0);\n cacheServer.start();\n return cacheServer.getPort();\n }\n }\n\n private class ClientBuilder {\n\n private boolean prSingleHopEnabled = true;\n private int readTimeoutMillis = TIMEOUT_MILLIS_INTEGER;\n private boolean registerInterest;\n private final Collection serverPorts = new ArrayList<>();\n private int subscriptionAckInterval = DEFAULT_SUBSCRIPTION_ACK_INTERVAL; // 100 millis\n private boolean subscriptionEnabled = DEFAULT_SUBSCRIPTION_ENABLED; // false\n private int subscriptionRedundancy = DEFAULT_SUBSCRIPTION_REDUNDANCY; // 0\n\n private ClientBuilder prSingleHopEnabled(boolean prSingleHopEnabled) {\n this.prSingleHopEnabled = prSingleHopEnabled;\n return this;\n }\n\n private ClientBuilder readTimeoutMillis(int readTimeoutMillis) {\n this.readTimeoutMillis = readTimeoutMillis;\n return this;\n }\n\n private ClientBuilder registerInterest(boolean registerInterest) {\n this.registerInterest = registerInterest;\n return this;\n }\n\n private ClientBuilder serverPorts(Integer... serverPorts) {\n this.serverPorts.addAll(asList(serverPorts));\n return this;\n }\n\n private ClientBuilder subscriptionAckInterval() {\n subscriptionAckInterval = 1;\n return this;\n }\n\n private ClientBuilder subscriptionEnabled(boolean subscriptionEnabled) {\n this.subscriptionEnabled = subscriptionEnabled;\n return this;\n }\n\n private ClientBuilder subscriptionRedundancy() {\n subscriptionRedundancy = -1;\n return this;\n }\n\n private void create() {\n assertThat(serverPorts).isNotEmpty();\n if (subscriptionAckInterval != DEFAULT_SUBSCRIPTION_ACK_INTERVAL ||\n subscriptionRedundancy != DEFAULT_SUBSCRIPTION_REDUNDANCY) {\n assertThat(subscriptionEnabled).isTrue();\n }\n\n Properties config = getDistributedSystemProperties();\n config.setProperty(LOCATORS, \"\");\n\n createClientCache(new ClientCacheFactory(config));\n\n PoolFactory poolFactory = PoolManager.createFactory();\n for (int serverPort : serverPorts) {\n poolFactory.addServer(hostName, serverPort);\n }\n poolFactory\n .setPRSingleHopEnabled(prSingleHopEnabled)\n .setReadTimeout(readTimeoutMillis)\n .setSubscriptionAckInterval(subscriptionAckInterval)\n .setSubscriptionEnabled(subscriptionEnabled)\n .setSubscriptionRedundancy(subscriptionRedundancy)\n .create(poolName);\n\n ClientRegionFactory clientRegionFactory =\n getClientCache().createClientRegionFactory(ClientRegionShortcut.LOCAL);\n\n clientRegionFactory\n .setConcurrencyChecksEnabled(true);\n\n clientRegionFactory\n .setPoolName(poolName);\n\n Region region = clientRegionFactory\n .create(regionName);\n\n if (registerInterest) {\n region.registerInterestRegex(\".*\", false, false);\n }\n }\n }\n\n private static class Counter implements Serializable {\n\n private final AtomicInteger creates = new AtomicInteger();\n private final AtomicInteger updates = new AtomicInteger();\n private final AtomicInteger invalidates = new AtomicInteger();\n private final AtomicInteger destroys = new AtomicInteger();\n private final String owner;\n\n private Counter(String owner) {\n this.owner = owner;\n }\n\n private int getCreates() {\n return creates.get();\n }\n\n private void incCreates() {\n creates.incrementAndGet();\n }\n\n private int getUpdates() {\n return updates.get();\n }\n\n private void incUpdates() {\n updates.incrementAndGet();\n }\n\n private int getInvalidates() {\n return invalidates.get();\n }\n\n private void incInvalidates() {\n invalidates.incrementAndGet();\n }\n\n private int getDestroys() {\n return destroys.get();\n }\n\n private void incDestroys() {\n destroys.incrementAndGet();\n }\n\n @Override\n public String toString() {\n return \"Owner=\" + owner + \",create=\" + creates + \",update=\" + updates\n + \",invalidate=\" + invalidates + \",destroy=\" + destroys;\n }\n }\n\n /**\n * Defines an action to be run after the specified operation is invoked by Geode callbacks.\n */\n private static class Action {\n\n private final Operation operation;\n private final Consumer consumer;\n\n private Action(Operation operation, Consumer consumer) {\n this.operation = operation;\n this.consumer = consumer;\n }\n\n private void run(Operation operation, T value) {\n if (operation == this.operation) {\n consumer.accept(value);\n }\n }\n }\n\n private static class CountingCacheListener extends CacheListenerAdapter {\n\n private final Counter counter;\n private final Action action;\n\n private CountingCacheListener(Counter counter) {\n this(counter, EMPTY_INTEGER_ACTION);\n }\n\n private CountingCacheListener(Counter counter, Action action) {\n this.counter = counter;\n counter.creates.set(0);\n this.action = action;\n }\n\n @Override\n public void afterCreate(EntryEvent event) {\n counter.incCreates();\n action.run(Operation.CREATE, counter.getCreates());\n }\n\n @Override\n public void afterUpdate(EntryEvent event) {\n counter.incUpdates();\n action.run(Operation.UPDATE, counter.getUpdates());\n }\n\n @Override\n public void afterInvalidate(EntryEvent event) {\n counter.incInvalidates();\n action.run(Operation.INVALIDATE, counter.getInvalidates());\n }\n\n @Override\n public void afterDestroy(EntryEvent event) {\n counter.incDestroys();\n action.run(Operation.DESTROY, counter.getDestroys());\n }\n }\n\n private static class SlowCacheListener extends CacheListenerAdapter {\n\n @Override\n public void afterCreate(EntryEvent event) {\n sleep();\n }\n\n @Override\n public void afterUpdate(EntryEvent event) {\n sleep();\n }\n }\n\n private static class SlowCountingCacheListener extends CountingCacheListener {\n\n private SlowCountingCacheListener(Action action) {\n this(DUMMY_COUNTER, action);\n }\n\n private SlowCountingCacheListener(Counter counter) {\n this(counter, EMPTY_INTEGER_ACTION);\n }\n\n private SlowCountingCacheListener(Counter counter, Action action) {\n super(counter, action);\n }\n\n @Override\n public void afterCreate(EntryEvent event) {\n super.afterCreate(event);\n sleep();\n }\n\n @Override\n public void afterUpdate(EntryEvent event) {\n super.afterUpdate(event);\n sleep();\n }\n }\n\n private static class ActionCacheListener extends CacheListenerAdapter {\n\n private final Action> action;\n\n private ActionCacheListener(Action> action) {\n this.action = action;\n }\n\n @Override\n public void afterUpdate(EntryEvent event) {\n action.run(Operation.UPDATE, event);\n }\n }\n\n @SuppressWarnings({\"unused\", \"WeakerAccess\"})\n private static class TickerData implements DataSerializable {\n\n private long timeStamp = System.currentTimeMillis();\n private int price;\n private String ticker;\n\n public TickerData() {\n // nothing\n }\n\n private TickerData(int price) {\n this.price = price;\n ticker = String.valueOf(price);\n }\n\n public String getTicker() {\n return ticker;\n }\n\n private int getPrice() {\n return price;\n }\n\n private long getTimeStamp() {\n return timeStamp;\n }\n\n @Override\n public void toData(DataOutput out) throws IOException {\n DataSerializer.writeString(ticker, out);\n out.writeInt(price);\n out.writeLong(timeStamp);\n }\n\n @Override\n public void fromData(DataInput in) throws IOException {\n ticker = DataSerializer.readString(in);\n price = in.readInt();\n timeStamp = in.readLong();\n }\n\n @Override\n public String toString() {\n return \"Price=\" + price;\n }\n }\n\n private static class CountingCqListener implements CqListener {\n\n private final AtomicInteger updates = new AtomicInteger();\n private final Region region;\n\n private CountingCqListener(Region region) {\n this.region = region;\n }\n\n @Override\n public void onEvent(CqEvent cqEvent) {\n if (cqEvent.getQueryOperation() == Operation.DESTROY) {\n return;\n }\n\n K key = cast(cqEvent.getKey());\n V newValue = cast(cqEvent.getNewValue());\n\n if (newValue == null) {\n region.create(key, null);\n } else {\n region.put(key, newValue);\n updates.incrementAndGet();\n }\n }\n\n @Override\n public void onError(CqEvent cqEvent) {\n // nothing\n }\n }\n\n private static class CountingCacheWriter extends CacheWriterAdapter {\n\n private final AtomicInteger destroys = new AtomicInteger();\n\n @Override\n public void beforeDestroy(EntryEvent event) {\n destroys.incrementAndGet();\n }\n\n private int getDestroys() {\n return destroys.get();\n }\n }\n\n /**\n * cacheWriter to slow down P2P operations, listener only works for c/s in this case\n */\n private static class ActionCacheWriter extends CacheWriterAdapter {\n\n private final AtomicInteger creates = new AtomicInteger();\n private final AtomicInteger destroys = new AtomicInteger();\n private final Action action;\n\n private ActionCacheWriter(Action action) {\n this.action = action;\n }\n\n @Override\n public void beforeCreate(EntryEvent event) {\n action.run(Operation.CREATE, creates.get());\n sleep();\n creates.incrementAndGet();\n }\n\n @Override\n public void beforeUpdate(EntryEvent event) {\n sleep();\n }\n\n @Override\n public void beforeDestroy(EntryEvent event) {\n action.run(Operation.DESTROY, destroys.get());\n sleep();\n destroys.incrementAndGet();\n }\n }\n}\n"},"new_file":{"kind":"string","value":"geode-cq/src/distributedTest/java/org/apache/geode/internal/cache/PutAllClientServerDistributedTest.java"},"old_contents":{"kind":"string","value":"/*\n * Licensed to the Apache Software Foundation (ASF) under one or more contributor license\n * agreements. See the NOTICE file distributed with this work for additional information regarding\n * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance with the License. You may obtain a\n * 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 distributed under the License\n * is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express\n * or implied. See the License for the specific language governing permissions and limitations under\n * the License.\n */\npackage org.apache.geode.internal.cache;\n\nimport static java.util.Arrays.asList;\nimport static java.util.Collections.emptySet;\nimport static java.util.concurrent.TimeUnit.MILLISECONDS;\nimport static org.apache.geode.cache.Region.SEPARATOR;\nimport static org.apache.geode.cache.RegionShortcut.PARTITION;\nimport static org.apache.geode.cache.RegionShortcut.PARTITION_PERSISTENT;\nimport static org.apache.geode.cache.RegionShortcut.REPLICATE;\nimport static org.apache.geode.cache.client.PoolFactory.DEFAULT_READ_TIMEOUT;\nimport static org.apache.geode.cache.client.PoolFactory.DEFAULT_SUBSCRIPTION_ACK_INTERVAL;\nimport static org.apache.geode.cache.client.PoolFactory.DEFAULT_SUBSCRIPTION_ENABLED;\nimport static org.apache.geode.cache.client.PoolFactory.DEFAULT_SUBSCRIPTION_REDUNDANCY;\nimport static org.apache.geode.distributed.ConfigurationProperties.LOCATORS;\nimport static org.apache.geode.internal.cache.AbstractCacheServer.MAXIMUM_TIME_BETWEEN_PINGS_PROPERTY;\nimport static org.apache.geode.test.awaitility.GeodeAwaitility.await;\nimport static org.apache.geode.test.awaitility.GeodeAwaitility.getTimeout;\nimport static org.apache.geode.test.dunit.IgnoredException.addIgnoredException;\nimport static org.apache.geode.test.dunit.VM.getController;\nimport static org.apache.geode.test.dunit.VM.getHostName;\nimport static org.apache.geode.test.dunit.VM.getVM;\nimport static org.apache.geode.test.dunit.VM.getVMId;\nimport static org.apache.geode.test.dunit.rules.DistributedRule.getDistributedSystemProperties;\nimport static org.apache.geode.test.dunit.rules.DistributedRule.getLocators;\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.assertj.core.api.Assertions.catchThrowable;\nimport static org.mockito.Mockito.mock;\n\nimport java.io.DataInput;\nimport java.io.DataOutput;\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.Serializable;\nimport java.net.ConnectException;\nimport java.net.SocketException;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.Set;\nimport java.util.concurrent.CountDownLatch;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.concurrent.atomic.AtomicReference;\nimport java.util.function.Consumer;\n\nimport junitparams.JUnitParamsRunner;\nimport junitparams.Parameters;\nimport junitparams.naming.TestCaseName;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.experimental.categories.Category;\nimport org.junit.runner.RunWith;\n\nimport org.apache.geode.DataSerializable;\nimport org.apache.geode.DataSerializer;\nimport org.apache.geode.cache.CacheFactory;\nimport org.apache.geode.cache.CacheWriterException;\nimport org.apache.geode.cache.DataPolicy;\nimport org.apache.geode.cache.DiskStore;\nimport org.apache.geode.cache.EntryEvent;\nimport org.apache.geode.cache.LowMemoryException;\nimport org.apache.geode.cache.Operation;\nimport org.apache.geode.cache.PartitionAttributesFactory;\nimport org.apache.geode.cache.Region;\nimport org.apache.geode.cache.Region.Entry;\nimport org.apache.geode.cache.RegionDestroyedException;\nimport org.apache.geode.cache.RegionFactory;\nimport org.apache.geode.cache.RegionShortcut;\nimport org.apache.geode.cache.Scope;\nimport org.apache.geode.cache.TimeoutException;\nimport org.apache.geode.cache.client.ClientCacheFactory;\nimport org.apache.geode.cache.client.ClientRegionFactory;\nimport org.apache.geode.cache.client.ClientRegionShortcut;\nimport org.apache.geode.cache.client.PoolFactory;\nimport org.apache.geode.cache.client.PoolManager;\nimport org.apache.geode.cache.client.ServerConnectivityException;\nimport org.apache.geode.cache.client.ServerOperationException;\nimport org.apache.geode.cache.client.internal.InternalClientCache;\nimport org.apache.geode.cache.persistence.PartitionOfflineException;\nimport org.apache.geode.cache.query.CqAttributes;\nimport org.apache.geode.cache.query.CqAttributesFactory;\nimport org.apache.geode.cache.query.CqEvent;\nimport org.apache.geode.cache.query.CqListener;\nimport org.apache.geode.cache.query.CqQuery;\nimport org.apache.geode.cache.query.SelectResults;\nimport org.apache.geode.cache.query.Struct;\nimport org.apache.geode.cache.server.CacheServer;\nimport org.apache.geode.cache.util.CacheListenerAdapter;\nimport org.apache.geode.cache.util.CacheWriterAdapter;\nimport org.apache.geode.distributed.DistributedSystemDisconnectedException;\nimport org.apache.geode.distributed.OplogCancelledException;\nimport org.apache.geode.internal.cache.persistence.DiskRecoveryStore;\nimport org.apache.geode.internal.cache.tier.sockets.VersionedObjectList;\nimport org.apache.geode.internal.cache.versions.VersionTag;\nimport org.apache.geode.test.dunit.AsyncInvocation;\nimport org.apache.geode.test.dunit.VM;\nimport org.apache.geode.test.dunit.rules.DistributedExecutorServiceRule;\nimport org.apache.geode.test.dunit.rules.DistributedRestoreSystemProperties;\nimport org.apache.geode.test.dunit.rules.DistributedRule;\nimport org.apache.geode.test.junit.categories.ClientServerTest;\nimport org.apache.geode.test.junit.categories.ClientSubscriptionTest;\nimport org.apache.geode.test.junit.rules.serializable.SerializableTemporaryFolder;\n\n/**\n * Tests putAll for c/s. Also tests removeAll\n *\n * @since GemFire 5.0.23\n */\n@Category({ClientServerTest.class, ClientSubscriptionTest.class})\n@RunWith(JUnitParamsRunner.class)\n@SuppressWarnings(\"serial,NumericCastThatLosesPrecision\")\npublic class PutAllClientServerDistributedTest implements Serializable {\n\n private static final long TIMEOUT_MILLIS_LONG = getTimeout().toMillis();\n private static final int TIMEOUT_MILLIS_INTEGER = (int) TIMEOUT_MILLIS_LONG;\n private static final String TIMEOUT_MILLIS_STRING = String.valueOf(TIMEOUT_MILLIS_LONG);\n\n private static final int ONE_HUNDRED = 100;\n private static final int ONE_THOUSAND = 1000;\n private static final InternalCache DUMMY_CACHE = mock(InternalCache.class);\n private static final InternalClientCache DUMMY_CLIENT_CACHE = mock(InternalClientCache.class);\n private static final Counter DUMMY_COUNTER = new Counter(\"dummy\");\n private static final Action EMPTY_INTEGER_ACTION =\n new Action<>(null, emptyConsumer());\n\n private static final AtomicReference VALUE = new AtomicReference<>();\n private static final AtomicReference LATCH = new AtomicReference<>();\n private static final AtomicReference BEFORE = new AtomicReference<>();\n private static final AtomicReference AFTER = new AtomicReference<>();\n private static final AtomicReference COUNTER = new AtomicReference<>();\n\n private static final AtomicReference CACHE = new AtomicReference<>();\n private static final AtomicReference CLIENT_CACHE = new AtomicReference<>();\n private static final AtomicReference DISK_DIR = new AtomicReference<>();\n\n private String regionName;\n private String hostName;\n private String poolName;\n private String diskStoreName;\n private String keyPrefix;\n private String locators;\n\n private VM server1;\n private VM server2;\n private VM client1;\n private VM client2;\n\n @Rule\n public DistributedRule distributedRule = new DistributedRule();\n @Rule\n public DistributedExecutorServiceRule executorServiceRule = new DistributedExecutorServiceRule();\n @Rule\n public DistributedRestoreSystemProperties restoreProps = new DistributedRestoreSystemProperties();\n @Rule\n public SerializableTemporaryFolder temporaryFolder = new SerializableTemporaryFolder();\n\n @Before\n public void setUp() {\n regionName = getClass().getSimpleName();\n hostName = getHostName();\n poolName = \"testPool\";\n diskStoreName = \"ds1\";\n keyPrefix = \"prefix-\";\n locators = getLocators();\n\n server1 = getVM(0);\n server2 = getVM(1);\n client1 = getVM(2);\n client2 = getVM(3);\n\n for (VM vm : asList(getController(), client1, client2, server1, server2)) {\n vm.invoke(() -> {\n VALUE.set(null);\n COUNTER.set(null);\n LATCH.set(new CountDownLatch(0));\n BEFORE.set(new CountDownLatch(0));\n AFTER.set(new CountDownLatch(0));\n CACHE.set(DUMMY_CACHE);\n CLIENT_CACHE.set(DUMMY_CLIENT_CACHE);\n DISK_DIR.set(temporaryFolder.newFolder(\"diskDir-\" + getVMId()).getAbsoluteFile());\n System.setProperty(MAXIMUM_TIME_BETWEEN_PINGS_PROPERTY, TIMEOUT_MILLIS_STRING);\n });\n }\n\n addIgnoredException(ConnectException.class);\n addIgnoredException(PutAllPartialResultException.class);\n addIgnoredException(RegionDestroyedException.class);\n addIgnoredException(ServerConnectivityException.class);\n addIgnoredException(SocketException.class);\n addIgnoredException(\"Broken pipe\");\n addIgnoredException(\"Connection reset\");\n addIgnoredException(\"Unexpected IOException\");\n }\n\n @After\n public void tearDown() {\n for (VM vm : asList(getController(), client1, client2, server1, server2)) {\n vm.invoke(() -> {\n countDown(LATCH);\n countDown(BEFORE);\n countDown(AFTER);\n closeClientCache();\n closeCache();\n PoolManager.close();\n DISK_DIR.set(null);\n });\n }\n }\n\n /**\n * Tests putAll to one server.\n */\n @Test\n public void testOneServer() throws Exception {\n int serverPort = server1.invoke(() -> new ServerBuilder()\n .regionShortcut(REPLICATE)\n .create());\n\n client1.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort)\n .subscriptionAckInterval()\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n client2.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort)\n .subscriptionAckInterval()\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n region.registerInterest(\"ALL_KEYS\");\n });\n\n client1.invoke(() -> {\n getClientCache()\n .createClientRegionFactory(ClientRegionShortcut.LOCAL)\n .create(\"localsave\");\n\n Region region = getClientCache().getRegion(regionName);\n doPutAll(region, \"key-\", ONE_HUNDRED);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n });\n\n client1.invoke(() -> {\n BEFORE.set(new CountDownLatch(1));\n AFTER.set(new CountDownLatch(1));\n });\n\n AsyncInvocation createCqInClient1 = client1.invokeAsync(() -> {\n // create a CQ for key 10-20\n Region localSaveRegion = getClientCache().getRegion(\"localsave\");\n\n CqAttributesFactory cqAttributesFactory = new CqAttributesFactory();\n cqAttributesFactory.addCqListener(new CountingCqListener<>(localSaveRegion));\n CqAttributes cqAttributes = cqAttributesFactory.create();\n\n String cqName = \"EOInfoTracker\";\n String query = String.join(\" \",\n \"SELECT ALL * FROM \" + SEPARATOR + regionName + \" ii\",\n \"WHERE ii.getTicker() >= '10' and ii.getTicker() < '20'\");\n\n CqQuery cqQuery = getClientCache().getQueryService().newCq(cqName, query, cqAttributes);\n\n SelectResults results = cqQuery.executeWithInitialResults();\n List resultsAsList = results.asList();\n for (int i = 0; i < resultsAsList.size(); i++) {\n Struct struct = resultsAsList.get(i);\n TickerData tickerData = (TickerData) struct.get(\"value\");\n localSaveRegion.put(\"key-\" + i, tickerData);\n }\n\n countDown(BEFORE);\n awaitLatch(AFTER);\n\n cqQuery.close();\n });\n\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"key-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n }\n });\n\n // verify CQ is ready\n client1.invoke(() -> {\n awaitLatch(BEFORE);\n\n Region localSaveRegion = getClientCache().getRegion(\"localsave\");\n await().untilAsserted(() -> assertThat(localSaveRegion.size()).isGreaterThan(0));\n });\n\n // verify registerInterest result at client2\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.size()).isEqualTo(ONE_HUNDRED));\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"key-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n }\n\n // then do update for key 10-20 to trigger CQ at server2\n // destroy key 10-14 to simulate create/update mix case\n region.removeAll(asList(\"key-10\", \"key-11\", \"key-12\", \"key-13\", \"key-14\"));\n assertThat(region.get(\"key-10\")).isNull();\n assertThat(region.get(\"key-11\")).isNull();\n assertThat(region.get(\"key-12\")).isNull();\n assertThat(region.get(\"key-13\")).isNull();\n assertThat(region.get(\"key-14\")).isNull();\n });\n\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n Map map = new LinkedHashMap<>();\n for (int i = 10; i < 20; i++) {\n map.put(\"key-\" + i, new TickerData(i * 10));\n }\n region.putAll(map);\n });\n\n // verify CQ result at client1\n client1.invoke(() -> {\n Region localSaveRegion = getClientCache().getRegion(\"localsave\");\n\n for (int i = 10; i < 20; i++) {\n String key = \"key-\" + i;\n int price = i * 10;\n await().untilAsserted(() -> {\n TickerData tickerData = localSaveRegion.get(key);\n assertThat(tickerData.getPrice()).isEqualTo(price);\n });\n }\n\n countDown(AFTER);\n });\n\n createCqInClient1.await();\n\n // Test Exception handling\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n\n Throwable thrown = catchThrowable(() -> region.putAll(null));\n assertThat(thrown).isInstanceOf(NullPointerException.class);\n\n region.localDestroyRegion();\n\n Map puts = new LinkedHashMap<>();\n for (int i = 1; i < 21; i++) {\n puts.put(\"key-\" + i, null);\n }\n\n thrown = catchThrowable(() -> region.putAll(puts));\n assertThat(thrown).isInstanceOf(RegionDestroyedException.class);\n\n thrown = catchThrowable(() -> region.removeAll(asList(\"key-10\", \"key-11\")));\n assertThat(thrown).isInstanceOf(RegionDestroyedException.class);\n });\n }\n\n /**\n * Tests putAll afterUpdate event contained oldValue.\n */\n @Test\n public void testOldValueInEvent() {\n // set notifyBySubscription=false to test local-invalidates\n int serverPort1 = server1.invoke(() -> new ServerBuilder()\n .regionShortcut(REPLICATE)\n .create());\n int serverPort2 = server2.invoke(() -> new ServerBuilder()\n .regionShortcut(REPLICATE)\n .create());\n\n client1.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort1)\n .subscriptionAckInterval()\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n client2.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort2)\n .subscriptionAckInterval()\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n\n client2.invoke(() -> {\n LATCH.set(new CountDownLatch(1));\n\n Region region = getClientCache().getRegion(regionName);\n region.getAttributesMutator()\n .addCacheListener(new ActionCacheListener<>(new Action<>(Operation.UPDATE,\n event -> {\n assertThat(event.getOldValue()).isNotNull();\n VALUE.set(event.getOldValue());\n countDown(LATCH);\n })));\n region.registerInterest(\"ALL_KEYS\");\n });\n\n client1.invoke(() -> {\n LATCH.set(new CountDownLatch(1));\n\n Region region = getClientCache().getRegion(regionName);\n region.getAttributesMutator()\n .addCacheListener(new ActionCacheListener<>(new Action<>(Operation.UPDATE,\n event -> {\n assertThat(event.getOldValue()).isNotNull();\n VALUE.set(event.getOldValue());\n countDown(LATCH);\n })));\n\n // create keys\n doPutAll(region, keyPrefix, ONE_HUNDRED);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n\n // update keys\n doPutAll(region, keyPrefix, ONE_HUNDRED);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n });\n\n // the local PUTALL_UPDATE event should contain old value\n client1.invoke(() -> {\n awaitLatch(LATCH);\n assertThat(VALUE.get()).isInstanceOf(TickerData.class);\n });\n\n client2.invoke(() -> {\n awaitLatch(LATCH);\n assertThat(VALUE.get()).isInstanceOf(TickerData.class);\n });\n }\n\n /**\n * Create PR without redundancy on 2 servers with lucene index. Feed some key s. From a client, do\n * removeAll on keys in server1. During the removeAll, restart server1 and trigger the removeAll\n * to retry. The retried removeAll should return the version tag of tombstones. Do removeAll again\n * on the same key, it should get the version tag again.\n */\n @Test\n public void shouldReturnVersionTagOfTombstoneVersionWhenRemoveAllRetried() {\n // set notifyBySubscription=false to test local-invalidates\n int serverPort1 = server1.invoke(() -> new ServerBuilder()\n .regionShortcut(PARTITION_PERSISTENT)\n .create());\n\n client1.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort1)\n .create());\n\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n doPutAll(region, \"key-\", ONE_HUNDRED);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n });\n\n // verify cache server 1, its data is from client\n server1.invoke(() -> {\n assertThat(getCache().getRegion(regionName).size()).isEqualTo(ONE_HUNDRED);\n });\n\n VersionedObjectList versions = client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n VersionedObjectList versionsToReturn = doRemoveAll(region, \"key-\", ONE_HUNDRED);\n assertThat(region.size()).isZero();\n return versionsToReturn;\n });\n\n // client1 removeAll again\n VersionedObjectList versionsAfterRetry = client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n VersionedObjectList versionsToReturn = doRemoveAll(region, \"key-\", ONE_HUNDRED);\n assertThat(region.size()).isZero();\n return versionsToReturn;\n });\n\n // noinspection rawtypes\n List versionTags = versions.getVersionTags();\n // noinspection rawtypes\n List versionTagsAfterRetry = versionsAfterRetry.getVersionTags();\n assertThat(versionTags)\n .hasSameSizeAs(versionTagsAfterRetry)\n .containsAll(versionTagsAfterRetry);\n }\n\n /**\n * Tests putAll and removeAll to 2 servers. Use Case: 1) putAll from a single-threaded client to a\n * replicated region 2) putAll from a multi-threaded client to a replicated region 3)\n */\n @Test\n public void test2Server() throws Exception {\n int serverPort1 = server1.invoke(() -> new ServerBuilder()\n .regionShortcut(REPLICATE)\n .create());\n int serverPort2 = server2.invoke(() -> new ServerBuilder()\n .regionShortcut(REPLICATE)\n .create());\n\n client1.invoke(() -> new ClientBuilder()\n .registerInterest(true)\n .serverPorts(serverPort1)\n .subscriptionAckInterval()\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n client2.invoke(() -> new ClientBuilder()\n .registerInterest(true)\n .serverPorts(serverPort2)\n .subscriptionAckInterval()\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n\n // client1 putAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n doPutAll(region, \"key-\", ONE_HUNDRED);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"key-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n }\n });\n\n // verify cache server 1\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator().setCacheWriter(new CountingCacheWriter<>());\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"key-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n }\n });\n\n // verify cache server 2\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator().setCacheWriter(new CountingCacheWriter<>());\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"key-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n }\n });\n\n // client2 verify putAll\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.size()).isEqualTo(ONE_HUNDRED));\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n Entry regionEntry = region.getEntry(\"key-\" + i);\n assertThat(regionEntry.getValue()).isNull();\n }\n });\n\n // client1 removeAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n doRemoveAll(region, \"key-\", ONE_HUNDRED);\n assertThat(region.size()).isZero();\n });\n\n // verify removeAll cache server 1\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n assertThat(region.size()).isZero();\n\n CountingCacheWriter countingCacheWriter =\n (CountingCacheWriter) region.getAttributes().getCacheWriter();\n assertThat(countingCacheWriter.getDestroys()).isEqualTo(ONE_HUNDRED);\n });\n\n // verify removeAll cache server 2\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n assertThat(region.size()).isZero();\n\n CountingCacheWriter countingCacheWriter =\n (CountingCacheWriter) region.getAttributes().getCacheWriter();\n // beforeDestroys are only triggered at server1 since removeAll is submitted from client1\n assertThat(countingCacheWriter.getDestroys()).isZero();\n });\n\n // client2 verify removeAll\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.size()).isZero());\n });\n\n // async putAll1 from client1\n AsyncInvocation putAll1InClient1 = client1.invokeAsync(\n () -> doPutAll(getClientCache().getRegion(regionName), \"async1key-\", ONE_HUNDRED));\n\n // async putAll2 from client1\n AsyncInvocation putAll2InClient1 = client1.invokeAsync(\n () -> doPutAll(getClientCache().getRegion(regionName), \"async2key-\", ONE_HUNDRED));\n\n putAll1InClient1.await();\n putAll2InClient1.await();\n\n // verify client 1 for async keys\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED * 2);\n\n long timeStamp1 = 0;\n long timeStamp2 = 0;\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"async1key-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n assertThat(tickerData.getTimeStamp()).isGreaterThanOrEqualTo(timeStamp1);\n timeStamp1 = tickerData.getTimeStamp();\n\n tickerData = region.getEntry(\"async2key-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n assertThat(tickerData.getTimeStamp()).isGreaterThanOrEqualTo(timeStamp2);\n timeStamp2 = tickerData.getTimeStamp();\n }\n });\n\n // verify cache server 1 for async keys\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED * 2);\n\n long timeStamp1 = 0;\n long timeStamp2 = 0;\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"async1key-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n assertThat(tickerData.getTimeStamp()).isGreaterThanOrEqualTo(timeStamp1);\n timeStamp1 = tickerData.getTimeStamp();\n\n tickerData = region.getEntry(\"async2key-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n assertThat(tickerData.getTimeStamp()).isGreaterThanOrEqualTo(timeStamp2);\n timeStamp2 = tickerData.getTimeStamp();\n }\n });\n\n // verify cache server 2 for async keys\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED * 2);\n\n long timeStamp1 = 0;\n long timeStamp2 = 0;\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"async1key-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n assertThat(tickerData.getTimeStamp()).isGreaterThanOrEqualTo(timeStamp1);\n timeStamp1 = tickerData.getTimeStamp();\n\n tickerData = region.getEntry(\"async2key-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n assertThat(tickerData.getTimeStamp()).isGreaterThanOrEqualTo(timeStamp2);\n timeStamp2 = tickerData.getTimeStamp();\n }\n });\n\n // client2 verify async putAll\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.size()).isEqualTo(ONE_HUNDRED * 2));\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n Entry regionEntry = region.getEntry(\"async1key-\" + i);\n assertThat(regionEntry.getValue()).isNull();\n }\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n Entry regionEntry = region.getEntry(\"async2key-\" + i);\n assertThat(regionEntry.getValue()).isNull();\n }\n });\n\n // async removeAll1 from client1\n AsyncInvocation removeAll1InClient1 = client1.invokeAsync(() -> {\n doRemoveAll(getClientCache().getRegion(regionName), \"async1key-\", ONE_HUNDRED);\n });\n\n // async removeAll2 from client1\n AsyncInvocation removeAll2InClient1 = client1.invokeAsync(() -> {\n doRemoveAll(getClientCache().getRegion(regionName), \"async2key-\", ONE_HUNDRED);\n });\n\n removeAll1InClient1.await();\n removeAll2InClient1.await();\n\n // client1 removeAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n doRemoveAll(region, \"key-\", ONE_HUNDRED);\n assertThat(region.size()).isZero();\n });\n\n // verify async removeAll cache server 1\n server1.invoke(() -> {\n assertThat(getCache().getRegion(regionName).size()).isZero();\n });\n\n // verify async removeAll cache server 2\n server2.invoke(() -> {\n assertThat(getCache().getRegion(regionName).size()).isZero();\n });\n\n // client2 verify async removeAll\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.size()).isZero());\n });\n\n // server1 execute P2P putAll\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n doPutAll(region, \"p2pkey-\", ONE_HUNDRED);\n\n long timeStamp = 0;\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"p2pkey-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n assertThat(tickerData.getTimeStamp()).isGreaterThanOrEqualTo(timeStamp);\n timeStamp = tickerData.getTimeStamp();\n }\n });\n\n // verify cache server 2 for p2p keys\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n\n long timeStamp = 0;\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"p2pkey-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n assertThat(tickerData.getTimeStamp()).isGreaterThanOrEqualTo(timeStamp);\n timeStamp = tickerData.getTimeStamp();\n }\n });\n\n // client2 verify p2p putAll\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.size()).isEqualTo(ONE_HUNDRED));\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n Entry regionEntry = region.getEntry(\"p2pkey-\" + i);\n assertThat(regionEntry.getValue()).isNull();\n }\n });\n\n // client1 verify p2p putAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.size()).isEqualTo(ONE_HUNDRED));\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n Entry regionEntry = region.getEntry(\"p2pkey-\" + i);\n assertThat(regionEntry.getValue()).isNull();\n }\n });\n\n // server1 execute P2P removeAll\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n doRemoveAll(region, \"p2pkey-\", ONE_HUNDRED);\n assertThat(region.size()).isZero();\n });\n\n // verify p2p removeAll cache server 2\n server2.invoke(() -> {\n assertThat(getCache().getRegion(regionName).size()).isZero();\n });\n\n // client2 verify p2p removeAll\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.size()).isZero());\n });\n\n // client1 verify p2p removeAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.size()).isZero());\n });\n\n // execute putAll on client2 for key 0-10\n client2.invoke(() -> doPutAll(getClientCache().getRegion(regionName), \"key-\", 10));\n\n // verify client1 for local invalidate\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n for (int i = 0; i < 10; i++) {\n String key = \"key-\" + i;\n\n await(\"entry with null value exists for \" + key).until(() -> {\n Entry regionEntry = region.getEntry(key);\n return regionEntry != null && regionEntry.getValue() == null;\n });\n\n // local invalidate will set the value to null\n TickerData tickerData = region.getEntry(\"key-\" + i).getValue();\n assertThat(tickerData).isNull();\n }\n });\n }\n\n @Test\n @Parameters({\"true\", \"false\"})\n @TestCaseName(\"{method}(concurrencyChecksEnabled={0})\")\n public void test2NormalServer(boolean concurrencyChecksEnabled) {\n Properties config = getDistributedSystemProperties();\n config.setProperty(LOCATORS, locators);\n\n // set notifyBySubscription=false to test local-invalidates\n int serverPort1 = server1.invoke(() -> {\n createCache(new CacheFactory(config));\n return createServerRegion(regionName, concurrencyChecksEnabled);\n });\n int serverPort2 = server2.invoke(() -> {\n createCache(new CacheFactory(config));\n return createServerRegion(regionName, concurrencyChecksEnabled);\n });\n\n client1.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort1)\n .create());\n client2.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort2)\n .create());\n\n // test case 1: putAll and removeAll to server1\n\n // client1 add listener and putAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n doPutAll(region, \"case1-\", ONE_HUNDRED);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"case1-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n }\n\n region.put(String.valueOf(ONE_HUNDRED), new TickerData());\n });\n\n // verify cache server 1\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator().setCacheWriter(new CountingCacheWriter<>());\n\n region.localDestroy(String.valueOf(ONE_HUNDRED));\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"case1-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n }\n });\n\n // verify cache server 2\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator().setCacheWriter(new CountingCacheWriter<>());\n // normal policy will not distribute create events\n assertThat(region.size()).isZero();\n });\n\n // client1 removeAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED + 1);\n\n // do removeAll with some keys not exist\n doRemoveAll(region, \"case1-\", ONE_HUNDRED * 2);\n assertThat(region.size()).isEqualTo(1);\n\n region.localDestroy(String.valueOf(ONE_HUNDRED));\n });\n\n // verify removeAll cache server 1\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n assertThat(region.size()).isZero();\n\n CountingCacheWriter countingCacheWriter =\n (CountingCacheWriter) region.getAttributes().getCacheWriter();\n assertThat(countingCacheWriter.getDestroys()).isEqualTo(ONE_HUNDRED);\n });\n\n // verify removeAll cache server 2\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n assertThat(region.size()).isZero();\n\n CountingCacheWriter countingCacheWriter =\n (CountingCacheWriter) region.getAttributes().getCacheWriter();\n // beforeDestroys are only triggered at server1 since the removeAll is submitted from client1\n assertThat(countingCacheWriter.getDestroys()).isZero();\n });\n\n // client2 verify removeAll\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.size()).isZero());\n });\n\n // test case 2: putAll to server1, removeAll to server2\n\n // client1 add listener and putAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n doPutAll(region, \"case2-\", ONE_HUNDRED);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"case2-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n }\n });\n\n // verify cache server 1\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"case2-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n }\n });\n\n // verify cache server 2\n server2.invoke(() -> {\n // normal policy will not distribute create events\n assertThat(getCache().getRegion(regionName).size()).isZero();\n });\n\n // client1 removeAll\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n doRemoveAll(region, \"case2-\", ONE_HUNDRED);\n assertThat(region.size()).isZero();\n });\n\n // verify removeAll cache server 1\n server1.invoke(() -> {\n assertThat(getCache().getRegion(regionName).size()).isEqualTo(100);\n });\n\n // verify removeAll cache server 2\n server2.invoke(() -> {\n assertThat(getCache().getRegion(regionName).size()).isZero();\n });\n\n // client1 verify removeAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.size()).isEqualTo(100));\n doRemoveAll(region, \"case2-\", ONE_HUNDRED);\n });\n\n // test case 3: removeAll a list with duplicated keys\n\n // put 3 keys then removeAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n region.put(\"case3-1\", new TickerData());\n region.put(\"case3-2\", new TickerData());\n region.put(\"case3-3\", new TickerData());\n assertThat(region.size()).isEqualTo(3);\n\n Collection keys = new ArrayList<>();\n keys.add(\"case3-1\");\n keys.add(\"case3-2\");\n keys.add(\"case3-3\");\n keys.add(\"case3-1\");\n region.removeAll(keys);\n assertThat(region.size()).isZero();\n });\n\n // verify cache server 1\n server1.invoke(() -> {\n assertThat(getCache().getRegion(regionName).size()).isZero();\n });\n }\n\n @Test\n @Parameters({\"PARTITION,1\", \"PARTITION,0\", \"REPLICATE,0\"})\n @TestCaseName(\"{method}(isPR={0}, redundantCopies={1})\")\n public void testPRServerRVDuplicatedKeys(RegionShortcut regionShortcut, int redundantCopies) {\n int serverPort1 = server1.invoke(() -> new ServerBuilder()\n .redundantCopies(redundantCopies)\n .regionShortcut(regionShortcut)\n .create());\n int serverPort2 = server2.invoke(() -> new ServerBuilder()\n .redundantCopies(redundantCopies)\n .regionShortcut(regionShortcut)\n .create());\n\n client1.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort1)\n .create());\n client2.invoke(() -> new ClientBuilder()\n .registerInterest(true)\n .serverPorts(serverPort2)\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n\n // client1 add listener and putAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n doPutAll(region, \"key-\", ONE_HUNDRED);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"key-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n }\n });\n\n // test case 3: removeAll a list with duplicated keys\n\n // put 3 keys then removeAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n region.put(\"case3-1\", new TickerData());\n region.put(\"case3-2\", new TickerData());\n region.put(\"case3-3\", new TickerData());\n });\n\n // verify cache server 2\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n\n await().untilAsserted(() -> {\n Entry regionEntry = region.getEntry(\"case3-1\");\n assertThat(regionEntry).isNotNull();\n\n regionEntry = region.getEntry(\"case3-2\");\n assertThat(regionEntry).isNotNull();\n\n regionEntry = region.getEntry(\"case3-3\");\n assertThat(regionEntry).isNotNull();\n });\n });\n\n // put 3 keys then removeAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n\n Collection keys = new ArrayList<>();\n keys.add(\"case3-1\");\n keys.add(\"case3-2\");\n keys.add(\"case3-3\");\n keys.add(\"case3-1\");\n region.removeAll(keys);\n\n Entry regionEntry = region.getEntry(\"case3-1\");\n assertThat(regionEntry).isNull();\n\n regionEntry = region.getEntry(\"case3-2\");\n assertThat(regionEntry).isNull();\n\n regionEntry = region.getEntry(\"case3-3\");\n assertThat(regionEntry).isNull();\n });\n\n // verify cache server 1\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n\n Entry regionEntry = region.getEntry(\"case3-1\");\n assertThat(regionEntry).isNull();\n\n regionEntry = region.getEntry(\"case3-2\");\n assertThat(regionEntry).isNull();\n\n regionEntry = region.getEntry(\"case3-3\");\n assertThat(regionEntry).isNull();\n });\n\n // verify cache server 2\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n\n Entry regionEntry = region.getEntry(\"case3-1\");\n assertThat(regionEntry).isNull();\n\n regionEntry = region.getEntry(\"case3-2\");\n assertThat(regionEntry).isNull();\n\n regionEntry = region.getEntry(\"case3-3\");\n assertThat(regionEntry).isNull();\n });\n\n // verify cache server 2\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n\n await().untilAsserted(() -> {\n Entry regionEntry = region.getEntry(\"case3-1\");\n assertThat(regionEntry).isNull();\n\n regionEntry = region.getEntry(\"case3-2\");\n assertThat(regionEntry).isNull();\n\n regionEntry = region.getEntry(\"case3-3\");\n assertThat(regionEntry).isNull();\n });\n });\n }\n\n /**\n * Bug: Data inconsistency between client/server with HA (Object is missing in client cache)\n *\n *

    \n * This is a known issue for persist region with HA.\n *

      \n *
    • client1 sends putAll key1,key2 to server1\n *
    • server1 applied the key1 locally, but the putAll failed due to CacheClosedException? (HA\n * test).\n *
    • Then client1 will not have key1. But when server1 is restarted, it recovered key1 from\n * persistence.\n *
    • Then data mismatch btw client and server.\n *
    \n *\n *

    \n * There's a known issue which can be improved by changing the test:\n *

      \n *
    • edge_14640 sends a putAll to servers. But the server is shutdown due to HA test. However at\n * that time, the putAll might have put the key into local cache.\n *
    • When the server is restarted, the servers will have the key, other clients will also have\n * the key (due to register interest), but the calling client (i.e. edge_14640) will not have the\n * key, unless it's restarted.\n *
    \n *\n *
    \n   * In above scenario, even changing redundantCopies to 1 will not help. This is the known issue. To improve the test, we should let all the clients restart before doing verification.\n   * How to verify the result falls into above scenario?\n   * 1) errors.txt, the edge_14640 has inconsistent cache compared with server's snapshot.\n   * 2) grep Object_82470 *.log and found the mismatched key is originated from 14640.\n   * 
    \n */\n @Test\n @Parameters({\"true\", \"false\"})\n @TestCaseName(\"{method}(singleHop={0})\")\n public void clientPutAllIsMissingKeyUntilShutdownServerRestarts(boolean singleHop) {\n int serverPort1 = server1.invoke(() -> new ServerBuilder()\n .regionShortcut(PARTITION_PERSISTENT)\n .create());\n server2.invoke(() -> new ServerBuilder()\n .regionShortcut(PARTITION_PERSISTENT)\n .create());\n\n client1.invoke(() -> new ClientBuilder()\n .prSingleHopEnabled(singleHop)\n .serverPorts(serverPort1)\n .create());\n client2.invoke(() -> new ClientBuilder()\n .prSingleHopEnabled(singleHop)\n .serverPorts(serverPort1)\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n\n // client2 add listener\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n region.registerInterest(\"ALL_KEYS\");\n });\n\n // put 3 keys then removeAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n\n // do putAll to create all buckets\n doPutAll(region, \"key-\", ONE_HUNDRED);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n });\n\n server2.invoke(() -> getCache().close());\n\n // putAll from client again\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n\n String message =\n String.format(\"Region %s putAll at server applied partial keys due to exception.\",\n region.getFullPath());\n\n Throwable thrown = catchThrowable(() -> doPutAll(region, keyPrefix, ONE_HUNDRED));\n\n assertThat(thrown)\n .isInstanceOf(ServerOperationException.class)\n .hasMessageContaining(message)\n .getCause()\n .isInstanceOf(PartitionOfflineException.class);\n\n assertThat(region.size()).isEqualTo(ONE_HUNDRED * 3 / 2);\n\n int count = 0;\n for (int i = 0; i < ONE_HUNDRED; i++) {\n VersionTag tag = ((InternalRegion) region).getVersionTag(keyPrefix + i);\n if (tag != null && 1 == tag.getEntryVersion()) {\n count++;\n }\n }\n\n assertThat(count).isEqualTo(ONE_HUNDRED / 2);\n\n message = String.format(\n \"Region %s removeAll at server applied partial keys due to exception.\",\n region.getFullPath());\n\n thrown = catchThrowable(() -> doRemoveAll(region, keyPrefix, ONE_HUNDRED));\n\n assertThat(thrown)\n .isInstanceOf(ServerOperationException.class)\n .hasMessageContaining(message)\n .getCause()\n .isInstanceOf(PartitionOfflineException.class);\n\n // putAll only created 50 entries, removeAll removed them. So 100 entries are all NULL\n for (int i = 0; i < ONE_HUNDRED; i++) {\n Entry regionEntry = region.getEntry(keyPrefix + i);\n assertThat(regionEntry).isNull();\n }\n });\n\n // verify entries from client2\n client2.invoke(() -> await().untilAsserted(() -> {\n Region region = getClientCache().getRegion(regionName);\n for (int i = 0; i < ONE_HUNDRED; i++) {\n Entry regionEntry = region.getEntry(keyPrefix + i);\n assertThat(regionEntry).isNull();\n }\n }));\n }\n\n /**\n * Tests putAll to 2 PR servers.\n */\n @Test\n public void testPRServer() throws Exception {\n // set means to test local-invalidates\n int serverPort1 = server1.invoke(() -> new ServerBuilder()\n .redundantCopies(1)\n .regionShortcut(PARTITION)\n .create());\n int serverPort2 = server2.invoke(() -> new ServerBuilder()\n .redundantCopies(1)\n .regionShortcut(PARTITION)\n .create());\n\n client1.invoke(() -> new ClientBuilder()\n .registerInterest(true)\n .serverPorts(serverPort1)\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n client2.invoke(() -> new ClientBuilder()\n .registerInterest(true)\n .serverPorts(serverPort2)\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n\n // client1 putAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n doPutAll(region, \"key-\", ONE_HUNDRED);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"key-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n }\n });\n\n // verify cache server 1\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator().setCacheWriter(new CountingCacheWriter<>());\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"key-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n }\n });\n\n // verify cache server 2\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator().setCacheWriter(new CountingCacheWriter<>());\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"key-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n }\n });\n\n // verify client2\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.size()).isEqualTo(ONE_HUNDRED));\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n Entry regionEntry = region.getEntry(\"key-\" + i);\n assertThat(regionEntry.getValue()).isNull();\n }\n });\n\n // client1 removeAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n doRemoveAll(region, \"key-\", ONE_HUNDRED);\n assertThat(region.size()).isZero();\n });\n\n // verify removeAll cache server 1\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n assertThat(region.size()).isZero();\n\n CountingCacheWriter countingCacheWriter =\n (CountingCacheWriter) region.getAttributes().getCacheWriter();\n // beforeDestroys are only triggered at primary buckets.\n // server1 and server2 each holds half of buckets\n assertThat(countingCacheWriter.getDestroys()).isEqualTo(ONE_HUNDRED / 2);\n });\n\n // verify removeAll cache server 2\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n assertThat(region.size()).isZero();\n\n CountingCacheWriter countingCacheWriter =\n (CountingCacheWriter) region.getAttributes().getCacheWriter();\n // beforeDestroys are only triggered at primary buckets.\n // server1 and server2 each holds half of buckets\n assertThat(countingCacheWriter.getDestroys()).isEqualTo(ONE_HUNDRED / 2);\n });\n\n // client2 verify removeAll\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.size()).isZero());\n });\n\n // Execute client putAll from multithread client\n\n // async putAll1 from client1\n AsyncInvocation putAll1InClient1 = client1.invokeAsync(\n () -> doPutAll(getClientCache().getRegion(regionName), \"async1key-\", ONE_HUNDRED));\n\n // async putAll2 from client1\n AsyncInvocation putAll2InClient1 = client1.invokeAsync(\n () -> doPutAll(getClientCache().getRegion(regionName), \"async2key-\", ONE_HUNDRED));\n\n putAll1InClient1.await();\n putAll2InClient1.await();\n\n // verify client 1 for async keys\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED * 2);\n\n long timeStamp1 = 0;\n long timeStamp2 = 0;\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"async1key-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n assertThat(tickerData.getTimeStamp()).isGreaterThanOrEqualTo(timeStamp1);\n timeStamp1 = tickerData.getTimeStamp();\n\n tickerData = region.getEntry(\"async2key-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n assertThat(tickerData.getTimeStamp()).isGreaterThanOrEqualTo(timeStamp2);\n timeStamp2 = tickerData.getTimeStamp();\n }\n });\n\n // verify cache server 2 for async keys\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n\n long timeStamp1 = 0;\n long timeStamp2 = 0;\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"async1key-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n assertThat(tickerData.getTimeStamp()).isGreaterThanOrEqualTo(timeStamp1);\n timeStamp1 = tickerData.getTimeStamp();\n\n tickerData = region.getEntry(\"async2key-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n assertThat(tickerData.getTimeStamp()).isGreaterThanOrEqualTo(timeStamp2);\n timeStamp2 = tickerData.getTimeStamp();\n }\n });\n\n // client2 verify async putAll\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.size()).isEqualTo(ONE_HUNDRED * 2));\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n Entry regionEntry = region.getEntry(\"async1key-\" + i);\n assertThat(regionEntry.getValue()).isNull();\n }\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n Entry regionEntry = region.getEntry(\"async2key-\" + i);\n assertThat(regionEntry.getValue()).isNull();\n }\n });\n\n // async removeAll1 from client1\n AsyncInvocation removeAll1InClient1 = client1.invokeAsync(() -> {\n doRemoveAll(getClientCache().getRegion(regionName), \"async1key-\", ONE_HUNDRED);\n });\n\n // async removeAll2 from client1\n AsyncInvocation removeAll2InClient1 = client1.invokeAsync(() -> {\n doRemoveAll(getClientCache().getRegion(regionName), \"async2key-\", ONE_HUNDRED);\n });\n\n removeAll1InClient1.await();\n removeAll2InClient1.await();\n\n // client1 removeAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n doRemoveAll(region, \"key-\", ONE_HUNDRED);\n assertThat(region.size()).isZero();\n });\n\n // verify async removeAll cache server 1\n server1.invoke(() -> {\n assertThat(getCache().getRegion(regionName).size()).isZero();\n });\n\n // verify async removeAll cache server 2\n server2.invoke(() -> {\n assertThat(getCache().getRegion(regionName).size()).isZero();\n });\n\n // client2 verify async removeAll\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.size()).isZero());\n });\n\n // server1 execute P2P putAll\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n doPutAll(region, \"p2pkey-\", ONE_HUNDRED);\n\n long timeStamp = 0;\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"p2pkey-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n assertThat(tickerData.getTimeStamp()).isGreaterThanOrEqualTo(timeStamp);\n timeStamp = tickerData.getTimeStamp();\n }\n });\n\n // verify cache server 2 for async keys\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n\n long timeStamp = 0;\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"p2pkey-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n assertThat(tickerData.getTimeStamp()).isGreaterThanOrEqualTo(timeStamp);\n timeStamp = tickerData.getTimeStamp();\n }\n });\n\n // client2 verify p2p putAll\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.size()).isEqualTo(ONE_HUNDRED));\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n Entry regionEntry = region.getEntry(\"p2pkey-\" + i);\n assertThat(regionEntry.getValue()).isNull();\n }\n });\n\n // client1 verify p2p putAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.size()).isEqualTo(ONE_HUNDRED));\n\n for (int i = 0; i < ONE_HUNDRED; i++) {\n Entry regionEntry = region.getEntry(\"p2pkey-\" + i);\n assertThat(regionEntry.getValue()).isNull();\n }\n });\n\n // server1 execute P2P removeAll\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n doRemoveAll(region, \"p2pkey-\", ONE_HUNDRED);\n assertThat(region.size()).isZero();\n });\n\n // verify p2p removeAll cache server 2\n server2.invoke(() -> {\n assertThat(getCache().getRegion(regionName).size()).isZero();\n });\n\n // client2 verify p2p removeAll\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.size()).isZero());\n });\n\n // client1 verify p2p removeAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.size()).isZero());\n });\n\n // execute putAll on client2 for key 0-10\n client2.invoke(() -> doPutAll(getClientCache().getRegion(regionName), \"key-\", 10));\n\n // verify client1 for local invalidate\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n\n for (int i = 0; i < 10; i++) {\n String key = \"key-\" + i;\n\n await().until(() -> {\n Entry regionEntry = region.getEntry(key);\n return regionEntry != null && regionEntry.getValue() == null;\n });\n\n // local invalidate will set the value to null\n TickerData tickerData = region.getEntry(\"key-\" + i).getValue();\n assertThat(tickerData).isNull();\n }\n });\n }\n\n /**\n * Checks to see if a client does a destroy that throws an exception from CacheWriter\n * beforeDestroy that the size of the region is still correct. See bug 51583.\n */\n @Test\n public void testClientDestroyOfUncreatedEntry() {\n // set means to test local-invalidates\n int serverPort1 = server1.invoke(() -> new ServerBuilder()\n .regionShortcut(REPLICATE)\n .create());\n\n client1.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort1)\n .create());\n\n // server1 add cacheWriter\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n // Install cacheWriter that causes the very first destroy to fail\n region.getAttributesMutator()\n .setCacheWriter(new ActionCacheWriter<>(new Action<>(Operation.DESTROY,\n destroys -> {\n if (destroys >= 0) {\n throw new CacheWriterException(\"Expected by test\");\n }\n })));\n assertThat(region.size()).isZero();\n });\n\n // client1 destroy\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n Throwable thrown = catchThrowable(() -> region.destroy(\"bogusKey\"));\n assertThat(thrown)\n .isInstanceOf(ServerOperationException.class)\n .hasCauseInstanceOf(CacheWriterException.class);\n });\n\n server1.invoke(() -> {\n assertThat(getCache().getRegion(regionName).size()).isZero();\n });\n }\n\n /**\n * Tests partial key putAll and removeAll to 2 servers with local region\n */\n @Test\n public void testPartialKeyInLocalRegion() {\n // set means to test local-invalidates\n int serverPort1 = server1.invoke(() -> new ServerBuilder()\n .regionShortcut(REPLICATE)\n .create());\n server2.invoke(() -> new ServerBuilder()\n .regionShortcut(REPLICATE)\n .create());\n\n client1.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort1)\n .create());\n client2.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort1)\n .subscriptionAckInterval()\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n\n // server1 add cacheWriter\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n // let the server to trigger exception after created 15 keys\n region.getAttributesMutator()\n .setCacheWriter(new ActionCacheWriter<>(new Action<>(Operation.CREATE,\n creates -> {\n if (creates >= 15) {\n throw new CacheWriterException(\"Expected by test\");\n }\n })));\n });\n\n // client2 register interest\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n region.registerInterest(\"ALL_KEYS\");\n });\n\n // client1 putAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n\n String message =\n String.format(\"Region %s putAll at server applied partial keys due to exception.\",\n region.getFullPath());\n\n Throwable thrown = catchThrowable(() -> doPutAll(region, \"key-\", ONE_HUNDRED));\n\n assertThat(thrown)\n .isInstanceOf(ServerOperationException.class)\n .hasMessageContaining(message)\n .getCause()\n .isInstanceOf(CacheWriterException.class);\n });\n\n await().untilAsserted(() -> {\n assertThat(client1.invoke(() -> getClientCache().getRegion(regionName).size())).isEqualTo(15);\n assertThat(client2.invoke(() -> getClientCache().getRegion(regionName).size())).isEqualTo(15);\n assertThat(server1.invoke(() -> getCache().getRegion(regionName).size())).isEqualTo(15);\n assertThat(server2.invoke(() -> getCache().getRegion(regionName).size())).isEqualTo(15);\n });\n\n int sizeOnServer1 = server1.invoke(() -> getCache().getRegion(regionName).size());\n\n // server1 add cacheWriter\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n // let the server to trigger exception after created 15 keys\n region.getAttributesMutator()\n .setCacheWriter(new ActionCacheWriter<>(new Action<>(Operation.CREATE,\n creates -> {\n if (creates >= 15) {\n throw new CacheWriterException(\"Expected by test\");\n }\n })));\n });\n\n // server2 add listener and putAll\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n Throwable thrown = catchThrowable(() -> doPutAll(region, \"key-\" + \"again:\", ONE_HUNDRED));\n assertThat(thrown).isInstanceOf(CacheWriterException.class);\n });\n\n int sizeOnServer2 = server2.invoke(() -> getCache().getRegion(regionName).size());\n assertThat(sizeOnServer2).isEqualTo(sizeOnServer1 + 15);\n\n await().untilAsserted(() -> {\n // client 1 did not register interest\n assertThat(client1.invoke(() -> getClientCache().getRegion(regionName).size())).isEqualTo(15);\n assertThat(client2.invoke(() -> getClientCache().getRegion(regionName).size()))\n .isEqualTo(15 * 2);\n assertThat(server1.invoke(() -> getCache().getRegion(regionName).size())).isEqualTo(15 * 2);\n assertThat(server2.invoke(() -> getCache().getRegion(regionName).size())).isEqualTo(15 * 2);\n });\n\n // server1 add cacheWriter\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n // server triggers exception after destroying 5 keys\n region.getAttributesMutator()\n .setCacheWriter(new ActionCacheWriter<>(new Action<>(Operation.DESTROY,\n creates -> {\n if (creates >= 5) {\n throw new CacheWriterException(\"Expected by test\");\n }\n })));\n });\n\n // client1 removeAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n\n String message =\n String.format(\"Region %s removeAll at server applied partial keys due to exception.\",\n region.getFullPath());\n\n Throwable thrown = catchThrowable(() -> doRemoveAll(region, \"key-\", ONE_HUNDRED));\n\n assertThat(thrown)\n .isInstanceOf(ServerOperationException.class)\n .hasMessageContaining(message)\n .getCause()\n .isInstanceOf(CacheWriterException.class);\n });\n\n await().untilAsserted(() -> {\n // client 1 did not register interest\n assertThat(client1.invoke(() -> getClientCache().getRegion(regionName).size()))\n .isEqualTo(15 - 5);\n assertThat(client2.invoke(() -> getClientCache().getRegion(regionName).size()))\n .isEqualTo(15 * 2 - 5);\n assertThat(server1.invoke(() -> getCache().getRegion(regionName).size()))\n .isEqualTo(15 * 2 - 5);\n assertThat(server2.invoke(() -> getCache().getRegion(regionName).size()))\n .isEqualTo(15 * 2 - 5);\n });\n\n // server1 add cacheWriter\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n // server triggers exception after destroying 5 keys\n region.getAttributesMutator()\n .setCacheWriter(new ActionCacheWriter<>(new Action<>(Operation.DESTROY,\n ops -> {\n if (ops >= 5) {\n throw new CacheWriterException(\"Expected by test\");\n }\n })));\n });\n\n // server2 add listener and removeAll\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n Throwable thrown = catchThrowable(() -> doRemoveAll(region, \"key-\" + \"again:\", ONE_HUNDRED));\n assertThat(thrown).isInstanceOf(CacheWriterException.class);\n });\n\n await().untilAsserted(() -> {\n // client 1 did not register interest\n assertThat(client1.invoke(() -> getClientCache().getRegion(regionName).size()))\n .isEqualTo(15 - 5);\n assertThat(client2.invoke(() -> getClientCache().getRegion(regionName).size()))\n .isEqualTo(15 * 2 - 5 - 5);\n assertThat(server1.invoke(() -> getCache().getRegion(regionName).size()))\n .isEqualTo(15 * 2 - 5 - 5);\n assertThat(server2.invoke(() -> getCache().getRegion(regionName).size()))\n .isEqualTo(15 * 2 - 5 - 5);\n });\n }\n\n /**\n * Verify all the possible exceptions a putAll/put/removeAll/destroy could return\n */\n @Test\n public void testPutAllReturnsExceptions() {\n // set means to test local-invalidates\n int serverPort1 = server1.invoke(() -> new ServerBuilder()\n .regionShortcut(REPLICATE)\n .create());\n server2.invoke(() -> new ServerBuilder()\n .regionShortcut(REPLICATE)\n .create());\n\n client1.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort1)\n .create());\n\n // server1 add cacheWriter\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n // let the server to trigger exception after created 15 keys\n region.getAttributesMutator()\n .setCacheWriter(new ActionCacheWriter<>(new Action<>(Operation.CREATE,\n creates -> {\n if (creates >= 15) {\n throw new CacheWriterException(\"Expected by test\");\n }\n })));\n\n Throwable thrown = catchThrowable(() -> doPutAll(region, \"key-\", ONE_HUNDRED));\n assertThat(thrown).isInstanceOf(CacheWriterException.class);\n\n thrown = catchThrowable(() -> region.put(\"dummyKey\", new TickerData(0)));\n assertThat(thrown).isInstanceOf(CacheWriterException.class);\n });\n\n // client1 putAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n\n String message =\n String.format(\"Region %s putAll at server applied partial keys due to exception.\",\n region.getFullPath());\n\n Throwable thrown = catchThrowable(() -> doPutAll(region, \"key-\", ONE_HUNDRED));\n\n assertThat(thrown)\n .isInstanceOf(ServerOperationException.class)\n .hasMessageContaining(message)\n .hasCauseInstanceOf(CacheWriterException.class);\n\n thrown = catchThrowable(() -> region.put(\"dummyKey\", new TickerData(0)));\n assertThat(thrown)\n .isInstanceOf(ServerOperationException.class)\n .hasCauseInstanceOf(CacheWriterException.class);\n });\n\n // let server1 to throw CancelException\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n // let the server to trigger exception after created 15 keys\n region.getAttributesMutator()\n .setCacheWriter(new ActionCacheWriter<>(new Action<>(Operation.CREATE,\n creates -> {\n throw new OplogCancelledException(\"Expected by test\");\n })));\n\n Throwable thrown = catchThrowable(() -> doPutAll(region, \"key-\", ONE_HUNDRED));\n assertThat(thrown).isInstanceOf(OplogCancelledException.class);\n\n thrown = catchThrowable(() -> region.put(\"dummyKey\", new TickerData(0)));\n assertThat(thrown).isInstanceOf(OplogCancelledException.class);\n });\n\n // client1 putAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n\n Throwable thrown = catchThrowable(() -> doPutAll(region, \"key-\", ONE_HUNDRED));\n assertThat(thrown)\n .isInstanceOf(ServerConnectivityException.class)\n .hasCauseInstanceOf(OplogCancelledException.class);\n\n thrown = catchThrowable(() -> region.put(\"dummyKey\", new TickerData(0)));\n assertThat(thrown)\n .isInstanceOf(ServerConnectivityException.class)\n .hasCauseInstanceOf(OplogCancelledException.class);\n });\n\n // let server1 to throw LowMemoryException\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n // let the server to trigger exception after created 15 keys\n region.getAttributesMutator()\n .setCacheWriter(new ActionCacheWriter<>(new Action<>(Operation.CREATE,\n creates -> {\n throw new LowMemoryException(\"Testing\", emptySet());\n })));\n\n Throwable thrown = catchThrowable(() -> doPutAll(region, \"key-\", ONE_HUNDRED));\n assertThat(thrown).isInstanceOf(LowMemoryException.class);\n\n thrown = catchThrowable(() -> region.put(\"dummyKey\", new TickerData(0)));\n assertThat(thrown).isInstanceOf(LowMemoryException.class);\n });\n\n // client1 putAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n\n Throwable thrown = catchThrowable(() -> doPutAll(region, \"key-\", ONE_HUNDRED));\n assertThat(thrown)\n .isInstanceOf(ServerOperationException.class)\n .getCause()\n .isInstanceOf(LowMemoryException.class);\n\n thrown = catchThrowable(() -> region.put(\"dummyKey\", new TickerData(0)));\n assertThat(thrown)\n .isInstanceOf(ServerOperationException.class)\n .getCause()\n .isInstanceOf(LowMemoryException.class);\n });\n\n // let server1 to throw TimeoutException\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n // let the server to trigger exception after created 15 keys\n region.getAttributesMutator()\n .setCacheWriter(new ActionCacheWriter<>(new Action<>(Operation.CREATE,\n creates -> {\n throw new TimeoutException(\"Testing\");\n })));\n\n Map map = new LinkedHashMap<>();\n for (int i = 0; i < ONE_HUNDRED; i++) {\n map.put(keyPrefix + i, new TickerData(i));\n }\n\n Throwable thrown = catchThrowable(() -> region.putAll(map));\n assertThat(thrown)\n .isInstanceOf(TimeoutException.class)\n .hasNoCause();\n\n thrown = catchThrowable(() -> region.put(\"dummyKey\", new TickerData(0)));\n assertThat(thrown)\n .isInstanceOf(TimeoutException.class)\n .hasNoCause();\n\n thrown = catchThrowable(() -> doPutAll(region, \"key-\", ONE_HUNDRED));\n assertThat(thrown)\n .isInstanceOf(TimeoutException.class)\n .hasNoCause();\n\n thrown = catchThrowable(() -> region.put(\"dummyKey\", new TickerData(0)));\n assertThat(thrown)\n .isInstanceOf(TimeoutException.class)\n .hasNoCause();\n });\n\n // client1 putAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n\n Map map = new LinkedHashMap<>();\n for (int i = 0; i < ONE_HUNDRED; i++) {\n map.put(keyPrefix + i, new TickerData(i));\n }\n\n Throwable thrown = catchThrowable(() -> region.putAll(map));\n assertThat(thrown)\n .isInstanceOf(ServerOperationException.class)\n .hasCauseInstanceOf(TimeoutException.class);\n\n thrown = catchThrowable(() -> region.put(\"dummyKey\", new TickerData(0)));\n assertThat(thrown)\n .isInstanceOf(ServerOperationException.class)\n .hasCauseInstanceOf(TimeoutException.class);\n\n thrown = catchThrowable(() -> doPutAll(region, \"key-\", ONE_HUNDRED));\n assertThat(thrown)\n .isInstanceOf(ServerOperationException.class)\n .hasCauseInstanceOf(TimeoutException.class);\n\n thrown = catchThrowable(() -> region.put(\"dummyKey\", new TickerData(0)));\n assertThat(thrown)\n .isInstanceOf(ServerOperationException.class)\n .hasCauseInstanceOf(TimeoutException.class);\n });\n }\n\n /**\n * Tests partial key putAll to 2 PR servers, because putting data at server side is different\n * between PR and LR. PR does it in postPutAll. It's not running in singleHop putAll\n */\n @Test\n public void testPartialKeyInPR() throws Exception {\n // set means to test local-invalidates\n int serverPort1 = server1.invoke(() -> new ServerBuilder()\n .regionShortcut(PARTITION_PERSISTENT)\n .create());\n int serverPort2 = server2.invoke(() -> new ServerBuilder()\n .regionShortcut(PARTITION_PERSISTENT)\n .create());\n\n for (VM clientVM : asList(client1, client2)) {\n clientVM.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort1, serverPort2)\n .subscriptionAckInterval()\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n }\n\n // server1 add slow listener\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator().addCacheListener(new SlowCacheListener<>());\n });\n\n // server2 add slow listener\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator()\n .addCacheListener(new SlowCountingCacheListener<>(new Action<>(Operation.CREATE,\n creates -> executorServiceRule.submit(() -> closeCacheConditionally(creates, 10)))));\n });\n\n // client2 add listener\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n region.getAttributesMutator().addCacheListener(new SlowCacheListener<>());\n region.registerInterest(\"ALL_KEYS\");\n });\n\n // client1 add listener and putAll\n AsyncInvocation registerInterestAndPutAllInClient1 = client1.invokeAsync(() -> {\n Region region = getClientCache().getRegion(regionName);\n region.getAttributesMutator().addCacheListener(new SlowCacheListener<>());\n region.registerInterest(\"ALL_KEYS\");\n\n String message =\n String.format(\"Region %s putAll at server applied partial keys due to exception.\",\n region.getFullPath());\n\n Throwable thrown = catchThrowable(() -> doPutAll(region, \"Key-\", ONE_HUNDRED));\n\n assertThat(thrown)\n .isInstanceOf(ServerOperationException.class)\n .hasMessageContaining(message)\n .getCause()\n .isInstanceOf(PartitionOfflineException.class);\n });\n\n // server2 will closeCache after created 10 keys\n\n registerInterestAndPutAllInClient1.await();\n\n int sizeOnClient1 = client1.invoke(() -> getClientCache().getRegion(regionName).size());\n // client2Size maybe more than client1Size\n int sizeOnClient2 = client2.invoke(() -> getClientCache().getRegion(regionName).size());\n\n // restart server2\n server2.invoke(() -> {\n new ServerBuilder().regionShortcut(PARTITION_PERSISTENT).create();\n });\n\n await().untilAsserted(() -> {\n assertThat(server1.invoke(() -> getCache().getRegion(regionName).size()))\n .isEqualTo(sizeOnClient2);\n assertThat(server2.invoke(() -> getCache().getRegion(regionName).size()))\n .isEqualTo(sizeOnClient2);\n });\n\n // close a server to re-run the test\n server2.invoke(() -> getCache().close());\n int sizeOnServer1 = server1.invoke(() -> getCache().getRegion(regionName).size());\n\n // client1 does putAll again\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n\n String message =\n String.format(\"Region %s putAll at server applied partial keys due to exception.\",\n region.getFullPath());\n\n Throwable thrown = catchThrowable(() -> doPutAll(region, \"key-\" + \"again:\", ONE_HUNDRED));\n\n assertThat(thrown)\n .isInstanceOf(ServerOperationException.class)\n .hasMessageContaining(message)\n .getCause()\n .isInstanceOf(PartitionOfflineException.class);\n });\n\n int newSizeOnServer1 = server1.invoke(() -> getCache().getRegion(regionName).size());\n int newSizeOnClient1 = client1.invoke(() -> getClientCache().getRegion(regionName).size());\n int newSizeOnClient2 = client2.invoke(() -> getClientCache().getRegion(regionName).size());\n\n assertThat(newSizeOnServer1).isEqualTo(sizeOnServer1 + ONE_HUNDRED / 2);\n assertThat(newSizeOnClient1).isEqualTo(sizeOnClient1 + ONE_HUNDRED / 2);\n assertThat(newSizeOnClient2).isEqualTo(sizeOnClient2 + ONE_HUNDRED / 2);\n\n // restart server2\n server2.invoke(() -> {\n new ServerBuilder().regionShortcut(PARTITION_PERSISTENT).create();\n });\n sizeOnServer1 = server1.invoke(() -> getCache().getRegion(regionName).size());\n int sizeOnServer2 = server2.invoke(() -> getCache().getRegion(regionName).size());\n assertThat(sizeOnServer2).isEqualTo(sizeOnServer1);\n\n // server1 execute P2P putAll\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n // let the server to trigger exception after created 15 keys\n region.getAttributesMutator()\n .setCacheWriter(new ActionCacheWriter<>(new Action<>(Operation.CREATE,\n creates -> {\n if (creates >= 15) {\n throw new CacheWriterException(\"Expected by test\");\n }\n })));\n });\n\n // server2 add listener and putAll\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n Throwable thrown =\n catchThrowable(() -> doPutAll(region, \"key-\" + \"once again:\", ONE_HUNDRED));\n assertThat(thrown)\n .isInstanceOf(CacheWriterException.class)\n .hasMessageContaining(\"Expected by test\");\n });\n\n newSizeOnServer1 = server1.invoke(() -> getCache().getRegion(regionName).size());\n int newSizeOnServer2 = server2.invoke(() -> getCache().getRegion(regionName).size());\n assertThat(newSizeOnServer1).isEqualTo(sizeOnServer1 + 15);\n assertThat(newSizeOnServer2).isEqualTo(sizeOnServer2 + 15);\n }\n\n /**\n * Tests partial key putAll to 2 PR servers, because putting data at server side is different\n * between PR and LR. PR does it in postPutAll. This is a singlehop putAll test.\n */\n @Test\n public void testPartialKeyInPRSingleHop() throws Exception {\n // set means to test local-invalidates\n int serverPort1 = server1.invoke(() -> new ServerBuilder()\n .regionShortcut(PARTITION_PERSISTENT)\n .create());\n int serverPort2 = server2.invoke(() -> new ServerBuilder()\n .regionShortcut(PARTITION_PERSISTENT)\n .create());\n\n client1.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort1, serverPort2)\n .create());\n client2.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort1, serverPort2)\n .subscriptionAckInterval()\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n\n // client2 add listener\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n region.registerInterest(\"ALL_KEYS\");\n });\n\n // do some putAll to get ClientMetaData for future putAll\n client1.invoke(() -> doPutAll(getClientCache().getRegion(regionName), \"key-\", ONE_HUNDRED));\n\n await().untilAsserted(() -> {\n assertThat(client1.invoke(() -> getClientCache().getRegion(regionName).size()))\n .isEqualTo(ONE_HUNDRED);\n assertThat(client2.invoke(() -> getClientCache().getRegion(regionName).size()))\n .isEqualTo(ONE_HUNDRED);\n assertThat(server1.invoke(() -> getCache().getRegion(regionName).size()))\n .isEqualTo(ONE_HUNDRED);\n assertThat(server2.invoke(() -> getCache().getRegion(regionName).size()))\n .isEqualTo(ONE_HUNDRED);\n });\n\n // server1 add slow listener\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator().addCacheListener(new SlowCacheListener<>());\n });\n\n // add a listener that will close the cache at the 10th update\n\n // server2 add slow listener\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator()\n .addCacheListener(new SlowCountingCacheListener<>(new Action<>(Operation.CREATE,\n creates -> executorServiceRule.submit(() -> closeCacheConditionally(creates, 10)))));\n });\n\n // client1 add listener and putAll\n AsyncInvocation addListenerAndPutAllInClient1 = client1.invokeAsync(() -> {\n Region region = getClientCache().getRegion(regionName);\n\n String message =\n String.format(\"Region %s putAll at server applied partial keys due to exception.\",\n region.getFullPath());\n\n Throwable thrown = catchThrowable(() -> doPutAll(region, keyPrefix, ONE_HUNDRED));\n\n assertThat(thrown)\n .isInstanceOf(ServerOperationException.class)\n .hasMessageContaining(message)\n .getCause()\n .isInstanceOf(PartitionOfflineException.class);\n });\n\n // server2 will closeCache after creating 10 keys\n\n addListenerAndPutAllInClient1.await();\n\n // restart server2\n server2.invoke(() -> {\n new ServerBuilder().regionShortcut(PARTITION_PERSISTENT).create();\n });\n\n // Test Case1: Trigger singleHop putAll. Stop server2 in middle.\n // ONE_HUNDRED_ENTRIES/2 + X keys will be created at servers. i.e. X keys at server2,\n // ONE_HUNDRED_ENTRIES/2 keys at server1.\n // The client should receive a PartialResultException due to PartitionOffline\n\n // close a server to re-run the test\n server2.invoke(() -> getCache().close());\n\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n\n String message =\n String.format(\"Region %s putAll at server applied partial keys due to exception.\",\n region.getFullPath());\n\n Throwable thrown = catchThrowable(() -> doPutAll(region, keyPrefix + \"again:\", ONE_HUNDRED));\n\n assertThat(thrown)\n .isInstanceOf(ServerOperationException.class)\n .hasMessageContaining(message)\n .getCause()\n .isInstanceOf(PartitionOfflineException.class);\n });\n\n // Test Case 2: based on case 1, but this time, there should be no X keys\n // created on server2.\n\n // restart server2\n server2.invoke(() -> {\n new ServerBuilder().regionShortcut(PARTITION_PERSISTENT).create();\n });\n\n // add a cacheWriter for server to fail putAll after it created cacheWriterAllowedKeyNum keys\n int throwAfterNumberCreates = 16;\n\n // server1 add cacheWriter to throw exception after created some keys\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator()\n .setCacheWriter(new ActionCacheWriter<>(new Action<>(Operation.CREATE,\n creates -> {\n if (creates >= throwAfterNumberCreates) {\n throw new CacheWriterException(\"Expected by test\");\n }\n })));\n });\n\n // client1 does putAll once more\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n\n String message =\n String.format(\"Region %s putAll at server applied partial keys due to exception.\",\n region.getFullPath());\n\n Throwable thrown =\n catchThrowable(() -> doPutAll(region, keyPrefix + \"once more:\", ONE_HUNDRED));\n\n assertThat(thrown)\n .isInstanceOf(ServerOperationException.class)\n .hasMessageContaining(message)\n .getCause()\n .isInstanceOf(CacheWriterException.class)\n .hasMessageContaining(\"Expected by test\");\n });\n }\n\n /**\n * Set redundancy=1 to see if retry succeeded after PRE This is a singlehop putAll test.\n */\n @Test\n public void testPartialKeyInPRSingleHopWithRedundancy() throws Exception {\n // set means to test local-invalidates\n int serverPort1 = server1.invoke(() -> new ServerBuilder()\n .redundantCopies(1)\n .regionShortcut(PARTITION_PERSISTENT)\n .create());\n int serverPort2 = server2.invoke(() -> new ServerBuilder()\n .redundantCopies(1)\n .regionShortcut(PARTITION_PERSISTENT)\n .create());\n\n client1.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort1, serverPort2)\n .subscriptionAckInterval()\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n client2.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort1, serverPort2)\n .subscriptionAckInterval()\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n\n // client2 add listener\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n region.registerInterest(\"ALL_KEYS\");\n });\n\n // do some putAll to get ClientMetaData for future putAll\n client1.invoke(() -> doPutAll(getClientCache().getRegion(regionName), \"key-\", ONE_HUNDRED));\n\n await().untilAsserted(() -> {\n assertThat(client1.invoke(() -> getClientCache().getRegion(regionName).size()))\n .isEqualTo(ONE_HUNDRED);\n assertThat(client2.invoke(() -> getClientCache().getRegion(regionName).size()))\n .isEqualTo(ONE_HUNDRED);\n assertThat(server1.invoke(() -> getCache().getRegion(regionName).size()))\n .isEqualTo(ONE_HUNDRED);\n assertThat(server2.invoke(() -> getCache().getRegion(regionName).size()))\n .isEqualTo(ONE_HUNDRED);\n });\n\n // server1 add slow listener\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator().addCacheListener(new SlowCacheListener<>());\n });\n\n // server2 add slow listener\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator()\n .addCacheListener(new SlowCountingCacheListener<>(new Action<>(Operation.CREATE,\n creates -> executorServiceRule.submit(() -> closeCacheConditionally(creates, 10)))));\n });\n\n // client1 add listener and putAll\n AsyncInvocation registerInterestAndPutAllInClient1 = client1.invokeAsync(() -> {\n Region region = getClientCache().getRegion(regionName);\n region.registerInterest(\"ALL_KEYS\");\n\n // create keys\n doPutAll(region, keyPrefix, ONE_HUNDRED);\n });\n\n // server2 will closeCache after created 10 keys\n\n registerInterestAndPutAllInClient1.await();\n\n int sizeOnClient1 = client1.invoke(() -> getClientCache().getRegion(regionName).size());\n int sizeOnClient2 = client2.invoke(() -> getClientCache().getRegion(regionName).size());\n int sizeOnServer1 = server1.invoke(() -> getCache().getRegion(regionName).size());\n // putAll should succeed after retry\n assertThat(sizeOnClient1).isEqualTo(sizeOnServer1);\n assertThat(sizeOnClient2).isEqualTo(sizeOnServer1);\n\n // restart server2\n server2.invoke(() -> {\n new ServerBuilder()\n .redundantCopies(1)\n .regionShortcut(PARTITION_PERSISTENT)\n .create();\n });\n\n sizeOnServer1 = server1.invoke(() -> getCache().getRegion(regionName).size());\n int sizeOnServer2 = server2.invoke(() -> getCache().getRegion(regionName).size());\n assertThat(sizeOnServer1).isEqualTo(sizeOnClient2);\n assertThat(sizeOnServer2).isEqualTo(sizeOnClient2);\n\n // close a server to re-run the test\n server2.invoke(() -> getCache().close());\n\n // client1 does putAll again\n client1.invoke(\n () -> doPutAll(getClientCache().getRegion(regionName), keyPrefix + \"again:\", ONE_HUNDRED));\n\n int newSizeOnServer1 = server1.invoke(() -> getCache().getRegion(regionName).size());\n int newSizeOnClient1 = client1.invoke(() -> getClientCache().getRegion(regionName).size());\n int newSizeOnClient2 = client2.invoke(() -> getClientCache().getRegion(regionName).size());\n\n // putAll should succeed, all the numbers should match\n assertThat(newSizeOnClient1).isEqualTo(newSizeOnServer1);\n assertThat(newSizeOnClient2).isEqualTo(newSizeOnServer1);\n }\n\n /**\n * The purpose of this test is to validate that when two servers of three in a cluster configured\n * with a client doing singlehop, that the client gets afterCreate messages for each entry in the\n * putall. Further, we also check that the region size is correct on the remaining server.\n */\n @Test\n public void testEventIdOutOfOrderInPartitionRegionSingleHop() {\n VM server3 = client2;\n\n int serverPort1 = server1.invoke(() -> new ServerBuilder()\n .regionShortcut(PARTITION)\n .create());\n int serverPort2 = server2.invoke(() -> new ServerBuilder()\n .regionShortcut(PARTITION)\n .create());\n int serverPort3 = server3.invoke(() -> new ServerBuilder()\n .regionShortcut(PARTITION)\n .create());\n\n client1.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort1, serverPort2, serverPort3)\n .subscriptionAckInterval()\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n\n // do some putAll to get ClientMetaData for future putAll\n client1.invoke(() -> {\n // register interest and add listener\n Region region = getClientCache().getRegion(regionName);\n doPutAll(getClientCache().getRegion(regionName), \"key-\", ONE_HUNDRED);\n\n COUNTER.set(new Counter(\"client1\"));\n region.getAttributesMutator()\n .addCacheListener(new CountingCacheListener<>(COUNTER.get()));\n region.registerInterest(\"ALL_KEYS\");\n });\n\n // server1 and server2 will closeCache after created 10 keys\n // server1 add slow listener\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator()\n .addCacheListener(new SlowCountingCacheListener<>(new Action<>(Operation.CREATE,\n creates -> closeCacheConditionally(creates, 10))));\n });\n\n // server2 add slow listener\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator()\n .addCacheListener(new SlowCountingCacheListener<>(new Action<>(Operation.CREATE,\n creates -> closeCacheConditionally(creates, 20))));\n });\n\n // server3 add slow listener\n server3.invoke(() -> {\n COUNTER.set(new Counter(\"server3\"));\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator()\n .addCacheListener(new SlowCountingCacheListener<>(COUNTER.get()));\n });\n\n // client1 add listener and putAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n doPutAll(region, keyPrefix, ONE_HUNDRED);\n\n assertThat(COUNTER.get().getCreates()).isEqualTo(100);\n assertThat(COUNTER.get().getUpdates()).isZero();\n });\n\n // server3 print counter\n server3.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n\n assertThat(region.size())\n .describedAs(\"Should have 100 entries plus 3 to 4 buckets worth of entries\")\n .isIn(ONE_HUNDRED + 3 * ONE_HUNDRED / 10, ONE_HUNDRED + 4 * ONE_HUNDRED / 10);\n assertThat(COUNTER.get().getUpdates()).isZero();\n verifyPutAll(region, keyPrefix);\n });\n }\n\n /**\n * Tests while putAll to 2 distributed servers, one server failed over Add a listener to slow down\n * the processing of putAll\n */\n @Test\n public void test2FailOverDistributedServer() throws Exception {\n // set notifyBySubscription=true to test register interest\n int serverPort1 = server1.invoke(() -> new ServerBuilder()\n .regionShortcut(REPLICATE)\n .create());\n int serverPort2 = server2.invoke(() -> new ServerBuilder()\n .regionShortcut(REPLICATE)\n .create());\n\n client1.invoke(() -> new ClientBuilder()\n .registerInterest(true)\n .serverPorts(serverPort1, serverPort2)\n .subscriptionAckInterval()\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n client2.invoke(() -> new ClientBuilder()\n .registerInterest(true)\n .serverPorts(serverPort1, serverPort2)\n .subscriptionAckInterval()\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n\n // server1 add slow listener\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator().addCacheListener(new SlowCacheListener<>());\n });\n\n // server2 add slow listener\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator().addCacheListener(new SlowCacheListener<>());\n });\n\n // client1 registerInterest\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n region.registerInterest(\"ALL_KEYS\");\n });\n\n // client2 registerInterest\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n region.registerInterest(\"ALL_KEYS\");\n });\n\n // async putAll1 from client1\n AsyncInvocation putAllInClient1 = client1.invokeAsync(() -> {\n try {\n doPutAll(getClientCache().getRegion(regionName), \"async1key-\", ONE_HUNDRED);\n } catch (ServerConnectivityException ignore) {\n // stopping the cache server will cause ServerConnectivityException\n // in the client if it hasn't completed performing the 100 puts yet\n }\n });\n\n // stop cache server 1\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.get(\"async1key-1\")).isNotNull());\n stopCacheServer(serverPort1);\n });\n\n putAllInClient1.await();\n\n // verify cache server 2 for async keys\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n\n long timeStamp = 0;\n for (int i = 0; i < ONE_HUNDRED; i++) {\n TickerData tickerData = region.getEntry(\"async1key-\" + i).getValue();\n assertThat(tickerData.getPrice()).isEqualTo(i);\n assertThat(tickerData.getTimeStamp()).isGreaterThanOrEqualTo(timeStamp);\n timeStamp = tickerData.getTimeStamp();\n }\n });\n }\n\n /**\n * Tests while putAll timeout's exception\n */\n @Test\n public void testClientTimeOut() {\n // set notifyBySubscription=true to test register interest\n int serverPort1 = server1.invoke(() -> new ServerBuilder()\n .regionShortcut(REPLICATE)\n .create());\n int serverPort2 = server2.invoke(() -> new ServerBuilder()\n .regionShortcut(REPLICATE)\n .create());\n\n client1.invoke(() -> new ClientBuilder()\n .readTimeoutMillis(DEFAULT_READ_TIMEOUT)\n .registerInterest(true)\n .serverPorts(serverPort1, serverPort2)\n .subscriptionAckInterval()\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n client2.invoke(() -> new ClientBuilder()\n .readTimeoutMillis(DEFAULT_READ_TIMEOUT)\n .registerInterest(true)\n .serverPorts(serverPort1, serverPort2)\n .subscriptionAckInterval()\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n\n // server1 add slow listener\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator().addCacheListener(new SlowCacheListener<>());\n });\n\n // server2 add slow listener\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator().addCacheListener(new SlowCacheListener<>());\n });\n\n // client1 execute putAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n Throwable thrown = catchThrowable(() -> doPutAll(region, \"key-\", ONE_THOUSAND));\n assertThat(thrown).isInstanceOf(ServerConnectivityException.class);\n });\n }\n\n /**\n * Tests while putAll timeout at endpoint1 and switch to endpoint2\n */\n @Test\n public void testEndPointSwitch() {\n // set notifyBySubscription=true to test register interest\n int serverPort1 = server1.invoke(() -> new ServerBuilder()\n .regionShortcut(REPLICATE)\n .create());\n int serverPort2 = server2.invoke(() -> new ServerBuilder()\n .regionShortcut(REPLICATE)\n .create());\n\n client1.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort1, serverPort2)\n .create());\n client2.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort1, serverPort2)\n .subscriptionAckInterval()\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n\n // only add slow listener to server1, because we wish it to succeed\n\n // server1 add slow listener\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator().addCacheListener(new SlowCacheListener<>());\n });\n\n // only register interest on client2\n // client2 registerInterest\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n region.registerInterest(\"ALL_KEYS\");\n });\n\n // putAll from client1\n client1.invoke(() -> doPutAll(getClientCache().getRegion(regionName), keyPrefix, ONE_HUNDRED));\n\n // verify Bridge client2 for keys arrived finally\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.size()).isEqualTo(ONE_HUNDRED));\n });\n }\n\n /**\n * Tests while putAll to 2 distributed servers, one server failed over Add a listener to slow down\n * the processing of putAll\n */\n @Test\n public void testHADRFailOver() throws Exception {\n addIgnoredException(DistributedSystemDisconnectedException.class);\n\n // set notifyBySubscription=true to test register interest\n int serverPort1 = server1.invoke(() -> new ServerBuilder()\n .regionShortcut(REPLICATE)\n .create());\n int serverPort2 = server2.invoke(() -> new ServerBuilder()\n .regionShortcut(REPLICATE)\n .create());\n\n client1.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort1, serverPort2)\n .subscriptionEnabled(true)\n .subscriptionAckInterval()\n .subscriptionRedundancy()\n .create());\n client2.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort1, serverPort2)\n .subscriptionAckInterval()\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n\n // client1 registerInterest\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n region.registerInterest(\"ALL_KEYS\");\n });\n\n // client2 registerInterest\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n region.registerInterest(\"ALL_KEYS\");\n });\n\n // async putAll1 from server2\n AsyncInvocation putAllInServer2 = server2\n .invokeAsync(() -> doPutAll(getCache().getRegion(regionName), \"server2-key-\", ONE_HUNDRED));\n\n // async putAll1 from client1\n AsyncInvocation putAllInClient1 = client1.invokeAsync(\n () -> doPutAll(getClientCache().getRegion(regionName), \"client1-key-\", ONE_HUNDRED));\n\n // stop cache server 1\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n await().untilAsserted(() -> {\n assertThat(region.get(\"server2-key-1\")).isNotNull();\n assertThat(region.get(\"client1-key-1\")).isNotNull();\n });\n stopCacheServer(serverPort1);\n });\n\n putAllInServer2.await();\n putAllInClient1.await();\n\n // verify Bridge client2 for async keys\n client2.invokeAsync(() -> {\n Region region = getClientCache().getRegion(regionName);\n await().untilAsserted(() -> assertThat(region.size()).isEqualTo(ONE_HUNDRED * 2));\n });\n }\n\n @Test\n public void testVersionsOnClientsWithNotificationsOnly() {\n // set notifyBySubscription=true to test register interest\n int serverPort1 = server1.invoke(() -> new ServerBuilder()\n .regionShortcut(PARTITION)\n .create());\n int serverPort2 = server2.invoke(() -> new ServerBuilder()\n .regionShortcut(PARTITION)\n .create());\n\n // set queueRedundancy=1\n client1.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort1)\n .create());\n client2.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort2)\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n\n // client1 putAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n doPutAll(region, \"key-\", ONE_HUNDRED * 2);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED * 2);\n });\n\n // client2 versions collection\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n region.registerInterest(\"ALL_KEYS\");\n });\n\n // client1 versions collection\n List> client1Versions = client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED * 2);\n\n RegionMap entries = ((DiskRecoveryStore) region).getRegionMap();\n List> versions = new ArrayList<>();\n for (Object key : entries.keySet()) {\n RegionEntry regionEntry = entries.getEntry(key);\n VersionTag tag = regionEntry.getVersionStamp().asVersionTag();\n versions.add(tag);\n }\n\n return versions;\n });\n\n // client2 versions collection\n List> client2Versions = client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED * 2);\n\n RegionMap entries = ((DiskRecoveryStore) region).getRegionMap();\n List> versions = new ArrayList<>();\n for (Object key : entries.keySet()) {\n RegionEntry regionEntry = entries.getEntry(key);\n VersionTag tag = regionEntry.getVersionStamp().asVersionTag();\n versions.add(tag);\n }\n\n return versions;\n });\n\n assertThat(client1Versions.size()).isEqualTo(ONE_HUNDRED * 2);\n\n for (VersionTag tag : client1Versions) {\n assertThat(client2Versions).contains(tag);\n }\n }\n\n /**\n * basically same test as testVersionsOnClientsWithNotificationsOnly but also do a removeAll\n */\n @Test\n public void testRAVersionsOnClientsWithNotificationsOnly() {\n // set notifyBySubscription=true to test register interest\n int serverPort1 = server1.invoke(() -> new ServerBuilder()\n .regionShortcut(PARTITION)\n .create());\n int serverPort2 = server2.invoke(() -> new ServerBuilder()\n .regionShortcut(PARTITION)\n .create());\n\n // set queueRedundancy=1\n client1.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort1)\n .create());\n client2.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort2)\n .subscriptionEnabled(true)\n .create());\n\n // client1 putAll+removeAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n\n doPutAll(region, \"key-\", ONE_HUNDRED * 2);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED * 2);\n\n doRemoveAll(region, \"key-\", ONE_HUNDRED);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n });\n\n // client2 versions collection\n client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n region.registerInterest(\"ALL_KEYS\");\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n });\n\n // client1 versions collection\n List> client1RAVersions = client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n\n RegionMap entries = ((DiskRecoveryStore) region).getRegionMap();\n assertThat(entries.size()).isEqualTo(ONE_HUNDRED * 2);\n\n List> versions = new ArrayList<>();\n for (Object key : entries.keySet()) {\n RegionEntry regionEntry = entries.getEntry(key);\n VersionTag tag = regionEntry.getVersionStamp().asVersionTag();\n versions.add(tag);\n }\n return versions;\n });\n\n // client2 versions collection\n List> client2RAVersions = client2.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n\n RegionMap entries = ((DiskRecoveryStore) region).getRegionMap();\n assertThat(entries.size()).isEqualTo(ONE_HUNDRED * 2);\n\n List> versions = new ArrayList<>();\n for (Object key : entries.keySet()) {\n RegionEntry regionEntry = entries.getEntry(key);\n VersionTag tag = regionEntry.getVersionStamp().asVersionTag();\n versions.add(tag);\n }\n return versions;\n });\n\n assertThat(client1RAVersions.size()).isEqualTo(ONE_HUNDRED * 2);\n\n for (VersionTag tag : client1RAVersions) {\n assertThat(client2RAVersions).contains(tag);\n }\n }\n\n @Test\n public void testVersionsOnServersWithNotificationsOnly() {\n VM server3 = client2;\n\n // set notifyBySubscription=true to test register interest\n server1.invoke(() -> new ServerBuilder()\n .redundantCopies(1)\n .regionShortcut(PARTITION)\n .create());\n server2.invoke(() -> new ServerBuilder()\n .redundantCopies(1)\n .regionShortcut(PARTITION)\n .create());\n int serverPort3 = server3.invoke(() -> new ServerBuilder()\n .redundantCopies(1)\n .regionShortcut(PARTITION)\n .create());\n\n client1.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort3)\n .subscriptionEnabled(true)\n .create());\n\n // client2 versions collection\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n region.registerInterest(\"ALL_KEYS\");\n });\n\n // client1 putAll\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n doPutAll(region, \"key-\", ONE_HUNDRED * 2);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED * 2);\n });\n\n // server1 versions collection\n List expectedVersions = server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED * 2);\n\n PartitionedRegionDataStore dataStore = ((PartitionedRegion) region).getDataStore();\n Set buckets = dataStore.getAllLocalPrimaryBucketRegions();\n\n List versions = new ArrayList<>();\n for (BucketRegion bucketRegion : buckets) {\n RegionMap entries = bucketRegion.entries;\n for (Object key : entries.keySet()) {\n RegionEntry regionEntry = entries.getEntry(key);\n VersionTag tag = regionEntry.getVersionStamp().asVersionTag();\n versions.add(key + \" \" + tag);\n }\n }\n return versions;\n });\n\n // client1 versions collection\n List actualVersions = client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n\n // Let client be updated with all keys.\n await().untilAsserted(() -> assertThat(region.size()).isEqualTo(ONE_HUNDRED * 2));\n\n RegionMap entries = ((DiskRecoveryStore) region).getRegionMap();\n List versions = new ArrayList<>();\n for (Object key : entries.keySet()) {\n RegionEntry regionEntry = entries.getEntry(key);\n VersionTag tag = regionEntry.getVersionStamp().asVersionTag();\n tag.setMemberID(null);\n versions.add(key + \" \" + tag);\n }\n return versions;\n });\n\n assertThat(actualVersions).hasSize(ONE_HUNDRED * 2);\n\n for (String keyTag : expectedVersions) {\n assertThat(actualVersions).contains(keyTag);\n }\n }\n\n /**\n * Same test as testVersionsOnServersWithNotificationsOnly but also does a removeAll\n */\n @Test\n public void testRAVersionsOnServersWithNotificationsOnly() {\n VM server3 = client2;\n\n // set notifyBySubscription=true to test register interest\n server1.invoke(() -> new ServerBuilder()\n .redundantCopies(1)\n .regionShortcut(PARTITION)\n .create());\n server2.invoke(() -> new ServerBuilder()\n .redundantCopies(1)\n .regionShortcut(PARTITION)\n .create());\n int serverPort3 = server3.invoke(() -> new ServerBuilder()\n .redundantCopies(1)\n .regionShortcut(PARTITION)\n .create());\n\n client1.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort3)\n .subscriptionEnabled(true)\n .create());\n\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n region.registerInterest(\"ALL_KEYS\");\n });\n\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n\n doPutAll(region, \"key-\", ONE_HUNDRED * 2);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED * 2);\n\n doRemoveAll(region, \"key-\", ONE_HUNDRED);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n });\n\n List expectedRAVersions = server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n\n PartitionedRegionDataStore dataStore = ((PartitionedRegion) region).getDataStore();\n Set buckets = dataStore.getAllLocalPrimaryBucketRegions();\n\n List versions = new ArrayList<>();\n for (BucketRegion bucketRegion : buckets) {\n RegionMap entries = bucketRegion.entries;\n for (Object key : entries.keySet()) {\n RegionEntry regionEntry = entries.getEntry(key);\n VersionTag tag = regionEntry.getVersionStamp().asVersionTag();\n versions.add(key + \" \" + tag);\n }\n }\n return versions;\n });\n\n List actualRAVersions = client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n\n // Let client be updated with all keys.\n RegionMap entries = ((DiskRecoveryStore) region).getRegionMap();\n\n await().untilAsserted(() -> {\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n assertThat(entries.size()).isEqualTo(ONE_HUNDRED * 2);\n });\n\n List versions = new ArrayList<>();\n for (Object key : entries.keySet()) {\n RegionEntry regionEntry = entries.getEntry(key);\n VersionTag tag = regionEntry.getVersionStamp().asVersionTag();\n tag.setMemberID(null);\n versions.add(key + \" \" + tag);\n }\n return versions;\n });\n\n assertThat(actualRAVersions).hasSize(ONE_HUNDRED * 2);\n\n for (String keyTag : expectedRAVersions) {\n assertThat(actualRAVersions).contains(keyTag);\n }\n }\n\n @Test\n public void testVersionsOnReplicasAfterPutAllAndRemoveAll() {\n // set notifyBySubscription=true to test register interest\n int serverPort1 = server1.invoke(() -> new ServerBuilder()\n .regionShortcut(REPLICATE)\n .create());\n server2.invoke(() -> new ServerBuilder()\n .regionShortcut(REPLICATE)\n .create());\n\n client1.invoke(() -> new ClientBuilder()\n .serverPorts(serverPort1)\n .create());\n\n // client1 putAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n\n doPutAll(region, \"key-\", ONE_HUNDRED * 2);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED * 2);\n\n doRemoveAll(region, \"key-\", ONE_HUNDRED);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n });\n\n // client1 versions collection\n List> client1Versions = server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n\n RegionMap entries = ((DiskRecoveryStore) region).getRegionMap();\n assertThat(entries.size()).isEqualTo(ONE_HUNDRED * 2);\n\n List> versions = new ArrayList<>();\n for (Object key : entries.keySet()) {\n RegionEntry regionEntry = entries.getEntry(key);\n VersionTag tag = regionEntry.getVersionStamp().asVersionTag();\n versions.add(tag);\n }\n return versions;\n });\n\n // client2 versions collection\n List> client2Versions = server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n assertThat(region.size()).isEqualTo(ONE_HUNDRED);\n\n RegionMap entries = ((DiskRecoveryStore) region).getRegionMap();\n assertThat(entries.size()).isEqualTo(ONE_HUNDRED * 2);\n\n List> versions = new ArrayList<>();\n for (Object key : entries.keySet()) {\n RegionEntry regionEntry = entries.getEntry(key);\n versions.add(regionEntry.getVersionStamp().asVersionTag());\n }\n return versions;\n });\n\n assertThat(client1Versions.size()).isEqualTo(ONE_HUNDRED * 2);\n\n for (VersionTag tag : client2Versions) {\n tag.setMemberID(null);\n assertThat(client1Versions).contains(tag);\n }\n }\n\n private void createCache(CacheFactory cacheFactory) {\n CACHE.set((InternalCache) cacheFactory.create());\n }\n\n private InternalCache getCache() {\n return CACHE.get();\n }\n\n private void closeCache() {\n CACHE.getAndSet(DUMMY_CACHE).close();\n }\n\n private void createClientCache(ClientCacheFactory clientCacheFactory) {\n CLIENT_CACHE.set((InternalClientCache) clientCacheFactory.create());\n }\n\n private InternalClientCache getClientCache() {\n return CLIENT_CACHE.get();\n }\n\n private void closeClientCache() {\n CLIENT_CACHE.getAndSet(DUMMY_CLIENT_CACHE).close(false);\n }\n\n private File[] getDiskDirs() {\n return new File[] {DISK_DIR.get()};\n }\n\n private int createServerRegion(String regionName, boolean concurrencyChecksEnabled)\n throws IOException {\n getCache().createRegionFactory()\n .setConcurrencyChecksEnabled(concurrencyChecksEnabled)\n .setScope(Scope.DISTRIBUTED_ACK)\n .setDataPolicy(DataPolicy.NORMAL)\n .create(regionName);\n\n CacheServer cacheServer = getCache().addCacheServer();\n cacheServer.setPort(0);\n cacheServer.start();\n return cacheServer.getPort();\n }\n\n private void doPutAll(Map region, String keyPrefix, int entryCount) {\n Map map = new LinkedHashMap<>();\n for (int i = 0; i < entryCount; i++) {\n map.put(keyPrefix + i, new TickerData(i));\n }\n region.putAll(map);\n }\n\n private void verifyPutAll(Map region, String keyPrefix) {\n for (int i = 0; i < ONE_HUNDRED; i++) {\n assertThat(region.containsKey(keyPrefix + i)).isTrue();\n }\n }\n\n private VersionedObjectList doRemoveAll(Region region, String keyPrefix,\n int entryCount) {\n InternalRegion internalRegion = (InternalRegion) region;\n\n InternalEntryEvent event =\n EntryEventImpl.create(internalRegion, Operation.REMOVEALL_DESTROY, null, null,\n null, false, internalRegion.getMyId());\n event.disallowOffHeapValues();\n\n Collection keys = new ArrayList<>();\n for (int i = 0; i < entryCount; i++) {\n keys.add(keyPrefix + i);\n }\n\n DistributedRemoveAllOperation removeAllOp =\n new DistributedRemoveAllOperation(event, keys.size(), false);\n\n return internalRegion.basicRemoveAll(keys, removeAllOp, null);\n }\n\n /**\n * Stops the cache server specified by port\n */\n private void stopCacheServer(int port) {\n boolean foundServer = false;\n for (CacheServer cacheServer : getCache().getCacheServers()) {\n if (cacheServer.getPort() == port) {\n cacheServer.stop();\n assertThat(cacheServer.isRunning()).isFalse();\n foundServer = true;\n break;\n }\n }\n assertThat(foundServer).isTrue();\n }\n\n private void closeCacheConditionally(int ops, int threshold) {\n if (ops == threshold) {\n getCache().close();\n }\n }\n\n private static Consumer emptyConsumer() {\n return input -> {\n // nothing\n };\n }\n\n private static void sleep() {\n try {\n Thread.sleep(50);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n }\n\n @SuppressWarnings(\"unchecked\")\n private static T cast(Object object) {\n return (T) object;\n }\n\n private static void awaitLatch(AtomicReference latch)\n throws InterruptedException {\n latch.get().await(TIMEOUT_MILLIS_LONG, MILLISECONDS);\n }\n\n private static void countDown(AtomicReference latch) {\n latch.get().countDown();\n }\n\n private class ServerBuilder {\n\n private int redundantCopies;\n private RegionShortcut regionShortcut;\n\n private ServerBuilder redundantCopies(int redundantCopies) {\n this.redundantCopies = redundantCopies;\n return this;\n }\n\n private ServerBuilder regionShortcut(RegionShortcut regionShortcut) {\n this.regionShortcut = regionShortcut;\n return this;\n }\n\n private int create() throws IOException {\n assertThat(regionShortcut).isNotNull();\n\n Properties config = getDistributedSystemProperties();\n config.setProperty(LOCATORS, locators);\n\n createCache(new CacheFactory(config));\n\n // In this test, no cacheLoader should be defined, otherwise, it will create a value for\n // destroyed key\n\n RegionFactory regionFactory =\n getCache().createRegionFactory(regionShortcut);\n if (regionShortcut.isPartition()) {\n regionFactory.setPartitionAttributes(new PartitionAttributesFactory()\n .setRedundantCopies(redundantCopies)\n .setTotalNumBuckets(10)\n .create());\n }\n\n // create diskStore if required\n if (regionShortcut.isPersistent()) {\n DiskStore diskStore = getCache().findDiskStore(diskStoreName);\n if (diskStore == null) {\n getCache().createDiskStoreFactory()\n .setDiskDirs(getDiskDirs())\n .create(diskStoreName);\n }\n regionFactory.setDiskStoreName(diskStoreName);\n\n } else {\n // enable concurrency checks (not for disk now - disk doesn't support versions yet)\n regionFactory.setConcurrencyChecksEnabled(true);\n }\n\n regionFactory.create(regionName);\n\n CacheServer cacheServer = getCache().addCacheServer();\n cacheServer.setMaxThreads(0);\n cacheServer.setPort(0);\n cacheServer.start();\n return cacheServer.getPort();\n }\n }\n\n private class ClientBuilder {\n\n private boolean prSingleHopEnabled = true;\n private int readTimeoutMillis = TIMEOUT_MILLIS_INTEGER;\n private boolean registerInterest;\n private final Collection serverPorts = new ArrayList<>();\n private int subscriptionAckInterval = DEFAULT_SUBSCRIPTION_ACK_INTERVAL; // 100 millis\n private boolean subscriptionEnabled = DEFAULT_SUBSCRIPTION_ENABLED; // false\n private int subscriptionRedundancy = DEFAULT_SUBSCRIPTION_REDUNDANCY; // 0\n\n private ClientBuilder prSingleHopEnabled(boolean prSingleHopEnabled) {\n this.prSingleHopEnabled = prSingleHopEnabled;\n return this;\n }\n\n private ClientBuilder readTimeoutMillis(int readTimeoutMillis) {\n this.readTimeoutMillis = readTimeoutMillis;\n return this;\n }\n\n private ClientBuilder registerInterest(boolean registerInterest) {\n this.registerInterest = registerInterest;\n return this;\n }\n\n private ClientBuilder serverPorts(Integer... serverPorts) {\n this.serverPorts.addAll(asList(serverPorts));\n return this;\n }\n\n private ClientBuilder subscriptionAckInterval() {\n subscriptionAckInterval = 1;\n return this;\n }\n\n private ClientBuilder subscriptionEnabled(boolean subscriptionEnabled) {\n this.subscriptionEnabled = subscriptionEnabled;\n return this;\n }\n\n private ClientBuilder subscriptionRedundancy() {\n subscriptionRedundancy = -1;\n return this;\n }\n\n private void create() {\n assertThat(serverPorts).isNotEmpty();\n if (subscriptionAckInterval != DEFAULT_SUBSCRIPTION_ACK_INTERVAL ||\n subscriptionRedundancy != DEFAULT_SUBSCRIPTION_REDUNDANCY) {\n assertThat(subscriptionEnabled).isTrue();\n }\n\n Properties config = getDistributedSystemProperties();\n config.setProperty(LOCATORS, \"\");\n\n createClientCache(new ClientCacheFactory(config));\n\n PoolFactory poolFactory = PoolManager.createFactory();\n for (int serverPort : serverPorts) {\n poolFactory.addServer(hostName, serverPort);\n }\n poolFactory\n .setPRSingleHopEnabled(prSingleHopEnabled)\n .setReadTimeout(readTimeoutMillis)\n .setSubscriptionAckInterval(subscriptionAckInterval)\n .setSubscriptionEnabled(subscriptionEnabled)\n .setSubscriptionRedundancy(subscriptionRedundancy)\n .create(poolName);\n\n ClientRegionFactory clientRegionFactory =\n getClientCache().createClientRegionFactory(ClientRegionShortcut.LOCAL);\n\n clientRegionFactory\n .setConcurrencyChecksEnabled(true);\n\n clientRegionFactory\n .setPoolName(poolName);\n\n Region region = clientRegionFactory\n .create(regionName);\n\n if (registerInterest) {\n region.registerInterestRegex(\".*\", false, false);\n }\n }\n }\n\n private static class Counter implements Serializable {\n\n private final AtomicInteger creates = new AtomicInteger();\n private final AtomicInteger updates = new AtomicInteger();\n private final AtomicInteger invalidates = new AtomicInteger();\n private final AtomicInteger destroys = new AtomicInteger();\n private final String owner;\n\n private Counter(String owner) {\n this.owner = owner;\n }\n\n private int getCreates() {\n return creates.get();\n }\n\n private void incCreates() {\n creates.incrementAndGet();\n }\n\n private int getUpdates() {\n return updates.get();\n }\n\n private void incUpdates() {\n updates.incrementAndGet();\n }\n\n private int getInvalidates() {\n return invalidates.get();\n }\n\n private void incInvalidates() {\n invalidates.incrementAndGet();\n }\n\n private int getDestroys() {\n return destroys.get();\n }\n\n private void incDestroys() {\n destroys.incrementAndGet();\n }\n\n @Override\n public String toString() {\n return \"Owner=\" + owner + \",create=\" + creates + \",update=\" + updates\n + \",invalidate=\" + invalidates + \",destroy=\" + destroys;\n }\n }\n\n /**\n * Defines an action to be run after the specified operation is invoked by Geode callbacks.\n */\n private static class Action {\n\n private final Operation operation;\n private final Consumer consumer;\n\n private Action(Operation operation, Consumer consumer) {\n this.operation = operation;\n this.consumer = consumer;\n }\n\n private void run(Operation operation, T value) {\n if (operation == this.operation) {\n consumer.accept(value);\n }\n }\n }\n\n private static class CountingCacheListener extends CacheListenerAdapter {\n\n private final Counter counter;\n private final Action action;\n\n private CountingCacheListener(Counter counter) {\n this(counter, EMPTY_INTEGER_ACTION);\n }\n\n private CountingCacheListener(Counter counter, Action action) {\n this.counter = counter;\n counter.creates.set(0);\n this.action = action;\n }\n\n @Override\n public void afterCreate(EntryEvent event) {\n counter.incCreates();\n action.run(Operation.CREATE, counter.getCreates());\n }\n\n @Override\n public void afterUpdate(EntryEvent event) {\n counter.incUpdates();\n action.run(Operation.UPDATE, counter.getUpdates());\n }\n\n @Override\n public void afterInvalidate(EntryEvent event) {\n counter.incInvalidates();\n action.run(Operation.INVALIDATE, counter.getInvalidates());\n }\n\n @Override\n public void afterDestroy(EntryEvent event) {\n counter.incDestroys();\n action.run(Operation.DESTROY, counter.getDestroys());\n }\n }\n\n private static class SlowCacheListener extends CacheListenerAdapter {\n\n @Override\n public void afterCreate(EntryEvent event) {\n sleep();\n }\n\n @Override\n public void afterUpdate(EntryEvent event) {\n sleep();\n }\n }\n\n private static class SlowCountingCacheListener extends CountingCacheListener {\n\n private SlowCountingCacheListener(Action action) {\n this(DUMMY_COUNTER, action);\n }\n\n private SlowCountingCacheListener(Counter counter) {\n this(counter, EMPTY_INTEGER_ACTION);\n }\n\n private SlowCountingCacheListener(Counter counter, Action action) {\n super(counter, action);\n }\n\n @Override\n public void afterCreate(EntryEvent event) {\n super.afterCreate(event);\n sleep();\n }\n\n @Override\n public void afterUpdate(EntryEvent event) {\n super.afterUpdate(event);\n sleep();\n }\n }\n\n private static class ActionCacheListener extends CacheListenerAdapter {\n\n private final Action> action;\n\n private ActionCacheListener(Action> action) {\n this.action = action;\n }\n\n @Override\n public void afterUpdate(EntryEvent event) {\n action.run(Operation.UPDATE, event);\n }\n }\n\n @SuppressWarnings({\"unused\", \"WeakerAccess\"})\n private static class TickerData implements DataSerializable {\n\n private long timeStamp = System.currentTimeMillis();\n private int price;\n private String ticker;\n\n public TickerData() {\n // nothing\n }\n\n private TickerData(int price) {\n this.price = price;\n ticker = String.valueOf(price);\n }\n\n public String getTicker() {\n return ticker;\n }\n\n private int getPrice() {\n return price;\n }\n\n private long getTimeStamp() {\n return timeStamp;\n }\n\n @Override\n public void toData(DataOutput out) throws IOException {\n DataSerializer.writeString(ticker, out);\n out.writeInt(price);\n out.writeLong(timeStamp);\n }\n\n @Override\n public void fromData(DataInput in) throws IOException {\n ticker = DataSerializer.readString(in);\n price = in.readInt();\n timeStamp = in.readLong();\n }\n\n @Override\n public String toString() {\n return \"Price=\" + price;\n }\n }\n\n private static class CountingCqListener implements CqListener {\n\n private final AtomicInteger updates = new AtomicInteger();\n private final Region region;\n\n private CountingCqListener(Region region) {\n this.region = region;\n }\n\n @Override\n public void onEvent(CqEvent cqEvent) {\n if (cqEvent.getQueryOperation() == Operation.DESTROY) {\n return;\n }\n\n K key = cast(cqEvent.getKey());\n V newValue = cast(cqEvent.getNewValue());\n\n if (newValue == null) {\n region.create(key, null);\n } else {\n region.put(key, newValue);\n updates.incrementAndGet();\n }\n }\n\n @Override\n public void onError(CqEvent cqEvent) {\n // nothing\n }\n }\n\n private static class CountingCacheWriter extends CacheWriterAdapter {\n\n private final AtomicInteger destroys = new AtomicInteger();\n\n @Override\n public void beforeDestroy(EntryEvent event) {\n destroys.incrementAndGet();\n }\n\n private int getDestroys() {\n return destroys.get();\n }\n }\n\n /**\n * cacheWriter to slow down P2P operations, listener only works for c/s in this case\n */\n private static class ActionCacheWriter extends CacheWriterAdapter {\n\n private final AtomicInteger creates = new AtomicInteger();\n private final AtomicInteger destroys = new AtomicInteger();\n private final Action action;\n\n private ActionCacheWriter(Action action) {\n this.action = action;\n }\n\n @Override\n public void beforeCreate(EntryEvent event) {\n action.run(Operation.CREATE, creates.get());\n sleep();\n creates.incrementAndGet();\n }\n\n @Override\n public void beforeUpdate(EntryEvent event) {\n sleep();\n }\n\n @Override\n public void beforeDestroy(EntryEvent event) {\n action.run(Operation.DESTROY, destroys.get());\n sleep();\n destroys.incrementAndGet();\n }\n }\n}\n"},"message":{"kind":"string","value":"GEODE-9373: add testEventIdOutOfOrderInPartitionRegionSingleHopFromCl… (#6609)\n\n"},"old_file":{"kind":"string","value":"geode-cq/src/distributedTest/java/org/apache/geode/internal/cache/PutAllClientServerDistributedTest.java"},"subject":{"kind":"string","value":"GEODE-9373: add testEventIdOutOfOrderInPartitionRegionSingleHopFromCl… (#6609)"},"git_diff":{"kind":"string","value":"eode-cq/src/distributedTest/java/org/apache/geode/internal/cache/PutAllClientServerDistributedTest.java\n }\n \n /**\n * The purpose of this test is to validate that when two servers of three in a cluster configured\n * with a client doing singlehop, that the client which registered interest gets afterCreate\n * messages for each\n * entry in the putall.\n * Further, we also check that the region size is correct on the remaining server.\n *\n * When the client has finished registerInterest to build the subscription queue, the servers\n * should guarantee all the afterCreate events arrive.\n *\n */\n @Test\n public void testEventIdOutOfOrderInPartitionRegionSingleHopFromClientRegisteredInterest() {\n VM server3 = client2;\n\n int serverPort1 = server1.invoke(() -> new ServerBuilder()\n .regionShortcut(PARTITION)\n .create());\n\n int serverPort2 = server2.invoke(() -> new ServerBuilder()\n .regionShortcut(PARTITION)\n .create());\n\n int serverPort3 = server3.invoke(() -> new ServerBuilder()\n .regionShortcut(PARTITION)\n .create());\n\n client1.invoke(() -> new ClientBuilder()\n .prSingleHopEnabled(true)\n .serverPorts(serverPort1, serverPort2, serverPort3)\n .subscriptionAckInterval()\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create());\n\n new ClientBuilder()\n .prSingleHopEnabled(true)\n .serverPorts(serverPort1, serverPort2, serverPort3)\n .subscriptionAckInterval()\n .subscriptionEnabled(true)\n .subscriptionRedundancy()\n .create();\n\n Region myRegion = getClientCache().getRegion(regionName);\n myRegion.registerInterest(\"ALL_KEYS\");\n\n // do some putAll to get ClientMetaData for future putAll\n client1.invoke(() -> doPutAll(getClientCache().getRegion(regionName), \"key-\", ONE_HUNDRED));\n await().until(() -> myRegion.size() == ONE_HUNDRED);\n\n // register interest and add listener\n Counter clientCounter = new Counter(\"client\");\n myRegion.getAttributesMutator().addCacheListener(new CountingCacheListener<>(clientCounter));\n\n // server1 and server2 will closeCache after created 10 keys\n // server1 add slow listener\n server1.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator()\n .addCacheListener(new SlowCountingCacheListener<>(new Action<>(Operation.CREATE,\n creates -> closeCacheConditionally(creates, 10))));\n });\n\n // server2 add slow listener\n server2.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator()\n .addCacheListener(new SlowCountingCacheListener<>(new Action<>(Operation.CREATE,\n creates -> closeCacheConditionally(creates, 20))));\n });\n\n // server3 add slow listener\n server3.invoke(() -> {\n COUNTER.set(new Counter(\"server3\"));\n Region region = getCache().getRegion(regionName);\n region.getAttributesMutator()\n .addCacheListener(new SlowCountingCacheListener<>(COUNTER.get()));\n });\n\n // client1 add listener and putAll\n client1.invoke(() -> {\n Region region = getClientCache().getRegion(regionName);\n doPutAll(region, keyPrefix, ONE_HUNDRED); // fails in GEODE-7812\n });\n\n await().untilAsserted(() -> assertThat(clientCounter.getCreates()).isEqualTo(ONE_HUNDRED));\n assertThat(clientCounter.getUpdates()).isZero();\n\n // server1 and server2 will closeCache after created 10 keys\n // server3 print counter\n server3.invoke(() -> {\n Region region = getCache().getRegion(regionName);\n\n assertThat(region.size())\n .describedAs(\"Should have 100 entries plus 3 to 4 buckets worth of entries\")\n .isIn(ONE_HUNDRED + 3 * (ONE_HUNDRED) / 10, ONE_HUNDRED + 4 * (ONE_HUNDRED) / 10);\n assertThat(COUNTER.get().getUpdates()).isZero();\n verifyPutAll(region, keyPrefix);\n\n });\n\n }\n\n /**\n * Tests while putAll to 2 distributed servers, one server failed over Add a listener to slow down\n * the processing of putAll\n */"}}},{"rowIdx":1962,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"69f4fec4fe9051eb9cf0385b911a55a3b21b7e37"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"opendatakit/androidcommon"},"new_contents":{"kind":"string","value":"/*\r\n * Copyright (C) 2015 University of Washington\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\r\n * in compliance with the License. You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software distributed under the License\r\n * is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express\r\n * or implied. See the License for the specific language governing permissions and limitations under\r\n * the License.\r\n */\r\n\r\npackage org.opendatakit.common.android.application;\r\n\r\nimport android.annotation.SuppressLint;\r\nimport android.app.Activity;\r\nimport android.content.ComponentName;\r\nimport android.content.Context;\r\nimport android.content.Intent;\r\nimport android.content.ServiceConnection;\r\nimport android.content.pm.PackageManager;\r\nimport android.content.res.Configuration;\r\nimport android.os.AsyncTask;\r\nimport android.os.Build;\r\nimport android.os.Handler;\r\nimport android.os.IBinder;\r\nimport android.util.Log;\r\nimport android.view.View;\r\nimport android.webkit.WebView;\r\nimport org.opendatakit.common.android.listener.DatabaseConnectionListener;\r\nimport org.opendatakit.common.android.listener.InitializationListener;\r\nimport org.opendatakit.common.android.logic.CommonToolProperties;\r\nimport org.opendatakit.common.android.logic.PropertiesSingleton;\r\nimport org.opendatakit.common.android.task.InitializationTask;\r\nimport org.opendatakit.common.android.utilities.ODKFileUtils;\r\nimport org.opendatakit.common.android.views.ODKWebView;\r\nimport org.opendatakit.database.DatabaseConsts;\r\nimport org.opendatakit.database.service.OdkDbInterface;\r\nimport org.opendatakit.webkitserver.WebkitServerConsts;\r\nimport org.opendatakit.webkitserver.service.OdkWebkitServerInterface;\r\n\r\nimport java.util.ArrayList;\r\n\r\npublic abstract class CommonApplication extends AppAwareApplication implements\r\n InitializationListener {\r\n\r\n private static final String t = \"CommonApplication\";\r\n \r\n public static final String PERMISSION_WEBSERVER = \"org.opendatakit.webkitserver.RUN_WEBSERVER\";\r\n public static final String PERMISSION_DATABASE = \"org.opendatakit.database.RUN_DATABASE\";\r\n\r\n // Support for mocking the remote interfaces that are actually accessed\r\n // vs. the WebKit service, which is merely started.\r\n private static boolean isMocked = false;\r\n \r\n // Hack to determine whether or not to cascade to the initialize task\r\n private static boolean disableInitializeCascade = true;\r\n \r\n // Hack for handling mock interfaces...\r\n private static OdkDbInterface mockDatabaseService = null;\r\n private static OdkWebkitServerInterface mockWebkitServerService = null;\r\n \r\n public static void setMocked() {\r\n isMocked = true;\r\n }\r\n \r\n public static boolean isMocked() {\r\n return isMocked;\r\n }\r\n \r\n public static boolean isDisableInitializeCascade() {\r\n return disableInitializeCascade;\r\n }\r\n \r\n public static void setEnableInitializeCascade() {\r\n disableInitializeCascade = false;\r\n }\r\n \r\n public static void setDisableInitializeCascade() {\r\n disableInitializeCascade = true;\r\n }\r\n \r\n public static void setMockDatabase(OdkDbInterface mock) {\r\n CommonApplication.mockDatabaseService = mock;\r\n }\r\n\r\n public static void setMockWebkitServer(OdkWebkitServerInterface mock) {\r\n CommonApplication.mockWebkitServerService = mock;\r\n }\r\n\r\n public static void mockServiceConnected(CommonApplication app, String name) {\r\n ComponentName className = null;\r\n if (name.equals(WebkitServerConsts.WEBKITSERVER_SERVICE_CLASS)) {\r\n className = new ComponentName(WebkitServerConsts.WEBKITSERVER_SERVICE_PACKAGE,\r\n WebkitServerConsts.WEBKITSERVER_SERVICE_CLASS);\r\n }\r\n\r\n if (name.equals(DatabaseConsts.DATABASE_SERVICE_CLASS)) {\r\n className = new ComponentName(DatabaseConsts.DATABASE_SERVICE_PACKAGE,\r\n DatabaseConsts.DATABASE_SERVICE_CLASS);\r\n }\r\n \r\n if ( className == null ) {\r\n throw new IllegalStateException(\"unrecognized mockService\");\r\n }\r\n \r\n app.doServiceConnected(className, null);\r\n }\r\n\r\n public static void mockServiceDisconnected(CommonApplication app, String name) {\r\n ComponentName className = null;\r\n if (name.equals(WebkitServerConsts.WEBKITSERVER_SERVICE_CLASS)) {\r\n className = new ComponentName(WebkitServerConsts.WEBKITSERVER_SERVICE_PACKAGE,\r\n WebkitServerConsts.WEBKITSERVER_SERVICE_CLASS);\r\n }\r\n\r\n if (name.equals(DatabaseConsts.DATABASE_SERVICE_CLASS)) {\r\n className = new ComponentName(DatabaseConsts.DATABASE_SERVICE_PACKAGE,\r\n DatabaseConsts.DATABASE_SERVICE_CLASS);\r\n }\r\n \r\n if ( className == null ) {\r\n throw new IllegalStateException(\"unrecognized mockService\");\r\n }\r\n \r\n app.doServiceDisconnected(className);\r\n }\r\n \r\n /**\r\n * Wrapper class for service activation management.\r\n * \r\n * @author mitchellsundt@gmail.com\r\n *\r\n */\r\n private final class ServiceConnectionWrapper implements ServiceConnection {\r\n\r\n @Override\r\n public void onServiceConnected(ComponentName name, IBinder service) {\r\n CommonApplication.this.doServiceConnected(name, service);\r\n }\r\n\r\n @Override\r\n public void onServiceDisconnected(ComponentName name) {\r\n CommonApplication.this.doServiceDisconnected(name);\r\n }\r\n }\r\n\r\n /**\r\n * Task instances that are preserved until the application dies.\r\n * \r\n * @author mitchellsundt@gmail.com\r\n *\r\n */\r\n private static final class BackgroundTasks {\r\n InitializationTask mInitializationTask = null;\r\n\r\n BackgroundTasks() {\r\n };\r\n }\r\n\r\n /**\r\n * Service connections that are preserved until the application dies.\r\n * \r\n * @author mitchellsundt@gmail.com\r\n *\r\n */\r\n private static final class BackgroundServices {\r\n\r\n private ServiceConnectionWrapper webkitfilesServiceConnection = null;\r\n private OdkWebkitServerInterface webkitfilesService = null;\r\n private ServiceConnectionWrapper databaseServiceConnection = null;\r\n private OdkDbInterface databaseService = null;\r\n private boolean isDestroying = false;\r\n\r\n BackgroundServices() {\r\n };\r\n }\r\n\r\n /**\r\n * Creates required directories on the SDCard (or other external storage)\r\n *\r\n * @return true if there are tables present\r\n * @throws RuntimeException\r\n * if there is no SDCard or the directory exists as a non directory\r\n */\r\n public static void createODKDirs(String appName) throws RuntimeException {\r\n\r\n ODKFileUtils.verifyExternalStorageAvailability();\r\n\r\n ODKFileUtils.assertDirectoryStructure(appName);\r\n }\r\n\r\n // handed across orientation changes\r\n private final BackgroundTasks mBackgroundTasks = new BackgroundTasks(); \r\n\r\n // handed across orientation changes\r\n private final BackgroundServices mBackgroundServices = new BackgroundServices(); \r\n\r\n // These are expected to be broken down and set up during orientation changes.\r\n private InitializationListener mInitializationListener = null;\r\n\r\n private boolean shuttingDown = false;\r\n \r\n public CommonApplication() {\r\n super();\r\n }\r\n \r\n @SuppressLint(\"NewApi\")\r\n @Override\r\n public void onCreate() {\r\n shuttingDown = false;\r\n super.onCreate();\r\n\r\n if (Build.VERSION.SDK_INT >= 19) {\r\n WebView.setWebContentsDebuggingEnabled(true);\r\n }\r\n }\r\n\r\n @Override\r\n public void onConfigurationChanged(Configuration newConfig) {\r\n super.onConfigurationChanged(newConfig);\r\n Log.i(t, \"onConfigurationChanged\");\r\n }\r\n\r\n @Override\r\n public void onTerminate() {\r\n cleanShutdown();\r\n super.onTerminate();\r\n Log.i(t, \"onTerminate\");\r\n }\r\n\r\n public abstract int getConfigZipResourceId();\r\n \r\n public abstract int getSystemZipResourceId();\r\n \r\n public abstract int getWebKitResourceId();\r\n \r\n public boolean shouldRunInitializationTask(String appName) {\r\n if ( isMocked() ) {\r\n if ( isDisableInitializeCascade() ) {\r\n return false;\r\n }\r\n }\r\n PropertiesSingleton props = CommonToolProperties.get(this, appName);\r\n return props.shouldRunInitializationTask(this.getToolName());\r\n }\r\n\r\n public void clearRunInitializationTask(String appName) {\r\n PropertiesSingleton props = CommonToolProperties.get(this, appName);\r\n props.clearRunInitializationTask(this.getToolName());\r\n }\r\n\r\n public void setRunInitializationTask(String appName) {\r\n PropertiesSingleton props = CommonToolProperties.get(this, appName);\r\n props.setRunInitializationTask(this.getToolName());\r\n }\r\n\r\n private void executeTask(AsyncTask task, T... args) {\r\n\r\n int androidVersion = android.os.Build.VERSION.SDK_INT;\r\n if (androidVersion < 11) {\r\n task.execute(args);\r\n } else {\r\n // TODO: execute on serial executor in version 11 onward...\r\n task.execute(args);\r\n // task.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, (Void[]) null);\r\n }\r\n\r\n }\r\n\r\n private Activity activeActivity = null;\r\n private Activity databaseListenerActivity = null;\r\n \r\n public void onActivityPause(Activity activity) {\r\n if ( activeActivity == activity ) {\r\n mInitializationListener = null;\r\n \r\n if (mBackgroundTasks.mInitializationTask != null) {\r\n mBackgroundTasks.mInitializationTask.setInitializationListener(null);\r\n }\r\n }\r\n }\r\n \r\n public void onActivityDestroy(Activity activity) {\r\n if ( activeActivity == activity ) {\r\n activeActivity = null;\r\n \r\n mInitializationListener = null;\r\n \r\n if (mBackgroundTasks.mInitializationTask != null) {\r\n mBackgroundTasks.mInitializationTask.setInitializationListener(null);\r\n }\r\n\r\n final Handler handler = new Handler();\r\n handler.postDelayed(new Runnable() {\r\n @Override\r\n public void run() {\r\n CommonApplication.this.testForShutdown();\r\n }\r\n }, 500);\r\n }\r\n }\r\n\r\n private void cleanShutdown() {\r\n try {\r\n shuttingDown = true;\r\n \r\n shutdownServices();\r\n } finally {\r\n shuttingDown = false;\r\n }\r\n }\r\n \r\n private void testForShutdown() {\r\n // no other activity has been started -- shut down\r\n if ( activeActivity == null ) {\r\n cleanShutdown();\r\n }\r\n }\r\n\r\n public void onActivityResume(Activity activity) {\r\n databaseListenerActivity = null;\r\n activeActivity = activity;\r\n \r\n if (mBackgroundTasks.mInitializationTask != null) {\r\n mBackgroundTasks.mInitializationTask.setInitializationListener(this);\r\n }\r\n \r\n // be sure the services are connected...\r\n mBackgroundServices.isDestroying = false;\r\n\r\n configureView();\r\n\r\n // failsafe -- ensure that the services are active...\r\n bindToService();\r\n }\r\n\r\n // /////////////////////////////////////////////////////////////////////////\r\n // service interactions\r\n private void unbindWebkitfilesServiceWrapper() {\r\n try {\r\n ServiceConnectionWrapper tmp = mBackgroundServices.webkitfilesServiceConnection;\r\n mBackgroundServices.webkitfilesServiceConnection = null;\r\n if ( tmp != null ) {\r\n unbindService(tmp);\r\n }\r\n } catch ( Exception e ) {\r\n // ignore\r\n e.printStackTrace();\r\n }\r\n }\r\n \r\n private void unbindDatabaseBinderWrapper() {\r\n try {\r\n ServiceConnectionWrapper tmp = mBackgroundServices.databaseServiceConnection;\r\n mBackgroundServices.databaseServiceConnection = null;\r\n if ( tmp != null ) {\r\n unbindService(tmp);\r\n triggerDatabaseEvent(false);\r\n }\r\n } catch ( Exception e ) {\r\n // ignore\r\n e.printStackTrace();\r\n }\r\n }\r\n\r\n private void shutdownServices() {\r\n Log.i(t, \"shutdownServices - Releasing WebServer and database service\");\r\n mBackgroundServices.isDestroying = true;\r\n mBackgroundServices.webkitfilesService = null;\r\n mBackgroundServices.databaseService = null;\r\n // release interfaces held by the view\r\n configureView();\r\n // release the webkitfilesService\r\n unbindWebkitfilesServiceWrapper();\r\n unbindDatabaseBinderWrapper();\r\n }\r\n \r\n private void bindToService() {\r\n if ( isMocked ) {\r\n // we directly control all the service binding interactions if we are mocked\r\n return;\r\n }\r\n if (!shuttingDown && !mBackgroundServices.isDestroying) {\r\n PackageManager pm = getPackageManager();\r\n boolean useWebServer = (pm.checkPermission(PERMISSION_WEBSERVER, getPackageName()) == PackageManager.PERMISSION_GRANTED);\r\n boolean useDatabase = (pm.checkPermission(PERMISSION_DATABASE, getPackageName()) == PackageManager.PERMISSION_GRANTED);\r\n\r\n // do something\r\n \r\n if (useWebServer && mBackgroundServices.webkitfilesService == null && \r\n mBackgroundServices.webkitfilesServiceConnection == null) {\r\n Log.i(t, \"Attempting bind to WebServer service\");\r\n mBackgroundServices.webkitfilesServiceConnection = new ServiceConnectionWrapper();\r\n Intent bind_intent = new Intent();\r\n bind_intent.setClassName(WebkitServerConsts.WEBKITSERVER_SERVICE_PACKAGE,\r\n WebkitServerConsts.WEBKITSERVER_SERVICE_CLASS);\r\n bindService(\r\n bind_intent,\r\n mBackgroundServices.webkitfilesServiceConnection,\r\n Context.BIND_AUTO_CREATE\r\n | ((Build.VERSION.SDK_INT >= 14) ? Context.BIND_ADJUST_WITH_ACTIVITY : 0));\r\n }\r\n\r\n if (useDatabase && mBackgroundServices.databaseService == null &&\r\n mBackgroundServices.databaseServiceConnection == null) {\r\n Log.i(t, \"Attempting bind to Database service\");\r\n mBackgroundServices.databaseServiceConnection = new ServiceConnectionWrapper();\r\n Intent bind_intent = new Intent();\r\n bind_intent.setClassName(DatabaseConsts.DATABASE_SERVICE_PACKAGE,\r\n DatabaseConsts.DATABASE_SERVICE_CLASS);\r\n bindService(\r\n bind_intent,\r\n mBackgroundServices.databaseServiceConnection,\r\n Context.BIND_AUTO_CREATE\r\n | ((Build.VERSION.SDK_INT >= 14) ? Context.BIND_ADJUST_WITH_ACTIVITY : 0));\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * \r\n * @param className\r\n * @param service can be null if we are mocked\r\n */\r\n private void doServiceConnected(ComponentName className, IBinder service) {\r\n if (className.getClassName().equals(WebkitServerConsts.WEBKITSERVER_SERVICE_CLASS)) {\r\n Log.i(t, \"Bound to WebServer service\");\r\n mBackgroundServices.webkitfilesService = (service == null) ? null : OdkWebkitServerInterface.Stub.asInterface(service);\r\n }\r\n\r\n if (className.getClassName().equals(DatabaseConsts.DATABASE_SERVICE_CLASS)) {\r\n Log.i(t, \"Bound to Database service\");\r\n mBackgroundServices.databaseService = (service == null) ? null : OdkDbInterface.Stub.asInterface(service);\r\n \r\n triggerDatabaseEvent(false);\r\n }\r\n\r\n configureView();\r\n }\r\n \r\n public OdkDbInterface getDatabase() {\r\n if ( isMocked ) {\r\n return mockDatabaseService;\r\n } else {\r\n return mBackgroundServices.databaseService;\r\n }\r\n }\r\n \r\n private OdkWebkitServerInterface getWebkitServer() {\r\n if ( isMocked ) {\r\n return mockWebkitServerService;\r\n } else {\r\n return mBackgroundServices.webkitfilesService;\r\n }\r\n }\r\n \r\n public void configureView() {\r\n if ( activeActivity != null ) {\r\n Log.i(t, \"configureView - possibly updating service information within ODKWebView\");\r\n if ( getWebKitResourceId() != -1 ) {\r\n View v = activeActivity.findViewById(getWebKitResourceId());\r\n if (v != null && v instanceof ODKWebView) {\r\n ODKWebView wv = (ODKWebView) v;\r\n if (mBackgroundServices.isDestroying) {\r\n wv.serviceChange(false);\r\n } else {\r\n OdkWebkitServerInterface webkitServerIf = getWebkitServer();\r\n OdkDbInterface dbIf = getDatabase();\r\n wv.serviceChange(webkitServerIf != null && dbIf != null);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n private void doServiceDisconnected(ComponentName className) {\r\n if (className.getClassName().equals(WebkitServerConsts.WEBKITSERVER_SERVICE_CLASS)) {\r\n if (mBackgroundServices.isDestroying) {\r\n Log.i(t, \"Unbound from WebServer service (intentionally)\");\r\n } else {\r\n Log.w(t, \"Unbound from WebServer service (unexpected)\");\r\n }\r\n mBackgroundServices.webkitfilesService = null;\r\n unbindWebkitfilesServiceWrapper();\r\n }\r\n\r\n if (className.getClassName().equals(DatabaseConsts.DATABASE_SERVICE_CLASS)) {\r\n if (mBackgroundServices.isDestroying) {\r\n Log.i(t, \"Unbound from Database service (intentionally)\");\r\n } else {\r\n Log.w(t, \"Unbound from Database service (unexpected)\");\r\n }\r\n mBackgroundServices.databaseService = null;\r\n unbindDatabaseBinderWrapper();\r\n }\r\n\r\n configureView();\r\n\r\n // the bindToService() method decides whether to connect or not...\r\n bindToService();\r\n }\r\n\r\n // /////////////////////////////////////////////////////////////////////////\r\n // registrations\r\n\r\n /**\r\n * Called by an activity when it has been sufficiently initialized so\r\n * that it can handle a databaseAvailable() call.\r\n * \r\n * @param activity\r\n */\r\n public void establishDatabaseConnectionListener(Activity activity) {\r\n databaseListenerActivity = activity;\r\n triggerDatabaseEvent(true);\r\n }\r\n\r\n /**\r\n * If the given activity is active, then fire the callback based upon \r\n * the availability of the database.\r\n * \r\n * @param activity\r\n * @param listener\r\n */\r\n public void possiblyFireDatabaseCallback(Activity activity, DatabaseConnectionListener listener) {\r\n if ( activeActivity != null &&\r\n activeActivity == databaseListenerActivity &&\r\n databaseListenerActivity == activity ) {\r\n if ( this.getDatabase() == null ) {\r\n listener.databaseUnavailable();\r\n } else {\r\n listener.databaseAvailable();\r\n }\r\n }\r\n }\r\n \r\n private void triggerDatabaseEvent(boolean availableOnly) {\r\n if ( activeActivity != null &&\r\n activeActivity == databaseListenerActivity &&\r\n activeActivity instanceof DatabaseConnectionListener ) {\r\n if ( !availableOnly && this.getDatabase() == null ) {\r\n ((DatabaseConnectionListener) activeActivity).databaseUnavailable();\r\n } else {\r\n ((DatabaseConnectionListener) activeActivity).databaseAvailable();\r\n }\r\n }\r\n }\r\n \r\n public void establishInitializationListener(InitializationListener listener) {\r\n mInitializationListener = listener;\r\n // async task may have completed while we were reorienting...\r\n if (mBackgroundTasks.mInitializationTask != null\r\n && mBackgroundTasks.mInitializationTask.getStatus() == AsyncTask.Status.FINISHED) {\r\n this.initializationComplete(mBackgroundTasks.mInitializationTask.getOverallSuccess(),\r\n mBackgroundTasks.mInitializationTask.getResult());\r\n }\r\n }\r\n\r\n // ///////////////////////////////////////////////////\r\n // actions\r\n\r\n public synchronized boolean initializeAppName(String appName, InitializationListener listener) {\r\n mInitializationListener = listener;\r\n if (mBackgroundTasks.mInitializationTask != null\r\n && mBackgroundTasks.mInitializationTask.getStatus() != AsyncTask.Status.FINISHED) {\r\n // Toast.makeText(this.getActivity(),\r\n // getString(R.string.expansion_in_progress),\r\n // Toast.LENGTH_LONG).show();\r\n return true;\r\n } else if ( getDatabase() != null ) {\r\n InitializationTask cf = new InitializationTask();\r\n cf.setApplication(this);\r\n cf.setAppName(appName);\r\n cf.setInitializationListener(this);\r\n mBackgroundTasks.mInitializationTask = cf;\r\n executeTask(mBackgroundTasks.mInitializationTask, (Void) null);\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }\r\n\r\n // /////////////////////////////////////////////////////////////////////////\r\n // clearing tasks\r\n //\r\n // NOTE: clearing these makes us forget that they are running, but it is\r\n // up to the task itself to eventually shutdown. i.e., we don't quite\r\n // know when they actually stop.\r\n\r\n\r\n public synchronized void clearInitializationTask() {\r\n mInitializationListener = null;\r\n if (mBackgroundTasks.mInitializationTask != null) {\r\n mBackgroundTasks.mInitializationTask.setInitializationListener(null);\r\n if (mBackgroundTasks.mInitializationTask.getStatus() != AsyncTask.Status.FINISHED) {\r\n mBackgroundTasks.mInitializationTask.cancel(true);\r\n }\r\n }\r\n mBackgroundTasks.mInitializationTask = null;\r\n }\r\n\r\n // /////////////////////////////////////////////////////////////////////////\r\n // cancel requests\r\n //\r\n // These maintain communications paths, so that we get a failure\r\n // completion callback eventually.\r\n\r\n\r\n public synchronized void cancelInitializationTask() {\r\n if (mBackgroundTasks.mInitializationTask != null) {\r\n if (mBackgroundTasks.mInitializationTask.getStatus() != AsyncTask.Status.FINISHED) {\r\n mBackgroundTasks.mInitializationTask.cancel(true);\r\n }\r\n }\r\n }\r\n\r\n // /////////////////////////////////////////////////////////////////////////\r\n // callbacks\r\n\r\n @Override\r\n public void initializationComplete(boolean overallSuccess, ArrayList result) {\r\n if (mInitializationListener != null) {\r\n mInitializationListener.initializationComplete(overallSuccess, result);\r\n }\r\n }\r\n\r\n @Override\r\n public void initializationProgressUpdate(String status) {\r\n if (mInitializationListener != null) {\r\n mInitializationListener.initializationProgressUpdate(status);\r\n }\r\n }\r\n\r\n}\r\n"},"new_file":{"kind":"string","value":"androidcommon_lib/src/main/java/org/opendatakit/common/android/application/CommonApplication.java"},"old_contents":{"kind":"string","value":"/*\r\n * Copyright (C) 2015 University of Washington\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\r\n * in compliance with the License. You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software distributed under the License\r\n * is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express\r\n * or implied. See the License for the specific language governing permissions and limitations under\r\n * the License.\r\n */\r\n\r\npackage org.opendatakit.common.android.application;\r\n\r\nimport android.annotation.SuppressLint;\r\nimport android.app.Activity;\r\nimport android.content.ComponentName;\r\nimport android.content.Context;\r\nimport android.content.Intent;\r\nimport android.content.ServiceConnection;\r\nimport android.content.pm.PackageManager;\r\nimport android.content.res.Configuration;\r\nimport android.os.AsyncTask;\r\nimport android.os.Build;\r\nimport android.os.Handler;\r\nimport android.os.IBinder;\r\nimport android.util.Log;\r\nimport android.view.View;\r\nimport android.webkit.WebView;\r\nimport org.opendatakit.common.android.listener.DatabaseConnectionListener;\r\nimport org.opendatakit.common.android.listener.InitializationListener;\r\nimport org.opendatakit.common.android.logic.CommonToolProperties;\r\nimport org.opendatakit.common.android.logic.PropertiesSingleton;\r\nimport org.opendatakit.common.android.task.InitializationTask;\r\nimport org.opendatakit.common.android.utilities.ODKFileUtils;\r\nimport org.opendatakit.common.android.utilities.PRNGFixes;\r\nimport org.opendatakit.common.android.views.ODKWebView;\r\nimport org.opendatakit.database.DatabaseConsts;\r\nimport org.opendatakit.database.service.OdkDbInterface;\r\nimport org.opendatakit.webkitserver.WebkitServerConsts;\r\nimport org.opendatakit.webkitserver.service.OdkWebkitServerInterface;\r\n\r\nimport java.util.ArrayList;\r\n\r\npublic abstract class CommonApplication extends AppAwareApplication implements\r\n InitializationListener {\r\n\r\n private static final String t = \"CommonApplication\";\r\n \r\n public static final String PERMISSION_WEBSERVER = \"org.opendatakit.webkitserver.RUN_WEBSERVER\";\r\n public static final String PERMISSION_DATABASE = \"org.opendatakit.database.RUN_DATABASE\";\r\n\r\n // Support for mocking the remote interfaces that are actually accessed\r\n // vs. the WebKit service, which is merely started.\r\n private static boolean isMocked = false;\r\n \r\n // Hack to determine whether or not to cascade to the initialize task\r\n private static boolean disableInitializeCascade = true;\r\n \r\n // Hack for handling mock interfaces...\r\n private static OdkDbInterface mockDatabaseService = null;\r\n private static OdkWebkitServerInterface mockWebkitServerService = null;\r\n \r\n public static void setMocked() {\r\n isMocked = true;\r\n }\r\n \r\n public static boolean isMocked() {\r\n return isMocked;\r\n }\r\n \r\n public static boolean isDisableInitializeCascade() {\r\n return disableInitializeCascade;\r\n }\r\n \r\n public static void setEnableInitializeCascade() {\r\n disableInitializeCascade = false;\r\n }\r\n \r\n public static void setDisableInitializeCascade() {\r\n disableInitializeCascade = true;\r\n }\r\n \r\n public static void setMockDatabase(OdkDbInterface mock) {\r\n CommonApplication.mockDatabaseService = mock;\r\n }\r\n\r\n public static void setMockWebkitServer(OdkWebkitServerInterface mock) {\r\n CommonApplication.mockWebkitServerService = mock;\r\n }\r\n\r\n public static void mockServiceConnected(CommonApplication app, String name) {\r\n ComponentName className = null;\r\n if (name.equals(WebkitServerConsts.WEBKITSERVER_SERVICE_CLASS)) {\r\n className = new ComponentName(WebkitServerConsts.WEBKITSERVER_SERVICE_PACKAGE,\r\n WebkitServerConsts.WEBKITSERVER_SERVICE_CLASS);\r\n }\r\n\r\n if (name.equals(DatabaseConsts.DATABASE_SERVICE_CLASS)) {\r\n className = new ComponentName(DatabaseConsts.DATABASE_SERVICE_PACKAGE,\r\n DatabaseConsts.DATABASE_SERVICE_CLASS);\r\n }\r\n \r\n if ( className == null ) {\r\n throw new IllegalStateException(\"unrecognized mockService\");\r\n }\r\n \r\n app.doServiceConnected(className, null);\r\n }\r\n\r\n public static void mockServiceDisconnected(CommonApplication app, String name) {\r\n ComponentName className = null;\r\n if (name.equals(WebkitServerConsts.WEBKITSERVER_SERVICE_CLASS)) {\r\n className = new ComponentName(WebkitServerConsts.WEBKITSERVER_SERVICE_PACKAGE,\r\n WebkitServerConsts.WEBKITSERVER_SERVICE_CLASS);\r\n }\r\n\r\n if (name.equals(DatabaseConsts.DATABASE_SERVICE_CLASS)) {\r\n className = new ComponentName(DatabaseConsts.DATABASE_SERVICE_PACKAGE,\r\n DatabaseConsts.DATABASE_SERVICE_CLASS);\r\n }\r\n \r\n if ( className == null ) {\r\n throw new IllegalStateException(\"unrecognized mockService\");\r\n }\r\n \r\n app.doServiceDisconnected(className);\r\n }\r\n \r\n /**\r\n * Wrapper class for service activation management.\r\n * \r\n * @author mitchellsundt@gmail.com\r\n *\r\n */\r\n private final class ServiceConnectionWrapper implements ServiceConnection {\r\n\r\n @Override\r\n public void onServiceConnected(ComponentName name, IBinder service) {\r\n CommonApplication.this.doServiceConnected(name, service);\r\n }\r\n\r\n @Override\r\n public void onServiceDisconnected(ComponentName name) {\r\n CommonApplication.this.doServiceDisconnected(name);\r\n }\r\n }\r\n\r\n /**\r\n * Task instances that are preserved until the application dies.\r\n * \r\n * @author mitchellsundt@gmail.com\r\n *\r\n */\r\n private static final class BackgroundTasks {\r\n InitializationTask mInitializationTask = null;\r\n\r\n BackgroundTasks() {\r\n };\r\n }\r\n\r\n /**\r\n * Service connections that are preserved until the application dies.\r\n * \r\n * @author mitchellsundt@gmail.com\r\n *\r\n */\r\n private static final class BackgroundServices {\r\n\r\n private ServiceConnectionWrapper webkitfilesServiceConnection = null;\r\n private OdkWebkitServerInterface webkitfilesService = null;\r\n private ServiceConnectionWrapper databaseServiceConnection = null;\r\n private OdkDbInterface databaseService = null;\r\n private boolean isDestroying = false;\r\n\r\n BackgroundServices() {\r\n };\r\n }\r\n\r\n /**\r\n * Creates required directories on the SDCard (or other external storage)\r\n *\r\n * @return true if there are tables present\r\n * @throws RuntimeException\r\n * if there is no SDCard or the directory exists as a non directory\r\n */\r\n public static void createODKDirs(String appName) throws RuntimeException {\r\n\r\n ODKFileUtils.verifyExternalStorageAvailability();\r\n\r\n ODKFileUtils.assertDirectoryStructure(appName);\r\n }\r\n\r\n // handed across orientation changes\r\n private final BackgroundTasks mBackgroundTasks = new BackgroundTasks(); \r\n\r\n // handed across orientation changes\r\n private final BackgroundServices mBackgroundServices = new BackgroundServices(); \r\n\r\n // These are expected to be broken down and set up during orientation changes.\r\n private InitializationListener mInitializationListener = null;\r\n\r\n private boolean shuttingDown = false;\r\n \r\n public CommonApplication() {\r\n super();\r\n PRNGFixes.apply();\r\n }\r\n \r\n @SuppressLint(\"NewApi\")\r\n @Override\r\n public void onCreate() {\r\n shuttingDown = false;\r\n super.onCreate();\r\n\r\n if (Build.VERSION.SDK_INT >= 19) {\r\n WebView.setWebContentsDebuggingEnabled(true);\r\n }\r\n }\r\n\r\n @Override\r\n public void onConfigurationChanged(Configuration newConfig) {\r\n super.onConfigurationChanged(newConfig);\r\n Log.i(t, \"onConfigurationChanged\");\r\n }\r\n\r\n @Override\r\n public void onTerminate() {\r\n cleanShutdown();\r\n super.onTerminate();\r\n Log.i(t, \"onTerminate\");\r\n }\r\n\r\n public abstract int getConfigZipResourceId();\r\n \r\n public abstract int getSystemZipResourceId();\r\n \r\n public abstract int getWebKitResourceId();\r\n \r\n public boolean shouldRunInitializationTask(String appName) {\r\n if ( isMocked() ) {\r\n if ( isDisableInitializeCascade() ) {\r\n return false;\r\n }\r\n }\r\n PropertiesSingleton props = CommonToolProperties.get(this, appName);\r\n return props.shouldRunInitializationTask(this.getToolName());\r\n }\r\n\r\n public void clearRunInitializationTask(String appName) {\r\n PropertiesSingleton props = CommonToolProperties.get(this, appName);\r\n props.clearRunInitializationTask(this.getToolName());\r\n }\r\n\r\n public void setRunInitializationTask(String appName) {\r\n PropertiesSingleton props = CommonToolProperties.get(this, appName);\r\n props.setRunInitializationTask(this.getToolName());\r\n }\r\n\r\n private void executeTask(AsyncTask task, T... args) {\r\n\r\n int androidVersion = android.os.Build.VERSION.SDK_INT;\r\n if (androidVersion < 11) {\r\n task.execute(args);\r\n } else {\r\n // TODO: execute on serial executor in version 11 onward...\r\n task.execute(args);\r\n // task.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, (Void[]) null);\r\n }\r\n\r\n }\r\n\r\n private Activity activeActivity = null;\r\n private Activity databaseListenerActivity = null;\r\n \r\n public void onActivityPause(Activity activity) {\r\n if ( activeActivity == activity ) {\r\n mInitializationListener = null;\r\n \r\n if (mBackgroundTasks.mInitializationTask != null) {\r\n mBackgroundTasks.mInitializationTask.setInitializationListener(null);\r\n }\r\n }\r\n }\r\n \r\n public void onActivityDestroy(Activity activity) {\r\n if ( activeActivity == activity ) {\r\n activeActivity = null;\r\n \r\n mInitializationListener = null;\r\n \r\n if (mBackgroundTasks.mInitializationTask != null) {\r\n mBackgroundTasks.mInitializationTask.setInitializationListener(null);\r\n }\r\n\r\n final Handler handler = new Handler();\r\n handler.postDelayed(new Runnable() {\r\n @Override\r\n public void run() {\r\n CommonApplication.this.testForShutdown();\r\n }\r\n }, 500);\r\n }\r\n }\r\n\r\n private void cleanShutdown() {\r\n try {\r\n shuttingDown = true;\r\n \r\n shutdownServices();\r\n } finally {\r\n shuttingDown = false;\r\n }\r\n }\r\n \r\n private void testForShutdown() {\r\n // no other activity has been started -- shut down\r\n if ( activeActivity == null ) {\r\n cleanShutdown();\r\n }\r\n }\r\n\r\n public void onActivityResume(Activity activity) {\r\n databaseListenerActivity = null;\r\n activeActivity = activity;\r\n \r\n if (mBackgroundTasks.mInitializationTask != null) {\r\n mBackgroundTasks.mInitializationTask.setInitializationListener(this);\r\n }\r\n \r\n // be sure the services are connected...\r\n mBackgroundServices.isDestroying = false;\r\n\r\n configureView();\r\n\r\n // failsafe -- ensure that the services are active...\r\n bindToService();\r\n }\r\n\r\n // /////////////////////////////////////////////////////////////////////////\r\n // service interactions\r\n private void unbindWebkitfilesServiceWrapper() {\r\n try {\r\n ServiceConnectionWrapper tmp = mBackgroundServices.webkitfilesServiceConnection;\r\n mBackgroundServices.webkitfilesServiceConnection = null;\r\n if ( tmp != null ) {\r\n unbindService(tmp);\r\n }\r\n } catch ( Exception e ) {\r\n // ignore\r\n e.printStackTrace();\r\n }\r\n }\r\n \r\n private void unbindDatabaseBinderWrapper() {\r\n try {\r\n ServiceConnectionWrapper tmp = mBackgroundServices.databaseServiceConnection;\r\n mBackgroundServices.databaseServiceConnection = null;\r\n if ( tmp != null ) {\r\n unbindService(tmp);\r\n triggerDatabaseEvent(false);\r\n }\r\n } catch ( Exception e ) {\r\n // ignore\r\n e.printStackTrace();\r\n }\r\n }\r\n\r\n private void shutdownServices() {\r\n Log.i(t, \"shutdownServices - Releasing WebServer and database service\");\r\n mBackgroundServices.isDestroying = true;\r\n mBackgroundServices.webkitfilesService = null;\r\n mBackgroundServices.databaseService = null;\r\n // release interfaces held by the view\r\n configureView();\r\n // release the webkitfilesService\r\n unbindWebkitfilesServiceWrapper();\r\n unbindDatabaseBinderWrapper();\r\n }\r\n \r\n private void bindToService() {\r\n if ( isMocked ) {\r\n // we directly control all the service binding interactions if we are mocked\r\n return;\r\n }\r\n if (!shuttingDown && !mBackgroundServices.isDestroying) {\r\n PackageManager pm = getPackageManager();\r\n boolean useWebServer = (pm.checkPermission(PERMISSION_WEBSERVER, getPackageName()) == PackageManager.PERMISSION_GRANTED);\r\n boolean useDatabase = (pm.checkPermission(PERMISSION_DATABASE, getPackageName()) == PackageManager.PERMISSION_GRANTED);\r\n\r\n // do something\r\n \r\n if (useWebServer && mBackgroundServices.webkitfilesService == null && \r\n mBackgroundServices.webkitfilesServiceConnection == null) {\r\n Log.i(t, \"Attempting bind to WebServer service\");\r\n mBackgroundServices.webkitfilesServiceConnection = new ServiceConnectionWrapper();\r\n Intent bind_intent = new Intent();\r\n bind_intent.setClassName(WebkitServerConsts.WEBKITSERVER_SERVICE_PACKAGE,\r\n WebkitServerConsts.WEBKITSERVER_SERVICE_CLASS);\r\n bindService(\r\n bind_intent,\r\n mBackgroundServices.webkitfilesServiceConnection,\r\n Context.BIND_AUTO_CREATE\r\n | ((Build.VERSION.SDK_INT >= 14) ? Context.BIND_ADJUST_WITH_ACTIVITY : 0));\r\n }\r\n\r\n if (useDatabase && mBackgroundServices.databaseService == null &&\r\n mBackgroundServices.databaseServiceConnection == null) {\r\n Log.i(t, \"Attempting bind to Database service\");\r\n mBackgroundServices.databaseServiceConnection = new ServiceConnectionWrapper();\r\n Intent bind_intent = new Intent();\r\n bind_intent.setClassName(DatabaseConsts.DATABASE_SERVICE_PACKAGE,\r\n DatabaseConsts.DATABASE_SERVICE_CLASS);\r\n bindService(\r\n bind_intent,\r\n mBackgroundServices.databaseServiceConnection,\r\n Context.BIND_AUTO_CREATE\r\n | ((Build.VERSION.SDK_INT >= 14) ? Context.BIND_ADJUST_WITH_ACTIVITY : 0));\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * \r\n * @param className\r\n * @param service can be null if we are mocked\r\n */\r\n private void doServiceConnected(ComponentName className, IBinder service) {\r\n if (className.getClassName().equals(WebkitServerConsts.WEBKITSERVER_SERVICE_CLASS)) {\r\n Log.i(t, \"Bound to WebServer service\");\r\n mBackgroundServices.webkitfilesService = (service == null) ? null : OdkWebkitServerInterface.Stub.asInterface(service);\r\n }\r\n\r\n if (className.getClassName().equals(DatabaseConsts.DATABASE_SERVICE_CLASS)) {\r\n Log.i(t, \"Bound to Database service\");\r\n mBackgroundServices.databaseService = (service == null) ? null : OdkDbInterface.Stub.asInterface(service);\r\n \r\n triggerDatabaseEvent(false);\r\n }\r\n\r\n configureView();\r\n }\r\n \r\n public OdkDbInterface getDatabase() {\r\n if ( isMocked ) {\r\n return mockDatabaseService;\r\n } else {\r\n return mBackgroundServices.databaseService;\r\n }\r\n }\r\n \r\n private OdkWebkitServerInterface getWebkitServer() {\r\n if ( isMocked ) {\r\n return mockWebkitServerService;\r\n } else {\r\n return mBackgroundServices.webkitfilesService;\r\n }\r\n }\r\n \r\n public void configureView() {\r\n if ( activeActivity != null ) {\r\n Log.i(t, \"configureView - possibly updating service information within ODKWebView\");\r\n if ( getWebKitResourceId() != -1 ) {\r\n View v = activeActivity.findViewById(getWebKitResourceId());\r\n if (v != null && v instanceof ODKWebView) {\r\n ODKWebView wv = (ODKWebView) v;\r\n if (mBackgroundServices.isDestroying) {\r\n wv.serviceChange(false);\r\n } else {\r\n OdkWebkitServerInterface webkitServerIf = getWebkitServer();\r\n OdkDbInterface dbIf = getDatabase();\r\n wv.serviceChange(webkitServerIf != null && dbIf != null);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n private void doServiceDisconnected(ComponentName className) {\r\n if (className.getClassName().equals(WebkitServerConsts.WEBKITSERVER_SERVICE_CLASS)) {\r\n if (mBackgroundServices.isDestroying) {\r\n Log.i(t, \"Unbound from WebServer service (intentionally)\");\r\n } else {\r\n Log.w(t, \"Unbound from WebServer service (unexpected)\");\r\n }\r\n mBackgroundServices.webkitfilesService = null;\r\n unbindWebkitfilesServiceWrapper();\r\n }\r\n\r\n if (className.getClassName().equals(DatabaseConsts.DATABASE_SERVICE_CLASS)) {\r\n if (mBackgroundServices.isDestroying) {\r\n Log.i(t, \"Unbound from Database service (intentionally)\");\r\n } else {\r\n Log.w(t, \"Unbound from Database service (unexpected)\");\r\n }\r\n mBackgroundServices.databaseService = null;\r\n unbindDatabaseBinderWrapper();\r\n }\r\n\r\n configureView();\r\n\r\n // the bindToService() method decides whether to connect or not...\r\n bindToService();\r\n }\r\n\r\n // /////////////////////////////////////////////////////////////////////////\r\n // registrations\r\n\r\n /**\r\n * Called by an activity when it has been sufficiently initialized so\r\n * that it can handle a databaseAvailable() call.\r\n * \r\n * @param activity\r\n */\r\n public void establishDatabaseConnectionListener(Activity activity) {\r\n databaseListenerActivity = activity;\r\n triggerDatabaseEvent(true);\r\n }\r\n\r\n /**\r\n * If the given activity is active, then fire the callback based upon \r\n * the availability of the database.\r\n * \r\n * @param activity\r\n * @param listener\r\n */\r\n public void possiblyFireDatabaseCallback(Activity activity, DatabaseConnectionListener listener) {\r\n if ( activeActivity != null &&\r\n activeActivity == databaseListenerActivity &&\r\n databaseListenerActivity == activity ) {\r\n if ( this.getDatabase() == null ) {\r\n listener.databaseUnavailable();\r\n } else {\r\n listener.databaseAvailable();\r\n }\r\n }\r\n }\r\n \r\n private void triggerDatabaseEvent(boolean availableOnly) {\r\n if ( activeActivity != null &&\r\n activeActivity == databaseListenerActivity &&\r\n activeActivity instanceof DatabaseConnectionListener ) {\r\n if ( !availableOnly && this.getDatabase() == null ) {\r\n ((DatabaseConnectionListener) activeActivity).databaseUnavailable();\r\n } else {\r\n ((DatabaseConnectionListener) activeActivity).databaseAvailable();\r\n }\r\n }\r\n }\r\n \r\n public void establishInitializationListener(InitializationListener listener) {\r\n mInitializationListener = listener;\r\n // async task may have completed while we were reorienting...\r\n if (mBackgroundTasks.mInitializationTask != null\r\n && mBackgroundTasks.mInitializationTask.getStatus() == AsyncTask.Status.FINISHED) {\r\n this.initializationComplete(mBackgroundTasks.mInitializationTask.getOverallSuccess(),\r\n mBackgroundTasks.mInitializationTask.getResult());\r\n }\r\n }\r\n\r\n // ///////////////////////////////////////////////////\r\n // actions\r\n\r\n public synchronized boolean initializeAppName(String appName, InitializationListener listener) {\r\n mInitializationListener = listener;\r\n if (mBackgroundTasks.mInitializationTask != null\r\n && mBackgroundTasks.mInitializationTask.getStatus() != AsyncTask.Status.FINISHED) {\r\n // Toast.makeText(this.getActivity(),\r\n // getString(R.string.expansion_in_progress),\r\n // Toast.LENGTH_LONG).show();\r\n return true;\r\n } else if ( getDatabase() != null ) {\r\n InitializationTask cf = new InitializationTask();\r\n cf.setApplication(this);\r\n cf.setAppName(appName);\r\n cf.setInitializationListener(this);\r\n mBackgroundTasks.mInitializationTask = cf;\r\n executeTask(mBackgroundTasks.mInitializationTask, (Void) null);\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }\r\n\r\n // /////////////////////////////////////////////////////////////////////////\r\n // clearing tasks\r\n //\r\n // NOTE: clearing these makes us forget that they are running, but it is\r\n // up to the task itself to eventually shutdown. i.e., we don't quite\r\n // know when they actually stop.\r\n\r\n\r\n public synchronized void clearInitializationTask() {\r\n mInitializationListener = null;\r\n if (mBackgroundTasks.mInitializationTask != null) {\r\n mBackgroundTasks.mInitializationTask.setInitializationListener(null);\r\n if (mBackgroundTasks.mInitializationTask.getStatus() != AsyncTask.Status.FINISHED) {\r\n mBackgroundTasks.mInitializationTask.cancel(true);\r\n }\r\n }\r\n mBackgroundTasks.mInitializationTask = null;\r\n }\r\n\r\n // /////////////////////////////////////////////////////////////////////////\r\n // cancel requests\r\n //\r\n // These maintain communications paths, so that we get a failure\r\n // completion callback eventually.\r\n\r\n\r\n public synchronized void cancelInitializationTask() {\r\n if (mBackgroundTasks.mInitializationTask != null) {\r\n if (mBackgroundTasks.mInitializationTask.getStatus() != AsyncTask.Status.FINISHED) {\r\n mBackgroundTasks.mInitializationTask.cancel(true);\r\n }\r\n }\r\n }\r\n\r\n // /////////////////////////////////////////////////////////////////////////\r\n // callbacks\r\n\r\n @Override\r\n public void initializationComplete(boolean overallSuccess, ArrayList result) {\r\n if (mInitializationListener != null) {\r\n mInitializationListener.initializationComplete(overallSuccess, result);\r\n }\r\n }\r\n\r\n @Override\r\n public void initializationProgressUpdate(String status) {\r\n if (mInitializationListener != null) {\r\n mInitializationListener.initializationProgressUpdate(status);\r\n }\r\n }\r\n\r\n}\r\n"},"message":{"kind":"string","value":"Move PRNG fix up to base class\n"},"old_file":{"kind":"string","value":"androidcommon_lib/src/main/java/org/opendatakit/common/android/application/CommonApplication.java"},"subject":{"kind":"string","value":"Move PRNG fix up to base class"},"git_diff":{"kind":"string","value":"ndroidcommon_lib/src/main/java/org/opendatakit/common/android/application/CommonApplication.java\n import org.opendatakit.common.android.logic.PropertiesSingleton;\n import org.opendatakit.common.android.task.InitializationTask;\n import org.opendatakit.common.android.utilities.ODKFileUtils;\nimport org.opendatakit.common.android.utilities.PRNGFixes;\n import org.opendatakit.common.android.views.ODKWebView;\n import org.opendatakit.database.DatabaseConsts;\n import org.opendatakit.database.service.OdkDbInterface;\n \n public CommonApplication() {\n super();\n PRNGFixes.apply();\n }\n \n @SuppressLint(\"NewApi\")"}}},{"rowIdx":1963,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"8061aa5217a92dffd2c643f4cb643b388d8076e6"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"jpkrohling/keycloak,stianst/keycloak,darranl/keycloak,mhajas/keycloak,vmuzikar/keycloak,abstractj/keycloak,ahus1/keycloak,darranl/keycloak,stianst/keycloak,keycloak/keycloak,hmlnarik/keycloak,pedroigor/keycloak,pedroigor/keycloak,raehalme/keycloak,thomasdarimont/keycloak,hmlnarik/keycloak,pedroigor/keycloak,mposolda/keycloak,ahus1/keycloak,jpkrohling/keycloak,jpkrohling/keycloak,darranl/keycloak,hmlnarik/keycloak,ssilvert/keycloak,mposolda/keycloak,reneploetz/keycloak,vmuzikar/keycloak,srose/keycloak,stianst/keycloak,hmlnarik/keycloak,ahus1/keycloak,jpkrohling/keycloak,ahus1/keycloak,vmuzikar/keycloak,mhajas/keycloak,abstractj/keycloak,srose/keycloak,hmlnarik/keycloak,keycloak/keycloak,vmuzikar/keycloak,mhajas/keycloak,keycloak/keycloak,darranl/keycloak,thomasdarimont/keycloak,srose/keycloak,ahus1/keycloak,hmlnarik/keycloak,reneploetz/keycloak,raehalme/keycloak,reneploetz/keycloak,reneploetz/keycloak,mhajas/keycloak,ssilvert/keycloak,vmuzikar/keycloak,reneploetz/keycloak,ssilvert/keycloak,pedroigor/keycloak,keycloak/keycloak,mposolda/keycloak,mposolda/keycloak,mposolda/keycloak,jpkrohling/keycloak,thomasdarimont/keycloak,mposolda/keycloak,abstractj/keycloak,stianst/keycloak,srose/keycloak,ssilvert/keycloak,ssilvert/keycloak,thomasdarimont/keycloak,thomasdarimont/keycloak,raehalme/keycloak,mhajas/keycloak,vmuzikar/keycloak,pedroigor/keycloak,abstractj/keycloak,pedroigor/keycloak,keycloak/keycloak,abstractj/keycloak,ahus1/keycloak,raehalme/keycloak,thomasdarimont/keycloak,stianst/keycloak,raehalme/keycloak,srose/keycloak,raehalme/keycloak"},"new_contents":{"kind":"string","value":"/*\n * Copyright 2016 Red Hat, Inc. and/or its affiliates\n * and other contributors as indicated by the @author tags.\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 org.keycloak.adapters.authentication;\n\nimport org.apache.http.NameValuePair;\nimport org.apache.http.client.methods.HttpPost;\nimport org.apache.http.message.BasicNameValuePair;\nimport org.jboss.logging.Logger;\nimport org.keycloak.adapters.KeycloakDeployment;\n\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.ServiceConfigurationError;\nimport java.util.ServiceLoader;\n\n/**\n * @author Marek Posolda\n */\npublic class ClientCredentialsProviderUtils {\n\n private static Logger logger = Logger.getLogger(ClientCredentialsProviderUtils.class);\n\n public static ClientCredentialsProvider bootstrapClientAuthenticator(KeycloakDeployment deployment) {\n String clientId = deployment.getResourceName();\n Map clientCredentials = deployment.getResourceCredentials();\n\n String authenticatorId;\n if (clientCredentials == null || clientCredentials.isEmpty()) {\n authenticatorId = ClientIdAndSecretCredentialsProvider.PROVIDER_ID;\n } else {\n authenticatorId = (String) clientCredentials.get(\"provider\");\n if (authenticatorId == null) {\n // If there is just one credential type, use provider from it\n if (clientCredentials.size() == 1) {\n authenticatorId = clientCredentials.keySet().iterator().next();\n } else {\n throw new RuntimeException(\"Can't identify clientAuthenticator from the configuration of client '\" + clientId + \"' . Check your adapter configurations\");\n }\n }\n }\n\n logger.debugf(\"Using provider '%s' for authentication of client '%s'\", authenticatorId, clientId);\n\n Map authenticators = new HashMap<>();\n loadAuthenticators(authenticators, ClientCredentialsProviderUtils.class.getClassLoader());\n loadAuthenticators(authenticators, Thread.currentThread().getContextClassLoader());\n\n ClientCredentialsProvider authenticator = authenticators.get(authenticatorId);\n if (authenticator == null) {\n throw new RuntimeException(\"Couldn't find ClientCredentialsProvider implementation class with id: \" + authenticatorId + \". Loaded authentication providers: \" + authenticators.keySet());\n }\n\n Object config = (clientCredentials==null) ? null : clientCredentials.get(authenticatorId);\n authenticator.init(deployment, config);\n\n return authenticator;\n }\n\n private static void loadAuthenticators(Map authenticators, ClassLoader classLoader) {\n Iterator iterator = ServiceLoader.load(ClientCredentialsProvider.class, classLoader).iterator();\n while (iterator.hasNext()) {\n try {\n ClientCredentialsProvider authenticator = iterator.next();\n logger.debugf(\"Loaded clientCredentialsProvider %s\", authenticator.getId());\n authenticators.put(authenticator.getId(), authenticator);\n } catch (ServiceConfigurationError e) {\n if (logger.isDebugEnabled()) {\n logger.debug(\"Failed to load clientCredentialsProvider with classloader: \" + classLoader, e);\n }\n }\n }\n }\n\n /**\n * Use this method when calling backchannel request directly from your application. See service-account example from demo for more details\n */\n public static void setClientCredentials(KeycloakDeployment deployment, Map requestHeaders, Map formparams) {\n ClientCredentialsProvider authenticator = deployment.getClientAuthenticator();\n authenticator.setClientCredentials(deployment, requestHeaders, formparams);\n }\n\n /**\n * Don't use directly from your JEE apps to avoid HttpClient linkage errors! Instead use the method {@link #setClientCredentials(KeycloakDeployment, Map, Map)}\n */\n public static void setClientCredentials(KeycloakDeployment deployment, HttpPost post, List formparams) {\n Map reqHeaders = new HashMap<>();\n Map reqParams = new HashMap<>();\n setClientCredentials(deployment, reqHeaders, reqParams);\n\n for (Map.Entry header : reqHeaders.entrySet()) {\n post.setHeader(header.getKey(), header.getValue());\n }\n\n for (Map.Entry param : reqParams.entrySet()) {\n formparams.add(new BasicNameValuePair(param.getKey(), param.getValue()));\n }\n }\n\n}\n"},"new_file":{"kind":"string","value":"adapters/oidc/adapter-core/src/main/java/org/keycloak/adapters/authentication/ClientCredentialsProviderUtils.java"},"old_contents":{"kind":"string","value":"/*\n * Copyright 2016 Red Hat, Inc. and/or its affiliates\n * and other contributors as indicated by the @author tags.\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 org.keycloak.adapters.authentication;\n\nimport org.apache.http.NameValuePair;\nimport org.apache.http.client.methods.HttpPost;\nimport org.apache.http.message.BasicNameValuePair;\nimport org.jboss.logging.Logger;\nimport org.keycloak.adapters.KeycloakDeployment;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.ServiceConfigurationError;\nimport java.util.ServiceLoader;\n\n/**\n * @author Marek Posolda\n */\npublic class ClientCredentialsProviderUtils {\n\n private static Logger logger = Logger.getLogger(ClientCredentialsProviderUtils.class);\n\n public static ClientCredentialsProvider bootstrapClientAuthenticator(KeycloakDeployment deployment) {\n String clientId = deployment.getResourceName();\n Map clientCredentials = deployment.getResourceCredentials();\n\n String authenticatorId;\n if (clientCredentials == null || clientCredentials.isEmpty()) {\n authenticatorId = ClientIdAndSecretCredentialsProvider.PROVIDER_ID;\n } else {\n authenticatorId = (String) clientCredentials.get(\"provider\");\n if (authenticatorId == null) {\n // If there is just one credential type, use provider from it\n if (clientCredentials.size() == 1) {\n authenticatorId = clientCredentials.keySet().iterator().next();\n } else {\n throw new RuntimeException(\"Can't identify clientAuthenticator from the configuration of client '\" + clientId + \"' . Check your adapter configurations\");\n }\n }\n }\n\n logger.debugf(\"Using provider '%s' for authentication of client '%s'\", authenticatorId, clientId);\n\n Map authenticators = new HashMap<>();\n loadAuthenticators(authenticators, ClientCredentialsProviderUtils.class.getClassLoader());\n loadAuthenticators(authenticators, Thread.currentThread().getContextClassLoader());\n\n ClientCredentialsProvider authenticator = authenticators.get(authenticatorId);\n if (authenticator == null) {\n throw new RuntimeException(\"Couldn't find ClientCredentialsProvider implementation class with id: \" + authenticatorId + \". Loaded authentication providers: \" + authenticators.keySet());\n }\n\n Object config = (clientCredentials==null) ? null : clientCredentials.get(authenticatorId);\n authenticator.init(deployment, config);\n\n return authenticator;\n }\n\n private static void loadAuthenticators(Map authenticators, ClassLoader classLoader) {\n for (ClientCredentialsProvider authenticator : ServiceLoader.load(ClientCredentialsProvider.class, classLoader)) {\n try {\n logger.debugf(\"Loaded clientCredentialsProvider %s\", authenticator.getId());\n authenticators.put(authenticator.getId(), authenticator);\n } catch (ServiceConfigurationError e) {\n if (logger.isDebugEnabled()) {\n logger.debug(\"Failed to load clientCredentialsProvider with classloader: \" + classLoader, e);\n }\n }\n }\n }\n\n /**\n * Use this method when calling backchannel request directly from your application. See service-account example from demo for more details\n */\n public static void setClientCredentials(KeycloakDeployment deployment, Map requestHeaders, Map formparams) {\n ClientCredentialsProvider authenticator = deployment.getClientAuthenticator();\n authenticator.setClientCredentials(deployment, requestHeaders, formparams);\n }\n\n /**\n * Don't use directly from your JEE apps to avoid HttpClient linkage errors! Instead use the method {@link #setClientCredentials(KeycloakDeployment, Map, Map)}\n */\n public static void setClientCredentials(KeycloakDeployment deployment, HttpPost post, List formparams) {\n Map reqHeaders = new HashMap<>();\n Map reqParams = new HashMap<>();\n setClientCredentials(deployment, reqHeaders, reqParams);\n\n for (Map.Entry header : reqHeaders.entrySet()) {\n post.setHeader(header.getKey(), header.getValue());\n }\n\n for (Map.Entry param : reqParams.entrySet()) {\n formparams.add(new BasicNameValuePair(param.getKey(), param.getValue()));\n }\n }\n\n}\n"},"message":{"kind":"string","value":"KEYCLOAK-13161 Use iterator instead of for-each loop in ClientCredentialsProviderUtils\n"},"old_file":{"kind":"string","value":"adapters/oidc/adapter-core/src/main/java/org/keycloak/adapters/authentication/ClientCredentialsProviderUtils.java"},"subject":{"kind":"string","value":"KEYCLOAK-13161 Use iterator instead of for-each loop in ClientCredentialsProviderUtils"},"git_diff":{"kind":"string","value":"dapters/oidc/adapter-core/src/main/java/org/keycloak/adapters/authentication/ClientCredentialsProviderUtils.java\n import org.keycloak.adapters.KeycloakDeployment;\n \n import java.util.HashMap;\nimport java.util.Iterator;\n import java.util.List;\n import java.util.Map;\n import java.util.ServiceConfigurationError;\n }\n \n private static void loadAuthenticators(Map authenticators, ClassLoader classLoader) {\n for (ClientCredentialsProvider authenticator : ServiceLoader.load(ClientCredentialsProvider.class, classLoader)) {\n Iterator iterator = ServiceLoader.load(ClientCredentialsProvider.class, classLoader).iterator();\n while (iterator.hasNext()) {\n try {\n ClientCredentialsProvider authenticator = iterator.next();\n logger.debugf(\"Loaded clientCredentialsProvider %s\", authenticator.getId());\n authenticators.put(authenticator.getId(), authenticator);\n } catch (ServiceConfigurationError e) {"}}},{"rowIdx":1964,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"lgpl-2.1"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"286cf1f6140370bcbae8a02524feef648e70b9d3"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine"},"new_contents":{"kind":"string","value":"package org.intermine.bio.postprocess;\n\n/*\n * Copyright (C) 2002-2005 FlyMine\n *\n * This code may be freely distributed and modified under the\n * terms of the GNU Lesser General Public Licence. This should\n * be distributed with the code. See the LICENSE file for more\n * information or http://www.gnu.org/copyleft/lesser.html.\n *\n */\n\nimport java.util.BitSet;\nimport java.util.Collections;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.apache.log4j.Logger;\n\nimport org.intermine.objectstore.query.Query;\nimport org.intermine.objectstore.query.*;\nimport org.intermine.objectstore.query.QueryClass;\nimport org.intermine.objectstore.query.Results;\nimport org.intermine.objectstore.query.ResultsRow;\nimport org.intermine.objectstore.query.QueryCollectionReference;\nimport org.intermine.objectstore.query.QueryObjectReference;\nimport org.intermine.objectstore.query.ConstraintSet;\nimport org.intermine.model.InterMineObject;\nimport org.intermine.objectstore.ObjectStore;\nimport org.intermine.objectstore.ObjectStoreException;\nimport org.intermine.objectstore.ObjectStoreWriter;\nimport org.intermine.util.DynamicUtil;\nimport org.intermine.util.TypeUtil;\nimport org.intermine.objectstore.intermine.ObjectStoreInterMineImpl;\n\nimport org.flymine.model.genomic.DataSet;\nimport org.flymine.model.genomic.DataSource;\nimport org.flymine.model.genomic.Chromosome;\nimport org.flymine.model.genomic.Transcript;\nimport org.flymine.model.genomic.Exon;\nimport org.flymine.model.genomic.Intron;\nimport org.flymine.model.genomic.Location;\nimport org.flymine.model.genomic.Synonym;\n\n/**\n * Methods for creating feature for introns.\n * @author Wenyan Ji\n */\npublic class IntronUtil\n{\n private static final Logger LOG = Logger.getLogger(IntronUtil.class);\n\n private ObjectStoreWriter osw = null;\n private ObjectStore os;\n private DataSet dataSet;\n private DataSource dataSource;\n\n protected Map intronMap = new HashMap();\n\n /**\n * Create a new IntronUtil object that will operate on the given ObjectStoreWriter.\n * NOTE - needs to be run after LocatedSequenceFeature.chromosomeLocation has been set.\n * @param osw the ObjectStoreWriter to use when creating/changing objects\n */\n public IntronUtil(ObjectStoreWriter osw) {\n this.osw = osw;\n this.os = osw.getObjectStore();\n dataSource = (DataSource) DynamicUtil.createObject(Collections.singleton(DataSource.class));\n dataSource.setName(\"FlyMine\");\n try {\n dataSource = (DataSource) os.getObjectByExample(dataSource,\n Collections.singleton(\"name\"));\n } catch (ObjectStoreException e) {\n throw new RuntimeException(\"unable to fetch FlyMine DataSource object\", e);\n }\n }\n\n /**\n * Create Intron objects\n * @throws ObjectStoreException if there is an ObjectStore problem\n * @throws IllegalAccessException if there is an ObjectStore problem\n */\n public void createIntronFeatures()\n throws ObjectStoreException, IllegalAccessException {\n\n dataSet = (DataSet) DynamicUtil.createObject(Collections.singleton(DataSet.class));\n dataSet.setTitle(\"FlyMine introns\");\n dataSet.setDescription(\"Introns calculated by FlyMine\");\n dataSet.setVersion(\"\" + new Date()); // current time and date\n dataSet.setUrl(\"http://www.flymine.org\");\n dataSet.setDataSource(dataSource);\n\n int exonCounts;\n Query q = new Query();\n ConstraintSet cs = new ConstraintSet(ConstraintOp.AND);\n QueryClass qcTran = new QueryClass(Transcript.class);\n q.addFrom(qcTran);\n q.addToSelect(qcTran);\n\n QueryClass qcTranLoc = new QueryClass(Location.class);\n q.addFrom(qcTranLoc);\n q.addToSelect(qcTranLoc);\n QueryObjectReference qorTranLoc = new QueryObjectReference(qcTran, \"chromosomeLocation\");\n ContainsConstraint ccTranLoc = new ContainsConstraint(qorTranLoc, ConstraintOp.CONTAINS, qcTranLoc);\n cs.addConstraint(ccTranLoc);\n\n QueryClass qcExon = new QueryClass(Exon.class);\n q.addFrom(qcExon);\n QueryCollectionReference qcrExons = new QueryCollectionReference(qcTran, \"exons\");\n ContainsConstraint ccTranExons = new ContainsConstraint(qcrExons, ConstraintOp.CONTAINS, qcExon);\n cs.addConstraint(ccTranExons);\n\n QueryClass qcExonLoc = new QueryClass(Location.class);\n q.addFrom(qcExonLoc);\n q.addToSelect(qcExonLoc);\n QueryObjectReference qorExonLoc = new QueryObjectReference(qcExon, \"chromosomeLocation\");\n ContainsConstraint ccExonLoc = new ContainsConstraint(qorExonLoc, ConstraintOp.CONTAINS, qcExonLoc);\n cs.addConstraint(ccExonLoc);\n\n q.setConstraint(cs);\n q.addToOrderBy(qcTran);\n\n ((ObjectStoreInterMineImpl) os).precompute(q, PostProcessTask.PRECOMPUTE_CATEGORY);\n Results results = new Results(q, os, os.getSequence());\n results.setBatchSize(500);\n Iterator resultsIter = results.iterator();\n\n Set locationSet = new HashSet();\n Transcript lastTran = null;\n Location lastTranLoc = null;\n int tranCount = 0, exonCount = 0, intronCount = 0;\n while (resultsIter.hasNext()) {\n ResultsRow rr = (ResultsRow) resultsIter.next();\n Transcript thisTran = (Transcript) rr.get(0);\n\n if (lastTran == null) {\n lastTran = thisTran;\n lastTranLoc = (Location) rr.get(1);\n }\n\n if (!thisTran.getId().equals(lastTran.getId())) {\n tranCount++;\n intronCount += createIntronFeatures(locationSet, lastTran, lastTranLoc);\n exonCount += locationSet.size();\n if ((tranCount % 100) == 0) {\n LOG.info(\"Created \" + intronCount + \" Introns for \" + tranCount\n + \" Transcripts with \" + exonCount + \" Exons.\");\n }\n locationSet = new HashSet();\n lastTran = thisTran;\n lastTranLoc = (Location) rr.get(1);\n }\n locationSet.add(rr.get(2));\n }\n\n if (lastTran != null) {\n intronCount += createIntronFeatures(locationSet, lastTran, lastTranLoc);\n tranCount++;\n exonCount += locationSet.size();\n }\n\n LOG.info(\"Read \" + tranCount + \" transcripts with \" + exonCount + \" exons.\");\n\n osw.beginTransaction();\n for (Iterator i = intronMap.keySet().iterator(); i.hasNext();) {\n String identifier = (String) i.next();\n Intron intron = (Intron) intronMap.get(identifier);\n osw.store(intron);\n osw.store(intron.getChromosomeLocation());\n osw.store((InterMineObject) intron.getSynonyms().iterator().next());\n }\n\n if (intronMap.size() > 1) {\n osw.store(dataSet);\n }\n osw.commitTransaction();\n }\n\n\n /**\n * Return a set of Intron objects that don't overlap the Locations\n * in the locationSet argument. The caller must call ObjectStoreWriter.store() on the\n * Intron, its chromosomeLocation and the synonym in the synonyms collection.\n * @param locationSet a set of Locations for the exonss on a particular transcript\n * @param transcriptId the ID of the Transcript that the Locations refer to\n * @return a set of Intron objects\n * @throws ObjectStoreException if there is an ObjectStore problem\n */\n protected int createIntronFeatures(Set locationSet, Transcript transcript, Location tranLoc)\n throws ObjectStoreException {\n //final BitSet bs = new BitSet(transcript.getLength().intValue() + 1);\n final BitSet bs = new BitSet(transcript.getLength().intValue());\n\n if (locationSet.size() == 1) {\n return 0;\n }\n Chromosome chr = transcript.getChromosome();\n\n Iterator locationIter = locationSet.iterator();\n int tranStart = tranLoc.getStart().intValue();\n\n while (locationIter.hasNext()) {\n Location location = (Location) locationIter.next();\n bs.set(location.getStart().intValue() - tranStart, (location.getEnd().intValue() - tranStart) + 1);\n }\n\n int prevEndPos = 0;\n\n int intronCount = 0;\n while (prevEndPos != -1) {\n intronCount++;\n int nextIntronStart = bs.nextClearBit(prevEndPos + 1);\n int intronEnd;\n int nextSetBit = bs.nextSetBit(nextIntronStart);\n\n if (nextSetBit == -1) {\n intronEnd = transcript.getLength().intValue();\n } else {\n intronEnd = nextSetBit - 1;\n }\n\n if (nextSetBit == -1\n || intronCount == (locationSet.size() - 1)) {\n prevEndPos = -1;\n } else {\n prevEndPos = intronEnd;\n }\n\n int newLocStart = nextIntronStart + tranStart;\n int newLocEnd = intronEnd + tranStart;\n\n String identifier = \"intron_chr\" + chr.getIdentifier()\n + \"_\" + Integer.toString(newLocStart) + \"..\" + Integer.toString(newLocEnd);\n\n if (intronMap.get(identifier) == null) {\n Intron intron = (Intron)\n DynamicUtil.createObject(Collections.singleton(Intron.class));\n Location location =\n (Location) DynamicUtil.createObject(Collections.singleton(Location.class));\n Synonym synonym =\n (Synonym) DynamicUtil.createObject(Collections.singleton(Synonym.class));\n\n intron.setChromosome(chr);\n intron.setOrganism(chr.getOrganism());\n intron.addEvidence(dataSet);\n intron.setIdentifier(identifier);\n\n location.setStart(new Integer(newLocStart));\n location.setEnd(new Integer(newLocEnd));\n location.setStrand(new Integer(1));\n location.setPhase(new Integer(0));\n location.setStartIsPartial(Boolean.FALSE);\n location.setEndIsPartial(Boolean.FALSE);\n location.setSubject(intron);\n location.setObject(transcript);\n location.addEvidence(dataSet);\n\n synonym.addEvidence(dataSet);\n synonym.setSource(dataSource);\n synonym.setSubject(intron);\n synonym.setType(\"identifier\");\n synonym.setValue(intron.getIdentifier());\n\n intron.setChromosomeLocation(location);\n intron.addSynonyms(synonym);\n int length = location.getEnd().intValue() - location.getStart().intValue() + 1;\n intron.setLength(new Integer(length));\n intron.addTranscripts(transcript);\n\n intronMap.put(identifier, intron);\n } else {\n Intron intron = (Intron) intronMap.get(identifier);\n intron.addTranscripts(transcript);\n intronMap.put(identifier, intron);\n }\n }\n return intronCount;\n }\n}\n"},"new_file":{"kind":"string","value":"bio/postprocess/main/src/org/intermine/bio/postprocess/IntronUtil.java"},"old_contents":{"kind":"string","value":"package org.intermine.bio.postprocess;\n\n/*\n * Copyright (C) 2002-2005 FlyMine\n *\n * This code may be freely distributed and modified under the\n * terms of the GNU Lesser General Public Licence. This should\n * be distributed with the code. See the LICENSE file for more\n * information or http://www.gnu.org/copyleft/lesser.html.\n *\n */\n\nimport java.util.BitSet;\nimport java.util.Collections;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.apache.log4j.Logger;\n\nimport org.intermine.objectstore.query.Query;\nimport org.intermine.objectstore.query.*;\nimport org.intermine.objectstore.query.QueryClass;\nimport org.intermine.objectstore.query.Results;\nimport org.intermine.objectstore.query.ResultsRow;\nimport org.intermine.objectstore.query.QueryCollectionReference;\nimport org.intermine.objectstore.query.QueryObjectReference;\nimport org.intermine.objectstore.query.ConstraintSet;\nimport org.intermine.model.InterMineObject;\nimport org.intermine.objectstore.ObjectStore;\nimport org.intermine.objectstore.ObjectStoreException;\nimport org.intermine.objectstore.ObjectStoreWriter;\nimport org.intermine.util.DynamicUtil;\nimport org.intermine.util.TypeUtil;\nimport org.intermine.objectstore.intermine.ObjectStoreInterMineImpl;\n\nimport org.flymine.model.genomic.DataSet;\nimport org.flymine.model.genomic.DataSource;\nimport org.flymine.model.genomic.Chromosome;\nimport org.flymine.model.genomic.Transcript;\nimport org.flymine.model.genomic.Exon;\nimport org.flymine.model.genomic.Intron;\nimport org.flymine.model.genomic.Location;\nimport org.flymine.model.genomic.Synonym;\n\n/**\n * Methods for creating feature for introns.\n * @author Wenyan Ji\n */\npublic class IntronUtil\n{\n private static final Logger LOG = Logger.getLogger(IntronUtil.class);\n\n private ObjectStoreWriter osw = null;\n private ObjectStore os;\n private DataSet dataSet;\n private DataSource dataSource;\n\n protected Map intronMap = new HashMap();\n\n /**\n * Create a new IntronUtil object that will operate on the given ObjectStoreWriter.\n * NOTE - needs to be run after LocatedSequenceFeature.chromosomeLocation has been set.\n * @param osw the ObjectStoreWriter to use when creating/changing objects\n */\n public IntronUtil(ObjectStoreWriter osw) {\n this.osw = osw;\n this.os = osw.getObjectStore();\n dataSource = (DataSource) DynamicUtil.createObject(Collections.singleton(DataSource.class));\n dataSource.setName(\"FlyMine\");\n try {\n dataSource = (DataSource) os.getObjectByExample(dataSource,\n Collections.singleton(\"name\"));\n } catch (ObjectStoreException e) {\n throw new RuntimeException(\"unable to fetch FlyMine DataSource object\", e);\n }\n }\n\n /**\n * Create Intron objects\n * @throws ObjectStoreException if there is an ObjectStore problem\n * @throws IllegalAccessException if there is an ObjectStore problem\n */\n public void createIntronFeatures()\n throws ObjectStoreException, IllegalAccessException {\n\n dataSet = (DataSet) DynamicUtil.createObject(Collections.singleton(DataSet.class));\n dataSet.setTitle(\"FlyMine introns\");\n dataSet.setDescription(\"Introns calculated by FlyMine\");\n dataSet.setVersion(\"\" + new Date()); // current time and date\n dataSet.setUrl(\"http://www.flymine.org\");\n dataSet.setDataSource(dataSource);\n\n int exonCounts;\n Query q = new Query();\n ConstraintSet cs = new ConstraintSet(ConstraintOp.AND);\n QueryClass qcTran = new QueryClass(Transcript.class);\n q.addFrom(qcTran);\n q.addToSelect(qcTran);\n\n QueryClass qcTranLoc = new QueryClass(Location.class);\n q.addFrom(qcTranLoc);\n q.addToSelect(qcTranLoc);\n QueryObjectReference qorTranLoc = new QueryObjectReference(qcTran, \"chromosomeLocation\");\n ContainsConstraint ccTranLoc = new ContainsConstraint(qorTranLoc, ConstraintOp.CONTAINS, qcTranLoc);\n cs.addConstraint(ccTranLoc);\n\n QueryClass qcExon = new QueryClass(Exon.class);\n q.addFrom(qcExon);\n QueryCollectionReference qcrExons = new QueryCollectionReference(qcTran, \"exons\");\n ContainsConstraint ccTranExons = new ContainsConstraint(qcrExons, ConstraintOp.CONTAINS, qcExon);\n cs.addConstraint(ccTranExons);\n\n QueryClass qcExonLoc = new QueryClass(Location.class);\n q.addFrom(qcExonLoc);\n q.addToSelect(qcExonLoc);\n QueryObjectReference qorExonLoc = new QueryObjectReference(qcExon, \"chromosomeLocation\");\n ContainsConstraint ccExonLoc = new ContainsConstraint(qorExonLoc, ConstraintOp.CONTAINS, qcExonLoc);\n cs.addConstraint(ccExonLoc);\n\n q.setConstraint(cs);\n q.addToOrderBy(qcTran);\n\n ((ObjectStoreInterMineImpl) os).precompute(q, PostProcessTask.PRECOMPUTE_CATEGORY);\n Results results = new Results(q, os, os.getSequence());\n results.setBatchSize(500);\n Iterator resultsIter = results.iterator();\n\n Set locationSet = new HashSet();\n Transcript lastTran = null;\n Location lastTranLoc = null;\n int tranCount = 0, exonCount = 0;\n while (resultsIter.hasNext()) {\n ResultsRow rr = (ResultsRow) resultsIter.next();\n Transcript thisTran = (Transcript) rr.get(0);\n\n if (lastTran == null) {\n lastTran = thisTran;\n lastTranLoc = (Location) rr.get(1);\n }\n\n if (!thisTran.getId().equals(lastTran.getId())) {\n tranCount++;\n Set intronSet = createIntronFeatures(locationSet, lastTran, lastTranLoc);\n exonCount += locationSet.size();\n locationSet = new HashSet();\n lastTran = thisTran;\n lastTranLoc = (Location) rr.get(1);\n }\n locationSet.add(rr.get(2));\n }\n\n if (lastTran != null) {\n Set intronSet = createIntronFeatures(locationSet, lastTran, lastTranLoc);\n tranCount++;\n exonCount += locationSet.size();\n }\n\n LOG.info(\"Read \" + tranCount + \" transcripts with \" + exonCount + \" exons.\");\n\n osw.beginTransaction();\n for (Iterator i = intronMap.keySet().iterator(); i.hasNext();) {\n String identifier = (String) i.next();\n Intron intron = (Intron) intronMap.get(identifier);\n osw.store(intron);\n osw.store(intron.getChromosomeLocation());\n osw.store((InterMineObject) intron.getSynonyms().iterator().next());\n }\n\n if (intronMap.size() > 1) {\n osw.store(dataSet);\n }\n osw.commitTransaction();\n //osw.abortTransaction();\n }\n\n\n /**\n * Return a set of Intron objects that don't overlap the Locations\n * in the locationSet argument. The caller must call ObjectStoreWriter.store() on the\n * Intron, its chromosomeLocation and the synonym in the synonyms collection.\n * @param locationSet a set of Locations for the exonss on a particular transcript\n * @param transcriptId the ID of the Transcript that the Locations refer to\n * @return a set of Intron objects\n * @throws ObjectStoreException if there is an ObjectStore problem\n */\n protected Set createIntronFeatures(Set locationSet, Transcript transcript, Location tranLoc)\n throws ObjectStoreException {\n //final BitSet bs = new BitSet(transcript.getLength().intValue() + 1);\n final BitSet bs = new BitSet(transcript.getLength().intValue());\n\n if (locationSet.size() == 1) {\n return null;\n }\n Chromosome chr = transcript.getChromosome();\n\n Iterator locationIter = locationSet.iterator();\n int tranStart = tranLoc.getStart().intValue();\n\n while (locationIter.hasNext()) {\n Location location = (Location) locationIter.next();\n bs.set(location.getStart().intValue() - tranStart, (location.getEnd().intValue() - tranStart) + 1);\n }\n\n int prevEndPos = 0;\n\n int intronCount = 0;\n while (prevEndPos != -1) {\n intronCount++;\n int nextIntronStart = bs.nextClearBit(prevEndPos + 1);\n int intronEnd;\n int nextSetBit = bs.nextSetBit(nextIntronStart);\n\n if (nextSetBit == -1) {\n intronEnd = transcript.getLength().intValue();\n } else {\n intronEnd = nextSetBit - 1;\n }\n\n if (nextSetBit == -1\n || intronCount == (locationSet.size() - 1)) {\n prevEndPos = -1;\n } else {\n prevEndPos = intronEnd;\n }\n\n int newLocStart = nextIntronStart + tranStart;\n int newLocEnd = intronEnd + tranStart;\n\n String identifier = \"intron_chr\" + chr.getIdentifier()\n + \"_\" + Integer.toString(newLocStart) + \"..\" + Integer.toString(newLocEnd);\n\n if (intronMap.get(identifier) == null) {\n Intron intron = (Intron)\n DynamicUtil.createObject(Collections.singleton(Intron.class));\n Location location =\n (Location) DynamicUtil.createObject(Collections.singleton(Location.class));\n Synonym synonym =\n (Synonym) DynamicUtil.createObject(Collections.singleton(Synonym.class));\n\n intron.setChromosome(chr);\n intron.setOrganism(chr.getOrganism());\n intron.addEvidence(dataSet);\n intron.setIdentifier(identifier);\n\n location.setStart(new Integer(newLocStart));\n location.setEnd(new Integer(newLocEnd));\n location.setStrand(new Integer(1));\n location.setPhase(new Integer(0));\n location.setStartIsPartial(Boolean.FALSE);\n location.setEndIsPartial(Boolean.FALSE);\n location.setSubject(intron);\n location.setObject(transcript);\n location.addEvidence(dataSet);\n\n synonym.addEvidence(dataSet);\n synonym.setSource(dataSource);\n synonym.setSubject(intron);\n synonym.setType(\"identifier\");\n synonym.setValue(intron.getIdentifier());\n\n intron.setChromosomeLocation(location);\n intron.addSynonyms(synonym);\n int length = location.getEnd().intValue() - location.getStart().intValue() + 1;\n intron.setLength(new Integer(length));\n intron.addTranscripts(transcript);\n\n intronMap.put(identifier, intron);\n } else {\n Intron intron = (Intron) intronMap.get(identifier);\n intron.addTranscripts(transcript);\n intronMap.put(identifier, intron);\n }\n }\n\n Set intronSet = new HashSet();\n for (Iterator i = intronMap.keySet().iterator(); i.hasNext(); ) {\n intronSet.add(intronMap.get(i.next()));\n }\n return intronSet;\n }\n\n /**\n * @param os objectStore\n * @param transcriptId Integer\n * @return all the exons locationSet for the particular transcriptId\n */\n private Set getLocationSet(ObjectStore os, Integer transcriptId) {\n Set locationSet = new HashSet();\n\n ConstraintSet cs = new ConstraintSet(ConstraintOp.AND);\n\n Query q = new Query();\n QueryClass qct = new QueryClass(Transcript.class);\n QueryField qf = new QueryField(qct, \"id\");\n SimpleConstraint sc1 = new SimpleConstraint(qf, ConstraintOp.EQUALS,\n new QueryValue(transcriptId));\n\n q.addFrom(qct);\n q.addToSelect(qf);\n q.addToOrderBy(qf);\n cs.addConstraint(sc1);\n\n QueryCollectionReference ref1 = new QueryCollectionReference(qct, \"exons\");\n QueryClass qce = new QueryClass(Exon.class);\n q.addFrom(qce);\n q.addToSelect(qce);\n ContainsConstraint cc1 = new ContainsConstraint(ref1, ConstraintOp.CONTAINS, qce);\n cs.addConstraint(cc1);\n\n QueryClass qcl = new QueryClass(Location.class);\n q.addFrom(qcl);\n q.addToSelect(qcl);\n QueryObjectReference ref2 = new QueryObjectReference(qcl, \"subject\");\n ContainsConstraint cc2 = new ContainsConstraint(ref2, ConstraintOp.CONTAINS, qce);\n cs.addConstraint(cc2);\n\n q.setConstraint(cs);\n\n Results res = new Results(q, os, os.getSequence());\n Iterator iter = res.iterator();\n while (iter.hasNext()) {\n ResultsRow rr = (ResultsRow) iter.next();\n Integer id = (Integer) rr.get(0);\n Location loc = (Location) rr.get(2);\n locationSet.add(loc);\n }\n return locationSet;\n }\n}\n"},"message":{"kind":"string","value":"added a log message to IntronUtil\n\n\n\nFormer-commit-id: 50bf683c0be7fad9d227ef44eeb7288e0c25239a"},"old_file":{"kind":"string","value":"bio/postprocess/main/src/org/intermine/bio/postprocess/IntronUtil.java"},"subject":{"kind":"string","value":"added a log message to IntronUtil"},"git_diff":{"kind":"string","value":"io/postprocess/main/src/org/intermine/bio/postprocess/IntronUtil.java\n Set locationSet = new HashSet();\n Transcript lastTran = null;\n Location lastTranLoc = null;\n int tranCount = 0, exonCount = 0;\n int tranCount = 0, exonCount = 0, intronCount = 0;\n while (resultsIter.hasNext()) {\n ResultsRow rr = (ResultsRow) resultsIter.next();\n Transcript thisTran = (Transcript) rr.get(0);\n \n if (!thisTran.getId().equals(lastTran.getId())) {\n tranCount++;\n Set intronSet = createIntronFeatures(locationSet, lastTran, lastTranLoc);\n intronCount += createIntronFeatures(locationSet, lastTran, lastTranLoc);\n exonCount += locationSet.size();\n if ((tranCount % 100) == 0) {\n LOG.info(\"Created \" + intronCount + \" Introns for \" + tranCount\n + \" Transcripts with \" + exonCount + \" Exons.\");\n }\n locationSet = new HashSet();\n lastTran = thisTran;\n lastTranLoc = (Location) rr.get(1);\n }\n \n if (lastTran != null) {\n Set intronSet = createIntronFeatures(locationSet, lastTran, lastTranLoc);\n intronCount += createIntronFeatures(locationSet, lastTran, lastTranLoc);\n tranCount++;\n exonCount += locationSet.size();\n }\n osw.store(dataSet);\n }\n osw.commitTransaction();\n //osw.abortTransaction();\n }\n \n \n * @return a set of Intron objects\n * @throws ObjectStoreException if there is an ObjectStore problem\n */\n protected Set createIntronFeatures(Set locationSet, Transcript transcript, Location tranLoc)\n protected int createIntronFeatures(Set locationSet, Transcript transcript, Location tranLoc)\n throws ObjectStoreException {\n //final BitSet bs = new BitSet(transcript.getLength().intValue() + 1);\n final BitSet bs = new BitSet(transcript.getLength().intValue());\n \n if (locationSet.size() == 1) {\n return null;\n return 0;\n }\n Chromosome chr = transcript.getChromosome();\n \n intronMap.put(identifier, intron);\n }\n }\n\n Set intronSet = new HashSet();\n for (Iterator i = intronMap.keySet().iterator(); i.hasNext(); ) {\n intronSet.add(intronMap.get(i.next()));\n }\n return intronSet;\n }\n\n /**\n * @param os objectStore\n * @param transcriptId Integer\n * @return all the exons locationSet for the particular transcriptId\n */\n private Set getLocationSet(ObjectStore os, Integer transcriptId) {\n Set locationSet = new HashSet();\n\n ConstraintSet cs = new ConstraintSet(ConstraintOp.AND);\n\n Query q = new Query();\n QueryClass qct = new QueryClass(Transcript.class);\n QueryField qf = new QueryField(qct, \"id\");\n SimpleConstraint sc1 = new SimpleConstraint(qf, ConstraintOp.EQUALS,\n new QueryValue(transcriptId));\n\n q.addFrom(qct);\n q.addToSelect(qf);\n q.addToOrderBy(qf);\n cs.addConstraint(sc1);\n\n QueryCollectionReference ref1 = new QueryCollectionReference(qct, \"exons\");\n QueryClass qce = new QueryClass(Exon.class);\n q.addFrom(qce);\n q.addToSelect(qce);\n ContainsConstraint cc1 = new ContainsConstraint(ref1, ConstraintOp.CONTAINS, qce);\n cs.addConstraint(cc1);\n\n QueryClass qcl = new QueryClass(Location.class);\n q.addFrom(qcl);\n q.addToSelect(qcl);\n QueryObjectReference ref2 = new QueryObjectReference(qcl, \"subject\");\n ContainsConstraint cc2 = new ContainsConstraint(ref2, ConstraintOp.CONTAINS, qce);\n cs.addConstraint(cc2);\n\n q.setConstraint(cs);\n\n Results res = new Results(q, os, os.getSequence());\n Iterator iter = res.iterator();\n while (iter.hasNext()) {\n ResultsRow rr = (ResultsRow) iter.next();\n Integer id = (Integer) rr.get(0);\n Location loc = (Location) rr.get(2);\n locationSet.add(loc);\n }\n return locationSet;\n return intronCount;\n }\n }"}}},{"rowIdx":1965,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"2edabfa647da3d8a7cbaa4017a0e6786dcb45af9"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"brahalla/PhotoAlbum-api"},"new_contents":{"kind":"string","value":"package com.brahalla.PhotoAlbum.controller.rest;\n\nimport com.brahalla.PhotoAlbum.domain.entity.Account;\nimport com.brahalla.PhotoAlbum.model.json.AccountInfo;\nimport com.brahalla.PhotoAlbum.model.json.response.LoginResponse;\nimport com.brahalla.PhotoAlbum.service.AccountService;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.security.authentication.AuthenticationManager;\nimport org.springframework.security.authentication.UsernamePasswordAuthenticationToken;\nimport org.springframework.security.core.Authentication;\nimport org.springframework.security.core.AuthenticationException;\nimport org.springframework.security.core.context.SecurityContextHolder;\nimport org.springframework.security.crypto.codec.Base64;\nimport org.springframework.web.bind.annotation.RequestBody;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\nimport org.springframework.web.bind.annotation.RestController;\n\n@RestController\n@RequestMapping(\"authenticate\")\npublic class AuthenticateController {\n\n\t@Autowired\n\tAccountService accountService;\n\n\t@Autowired\n\tAuthenticationManager authenticationManager;\n\n\t/* Attempt to authenticate with API\n\t * REQUEST: POST /api/authenticate\n\t */\n @RequestMapping(method = RequestMethod.POST)\n public LoginResponse authenticationRequest(@RequestBody AccountInfo accountInfo) throws AuthenticationException {\n\t\tAuthentication authentication = this.authenticationManager.authenticate(\n\t\t\tnew UsernamePasswordAuthenticationToken(\n\t\t\t\taccountInfo.getUsername(),\n\t\t\t\taccountInfo.getPassword()\n\t\t\t));\n\t\tif (authentication.isAuthenticated()) {\n\t\t\tSecurityContextHolder.getContext().setAuthentication(authentication);\n\t\t\tString credentials = accountInfo.getUsername() + \":\" + accountInfo.getPassword();\n\t\t\tbyte[] token = Base64.encode(credentials.getBytes());\n\t return new LoginResponse(new String(token));\n\t\t} else {\n\t\t\treturn new LoginResponse();\n\t\t}\n }\n\n}\n"},"new_file":{"kind":"string","value":"src/main/java/com/brahalla/PhotoAlbum/controller/rest/AuthenticateController.java"},"old_contents":{"kind":"string","value":"package com.brahalla.PhotoAlbum.controller.rest;\n\nimport com.brahalla.PhotoAlbum.domain.entity.Account;\nimport com.brahalla.PhotoAlbum.model.json.AccountInfo;\nimport com.brahalla.PhotoAlbum.model.json.response.LoginResponse;\nimport com.brahalla.PhotoAlbum.service.AccountService;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.security.core.userdetails.UserDetails;\nimport org.springframework.security.core.userdetails.UserDetailsService;\nimport org.springframework.security.crypto.codec.Base64;\nimport org.springframework.web.bind.annotation.RequestBody;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\nimport org.springframework.web.bind.annotation.RestController;\n\n@RestController\n@RequestMapping(\"authenticate\")\npublic class AuthenticateController {\n\n\t@Autowired\n\tAccountService accountService;\n\n\t@Autowired\n\tUserDetailsService userDetailsService;\n\n\t/* Attempt to authenticate with API\n\t * REQUEST: POST /api/authenticate\n\t */\n @RequestMapping(method = RequestMethod.POST)\n public LoginResponse authenticationRequest(@RequestBody AccountInfo accountInfo) {\n\t\tUserDetails userDetails = this.userDetailsService.loadUserByUsername(accountInfo.getUsername());\n\t\tif (userDetails.getPassword() == accountInfo.getPassword()) {\n\t\t\tString credentials = accountInfo.getUsername() + \":\" + accountInfo.getPassword();\n\t\t\tbyte[] token = Base64.encode(credentials.getBytes());\n\t return new LoginResponse(new String(token));\n\t\t} else {\n\t\t\treturn new LoginResponse();\n\t\t}\n }\n\n}\n"},"message":{"kind":"string","value":"testing authentication manager\n"},"old_file":{"kind":"string","value":"src/main/java/com/brahalla/PhotoAlbum/controller/rest/AuthenticateController.java"},"subject":{"kind":"string","value":"testing authentication manager"},"git_diff":{"kind":"string","value":"rc/main/java/com/brahalla/PhotoAlbum/controller/rest/AuthenticateController.java\n import com.brahalla.PhotoAlbum.service.AccountService;\n \n import org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.security.core.userdetails.UserDetails;\nimport org.springframework.security.core.userdetails.UserDetailsService;\nimport org.springframework.security.authentication.AuthenticationManager;\nimport org.springframework.security.authentication.UsernamePasswordAuthenticationToken;\nimport org.springframework.security.core.Authentication;\nimport org.springframework.security.core.AuthenticationException;\nimport org.springframework.security.core.context.SecurityContextHolder;\n import org.springframework.security.crypto.codec.Base64;\n import org.springframework.web.bind.annotation.RequestBody;\n import org.springframework.web.bind.annotation.RequestMapping;\n \tAccountService accountService;\n \n \t@Autowired\n\tUserDetailsService userDetailsService;\n\tAuthenticationManager authenticationManager;\n \n \t/* Attempt to authenticate with API\n \t * REQUEST: POST /api/authenticate\n \t */\n @RequestMapping(method = RequestMethod.POST)\n public LoginResponse authenticationRequest(@RequestBody AccountInfo accountInfo) {\n\t\tUserDetails userDetails = this.userDetailsService.loadUserByUsername(accountInfo.getUsername());\n\t\tif (userDetails.getPassword() == accountInfo.getPassword()) {\n public LoginResponse authenticationRequest(@RequestBody AccountInfo accountInfo) throws AuthenticationException {\n\t\tAuthentication authentication = this.authenticationManager.authenticate(\n\t\t\tnew UsernamePasswordAuthenticationToken(\n\t\t\t\taccountInfo.getUsername(),\n\t\t\t\taccountInfo.getPassword()\n\t\t\t));\n\t\tif (authentication.isAuthenticated()) {\n\t\t\tSecurityContextHolder.getContext().setAuthentication(authentication);\n \t\t\tString credentials = accountInfo.getUsername() + \":\" + accountInfo.getPassword();\n \t\t\tbyte[] token = Base64.encode(credentials.getBytes());\n \t return new LoginResponse(new String(token));"}}},{"rowIdx":1966,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"69b4b523dfc390c853857fcffef6b08213e24841"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"DevStreet/FinanceAnalytics,ChinaQuants/OG-Platform,nssales/OG-Platform,nssales/OG-Platform,DevStreet/FinanceAnalytics,jerome79/OG-Platform,ChinaQuants/OG-Platform,nssales/OG-Platform,McLeodMoores/starling,McLeodMoores/starling,DevStreet/FinanceAnalytics,jeorme/OG-Platform,ChinaQuants/OG-Platform,jeorme/OG-Platform,DevStreet/FinanceAnalytics,jeorme/OG-Platform,McLeodMoores/starling,jerome79/OG-Platform,codeaudit/OG-Platform,jerome79/OG-Platform,nssales/OG-Platform,jerome79/OG-Platform,codeaudit/OG-Platform,jeorme/OG-Platform,codeaudit/OG-Platform,ChinaQuants/OG-Platform,McLeodMoores/starling,codeaudit/OG-Platform"},"new_contents":{"kind":"string","value":"/**\n * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies\n *\n * Please see distribution for license.\n */\npackage com.opengamma.livedata.client;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.Map;\n\nimport org.fudgemsg.FudgeContext;\nimport org.fudgemsg.FudgeMsg;\nimport org.fudgemsg.FudgeMsgEnvelope;\nimport org.fudgemsg.mapping.FudgeDeserializer;\nimport org.fudgemsg.mapping.FudgeSerializer;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.opengamma.OpenGammaRuntimeException;\nimport com.opengamma.livedata.LiveDataListener;\nimport com.opengamma.livedata.LiveDataSpecification;\nimport com.opengamma.livedata.LiveDataValueUpdateBean;\nimport com.opengamma.livedata.LiveDataValueUpdateBeanFudgeBuilder;\nimport com.opengamma.livedata.UserPrincipal;\nimport com.opengamma.livedata.msg.LiveDataSubscriptionRequest;\nimport com.opengamma.livedata.msg.LiveDataSubscriptionResponse;\nimport com.opengamma.livedata.msg.LiveDataSubscriptionResponseMsg;\nimport com.opengamma.livedata.msg.LiveDataSubscriptionResult;\nimport com.opengamma.livedata.msg.SubscriptionType;\nimport com.opengamma.transport.FudgeMessageReceiver;\nimport com.opengamma.transport.FudgeRequestSender;\nimport com.opengamma.util.ArgumentChecker;\nimport com.opengamma.util.PublicAPI;\nimport com.opengamma.util.fudgemsg.OpenGammaFudgeContext;\n\n/**\n * A client that talks to a remote LiveData server through an unspecified protocol.\n * Possibilities are JMS, Fudge, direct socket connection, and so on. \n */\n@PublicAPI\npublic class DistributedLiveDataClient extends AbstractLiveDataClient implements FudgeMessageReceiver {\n private static final Logger s_logger = LoggerFactory.getLogger(DistributedLiveDataClient.class);\n // Injected Inputs:\n private final FudgeContext _fudgeContext;\n private final FudgeRequestSender _subscriptionRequestSender;\n \n private final DistributedEntitlementChecker _entitlementChecker;\n \n /**\n * An exception will be thrown when doing a snapshot if no reply is received from the server\n * within this time. Milliseconds.\n */\n private static final long TIMEOUT = 30000;\n \n public DistributedLiveDataClient(\n FudgeRequestSender subscriptionRequestSender,\n FudgeRequestSender entitlementRequestSender) {\n this(subscriptionRequestSender, entitlementRequestSender, OpenGammaFudgeContext.getInstance());\n }\n\n public DistributedLiveDataClient(\n FudgeRequestSender subscriptionRequestSender,\n FudgeRequestSender entitlementRequestSender,\n FudgeContext fudgeContext) {\n ArgumentChecker.notNull(subscriptionRequestSender, \"Subscription request sender\");\n ArgumentChecker.notNull(entitlementRequestSender, \"Entitlement request sender\");\n ArgumentChecker.notNull(fudgeContext, \"Fudge Context\");\n \n _subscriptionRequestSender = subscriptionRequestSender;\n _fudgeContext = fudgeContext;\n \n _entitlementChecker = new DistributedEntitlementChecker(entitlementRequestSender, fudgeContext);\n }\n\n /**\n * @return the subscriptionRequestSender\n */\n public FudgeRequestSender getSubscriptionRequestSender() {\n return _subscriptionRequestSender;\n }\n\n /**\n * @return the fudgeContext\n */\n @Override\n public FudgeContext getFudgeContext() {\n return _fudgeContext;\n }\n\n @Override\n protected void cancelPublication(LiveDataSpecification fullyQualifiedSpecification) {\n s_logger.info(\"Request made to cancel publication of {}\", fullyQualifiedSpecification);\n // TODO kirk 2009-10-28 -- This should handle an unsubscription request. For now,\n // however, we can just make do with allowing the heartbeat to time out.\n }\n\n @Override\n protected void handleSubscriptionRequest(Collection subHandles) {\n ArgumentChecker.notEmpty(subHandles, \"Subscription handle collection\");\n \n // Determine common user and subscription type\n UserPrincipal user = null;\n SubscriptionType type = null;\n \n ArrayList specs = new ArrayList();\n for (SubscriptionHandle subHandle : subHandles) {\n specs.add(new LiveDataSpecification(subHandle.getRequestedSpecification()));\n \n if (user == null) {\n user = subHandle.getUser();\n } else if (!user.equals(subHandle.getUser())) {\n throw new OpenGammaRuntimeException(\"Not all usernames are equal\"); \n }\n \n if (type == null) {\n type = subHandle.getSubscriptionType();\n } else if (!type.equals(subHandle.getSubscriptionType())) {\n throw new OpenGammaRuntimeException(\"Not all subscription types are equal\");\n }\n }\n \n // Build request message\n LiveDataSubscriptionRequest subReqMessage = new LiveDataSubscriptionRequest(user, type, specs);\n FudgeMsg requestMessage = subReqMessage.toFudgeMsg(new FudgeSerializer(getFudgeContext()));\n \n // Build response receiver\n FudgeMessageReceiver responseReceiver;\n if (type == SubscriptionType.SNAPSHOT) {\n responseReceiver = new SnapshotResponseReceiver(subHandles);\n } else {\n responseReceiver = new TopicBasedSubscriptionResponseReceiver(subHandles);\n }\n \n getSubscriptionRequestSender().sendRequest(requestMessage, responseReceiver);\n }\n \n /**\n * Common functionality for receiving subscription responses from the server. \n */\n private abstract class AbstractSubscriptionResponseReceiver implements FudgeMessageReceiver {\n \n private final Map _spec2SubHandle;\n \n private final Map _successResponses = new HashMap();\n private final Map _failedResponses = new HashMap();\n \n private UserPrincipal _user;\n \n public AbstractSubscriptionResponseReceiver(Collection subHandles) {\n _spec2SubHandle = new HashMap();\n for (SubscriptionHandle subHandle : subHandles) {\n _spec2SubHandle.put(subHandle.getRequestedSpecification(), subHandle); \n }\n }\n \n public UserPrincipal getUser() {\n return _user;\n }\n\n public void setUser(UserPrincipal user) {\n _user = user;\n }\n\n public Map getSpec2SubHandle() {\n return _spec2SubHandle;\n }\n\n public Map getSuccessResponses() {\n return _successResponses;\n }\n\n public Map getFailedResponses() {\n return _failedResponses;\n }\n\n @Override\n public void messageReceived(FudgeContext fudgeContext, FudgeMsgEnvelope envelope) {\n try {\n \n if ((envelope == null) || (envelope.getMessage() == null)) {\n throw new OpenGammaRuntimeException(\"Got a message that can't be deserialized from a Fudge message.\");\n }\n FudgeMsg msg = envelope.getMessage();\n \n LiveDataSubscriptionResponseMsg responseMessage = LiveDataSubscriptionResponseMsg.fromFudgeMsg(new FudgeDeserializer(getFudgeContext()), msg);\n if (responseMessage.getResponses().isEmpty()) {\n throw new OpenGammaRuntimeException(\"Got empty subscription response \" + responseMessage);\n }\n \n messageReceived(responseMessage);\n \n } catch (Exception e) {\n s_logger.error(\"Failed to process response message\", e);\n \n for (SubscriptionHandle handle : getSpec2SubHandle().values()) {\n if (handle.getSubscriptionType() != SubscriptionType.SNAPSHOT) {\n subscriptionRequestFailed(handle, new LiveDataSubscriptionResponse(\n handle.getRequestedSpecification(), \n LiveDataSubscriptionResult.INTERNAL_ERROR, \n e.toString(),\n null,\n null,\n null)); \n }\n }\n }\n }\n \n \n private void messageReceived(LiveDataSubscriptionResponseMsg responseMessage) {\n parseResponse(responseMessage);\n processResponse();\n sendResponse();\n }\n\n \n private void parseResponse(LiveDataSubscriptionResponseMsg responseMessage) {\n for (LiveDataSubscriptionResponse response : responseMessage.getResponses()) {\n \n SubscriptionHandle handle = getSpec2SubHandle().get(response.getRequestedSpecification());\n if (handle == null) {\n throw new OpenGammaRuntimeException(\"Could not find handle corresponding to request \" + response.getRequestedSpecification());\n }\n \n if (getUser() != null && !getUser().equals(handle.getUser())) {\n throw new OpenGammaRuntimeException(\"Not all usernames are equal\");\n }\n setUser(handle.getUser());\n \n if (response.getSubscriptionResult() == LiveDataSubscriptionResult.SUCCESS) {\n getSuccessResponses().put(handle, response);\n } else {\n getFailedResponses().put(handle, response);\n }\n }\n }\n\n \n protected void processResponse() {\n }\n\n \n protected void sendResponse() {\n \n Map responses = new HashMap(); \n responses.putAll(getSuccessResponses());\n responses.putAll(getFailedResponses());\n \n int total = responses.size();\n s_logger.info(\"{} subscription responses received\", total);\n Map> batch = new HashMap>();\n for (Map.Entry successEntry : responses.entrySet()) {\n SubscriptionHandle handle = successEntry.getKey();\n LiveDataSubscriptionResponse response = successEntry.getValue();\n Collection responseBatch = batch.get(handle.getListener());\n if (responseBatch == null) {\n responseBatch = new LinkedList();\n batch.put(handle.getListener(), responseBatch);\n }\n responseBatch.add(response);\n }\n for (Map.Entry> batchEntry : batch.entrySet()) {\n batchEntry.getKey().subscriptionResultsReceived(batchEntry.getValue());\n }\n\n }\n }\n \n /**\n * Some market data requests are snapshot requests; this means that they do not require a JMS subscription. \n */\n private class SnapshotResponseReceiver extends AbstractSubscriptionResponseReceiver {\n \n public SnapshotResponseReceiver(Collection subHandles) {\n super(subHandles);\n }\n \n }\n \n /**\n * Some market data requests are non-snapshot requests where market data is continuously read from a JMS topic;\n * this means they require a JMS subscription.\n *

    \n * As per LIV-19, after we've subscribed to the market data (and started getting deltas), we do a snapshot\n * to make sure we get a full initial image of the data. Things are done in this order (first subscribe, then snapshot)\n * so we don't lose any ticks. See LIV-19.\n */\n private class TopicBasedSubscriptionResponseReceiver extends AbstractSubscriptionResponseReceiver {\n \n public TopicBasedSubscriptionResponseReceiver(Collection subHandles) {\n super(subHandles);\n }\n \n @Override\n protected void processResponse() {\n try {\n // Phase 1. Create a subscription to market data topic\n startReceivingTicks();\n \n // Phase 2. After we've subscribed to the market data (and started getting deltas), snapshot it\n snapshot();\n\n } catch (RuntimeException e) {\n s_logger.error(\"Failed to process subscription response\", e);\n \n // This is unexpected. Fail everything.\n for (LiveDataSubscriptionResponse response : getSuccessResponses().values()) {\n response.setSubscriptionResult(LiveDataSubscriptionResult.INTERNAL_ERROR); \n response.setUserMessage(e.toString());\n }\n \n getFailedResponses().putAll(getSuccessResponses());\n getSuccessResponses().clear();\n }\n }\n \n private void startReceivingTicks() {\n Map resps = getSuccessResponses();\n // tick distribution specifications can be duplicated, only pass each down once to startReceivingTicks()\n Collection distributionSpecs = new HashSet<>(resps.size());\n for (Map.Entry entry : resps.entrySet()) {\n DistributedLiveDataClient.this.subscriptionStartingToReceiveTicks(entry.getKey(), entry.getValue());\n distributionSpecs.add(entry.getValue().getTickDistributionSpecification());\n }\n DistributedLiveDataClient.this.startReceivingTicks(distributionSpecs);\n }\n \n private void snapshot() {\n \n ArrayList successLiveDataSpecs = new ArrayList();\n for (LiveDataSubscriptionResponse response : getSuccessResponses().values()) {\n successLiveDataSpecs.add(response.getRequestedSpecification()); \n }\n \n Collection snapshots = DistributedLiveDataClient.this.snapshot(getUser(), successLiveDataSpecs, TIMEOUT);\n \n for (LiveDataSubscriptionResponse response : snapshots) {\n \n SubscriptionHandle handle = getSpec2SubHandle().get(response.getRequestedSpecification());\n if (handle == null) {\n throw new OpenGammaRuntimeException(\"Could not find handle corresponding to request \" + response.getRequestedSpecification());\n }\n \n // could be that even though subscription to the JMS topic (phase 1) succeeded, snapshot (phase 2) for some reason failed.\n // since phase 1 already validated everything, this should mainly happen when user permissions are modified \n // in the sub-second interval between phases 1 and 2!\n \n // Not so. In fact for a system like Bloomberg, because of the lag in subscription, the LiveDataServer\n // may in fact think that you can successfully subscribe, but then when the snapshot is requested we detect\n // that it's not a valid code. So this is the time that we've actually poked the underlying data provider\n // to check.\n \n // In addition, it may be that for a FireHose server we didn't have the full SoW on the initial request\n // but now we do.\n if (response.getSubscriptionResult() == LiveDataSubscriptionResult.SUCCESS) {\n \n handle.addSnapshotOnHold(response.getSnapshot());\n \n } else {\n getSuccessResponses().remove(handle);\n getFailedResponses().put(handle, response);\n }\n }\n }\n \n @Override\n protected void sendResponse() {\n super.sendResponse();\n \n for (Map.Entry successEntry : getSuccessResponses().entrySet()) {\n SubscriptionHandle handle = successEntry.getKey();\n LiveDataSubscriptionResponse response = successEntry.getValue();\n subscriptionRequestSatisfied(handle, response);\n }\n \n for (Map.Entry failedEntry : getFailedResponses().entrySet()) {\n SubscriptionHandle handle = failedEntry.getKey();\n LiveDataSubscriptionResponse response = failedEntry.getValue();\n subscriptionRequestFailed(handle, response);\n \n // this is here just to clean up. It's safe to call stopReceivingTicks()\n // even if no JMS subscription actually exists.\n stopReceivingTicks(response.getTickDistributionSpecification());\n }\n }\n \n }\n \n /**\n * @param tickDistributionSpecification JMS topic name\n */\n public void startReceivingTicks(Collection tickDistributionSpecification) {\n // Default no-op.\n }\n \n public void stopReceivingTicks(String tickDistributionSpecification) {\n // Default no-op.\n }\n\n // REVIEW kirk 2009-10-28 -- This is just a braindead way of getting ticks to come in\n // until we can get a handle on the construction of receivers based on responses.\n @Override\n public void messageReceived(FudgeContext fudgeContext,\n FudgeMsgEnvelope msgEnvelope) {\n FudgeMsg fudgeMsg = msgEnvelope.getMessage();\n LiveDataValueUpdateBean update = LiveDataValueUpdateBeanFudgeBuilder.fromFudgeMsg(new FudgeDeserializer(fudgeContext), fudgeMsg);\n valueUpdate(update);\n }\n\n @Override\n public Map isEntitled(UserPrincipal user,\n Collection requestedSpecifications) {\n return _entitlementChecker.isEntitled(user, requestedSpecifications);\n }\n\n @Override\n public boolean isEntitled(UserPrincipal user, LiveDataSpecification requestedSpecification) {\n return _entitlementChecker.isEntitled(user, requestedSpecification);\n }\n \n}\n"},"new_file":{"kind":"string","value":"projects/OG-LiveData/src/main/java/com/opengamma/livedata/client/DistributedLiveDataClient.java"},"old_contents":{"kind":"string","value":"/**\n * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies\n *\n * Please see distribution for license.\n */\npackage com.opengamma.livedata.client;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.Map;\n\nimport org.fudgemsg.FudgeContext;\nimport org.fudgemsg.FudgeMsg;\nimport org.fudgemsg.FudgeMsgEnvelope;\nimport org.fudgemsg.mapping.FudgeDeserializer;\nimport org.fudgemsg.mapping.FudgeSerializer;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.opengamma.OpenGammaRuntimeException;\nimport com.opengamma.livedata.LiveDataListener;\nimport com.opengamma.livedata.LiveDataSpecification;\nimport com.opengamma.livedata.LiveDataValueUpdateBean;\nimport com.opengamma.livedata.LiveDataValueUpdateBeanFudgeBuilder;\nimport com.opengamma.livedata.UserPrincipal;\nimport com.opengamma.livedata.msg.LiveDataSubscriptionRequest;\nimport com.opengamma.livedata.msg.LiveDataSubscriptionResponse;\nimport com.opengamma.livedata.msg.LiveDataSubscriptionResponseMsg;\nimport com.opengamma.livedata.msg.LiveDataSubscriptionResult;\nimport com.opengamma.livedata.msg.SubscriptionType;\nimport com.opengamma.transport.FudgeMessageReceiver;\nimport com.opengamma.transport.FudgeRequestSender;\nimport com.opengamma.util.ArgumentChecker;\nimport com.opengamma.util.PublicAPI;\nimport com.opengamma.util.fudgemsg.OpenGammaFudgeContext;\n\n/**\n * A client that talks to a remote LiveData server through an unspecified protocol.\n * Possibilities are JMS, Fudge, direct socket connection, and so on. \n */\n@PublicAPI\npublic class DistributedLiveDataClient extends AbstractLiveDataClient implements FudgeMessageReceiver {\n private static final Logger s_logger = LoggerFactory.getLogger(DistributedLiveDataClient.class);\n // Injected Inputs:\n private final FudgeContext _fudgeContext;\n private final FudgeRequestSender _subscriptionRequestSender;\n \n private final DistributedEntitlementChecker _entitlementChecker;\n \n /**\n * An exception will be thrown when doing a snapshot if no reply is received from the server\n * within this time. Milliseconds.\n */\n private static final long TIMEOUT = 30000;\n \n public DistributedLiveDataClient(\n FudgeRequestSender subscriptionRequestSender,\n FudgeRequestSender entitlementRequestSender) {\n this(subscriptionRequestSender, entitlementRequestSender, OpenGammaFudgeContext.getInstance());\n }\n\n public DistributedLiveDataClient(\n FudgeRequestSender subscriptionRequestSender,\n FudgeRequestSender entitlementRequestSender,\n FudgeContext fudgeContext) {\n ArgumentChecker.notNull(subscriptionRequestSender, \"Subscription request sender\");\n ArgumentChecker.notNull(entitlementRequestSender, \"Entitlement request sender\");\n ArgumentChecker.notNull(fudgeContext, \"Fudge Context\");\n \n _subscriptionRequestSender = subscriptionRequestSender;\n _fudgeContext = fudgeContext;\n \n _entitlementChecker = new DistributedEntitlementChecker(entitlementRequestSender, fudgeContext);\n }\n\n /**\n * @return the subscriptionRequestSender\n */\n public FudgeRequestSender getSubscriptionRequestSender() {\n return _subscriptionRequestSender;\n }\n\n /**\n * @return the fudgeContext\n */\n @Override\n public FudgeContext getFudgeContext() {\n return _fudgeContext;\n }\n\n @Override\n protected void cancelPublication(LiveDataSpecification fullyQualifiedSpecification) {\n s_logger.info(\"Request made to cancel publication of {}\", fullyQualifiedSpecification);\n // TODO kirk 2009-10-28 -- This should handle an unsubscription request. For now,\n // however, we can just make do with allowing the heartbeat to time out.\n }\n\n @Override\n protected void handleSubscriptionRequest(Collection subHandles) {\n ArgumentChecker.notEmpty(subHandles, \"Subscription handle collection\");\n \n // Determine common user and subscription type\n UserPrincipal user = null;\n SubscriptionType type = null;\n \n ArrayList specs = new ArrayList();\n for (SubscriptionHandle subHandle : subHandles) {\n specs.add(new LiveDataSpecification(subHandle.getRequestedSpecification()));\n \n if (user == null) {\n user = subHandle.getUser();\n } else if (!user.equals(subHandle.getUser())) {\n throw new OpenGammaRuntimeException(\"Not all usernames are equal\"); \n }\n \n if (type == null) {\n type = subHandle.getSubscriptionType();\n } else if (!type.equals(subHandle.getSubscriptionType())) {\n throw new OpenGammaRuntimeException(\"Not all subscription types are equal\");\n }\n }\n \n // Build request message\n LiveDataSubscriptionRequest subReqMessage = new LiveDataSubscriptionRequest(user, type, specs);\n FudgeMsg requestMessage = subReqMessage.toFudgeMsg(new FudgeSerializer(getFudgeContext()));\n \n // Build response receiver\n FudgeMessageReceiver responseReceiver;\n if (type == SubscriptionType.SNAPSHOT) {\n responseReceiver = new SnapshotResponseReceiver(subHandles);\n } else {\n responseReceiver = new TopicBasedSubscriptionResponseReceiver(subHandles);\n }\n \n getSubscriptionRequestSender().sendRequest(requestMessage, responseReceiver);\n }\n \n /**\n * Common functionality for receiving subscription responses from the server. \n */\n private abstract class AbstractSubscriptionResponseReceiver implements FudgeMessageReceiver {\n \n private final Map _spec2SubHandle;\n \n private final Map _successResponses = new HashMap();\n private final Map _failedResponses = new HashMap();\n \n private UserPrincipal _user;\n \n public AbstractSubscriptionResponseReceiver(Collection subHandles) {\n _spec2SubHandle = new HashMap();\n for (SubscriptionHandle subHandle : subHandles) {\n _spec2SubHandle.put(subHandle.getRequestedSpecification(), subHandle); \n }\n }\n \n public UserPrincipal getUser() {\n return _user;\n }\n\n public void setUser(UserPrincipal user) {\n _user = user;\n }\n\n public Map getSpec2SubHandle() {\n return _spec2SubHandle;\n }\n\n public Map getSuccessResponses() {\n return _successResponses;\n }\n\n public Map getFailedResponses() {\n return _failedResponses;\n }\n\n @Override\n public void messageReceived(FudgeContext fudgeContext, FudgeMsgEnvelope envelope) {\n try {\n \n if ((envelope == null) || (envelope.getMessage() == null)) {\n throw new OpenGammaRuntimeException(\"Got a message that can't be deserialized from a Fudge message.\");\n }\n FudgeMsg msg = envelope.getMessage();\n \n LiveDataSubscriptionResponseMsg responseMessage = LiveDataSubscriptionResponseMsg.fromFudgeMsg(new FudgeDeserializer(getFudgeContext()), msg);\n if (responseMessage.getResponses().isEmpty()) {\n throw new OpenGammaRuntimeException(\"Got empty subscription response \" + responseMessage);\n }\n \n messageReceived(responseMessage);\n \n } catch (Exception e) {\n s_logger.error(\"Failed to process response message\", e);\n \n for (SubscriptionHandle handle : getSpec2SubHandle().values()) {\n if (handle.getSubscriptionType() != SubscriptionType.SNAPSHOT) {\n subscriptionRequestFailed(handle, new LiveDataSubscriptionResponse(\n handle.getRequestedSpecification(), \n LiveDataSubscriptionResult.INTERNAL_ERROR, \n e.toString(),\n null,\n null,\n null)); \n }\n }\n }\n }\n \n \n private void messageReceived(LiveDataSubscriptionResponseMsg responseMessage) {\n parseResponse(responseMessage);\n processResponse();\n sendResponse();\n }\n\n \n private void parseResponse(LiveDataSubscriptionResponseMsg responseMessage) {\n for (LiveDataSubscriptionResponse response : responseMessage.getResponses()) {\n \n SubscriptionHandle handle = getSpec2SubHandle().get(response.getRequestedSpecification());\n if (handle == null) {\n throw new OpenGammaRuntimeException(\"Could not find handle corresponding to request \" + response.getRequestedSpecification());\n }\n \n if (getUser() != null && !getUser().equals(handle.getUser())) {\n throw new OpenGammaRuntimeException(\"Not all usernames are equal\");\n }\n setUser(handle.getUser());\n \n if (response.getSubscriptionResult() == LiveDataSubscriptionResult.SUCCESS) {\n getSuccessResponses().put(handle, response);\n } else {\n getFailedResponses().put(handle, response);\n }\n }\n }\n\n \n protected void processResponse() {\n }\n\n \n protected void sendResponse() {\n \n Map responses = new HashMap(); \n responses.putAll(getSuccessResponses());\n responses.putAll(getFailedResponses());\n \n int total = responses.size();\n s_logger.error(\"{} subscription responses received\", total); // info\n Map> batch = new HashMap>();\n for (Map.Entry successEntry : responses.entrySet()) {\n SubscriptionHandle handle = successEntry.getKey();\n LiveDataSubscriptionResponse response = successEntry.getValue();\n Collection responseBatch = batch.get(handle.getListener());\n if (responseBatch == null) {\n responseBatch = new LinkedList();\n batch.put(handle.getListener(), responseBatch);\n }\n responseBatch.add(response);\n }\n for (Map.Entry> batchEntry : batch.entrySet()) {\n batchEntry.getKey().subscriptionResultsReceived(batchEntry.getValue());\n }\n\n }\n }\n \n /**\n * Some market data requests are snapshot requests; this means that they do not require a JMS subscription. \n */\n private class SnapshotResponseReceiver extends AbstractSubscriptionResponseReceiver {\n \n public SnapshotResponseReceiver(Collection subHandles) {\n super(subHandles);\n }\n \n }\n \n /**\n * Some market data requests are non-snapshot requests where market data is continuously read from a JMS topic;\n * this means they require a JMS subscription.\n *

    \n * As per LIV-19, after we've subscribed to the market data (and started getting deltas), we do a snapshot\n * to make sure we get a full initial image of the data. Things are done in this order (first subscribe, then snapshot)\n * so we don't lose any ticks. See LIV-19.\n */\n private class TopicBasedSubscriptionResponseReceiver extends AbstractSubscriptionResponseReceiver {\n \n public TopicBasedSubscriptionResponseReceiver(Collection subHandles) {\n super(subHandles);\n }\n \n @Override\n protected void processResponse() {\n try {\n // Phase 1. Create a subscription to market data topic\n startReceivingTicks();\n \n // Phase 2. After we've subscribed to the market data (and started getting deltas), snapshot it\n snapshot();\n\n } catch (RuntimeException e) {\n s_logger.error(\"Failed to process subscription response\", e);\n \n // This is unexpected. Fail everything.\n for (LiveDataSubscriptionResponse response : getSuccessResponses().values()) {\n response.setSubscriptionResult(LiveDataSubscriptionResult.INTERNAL_ERROR); \n response.setUserMessage(e.toString());\n }\n \n getFailedResponses().putAll(getSuccessResponses());\n getSuccessResponses().clear();\n }\n }\n \n private void startReceivingTicks() {\n Map resps = getSuccessResponses();\n // tick distribution specifications can be duplicated, only pass each down once to startReceivingTicks()\n Collection distributionSpecs = new HashSet<>(resps.size());\n for (Map.Entry entry : resps.entrySet()) {\n DistributedLiveDataClient.this.subscriptionStartingToReceiveTicks(entry.getKey(), entry.getValue());\n distributionSpecs.add(entry.getValue().getTickDistributionSpecification());\n }\n DistributedLiveDataClient.this.startReceivingTicks(distributionSpecs);\n }\n \n private void snapshot() {\n \n ArrayList successLiveDataSpecs = new ArrayList();\n for (LiveDataSubscriptionResponse response : getSuccessResponses().values()) {\n successLiveDataSpecs.add(response.getRequestedSpecification()); \n }\n \n Collection snapshots = DistributedLiveDataClient.this.snapshot(getUser(), successLiveDataSpecs, TIMEOUT);\n \n for (LiveDataSubscriptionResponse response : snapshots) {\n \n SubscriptionHandle handle = getSpec2SubHandle().get(response.getRequestedSpecification());\n if (handle == null) {\n throw new OpenGammaRuntimeException(\"Could not find handle corresponding to request \" + response.getRequestedSpecification());\n }\n \n // could be that even though subscription to the JMS topic (phase 1) succeeded, snapshot (phase 2) for some reason failed.\n // since phase 1 already validated everything, this should mainly happen when user permissions are modified \n // in the sub-second interval between phases 1 and 2!\n \n // Not so. In fact for a system like Bloomberg, because of the lag in subscription, the LiveDataServer\n // may in fact think that you can successfully subscribe, but then when the snapshot is requested we detect\n // that it's not a valid code. So this is the time that we've actually poked the underlying data provider\n // to check.\n \n // In addition, it may be that for a FireHose server we didn't have the full SoW on the initial request\n // but now we do.\n if (response.getSubscriptionResult() == LiveDataSubscriptionResult.SUCCESS) {\n \n handle.addSnapshotOnHold(response.getSnapshot());\n \n } else {\n getSuccessResponses().remove(handle);\n getFailedResponses().put(handle, response);\n }\n }\n }\n \n @Override\n protected void sendResponse() {\n super.sendResponse();\n \n for (Map.Entry successEntry : getSuccessResponses().entrySet()) {\n SubscriptionHandle handle = successEntry.getKey();\n LiveDataSubscriptionResponse response = successEntry.getValue();\n subscriptionRequestSatisfied(handle, response);\n }\n \n for (Map.Entry failedEntry : getFailedResponses().entrySet()) {\n SubscriptionHandle handle = failedEntry.getKey();\n LiveDataSubscriptionResponse response = failedEntry.getValue();\n subscriptionRequestFailed(handle, response);\n \n // this is here just to clean up. It's safe to call stopReceivingTicks()\n // even if no JMS subscription actually exists.\n stopReceivingTicks(response.getTickDistributionSpecification());\n }\n }\n \n }\n \n /**\n * @param tickDistributionSpecification JMS topic name\n */\n public void startReceivingTicks(Collection tickDistributionSpecification) {\n // Default no-op.\n }\n \n public void stopReceivingTicks(String tickDistributionSpecification) {\n // Default no-op.\n }\n\n // REVIEW kirk 2009-10-28 -- This is just a braindead way of getting ticks to come in\n // until we can get a handle on the construction of receivers based on responses.\n @Override\n public void messageReceived(FudgeContext fudgeContext,\n FudgeMsgEnvelope msgEnvelope) {\n FudgeMsg fudgeMsg = msgEnvelope.getMessage();\n LiveDataValueUpdateBean update = LiveDataValueUpdateBeanFudgeBuilder.fromFudgeMsg(new FudgeDeserializer(fudgeContext), fudgeMsg);\n valueUpdate(update);\n }\n\n @Override\n public Map isEntitled(UserPrincipal user,\n Collection requestedSpecifications) {\n return _entitlementChecker.isEntitled(user, requestedSpecifications);\n }\n\n @Override\n public boolean isEntitled(UserPrincipal user, LiveDataSpecification requestedSpecification) {\n return _entitlementChecker.isEntitled(user, requestedSpecification);\n }\n \n}\n"},"message":{"kind":"string","value":"[PLAT-3926] Decreasing logging level back to info\n"},"old_file":{"kind":"string","value":"projects/OG-LiveData/src/main/java/com/opengamma/livedata/client/DistributedLiveDataClient.java"},"subject":{"kind":"string","value":"[PLAT-3926] Decreasing logging level back to info"},"git_diff":{"kind":"string","value":"rojects/OG-LiveData/src/main/java/com/opengamma/livedata/client/DistributedLiveDataClient.java\n responses.putAll(getFailedResponses());\n \n int total = responses.size();\n s_logger.error(\"{} subscription responses received\", total); // info\n s_logger.info(\"{} subscription responses received\", total);\n Map> batch = new HashMap>();\n for (Map.Entry successEntry : responses.entrySet()) {\n SubscriptionHandle handle = successEntry.getKey();"}}},{"rowIdx":1967,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"f4a0900ba9fecfa81b2fb15eb1b562b0beff6371"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"Zariel/parquet-mr,nevillelyh/parquet-mr,cchang738/parquet-mr,laurentgo/parquet-mr,spena/parquet-mr,rdblue/parquet-mr,tsdeng/incubator-parquet-mr,nkhuyu/parquet-mr,winningsix/incubator-parquet-mr,jaltekruse/parquet-mr-1,hassyma/parquet-mr,cchang738/parquet-mr,piyushnarang/parquet-mr,MickDavies/incubator-parquet-mr,davidgin/parquet-mr,dlanza1/parquet-mr,SinghAsDev/parquet-mr,cchang738/parquet-mr,coughman/incubator-parquet-mr,nkhuyu/parquet-mr,dlanza1/parquet-mr,winningsix/incubator-parquet-mr,MickDavies/incubator-parquet-mr,DataDog/parquet-mr,winningsix/incubator-parquet-mr,sworisbreathing/parquet-mr,HyukjinKwon/parquet-mr-1,forcedotcom/incubator-parquet-mr,pronix/parquet-mr,spena/parquet-mr,nitin2goyal/parquet-mr-1,MickDavies/incubator-parquet-mr,SaintBacchus/parquet-mr,apache/parquet-mr,nitin2goyal/parquet-mr,saucam/incubator-parquet-mr,hassyma/parquet-mr,SinghAsDev/parquet-mr,nezihyigitbasi-nflx/parquet-mr,zhenxiao/parquet-mr,tsdeng/incubator-parquet-mr,nitin2goyal/parquet-mr,coughman/incubator-parquet-mr,hassyma/parquet-mr,HyukjinKwon/parquet-mr-1,jaltekruse/parquet-mr-1,laurentgo/parquet-mr,nevillelyh/parquet-mr,apache/parquet-mr,spena/parquet-mr,DataDog/parquet-mr,HyukjinKwon/parquet-mr,nitin2goyal/parquet-mr-1,forcedotcom/incubator-parquet-mr,danielcweeks/incubator-parquet-mr,davidgin/parquet-mr,sircodesalotOfTheRound/parquet-mr,zhenxiao/parquet-mr,pronix/parquet-mr,dlanza1/parquet-mr,nezihyigitbasi-nflx/parquet-mr,laurentgo/parquet-mr,nitin2goyal/parquet-mr-1,Zariel/parquet-mr,rdblue/parquet-mr,dongche/incubator-parquet-mr,DataDog/parquet-mr,SaintBacchus/parquet-mr,danielcweeks/incubator-parquet-mr,pronix/parquet-mr,HyukjinKwon/parquet-mr,apache/parquet-mr,rdblue/parquet-mr,jaltekruse/parquet-mr-1,piyushnarang/parquet-mr,nevillelyh/parquet-mr,dongche/incubator-parquet-mr,HyukjinKwon/parquet-mr-1,davidgin/parquet-mr,SaintBacchus/parquet-mr,danielcweeks/incubator-parquet-mr,nguyenvanthan/parquet-mr,sircodesalotOfTheRound/parquet-mr,sworisbreathing/parquet-mr,tsdeng/incubator-parquet-mr,saucam/incubator-parquet-mr,HyukjinKwon/parquet-mr,sircodesalotOfTheRound/parquet-mr,nezihyigitbasi-nflx/parquet-mr,dongche/incubator-parquet-mr,nitin2goyal/parquet-mr,Zariel/parquet-mr,sworisbreathing/parquet-mr,nguyenvanthan/parquet-mr,nkhuyu/parquet-mr,piyushnarang/parquet-mr,saucam/incubator-parquet-mr,nguyenvanthan/parquet-mr,coughman/incubator-parquet-mr,SinghAsDev/parquet-mr,forcedotcom/incubator-parquet-mr,zhenxiao/parquet-mr"},"new_contents":{"kind":"string","value":"/**\n * Copyright 2012 Twitter, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage parquet.hadoop.thrift;\n\nimport java.lang.reflect.Constructor;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.apache.hadoop.conf.Configuration;\nimport org.apache.hadoop.mapred.JobConf;\nimport org.apache.thrift.TBase;\nimport org.apache.thrift.protocol.TProtocol;\n\nimport parquet.Log;\nimport parquet.hadoop.api.InitContext;\nimport parquet.hadoop.api.ReadSupport;\nimport parquet.io.ParquetDecodingException;\nimport parquet.io.api.RecordMaterializer;\nimport parquet.schema.MessageType;\nimport parquet.thrift.TBaseRecordConverter;\nimport parquet.thrift.ThriftMetaData;\nimport parquet.thrift.ThriftRecordConverter;\nimport parquet.thrift.ThriftSchemaConverter;\nimport parquet.thrift.projection.FieldProjectionFilter;\nimport parquet.thrift.projection.ThriftProjectionException;\nimport parquet.thrift.struct.ThriftType.StructType;\n\npublic class ThriftReadSupport extends ReadSupport {\n private static final Log LOG = Log.getLog(ThriftReadSupport.class);\n\n /**\n * configuration key for thrift read projection schema\n */\n public static final String THRIFT_COLUMN_FILTER_KEY = \"parquet.thrift.column.filter\";\n private static final String RECORD_CONVERTER_DEFAULT = TBaseRecordConverter.class.getName();\n public static final String THRIFT_READ_CLASS_KEY = \"parquet.thrift.read.class\";\n\n\n /**\n * A {@link ThriftRecordConverter} builds an object by working with {@link TProtocol}. The default\n * implementation creates standard Apache Thrift {@link TBase} objects; to support alternatives, such\n * as Twiter's Scrooge, a custom converter can be specified using this key\n * (for example, ScroogeRecordConverter from parquet-scrooge).\n */\n private static final String RECORD_CONVERTER_CLASS_KEY = \"parquet.thrift.converter.class\";\n\n protected Class thriftClass;\n\n /**\n * A {@link ThriftRecordConverter} builds an object by working with {@link TProtocol}. The default\n * implementation creates standard Apache Thrift {@link TBase} objects; to support alternatives, such\n * as Twiter's Scrooge, a custom converter can be specified\n * (for example, ScroogeRecordConverter from parquet-scrooge).\n */\n public static void setRecordConverterClass(JobConf conf,\n Class klass) {\n conf.set(RECORD_CONVERTER_CLASS_KEY, klass.getName());\n }\n\n /**\n * used from hadoop\n * the configuration must contain a \"parquet.thrift.read.class\" setting\n */\n public ThriftReadSupport() {\n }\n\n /**\n * @param thriftClass the thrift class used to deserialize the records\n */\n public ThriftReadSupport(Class thriftClass) {\n this.thriftClass = thriftClass;\n }\n\n\n\n @Override\n public parquet.hadoop.api.ReadSupport.ReadContext init(InitContext context) {\n final Configuration configuration = context.getConfiguration();\n final MessageType fileMessageType = context.getFileSchema();\n MessageType requestedProjection = fileMessageType;\n String partialSchemaString = configuration.get(ReadSupport.PARQUET_READ_SCHEMA);\n String projectionFilterString = configuration.get(THRIFT_COLUMN_FILTER_KEY);\n\n if (partialSchemaString != null && projectionFilterString != null)\n throw new ThriftProjectionException(\"PARQUET_READ_SCHEMA and THRIFT_COLUMN_FILTER_KEY are both specified, should use only one.\");\n\n //set requestedProjections only when it's specified\n if (partialSchemaString != null) {\n requestedProjection = getSchemaForRead(fileMessageType, partialSchemaString);\n } else if (projectionFilterString != null && !projectionFilterString.isEmpty()) {\n FieldProjectionFilter fieldProjectionFilter = new FieldProjectionFilter(projectionFilterString);\n try {\n initThriftClassFromMultipleFiles(context.getKeyValueMetadata(), configuration);\n requestedProjection = getProjectedSchema(fieldProjectionFilter);\n } catch (ClassNotFoundException e) {\n throw new ThriftProjectionException(\"can not find thriftClass from configuration\");\n }\n }\n\n MessageType schemaForRead = getSchemaForRead(fileMessageType, requestedProjection);\n return new ReadContext(schemaForRead);\n }\n\n protected MessageType getProjectedSchema(FieldProjectionFilter fieldProjectionFilter) {\n return new ThriftSchemaConverter(fieldProjectionFilter).convert((Class>)thriftClass);\n }\n\n @SuppressWarnings(\"unchecked\")\n private void initThriftClassFromMultipleFiles(Map> fileMetadata, Configuration conf) throws ClassNotFoundException {\n if (thriftClass != null) {\n return;\n }\n String className = conf.get(THRIFT_READ_CLASS_KEY, null);\n if (className == null) {\n Set names = ThriftMetaData.getThriftClassNames(fileMetadata);\n if (names == null || names.size() != 1) {\n throw new ParquetDecodingException(\"Could not read file as the Thrift class is not provided and could not be resolved from the file: \" + names);\n }\n className = names.iterator().next();\n }\n thriftClass = (Class)Class.forName(className);\n }\n\n @SuppressWarnings(\"unchecked\")\n private void initThriftClass(Map fileMetadata, Configuration conf) throws ClassNotFoundException {\n if (thriftClass != null) {\n return;\n }\n String className = conf.get(THRIFT_READ_CLASS_KEY, null);\n if (className == null) {\n final ThriftMetaData metaData = ThriftMetaData.fromExtraMetaData(fileMetadata);\n if (metaData == null) {\n throw new ParquetDecodingException(\"Could not read file as the Thrift class is not provided and could not be resolved from the file\");\n }\n thriftClass = (Class)metaData.getThriftClass();\n } else {\n thriftClass = (Class)Class.forName(className);\n }\n }\n\n @Override\n public RecordMaterializer prepareForRead(Configuration configuration,\n Map keyValueMetaData, MessageType fileSchema,\n parquet.hadoop.api.ReadSupport.ReadContext readContext) {\n ThriftMetaData thriftMetaData = ThriftMetaData.fromExtraMetaData(keyValueMetaData);\n try {\n initThriftClass(keyValueMetaData, configuration);\n\n String converterClassName = configuration.get(RECORD_CONVERTER_CLASS_KEY, RECORD_CONVERTER_DEFAULT);\n @SuppressWarnings(\"unchecked\")\n Class> converterClass = (Class>) Class.forName(converterClassName);\n Constructor> constructor =\n converterClass.getConstructor(Class.class, MessageType.class, StructType.class);\n ThriftRecordConverter converter = constructor.newInstance(thriftClass, readContext.getRequestedSchema(), thriftMetaData.getDescriptor());\n return converter;\n } catch (Exception t) {\n throw new RuntimeException(\"Unable to create Thrift Converter for Thrift metadata \" + thriftMetaData, t);\n }\n }\n}\n"},"new_file":{"kind":"string","value":"parquet-thrift/src/main/java/parquet/hadoop/thrift/ThriftReadSupport.java"},"old_contents":{"kind":"string","value":"/**\n * Copyright 2012 Twitter, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage parquet.hadoop.thrift;\n\nimport java.lang.reflect.Constructor;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.apache.hadoop.conf.Configuration;\nimport org.apache.hadoop.mapred.JobConf;\nimport org.apache.thrift.TBase;\nimport org.apache.thrift.protocol.TProtocol;\n\nimport parquet.Log;\nimport parquet.hadoop.api.InitContext;\nimport parquet.hadoop.api.ReadSupport;\nimport parquet.io.ParquetDecodingException;\nimport parquet.io.api.RecordMaterializer;\nimport parquet.schema.MessageType;\nimport parquet.thrift.TBaseRecordConverter;\nimport parquet.thrift.ThriftMetaData;\nimport parquet.thrift.ThriftRecordConverter;\nimport parquet.thrift.ThriftSchemaConverter;\nimport parquet.thrift.projection.FieldProjectionFilter;\nimport parquet.thrift.projection.ThriftProjectionException;\nimport parquet.thrift.struct.ThriftType.StructType;\n\npublic class ThriftReadSupport extends ReadSupport {\n private static final Log LOG = Log.getLog(ThriftReadSupport.class);\n\n /**\n * configuration key for thrift read projection schema\n */\n public static final String THRIFT_COLUMN_FILTER_KEY = \"parquet.thrift.column.filter\";\n private static final String RECORD_CONVERTER_DEFAULT = TBaseRecordConverter.class.getName();\n public static final String THRIFT_READ_CLASS_KEY = \"parquet.thrift.read.class\";\n\n\n /**\n * A {@link ThriftRecordConverter} builds an object by working with {@link TProtocol}. The default\n * implementation creates standard Apache Thrift {@link TBase} objects; to support alternatives, such\n * as Twiter's Scrooge, a custom converter can be specified using this key\n * (for example, ScroogeRecordConverter from parquet-scrooge).\n */\n private static final String RECORD_CONVERTER_CLASS_KEY = \"parquet.thrift.converter.class\";\n\n protected Class thriftClass;\n\n /**\n * A {@link ThriftRecordConverter} builds an object by working with {@link TProtocol}. The default\n * implementation creates standard Apache Thrift {@link TBase} objects; to support alternatives, such\n * as Twiter's Scrooge, a custom converter can be specified\n * (for example, ScroogeRecordConverter from parquet-scrooge).\n */\n public static void setRecordConverterClass(JobConf conf,\n Class klass) {\n conf.set(RECORD_CONVERTER_CLASS_KEY, klass.getName());\n }\n\n /**\n * used from hadoop\n * the configuration must contain a \"parquet.thrift.read.class\" setting\n */\n public ThriftReadSupport() {\n }\n\n /**\n * @param thriftClass the thrift class used to deserialize the records\n */\n public ThriftReadSupport(Class thriftClass) {\n this.thriftClass = thriftClass;\n }\n\n\n\n @Override\n public parquet.hadoop.api.ReadSupport.ReadContext init(InitContext context) {\n final Configuration configuration = context.getConfiguration();\n final MessageType fileMessageType = context.getFileSchema();\n MessageType requestedProjection = fileMessageType;\n String partialSchemaString = configuration.get(ReadSupport.PARQUET_READ_SCHEMA);\n String projectionFilterString = configuration.get(THRIFT_COLUMN_FILTER_KEY);\n\n if (partialSchemaString != null && projectionFilterString != null)\n throw new ThriftProjectionException(\"PARQUET_READ_SCHEMA and THRIFT_COLUMN_FILTER_KEY are both specified, should use only one.\");\n\n //set requestedProjections only when it's specified\n if (partialSchemaString != null) {\n requestedProjection = getSchemaForRead(fileMessageType, partialSchemaString);\n } else if (projectionFilterString != null && !projectionFilterString.isEmpty()) {\n FieldProjectionFilter fieldProjectionFilter = new FieldProjectionFilter(projectionFilterString);\n context.getKeyValueMetadata();\n try {\n initThriftClassFromMultipleFiles(context.getKeyValueMetadata(), configuration);\n requestedProjection = getProjectedSchema(fieldProjectionFilter);\n } catch (ClassNotFoundException e) {\n throw new ThriftProjectionException(\"can not find thriftClass from configuration\");\n }\n }\n\n MessageType schemaForRead = getSchemaForRead(fileMessageType, requestedProjection);\n return new ReadContext(schemaForRead);\n }\n\n protected MessageType getProjectedSchema(FieldProjectionFilter fieldProjectionFilter) {\n return new ThriftSchemaConverter(fieldProjectionFilter).convert((Class>)thriftClass);\n }\n\n @SuppressWarnings(\"unchecked\")\n private void initThriftClassFromMultipleFiles(Map> fileMetadata, Configuration conf) throws ClassNotFoundException {\n if (thriftClass != null) {\n return;\n }\n String className = conf.get(THRIFT_READ_CLASS_KEY, null);\n if (className == null) {\n Set names = ThriftMetaData.getThriftClassNames(fileMetadata);\n if (names == null || names.size() != 1) {\n throw new ParquetDecodingException(\"Could not read file as the Thrift class is not provided and could not be resolved from the file: \" + names);\n }\n className = names.iterator().next();\n }\n thriftClass = (Class)Class.forName(className);\n }\n\n @SuppressWarnings(\"unchecked\")\n private void initThriftClass(Map fileMetadata, Configuration conf) throws ClassNotFoundException {\n if (thriftClass != null) {\n return;\n }\n String className = conf.get(THRIFT_READ_CLASS_KEY, null);\n if (className == null) {\n final ThriftMetaData metaData = ThriftMetaData.fromExtraMetaData(fileMetadata);\n if (metaData == null) {\n throw new ParquetDecodingException(\"Could not read file as the Thrift class is not provided and could not be resolved from the file\");\n }\n thriftClass = (Class)metaData.getThriftClass();\n } else {\n thriftClass = (Class)Class.forName(className);\n }\n }\n\n @Override\n public RecordMaterializer prepareForRead(Configuration configuration,\n Map keyValueMetaData, MessageType fileSchema,\n parquet.hadoop.api.ReadSupport.ReadContext readContext) {\n ThriftMetaData thriftMetaData = ThriftMetaData.fromExtraMetaData(keyValueMetaData);\n try {\n initThriftClass(keyValueMetaData, configuration);\n\n String converterClassName = configuration.get(RECORD_CONVERTER_CLASS_KEY, RECORD_CONVERTER_DEFAULT);\n @SuppressWarnings(\"unchecked\")\n Class> converterClass = (Class>) Class.forName(converterClassName);\n Constructor> constructor =\n converterClass.getConstructor(Class.class, MessageType.class, StructType.class);\n ThriftRecordConverter converter = constructor.newInstance(thriftClass, readContext.getRequestedSchema(), thriftMetaData.getDescriptor());\n return converter;\n } catch (Exception t) {\n throw new RuntimeException(\"Unable to create Thrift Converter for Thrift metadata \" + thriftMetaData, t);\n }\n }\n}\n"},"message":{"kind":"string","value":"remove unused code\n"},"old_file":{"kind":"string","value":"parquet-thrift/src/main/java/parquet/hadoop/thrift/ThriftReadSupport.java"},"subject":{"kind":"string","value":"remove unused code"},"git_diff":{"kind":"string","value":"arquet-thrift/src/main/java/parquet/hadoop/thrift/ThriftReadSupport.java\n requestedProjection = getSchemaForRead(fileMessageType, partialSchemaString);\n } else if (projectionFilterString != null && !projectionFilterString.isEmpty()) {\n FieldProjectionFilter fieldProjectionFilter = new FieldProjectionFilter(projectionFilterString);\n context.getKeyValueMetadata();\n try {\n initThriftClassFromMultipleFiles(context.getKeyValueMetadata(), configuration);\n requestedProjection = getProjectedSchema(fieldProjectionFilter);"}}},{"rowIdx":1968,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"d0beff0889b76484aedf53ec8f4260ba043f2347"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"McLeodMoores/starling,nssales/OG-Platform,jeorme/OG-Platform,ChinaQuants/OG-Platform,jeorme/OG-Platform,McLeodMoores/starling,jerome79/OG-Platform,nssales/OG-Platform,jerome79/OG-Platform,jerome79/OG-Platform,DevStreet/FinanceAnalytics,McLeodMoores/starling,codeaudit/OG-Platform,ChinaQuants/OG-Platform,DevStreet/FinanceAnalytics,McLeodMoores/starling,nssales/OG-Platform,ChinaQuants/OG-Platform,ChinaQuants/OG-Platform,jeorme/OG-Platform,DevStreet/FinanceAnalytics,codeaudit/OG-Platform,jerome79/OG-Platform,DevStreet/FinanceAnalytics,jeorme/OG-Platform,codeaudit/OG-Platform,codeaudit/OG-Platform,nssales/OG-Platform"},"new_contents":{"kind":"string","value":"/**\n * Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies\n *\n * Please see distribution for license.\n */\npackage com.opengamma.financial.analytics.volatility.surface;\n\nimport javax.time.InstantProvider;\nimport javax.time.calendar.TimeZone;\nimport javax.time.calendar.ZonedDateTime;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.opengamma.OpenGammaRuntimeException;\nimport com.opengamma.core.config.ConfigSource;\nimport com.opengamma.engine.ComputationTarget;\nimport com.opengamma.engine.function.CompiledFunctionDefinition;\nimport com.opengamma.engine.function.FunctionCompilationContext;\nimport com.opengamma.financial.OpenGammaCompilationContext;\nimport com.opengamma.financial.analytics.model.InstrumentTypeProperties;\nimport com.opengamma.util.money.UnorderedCurrencyPair;\n\n/**\n *\n */\npublic class RawFXVolatilitySurfaceDataFunction extends RawVolatilitySurfaceDataFunction {\n private static final Logger s_logger = LoggerFactory.getLogger(RawFXVolatilitySurfaceDataFunction.class);\n\n public RawFXVolatilitySurfaceDataFunction() {\n super(InstrumentTypeProperties.FOREX);\n }\n\n @Override\n public boolean isCorrectIdType(final ComputationTarget target) {\n if (target.getUniqueId() == null) {\n s_logger.error(\"Target unique id was null {}\", target);\n return false;\n }\n return UnorderedCurrencyPair.OBJECT_SCHEME.equals(target.getUniqueId().getScheme());\n }\n\n @Override\n public CompiledFunctionDefinition compile(final FunctionCompilationContext myContext, final InstantProvider atInstantProvider) {\n final ConfigSource configSource = OpenGammaCompilationContext.getConfigSource(myContext);\n final ConfigDBVolatilitySurfaceDefinitionSource definitionSource = new ConfigDBVolatilitySurfaceDefinitionSource(configSource);\n final ConfigDBVolatilitySurfaceSpecificationSource specificationSource = new ConfigDBVolatilitySurfaceSpecificationSource(configSource);\n final ZonedDateTime atInstant = ZonedDateTime.ofInstant(atInstantProvider, TimeZone.UTC);\n return new FXVolatilitySurfaceCompiledFunction(atInstant.withTime(0, 0), atInstant.plusDays(1).withTime(0, 0).minusNanos(1000000), atInstant, definitionSource, specificationSource);\n }\n\n /**\n * Implementation of the compiled function\n */\n protected class FXVolatilitySurfaceCompiledFunction extends CompiledFunction {\n\n public FXVolatilitySurfaceCompiledFunction(final ZonedDateTime from, final ZonedDateTime to, final ZonedDateTime now,\n final ConfigDBVolatilitySurfaceDefinitionSource definitionSource, final ConfigDBVolatilitySurfaceSpecificationSource specificationSource) {\n super(from, to, now, definitionSource, specificationSource);\n }\n\n @Override\n protected VolatilitySurfaceDefinition getSurfaceDefinition(final ComputationTarget target, final String definitionName, final String instrumentType) {\n final UnorderedCurrencyPair pair = UnorderedCurrencyPair.of(target.getUniqueId());\n String name = pair.getFirstCurrency().getCode() + pair.getSecondCurrency().getCode();\n String fullDefinitionName = definitionName + \"_\" + name;\n VolatilitySurfaceDefinition definition = (VolatilitySurfaceDefinition) getDefinitionSource().getDefinition(fullDefinitionName, instrumentType);\n if (definition == null) {\n name = pair.getSecondCurrency().getCode() + pair.getFirstCurrency().getCode();\n fullDefinitionName = definitionName + \"_\" + name;\n definition = (VolatilitySurfaceDefinition) getDefinitionSource().getDefinition(fullDefinitionName, instrumentType);\n if (definition == null) {\n s_logger.error(\"Could not get volatility surface definition named \" + fullDefinitionName + \" for instrument type \" + instrumentType);\n return null;\n }\n }\n return definition;\n }\n\n @Override\n protected VolatilitySurfaceSpecification getSurfaceSpecification(final ComputationTarget target, final String specificationName, final String instrumentType) {\n final UnorderedCurrencyPair pair = UnorderedCurrencyPair.of(target.getUniqueId());\n String name = pair.getFirstCurrency().getCode() + pair.getSecondCurrency().getCode();\n String fullSpecificationName = specificationName + \"_\" + name;\n VolatilitySurfaceSpecification specification = getSpecificationSource().getSpecification(fullSpecificationName, instrumentType);\n if (specification == null) {\n name = pair.getSecondCurrency().getCode() + pair.getFirstCurrency().getCode();\n fullSpecificationName = specificationName + \"_\" + name;\n specification = getSpecificationSource().getSpecification(fullSpecificationName, instrumentType);\n if (specification == null) {\n throw new OpenGammaRuntimeException(\"Could not get volatility surface specification named \" + fullSpecificationName);\n }\n }\n return specification;\n }\n }\n}\n"},"new_file":{"kind":"string","value":"projects/OG-Financial/src/com/opengamma/financial/analytics/volatility/surface/RawFXVolatilitySurfaceDataFunction.java"},"old_contents":{"kind":"string","value":"/**\n * Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies\n * \n * Please see distribution for license.\n */\npackage com.opengamma.financial.analytics.volatility.surface;\n\nimport javax.time.InstantProvider;\nimport javax.time.calendar.TimeZone;\nimport javax.time.calendar.ZonedDateTime;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.opengamma.OpenGammaRuntimeException;\nimport com.opengamma.core.config.ConfigSource;\nimport com.opengamma.engine.ComputationTarget;\nimport com.opengamma.engine.function.CompiledFunctionDefinition;\nimport com.opengamma.engine.function.FunctionCompilationContext;\nimport com.opengamma.financial.OpenGammaCompilationContext;\nimport com.opengamma.financial.analytics.model.InstrumentTypeProperties;\nimport com.opengamma.util.money.UnorderedCurrencyPair;\n\n/**\n * \n */\npublic class RawFXVolatilitySurfaceDataFunction extends RawVolatilitySurfaceDataFunction {\n private static final Logger s_logger = LoggerFactory.getLogger(RawFXVolatilitySurfaceDataFunction.class);\n\n public RawFXVolatilitySurfaceDataFunction() {\n super(InstrumentTypeProperties.FOREX);\n }\n\n @Override\n public boolean isCorrectIdType(final ComputationTarget target) {\n if (target.getUniqueId() == null) {\n s_logger.error(\"Target unique id was null {}\", target);\n return false;\n }\n return UnorderedCurrencyPair.OBJECT_SCHEME.equals(target.getUniqueId().getScheme());\n }\n\n @Override\n public CompiledFunctionDefinition compile(final FunctionCompilationContext myContext, final InstantProvider atInstantProvider) {\n final ConfigSource configSource = OpenGammaCompilationContext.getConfigSource(myContext);\n final ConfigDBVolatilitySurfaceDefinitionSource definitionSource = new ConfigDBVolatilitySurfaceDefinitionSource(configSource);\n final ConfigDBVolatilitySurfaceSpecificationSource specificationSource = new ConfigDBVolatilitySurfaceSpecificationSource(configSource);\n final ZonedDateTime atInstant = ZonedDateTime.ofInstant(atInstantProvider, TimeZone.UTC);\n return new FXVolatilitySurfaceCompiledFunction(atInstant.withTime(0, 0), atInstant.plusDays(1).withTime(0, 0).minusNanos(1000000), atInstant, definitionSource, specificationSource);\n }\n\n /**\n * Implementation of the compiled function\n */\n protected class FXVolatilitySurfaceCompiledFunction extends CompiledFunction {\n\n public FXVolatilitySurfaceCompiledFunction(final ZonedDateTime from, final ZonedDateTime to, final ZonedDateTime now,\n final ConfigDBVolatilitySurfaceDefinitionSource definitionSource, final ConfigDBVolatilitySurfaceSpecificationSource specificationSource) {\n super(from, to, now, definitionSource, specificationSource);\n }\n\n @Override\n protected VolatilitySurfaceDefinition getSurfaceDefinition(final ComputationTarget target, final String definitionName, final String instrumentType) {\n final UnorderedCurrencyPair pair = UnorderedCurrencyPair.of(target.getUniqueId());\n String name = pair.getFirstCurrency().getCode() + pair.getSecondCurrency().getCode();\n String fullDefinitionName = definitionName + \"_\" + name;\n VolatilitySurfaceDefinition definition = (VolatilitySurfaceDefinition) getDefinitionSource().getDefinition(fullDefinitionName, instrumentType);\n if (definition == null) {\n name = pair.getSecondCurrency().getCode() + pair.getFirstCurrency().getCode();\n fullDefinitionName = definitionName + \"_\" + name;\n definition = (VolatilitySurfaceDefinition) getDefinitionSource().getDefinition(fullDefinitionName, instrumentType);\n if (definition == null) {\n throw new OpenGammaRuntimeException(\"Could not get volatility surface definition named \" + fullDefinitionName + \" for instrument type \" + instrumentType);\n }\n }\n return definition;\n }\n\n @Override\n protected VolatilitySurfaceSpecification getSurfaceSpecification(final ComputationTarget target, final String specificationName, final String instrumentType) {\n final UnorderedCurrencyPair pair = UnorderedCurrencyPair.of(target.getUniqueId());\n String name = pair.getFirstCurrency().getCode() + pair.getSecondCurrency().getCode();\n String fullSpecificationName = specificationName + \"_\" + name;\n VolatilitySurfaceSpecification specification = getSpecificationSource().getSpecification(fullSpecificationName, instrumentType);\n if (specification == null) {\n name = pair.getSecondCurrency().getCode() + pair.getFirstCurrency().getCode();\n fullSpecificationName = specificationName + \"_\" + name;\n specification = getSpecificationSource().getSpecification(fullSpecificationName, instrumentType);\n if (specification == null) {\n throw new OpenGammaRuntimeException(\"Could not get volatility surface specification named \" + fullSpecificationName);\n }\n }\n return specification;\n }\n }\n}\n"},"message":{"kind":"string","value":"Logging and returning null rather than throwing an exception in getRequirements()\n"},"old_file":{"kind":"string","value":"projects/OG-Financial/src/com/opengamma/financial/analytics/volatility/surface/RawFXVolatilitySurfaceDataFunction.java"},"subject":{"kind":"string","value":"Logging and returning null rather than throwing an exception in getRequirements()"},"git_diff":{"kind":"string","value":"rojects/OG-Financial/src/com/opengamma/financial/analytics/volatility/surface/RawFXVolatilitySurfaceDataFunction.java\n /**\n * Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies\n * \n *\n * Please see distribution for license.\n */\n package com.opengamma.financial.analytics.volatility.surface;\n import com.opengamma.util.money.UnorderedCurrencyPair;\n \n /**\n * \n *\n */\n public class RawFXVolatilitySurfaceDataFunction extends RawVolatilitySurfaceDataFunction {\n private static final Logger s_logger = LoggerFactory.getLogger(RawFXVolatilitySurfaceDataFunction.class);\n fullDefinitionName = definitionName + \"_\" + name;\n definition = (VolatilitySurfaceDefinition) getDefinitionSource().getDefinition(fullDefinitionName, instrumentType);\n if (definition == null) {\n throw new OpenGammaRuntimeException(\"Could not get volatility surface definition named \" + fullDefinitionName + \" for instrument type \" + instrumentType);\n s_logger.error(\"Could not get volatility surface definition named \" + fullDefinitionName + \" for instrument type \" + instrumentType);\n return null;\n }\n }\n return definition;"}}},{"rowIdx":1969,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"9a19fac9419a45c048e61ab0a753224ce7dc1850"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"grechaw/java-client-api,marklogic/java-client-api,grechaw/java-client-api,supriyantomaftuh/java-client-api,marklogic/java-client-api,marklogic/java-client-api,supriyantomaftuh/java-client-api,supriyantomaftuh/java-client-api,supriyantomaftuh/java-client-api,marklogic/java-client-api,omkarudipi/java-client-api,omkarudipi/java-client-api,omkarudipi/java-client-api,omkarudipi/java-client-api,marklogic/java-client-api"},"new_contents":{"kind":"string","value":"/*\n * Copyright 2012-2013 MarkLogic Corporation\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.marklogic.client.impl;\n\nimport java.io.File;\nimport java.io.InputStream;\nimport java.io.PrintStream;\nimport java.io.Reader;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.Random;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentLinkedQueue;\n\nimport javax.net.ssl.SSLContext;\nimport javax.net.ssl.SSLException;\nimport javax.ws.rs.core.Cookie;\nimport javax.ws.rs.core.MediaType;\nimport javax.ws.rs.core.MultivaluedMap;\nimport javax.ws.rs.core.StreamingOutput;\n\nimport org.apache.http.HttpHost;\nimport org.apache.http.HttpVersion;\nimport org.apache.http.auth.params.AuthPNames;\nimport org.apache.http.client.HttpClient;\nimport org.apache.http.client.params.AuthPolicy;\nimport org.apache.http.client.params.ClientPNames;\nimport org.apache.http.conn.routing.HttpRoute;\nimport org.apache.http.conn.scheme.PlainSocketFactory;\nimport org.apache.http.conn.scheme.Scheme;\nimport org.apache.http.conn.scheme.SchemeRegistry;\nimport org.apache.http.conn.scheme.SchemeSocketFactory;\nimport org.apache.http.conn.ssl.AbstractVerifier;\nimport org.apache.http.conn.ssl.SSLSocketFactory;\nimport org.apache.http.conn.ssl.X509HostnameVerifier;\nimport org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;\nimport org.apache.http.params.BasicHttpParams;\nimport org.apache.http.params.HttpParams;\nimport org.apache.http.params.HttpProtocolParams;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.marklogic.client.DatabaseClientFactory.Authentication;\nimport com.marklogic.client.DatabaseClientFactory.SSLHostnameVerifier;\nimport com.marklogic.client.FailedRequestException;\nimport com.marklogic.client.ForbiddenUserException;\nimport com.marklogic.client.MarkLogicInternalException;\nimport com.marklogic.client.ResourceNotFoundException;\nimport com.marklogic.client.ResourceNotResendableException;\nimport com.marklogic.client.document.ContentDescriptor;\nimport com.marklogic.client.document.DocumentDescriptor;\nimport com.marklogic.client.document.DocumentManager.Metadata;\nimport com.marklogic.client.document.DocumentUriTemplate;\nimport com.marklogic.client.document.ServerTransform;\nimport com.marklogic.client.extensions.ResourceServices.ServiceResult;\nimport com.marklogic.client.extensions.ResourceServices.ServiceResultIterator;\nimport com.marklogic.client.io.Format;\nimport com.marklogic.client.io.OutputStreamSender;\nimport com.marklogic.client.io.marker.AbstractReadHandle;\nimport com.marklogic.client.io.marker.AbstractWriteHandle;\nimport com.marklogic.client.io.marker.DocumentMetadataReadHandle;\nimport com.marklogic.client.io.marker.DocumentMetadataWriteHandle;\nimport com.marklogic.client.io.marker.DocumentPatchHandle;\nimport com.marklogic.client.io.marker.StructureWriteHandle;\nimport com.marklogic.client.query.DeleteQueryDefinition;\nimport com.marklogic.client.query.ElementLocator;\nimport com.marklogic.client.query.KeyLocator;\nimport com.marklogic.client.query.KeyValueQueryDefinition;\nimport com.marklogic.client.query.QueryDefinition;\nimport com.marklogic.client.query.QueryManager.QueryView;\nimport com.marklogic.client.query.RawQueryByExampleDefinition;\nimport com.marklogic.client.query.RawQueryDefinition;\nimport com.marklogic.client.query.StringQueryDefinition;\nimport com.marklogic.client.query.StructuredQueryDefinition;\nimport com.marklogic.client.query.SuggestDefinition;\nimport com.marklogic.client.query.ValueLocator;\nimport com.marklogic.client.query.ValueQueryDefinition;\nimport com.marklogic.client.query.ValuesDefinition;\nimport com.marklogic.client.query.ValuesListDefinition;\nimport com.marklogic.client.util.RequestLogger;\nimport com.marklogic.client.util.RequestParameters;\nimport com.sun.jersey.api.client.ClientResponse;\nimport com.sun.jersey.api.client.WebResource;\nimport com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;\nimport com.sun.jersey.api.client.filter.HTTPDigestAuthFilter;\nimport com.sun.jersey.api.uri.UriComponent;\nimport com.sun.jersey.client.apache4.ApacheHttpClient4;\nimport com.sun.jersey.client.apache4.config.ApacheHttpClient4Config;\nimport com.sun.jersey.client.apache4.config.DefaultApacheHttpClient4Config;\nimport com.sun.jersey.core.util.MultivaluedMapImpl;\nimport com.sun.jersey.multipart.BodyPart;\nimport com.sun.jersey.multipart.Boundary;\nimport com.sun.jersey.multipart.MultiPart;\nimport com.sun.jersey.multipart.MultiPartMediaTypes;\n\n@SuppressWarnings({ \"unchecked\", \"rawtypes\" })\npublic class JerseyServices implements RESTServices {\n\tstatic final private Logger logger = LoggerFactory\n\t\t\t.getLogger(JerseyServices.class);\n\tstatic final String ERROR_NS = \"http://marklogic.com/rest-api\";\n\n\tstatic final private String DOCUMENT_URI_PREFIX = \"/documents?uri=\";\n\n\tstatic final private int DELAY_FLOOR = 125;\n\tstatic final private int DELAY_CEILING = 2000;\n\tstatic final private int DELAY_MULTIPLIER = 20;\n\tstatic final private int DEFAULT_MAX_DELAY = 120000;\n\tstatic final private int DEFAULT_MIN_RETRY = 8;\n\n\tstatic final private String MAX_DELAY_PROP = \"com.marklogic.client.maximumRetrySeconds\";\n\tstatic final private String MIN_RETRY_PROP = \"com.marklogic.client.minimumRetries\";\n\n\tstatic protected class HostnameVerifierAdapter extends AbstractVerifier {\n\t\tprivate SSLHostnameVerifier verifier;\n\n\t\tprotected HostnameVerifierAdapter(SSLHostnameVerifier verifier) {\n\t\t\tsuper();\n\t\t\tthis.verifier = verifier;\n\t\t}\n\n\t\t@Override\n\t\tpublic void verify(String hostname, String[] cns, String[] subjectAlts)\n\t\t\t\tthrows SSLException {\n\t\t\tverifier.verify(hostname, cns, subjectAlts);\n\t\t}\n\t}\n\n\tprivate ApacheHttpClient4 client;\n\tprivate WebResource connection;\n\n\tprivate Random randRetry = new Random();\n\n\tprivate int maxDelay = DEFAULT_MAX_DELAY;\n\tprivate int minRetry = DEFAULT_MIN_RETRY;\n\n\tprivate boolean isFirstRequest = false;\n\n\tpublic JerseyServices() {\n\t}\n\n\tprivate FailedRequest extractErrorFields(ClientResponse response) {\n\t\tInputStream is = response.getEntityInputStream();\n\t\ttry {\n\t\t\tFailedRequest handler = FailedRequest.getFailedRequest(\n\t\t\t\t\tresponse.getStatus(), response.getType(), is);\n\t\t\treturn handler;\n\t\t} catch (RuntimeException e) {\n\t\t\tthrow (e);\n\t\t} finally {\n\t\t\tresponse.close();\n\t\t}\n\t}\n\n\t@Override\n\tpublic void connect(String host, int port, String user, String password,\n\t\t\tAuthentication authenType, SSLContext context,\n\t\t\tSSLHostnameVerifier verifier) {\n\t\tX509HostnameVerifier x509Verifier = null;\n\t\tif (verifier == null) {\n\t\t\tif (context != null)\n\t\t\t\tx509Verifier = SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;\n\t\t\t}\n\t\telse if (verifier == SSLHostnameVerifier.ANY)\n\t\t\tx509Verifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;\n\t\telse if (verifier == SSLHostnameVerifier.COMMON)\n\t\t\tx509Verifier = SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;\n\t\telse if (verifier == SSLHostnameVerifier.STRICT)\n\t\t\tx509Verifier = SSLSocketFactory.STRICT_HOSTNAME_VERIFIER;\n\t\telse if (context != null)\n\t\t\tx509Verifier = new HostnameVerifierAdapter(verifier);\n\t\telse\n\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\"Null SSLContent but non-null SSLHostnameVerifier for client\");\n\n\t\tconnect(host, port, user, password, authenType, context, x509Verifier);\n\t}\n\n\tprivate void connect(String host, int port, String user, String password,\n\t\t\tAuthentication authenType, SSLContext context,\n\t\t\tX509HostnameVerifier verifier) {\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Connecting to {} at {} as {}\", new Object[] { host,\n\t\t\t\t\tport, user });\n\n\t\tif (host == null)\n\t\t\tthrow new IllegalArgumentException(\"No host provided\");\n\n\t\tif (authenType == null) {\n\t\t\tif (context != null) {\n\t\t\t\tauthenType = Authentication.BASIC;\n\t\t\t}\n\t\t}\n\n\t\tif (authenType != null) {\n\t\t\tif (user == null)\n\t\t\t\tthrow new IllegalArgumentException(\"No user provided\");\n\t\t\tif (password == null)\n\t\t\t\tthrow new IllegalArgumentException(\"No password provided\");\n\t\t}\n\n\t\tif (connection != null)\n\t\t\tconnection = null;\n\t\tif (client != null) {\n\t\t\tclient.destroy();\n\t\t\tclient = null;\n\t\t}\n\n\t\tString baseUri = ((context == null) ? \"http\" : \"https\") + \"://\" + host\n\t\t\t\t+ \":\" + port + \"/v1/\";\n\n\t\tProperties props = System.getProperties();\n\n\t\tif (props.containsKey(MAX_DELAY_PROP)) {\n\t\t\tString maxDelayStr = props.getProperty(MAX_DELAY_PROP);\n\t\t\tif (maxDelayStr != null && maxDelayStr.length() > 0) {\n\t\t\t\tint max = Integer.parseInt(maxDelayStr);\n\t\t\t\tif (max > 0) {\n\t\t\t\t\tmaxDelay = max * 1000;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (props.containsKey(MIN_RETRY_PROP)) {\n\t\t\tString minRetryStr = props.getProperty(MIN_RETRY_PROP);\n\t\t\tif (minRetryStr != null && minRetryStr.length() > 0) {\n\t\t\t\tint min = Integer.parseInt(minRetryStr);\n\t\t\t\tif (min > 0) {\n\t\t\t\t\tminRetry = min;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// TODO: integrated control of HTTP Client and Jersey Client logging\n\t\tif (!props.containsKey(\"org.apache.commons.logging.Log\")) {\n\t\t\tSystem.setProperty(\"org.apache.commons.logging.Log\",\n\t\t\t\t\"org.apache.commons.logging.impl.SimpleLog\");\n\t\t}\n\t\tif (!props.containsKey(\"org.apache.commons.logging.simplelog.log.org.apache.http\")) {\n\t\t\tSystem.setProperty(\n\t\t\t\t\"org.apache.commons.logging.simplelog.log.org.apache.http\",\n\t\t\t\t\"warn\");\n\t\t}\n\t\tif (!props.containsKey(\"org.apache.commons.logging.simplelog.log.org.apache.http.wire\")) {\n\t\t\tSystem.setProperty(\n\t\t\t\t\"org.apache.commons.logging.simplelog.log.org.apache.http.wire\",\n\t\t\t\t\"warn\");\n\t\t}\n\n\t\tScheme scheme = null;\n\t\tif (context == null) {\n\t\t\tSchemeSocketFactory socketFactory = PlainSocketFactory\n\t\t\t\t\t.getSocketFactory();\n\t\t\tscheme = new Scheme(\"http\", port, socketFactory);\n\t\t} else {\n\t\t\tSSLSocketFactory socketFactory = new SSLSocketFactory(context,\n\t\t\t\t\tverifier);\n\t\t\tscheme = new Scheme(\"https\", port, socketFactory);\n\t\t}\n\t\tSchemeRegistry schemeRegistry = new SchemeRegistry();\n\t\tschemeRegistry.register(scheme);\n\n\t\tint maxRouteConnections = 100;\n\t\tint maxTotalConnections = 2 * maxRouteConnections;\n\n\t\t/*\n\t\t * 4.2 PoolingClientConnectionManager connMgr = new\n\t\t * PoolingClientConnectionManager(schemeRegistry);\n\t\t * connMgr.setMaxTotal(maxTotalConnections);\n\t\t * connMgr.setDefaultMaxPerRoute(maxRouteConnections);\n\t\t * connMgr.setMaxPerRoute( new HttpRoute(new HttpHost(baseUri)),\n\t\t * maxRouteConnections);\n\t\t */\n\t\t// start 4.1\n\t\tThreadSafeClientConnManager connMgr = new ThreadSafeClientConnManager(\n\t\t\t\tschemeRegistry);\n\t\tconnMgr.setMaxTotal(maxTotalConnections);\n\t\tconnMgr.setDefaultMaxPerRoute(maxRouteConnections);\n\t\tconnMgr.setMaxForRoute(new HttpRoute(new HttpHost(baseUri)),\n\t\t\t\tmaxRouteConnections);\n\t\t// end 4.1\n\n\t\t// CredentialsProvider credentialsProvider = new\n\t\t// BasicCredentialsProvider();\n\t\t// credentialsProvider.setCredentials(new AuthScope(host, port),\n\t\t// new UsernamePasswordCredentials(user, password));\n\n\t\tHttpParams httpParams = new BasicHttpParams();\n\n\t\tif (authenType != null) {\n\t\t\tList authpref = new ArrayList();\n\n\t\t\tif (authenType == Authentication.BASIC)\n\t\t\t\tauthpref.add(AuthPolicy.BASIC);\n\t\t\telse if (authenType == Authentication.DIGEST)\n\t\t\t\tauthpref.add(AuthPolicy.DIGEST);\n\t\t\telse\n\t\t\t\tthrow new MarkLogicInternalException(\n\t\t\t\t\t\t\"Internal error - unknown authentication type: \"\n\t\t\t\t\t\t\t\t+ authenType.name());\n\n\t\t\thttpParams.setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);\n\t\t}\n\n\t\thttpParams.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false);\n\n HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);\n\n // HttpConnectionParams.setStaleCheckingEnabled(httpParams, false);\n\n // long-term alternative to isFirstRequest alive\n\t\t// HttpProtocolParams.setUseExpectContinue(httpParams, false);\n\t\t// httpParams.setIntParameter(CoreProtocolPNames.WAIT_FOR_CONTINUE, 1000);\n\n\t\tDefaultApacheHttpClient4Config config = new DefaultApacheHttpClient4Config();\n\t\tMap configProps = config.getProperties();\n\t\tconfigProps\n\t\t\t\t.put(ApacheHttpClient4Config.PROPERTY_PREEMPTIVE_BASIC_AUTHENTICATION,\n\t\t\t\t\t\tfalse);\n\t\tconfigProps.put(ApacheHttpClient4Config.PROPERTY_CONNECTION_MANAGER,\n\t\t\t\tconnMgr);\n\t\t// ignored?\n\t\tconfigProps.put(ApacheHttpClient4Config.PROPERTY_FOLLOW_REDIRECTS,\n\t\t\t\tfalse);\n\t\t// configProps.put(ApacheHttpClient4Config.PROPERTY_CREDENTIALS_PROVIDER,\n\t\t// credentialsProvider);\n\t\tconfigProps.put(ApacheHttpClient4Config.PROPERTY_HTTP_PARAMS,\n\t\t\t\thttpParams);\n\t\t// switches from buffered to streamed in Jersey Client\n\t\tconfigProps.put(ApacheHttpClient4Config.PROPERTY_CHUNKED_ENCODING_SIZE,\n\t\t\t\t32 * 1024);\n\n\t\tclient = ApacheHttpClient4.create(config);\n\n\t\t// System.setProperty(\"javax.net.debug\", \"all\"); // all or ssl\n\n\t\tif (authenType == null) {\n\t\t\tisFirstRequest = false;\n\t\t} else if (authenType == Authentication.BASIC) {\n\t\t\tisFirstRequest = false;\n\n\t\t\tclient.addFilter(new HTTPBasicAuthFilter(user, password));\n\t\t} else if (authenType == Authentication.DIGEST) {\n\t\t\tisFirstRequest = true;\n\n\t\t\t// workaround for JerseyClient bug 1445\n\t\t\tclient.addFilter(new DigestChallengeFilter());\n\n\t\t\tclient.addFilter(new HTTPDigestAuthFilter(user, password));\n\t\t} else {\n\t\t\tthrow new MarkLogicInternalException(\n\t\t\t\t\t\"Internal error - unknown authentication type: \"\n\t\t\t\t\t\t\t+ authenType.name());\n\t\t}\n\n\t\t// client.addFilter(new LoggingFilter(System.err));\n\n\t\tconnection = client.resource(baseUri);\n\t}\n\n\t@Override\n\tpublic void release() {\n\t\tif (client == null)\n\t\t\treturn;\n\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Releasing connection\");\n\n\t\tconnection = null;\n\t\tclient.destroy();\n\t\tclient = null;\n\t}\n\n\tprivate void makeFirstRequest() {\n\t\tconnection.path(\"ping\").head().close();\n\t}\n\n\t@Override\n\tpublic void deleteDocument(RequestLogger reqlog, DocumentDescriptor desc,\n\t\t\tString transactionId, Set categories)\n\t\t\tthrows ResourceNotFoundException, ForbiddenUserException,\n\t\t\tFailedRequestException {\n\t\tString uri = desc.getUri();\n\t\tif (uri == null)\n\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\"Document delete for document identifier without uri\");\n\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Deleting {} in transaction {}\", uri, transactionId);\n\n\t\tWebResource webResource = makeDocumentResource(makeDocumentParams(uri,\n\t\t\t\tcategories, transactionId, null));\n\n\t\tWebResource.Builder builder = addVersionHeader(desc,\n\t\t\t\twebResource.getRequestBuilder(), \"If-Match\");\n\t\tbuilder = addTransactionCookie(builder, transactionId);\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n\t\tint retry = 0;\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresponse = builder.delete(ClientResponse.class);\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n\t\t}\n\t\tif (status == ClientResponse.Status.NOT_FOUND) {\n\t\t\tresponse.close();\n\t\t\tthrow new ResourceNotFoundException(\n\t\t\t\t\t\"Could not delete non-existent document\");\n\t\t}\n\t\tif (status == ClientResponse.Status.FORBIDDEN) {\n\t\t\tFailedRequest failure = extractErrorFields(response);\n\t\t\tif (failure.getMessageCode().equals(\"RESTAPI-CONTENTNOVERSION\"))\n\t\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\t\"Content version required to delete document\", failure);\n\t\t\tthrow new ForbiddenUserException(\n\t\t\t\t\t\"User is not allowed to delete documents\", failure);\n\t\t}\n\t\tif (status == ClientResponse.Status.PRECONDITION_FAILED) {\n\t\t\tFailedRequest failure = extractErrorFields(response);\n\t\t\tif (failure.getMessageCode().equals(\"RESTAPI-CONTENTWRONGVERSION\"))\n\t\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\t\"Content version must match to delete document\",\n\t\t\t\t\t\tfailure);\n\t\t\telse if (failure.getMessageCode().equals(\"RESTAPI-EMPTYBODY\"))\n\t\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\t\"Empty request body sent to server\", failure);\n\t\t\tthrow new FailedRequestException(\"Precondition Failed\", failure);\n\t\t}\n\t\tif (status != ClientResponse.Status.NO_CONTENT)\n\t\t\tthrow new FailedRequestException(\"delete failed: \"\n\t\t\t\t\t+ status.getReasonPhrase(), extractErrorFields(response));\n\n\t\tresponse.close();\n\t\tlogRequest(reqlog, \"deleted %s document\", uri);\n\t}\n\n\t@Override\n\tpublic boolean getDocument(RequestLogger reqlog, DocumentDescriptor desc,\n\t\t\tString transactionId, Set categories,\n\t\t\tRequestParameters extraParams,\n\t\t\tDocumentMetadataReadHandle metadataHandle,\n\t\t\tAbstractReadHandle contentHandle) throws ResourceNotFoundException,\n\t\t\tForbiddenUserException, FailedRequestException {\n\n\t\tHandleImplementation metadataBase = HandleAccessor.checkHandle(\n\t\t\t\tmetadataHandle, \"metadata\");\n\t\tHandleImplementation contentBase = HandleAccessor.checkHandle(\n\t\t\t\tcontentHandle, \"content\");\n\n\t\tString metadataFormat = null;\n\t\tString metadataMimetype = null;\n\t\tif (metadataBase != null) {\n\t\t\tmetadataFormat = metadataBase.getFormat().toString().toLowerCase();\n\t\t\tmetadataMimetype = metadataBase.getMimetype();\n\t\t}\n\n\t\tString contentMimetype = null;\n\t\tif (contentBase != null) {\n\t\t\tcontentMimetype = contentBase.getMimetype();\n\t\t}\n\n\t\tif (metadataBase != null && contentBase != null) {\n\t\t\treturn getDocumentImpl(reqlog, desc, transactionId, categories,\n\t\t\t\t\textraParams, metadataFormat, metadataHandle, contentHandle);\n\t\t} else if (metadataBase != null) {\n\t\t\treturn getDocumentImpl(reqlog, desc, transactionId, categories,\n\t\t\t\t\textraParams, metadataMimetype, metadataHandle);\n\t\t} else if (contentBase != null) {\n\t\t\treturn getDocumentImpl(reqlog, desc, transactionId, null,\n\t\t\t\t\textraParams, contentMimetype, contentHandle);\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tprivate boolean getDocumentImpl(RequestLogger reqlog,\n\t\t\tDocumentDescriptor desc, String transactionId,\n\t\t\tSet categories, RequestParameters extraParams,\n\t\t\tString mimetype, AbstractReadHandle handle)\n\t\t\tthrows ResourceNotFoundException, ForbiddenUserException,\n\t\t\tFailedRequestException {\n\t\tString uri = desc.getUri();\n\t\tif (uri == null)\n\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\"Document read for document identifier without uri\");\n\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Getting {} in transaction {}\", uri, transactionId);\n\n\t\tWebResource.Builder builder = makeDocumentResource(\n\t\t\t\tmakeDocumentParams(uri, categories, transactionId, extraParams))\n\t\t\t\t.accept(mimetype);\n\t\tbuilder = addTransactionCookie(builder, transactionId);\n\n\t\tif (extraParams != null && extraParams.containsKey(\"range\"))\n\t\t\tbuilder = builder.header(\"range\", extraParams.get(\"range\").get(0));\n\n\t\tbuilder = addVersionHeader(desc, builder, \"If-None-Match\");\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n\t\tint retry = 0;\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresponse = builder.get(ClientResponse.class);\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n\t\t}\n\t\tif (status == ClientResponse.Status.NOT_FOUND)\n\t\t\tthrow new ResourceNotFoundException(\n\t\t\t\t\t\"Could not read non-existent document\",\n\t\t\t\t\textractErrorFields(response));\n\t\tif (status == ClientResponse.Status.FORBIDDEN)\n\t\t\tthrow new ForbiddenUserException(\n\t\t\t\t\t\"User is not allowed to read documents\",\n\t\t\t\t\textractErrorFields(response));\n\t\tif (status == ClientResponse.Status.NOT_MODIFIED) {\n\t\t\tresponse.close();\n\t\t\treturn false;\n\t\t}\n\t\tif (status != ClientResponse.Status.OK\n\t\t\t\t&& status != ClientResponse.Status.PARTIAL_CONTENT)\n\t\t\tthrow new FailedRequestException(\"read failed: \"\n\t\t\t\t\t+ status.getReasonPhrase(), extractErrorFields(response));\n\n\t\tlogRequest(\n\t\t\t\treqlog,\n\t\t\t\t\"read %s document from %s transaction with %s mime type and %s metadata categories\",\n\t\t\t\turi, (transactionId != null) ? transactionId : \"no\",\n\t\t\t\t(mimetype != null) ? mimetype : \"no\",\n\t\t\t\tstringJoin(categories, \", \", \"no\"));\n\n\t\tHandleImplementation handleBase = HandleAccessor.as(handle);\n\n\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\tif (isExternalDescriptor(desc)) {\n\t\t\tupdateVersion(desc, responseHeaders);\n\t\t\tupdateDescriptor(desc, responseHeaders);\n\t\t\tcopyDescriptor(desc, handleBase);\n\t\t} else {\n\t\t\tupdateDescriptor(handleBase, responseHeaders);\n\t\t}\n\n\t\tClass as = handleBase.receiveAs();\n\t\tObject entity = response.hasEntity() ? response.getEntity(as) : null;\n\n\t\tif (entity == null ||\n\t\t\t\t(!InputStream.class.isAssignableFrom(as) && !Reader.class.isAssignableFrom(as)))\n\t\t\tresponse.close();\n\n\t\thandleBase.receiveContent((reqlog != null) ? reqlog.copyContent(entity)\n\t\t\t\t: entity);\n\n\t\treturn true;\n\t}\n\n\tprivate boolean getDocumentImpl(RequestLogger reqlog,\n\t\t\tDocumentDescriptor desc, String transactionId,\n\t\t\tSet categories, RequestParameters extraParams,\n\t\t\tString metadataFormat, DocumentMetadataReadHandle metadataHandle,\n\t\t\tAbstractReadHandle contentHandle) throws ResourceNotFoundException,\n\t\t\tForbiddenUserException, FailedRequestException {\n\t\tString uri = desc.getUri();\n\t\tif (uri == null)\n\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\"Document read for document identifier without uri\");\n\n\t\tassert metadataHandle != null : \"metadataHandle is null\";\n\t\tassert contentHandle != null : \"contentHandle is null\";\n\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Getting multipart for {} in transaction {}\", uri,\n\t\t\t\t\ttransactionId);\n\n\t\tMultivaluedMap docParams = makeDocumentParams(uri,\n\t\t\t\tcategories, transactionId, extraParams, true);\n\t\tdocParams.add(\"format\", metadataFormat);\n\n\t\tWebResource.Builder builder = makeDocumentResource(docParams).getRequestBuilder();\n\t\tbuilder = addTransactionCookie(builder, transactionId);\n\t\tbuilder = addVersionHeader(desc, builder, \"If-None-Match\");\n\n\t\tMediaType multipartType = Boundary.addBoundary(MultiPartMediaTypes.MULTIPART_MIXED_TYPE);\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n\t\tint retry = 0;\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresponse = builder.accept(multipartType).get(ClientResponse.class);\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n\t\t}\n\t\tif (status == ClientResponse.Status.NOT_FOUND)\n\t\t\tthrow new ResourceNotFoundException(\n\t\t\t\t\t\"Could not read non-existent document\",\n\t\t\t\t\textractErrorFields(response));\n\t\tif (status == ClientResponse.Status.FORBIDDEN)\n\t\t\tthrow new ForbiddenUserException(\n\t\t\t\t\t\"User is not allowed to read documents\",\n\t\t\t\t\textractErrorFields(response));\n\t\tif (status == ClientResponse.Status.NOT_MODIFIED) {\n\t\t\tresponse.close();\n\t\t\treturn false;\n\t\t}\n\t\tif (status != ClientResponse.Status.OK)\n\t\t\tthrow new FailedRequestException(\"read failed: \"\n\t\t\t\t\t+ status.getReasonPhrase(), extractErrorFields(response));\n\n\t\tlogRequest(\n\t\t\t\treqlog,\n\t\t\t\t\"read %s document from %s transaction with %s metadata categories and content\",\n\t\t\t\turi, (transactionId != null) ? transactionId : \"no\",\n\t\t\t\tstringJoin(categories, \", \", \"no\"));\n\n\t\tMultiPart entity = response.hasEntity() ?\n\t\t\t\tresponse.getEntity(MultiPart.class) : null;\n\t\tif (entity == null)\n\t\t\treturn false;\n\n\t\tList partList = entity.getBodyParts();\n\t\tif (partList == null)\n\t\t\treturn false;\n\n\t\tint partCount = partList.size();\n\t\tif (partCount == 0)\n\t\t\treturn false;\n\t\tif (partCount != 2)\n\t\t\tthrow new FailedRequestException(\"read expected 2 parts but got \"\n\t\t\t\t\t+ partCount + \" parts\");\n\n\t\tHandleImplementation metadataBase = HandleAccessor.as(metadataHandle);\n\t\tHandleImplementation contentBase = HandleAccessor.as(contentHandle);\n\n\t\tBodyPart contentPart = partList.get(1);\n\n\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\tMultivaluedMap contentHeaders = contentPart\n\t\t\t\t.getHeaders();\n\t\tif (isExternalDescriptor(desc)) {\n\t\t\tupdateVersion(desc, responseHeaders);\n\t\t\tupdateFormat(desc, responseHeaders);\n\t\t\tupdateMimetype(desc, contentHeaders);\n\t\t\tupdateLength(desc, contentHeaders);\n\t\t\tcopyDescriptor(desc, contentBase);\n\t\t} else {\n\t\t\tupdateFormat(contentBase, responseHeaders);\n\t\t\tupdateMimetype(contentBase, contentHeaders);\n\t\t\tupdateLength(contentBase, contentHeaders);\n\t\t}\n\n\t\tmetadataBase.receiveContent(partList.get(0).getEntityAs(\n\t\t\t\tmetadataBase.receiveAs()));\n\n\t\tObject contentEntity = contentPart.getEntityAs(contentBase.receiveAs());\n\t\tcontentBase.receiveContent((reqlog != null) ? reqlog\n\t\t\t\t.copyContent(contentEntity) : contentEntity);\n\n\t\tresponse.close();\n\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic DocumentDescriptor head(RequestLogger reqlog, String uri,\n\t\t\tString transactionId) throws ForbiddenUserException,\n\t\t\tFailedRequestException {\n\t\tClientResponse response = headImpl(reqlog, uri, transactionId, makeDocumentResource(makeDocumentParams(uri,\n\t\t\t\tnull, transactionId, null)));\n\t\t\n\t\t// 404\n\t\tif (response == null) return null;\n\t\t\n\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\n\t\tresponse.close();\n\t\tlogRequest(reqlog, \"checked %s document from %s transaction\", uri,\n\t\t\t\t(transactionId != null) ? transactionId : \"no\");\n\n\t\tDocumentDescriptorImpl desc = new DocumentDescriptorImpl(uri, false);\n\n\t\tupdateVersion(desc, responseHeaders);\n\t\tupdateDescriptor(desc, responseHeaders);\n\n\t\treturn desc;\n\t}\n\t\n\t@Override\n\tpublic boolean exists(String uri) throws ForbiddenUserException,\n\t\t\tFailedRequestException {\n\t\treturn headImpl(null, uri, null, connection.path(uri)) == null ? false : true;\n\t}\n\t\n\tpublic ClientResponse headImpl(RequestLogger reqlog, String uri,\n\t\t\tString transactionId, WebResource webResource) {\n\t\tif (uri == null)\n\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\"Existence check for document identifier without uri\");\n\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Requesting head for {} in transaction {}\", uri,\n\t\t\t\t\ttransactionId);\n\n\t\tWebResource.Builder builder = webResource.getRequestBuilder();\n\t\tbuilder = addTransactionCookie(builder, transactionId);\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n\t\tint retry = 0;\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresponse = builder.head();\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n\t\t}\n\t\tif (status != ClientResponse.Status.OK) {\n\t\t\tif (status == ClientResponse.Status.NOT_FOUND) {\n\t\t\t\tresponse.close();\n\t\t\t\treturn null;\n\t\t\t} else if (status == ClientResponse.Status.FORBIDDEN)\n\t\t\t\tthrow new ForbiddenUserException(\n\t\t\t\t\t\t\"User is not allowed to check the existence of documents\",\n\t\t\t\t\t\textractErrorFields(response));\n\t\t\telse\n\t\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\t\"Document existence check failed: \"\n\t\t\t\t\t\t\t\t+ status.getReasonPhrase(),\n\t\t\t\t\t\textractErrorFields(response));\n\t\t}\n\t\treturn response;\n\t}\n\n\t@Override\n\tpublic void putDocument(RequestLogger reqlog, DocumentDescriptor desc,\n\t\t\tString transactionId, Set categories,\n\t\t\tRequestParameters extraParams,\n\t\t\tDocumentMetadataWriteHandle metadataHandle,\n\t\t\tAbstractWriteHandle contentHandle)\n\t\t\tthrows ResourceNotFoundException, ForbiddenUserException,\n\t\t\tFailedRequestException {\n\t\tif (desc.getUri() == null)\n\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\"Document write for document identifier without uri\");\n\n\t\tHandleImplementation metadataBase = HandleAccessor.checkHandle(\n\t\t\t\tmetadataHandle, \"metadata\");\n\t\tHandleImplementation contentBase = HandleAccessor.checkHandle(\n\t\t\t\tcontentHandle, \"content\");\n\n\t\tString metadataMimetype = null;\n\t\tif (metadataBase != null) {\n\t\t\tmetadataMimetype = metadataBase.getMimetype();\n\t\t}\n\n\t\tFormat descFormat = desc.getFormat();\n\t\tString contentMimetype = (descFormat != null && descFormat != Format.UNKNOWN) ? desc\n\t\t\t\t.getMimetype() : null;\n\t\tif (contentMimetype == null && contentBase != null) {\n\t\t\tFormat contentFormat = contentBase.getFormat();\n\t\t\tif (descFormat != null && descFormat != contentFormat) {\n\t\t\t\tcontentMimetype = descFormat.getDefaultMimetype();\n\t\t\t} else if (contentFormat != null && contentFormat != Format.UNKNOWN) {\n\t\t\t\tcontentMimetype = contentBase.getMimetype();\n\t\t\t}\n\t\t}\n\n\t\tif (metadataBase != null && contentBase != null) {\n\t\t\tputPostDocumentImpl(reqlog, \"put\", desc, transactionId, categories,\n\t\t\t\t\textraParams, metadataMimetype, metadataHandle,\n\t\t\t\t\tcontentMimetype, contentHandle);\n\t\t} else if (metadataBase != null) {\n\t\t\tputPostDocumentImpl(reqlog, \"put\", desc, transactionId, categories, false,\n\t\t\t\t\textraParams, metadataMimetype, metadataHandle);\n\t\t} else if (contentBase != null) {\n\t\t\tputPostDocumentImpl(reqlog, \"put\", desc, transactionId, null, true, \n\t\t\t\t\textraParams, contentMimetype, contentHandle);\n\t\t}\n\t}\n\n\t@Override\n\tpublic DocumentDescriptor postDocument(RequestLogger reqlog, DocumentUriTemplate template,\n\t\t\tString transactionId, Set categories, RequestParameters extraParams,\n\t\t\tDocumentMetadataWriteHandle metadataHandle, AbstractWriteHandle contentHandle)\n\tthrows ResourceNotFoundException, ForbiddenUserException, FailedRequestException {\n\t\tDocumentDescriptorImpl desc = new DocumentDescriptorImpl(false);\n\n\t\tHandleImplementation metadataBase = HandleAccessor.checkHandle(\n\t\t\t\tmetadataHandle, \"metadata\");\n\t\tHandleImplementation contentBase = HandleAccessor.checkHandle(\n\t\t\t\tcontentHandle, \"content\");\n\n\t\tString metadataMimetype = null;\n\t\tif (metadataBase != null) {\n\t\t\tmetadataMimetype = metadataBase.getMimetype();\n\t\t}\n\n\t\tFormat templateFormat = template.getFormat();\n\t\tString contentMimetype = (templateFormat != null && templateFormat != Format.UNKNOWN) ?\n\t\t\t\ttemplate.getMimetype() : null;\n\t\tif (contentMimetype == null && contentBase != null) {\n\t\t\tFormat contentFormat = contentBase.getFormat();\n\t\t\tif (templateFormat != null && templateFormat != contentFormat) {\n\t\t\t\tcontentMimetype = templateFormat.getDefaultMimetype();\n\t\t\t\tdesc.setFormat(templateFormat);\n\t\t\t} else if (contentFormat != null && contentFormat != Format.UNKNOWN) {\n\t\t\t\tcontentMimetype = contentBase.getMimetype();\n\t\t\t\tdesc.setFormat(contentFormat);\n\t\t\t}\n\t\t}\n\t\tdesc.setMimetype(contentMimetype);\n\n\t\tif (extraParams == null)\n\t\t\textraParams = new RequestParameters();\n\n\t\tString extension = template.getExtension();\n\t\tif (extension != null)\n\t\t\textraParams.add(\"extension\", extension);\n\n\t\tString directory = template.getDirectory();\n\t\tif (directory != null)\n\t\t\textraParams.add(\"directory\", directory);\n\n\t\tif (metadataBase != null && contentBase != null) {\n\t\t\tputPostDocumentImpl(reqlog, \"post\", desc, transactionId, categories, extraParams,\n\t\t\t\t\tmetadataMimetype, metadataHandle, contentMimetype, contentHandle);\n\t\t} else if (contentBase != null) {\n\t\t\tputPostDocumentImpl(reqlog, \"post\", desc, transactionId, null, true, extraParams,\n\t\t\t\t\tcontentMimetype, contentHandle);\n\t\t}\n\n\t\treturn desc;\n\t}\n\n\tprivate void putPostDocumentImpl(RequestLogger reqlog, String method, DocumentDescriptor desc,\n\t\t\tString transactionId, Set categories, boolean isOnContent, RequestParameters extraParams,\n\t\t\tString mimetype, AbstractWriteHandle handle)\n\tthrows ResourceNotFoundException, ResourceNotResendableException, ForbiddenUserException,\n\t\t\tFailedRequestException {\n\t\tString uri = desc.getUri();\n\n\t\tHandleImplementation handleBase = HandleAccessor.as(handle);\n\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Sending {} document in transaction {}\",\n\t\t\t\t\t(uri != null) ? uri : \"new\", transactionId);\n\n\t\tlogRequest(\n\t\t\t\treqlog,\n\t\t\t\t\"writing %s document from %s transaction with %s mime type and %s metadata categories\",\n\t\t\t\t(uri != null) ? uri : \"new\",\n\t\t\t\t(transactionId != null) ? transactionId : \"no\",\n\t\t\t\t(mimetype != null) ? mimetype : \"no\",\n\t\t\t\tstringJoin(categories, \", \", \"no\"));\n\n\t\tWebResource webResource = makeDocumentResource(\n\t\t\t\tmakeDocumentParams(\n\t\t\t\t\t\turi, categories, transactionId, extraParams, isOnContent\n\t\t\t\t\t\t));\n\n\t\tWebResource.Builder builder = webResource.type(\n\t\t\t\t(mimetype != null) ? mimetype : MediaType.WILDCARD);\n\t\tbuilder = addTransactionCookie(builder, transactionId);\n\t\tif (uri != null) {\n\t\t\tbuilder = addVersionHeader(desc, builder, \"If-Match\");\n\t\t}\n\n\t\tif (\"patch\".equals(method)) {\n\t\t\tbuilder = builder.header(\"X-HTTP-Method-Override\", \"PATCH\");\n\t\t\tmethod = \"post\";\n\t\t}\n\t\tboolean isResendable = handleBase.isResendable();\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tMultivaluedMap responseHeaders = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n\t\tint retry = 0;\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tObject value = handleBase.sendContent();\n\t\t\tif (value == null)\n\t\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\t\"Document write with null value for \" +\n\t\t\t\t\t\t((uri != null) ? uri : \"new document\"));\n\n\t\t\tif (isFirstRequest && isStreaming(value))\n\t\t\t\tmakeFirstRequest();\n\n\t\t\tif (value instanceof OutputStreamSender) {\n\t\t\t\tStreamingOutput sentStream =\n\t\t\t\t\tnew StreamingOutputImpl((OutputStreamSender) value, reqlog);\n\t\t\t\tresponse =\n\t\t\t\t\t(\"put\".equals(method)) ?\n\t\t\t\t\tbuilder.put(ClientResponse.class, sentStream) :\n\t\t\t\t\tbuilder.post(ClientResponse.class, sentStream);\n\t\t\t} else {\n\t\t\t\tObject sentObj = (reqlog != null) ?\n\t\t\t\t\t\treqlog.copyContent(value) : value;\n\t\t\t\tresponse =\n\t\t\t\t\t(\"put\".equals(method)) ?\n\t\t\t\t\tbuilder.put(ClientResponse.class, sentObj) :\n\t\t\t\t\tbuilder.post(ClientResponse.class, sentObj);\n\t\t\t}\n\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tresponseHeaders = response.getHeaders();\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tresponse.close();\n\n\t\t\tif (!isResendable) {\n\t\t\t\tthrow new ResourceNotResendableException(\n\t\t\t\t\t\t\"Cannot retry request for \" +\n\t\t\t\t\t\t ((uri != null) ? uri : \"new document\"));\n\t\t\t}\n\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n\t\t}\n\t\tif (status == ClientResponse.Status.NOT_FOUND)\n\t\t\tthrow new ResourceNotFoundException(\n\t\t\t\t\t\"Could not write non-existent document\",\n\t\t\t\t\textractErrorFields(response));\n\t\tif (status == ClientResponse.Status.FORBIDDEN) {\n\t\t\tFailedRequest failure = extractErrorFields(response);\n\t\t\tif (failure.getMessageCode().equals(\"RESTAPI-CONTENTNOVERSION\"))\n\t\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\t\"Content version required to write document\", failure);\n\t\t\tthrow new ForbiddenUserException(\n\t\t\t\t\t\"User is not allowed to write documents\", failure);\n\t\t}\n\t\tif (status == ClientResponse.Status.PRECONDITION_FAILED) {\n\t\t\tFailedRequest failure = extractErrorFields(response);\n\t\t\tif (failure.getMessageCode().equals(\"RESTAPI-CONTENTWRONGVERSION\"))\n\t\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\t\"Content version must match to write document\", failure);\n\t\t\telse if (failure.getMessageCode().equals(\"RESTAPI-EMPTYBODY\"))\n\t\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\t\"Empty request body sent to server\", failure);\n\t\t\tthrow new FailedRequestException(\"Precondition Failed\", failure);\n\t\t}\n\t\tif (status != ClientResponse.Status.CREATED\n\t\t\t\t&& status != ClientResponse.Status.NO_CONTENT) {\n\t\t\tthrow new FailedRequestException(\"write failed: \"\n\t\t\t\t\t+ status.getReasonPhrase(), extractErrorFields(response));\n\t\t}\n\n\t\tif (uri == null) {\n\t\t\tString location = responseHeaders.getFirst(\"Location\");\n\t\t\tif (location != null) {\n\t\t\t\tint offset = location.indexOf(DOCUMENT_URI_PREFIX);\n\t\t\t\tif (offset == -1)\n\t\t\t\t\tthrow new MarkLogicInternalException(\n\t\t\t\t\t\t\t\"document create produced invalid location: \" + location);\n\t\t\t\turi = location.substring(offset + DOCUMENT_URI_PREFIX.length());\n\t\t\t\tif (uri == null)\n\t\t\t\t\tthrow new MarkLogicInternalException(\n\t\t\t\t\t\t\t\"document create produced location without uri: \" + location);\n\t\t\t\tdesc.setUri(uri);\n\t\t\t\tupdateVersion(desc, responseHeaders);\n\t\t\t\tupdateDescriptor(desc, responseHeaders);\n\t\t\t}\n\t\t}\n\n\t\tresponse.close();\n\t}\n\n\tprivate void putPostDocumentImpl(RequestLogger reqlog, String method, DocumentDescriptor desc,\n\t\t\tString transactionId, Set categories, RequestParameters extraParams,\n\t\t\tString metadataMimetype, DocumentMetadataWriteHandle metadataHandle, String contentMimetype,\n\t\t\tAbstractWriteHandle contentHandle)\n\tthrows ResourceNotFoundException, ResourceNotResendableException,\n\t\t\tForbiddenUserException, FailedRequestException {\n\t\tString uri = desc.getUri();\n\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Sending {} multipart document in transaction {}\",\n\t\t\t\t\t(uri != null) ? uri : \"new\", transactionId);\n\n\t\tlogRequest(\n\t\t\t\treqlog,\n\t\t\t\t\"writing %s document from %s transaction with %s metadata categories and content\",\n\t\t\t\t(uri != null) ? uri : \"new\",\n\t\t\t\t(transactionId != null) ? transactionId : \"no\",\n\t\t\t\tstringJoin(categories, \", \", \"no\"));\n\n\t\tMultivaluedMap docParams =\n\t\t\tmakeDocumentParams(uri, categories, transactionId, extraParams, true);\n\n\t\tWebResource.Builder builder = makeDocumentResource(docParams).getRequestBuilder();\n\t\tbuilder = addTransactionCookie(builder, transactionId);\n\t\tif (uri != null) {\n\t\t\tbuilder = addVersionHeader(desc, builder, \"If-Match\");\n\t\t}\n\n\t\tMediaType multipartType = Boundary.addBoundary(MultiPartMediaTypes.MULTIPART_MIXED_TYPE);\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tMultivaluedMap responseHeaders = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n\t\tint retry = 0;\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tMultiPart multiPart = new MultiPart();\n\t\t\tboolean hasStreamingPart = addParts(multiPart, reqlog,\n\t\t\t\t\tnew String[] { metadataMimetype, contentMimetype },\n\t\t\t\t\tnew AbstractWriteHandle[] { metadataHandle, contentHandle });\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tmakeFirstRequest();\n\n\t\t\t// Must set multipart/mixed mime type explicitly on each request\n\t\t\t// because Jersey client 1.17 adapter for HttpClient switches\n\t\t\t// to application/octet-stream on retry\n\t\t\tWebResource.Builder requestBlder = builder.type(multipartType);\n\t\t\tresponse =\n\t\t\t\t(\"put\".equals(method)) ?\n\t\t\t\trequestBlder.put(ClientResponse.class, multiPart) :\n\t\t\t\trequestBlder.post(ClientResponse.class, multiPart);\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tresponseHeaders = response.getHeaders();\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tresponse.close();\n\n\t\t\tif (hasStreamingPart) {\n\t\t\t\tthrow new ResourceNotResendableException(\n\t\t\t\t\t\t\"Cannot retry request for \" +\n\t\t\t\t\t\t((uri != null) ? uri : \"new document\"));\n\t\t\t}\n\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n\t\t}\n\t\tif (status == ClientResponse.Status.NOT_FOUND) {\n\t\t\tresponse.close();\n\t\t\tthrow new ResourceNotFoundException(\n\t\t\t\t\t\"Could not write non-existent document\");\n\t\t}\n\t\tif (status == ClientResponse.Status.FORBIDDEN) {\n\t\t\tFailedRequest failure = extractErrorFields(response);\n\t\t\tif (failure.getMessageCode().equals(\"RESTAPI-CONTENTNOVERSION\"))\n\t\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\t\"Content version required to write document\", failure);\n\t\t\tthrow new ForbiddenUserException(\n\t\t\t\t\t\"User is not allowed to write documents\", failure);\n\t\t}\n\t\tif (status == ClientResponse.Status.PRECONDITION_FAILED) {\n\t\t\tFailedRequest failure = extractErrorFields(response);\n\t\t\tif (failure.getMessageCode().equals(\"RESTAPI-CONTENTWRONGVERSION\"))\n\t\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\t\"Content version must match to write document\", failure);\n\t\t\telse if (failure.getMessageCode().equals(\"RESTAPI-EMPTYBODY\"))\n\t\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\t\"Empty request body sent to server\", failure);\n\t\t\tthrow new FailedRequestException(\"Precondition Failed\", failure);\n\t\t}\n\t\tif (status != ClientResponse.Status.CREATED\n\t\t\t\t&& status != ClientResponse.Status.NO_CONTENT) {\n\t\t\tthrow new FailedRequestException(\"write failed: \"\n\t\t\t\t\t+ status.getReasonPhrase(), extractErrorFields(response));\n\t\t}\n\n\t\tif (uri == null) {\n\t\t\tString location = responseHeaders.getFirst(\"Location\");\n\t\t\tif (location != null) {\n\t\t\t\tint offset = location.indexOf(DOCUMENT_URI_PREFIX);\n\t\t\t\tif (offset == -1)\n\t\t\t\t\tthrow new MarkLogicInternalException(\n\t\t\t\t\t\t\t\"document create produced invalid location: \" + location);\n\t\t\t\turi = location.substring(offset + DOCUMENT_URI_PREFIX.length());\n\t\t\t\tif (uri == null)\n\t\t\t\t\tthrow new MarkLogicInternalException(\n\t\t\t\t\t\t\t\"document create produced location without uri: \" + location);\n\t\t\t\tdesc.setUri(uri);\n\t\t\t\tupdateVersion(desc, responseHeaders);\n\t\t\t\tupdateDescriptor(desc, responseHeaders);\n\t\t\t}\n\t\t}\n\n\t\tresponse.close();\n\t}\n\n\t@Override\n\tpublic void patchDocument(RequestLogger reqlog, DocumentDescriptor desc, String transactionId,\n\t\t\tSet categories, boolean isOnContent, DocumentPatchHandle patchHandle)\n\tthrows ResourceNotFoundException, ResourceNotResendableException,\n\t\t\tForbiddenUserException, FailedRequestException {\n\t\tHandleImplementation patchBase = HandleAccessor.checkHandle(\n\t\t\t\tpatchHandle, \"patch\");\n\n\t\tputPostDocumentImpl(reqlog, \"patch\", desc, transactionId, categories, isOnContent, null,\n\t\t\t\tpatchBase.getMimetype(), patchHandle);\n\t}\n\n\t@Override\n\tpublic String openTransaction(String name, int timeLimit)\n\t\t\tthrows ForbiddenUserException, FailedRequestException {\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Opening transaction\");\n\n\t\tMultivaluedMap transParams = null;\n\t\tif (name != null || timeLimit > 0) {\n\t\t\ttransParams = new MultivaluedMapImpl();\n\t\t\tif (name != null)\n\t\t\t\taddEncodedParam(transParams, \"name\", name);\n\t\t\tif (timeLimit > 0)\n\t\t\t\ttransParams.add(\"timeLimit\", String.valueOf(timeLimit));\n\t\t}\n\n\t\tWebResource resource = (transParams != null) ? connection.path(\n\t\t\t\t\"transactions\").queryParams(transParams) : connection\n\t\t\t\t.path(\"transactions\");\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n\t\tint retry = 0;\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresponse = resource.post(ClientResponse.class);\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n\t\t}\n\t\tif (status == ClientResponse.Status.FORBIDDEN)\n\t\t\tthrow new ForbiddenUserException(\n\t\t\t\t\t\"User is not allowed to open transactions\",\n\t\t\t\t\textractErrorFields(response));\n\t\tif (status != ClientResponse.Status.SEE_OTHER)\n\t\t\tthrow new FailedRequestException(\"transaction open failed: \"\n\t\t\t\t\t+ status.getReasonPhrase(), extractErrorFields(response));\n\n\t\tString location = response.getHeaders().getFirst(\"Location\");\n\t\tresponse.close();\n\t\tif (location == null)\n\t\t\tthrow new MarkLogicInternalException(\n\t\t\t\t\t\"transaction open failed to provide location\");\n\t\tif (!location.contains(\"/\"))\n\t\t\tthrow new MarkLogicInternalException(\n\t\t\t\t\t\"transaction open produced invalid location: \" + location);\n\n\t\treturn location.substring(location.lastIndexOf(\"/\") + 1);\n\t}\n\n\t@Override\n\tpublic void commitTransaction(String transactionId)\n\t\t\tthrows ForbiddenUserException, FailedRequestException {\n\t\tcompleteTransaction(transactionId, \"commit\");\n\t}\n\n\t@Override\n\tpublic void rollbackTransaction(String transactionId)\n\t\t\tthrows ForbiddenUserException, FailedRequestException {\n\t\tcompleteTransaction(transactionId, \"rollback\");\n\t}\n\n\tprivate void completeTransaction(String transactionId, String result)\n\t\t\tthrows ForbiddenUserException, FailedRequestException {\n\t\tif (result == null)\n\t\t\tthrow new MarkLogicInternalException(\n\t\t\t\t\t\"transaction completion without operation\");\n\t\tif (transactionId == null)\n\t\t\tthrow new MarkLogicInternalException(\n\t\t\t\t\t\"transaction completion without id: \" + result);\n\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Completing transaction {} with {}\", transactionId,\n\t\t\t\t\tresult);\n\n\t\tMultivaluedMap transParams = new MultivaluedMapImpl();\n\t\ttransParams.add(\"result\", result);\n\n\t\tWebResource webResource = connection.path(\"transactions/\" + transactionId)\n\t\t\t\t.queryParams(transParams);\n\n\t\tWebResource.Builder builder = webResource.getRequestBuilder();\n\t\tbuilder = addTransactionCookie(builder, transactionId);\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n\t\tint retry = 0;\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresponse = builder.post(ClientResponse.class);\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n\t\t}\n\t\tif (status == ClientResponse.Status.FORBIDDEN)\n\t\t\tthrow new ForbiddenUserException(\n\t\t\t\t\t\"User is not allowed to complete transaction with \"\n\t\t\t\t\t\t\t+ result, extractErrorFields(response));\n\t\tif (status != ClientResponse.Status.NO_CONTENT)\n\t\t\tthrow new FailedRequestException(\"transaction \" + result\n\t\t\t\t\t+ \" failed: \" + status.getReasonPhrase(),\n\t\t\t\t\textractErrorFields(response));\n\n\t\tresponse.close();\n\t}\n\n\tprivate MultivaluedMap makeDocumentParams(String uri,\n\t\t\tSet categories, String transactionId,\n\t\t\tRequestParameters extraParams) {\n\t\treturn makeDocumentParams(uri, categories, transactionId, extraParams,\n\t\t\t\tfalse);\n\t}\n\n\tprivate MultivaluedMap makeDocumentParams(String uri,\n\t\t\tSet categories, String transactionId,\n\t\t\tRequestParameters extraParams, boolean withContent) {\n\t\tMultivaluedMap docParams = new MultivaluedMapImpl();\n\t\tif (extraParams != null && extraParams.size() > 0) {\n\t\t\tfor (Map.Entry> entry : extraParams.entrySet()) {\n\t\t\t\tString extraKey = entry.getKey();\n\t\t\t\tif (!\"range\".equalsIgnoreCase(extraKey)) {\n\t\t\t\t\taddEncodedParam(docParams, extraKey, entry.getValue());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\taddEncodedParam(docParams, \"uri\", uri);\n\t\tif (categories == null || categories.size() == 0) {\n\t\t\tdocParams.add(\"category\", \"content\");\n\t\t} else {\n\t\t\tif (withContent)\n\t\t\t\tdocParams.add(\"category\", \"content\");\n\t\t\tif (categories.contains(Metadata.ALL)) {\n\t\t\t\tdocParams.add(\"category\", \"metadata\");\n\t\t\t} else {\n\t\t\t\tfor (Metadata category : categories)\n\t\t\t\t\tdocParams.add(\"category\", category.name().toLowerCase());\n\t\t\t}\n\t\t}\n\t\tif (transactionId != null) {\n\t\t\tdocParams.add(\"txid\", transactionId);\n\t\t}\n\t\treturn docParams;\n\t}\n\n\tprivate WebResource makeDocumentResource(\n\t\t\tMultivaluedMap queryParams) {\n\t\treturn connection.path(\"documents\").queryParams(queryParams);\n\t}\n\n\tprivate boolean isExternalDescriptor(ContentDescriptor desc) {\n\t\treturn desc != null && desc instanceof DocumentDescriptorImpl\n\t\t\t\t&& !((DocumentDescriptorImpl) desc).isInternal();\n\t}\n\n\tprivate void updateDescriptor(ContentDescriptor desc,\n\t\t\tMultivaluedMap headers) {\n\t\tif (desc == null || headers == null)\n\t\t\treturn;\n\n\t\tupdateFormat(desc, headers);\n\t\tupdateMimetype(desc, headers);\n\t\tupdateLength(desc, headers);\n\t}\n\n\tprivate void copyDescriptor(DocumentDescriptor desc,\n\t\t\tHandleImplementation handleBase) {\n\t\tif (handleBase == null)\n\t\t\treturn;\n\n\t\thandleBase.setFormat(desc.getFormat());\n\t\thandleBase.setMimetype(desc.getMimetype());\n\t\thandleBase.setByteLength(desc.getByteLength());\n\t}\n\n\tprivate void updateFormat(ContentDescriptor descriptor,\n\t\t\tMultivaluedMap headers) {\n\t\tupdateFormat(descriptor, getHeaderFormat(headers));\n\t}\n\n\tprivate void updateFormat(ContentDescriptor descriptor, Format format) {\n\t\tif (format != null) {\n\t\t\tdescriptor.setFormat(format);\n\t\t}\n\t}\n\n\tprivate Format getHeaderFormat(MultivaluedMap headers) {\n\t\tif (headers.containsKey(\"vnd.marklogic.document-format\")) {\n\t\t\tList values = headers.get(\"vnd.marklogic.document-format\");\n\t\t\tif (values != null) {\n\t\t\t\treturn Format.valueOf(values.get(0).toUpperCase());\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tprivate void updateMimetype(ContentDescriptor descriptor,\n\t\t\tMultivaluedMap headers) {\n\t\tupdateMimetype(descriptor, getHeaderMimetype(headers));\n\t}\n\n\tprivate void updateMimetype(ContentDescriptor descriptor, String mimetype) {\n\t\tif (mimetype != null) {\n\t\t\tdescriptor.setMimetype(mimetype);\n\t\t}\n\t}\n\n\tprivate String getHeaderMimetype(MultivaluedMap headers) {\n\t\tif (headers.containsKey(\"Content-Type\")) {\n\t\t\tList values = headers.get(\"Content-Type\");\n\t\t\tif (values != null) {\n\t\t\t\tString contentType = values.get(0);\n\t\t\t\tString mimetype = contentType.contains(\";\") ? contentType\n\t\t\t\t\t\t.substring(0, contentType.indexOf(\";\")) : contentType;\n\t\t\t\t// TODO: if \"; charset=foo\" set character set\n\t\t\t\tif (mimetype != null && mimetype.length() > 0) {\n\t\t\t\t\treturn mimetype;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tprivate void updateLength(ContentDescriptor descriptor,\n\t\t\tMultivaluedMap headers) {\n\t\tupdateLength(descriptor, getHeaderLength(headers));\n\t}\n\n\tprivate void updateLength(ContentDescriptor descriptor, long length) {\n\t\tdescriptor.setByteLength(length);\n\t}\n\n\tprivate long getHeaderLength(MultivaluedMap headers) {\n\t\tif (headers.containsKey(\"Content-Length\")) {\n\t\t\tList values = headers.get(\"Content-Length\");\n\t\t\tif (values != null) {\n\t\t\t\treturn Long.valueOf(values.get(0));\n\t\t\t}\n\t\t}\n\t\treturn ContentDescriptor.UNKNOWN_LENGTH;\n\t}\n\n\tprivate void updateVersion(DocumentDescriptor descriptor,\n\t\t\tMultivaluedMap headers) {\n\t\tlong version = DocumentDescriptor.UNKNOWN_VERSION;\n\t\tif (headers.containsKey(\"ETag\")) {\n\t\t\tList values = headers.get(\"ETag\");\n\t\t\tif (values != null) {\n\t\t\t\t// trim the double quotes\n\t\t\t\tString value = values.get(0);\n\t\t\t\tversion = Long.valueOf(value.substring(1, value.length() - 1));\n\t\t\t}\n\t\t}\n\t\tdescriptor.setVersion(version);\n\t}\n\n\tprivate WebResource.Builder addTransactionCookie(\n\t\t\tWebResource.Builder builder, String transactionId) {\n\t\tif (transactionId != null) {\n\t\t\tint pos = transactionId.indexOf(\"_\");\n\t\t\tif (pos != -1) {\n\t\t\t\tString hostId = transactionId.substring(0, pos);\n\t\t\t\tbuilder.cookie(new Cookie(\"HostId\", hostId));\n\t\t\t} else {\n\t\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\t\"transaction id without host id separator: \"+transactionId\n\t\t\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\treturn builder;\n\t}\n\n\tprivate WebResource.Builder addVersionHeader(DocumentDescriptor desc,\n\t\t\tWebResource.Builder builder, String name) {\n\t\tif (desc != null && desc instanceof DocumentDescriptorImpl\n\t\t\t\t&& !((DocumentDescriptorImpl) desc).isInternal()) {\n\t\t\tlong version = desc.getVersion();\n\t\t\tif (version != DocumentDescriptor.UNKNOWN_VERSION) {\n\t\t\t\treturn builder.header(name, \"\\\"\" + String.valueOf(version)\n\t\t\t\t\t\t+ \"\\\"\");\n\t\t\t}\n\t\t}\n\t\treturn builder;\n\t}\n\n\t@Override\n\tpublic T search(RequestLogger reqlog, Class as, QueryDefinition queryDef, String mimetype,\n\t\t\tlong start, long len, QueryView view, String transactionId\n\t) throws ForbiddenUserException, FailedRequestException {\n\t\tMultivaluedMap params = new MultivaluedMapImpl();\n\n\t\tif (start > 1) {\n\t\t\tparams.add(\"start\", Long.toString(start));\n\t\t}\n\n\t\tif (len > 0) {\n\t\t\tparams.add(\"pageLength\", Long.toString(len));\n\t\t}\n\n\t\tif (transactionId != null) {\n\t\t\tparams.add(\"txid\", transactionId);\n\t\t}\n\n\t\tif (view != null && view != QueryView.DEFAULT) {\n\t\t\tif (view == QueryView.ALL) {\n\t\t\t\tparams.add(\"view\", \"all\");\n\t\t\t} else if (view == QueryView.RESULTS) {\n\t\t\t\tparams.add(\"view\", \"results\");\n\t\t\t} else if (view == QueryView.FACETS) {\n\t\t\t\tparams.add(\"view\", \"facets\");\n\t\t\t} else if (view == QueryView.METADATA) {\n\t\t\t\tparams.add(\"view\", \"metadata\");\n\t\t\t}\n\t\t}\n\n\t\tT entity = search(reqlog, as, queryDef, mimetype, params);\n\n\t\tlogRequest(\n\t\t\t\treqlog,\n\t\t\t\t\"searched starting at %s with length %s in %s transaction with %s mime type\",\n\t\t\t\tstart, len, transactionId, mimetype);\n\t\t\n\t\treturn entity;\n\t}\n\t@Override\n\tpublic T search(\n\t\t\tRequestLogger reqlog, Class as, QueryDefinition queryDef, String mimetype, String view\n\t) throws ForbiddenUserException, FailedRequestException {\n\t\tMultivaluedMap params = new MultivaluedMapImpl();\n\n\t\tif (view != null) {\n\t\t\tparams.add(\"view\", view);\n\t\t}\n\n\t\treturn search(reqlog, as, queryDef, mimetype, params);\n\t}\n\tprivate T search(RequestLogger reqlog, Class as, QueryDefinition queryDef, String mimetype,\n\t\t\tMultivaluedMap params\n\t) throws ForbiddenUserException, FailedRequestException {\n\n\t\tString directory = queryDef.getDirectory();\n\t\tif (directory != null) {\n\t\t\taddEncodedParam(params, \"directory\", directory);\n\t\t}\n\n\t\taddEncodedParam(params, \"collection\", queryDef.getCollections());\n\n\t\tString optionsName = queryDef.getOptionsName();\n\t\tif (optionsName != null && optionsName.length() > 0) {\n\t\t\taddEncodedParam(params, \"options\", optionsName);\n\t\t}\n\n\t\tServerTransform transform = queryDef.getResponseTransform();\n\t\tif (transform != null) {\n\t\t\ttransform.merge(params);\n\t\t}\n\n\t\tWebResource.Builder builder = null;\n\t\tString structure = null;\n\t\tHandleImplementation baseHandle = null;\n\n\t\tif (queryDef instanceof RawQueryDefinition) {\n\t\t\tif (logger.isDebugEnabled())\n\t\t\t\tlogger.debug(\"Raw search\");\n\n\t\t\tStructureWriteHandle handle =\n\t\t\t\t((RawQueryDefinition) queryDef).getHandle();\n\n\t\t\tbaseHandle = HandleAccessor.checkHandle(handle, \"search\");\n\n\t\t\tFormat payloadFormat = baseHandle.getFormat();\n\t\t\tif (payloadFormat == Format.UNKNOWN)\n\t\t\t\tpayloadFormat = null;\n\t\t\telse if (payloadFormat != Format.XML && payloadFormat != Format.JSON)\n\t\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\t\"Cannot perform raw search for \"+payloadFormat.name());\n\n\t\t\tString payloadMimetype = baseHandle.getMimetype();\n\t\t\tif (payloadFormat != null) {\n\t\t\t\tif (payloadMimetype == null)\n\t\t\t\t\tpayloadMimetype = payloadFormat.getDefaultMimetype();\n\t\t\t\tparams.add(\"format\", payloadFormat.toString().toLowerCase());\n\t\t\t} else if (payloadMimetype == null) {\n\t\t\t\tpayloadMimetype = \"application/xml\";\n\t\t\t}\n\n\t\t\tString path = (queryDef instanceof RawQueryByExampleDefinition) ?\n\t\t\t\t\t\"qbe\" : \"search\";\n\n\t\t\tWebResource resource = connection.path(path).queryParams(params);\n\t\t\tbuilder = (payloadMimetype != null) ?\n\t\t\t\t\tresource.type(payloadMimetype).accept(mimetype) :\n\t\t\t\t\tresource.accept(mimetype);\n\t\t} else if (queryDef instanceof StringQueryDefinition) {\n\t\t\tString text = ((StringQueryDefinition) queryDef).getCriteria();\n\t\t\tif (logger.isDebugEnabled())\n\t\t\t\tlogger.debug(\"Searching for {}\", text);\n\n\t\t\tif (text != null) {\n\t\t\t\taddEncodedParam(params, \"q\", text);\n\t\t\t}\n\n\t\t\tbuilder = connection.path(\"search\").queryParams(params)\n\t\t\t\t.type(\"application/xml\").accept(mimetype);\n\t\t} else if (queryDef instanceof KeyValueQueryDefinition) {\n\t\t\tif (logger.isDebugEnabled())\n\t\t\t\tlogger.debug(\"Searching for keys/values\");\n\n\t\t\tMap pairs = ((KeyValueQueryDefinition) queryDef);\n\t\t\tfor (Map.Entry entry: pairs.entrySet()) {\n\t\t\t\tValueLocator loc = entry.getKey();\n\t\t\t\tif (loc instanceof KeyLocator) {\n\t\t\t\t\taddEncodedParam(params, \"key\", ((KeyLocator) loc).getKey());\n\t\t\t\t} else {\n\t\t\t\t\tElementLocator eloc = (ElementLocator) loc;\n\t\t\t\t\tparams.add(\"element\", eloc.getElement().toString());\n\t\t\t\t\tif (eloc.getAttribute() != null) {\n\t\t\t\t\t\tparams.add(\"attribute\", eloc.getAttribute().toString());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\taddEncodedParam(params, \"value\", entry.getValue());\n\t\t\t}\n\n\t\t\tbuilder = connection.path(\"keyvalue\").queryParams(params)\n\t\t\t\t\t.accept(mimetype);\n\t\t} else if (queryDef instanceof StructuredQueryDefinition) {\n\t\t\tstructure = ((StructuredQueryDefinition) queryDef).serialize();\n\n\t\t\tif (logger.isDebugEnabled())\n\t\t\t\tlogger.debug(\"Searching for structure {}\", structure);\n\n\t\t\tbuilder = connection.path(\"search\").queryParams(params)\n\t\t\t\t\t.type(\"application/xml\").accept(mimetype);\n\t\t} else if (queryDef instanceof DeleteQueryDefinition) {\n\t\t\tif (logger.isDebugEnabled())\n\t\t\t\tlogger.debug(\"Searching for deletes\");\n\n\t\t\tbuilder = connection.path(\"search\").queryParams(params)\n\t\t\t\t\t.accept(mimetype);\n\t\t} else {\n\t\t\tthrow new UnsupportedOperationException(\"Cannot search with \"\n\t\t\t\t\t+ queryDef.getClass().getName());\n\t\t}\n\n\t\tif (params.containsKey(\"txid\")) {\n\t\t\tbuilder = addTransactionCookie(builder, params.getFirst(\"txid\"));\n\t\t}\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n\t\tint retry = 0;\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (queryDef instanceof StringQueryDefinition) {\n\t\t\t\tresponse = doGet(builder);\n\t\t\t} else if (queryDef instanceof KeyValueQueryDefinition) {\n\t\t\t\tresponse = doGet(builder);\n\t\t\t} else if (queryDef instanceof StructuredQueryDefinition) {\n\t\t\t\tresponse = doPost(reqlog, builder, structure, true);\n\t\t\t} else if (queryDef instanceof DeleteQueryDefinition) {\n\t\t\t\tresponse = doGet(builder);\n\t\t\t} else if (queryDef instanceof RawQueryDefinition) {\n\t\t\t\tresponse = doPost(reqlog, builder, baseHandle.sendContent(), true);\n\t\t\t} else {\n\t\t\t\tthrow new UnsupportedOperationException(\"Cannot search with \"\n\t\t\t\t\t\t+ queryDef.getClass().getName());\n\t\t\t}\n\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n\t\t}\n\t\tif (status == ClientResponse.Status.FORBIDDEN) {\n\t\t\tthrow new ForbiddenUserException(\"User is not allowed to search\",\n\t\t\t\t\textractErrorFields(response));\n\t\t}\n\t\tif (status != ClientResponse.Status.OK) {\n\t\t\tthrow new FailedRequestException(\"search failed: \"\n\t\t\t\t\t+ status.getReasonPhrase(), extractErrorFields(response));\n\t\t}\n\n\t\tT entity = response.hasEntity() ? response.getEntity(as) : null;\n\t\tif (entity == null || (as != InputStream.class && as != Reader.class))\n\t\t\tresponse.close();\n\n\t\treturn entity;\n\t}\n\n\t@Override\n\tpublic void deleteSearch(RequestLogger reqlog, DeleteQueryDefinition queryDef,\n\t\t\tString transactionId) throws ForbiddenUserException,\n\t\t\tFailedRequestException {\n\t\tMultivaluedMap params = new MultivaluedMapImpl();\n\n\t\tif (queryDef.getDirectory() != null) {\n\t\t\taddEncodedParam(params, \"directory\", queryDef.getDirectory());\n\t\t}\n\n\t\taddEncodedParam(params, \"collection\", queryDef.getCollections());\n\n\t\tif (transactionId != null) {\n\t\t\tparams.add(\"txid\", transactionId);\n\t\t}\n\n\t\tWebResource webResource = connection.path(\"search\").queryParams(params);\n\n\t\tWebResource.Builder builder = webResource.getRequestBuilder();\n\t\tbuilder = addTransactionCookie(builder, transactionId);\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n\t\tint retry = 0;\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresponse = builder.delete(ClientResponse.class);\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n\t\t}\n\t\tif (status == ClientResponse.Status.FORBIDDEN) {\n\t\t\tthrow new ForbiddenUserException(\"User is not allowed to delete\",\n\t\t\t\t\textractErrorFields(response));\n\t\t}\n\n\t\tif (status != ClientResponse.Status.NO_CONTENT) {\n\t\t\tthrow new FailedRequestException(\"delete failed: \"\n\t\t\t\t\t+ status.getReasonPhrase(), extractErrorFields(response));\n\t\t}\n\t\t\n\t\tlogRequest(\n\t\t\t\treqlog,\n\t\t\t\t\"deleted search results in %s transaction\",\n\t\t\t\ttransactionId);\n\t}\n\n\t@Override\n\tpublic T values(Class as, ValuesDefinition valDef, String mimetype,\n\t\t\tString transactionId) throws ForbiddenUserException,\n\t\t\tFailedRequestException {\n\t\tMultivaluedMap docParams = new MultivaluedMapImpl();\n\n\t\tString optionsName = valDef.getOptionsName();\n\t\tif (optionsName != null && optionsName.length() > 0) {\n\t\t\taddEncodedParam(docParams, \"options\", optionsName);\n\t\t}\n\n\t\tif (valDef.getAggregate() != null) {\n\t\t\taddEncodedParam(docParams, \"aggregate\", valDef.getAggregate());\n\t\t}\n\n\t\tif (valDef.getAggregatePath() != null) {\n\t\t\taddEncodedParam(docParams, \"aggregatePath\",\n\t\t\t\t\tvalDef.getAggregatePath());\n\t\t}\n\n\t\tif (valDef.getView() != null) {\n\t\t\tdocParams.add(\"view\", valDef.getView());\n\t\t}\n\n\t\tif (valDef.getDirection() != null) {\n\t\t\tif (valDef.getDirection() == ValuesDefinition.Direction.ASCENDING) {\n\t\t\t\tdocParams.add(\"direction\", \"ascending\");\n\t\t\t} else {\n\t\t\t\tdocParams.add(\"direction\", \"descending\");\n\t\t\t}\n\t\t}\n\n\t\tif (valDef.getFrequency() != null) {\n\t\t\tif (valDef.getFrequency() == ValuesDefinition.Frequency.FRAGMENT) {\n\t\t\t\tdocParams.add(\"frequency\", \"fragment\");\n\t\t\t} else {\n\t\t\t\tdocParams.add(\"frequency\", \"item\");\n\t\t\t}\n\t\t}\n\n\t\tHandleImplementation baseHandle = null;\n\n\t\tif (valDef.getQueryDefinition() != null) {\n\t\t\tValueQueryDefinition queryDef = valDef.getQueryDefinition();\n\n\t\t\tif (optionsName == null) {\n\t\t\t\toptionsName = queryDef.getOptionsName();\n\t\t\t\tif (optionsName != null) {\n\t\t\t\t\taddEncodedParam(docParams, \"options\", optionsName);\n\t\t\t\t}\n\t\t\t} else if (queryDef.getOptionsName() != null) {\n\t\t\t\tif (optionsName != queryDef.getOptionsName()\n\t\t\t\t\t\t&& logger.isWarnEnabled())\n\t\t\t\t\tlogger.warn(\"values definition options take precedence over query definition options\");\n\t\t\t}\n\n\t\t\tif (queryDef.getCollections() != null) {\n\t\t\t\tif (logger.isWarnEnabled())\n\t\t\t\t\tlogger.warn(\"collections scope ignored for values query\");\n\t\t\t}\n\t\t\tif (queryDef.getDirectory() != null) {\n\t\t\t\tif (logger.isWarnEnabled())\n\t\t\t\t\tlogger.warn(\"directory scope ignored for values query\");\n\t\t\t}\n\n\t\t\tif (queryDef instanceof StringQueryDefinition) {\n\t\t\t\tString text = ((StringQueryDefinition) queryDef).getCriteria();\n\t\t\t\tif (text != null) {\n\t\t\t\t\taddEncodedParam(docParams, \"q\", text);\n\t\t\t\t}\n\t\t\t} else if (queryDef instanceof StructuredQueryDefinition) {\n\t\t\t\tString structure = ((StructuredQueryDefinition) queryDef)\n\t\t\t\t\t\t.serialize();\n\t\t\t\tif (structure != null) {\n\t\t\t\t\taddEncodedParam(docParams, \"structuredQuery\", structure);\n\t\t\t\t}\n\t\t\t} else if (queryDef instanceof RawQueryDefinition) {\n StructureWriteHandle handle = ((RawQueryDefinition) queryDef).getHandle();\n baseHandle = HandleAccessor.checkHandle(handle, \"values\");\n } else {\n\t\t\t\tif (logger.isWarnEnabled())\n\t\t\t\t\tlogger.warn(\"unsupported query definition: \"\n\t\t\t\t\t\t\t+ queryDef.getClass().getName());\n\t\t\t}\n\n\t\t\tServerTransform transform = queryDef.getResponseTransform();\n\t\t\tif (transform != null) {\n\t\t\t\ttransform.merge(docParams);\n\t\t\t}\n\t\t}\n\n\t\tif (transactionId != null) {\n\t\t\tdocParams.add(\"txid\", transactionId);\n\t\t}\n\n\t\tString uri = \"values\";\n\t\tif (valDef.getName() != null) {\n\t\t\turi += \"/\" + valDef.getName();\n\t\t}\n\n\t\tWebResource.Builder builder = connection.path(uri)\n\t\t\t\t.queryParams(docParams).accept(mimetype);\n\t\tbuilder = addTransactionCookie(builder, transactionId);\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n\t\tint retry = 0;\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n response = baseHandle == null ?\n doGet(builder) :\n doPost(null, builder.type(baseHandle.getMimetype()), baseHandle.sendContent(), baseHandle.isResendable());\n\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n\t\t}\n\t\tif (status == ClientResponse.Status.FORBIDDEN) {\n\t\t\tthrow new ForbiddenUserException(\"User is not allowed to search\",\n\t\t\t\t\textractErrorFields(response));\n\t\t}\n\t\tif (status != ClientResponse.Status.OK) {\n\t\t\tthrow new FailedRequestException(\"search failed: \"\n\t\t\t\t\t+ status.getReasonPhrase(), extractErrorFields(response));\n\t\t}\n\n\t\tT entity = response.hasEntity() ? response.getEntity(as) : null;\n\t\tif (entity == null || (as != InputStream.class && as != Reader.class))\n\t\t\tresponse.close();\n\n\t\treturn entity;\n\t\t\n\t}\n\n\t@Override\n\tpublic T valuesList(Class as, ValuesListDefinition valDef,\n\t\t\tString mimetype, String transactionId)\n\t\t\tthrows ForbiddenUserException, FailedRequestException {\n\t\tMultivaluedMap docParams = new MultivaluedMapImpl();\n\n\t\tString optionsName = valDef.getOptionsName();\n\t\tif (optionsName != null && optionsName.length() > 0) {\n\t\t\taddEncodedParam(docParams, \"options\", optionsName);\n\t\t}\n\n\t\tif (transactionId != null) {\n\t\t\tdocParams.add(\"txid\", transactionId);\n\t\t}\n\n\t\tString uri = \"values\";\n\n\t\tWebResource.Builder builder = connection.path(uri)\n\t\t\t\t.queryParams(docParams).accept(mimetype);\n\t\tbuilder = addTransactionCookie(builder, transactionId);\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n\t\tint retry = 0;\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresponse = builder.get(ClientResponse.class);\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n\t\t}\n\t\tif (status == ClientResponse.Status.FORBIDDEN) {\n\t\t\tthrow new ForbiddenUserException(\"User is not allowed to search\",\n\t\t\t\t\textractErrorFields(response));\n\t\t}\n\t\tif (status != ClientResponse.Status.OK) {\n\t\t\tthrow new FailedRequestException(\"search failed: \"\n\t\t\t\t\t+ status.getReasonPhrase(), extractErrorFields(response));\n\t\t}\n\n\t\tT entity = response.hasEntity() ? response.getEntity(as) : null;\n\t\tif (entity == null || (as != InputStream.class && as != Reader.class))\n\t\t\tresponse.close();\n\n\t\treturn entity;\n\t}\n\n\t@Override\n\tpublic T optionsList(Class as, String mimetype, String transactionId)\n\t\t\tthrows ForbiddenUserException, FailedRequestException {\n\t\tMultivaluedMap docParams = new MultivaluedMapImpl();\n\n\t\tif (transactionId != null) {\n\t\t\tdocParams.add(\"txid\", transactionId);\n\t\t}\n\n\t\tString uri = \"config/query\";\n\n\t\tWebResource.Builder builder = connection.path(uri)\n\t\t\t\t.queryParams(docParams).accept(mimetype);\n\t\tbuilder = addTransactionCookie(builder, transactionId);\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n\t\tint retry = 0;\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresponse = builder.get(ClientResponse.class);\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n\t\t}\n\t\tif (status == ClientResponse.Status.FORBIDDEN) {\n\t\t\tthrow new ForbiddenUserException(\"User is not allowed to search\",\n\t\t\t\t\textractErrorFields(response));\n\t\t}\n\t\tif (status != ClientResponse.Status.OK) {\n\t\t\tthrow new FailedRequestException(\"search failed: \"\n\t\t\t\t\t+ status.getReasonPhrase(), extractErrorFields(response));\n\t\t}\n\n\t\tT entity = response.hasEntity() ? response.getEntity(as) : null;\n\t\tif (entity == null || (as != InputStream.class && as != Reader.class))\n\t\t\tresponse.close();\n\n\t\treturn entity;\n\t}\n\n\t// namespaces, search options etc.\n\t@Override\n\tpublic T getValue(RequestLogger reqlog, String type, String key,\n\t\t\tboolean isNullable, String mimetype, Class as)\n\t\t\tthrows ResourceNotFoundException, ForbiddenUserException,\n\t\t\tFailedRequestException {\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Getting {}/{}\", type, key);\n\n\t\tWebResource.Builder builder = connection.path(type + \"/\" + key).accept(\n\t\t\t\tmimetype);\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n\t\tint retry = 0;\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresponse = builder.get(ClientResponse.class);\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n\t\t}\n\t\tif (status != ClientResponse.Status.OK) {\n\t\t\tif (status == ClientResponse.Status.NOT_FOUND) {\n\t\t\t\tresponse.close();\n\t\t\t\tif (!isNullable)\n\t\t\t\t\tthrow new ResourceNotFoundException(\"Could not get \" + type\n\t\t\t\t\t\t\t+ \"/\" + key);\n\t\t\t\treturn null;\n\t\t\t} else if (status == ClientResponse.Status.FORBIDDEN)\n\t\t\t\tthrow new ForbiddenUserException(\"User is not allowed to read \"\n\t\t\t\t\t\t+ type, extractErrorFields(response));\n\t\t\telse\n\t\t\t\tthrow new FailedRequestException(type + \" read failed: \"\n\t\t\t\t\t\t+ status.getReasonPhrase(),\n\t\t\t\t\t\textractErrorFields(response));\n\t\t}\n\n\t\tlogRequest(reqlog, \"read %s value with %s key and %s mime type\", type,\n\t\t\t\tkey, (mimetype != null) ? mimetype : null);\n\n\t\tT entity = response.hasEntity() ? response.getEntity(as) : null;\n\t\tif (entity == null || (as != InputStream.class && as != Reader.class))\n\t\t\tresponse.close();\n\n\t\treturn (reqlog != null) ? reqlog.copyContent(entity) : entity;\n\t}\n\n\t@Override\n\tpublic T getValues(RequestLogger reqlog, String type, String mimetype, Class as)\n\tthrows ForbiddenUserException, FailedRequestException {\n\t\treturn getValues(reqlog, type, null, mimetype, as);\n\t}\n\t@Override\n\tpublic T getValues(RequestLogger reqlog, String type, RequestParameters extraParams,\n\t\t\tString mimetype, Class as)\n\tthrows ForbiddenUserException, FailedRequestException {\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Getting {}\", type);\n\n\t\tMultivaluedMap requestParams = convertParams(extraParams);\n\n\t\tWebResource.Builder builder = (requestParams == null) ?\n\t\t\t\tconnection.path(type).accept(mimetype) :\n\t\t\t\tconnection.path(type).queryParams(requestParams).accept(mimetype);\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n\t\tint retry = 0;\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresponse = builder.get(ClientResponse.class);\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n\t\t}\n\t\tif (status == ClientResponse.Status.FORBIDDEN) {\n\t\t\tthrow new ForbiddenUserException(\"User is not allowed to read \"\n\t\t\t\t\t+ type, extractErrorFields(response));\n\t\t}\n\t\tif (status != ClientResponse.Status.OK) {\n\t\t\tthrow new FailedRequestException(type + \" read failed: \"\n\t\t\t\t\t+ status.getReasonPhrase(), extractErrorFields(response));\n\t\t}\n\n\t\tlogRequest(reqlog, \"read %s values with %s mime type\", type,\n\t\t\t\t(mimetype != null) ? mimetype : null);\n\n\t\tT entity = response.hasEntity() ? response.getEntity(as) : null;\n\t\tif (entity == null || (as != InputStream.class && as != Reader.class))\n\t\t\tresponse.close();\n\n\t\treturn (reqlog != null) ? reqlog.copyContent(entity) : entity;\n\t}\n\n\t@Override\n\tpublic void postValue(RequestLogger reqlog, String type, String key,\n\t\t\tString mimetype, Object value)\n\t\t\tthrows ResourceNotResendableException, ForbiddenUserException,\n\t\t\tFailedRequestException {\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Posting {}/{}\", type, key);\n\n\t\tputPostValueImpl(reqlog, \"post\", type, key, null, mimetype, value,\n\t\t\t\tClientResponse.Status.CREATED);\n\t}\n\t@Override\n\tpublic void postValue(RequestLogger reqlog, String type, String key,\n\t\t\tRequestParameters extraParams\n\t) throws ResourceNotResendableException, ForbiddenUserException, FailedRequestException\n\t{\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Posting {}/{}\", type, key);\n\n\t\tputPostValueImpl(reqlog, \"post\", type, key, extraParams, null, null,\n\t\t\t\tClientResponse.Status.NO_CONTENT);\n\t}\n\n\n\t@Override\n\tpublic void putValue(RequestLogger reqlog, String type, String key,\n\t\t\tString mimetype, Object value) throws ResourceNotFoundException,\n\t\t\tResourceNotResendableException, ForbiddenUserException,\n\t\t\tFailedRequestException {\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Putting {}/{}\", type, key);\n\n\t\tputPostValueImpl(reqlog, \"put\", type, key, null, mimetype, value,\n\t\t\t\tClientResponse.Status.NO_CONTENT, ClientResponse.Status.CREATED);\n\t}\n\n\t@Override\n\tpublic void putValue(RequestLogger reqlog, String type, String key,\n\t\t\tRequestParameters extraParams, String mimetype, Object value)\n\t\t\tthrows ResourceNotFoundException, ResourceNotResendableException,\n\t\t\tForbiddenUserException, FailedRequestException {\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Putting {}/{}\", type, key);\n\n\t\tputPostValueImpl(reqlog, \"put\", type, key, extraParams, mimetype,\n\t\t\t\tvalue, ClientResponse.Status.NO_CONTENT);\n\t}\n\n\tprivate void putPostValueImpl(RequestLogger reqlog, String method,\n\t\t\tString type, String key, RequestParameters extraParams,\n\t\t\tString mimetype, Object value,\n\t\t\tClientResponse.Status... expectedStatuses) {\n\t\tif (key != null) {\n\t\t\tlogRequest(reqlog, \"writing %s value with %s key and %s mime type\",\n\t\t\t\t\ttype, key, (mimetype != null) ? mimetype : null);\n\t\t} else {\n\t\t\tlogRequest(reqlog, \"writing %s values with %s mime type\", type,\n\t\t\t\t\t(mimetype != null) ? mimetype : null);\n\t\t}\n\n\t\tHandleImplementation handle = (value instanceof HandleImplementation) ?\n\t\t\t\t(HandleImplementation) value : null;\n\n\t\tMultivaluedMap requestParams = convertParams(extraParams);\n\n\t\tString connectPath = null;\n\t\tWebResource.Builder builder = null;\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n\t\tint retry = 0;\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tObject nextValue = (handle != null) ? handle.sendContent() : value;\n\n\t\t\tObject sentValue = null;\n\t\t\tif (nextValue instanceof OutputStreamSender) {\n\t\t\t\tsentValue = new StreamingOutputImpl(\n\t\t\t\t\t\t(OutputStreamSender) nextValue, reqlog);\n\t\t\t} else {\n\t\t\t\tif (reqlog != null && retry == 0)\n\t\t\t\t\tsentValue = reqlog.copyContent(nextValue);\n\t\t\t\telse\n\t\t\t\t\tsentValue = nextValue;\n\t\t\t}\n\n\t\t\tboolean isStreaming = (isFirstRequest || handle == null) ? isStreaming(sentValue)\n\t\t\t\t\t: false;\n\n\t\t\tboolean isResendable = (handle == null) ? !isStreaming :\n\t\t\t\thandle.isResendable();\n\n\t\t\tif (\"put\".equals(method)) {\n\t\t\t\tif (isFirstRequest && isStreaming)\n\t\t\t\t\tmakeFirstRequest();\n\n\t\t\t\tif (builder == null) {\n\t\t\t\t\tconnectPath = (key != null) ? type + \"/\" + key : type;\n\t\t\t\t\tWebResource resource = (requestParams == null) ?\n\t\t\t\t\t\tconnection.path(connectPath) :\n\t\t\t\t\t\tconnection.path(connectPath).queryParams(requestParams);\n\t\t\t\t\tbuilder = (mimetype == null) ?\n\t\t\t\t\t\tresource.getRequestBuilder() : resource.type(mimetype);\n\t\t\t\t}\n\n\t\t\t\tresponse = (sentValue == null) ?\n\t\t\t\t\t\tbuilder.put(ClientResponse.class) :\n\t\t\t\t\t\tbuilder.put(ClientResponse.class, sentValue);\n\t\t\t} else if (\"post\".equals(method)) {\n\t\t\t\tif (isFirstRequest && isStreaming)\n\t\t\t\t\tmakeFirstRequest();\n\n\t\t\t\tif (builder == null) {\n\t\t\t\t\tconnectPath = type;\n\t\t\t\t\tWebResource resource = (requestParams == null) ?\n\t\t\t\t\t\tconnection.path(connectPath) :\n\t\t\t\t\t\tconnection.path(connectPath).queryParams(requestParams);\n\t\t\t\t\tbuilder = (mimetype == null) ?\n\t\t\t\t\t\tresource.getRequestBuilder() : resource.type(mimetype);\n\t\t\t\t}\n\n\t\t\t\tresponse = (sentValue == null) ?\n\t\t\t\t\tbuilder.post(ClientResponse.class) :\n\t\t\t\t\tbuilder.post(ClientResponse.class, sentValue);\n\t\t\t} else {\n\t\t\t\tthrow new MarkLogicInternalException(\"unknown method type \"\n\t\t\t\t\t\t+ method);\n\t\t\t}\n\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tresponse.close();\n\n\t\t\tif (!isResendable) {\n\t\t\t\tthrow new ResourceNotResendableException(\n\t\t\t\t\t\t\"Cannot retry request for \" + connectPath);\n\t\t\t}\n\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n\t\t}\n\t\tif (status == ClientResponse.Status.FORBIDDEN)\n\t\t\tthrow new ForbiddenUserException(\"User is not allowed to write \"\n\t\t\t\t\t+ type, extractErrorFields(response));\n\t\tif (status == ClientResponse.Status.NOT_FOUND)\n\t\t\tthrow new ResourceNotFoundException(type + \" not found for write\",\n\t\t\t\t\textractErrorFields(response));\n\t\tboolean statusOk = false;\n\t\tfor (ClientResponse.Status expectedStatus : expectedStatuses) {\n\t\t\tstatusOk = statusOk || (status == expectedStatus);\n\t\t\tif (statusOk) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (!statusOk) {\n\t\t\tthrow new FailedRequestException(type + \" write failed: \"\n\t\t\t\t\t+ status.getReasonPhrase(), extractErrorFields(response));\n\t\t}\n\t\tresponse.close();\n\n\t}\n\n\t@Override\n\tpublic void deleteValue(RequestLogger reqlog, String type, String key)\n\t\t\tthrows ResourceNotFoundException, ForbiddenUserException,\n\t\t\tFailedRequestException {\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Deleting {}/{}\", type, key);\n\n\t\tWebResource builder = connection.path(type + \"/\" + key);\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n\t\tint retry = 0;\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresponse = builder.delete(ClientResponse.class);\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n\t\t}\n\t\tif (status == ClientResponse.Status.FORBIDDEN)\n\t\t\tthrow new ForbiddenUserException(\"User is not allowed to delete \"\n\t\t\t\t\t+ type, extractErrorFields(response));\n\t\tif (status == ClientResponse.Status.NOT_FOUND)\n\t\t\tthrow new ResourceNotFoundException(type + \" not found for delete\",\n\t\t\t\t\textractErrorFields(response));\n\t\tif (status != ClientResponse.Status.NO_CONTENT)\n\t\t\tthrow new FailedRequestException(\"delete failed: \"\n\t\t\t\t\t+ status.getReasonPhrase(), extractErrorFields(response));\n\n\t\tresponse.close();\n\n\t\tlogRequest(reqlog, \"deleted %s value with %s key\", type, key);\n\t}\n\n\t@Override\n\tpublic void deleteValues(RequestLogger reqlog, String type)\n\t\t\tthrows ForbiddenUserException, FailedRequestException {\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Deleting {}\", type);\n\n\t\tWebResource builder = connection.path(type);\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n\t\tint retry = 0;\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresponse = builder.delete(ClientResponse.class);\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n\t\t}\n\t\tif (status == ClientResponse.Status.FORBIDDEN)\n\t\t\tthrow new ForbiddenUserException(\"User is not allowed to delete \"\n\t\t\t\t\t+ type, extractErrorFields(response));\n\t\tif (status != ClientResponse.Status.NO_CONTENT)\n\t\t\tthrow new FailedRequestException(\"delete failed: \"\n\t\t\t\t\t+ status.getReasonPhrase(), extractErrorFields(response));\n\t\tresponse.close();\n\n\t\tlogRequest(reqlog, \"deleted %s values\", type);\n\t}\n\n\t@Override\n\tpublic R getResource(RequestLogger reqlog,\n\t\t\tString path, RequestParameters params, R output)\n\t\t\tthrows ResourceNotFoundException, ForbiddenUserException,\n\t\t\tFailedRequestException {\n\t\tHandleImplementation outputBase = HandleAccessor.checkHandle(output,\n\t\t\t\t\"read\");\n\n\t\tString mimetype = outputBase.getMimetype();\n\t\tClass as = outputBase.receiveAs();\n\n\t\tWebResource.Builder builder = makeGetBuilder(path, params, mimetype);\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n\t\tint retry = 0;\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresponse = doGet(builder);\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n\t\t}\n\t\tcheckStatus(response, status, \"read\", \"resource\", path,\n\t\t\t\tResponseStatus.OK_OR_NO_CONTENT);\n\n\t\tif (as != null) {\n\t\t\toutputBase.receiveContent(makeResult(reqlog, \"read\", \"resource\",\n\t\t\t\t\tresponse, as));\n\t\t} else {\n\t\t\tresponse.close();\n\t\t}\n\n\t\treturn output;\n\t}\n\n\t@Override\n\tpublic ServiceResultIterator getIteratedResource(RequestLogger reqlog,\n\t\t\tString path, RequestParameters params, String... mimetypes)\n\t\t\tthrows ResourceNotFoundException, ForbiddenUserException,\n\t\t\tFailedRequestException {\n\n\t\tWebResource.Builder builder = makeGetBuilder(path, params, null);\n\n\t\tMediaType multipartType = Boundary.addBoundary(MultiPartMediaTypes.MULTIPART_MIXED_TYPE);\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n\t\tint retry = 0;\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresponse = doGet(builder.accept(multipartType));\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n\t\t}\n\n\t\tcheckStatus(response, status, \"read\", \"resource\", path,\n\t\t\t\tResponseStatus.OK_OR_NO_CONTENT);\n\n\t\treturn makeResults(reqlog, \"read\", \"resource\", response);\n\t}\n\n\t@Override\n\tpublic R putResource(RequestLogger reqlog,\n\t\t\tString path, RequestParameters params, AbstractWriteHandle input,\n\t\t\tR output) throws ResourceNotFoundException,\n\t\t\tResourceNotResendableException, ForbiddenUserException,\n\t\t\tFailedRequestException {\n\t\tHandleImplementation inputBase = HandleAccessor.checkHandle(input,\n\t\t\t\t\"write\");\n\t\tHandleImplementation outputBase = HandleAccessor.checkHandle(output,\n\t\t\t\t\"read\");\n\n\t\tString inputMimetype = inputBase.getMimetype();\n\t\tboolean isResendable = inputBase.isResendable();\n\t\tString outputMimeType = null;\n\t\tClass as = null;\n\t\tif (outputBase != null) {\n\t\t\toutputMimeType = outputBase.getMimetype();\n\t\t\n\t\t\tas = outputBase.receiveAs();\n\t\t}\n\t\tWebResource.Builder builder = makePutBuilder(path, params,\n\t\t\t\tinputMimetype, outputMimeType);\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n\t\tint retry = 0;\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresponse = doPut(reqlog, builder, inputBase.sendContent(),\n\t\t\t\t\t!isResendable);\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tresponse.close();\n\n\t\t\tif (!isResendable) {\n\t\t\t\tthrow new ResourceNotResendableException(\n\t\t\t\t\t\t\"Cannot retry request for \" + path);\n\t\t\t}\n\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n\t\t}\n\n\t\tcheckStatus(response, status, \"write\", \"resource\", path,\n\t\t\t\tResponseStatus.OK_OR_CREATED_OR_NO_CONTENT);\n\n\t\tif (as != null) {\n\t\t\toutputBase.receiveContent(makeResult(reqlog, \"write\", \"resource\",\n\t\t\t\t\tresponse, as));\n\t\t} else {\n\t\t\tresponse.close();\n\t\t}\n\n\t\treturn output;\n\t}\n\n\t@Override\n\tpublic R putResource(\n\t\t\tRequestLogger reqlog, String path, RequestParameters params,\n\t\t\tW[] input, R output) throws ResourceNotFoundException,\n\t\t\tResourceNotResendableException, ForbiddenUserException,\n\t\t\tFailedRequestException {\n\t\tif (input == null || input.length == 0)\n\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\"input not specified for multipart\");\n\n\t\tHandleImplementation outputBase = HandleAccessor.checkHandle(output,\n\t\t\t\t\"read\");\n\n\t\tString outputMimetype = outputBase.getMimetype();\n\t\tClass as = outputBase.receiveAs();\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n\t\tint retry = 0;\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tMultiPart multiPart = new MultiPart();\n\t\t\tboolean hasStreamingPart = addParts(multiPart, reqlog, input);\n\n\t\t\tWebResource.Builder builder = makePutBuilder(path, params,\n\t\t\t\t\tmultiPart, outputMimetype);\n\n\t\t\tresponse = doPut(builder, multiPart, hasStreamingPart);\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tresponse.close();\n\n\t\t\tif (hasStreamingPart) {\n\t\t\t\tthrow new ResourceNotResendableException(\n\t\t\t\t\t\t\"Cannot retry request for \" + path);\n\t\t\t}\n\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n\t\t}\n\n\t\tcheckStatus(response, status, \"write\", \"resource\", path,\n\t\t\t\tResponseStatus.OK_OR_CREATED_OR_NO_CONTENT);\n\n\t\tif (as != null) {\n\t\t\toutputBase.receiveContent(makeResult(reqlog, \"write\", \"resource\",\n\t\t\t\t\tresponse, as));\n\t\t} else {\n\t\t\tresponse.close();\n\t\t}\n\n\t\treturn output;\n\t}\n\n\t@Override\n\tpublic R postResource(RequestLogger reqlog,\n\t\t\tString path, RequestParameters params, AbstractWriteHandle input,\n\t\t\tR output) throws ResourceNotFoundException,\n\t\t\tResourceNotResendableException, ForbiddenUserException,\n\t\t\tFailedRequestException {\n\t\tHandleImplementation inputBase = HandleAccessor.checkHandle(input,\n\t\t\t\t\"write\");\n\t\tHandleImplementation outputBase = HandleAccessor.checkHandle(output,\n\t\t\t\t\"read\");\n\n\t\tString inputMimetype = inputBase.getMimetype();\n\t\tString outputMimetype = outputBase.getMimetype();\n\t\tboolean isResendable = inputBase.isResendable();\n\t\tClass as = outputBase.receiveAs();\n\n\t\tWebResource.Builder builder = makePostBuilder(path, params,\n\t\t\t\tinputMimetype, outputMimetype);\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n\t\tint retry = 0;\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresponse = doPost(reqlog, builder, inputBase.sendContent(),\n\t\t\t\t\t!isResendable);\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tresponse.close();\n\n\t\t\tif (!isResendable) {\n\t\t\t\tthrow new ResourceNotResendableException(\n\t\t\t\t\t\t\"Cannot retry request for \" + path);\n\t\t\t}\n\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n\t\t}\n\n\t\tcheckStatus(response, status, \"apply\", \"resource\", path,\n\t\t\t\tResponseStatus.OK_OR_CREATED_OR_NO_CONTENT);\n\n\t\tif (as != null) {\n\t\t\toutputBase.receiveContent(makeResult(reqlog, \"apply\", \"resource\",\n\t\t\t\t\tresponse, as));\n\t\t} else {\n\t\t\tresponse.close();\n\t\t}\n\n\t\treturn output;\n\t}\n\n\t@Override\n\tpublic R postResource(\n\t\t\tRequestLogger reqlog, String path, RequestParameters params,\n\t\t\tW[] input, R output) throws ResourceNotFoundException,\n\t\t\tResourceNotResendableException, ForbiddenUserException,\n\t\t\tFailedRequestException {\n\t\tHandleImplementation outputBase = HandleAccessor.checkHandle(output,\n\t\t\t\t\"read\");\n\n\t\tString outputMimetype = outputBase.getMimetype();\n\t\tClass as = outputBase.receiveAs();\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n\t\tint retry = 0;\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tMultiPart multiPart = new MultiPart();\n\t\t\tboolean hasStreamingPart = addParts(multiPart, reqlog, input);\n\n\t\t\tWebResource.Builder builder = makePostBuilder(path, params,\n\t\t\t\t\tmultiPart, outputMimetype);\n\n\t\t\tresponse = doPost(builder, multiPart, hasStreamingPart);\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tresponse.close();\n\n\t\t\tif (hasStreamingPart) {\n\t\t\t\tthrow new ResourceNotResendableException(\n\t\t\t\t\t\t\"Cannot retry request for \" + path);\n\t\t\t}\n\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n\t\t}\n\n\t\tcheckStatus(response, status, \"apply\", \"resource\", path,\n\t\t\t\tResponseStatus.OK_OR_CREATED_OR_NO_CONTENT);\n\n\t\tif (as != null) {\n\t\t\toutputBase.receiveContent(makeResult(reqlog, \"apply\", \"resource\",\n\t\t\t\t\tresponse, as));\n\t\t} else {\n\t\t\tresponse.close();\n\t\t}\n\n\t\treturn output;\n\t}\n\n\t@Override\n\tpublic ServiceResultIterator postIteratedResource(RequestLogger reqlog,\n\t\t\tString path, RequestParameters params, AbstractWriteHandle input,\n\t\t\tString... outputMimetypes) throws ResourceNotFoundException,\n\t\t\tResourceNotResendableException, ForbiddenUserException,\n\t\t\tFailedRequestException {\n\t\tHandleImplementation inputBase = HandleAccessor.checkHandle(input,\n\t\t\t\t\"write\");\n\n\t\tString inputMimetype = inputBase.getMimetype();\n\t\tboolean isResendable = inputBase.isResendable();\n\n\t\tWebResource.Builder builder = makePostBuilder(path, params, inputMimetype, null);\n\n\t\tMediaType multipartType = Boundary.addBoundary(MultiPartMediaTypes.MULTIPART_MIXED_TYPE);\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n\t\tint retry = 0;\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tObject value = inputBase.sendContent();\n\n\t\t\tresponse = doPost(reqlog, builder.accept(multipartType), value, !isResendable);\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tresponse.close();\n\n\t\t\tif (!isResendable) {\n\t\t\t\tthrow new ResourceNotResendableException(\n\t\t\t\t\t\t\"Cannot retry request for \" + path);\n\t\t\t}\n\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n\t\t}\n\n\t\tcheckStatus(response, status, \"apply\", \"resource\", path,\n\t\t\t\tResponseStatus.OK_OR_CREATED_OR_NO_CONTENT);\n\n\t\treturn makeResults(reqlog, \"apply\", \"resource\", response);\n\t}\n\n\t@Override\n\tpublic ServiceResultIterator postIteratedResource(\n\t\t\tRequestLogger reqlog, String path, RequestParameters params,\n\t\t\tW[] input, String... outputMimetypes)\n\t\t\tthrows ResourceNotFoundException, ResourceNotResendableException,\n\t\t\tForbiddenUserException, FailedRequestException {\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n\t\tint retry = 0;\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tMultiPart multiPart = new MultiPart();\n\t\t\tboolean hasStreamingPart = addParts(multiPart, reqlog, input);\n\n\t\t\tWebResource.Builder builder = makePostBuilder(\n\t\t\t\t\tpath,\n\t\t\t\t\tparams,\n\t\t\t\t\tmultiPart,\n\t\t\t\t\tBoundary.addBoundary(MultiPartMediaTypes.MULTIPART_MIXED_TYPE));\n\n\t\t\tresponse = doPost(builder, multiPart, hasStreamingPart);\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tresponse.close();\n\n\t\t\tif (hasStreamingPart) {\n\t\t\t\tthrow new ResourceNotResendableException(\n\t\t\t\t\t\t\"Cannot retry request for \" + path);\n\t\t\t}\n\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n\t\t}\n\n\t\tcheckStatus(response, status, \"apply\", \"resource\", path,\n\t\t\t\tResponseStatus.OK_OR_CREATED_OR_NO_CONTENT);\n\n\t\treturn makeResults(reqlog, \"apply\", \"resource\", response);\n\t}\n\n\t@Override\n\tpublic R deleteResource(\n\t\t\tRequestLogger reqlog, String path, RequestParameters params,\n\t\t\tR output) throws ResourceNotFoundException, ForbiddenUserException,\n\t\t\tFailedRequestException {\n\t\tHandleImplementation outputBase = HandleAccessor.checkHandle(output,\n\t\t\t\t\"read\");\n\n\t\tString outputMimeType = null;\n\t\tClass as = null;\n\t\tif (outputBase != null) {\n\t\t\toutputMimeType = outputBase.getMimetype();\n\t\t\tas = outputBase.receiveAs();\n\t\t}\n\t\tWebResource.Builder builder = makeDeleteBuilder(reqlog, path, params,\n\t\t\t\toutputMimeType);\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n\t\tint retry = 0;\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresponse = doDelete(builder);\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n\t\t}\n\n\t\tcheckStatus(response, status, \"delete\", \"resource\", path,\n\t\t\t\tResponseStatus.OK_OR_NO_CONTENT);\n\n\t\tif (as != null) {\n\t\t\toutputBase.receiveContent(makeResult(reqlog, \"delete\", \"resource\",\n\t\t\t\t\tresponse, as));\n\t\t} else {\n\t\t\tresponse.close();\n\t\t}\n\n\t\treturn output;\n\t}\n\n\tprivate WebResource.Builder makeGetBuilder(String path,\n\t\t\tRequestParameters params, Object mimetype) {\n\t\tif (path == null)\n\t\t\tthrow new IllegalArgumentException(\"Read with null path\");\n\n\t\tWebResource.Builder builder = makeBuilder(path, convertParams(params),\n\t\t\t\tnull, mimetype);\n\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(String.format(\"Getting %s as %s\", path, mimetype));\n\n\t\treturn builder;\n\t}\n\n\tprivate ClientResponse doGet(WebResource.Builder builder) {\n\t\tClientResponse response = builder.get(ClientResponse.class);\n\n\t\tif (isFirstRequest)\n\t\t\tisFirstRequest = false;\n\n\t\treturn response;\n\t}\n\n\tprivate WebResource.Builder makePutBuilder(String path,\n\t\t\tRequestParameters params, String inputMimetype,\n\t\t\tString outputMimetype) {\n\t\tif (path == null)\n\t\t\tthrow new IllegalArgumentException(\"Write with null path\");\n\n\t\tWebResource.Builder builder = makeBuilder(path, convertParams(params),\n\t\t\t\tinputMimetype, outputMimetype);\n\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Putting {}\", path);\n\n\t\treturn builder;\n\t}\n\n\tprivate ClientResponse doPut(RequestLogger reqlog,\n\t\t\tWebResource.Builder builder, Object value, boolean isStreaming) {\n\t\tif (value == null)\n\t\t\tthrow new IllegalArgumentException(\"Resource write with null value\");\n\n\t\tif (isFirstRequest && isStreaming(value))\n\t\t\tmakeFirstRequest();\n\n\t\tClientResponse response = null;\n\t\tif (value instanceof OutputStreamSender) {\n\t\t\tresponse = builder\n\t\t\t\t\t.put(ClientResponse.class, new StreamingOutputImpl(\n\t\t\t\t\t\t\t(OutputStreamSender) value, reqlog));\n\t\t} else {\n\t\t\tif (reqlog != null)\n\t\t\t\tresponse = builder.put(ClientResponse.class,\n\t\t\t\t\t\treqlog.copyContent(value));\n\t\t\telse\n\t\t\t\tresponse = builder.put(ClientResponse.class, value);\n\t\t}\n\n\t\tif (isFirstRequest)\n\t\t\tisFirstRequest = false;\n\n\t\treturn response;\n\t}\n\n\tprivate WebResource.Builder makePutBuilder(String path,\n\t\t\tRequestParameters params, MultiPart multiPart, String outputMimetype) {\n\t\tif (path == null)\n\t\t\tthrow new IllegalArgumentException(\"Write with null path\");\n\n\t\tWebResource.Builder builder = makeBuilder(path, convertParams(params),\n\t\t\t\tBoundary.addBoundary(MultiPartMediaTypes.MULTIPART_MIXED_TYPE),\n\t\t\t\toutputMimetype);\n\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Putting multipart for {}\", path);\n\n\t\treturn builder;\n\t}\n\n\tprivate ClientResponse doPut(WebResource.Builder builder,\n\t\t\tMultiPart multiPart, boolean hasStreamingPart) {\n\t\tif (isFirstRequest)\n\t\t\tmakeFirstRequest();\n\n\t\tClientResponse response = builder.put(ClientResponse.class, multiPart);\n\n\t\tif (isFirstRequest)\n\t\t\tisFirstRequest = false;\n\n\t\treturn response;\n\t}\n\n\tprivate WebResource.Builder makePostBuilder(String path,\n\t\t\tRequestParameters params, Object inputMimetype,\n\t\t\tObject outputMimetype) {\n\t\tif (path == null)\n\t\t\tthrow new IllegalArgumentException(\"Apply with null path\");\n\n\t\tWebResource.Builder builder = makeBuilder(path, convertParams(params),\n\t\t\t\tinputMimetype, outputMimetype);\n\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Posting {}\", path);\n\n\t\treturn builder;\n\t}\n\n\tprivate ClientResponse doPost(RequestLogger reqlog,\n\t\t\tWebResource.Builder builder, Object value, boolean isStreaming) {\n\t\tif (isFirstRequest && isStreaming(value))\n\t\t\tmakeFirstRequest();\n\n\t\tClientResponse response = null;\n\t\tif (value instanceof OutputStreamSender) {\n\t\t\tresponse = builder\n\t\t\t\t\t.post(ClientResponse.class, new StreamingOutputImpl(\n\t\t\t\t\t\t\t(OutputStreamSender) value, reqlog));\n\t\t} else {\n\t\t\tif (reqlog != null)\n\t\t\t\tresponse = builder.post(ClientResponse.class,\n\t\t\t\t\t\treqlog.copyContent(value));\n\t\t\telse\n\t\t\t\tresponse = builder.post(ClientResponse.class, value);\n\t\t}\n\n\t\tif (isFirstRequest)\n\t\t\tisFirstRequest = false;\n\n\t\treturn response;\n\t}\n\n\tprivate WebResource.Builder makePostBuilder(String path,\n\t\t\tRequestParameters params, MultiPart multiPart, Object outputMimetype) {\n\t\tif (path == null)\n\t\t\tthrow new IllegalArgumentException(\"Apply with null path\");\n\n\t\tWebResource.Builder builder = makeBuilder(path, convertParams(params),\n\t\t\t\tBoundary.addBoundary(MultiPartMediaTypes.MULTIPART_MIXED_TYPE),\n\t\t\t\toutputMimetype);\n\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Posting multipart for {}\", path);\n\n\t\treturn builder;\n\t}\n\n\tprivate ClientResponse doPost(WebResource.Builder builder,\n\t\t\tMultiPart multiPart, boolean hasStreamingPart) {\n\t\tif (isFirstRequest)\n\t\t\tmakeFirstRequest();\n\n\t\tClientResponse response = builder.post(ClientResponse.class, multiPart);\n\n\t\tif (isFirstRequest)\n\t\t\tisFirstRequest = false;\n\n\t\treturn response;\n\t}\n\n\tprivate WebResource.Builder makeDeleteBuilder(RequestLogger reqlog,\n\t\t\tString path, RequestParameters params, String mimetype) {\n\t\tif (path == null)\n\t\t\tthrow new IllegalArgumentException(\"Delete with null path\");\n\n\t\tWebResource.Builder builder = makeBuilder(path, convertParams(params),\n\t\t\t\tnull, mimetype);\n\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Deleting {}\", path);\n\n\t\treturn builder;\n\t}\n\n\tprivate ClientResponse doDelete(WebResource.Builder builder) {\n\t\tClientResponse response = builder.delete(ClientResponse.class);\n\n\t\tif (isFirstRequest)\n\t\t\tisFirstRequest = false;\n\n\t\treturn response;\n\t}\n\n\tprivate MultivaluedMap convertParams(\n\t\t\tRequestParameters params) {\n\t\tif (params == null || params.size() == 0)\n\t\t\treturn null;\n\n\t\tMultivaluedMap requestParams = new MultivaluedMapImpl();\n\t\tfor (Map.Entry> entry : params.entrySet()) {\n\t\t\taddEncodedParam(requestParams, entry.getKey(), entry.getValue());\n\t\t}\n\n\t\treturn requestParams;\n\t}\n\n\tprivate void addEncodedParam(MultivaluedMap params,\n\t\t\tString key, List values) {\n\t\tList encodedParams = encodeParamValues(values);\n\t\tif (encodedParams != null && encodedParams.size() > 0)\n\t\t\tparams.put(key, encodedParams);\n\t}\n\n\tprivate void addEncodedParam(MultivaluedMap params,\n\t\t\tString key, String[] values) {\n\t\tList encodedParams = encodeParamValues(values);\n\t\tif (encodedParams != null && encodedParams.size() > 0)\n\t\t\tparams.put(key, encodedParams);\n\t}\n\n\tprivate void addEncodedParam(MultivaluedMap params,\n\t\t\tString key, String value) {\n\t\tvalue = encodeParamValue(value);\n\t\tif (value == null)\n\t\t\treturn;\n\n\t\tparams.add(key, value);\n\t}\n\n\tprivate List encodeParamValues(List oldValues) {\n\t\tif (oldValues == null)\n\t\t\treturn null;\n\n\t\tint oldSize = oldValues.size();\n\t\tif (oldSize == 0)\n\t\t\treturn null;\n\n\t\tList newValues = new ArrayList(oldSize);\n\t\tfor (String value : oldValues) {\n\t\t\tString newValue = encodeParamValue(value);\n\t\t\tif (newValue == null)\n\t\t\t\tcontinue;\n\t\t\tnewValues.add(newValue);\n\t\t}\n\n\t\treturn newValues;\n\t}\n\n\tprivate List encodeParamValues(String[] oldValues) {\n\t\tif (oldValues == null)\n\t\t\treturn null;\n\n\t\tint oldSize = oldValues.length;\n\t\tif (oldSize == 0)\n\t\t\treturn null;\n\n\t\tList newValues = new ArrayList(oldSize);\n\t\tfor (String value : oldValues) {\n\t\t\tString newValue = encodeParamValue(value);\n\t\t\tif (newValue == null)\n\t\t\t\tcontinue;\n\t\t\tnewValues.add(newValue);\n\t\t}\n\n\t\treturn newValues;\n\t}\n\n\tprivate String encodeParamValue(String value) {\n\t\tif (value == null)\n\t\t\treturn null;\n\n\t\treturn UriComponent.encode(value, UriComponent.Type.QUERY_PARAM)\n\t\t\t\t.replace(\"+\", \"%20\");\n\t}\n\n\tprivate boolean addParts(\n\t\t\tMultiPart multiPart, RequestLogger reqlog, W[] input) {\n\t\treturn addParts(multiPart, reqlog, null, input);\n\t}\n\n\tprivate boolean addParts(\n\t\t\tMultiPart multiPart, RequestLogger reqlog, String[] mimetypes,\n\t\t\tW[] input) {\n\t\tif (mimetypes != null && mimetypes.length != input.length)\n\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\"Mismatch between mimetypes and input\");\n\n\t\tmultiPart.setMediaType(new MediaType(\"multipart\", \"mixed\"));\n\n\t\tboolean hasStreamingPart = false;\n\t\tfor (int i = 0; i < input.length; i++) {\n\t\t\tAbstractWriteHandle handle = input[i];\n\t\t\tHandleImplementation handleBase = HandleAccessor.checkHandle(\n\t\t\t\t\thandle, \"write\");\n\t\t\tObject value = handleBase.sendContent();\n\t\t\tString inputMimetype = (mimetypes != null) ? mimetypes[i]\n\t\t\t\t\t: handleBase.getMimetype();\n\n\t\t\tif (!hasStreamingPart)\n\t\t\t\thasStreamingPart = !handleBase.isResendable();\n\n\t\t\tString[] typeParts = (inputMimetype != null && inputMimetype\n\t\t\t\t\t.contains(\"/\")) ? inputMimetype.split(\"/\", 2) : null;\n\n\t\t\tMediaType typePart = (typeParts != null) ? new MediaType(\n\t\t\t\t\ttypeParts[0], typeParts[1]) : MediaType.WILDCARD_TYPE;\n\n\t\t\tBodyPart bodyPart = null;\n\t\t\tif (value instanceof OutputStreamSender) {\n\t\t\t\tbodyPart = new BodyPart(new StreamingOutputImpl(\n\t\t\t\t\t\t(OutputStreamSender) value, reqlog), typePart);\n\t\t\t} else {\n\t\t\t\tif (reqlog != null)\n\t\t\t\t\tbodyPart = new BodyPart(reqlog.copyContent(value), typePart);\n\t\t\t\telse\n\t\t\t\t\tbodyPart = new BodyPart(value, typePart);\n\t\t\t}\n\n\t\t\tmultiPart = multiPart.bodyPart(bodyPart);\n\t\t}\n\n\t\treturn hasStreamingPart;\n\t}\n\n\tprivate WebResource.Builder makeBuilder(String path,\n\t\t\tMultivaluedMap params, Object inputMimetype,\n\t\t\tObject outputMimetype) {\n\t\tWebResource resource = (params == null) ? connection.path(path)\n\t\t\t\t: connection.path(path).queryParams(params);\n\n\t\tWebResource.Builder builder = resource.getRequestBuilder();\n\n\t\tif (inputMimetype == null) {\n\t\t} else if (inputMimetype instanceof String) {\n\t\t\tbuilder = builder.type((String) inputMimetype);\n\t\t} else if (inputMimetype instanceof MediaType) {\n\t\t\tbuilder = builder.type((MediaType) inputMimetype);\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\"Unknown input mimetype specifier \"\n\t\t\t\t\t\t\t+ inputMimetype.getClass().getName());\n\t\t}\n\n\t\tif (outputMimetype == null) {\n\t\t} else if (outputMimetype instanceof String) {\n\t\t\tbuilder = builder.accept((String) outputMimetype);\n\t\t} else if (outputMimetype instanceof MediaType) {\n\t\t\tbuilder = builder.accept((MediaType) outputMimetype);\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\"Unknown output mimetype specifier \"\n\t\t\t\t\t\t\t+ outputMimetype.getClass().getName());\n\t\t}\n\n\t\treturn builder;\n\t}\n\n\tprivate void checkStatus(ClientResponse response,\n\t\t\tClientResponse.Status status, String operation, String entityType,\n\t\t\tString path, ResponseStatus expected) {\n\t\tif (!expected.isExpected(status)) {\n\t\t\tif (status == ClientResponse.Status.NOT_FOUND) {\n\t\t\t\tthrow new ResourceNotFoundException(\"Could not \" + operation\n\t\t\t\t\t\t+ \" \" + entityType + \" at \" + path,\n\t\t\t\t\t\textractErrorFields(response));\n\t\t\t}\n\t\t\tif (status == ClientResponse.Status.FORBIDDEN) {\n\t\t\t\tthrow new ForbiddenUserException(\"User is not allowed to \"\n\t\t\t\t\t\t+ operation + \" \" + entityType + \" at \" + path,\n\t\t\t\t\t\textractErrorFields(response));\n\t\t\t}\n\t\t\tthrow new FailedRequestException(\"failed to \" + operation + \" \"\n\t\t\t\t\t+ entityType + \" at \" + path + \": \"\n\t\t\t\t\t+ status.getReasonPhrase(), extractErrorFields(response));\n\t\t}\n\t}\n\n\tprivate T makeResult(RequestLogger reqlog, String operation,\n\t\t\tString entityType, ClientResponse response, Class as) {\n\t\tif (as == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\tlogRequest(reqlog, \"%s for %s\", operation, entityType);\n\n\t\tT entity = response.hasEntity() ? response.getEntity(as) : null;\n\t\tif (entity == null || (as != InputStream.class && as != Reader.class))\n\t\t\tresponse.close();\n\n\t\treturn (reqlog != null) ? reqlog.copyContent(entity) : entity;\n\t}\n\n\tprivate ServiceResultIterator makeResults(RequestLogger reqlog,\n\t\t\tString operation, String entityType, ClientResponse response) {\n\t\tlogRequest(reqlog, \"%s for %s\", operation, entityType);\n\n\t\tMultiPart entity = response.hasEntity() ?\n\t\t\t\tresponse.getEntity(MultiPart.class) : null;\n\t\tif (entity == null)\n\t\t\treturn null;\n\n\t\tList partList = entity.getBodyParts();\n\t\tif (partList == null || partList.size() == 0) {\n\t\t\tresponse.close();\n\t\t\treturn null;\n\t\t}\n\n\t\treturn new JerseyResultIterator(reqlog, response, partList);\n\t}\n\n\tprivate boolean isStreaming(Object value) {\n\t\treturn !(value instanceof String || value instanceof byte[] || value instanceof File);\n\t}\n\n\tprivate void logRequest(RequestLogger reqlog, String message,\n\t\t\tObject... params) {\n\t\tif (reqlog == null)\n\t\t\treturn;\n\n\t\tPrintStream out = reqlog.getPrintStream();\n\t\tif (out == null)\n\t\t\treturn;\n\n\t\tif (params == null || params.length == 0) {\n\t\t\tout.println(message);\n\t\t} else {\n\t\t\tout.format(message, params);\n\t\t\tout.println();\n\t\t}\n\t}\n\n\tprivate String stringJoin(Collection collection, String separator,\n\t\t\tString defaultValue) {\n\t\tif (collection == null || collection.size() == 0)\n\t\t\treturn defaultValue;\n\n\t\tStringBuilder builder = null;\n\t\tfor (Object value : collection) {\n\t\t\tif (builder == null)\n\t\t\t\tbuilder = new StringBuilder();\n\t\t\telse\n\t\t\t\tbuilder.append(separator);\n\n\t\t\tbuilder.append(value);\n\t\t}\n\n\t\treturn (builder != null) ? builder.toString() : null;\n\t}\n\n\tprivate int calculateDelay(Random rand, int i) {\n\t\tint min =\n\t\t\t(i > 6) ? DELAY_CEILING :\n\t\t\t(i == 0) ? DELAY_FLOOR :\n\t\t\t DELAY_FLOOR + (1 << i) * DELAY_MULTIPLIER;\n\t\tint range =\n\t\t\t(i > 6) ? DELAY_FLOOR :\n\t\t\t(i == 0) ? 2 * DELAY_MULTIPLIER :\n\t\t\t(i == 6) ? DELAY_CEILING - min :\n\t\t\t\t (1 << i) * DELAY_MULTIPLIER;\n\t\treturn min + randRetry.nextInt(range);\n\t}\n\n\tpublic class JerseyResult implements ServiceResult {\n\t\tprivate RequestLogger reqlog;\n\t\tprivate BodyPart part;\n\t\tprivate boolean extractedHeaders = false;\n\t\tprivate Format format;\n\t\tprivate String mimetype;\n\t\tprivate long length;\n\n\t\tpublic JerseyResult(RequestLogger reqlog, BodyPart part) {\n\t\t\tsuper();\n\t\t\tthis.reqlog = reqlog;\n\t\t\tthis.part = part;\n\t\t}\n\n\t\t@Override\n\t\tpublic R getContent(R handle) {\n\t\t\tif (part == null)\n\t\t\t\tthrow new IllegalStateException(\"Content already retrieved\");\n\n\t\t\tHandleImplementation handleBase = HandleAccessor.as(handle);\n\n\t\t\textractHeaders();\n\t\t\tupdateFormat(handleBase, format);\n\t\t\tupdateMimetype(handleBase, mimetype);\n\t\t\tupdateLength(handleBase, length);\n\n\t\t\tObject contentEntity = part.getEntityAs(handleBase.receiveAs());\n\t\t\thandleBase.receiveContent((reqlog != null) ? reqlog\n\t\t\t\t\t.copyContent(contentEntity) : contentEntity);\n\n\t\t\tpart = null;\n\t\t\treqlog = null;\n\n\t\t\treturn handle;\n\t\t}\n\n\t\t@Override\n\t\tpublic Format getFormat() {\n\t\t\textractHeaders();\n\t\t\treturn format;\n\t\t}\n\n\t\t@Override\n\t\tpublic String getMimetype() {\n\t\t\textractHeaders();\n\t\t\treturn mimetype;\n\t\t}\n\n\t\t@Override\n\t\tpublic long getLength() {\n\t\t\textractHeaders();\n\t\t\treturn length;\n\t\t}\n\n\t\tprivate void extractHeaders() {\n\t\t\tif (part == null || extractedHeaders)\n\t\t\t\treturn;\n\t\t\tMultivaluedMap headers = part.getHeaders();\n\t\t\tformat = getHeaderFormat(headers);\n\t\t\tmimetype = getHeaderMimetype(headers);\n\t\t\tlength = getHeaderLength(headers);\n\t\t\textractedHeaders = true;\n\t\t}\n\t}\n\n\tpublic class JerseyResultIterator implements ServiceResultIterator {\n\t\tprivate RequestLogger reqlog;\n\t\tprivate ClientResponse response;\n\t\tprivate Iterator partQueue;\n\n\t\tpublic JerseyResultIterator(RequestLogger reqlog,\n\t\t\t\tClientResponse response, List partList) {\n\t\t\tsuper();\n\t\t\tif (response != null) {\n\t\t\t\tif (partList != null && partList.size() > 0) {\n\t\t\t\t\tthis.reqlog = reqlog;\n\t\t\t\t\tthis.response = response;\n\t\t\t\t\tthis.partQueue = new ConcurrentLinkedQueue(\n\t\t\t\t\t\t\tpartList).iterator();\n\t\t\t\t} else {\n\t\t\t\t\tresponse.close();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean hasNext() {\n\t\t\tif (partQueue == null)\n\t\t\t\treturn false;\n\t\t\tboolean hasNext = partQueue.hasNext();\n\t\t\tif (!partQueue.hasNext())\n\t\t\t\tclose();\n\t\t\treturn hasNext;\n\t\t}\n\n\t\t@Override\n\t\tpublic ServiceResult next() {\n\t\t\tif (partQueue == null)\n\t\t\t\treturn null;\n\n\t\t\tServiceResult result = new JerseyResult(reqlog, partQueue.next());\n\t\t\tif (!partQueue.hasNext())\n\t\t\t\tclose();\n\n\t\t\treturn result;\n\t\t}\n\n\t\t@Override\n\t\tpublic void remove() {\n\t\t\tif (partQueue == null)\n\t\t\t\treturn;\n\t\t\tpartQueue.remove();\n\t\t\tif (!partQueue.hasNext())\n\t\t\t\tclose();\n\t\t}\n\n\t\t@Override\n\t\tpublic void close() {\n\t\t\tif (response != null) {\n\t\t\t\tresponse.close();\n\t\t\t\tresponse = null;\n\t\t\t}\n\t\t\tpartQueue = null;\n\t\t\treqlog = null;\n\t\t}\n\n\t\t@Override\n\t\tprotected void finalize() throws Throwable {\n\t\t\tclose();\n\t\t\tsuper.finalize();\n\t\t}\n\t}\n\n\t@Override\n\tpublic HttpClient getClientImplementation() {\n\t\tif (client == null)\n\t\t\treturn null;\n\t\treturn client.getClientHandler().getHttpClient();\n\t}\n\n\t@Override\n\tpublic T suggest(Class as, SuggestDefinition suggestionDef) {\n\t\tMultivaluedMap params = new MultivaluedMapImpl();\n\n\t\tString suggestCriteria = suggestionDef.getStringCriteria();\n\t\tString[] queries = suggestionDef.getQueryStrings();\n\t\tString optionsName = suggestionDef.getOptionsName();\n\t\tInteger limit = suggestionDef.getLimit();\n\t\tInteger cursorPosition = suggestionDef.getCursorPosition();\n\n\t\tif (suggestCriteria != null) {\n\t\t\tparams.add(\"partial-q\", suggestCriteria);\n\t\t}\n\t\tif (optionsName != null) {\n\t\t\tparams.add(\"options\", optionsName);\n\t\t}\n\t\tif (limit != null) {\n\t\t\tparams.add(\"limit\", Long.toString(limit));\n\t\t}\n\t\tif (cursorPosition != null) {\n\t\t\tparams.add(\"cursor-position\", Long.toString(cursorPosition));\n\t\t}\n\t\tif (queries != null) {\n\t\t\tfor (String stringQuery : queries) {\n\t\t\t\tparams.add(\"q\", stringQuery);\n\t\t\t}\n\t\t}\n\t\tWebResource.Builder builder = null;\n\t\tbuilder = connection.path(\"suggest\").queryParams(params)\n\t\t\t\t.accept(\"application/xml\");\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n\t\tint retry = 0;\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresponse = builder.get(ClientResponse.class);\n\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n\t\t}\n\t\tif (status == ClientResponse.Status.FORBIDDEN) {\n\t\t\tthrow new ForbiddenUserException(\n\t\t\t\t\t\"User is not allowed to get suggestions\",\n\t\t\t\t\textractErrorFields(response));\n\t\t}\n\t\tif (status != ClientResponse.Status.OK) {\n\t\t\tthrow new FailedRequestException(\"Suggest call failed: \"\n\t\t\t\t\t+ status.getReasonPhrase(), extractErrorFields(response));\n\t\t}\n\n\t\tT entity = response.hasEntity() ? response.getEntity(as) : null;\n\t\tif (entity == null || (as != InputStream.class && as != Reader.class))\n\t\t\tresponse.close();\n\n\t\treturn entity;\n\t}\n\n\t@Override\n\tpublic InputStream match(StructureWriteHandle document,\n\t\t\tString[] candidateRules, String mimeType, ServerTransform transform) {\n\t\tMultivaluedMap params = new MultivaluedMapImpl();\n\n\t\tHandleImplementation baseHandle = HandleAccessor.checkHandle(document, \"match\");\n\t\tif (candidateRules.length > 0) {\n\t\t\tfor (String candidateRule : candidateRules) {\n\t\t\t\tparams.add(\"rule\", candidateRule);\n\t\t\t}\n\t\t}\n\t\tif (transform != null) {\n\t\t\ttransform.merge(params);\n\t\t}\n\t\tWebResource.Builder builder = null;\n\t\tbuilder = connection.path(\"alert/match\").queryParams(params)\n\t\t\t\t.accept(\"application/xml\").type(mimeType);\n\t\t\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n\t\tint retry = 0;\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresponse = doPost(null, builder, baseHandle.sendContent(), false);\n\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n\t\t}\n\t\tif (status == ClientResponse.Status.FORBIDDEN) {\n\t\t\tthrow new ForbiddenUserException(\"User is not allowed to match\",\n\t\t\t\t\textractErrorFields(response));\n\t\t}\n\t\tif (status != ClientResponse.Status.OK) {\n\t\t\tthrow new FailedRequestException(\"match failed: \"\n\t\t\t\t\t+ status.getReasonPhrase(), extractErrorFields(response));\n\t\t}\n\n\t\tInputStream entity = response.hasEntity() ?\n\t\t\t\tresponse.getEntity(InputStream.class) : null;\n\t\tif (entity == null)\n\t\t\tresponse.close();\n\t\t\n\t\treturn entity;\n\t}\n\n\t@Override\n\tpublic InputStream match(QueryDefinition queryDef,\n\t\t\tlong start, long pageLength, String[] candidateRules, ServerTransform transform) {\n\t\tif (queryDef == null) {\n\t\t\tthrow new IllegalArgumentException(\"Cannot match null query\");\n\t\t}\n\n\t\tMultivaluedMap params = new MultivaluedMapImpl();\n\n\t\tif (start > 1) {\n\t\t\tparams.add(\"start\", Long.toString(start));\n\t\t}\n\t\tif (pageLength >= 0) {\n\t\t\tparams.add(\"pageLength\", Long.toString(pageLength));\n\t\t}\n\t\tif (transform != null) {\n\t\t\ttransform.merge(params);\n\t\t}\n\t\tif (candidateRules.length > 0) {\n\t\t\tfor (String candidateRule : candidateRules) {\n\t\t\t\tparams.add(\"rule\", candidateRule);\n\t\t\t}\n\t\t}\n\n\t\tif (queryDef.getOptionsName() != null) {\n\t\t\tparams.add(\"options\", queryDef.getOptionsName());\n\t\t}\n\n\t\tWebResource.Builder builder = null;\n\t\tString structure = null;\n\t\tHandleImplementation baseHandle = null;\n\n\t\tif (queryDef instanceof RawQueryDefinition) {\n\t\t\tStructureWriteHandle handle = ((RawQueryDefinition) queryDef).getHandle();\n\t\t\tbaseHandle = HandleAccessor.checkHandle(handle, \"match\");\n\n\t\t\tif (logger.isDebugEnabled())\n\t\t\t\tlogger.debug(\"Searching for structure {}\", structure);\n\n\t\t\tbuilder = connection.path(\"alert/match\").queryParams(params)\n\t\t\t\t\t.type(\"application/xml\").accept(\"application/xml\");\n\t\t} else if (queryDef instanceof StringQueryDefinition) {\n\t\t\tString text = ((StringQueryDefinition) queryDef).getCriteria();\n\t\t\tif (logger.isDebugEnabled())\n\t\t\t\tlogger.debug(\"Searching for {} in transaction {}\", text);\n\n\t\t\tif (text != null) {\n\t\t\t\taddEncodedParam(params, \"q\", text);\n\t\t\t}\n\n\t\t\tbuilder = connection.path(\"alert/match\").queryParams(params)\n\t\t\t\t\t.accept(\"application/xml\");\n\t\t} else if (queryDef instanceof StructuredQueryDefinition) {\n\t\t\tstructure = ((StructuredQueryDefinition) queryDef).serialize();\n\n\t\t\tif (logger.isDebugEnabled())\n\t\t\t\tlogger.debug(\"Searching for structure {} in transaction {}\",\n\t\t\t\t\t\tstructure);\n\n\t\t\tbuilder = connection.path(\"alert/match\").queryParams(params)\n\t\t\t\t\t.type(\"application/xml\").accept(\"application/xml\");\n\t\t} else {\n\t\t\tthrow new UnsupportedOperationException(\"Cannot match with \"\n\t\t\t\t\t+ queryDef.getClass().getName());\n\t\t}\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n\t\tint retry = 0;\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (queryDef instanceof StringQueryDefinition) {\n\t\t\t\tresponse = builder.get(ClientResponse.class);\n\t\t\t} else if (queryDef instanceof StructuredQueryDefinition) {\n\t\t\t\tresponse = builder.post(ClientResponse.class, structure);\n\t\t\t} else if (queryDef instanceof RawQueryDefinition) {\n\t\t\t\tresponse = doPost(null, builder, baseHandle.sendContent(), false);\n\t\t\t} else {\n\t\t\t\tthrow new UnsupportedOperationException(\"Cannot match with \"\n\t\t\t\t\t\t+ queryDef.getClass().getName());\n\t\t\t}\n\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n\t\t}\n\t\tif (status == ClientResponse.Status.FORBIDDEN) {\n\t\t\tthrow new ForbiddenUserException(\"User is not allowed to match\",\n\t\t\t\t\textractErrorFields(response));\n\t\t}\n\t\tif (status != ClientResponse.Status.OK) {\n\t\t\tthrow new FailedRequestException(\"match failed: \"\n\t\t\t\t\t+ status.getReasonPhrase(), extractErrorFields(response));\n\t\t}\n\n\t\tInputStream entity = response.hasEntity() ?\n\t\t\t\tresponse.getEntity(InputStream.class) : null;\n\t\tif (entity == null)\n\t\t\tresponse.close();\n\t\t\n\t\treturn entity;\n\t}\n\n\t@Override\n\tpublic InputStream match(String[] docIds, String[] candidateRules, ServerTransform transform) {\n\t\tMultivaluedMap params = new MultivaluedMapImpl();\n\n\t\tif (docIds.length > 0) {\n\t\t\tfor (String docId : docIds) {\n\t\t\t\tparams.add(\"uri\", docId);\n\t\t\t}\n\t\t}\n\t\tif (candidateRules.length > 0) {\n\t\t\tfor (String candidateRule : candidateRules) {\n\t\t\t\tparams.add(\"rule\", candidateRule);\n\t\t\t}\n\t\t}\n\t\tif (transform != null) {\n\t\t\ttransform.merge(params);\n\t\t}\n\t\tWebResource.Builder builder = connection.path(\"alert/match\").queryParams(params)\n\t\t\t\t.accept(\"application/xml\");\n\t\t\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n\t\tint retry = 0;\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresponse = doGet(builder);\n\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n\t\t}\n\t\tif (status == ClientResponse.Status.FORBIDDEN) {\n\t\t\tthrow new ForbiddenUserException(\"User is not allowed to match\",\n\t\t\t\t\textractErrorFields(response));\n\t\t}\n\t\tif (status != ClientResponse.Status.OK) {\n\t\t\tthrow new FailedRequestException(\"match failed: \"\n\t\t\t\t\t+ status.getReasonPhrase(), extractErrorFields(response));\n\t\t}\n\n\t\tInputStream entity = response.hasEntity() ?\n\t\t\t\tresponse.getEntity(InputStream.class) : null;\n\t\tif (entity == null)\n\t\t\tresponse.close();\n\t\t\n\t\treturn entity;\n\t}\n}\n"},"new_file":{"kind":"string","value":"src/main/java/com/marklogic/client/impl/JerseyServices.java"},"old_contents":{"kind":"string","value":"/*\n * Copyright 2012-2013 MarkLogic Corporation\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.marklogic.client.impl;\n\nimport java.io.File;\nimport java.io.InputStream;\nimport java.io.PrintStream;\nimport java.io.Reader;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Random;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentLinkedQueue;\n\nimport javax.net.ssl.SSLContext;\nimport javax.net.ssl.SSLException;\nimport javax.ws.rs.core.Cookie;\nimport javax.ws.rs.core.MediaType;\nimport javax.ws.rs.core.MultivaluedMap;\nimport javax.ws.rs.core.StreamingOutput;\n\nimport org.apache.http.HttpHost;\nimport org.apache.http.HttpVersion;\nimport org.apache.http.auth.params.AuthPNames;\nimport org.apache.http.client.HttpClient;\nimport org.apache.http.client.params.AuthPolicy;\nimport org.apache.http.client.params.ClientPNames;\nimport org.apache.http.conn.routing.HttpRoute;\nimport org.apache.http.conn.scheme.PlainSocketFactory;\nimport org.apache.http.conn.scheme.Scheme;\nimport org.apache.http.conn.scheme.SchemeRegistry;\nimport org.apache.http.conn.scheme.SchemeSocketFactory;\nimport org.apache.http.conn.ssl.AbstractVerifier;\nimport org.apache.http.conn.ssl.SSLSocketFactory;\nimport org.apache.http.conn.ssl.X509HostnameVerifier;\nimport org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;\nimport org.apache.http.params.BasicHttpParams;\nimport org.apache.http.params.HttpParams;\nimport org.apache.http.params.HttpProtocolParams;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.marklogic.client.DatabaseClientFactory.Authentication;\nimport com.marklogic.client.DatabaseClientFactory.SSLHostnameVerifier;\nimport com.marklogic.client.FailedRequestException;\nimport com.marklogic.client.ForbiddenUserException;\nimport com.marklogic.client.MarkLogicInternalException;\nimport com.marklogic.client.ResourceNotFoundException;\nimport com.marklogic.client.ResourceNotResendableException;\nimport com.marklogic.client.document.ContentDescriptor;\nimport com.marklogic.client.document.DocumentDescriptor;\nimport com.marklogic.client.document.DocumentManager.Metadata;\nimport com.marklogic.client.document.DocumentUriTemplate;\nimport com.marklogic.client.document.ServerTransform;\nimport com.marklogic.client.extensions.ResourceServices.ServiceResult;\nimport com.marklogic.client.extensions.ResourceServices.ServiceResultIterator;\nimport com.marklogic.client.io.Format;\nimport com.marklogic.client.io.OutputStreamSender;\nimport com.marklogic.client.io.marker.AbstractReadHandle;\nimport com.marklogic.client.io.marker.AbstractWriteHandle;\nimport com.marklogic.client.io.marker.DocumentMetadataReadHandle;\nimport com.marklogic.client.io.marker.DocumentMetadataWriteHandle;\nimport com.marklogic.client.io.marker.DocumentPatchHandle;\nimport com.marklogic.client.io.marker.StructureWriteHandle;\nimport com.marklogic.client.query.DeleteQueryDefinition;\nimport com.marklogic.client.query.ElementLocator;\nimport com.marklogic.client.query.KeyLocator;\nimport com.marklogic.client.query.KeyValueQueryDefinition;\nimport com.marklogic.client.query.QueryDefinition;\nimport com.marklogic.client.query.QueryManager.QueryView;\nimport com.marklogic.client.query.RawQueryByExampleDefinition;\nimport com.marklogic.client.query.RawQueryDefinition;\nimport com.marklogic.client.query.StringQueryDefinition;\nimport com.marklogic.client.query.StructuredQueryDefinition;\nimport com.marklogic.client.query.SuggestDefinition;\nimport com.marklogic.client.query.ValueLocator;\nimport com.marklogic.client.query.ValueQueryDefinition;\nimport com.marklogic.client.query.ValuesDefinition;\nimport com.marklogic.client.query.ValuesListDefinition;\nimport com.marklogic.client.util.RequestLogger;\nimport com.marklogic.client.util.RequestParameters;\nimport com.sun.jersey.api.client.ClientResponse;\nimport com.sun.jersey.api.client.WebResource;\nimport com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;\nimport com.sun.jersey.api.client.filter.HTTPDigestAuthFilter;\nimport com.sun.jersey.api.uri.UriComponent;\nimport com.sun.jersey.client.apache4.ApacheHttpClient4;\nimport com.sun.jersey.client.apache4.config.ApacheHttpClient4Config;\nimport com.sun.jersey.client.apache4.config.DefaultApacheHttpClient4Config;\nimport com.sun.jersey.core.util.MultivaluedMapImpl;\nimport com.sun.jersey.multipart.BodyPart;\nimport com.sun.jersey.multipart.Boundary;\nimport com.sun.jersey.multipart.MultiPart;\nimport com.sun.jersey.multipart.MultiPartMediaTypes;\n\n@SuppressWarnings({ \"unchecked\", \"rawtypes\" })\npublic class JerseyServices implements RESTServices {\n\tstatic final private Logger logger = LoggerFactory\n\t\t\t.getLogger(JerseyServices.class);\n\tstatic final String ERROR_NS = \"http://marklogic.com/rest-api\";\n\n\tstatic final private String DOCUMENT_URI_PREFIX = \"/documents?uri=\";\n\n\tstatic protected class HostnameVerifierAdapter extends AbstractVerifier {\n\t\tprivate SSLHostnameVerifier verifier;\n\n\t\tprotected HostnameVerifierAdapter(SSLHostnameVerifier verifier) {\n\t\t\tsuper();\n\t\t\tthis.verifier = verifier;\n\t\t}\n\n\t\t@Override\n\t\tpublic void verify(String hostname, String[] cns, String[] subjectAlts)\n\t\t\t\tthrows SSLException {\n\t\t\tverifier.verify(hostname, cns, subjectAlts);\n\t\t}\n\t}\n\n\tprivate ApacheHttpClient4 client;\n\tprivate WebResource connection;\n\n\tprivate Random randRetry = new Random();\n\tprivate int maxRetries = 8;\n\tprivate int delayFloor = 60;\n\tprivate int delayMultiplier = 40;\n\n\tprivate boolean isFirstRequest = false;\n\n\tpublic JerseyServices() {\n\t}\n\n\tprivate FailedRequest extractErrorFields(ClientResponse response) {\n\t\tInputStream is = response.getEntityInputStream();\n\t\ttry {\n\t\t\tFailedRequest handler = FailedRequest.getFailedRequest(\n\t\t\t\t\tresponse.getStatus(), response.getType(), is);\n\t\t\treturn handler;\n\t\t} catch (RuntimeException e) {\n\t\t\tthrow (e);\n\t\t} finally {\n\t\t\tresponse.close();\n\t\t}\n\t}\n\n\t@Override\n\tpublic void connect(String host, int port, String user, String password,\n\t\t\tAuthentication authenType, SSLContext context,\n\t\t\tSSLHostnameVerifier verifier) {\n\t\tX509HostnameVerifier x509Verifier = null;\n\t\tif (verifier == null) {\n\t\t\tif (context != null)\n\t\t\t\tx509Verifier = SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;\n\t\t\t}\n\t\telse if (verifier == SSLHostnameVerifier.ANY)\n\t\t\tx509Verifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;\n\t\telse if (verifier == SSLHostnameVerifier.COMMON)\n\t\t\tx509Verifier = SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;\n\t\telse if (verifier == SSLHostnameVerifier.STRICT)\n\t\t\tx509Verifier = SSLSocketFactory.STRICT_HOSTNAME_VERIFIER;\n\t\telse if (context != null)\n\t\t\tx509Verifier = new HostnameVerifierAdapter(verifier);\n\t\telse\n\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\"Null SSLContent but non-null SSLHostnameVerifier for client\");\n\n\t\tconnect(host, port, user, password, authenType, context, x509Verifier);\n\t}\n\n\tprivate void connect(String host, int port, String user, String password,\n\t\t\tAuthentication authenType, SSLContext context,\n\t\t\tX509HostnameVerifier verifier) {\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Connecting to {} at {} as {}\", new Object[] { host,\n\t\t\t\t\tport, user });\n\n\t\tif (host == null)\n\t\t\tthrow new IllegalArgumentException(\"No host provided\");\n\n\t\tif (authenType == null) {\n\t\t\tif (context != null) {\n\t\t\t\tauthenType = Authentication.BASIC;\n\t\t\t}\n\t\t}\n\n\t\tif (authenType != null) {\n\t\t\tif (user == null)\n\t\t\t\tthrow new IllegalArgumentException(\"No user provided\");\n\t\t\tif (password == null)\n\t\t\t\tthrow new IllegalArgumentException(\"No password provided\");\n\t\t}\n\n\t\tif (connection != null)\n\t\t\tconnection = null;\n\t\tif (client != null) {\n\t\t\tclient.destroy();\n\t\t\tclient = null;\n\t\t}\n\n\t\tString baseUri = ((context == null) ? \"http\" : \"https\") + \"://\" + host\n\t\t\t\t+ \":\" + port + \"/v1/\";\n\n\t\t// TODO: integrated control of HTTP Client and Jersey Client logging\n\t\tif (System.getProperty(\"org.apache.commons.logging.Log\") == null) {\n\t\t\tSystem.setProperty(\"org.apache.commons.logging.Log\",\n\t\t\t\t\"org.apache.commons.logging.impl.SimpleLog\");\n\t\t}\n\t\tif (System.getProperty(\"org.apache.commons.logging.simplelog.log.org.apache.http\") == null) {\n\t\t\tSystem.setProperty(\n\t\t\t\t\"org.apache.commons.logging.simplelog.log.org.apache.http\",\n\t\t\t\t\"warn\");\n\t\t}\n\t\tif (System.getProperty(\"org.apache.commons.logging.simplelog.log.org.apache.http.wire\") == null) {\n\t\t\tSystem.setProperty(\n\t\t\t\t\"org.apache.commons.logging.simplelog.log.org.apache.http.wire\",\n\t\t\t\t\"warn\");\n\t\t}\n\n\t\tScheme scheme = null;\n\t\tif (context == null) {\n\t\t\tSchemeSocketFactory socketFactory = PlainSocketFactory\n\t\t\t\t\t.getSocketFactory();\n\t\t\tscheme = new Scheme(\"http\", port, socketFactory);\n\t\t} else {\n\t\t\tSSLSocketFactory socketFactory = new SSLSocketFactory(context,\n\t\t\t\t\tverifier);\n\t\t\tscheme = new Scheme(\"https\", port, socketFactory);\n\t\t}\n\t\tSchemeRegistry schemeRegistry = new SchemeRegistry();\n\t\tschemeRegistry.register(scheme);\n\n\t\tint maxRouteConnections = 100;\n\t\tint maxTotalConnections = 2 * maxRouteConnections;\n\n\t\t/*\n\t\t * 4.2 PoolingClientConnectionManager connMgr = new\n\t\t * PoolingClientConnectionManager(schemeRegistry);\n\t\t * connMgr.setMaxTotal(maxTotalConnections);\n\t\t * connMgr.setDefaultMaxPerRoute(maxRouteConnections);\n\t\t * connMgr.setMaxPerRoute( new HttpRoute(new HttpHost(baseUri)),\n\t\t * maxRouteConnections);\n\t\t */\n\t\t// start 4.1\n\t\tThreadSafeClientConnManager connMgr = new ThreadSafeClientConnManager(\n\t\t\t\tschemeRegistry);\n\t\tconnMgr.setMaxTotal(maxTotalConnections);\n\t\tconnMgr.setDefaultMaxPerRoute(maxRouteConnections);\n\t\tconnMgr.setMaxForRoute(new HttpRoute(new HttpHost(baseUri)),\n\t\t\t\tmaxRouteConnections);\n\t\t// end 4.1\n\n\t\t// CredentialsProvider credentialsProvider = new\n\t\t// BasicCredentialsProvider();\n\t\t// credentialsProvider.setCredentials(new AuthScope(host, port),\n\t\t// new UsernamePasswordCredentials(user, password));\n\n\t\tHttpParams httpParams = new BasicHttpParams();\n\n\t\tif (authenType != null) {\n\t\t\tList authpref = new ArrayList();\n\n\t\t\tif (authenType == Authentication.BASIC)\n\t\t\t\tauthpref.add(AuthPolicy.BASIC);\n\t\t\telse if (authenType == Authentication.DIGEST)\n\t\t\t\tauthpref.add(AuthPolicy.DIGEST);\n\t\t\telse\n\t\t\t\tthrow new MarkLogicInternalException(\n\t\t\t\t\t\t\"Internal error - unknown authentication type: \"\n\t\t\t\t\t\t\t\t+ authenType.name());\n\n\t\t\thttpParams.setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);\n\t\t}\n\n\t\thttpParams.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false);\n\n HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);\n\n // HttpConnectionParams.setStaleCheckingEnabled(httpParams, false);\n\n // long-term alternative to isFirstRequest alive\n\t\t// HttpProtocolParams.setUseExpectContinue(httpParams, false);\n\t\t// httpParams.setIntParameter(CoreProtocolPNames.WAIT_FOR_CONTINUE, 1000);\n\n\t\tDefaultApacheHttpClient4Config config = new DefaultApacheHttpClient4Config();\n\t\tMap configProps = config.getProperties();\n\t\tconfigProps\n\t\t\t\t.put(ApacheHttpClient4Config.PROPERTY_PREEMPTIVE_BASIC_AUTHENTICATION,\n\t\t\t\t\t\tfalse);\n\t\tconfigProps.put(ApacheHttpClient4Config.PROPERTY_CONNECTION_MANAGER,\n\t\t\t\tconnMgr);\n\t\t// ignored?\n\t\tconfigProps.put(ApacheHttpClient4Config.PROPERTY_FOLLOW_REDIRECTS,\n\t\t\t\tfalse);\n\t\t// configProps.put(ApacheHttpClient4Config.PROPERTY_CREDENTIALS_PROVIDER,\n\t\t// credentialsProvider);\n\t\tconfigProps.put(ApacheHttpClient4Config.PROPERTY_HTTP_PARAMS,\n\t\t\t\thttpParams);\n\t\t// switches from buffered to streamed in Jersey Client\n\t\tconfigProps.put(ApacheHttpClient4Config.PROPERTY_CHUNKED_ENCODING_SIZE,\n\t\t\t\t32 * 1024);\n\n\t\tclient = ApacheHttpClient4.create(config);\n\n\t\t// System.setProperty(\"javax.net.debug\", \"all\"); // all or ssl\n\n\t\tif (authenType == null) {\n\t\t\tisFirstRequest = false;\n\t\t} else if (authenType == Authentication.BASIC) {\n\t\t\tisFirstRequest = false;\n\n\t\t\tclient.addFilter(new HTTPBasicAuthFilter(user, password));\n\t\t} else if (authenType == Authentication.DIGEST) {\n\t\t\tisFirstRequest = true;\n\n\t\t\t// workaround for JerseyClient bug 1445\n\t\t\tclient.addFilter(new DigestChallengeFilter());\n\n\t\t\tclient.addFilter(new HTTPDigestAuthFilter(user, password));\n\t\t} else {\n\t\t\tthrow new MarkLogicInternalException(\n\t\t\t\t\t\"Internal error - unknown authentication type: \"\n\t\t\t\t\t\t\t+ authenType.name());\n\t\t}\n\n\t\t// client.addFilter(new LoggingFilter(System.err));\n\n\t\tconnection = client.resource(baseUri);\n\t}\n\n\t@Override\n\tpublic void release() {\n\t\tif (client == null)\n\t\t\treturn;\n\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Releasing connection\");\n\n\t\tconnection = null;\n\t\tclient.destroy();\n\t\tclient = null;\n\t}\n\n\tprivate void makeFirstRequest() {\n\t\tconnection.path(\"ping\").head().close();\n\t}\n\n\t@Override\n\tpublic void deleteDocument(RequestLogger reqlog, DocumentDescriptor desc,\n\t\t\tString transactionId, Set categories)\n\t\t\tthrows ResourceNotFoundException, ForbiddenUserException,\n\t\t\tFailedRequestException {\n\t\tString uri = desc.getUri();\n\t\tif (uri == null)\n\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\"Document delete for document identifier without uri\");\n\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Deleting {} in transaction {}\", uri, transactionId);\n\n\t\tWebResource webResource = makeDocumentResource(makeDocumentParams(uri,\n\t\t\t\tcategories, transactionId, null));\n\n\t\tWebResource.Builder builder = addVersionHeader(desc,\n\t\t\t\twebResource.getRequestBuilder(), \"If-Match\");\n\t\tbuilder = addTransactionCookie(builder, transactionId);\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\t\tresponse = builder.delete(ClientResponse.class);\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t}\n\t\tif (status == ClientResponse.Status.NOT_FOUND) {\n\t\t\tresponse.close();\n\t\t\tthrow new ResourceNotFoundException(\n\t\t\t\t\t\"Could not delete non-existent document\");\n\t\t}\n\t\tif (status == ClientResponse.Status.FORBIDDEN) {\n\t\t\tFailedRequest failure = extractErrorFields(response);\n\t\t\tif (failure.getMessageCode().equals(\"RESTAPI-CONTENTNOVERSION\"))\n\t\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\t\"Content version required to delete document\", failure);\n\t\t\tthrow new ForbiddenUserException(\n\t\t\t\t\t\"User is not allowed to delete documents\", failure);\n\t\t}\n\t\tif (status == ClientResponse.Status.PRECONDITION_FAILED) {\n\t\t\tFailedRequest failure = extractErrorFields(response);\n\t\t\tif (failure.getMessageCode().equals(\"RESTAPI-CONTENTWRONGVERSION\"))\n\t\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\t\"Content version must match to delete document\",\n\t\t\t\t\t\tfailure);\n\t\t\telse if (failure.getMessageCode().equals(\"RESTAPI-EMPTYBODY\"))\n\t\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\t\"Empty request body sent to server\", failure);\n\t\t\tthrow new FailedRequestException(\"Precondition Failed\", failure);\n\t\t}\n\t\tif (status != ClientResponse.Status.NO_CONTENT)\n\t\t\tthrow new FailedRequestException(\"delete failed: \"\n\t\t\t\t\t+ status.getReasonPhrase(), extractErrorFields(response));\n\n\t\tresponse.close();\n\t\tlogRequest(reqlog, \"deleted %s document\", uri);\n\t}\n\n\t@Override\n\tpublic boolean getDocument(RequestLogger reqlog, DocumentDescriptor desc,\n\t\t\tString transactionId, Set categories,\n\t\t\tRequestParameters extraParams,\n\t\t\tDocumentMetadataReadHandle metadataHandle,\n\t\t\tAbstractReadHandle contentHandle) throws ResourceNotFoundException,\n\t\t\tForbiddenUserException, FailedRequestException {\n\n\t\tHandleImplementation metadataBase = HandleAccessor.checkHandle(\n\t\t\t\tmetadataHandle, \"metadata\");\n\t\tHandleImplementation contentBase = HandleAccessor.checkHandle(\n\t\t\t\tcontentHandle, \"content\");\n\n\t\tString metadataFormat = null;\n\t\tString metadataMimetype = null;\n\t\tif (metadataBase != null) {\n\t\t\tmetadataFormat = metadataBase.getFormat().toString().toLowerCase();\n\t\t\tmetadataMimetype = metadataBase.getMimetype();\n\t\t}\n\n\t\tString contentMimetype = null;\n\t\tif (contentBase != null) {\n\t\t\tcontentMimetype = contentBase.getMimetype();\n\t\t}\n\n\t\tif (metadataBase != null && contentBase != null) {\n\t\t\treturn getDocumentImpl(reqlog, desc, transactionId, categories,\n\t\t\t\t\textraParams, metadataFormat, metadataHandle, contentHandle);\n\t\t} else if (metadataBase != null) {\n\t\t\treturn getDocumentImpl(reqlog, desc, transactionId, categories,\n\t\t\t\t\textraParams, metadataMimetype, metadataHandle);\n\t\t} else if (contentBase != null) {\n\t\t\treturn getDocumentImpl(reqlog, desc, transactionId, null,\n\t\t\t\t\textraParams, contentMimetype, contentHandle);\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tprivate boolean getDocumentImpl(RequestLogger reqlog,\n\t\t\tDocumentDescriptor desc, String transactionId,\n\t\t\tSet categories, RequestParameters extraParams,\n\t\t\tString mimetype, AbstractReadHandle handle)\n\t\t\tthrows ResourceNotFoundException, ForbiddenUserException,\n\t\t\tFailedRequestException {\n\t\tString uri = desc.getUri();\n\t\tif (uri == null)\n\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\"Document read for document identifier without uri\");\n\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Getting {} in transaction {}\", uri, transactionId);\n\n\t\tWebResource.Builder builder = makeDocumentResource(\n\t\t\t\tmakeDocumentParams(uri, categories, transactionId, extraParams))\n\t\t\t\t.accept(mimetype);\n\t\tbuilder = addTransactionCookie(builder, transactionId);\n\n\t\tif (extraParams != null && extraParams.containsKey(\"range\"))\n\t\t\tbuilder = builder.header(\"range\", extraParams.get(\"range\").get(0));\n\n\t\tbuilder = addVersionHeader(desc, builder, \"If-None-Match\");\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\t\tresponse = builder.get(ClientResponse.class);\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t}\n\t\tif (status == ClientResponse.Status.NOT_FOUND)\n\t\t\tthrow new ResourceNotFoundException(\n\t\t\t\t\t\"Could not read non-existent document\",\n\t\t\t\t\textractErrorFields(response));\n\t\tif (status == ClientResponse.Status.FORBIDDEN)\n\t\t\tthrow new ForbiddenUserException(\n\t\t\t\t\t\"User is not allowed to read documents\",\n\t\t\t\t\textractErrorFields(response));\n\t\tif (status == ClientResponse.Status.NOT_MODIFIED) {\n\t\t\tresponse.close();\n\t\t\treturn false;\n\t\t}\n\t\tif (status != ClientResponse.Status.OK\n\t\t\t\t&& status != ClientResponse.Status.PARTIAL_CONTENT)\n\t\t\tthrow new FailedRequestException(\"read failed: \"\n\t\t\t\t\t+ status.getReasonPhrase(), extractErrorFields(response));\n\n\t\tlogRequest(\n\t\t\t\treqlog,\n\t\t\t\t\"read %s document from %s transaction with %s mime type and %s metadata categories\",\n\t\t\t\turi, (transactionId != null) ? transactionId : \"no\",\n\t\t\t\t(mimetype != null) ? mimetype : \"no\",\n\t\t\t\tstringJoin(categories, \", \", \"no\"));\n\n\t\tHandleImplementation handleBase = HandleAccessor.as(handle);\n\n\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\tif (isExternalDescriptor(desc)) {\n\t\t\tupdateVersion(desc, responseHeaders);\n\t\t\tupdateDescriptor(desc, responseHeaders);\n\t\t\tcopyDescriptor(desc, handleBase);\n\t\t} else {\n\t\t\tupdateDescriptor(handleBase, responseHeaders);\n\t\t}\n\n\t\tClass as = handleBase.receiveAs();\n\t\tObject entity = response.hasEntity() ? response.getEntity(as) : null;\n\n// TODO: test assignable from, not identical to\n\t\tif (entity == null || (as != InputStream.class && as != Reader.class))\n\t\t\tresponse.close();\n\n\t\thandleBase.receiveContent((reqlog != null) ? reqlog.copyContent(entity)\n\t\t\t\t: entity);\n\n\t\treturn true;\n\t}\n\n\tprivate boolean getDocumentImpl(RequestLogger reqlog,\n\t\t\tDocumentDescriptor desc, String transactionId,\n\t\t\tSet categories, RequestParameters extraParams,\n\t\t\tString metadataFormat, DocumentMetadataReadHandle metadataHandle,\n\t\t\tAbstractReadHandle contentHandle) throws ResourceNotFoundException,\n\t\t\tForbiddenUserException, FailedRequestException {\n\t\tString uri = desc.getUri();\n\t\tif (uri == null)\n\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\"Document read for document identifier without uri\");\n\n\t\tassert metadataHandle != null : \"metadataHandle is null\";\n\t\tassert contentHandle != null : \"contentHandle is null\";\n\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Getting multipart for {} in transaction {}\", uri,\n\t\t\t\t\ttransactionId);\n\n\t\tMultivaluedMap docParams = makeDocumentParams(uri,\n\t\t\t\tcategories, transactionId, extraParams, true);\n\t\tdocParams.add(\"format\", metadataFormat);\n\n\t\tWebResource.Builder builder = makeDocumentResource(docParams).getRequestBuilder();\n\t\tbuilder = addTransactionCookie(builder, transactionId);\n\t\tbuilder = addVersionHeader(desc, builder, \"If-None-Match\");\n\n\t\tMediaType multipartType = Boundary.addBoundary(MultiPartMediaTypes.MULTIPART_MIXED_TYPE);\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\t\tresponse = builder.accept(multipartType).get(ClientResponse.class);\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t}\n\t\tif (status == ClientResponse.Status.NOT_FOUND)\n\t\t\tthrow new ResourceNotFoundException(\n\t\t\t\t\t\"Could not read non-existent document\",\n\t\t\t\t\textractErrorFields(response));\n\t\tif (status == ClientResponse.Status.FORBIDDEN)\n\t\t\tthrow new ForbiddenUserException(\n\t\t\t\t\t\"User is not allowed to read documents\",\n\t\t\t\t\textractErrorFields(response));\n\t\tif (status == ClientResponse.Status.NOT_MODIFIED) {\n\t\t\tresponse.close();\n\t\t\treturn false;\n\t\t}\n\t\tif (status != ClientResponse.Status.OK)\n\t\t\tthrow new FailedRequestException(\"read failed: \"\n\t\t\t\t\t+ status.getReasonPhrase(), extractErrorFields(response));\n\n\t\tlogRequest(\n\t\t\t\treqlog,\n\t\t\t\t\"read %s document from %s transaction with %s metadata categories and content\",\n\t\t\t\turi, (transactionId != null) ? transactionId : \"no\",\n\t\t\t\tstringJoin(categories, \", \", \"no\"));\n\n\t\tMultiPart entity = response.hasEntity() ?\n\t\t\t\tresponse.getEntity(MultiPart.class) : null;\n\t\tif (entity == null)\n\t\t\treturn false;\n\n\t\tList partList = entity.getBodyParts();\n\t\tif (partList == null)\n\t\t\treturn false;\n\n\t\tint partCount = partList.size();\n\t\tif (partCount == 0)\n\t\t\treturn false;\n\t\tif (partCount != 2)\n\t\t\tthrow new FailedRequestException(\"read expected 2 parts but got \"\n\t\t\t\t\t+ partCount + \" parts\");\n\n\t\tHandleImplementation metadataBase = HandleAccessor.as(metadataHandle);\n\t\tHandleImplementation contentBase = HandleAccessor.as(contentHandle);\n\n\t\tBodyPart contentPart = partList.get(1);\n\n\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\tMultivaluedMap contentHeaders = contentPart\n\t\t\t\t.getHeaders();\n\t\tif (isExternalDescriptor(desc)) {\n\t\t\tupdateVersion(desc, responseHeaders);\n\t\t\tupdateFormat(desc, responseHeaders);\n\t\t\tupdateMimetype(desc, contentHeaders);\n\t\t\tupdateLength(desc, contentHeaders);\n\t\t\tcopyDescriptor(desc, contentBase);\n\t\t} else {\n\t\t\tupdateFormat(contentBase, responseHeaders);\n\t\t\tupdateMimetype(contentBase, contentHeaders);\n\t\t\tupdateLength(contentBase, contentHeaders);\n\t\t}\n\n\t\tmetadataBase.receiveContent(partList.get(0).getEntityAs(\n\t\t\t\tmetadataBase.receiveAs()));\n\n\t\tObject contentEntity = contentPart.getEntityAs(contentBase.receiveAs());\n\t\tcontentBase.receiveContent((reqlog != null) ? reqlog\n\t\t\t\t.copyContent(contentEntity) : contentEntity);\n\n\t\tresponse.close();\n\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic DocumentDescriptor head(RequestLogger reqlog, String uri,\n\t\t\tString transactionId) throws ForbiddenUserException,\n\t\t\tFailedRequestException {\n\t\tClientResponse response = headImpl(reqlog, uri, transactionId, makeDocumentResource(makeDocumentParams(uri,\n\t\t\t\tnull, transactionId, null)));\n\t\t\n\t\t// 404\n\t\tif (response == null) return null;\n\t\t\n\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\n\t\tresponse.close();\n\t\tlogRequest(reqlog, \"checked %s document from %s transaction\", uri,\n\t\t\t\t(transactionId != null) ? transactionId : \"no\");\n\n\t\tDocumentDescriptorImpl desc = new DocumentDescriptorImpl(uri, false);\n\n\t\tupdateVersion(desc, responseHeaders);\n\t\tupdateDescriptor(desc, responseHeaders);\n\n\t\treturn desc;\n\t}\n\t\n\t@Override\n\tpublic boolean exists(String uri) throws ForbiddenUserException,\n\t\t\tFailedRequestException {\n\t\treturn headImpl(null, uri, null, connection.path(uri)) == null ? false : true;\n\t}\n\t\n\tpublic ClientResponse headImpl(RequestLogger reqlog, String uri,\n\t\t\tString transactionId, WebResource webResource) {\n\t\tif (uri == null)\n\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\"Existence check for document identifier without uri\");\n\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Requesting head for {} in transaction {}\", uri,\n\t\t\t\t\ttransactionId);\n\n\t\tWebResource.Builder builder = webResource.getRequestBuilder();\n\t\tbuilder = addTransactionCookie(builder, transactionId);\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\t\tresponse = builder.head();\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t}\t\t\n\t\tif (status != ClientResponse.Status.OK) {\n\t\t\tif (status == ClientResponse.Status.NOT_FOUND) {\n\t\t\t\tresponse.close();\n\t\t\t\treturn null;\n\t\t\t} else if (status == ClientResponse.Status.FORBIDDEN)\n\t\t\t\tthrow new ForbiddenUserException(\n\t\t\t\t\t\t\"User is not allowed to check the existence of documents\",\n\t\t\t\t\t\textractErrorFields(response));\n\t\t\telse\n\t\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\t\"Document existence check failed: \"\n\t\t\t\t\t\t\t\t+ status.getReasonPhrase(),\n\t\t\t\t\t\textractErrorFields(response));\n\t\t}\n\t\treturn response;\n\t}\n\n\t@Override\n\tpublic void putDocument(RequestLogger reqlog, DocumentDescriptor desc,\n\t\t\tString transactionId, Set categories,\n\t\t\tRequestParameters extraParams,\n\t\t\tDocumentMetadataWriteHandle metadataHandle,\n\t\t\tAbstractWriteHandle contentHandle)\n\t\t\tthrows ResourceNotFoundException, ForbiddenUserException,\n\t\t\tFailedRequestException {\n\t\tif (desc.getUri() == null)\n\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\"Document write for document identifier without uri\");\n\n\t\tHandleImplementation metadataBase = HandleAccessor.checkHandle(\n\t\t\t\tmetadataHandle, \"metadata\");\n\t\tHandleImplementation contentBase = HandleAccessor.checkHandle(\n\t\t\t\tcontentHandle, \"content\");\n\n\t\tString metadataMimetype = null;\n\t\tif (metadataBase != null) {\n\t\t\tmetadataMimetype = metadataBase.getMimetype();\n\t\t}\n\n\t\tFormat descFormat = desc.getFormat();\n\t\tString contentMimetype = (descFormat != null && descFormat != Format.UNKNOWN) ? desc\n\t\t\t\t.getMimetype() : null;\n\t\tif (contentMimetype == null && contentBase != null) {\n\t\t\tFormat contentFormat = contentBase.getFormat();\n\t\t\tif (descFormat != null && descFormat != contentFormat) {\n\t\t\t\tcontentMimetype = descFormat.getDefaultMimetype();\n\t\t\t} else if (contentFormat != null && contentFormat != Format.UNKNOWN) {\n\t\t\t\tcontentMimetype = contentBase.getMimetype();\n\t\t\t}\n\t\t}\n\n\t\tif (metadataBase != null && contentBase != null) {\n\t\t\tputPostDocumentImpl(reqlog, \"put\", desc, transactionId, categories,\n\t\t\t\t\textraParams, metadataMimetype, metadataHandle,\n\t\t\t\t\tcontentMimetype, contentHandle);\n\t\t} else if (metadataBase != null) {\n\t\t\tputPostDocumentImpl(reqlog, \"put\", desc, transactionId, categories, false,\n\t\t\t\t\textraParams, metadataMimetype, metadataHandle);\n\t\t} else if (contentBase != null) {\n\t\t\tputPostDocumentImpl(reqlog, \"put\", desc, transactionId, null, true, \n\t\t\t\t\textraParams, contentMimetype, contentHandle);\n\t\t}\n\t}\n\n\t@Override\n\tpublic DocumentDescriptor postDocument(RequestLogger reqlog, DocumentUriTemplate template,\n\t\t\tString transactionId, Set categories, RequestParameters extraParams,\n\t\t\tDocumentMetadataWriteHandle metadataHandle, AbstractWriteHandle contentHandle)\n\tthrows ResourceNotFoundException, ForbiddenUserException, FailedRequestException {\n\t\tDocumentDescriptorImpl desc = new DocumentDescriptorImpl(false);\n\n\t\tHandleImplementation metadataBase = HandleAccessor.checkHandle(\n\t\t\t\tmetadataHandle, \"metadata\");\n\t\tHandleImplementation contentBase = HandleAccessor.checkHandle(\n\t\t\t\tcontentHandle, \"content\");\n\n\t\tString metadataMimetype = null;\n\t\tif (metadataBase != null) {\n\t\t\tmetadataMimetype = metadataBase.getMimetype();\n\t\t}\n\n\t\tFormat templateFormat = template.getFormat();\n\t\tString contentMimetype = (templateFormat != null && templateFormat != Format.UNKNOWN) ?\n\t\t\t\ttemplate.getMimetype() : null;\n\t\tif (contentMimetype == null && contentBase != null) {\n\t\t\tFormat contentFormat = contentBase.getFormat();\n\t\t\tif (templateFormat != null && templateFormat != contentFormat) {\n\t\t\t\tcontentMimetype = templateFormat.getDefaultMimetype();\n\t\t\t\tdesc.setFormat(templateFormat);\n\t\t\t} else if (contentFormat != null && contentFormat != Format.UNKNOWN) {\n\t\t\t\tcontentMimetype = contentBase.getMimetype();\n\t\t\t\tdesc.setFormat(contentFormat);\n\t\t\t}\n\t\t}\n\t\tdesc.setMimetype(contentMimetype);\n\n\t\tif (extraParams == null)\n\t\t\textraParams = new RequestParameters();\n\n\t\tString extension = template.getExtension();\n\t\tif (extension != null)\n\t\t\textraParams.add(\"extension\", extension);\n\n\t\tString directory = template.getDirectory();\n\t\tif (directory != null)\n\t\t\textraParams.add(\"directory\", directory);\n\n\t\tif (metadataBase != null && contentBase != null) {\n\t\t\tputPostDocumentImpl(reqlog, \"post\", desc, transactionId, categories, extraParams,\n\t\t\t\t\tmetadataMimetype, metadataHandle, contentMimetype, contentHandle);\n\t\t} else if (contentBase != null) {\n\t\t\tputPostDocumentImpl(reqlog, \"post\", desc, transactionId, null, true, extraParams,\n\t\t\t\t\tcontentMimetype, contentHandle);\n\t\t}\n\n\t\treturn desc;\n\t}\n\n\tprivate void putPostDocumentImpl(RequestLogger reqlog, String method, DocumentDescriptor desc,\n\t\t\tString transactionId, Set categories, boolean isOnContent, RequestParameters extraParams,\n\t\t\tString mimetype, AbstractWriteHandle handle)\n\tthrows ResourceNotFoundException, ResourceNotResendableException, ForbiddenUserException,\n\t\t\tFailedRequestException {\n\t\tString uri = desc.getUri();\n\n\t\tHandleImplementation handleBase = HandleAccessor.as(handle);\n\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Sending {} document in transaction {}\",\n\t\t\t\t\t(uri != null) ? uri : \"new\", transactionId);\n\n\t\tlogRequest(\n\t\t\t\treqlog,\n\t\t\t\t\"writing %s document from %s transaction with %s mime type and %s metadata categories\",\n\t\t\t\t(uri != null) ? uri : \"new\",\n\t\t\t\t(transactionId != null) ? transactionId : \"no\",\n\t\t\t\t(mimetype != null) ? mimetype : \"no\",\n\t\t\t\tstringJoin(categories, \", \", \"no\"));\n\n\t\tWebResource webResource = makeDocumentResource(\n\t\t\t\tmakeDocumentParams(\n\t\t\t\t\t\turi, categories, transactionId, extraParams, isOnContent\n\t\t\t\t\t\t));\n\n\t\tWebResource.Builder builder = webResource.type(\n\t\t\t\t(mimetype != null) ? mimetype : MediaType.WILDCARD);\n\t\tbuilder = addTransactionCookie(builder, transactionId);\n\t\tif (uri != null) {\n\t\t\tbuilder = addVersionHeader(desc, builder, \"If-Match\");\n\t\t}\n\n\t\tif (\"patch\".equals(method)) {\n\t\t\tbuilder = builder.header(\"X-HTTP-Method-Override\", \"PATCH\");\n\t\t\tmethod = \"post\";\n\t\t}\n\t\tboolean isResendable = handleBase.isResendable();\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tMultivaluedMap responseHeaders = null;\n\t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\t\tObject value = handleBase.sendContent();\n\t\t\tif (value == null)\n\t\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\t\"Document write with null value for \" +\n\t\t\t\t\t\t((uri != null) ? uri : \"new document\"));\n\n\t\t\tif (isFirstRequest && isStreaming(value))\n\t\t\t\tmakeFirstRequest();\n\n\t\t\tif (value instanceof OutputStreamSender) {\n\t\t\t\tStreamingOutput sentStream =\n\t\t\t\t\tnew StreamingOutputImpl((OutputStreamSender) value, reqlog);\n\t\t\t\tresponse =\n\t\t\t\t\t(\"put\".equals(method)) ?\n\t\t\t\t\tbuilder.put(ClientResponse.class, sentStream) :\n\t\t\t\t\tbuilder.post(ClientResponse.class, sentStream);\n\t\t\t} else {\n\t\t\t\tObject sentObj = (reqlog != null) ?\n\t\t\t\t\t\treqlog.copyContent(value) : value;\n\t\t\t\tresponse =\n\t\t\t\t\t(\"put\".equals(method)) ?\n\t\t\t\t\tbuilder.put(ClientResponse.class, sentObj) :\n\t\t\t\t\tbuilder.post(ClientResponse.class, sentObj);\n\t\t\t}\n\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tresponseHeaders = response.getHeaders();\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(responseHeaders.getFirst(\"Retry-After\"))) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresponse.close();\n\n\t\t\tif (!isResendable)\n\t\t\t\tthrow new ResourceNotResendableException(\n\t\t\t\t\t\t\"Cannot retry request for \" +\n\t\t\t\t\t\t ((uri != null) ? uri : \"new document\"));\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t}\n\t\tif (status == ClientResponse.Status.NOT_FOUND)\n\t\t\tthrow new ResourceNotFoundException(\n\t\t\t\t\t\"Could not write non-existent document\",\n\t\t\t\t\textractErrorFields(response));\n\t\tif (status == ClientResponse.Status.FORBIDDEN) {\n\t\t\tFailedRequest failure = extractErrorFields(response);\n\t\t\tif (failure.getMessageCode().equals(\"RESTAPI-CONTENTNOVERSION\"))\n\t\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\t\"Content version required to write document\", failure);\n\t\t\tthrow new ForbiddenUserException(\n\t\t\t\t\t\"User is not allowed to write documents\", failure);\n\t\t}\n\t\tif (status == ClientResponse.Status.PRECONDITION_FAILED) {\n\t\t\tFailedRequest failure = extractErrorFields(response);\n\t\t\tif (failure.getMessageCode().equals(\"RESTAPI-CONTENTWRONGVERSION\"))\n\t\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\t\"Content version must match to write document\", failure);\n\t\t\telse if (failure.getMessageCode().equals(\"RESTAPI-EMPTYBODY\"))\n\t\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\t\"Empty request body sent to server\", failure);\n\t\t\tthrow new FailedRequestException(\"Precondition Failed\", failure);\n\t\t}\n\t\tif (status != ClientResponse.Status.CREATED\n\t\t\t\t&& status != ClientResponse.Status.NO_CONTENT)\n\t\t\tthrow new FailedRequestException(\"write failed: \"\n\t\t\t\t\t+ status.getReasonPhrase(), extractErrorFields(response));\n\n\t\tif (uri == null) {\n\t\t\tString location = responseHeaders.getFirst(\"Location\");\n\t\t\tif (location != null) {\n\t\t\t\tint offset = location.indexOf(DOCUMENT_URI_PREFIX);\n\t\t\t\tif (offset == -1)\n\t\t\t\t\tthrow new MarkLogicInternalException(\n\t\t\t\t\t\t\t\"document create produced invalid location: \" + location);\n\t\t\t\turi = location.substring(offset + DOCUMENT_URI_PREFIX.length());\n\t\t\t\tif (uri == null)\n\t\t\t\t\tthrow new MarkLogicInternalException(\n\t\t\t\t\t\t\t\"document create produced location without uri: \" + location);\n\t\t\t\tdesc.setUri(uri);\n\t\t\t\tupdateVersion(desc, responseHeaders);\n\t\t\t\tupdateDescriptor(desc, responseHeaders);\n\t\t\t}\n\t\t}\n\n\t\tresponse.close();\n\t}\n\n\tprivate void putPostDocumentImpl(RequestLogger reqlog, String method, DocumentDescriptor desc,\n\t\t\tString transactionId, Set categories, RequestParameters extraParams,\n\t\t\tString metadataMimetype, DocumentMetadataWriteHandle metadataHandle, String contentMimetype,\n\t\t\tAbstractWriteHandle contentHandle)\n\tthrows ResourceNotFoundException, ResourceNotResendableException,\n\t\t\tForbiddenUserException, FailedRequestException {\n\t\tString uri = desc.getUri();\n\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Sending {} multipart document in transaction {}\",\n\t\t\t\t\t(uri != null) ? uri : \"new\", transactionId);\n\n\t\tlogRequest(\n\t\t\t\treqlog,\n\t\t\t\t\"writing %s document from %s transaction with %s metadata categories and content\",\n\t\t\t\t(uri != null) ? uri : \"new\",\n\t\t\t\t(transactionId != null) ? transactionId : \"no\",\n\t\t\t\tstringJoin(categories, \", \", \"no\"));\n\n\t\tMultivaluedMap docParams =\n\t\t\tmakeDocumentParams(uri, categories, transactionId, extraParams, true);\n\n\t\tWebResource.Builder builder = makeDocumentResource(docParams).getRequestBuilder();\n\t\tbuilder = addTransactionCookie(builder, transactionId);\n\t\tif (uri != null) {\n\t\t\tbuilder = addVersionHeader(desc, builder, \"If-Match\");\n\t\t}\n\n\t\tMediaType multipartType = Boundary.addBoundary(MultiPartMediaTypes.MULTIPART_MIXED_TYPE);\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tMultivaluedMap responseHeaders = null;\n\t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\t\tMultiPart multiPart = new MultiPart();\n\t\t\tboolean hasStreamingPart = addParts(multiPart, reqlog,\n\t\t\t\t\tnew String[] { metadataMimetype, contentMimetype },\n\t\t\t\t\tnew AbstractWriteHandle[] { metadataHandle, contentHandle });\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tmakeFirstRequest();\n\n\t\t\t// Must set multipart/mixed mime type explicitly on each request\n\t\t\t// because Jersey client 1.17 adapter for HttpClient switches\n\t\t\t// to application/octet-stream on retry\n\t\t\tWebResource.Builder requestBlder = builder.type(multipartType);\n\t\t\tresponse =\n\t\t\t\t(\"put\".equals(method)) ?\n\t\t\t\trequestBlder.put(ClientResponse.class, multiPart) :\n\t\t\t\trequestBlder.post(ClientResponse.class, multiPart);\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tresponseHeaders = response.getHeaders();\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(responseHeaders.getFirst(\"Retry-After\"))) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresponse.close();\n\n\t\t\tif (hasStreamingPart)\n\t\t\t\tthrow new ResourceNotResendableException(\n\t\t\t\t\t\t\"Cannot retry request for \" +\n\t\t\t\t\t\t((uri != null) ? uri : \"new document\"));\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t}\n\t\tif (status == ClientResponse.Status.NOT_FOUND) {\n\t\t\tresponse.close();\n\t\t\tthrow new ResourceNotFoundException(\n\t\t\t\t\t\"Could not write non-existent document\");\n\t\t}\n\t\tif (status == ClientResponse.Status.FORBIDDEN) {\n\t\t\tFailedRequest failure = extractErrorFields(response);\n\t\t\tif (failure.getMessageCode().equals(\"RESTAPI-CONTENTNOVERSION\"))\n\t\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\t\"Content version required to write document\", failure);\n\t\t\tthrow new ForbiddenUserException(\n\t\t\t\t\t\"User is not allowed to write documents\", failure);\n\t\t}\n\t\tif (status == ClientResponse.Status.PRECONDITION_FAILED) {\n\t\t\tFailedRequest failure = extractErrorFields(response);\n\t\t\tif (failure.getMessageCode().equals(\"RESTAPI-CONTENTWRONGVERSION\"))\n\t\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\t\"Content version must match to write document\", failure);\n\t\t\telse if (failure.getMessageCode().equals(\"RESTAPI-EMPTYBODY\"))\n\t\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\t\"Empty request body sent to server\", failure);\n\t\t\tthrow new FailedRequestException(\"Precondition Failed\", failure);\n\t\t}\n\t\tif (status != ClientResponse.Status.CREATED\n\t\t\t\t&& status != ClientResponse.Status.NO_CONTENT)\n\t\t\tthrow new FailedRequestException(\"write failed: \"\n\t\t\t\t\t+ status.getReasonPhrase(), extractErrorFields(response));\n\n\t\tif (uri == null) {\n\t\t\tString location = responseHeaders.getFirst(\"Location\");\n\t\t\tif (location != null) {\n\t\t\t\tint offset = location.indexOf(DOCUMENT_URI_PREFIX);\n\t\t\t\tif (offset == -1)\n\t\t\t\t\tthrow new MarkLogicInternalException(\n\t\t\t\t\t\t\t\"document create produced invalid location: \" + location);\n\t\t\t\turi = location.substring(offset + DOCUMENT_URI_PREFIX.length());\n\t\t\t\tif (uri == null)\n\t\t\t\t\tthrow new MarkLogicInternalException(\n\t\t\t\t\t\t\t\"document create produced location without uri: \" + location);\n\t\t\t\tdesc.setUri(uri);\n\t\t\t\tupdateVersion(desc, responseHeaders);\n\t\t\t\tupdateDescriptor(desc, responseHeaders);\n\t\t\t}\n\t\t}\n\n\t\tresponse.close();\n\t}\n\n\t@Override\n\tpublic void patchDocument(RequestLogger reqlog, DocumentDescriptor desc, String transactionId,\n\t\t\tSet categories, boolean isOnContent, DocumentPatchHandle patchHandle)\n\tthrows ResourceNotFoundException, ResourceNotResendableException,\n\t\t\tForbiddenUserException, FailedRequestException {\n\t\tHandleImplementation patchBase = HandleAccessor.checkHandle(\n\t\t\t\tpatchHandle, \"patch\");\n\n\t\tputPostDocumentImpl(reqlog, \"patch\", desc, transactionId, categories, isOnContent, null,\n\t\t\t\tpatchBase.getMimetype(), patchHandle);\n\t}\n\n\t@Override\n\tpublic String openTransaction(String name, int timeLimit)\n\t\t\tthrows ForbiddenUserException, FailedRequestException {\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Opening transaction\");\n\n\t\tMultivaluedMap transParams = null;\n\t\tif (name != null || timeLimit > 0) {\n\t\t\ttransParams = new MultivaluedMapImpl();\n\t\t\tif (name != null)\n\t\t\t\taddEncodedParam(transParams, \"name\", name);\n\t\t\tif (timeLimit > 0)\n\t\t\t\ttransParams.add(\"timeLimit\", String.valueOf(timeLimit));\n\t\t}\n\n\t\tWebResource resource = (transParams != null) ? connection.path(\n\t\t\t\t\"transactions\").queryParams(transParams) : connection\n\t\t\t\t.path(\"transactions\");\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\t\tresponse = resource.post(ClientResponse.class);\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t}\n\t\tif (status == ClientResponse.Status.FORBIDDEN)\n\t\t\tthrow new ForbiddenUserException(\n\t\t\t\t\t\"User is not allowed to open transactions\",\n\t\t\t\t\textractErrorFields(response));\n\t\tif (status != ClientResponse.Status.SEE_OTHER)\n\t\t\tthrow new FailedRequestException(\"transaction open failed: \"\n\t\t\t\t\t+ status.getReasonPhrase(), extractErrorFields(response));\n\n\t\tString location = response.getHeaders().getFirst(\"Location\");\n\t\tresponse.close();\n\t\tif (location == null)\n\t\t\tthrow new MarkLogicInternalException(\n\t\t\t\t\t\"transaction open failed to provide location\");\n\t\tif (!location.contains(\"/\"))\n\t\t\tthrow new MarkLogicInternalException(\n\t\t\t\t\t\"transaction open produced invalid location \" + location);\n\n\t\treturn location.substring(location.lastIndexOf(\"/\") + 1);\n\t}\n\n\t@Override\n\tpublic void commitTransaction(String transactionId)\n\t\t\tthrows ForbiddenUserException, FailedRequestException {\n\t\tcompleteTransaction(transactionId, \"commit\");\n\t}\n\n\t@Override\n\tpublic void rollbackTransaction(String transactionId)\n\t\t\tthrows ForbiddenUserException, FailedRequestException {\n\t\tcompleteTransaction(transactionId, \"rollback\");\n\t}\n\n\tprivate void completeTransaction(String transactionId, String result)\n\t\t\tthrows ForbiddenUserException, FailedRequestException {\n\t\tif (result == null)\n\t\t\tthrow new MarkLogicInternalException(\n\t\t\t\t\t\"transaction completion without operation\");\n\t\tif (transactionId == null)\n\t\t\tthrow new MarkLogicInternalException(\n\t\t\t\t\t\"transaction completion without id: \" + result);\n\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Completing transaction {} with {}\", transactionId,\n\t\t\t\t\tresult);\n\n\t\tMultivaluedMap transParams = new MultivaluedMapImpl();\n\t\ttransParams.add(\"result\", result);\n\n\t\tWebResource webResource = connection.path(\"transactions/\" + transactionId)\n\t\t\t\t.queryParams(transParams);\n\n\t\tWebResource.Builder builder = webResource.getRequestBuilder();\n\t\tbuilder = addTransactionCookie(builder, transactionId);\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\t\tresponse = builder.post(ClientResponse.class);\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t}\n\t\tif (status == ClientResponse.Status.FORBIDDEN)\n\t\t\tthrow new ForbiddenUserException(\n\t\t\t\t\t\"User is not allowed to complete transaction with \"\n\t\t\t\t\t\t\t+ result, extractErrorFields(response));\n\t\tif (status != ClientResponse.Status.NO_CONTENT)\n\t\t\tthrow new FailedRequestException(\"transaction \" + result\n\t\t\t\t\t+ \" failed: \" + status.getReasonPhrase(),\n\t\t\t\t\textractErrorFields(response));\n\n\t\tresponse.close();\n\t}\n\n\tprivate MultivaluedMap makeDocumentParams(String uri,\n\t\t\tSet categories, String transactionId,\n\t\t\tRequestParameters extraParams) {\n\t\treturn makeDocumentParams(uri, categories, transactionId, extraParams,\n\t\t\t\tfalse);\n\t}\n\n\tprivate MultivaluedMap makeDocumentParams(String uri,\n\t\t\tSet categories, String transactionId,\n\t\t\tRequestParameters extraParams, boolean withContent) {\n\t\tMultivaluedMap docParams = new MultivaluedMapImpl();\n\t\tif (extraParams != null && extraParams.size() > 0) {\n\t\t\tfor (Map.Entry> entry : extraParams.entrySet()) {\n\t\t\t\tString extraKey = entry.getKey();\n\t\t\t\tif (!\"range\".equalsIgnoreCase(extraKey)) {\n\t\t\t\t\taddEncodedParam(docParams, extraKey, entry.getValue());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\taddEncodedParam(docParams, \"uri\", uri);\n\t\tif (categories == null || categories.size() == 0) {\n\t\t\tdocParams.add(\"category\", \"content\");\n\t\t} else {\n\t\t\tif (withContent)\n\t\t\t\tdocParams.add(\"category\", \"content\");\n\t\t\tif (categories.contains(Metadata.ALL)) {\n\t\t\t\tdocParams.add(\"category\", \"metadata\");\n\t\t\t} else {\n\t\t\t\tfor (Metadata category : categories)\n\t\t\t\t\tdocParams.add(\"category\", category.name().toLowerCase());\n\t\t\t}\n\t\t}\n\t\tif (transactionId != null) {\n\t\t\tdocParams.add(\"txid\", transactionId);\n\t\t}\n\t\treturn docParams;\n\t}\n\n\tprivate WebResource makeDocumentResource(\n\t\t\tMultivaluedMap queryParams) {\n\t\treturn connection.path(\"documents\").queryParams(queryParams);\n\t}\n\n\tprivate boolean isExternalDescriptor(ContentDescriptor desc) {\n\t\treturn desc != null && desc instanceof DocumentDescriptorImpl\n\t\t\t\t&& !((DocumentDescriptorImpl) desc).isInternal();\n\t}\n\n\tprivate void updateDescriptor(ContentDescriptor desc,\n\t\t\tMultivaluedMap headers) {\n\t\tif (desc == null || headers == null)\n\t\t\treturn;\n\n\t\tupdateFormat(desc, headers);\n\t\tupdateMimetype(desc, headers);\n\t\tupdateLength(desc, headers);\n\t}\n\n\tprivate void copyDescriptor(DocumentDescriptor desc,\n\t\t\tHandleImplementation handleBase) {\n\t\tif (handleBase == null)\n\t\t\treturn;\n\n\t\thandleBase.setFormat(desc.getFormat());\n\t\thandleBase.setMimetype(desc.getMimetype());\n\t\thandleBase.setByteLength(desc.getByteLength());\n\t}\n\n\tprivate void updateFormat(ContentDescriptor descriptor,\n\t\t\tMultivaluedMap headers) {\n\t\tupdateFormat(descriptor, getHeaderFormat(headers));\n\t}\n\n\tprivate void updateFormat(ContentDescriptor descriptor, Format format) {\n\t\tif (format != null) {\n\t\t\tdescriptor.setFormat(format);\n\t\t}\n\t}\n\n\tprivate Format getHeaderFormat(MultivaluedMap headers) {\n\t\tif (headers.containsKey(\"vnd.marklogic.document-format\")) {\n\t\t\tList values = headers.get(\"vnd.marklogic.document-format\");\n\t\t\tif (values != null) {\n\t\t\t\treturn Format.valueOf(values.get(0).toUpperCase());\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tprivate void updateMimetype(ContentDescriptor descriptor,\n\t\t\tMultivaluedMap headers) {\n\t\tupdateMimetype(descriptor, getHeaderMimetype(headers));\n\t}\n\n\tprivate void updateMimetype(ContentDescriptor descriptor, String mimetype) {\n\t\tif (mimetype != null) {\n\t\t\tdescriptor.setMimetype(mimetype);\n\t\t}\n\t}\n\n\tprivate String getHeaderMimetype(MultivaluedMap headers) {\n\t\tif (headers.containsKey(\"Content-Type\")) {\n\t\t\tList values = headers.get(\"Content-Type\");\n\t\t\tif (values != null) {\n\t\t\t\tString contentType = values.get(0);\n\t\t\t\tString mimetype = contentType.contains(\";\") ? contentType\n\t\t\t\t\t\t.substring(0, contentType.indexOf(\";\")) : contentType;\n\t\t\t\t// TODO: if \"; charset=foo\" set character set\n\t\t\t\tif (mimetype != null && mimetype.length() > 0) {\n\t\t\t\t\treturn mimetype;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tprivate void updateLength(ContentDescriptor descriptor,\n\t\t\tMultivaluedMap headers) {\n\t\tupdateLength(descriptor, getHeaderLength(headers));\n\t}\n\n\tprivate void updateLength(ContentDescriptor descriptor, long length) {\n\t\tdescriptor.setByteLength(length);\n\t}\n\n\tprivate long getHeaderLength(MultivaluedMap headers) {\n\t\tif (headers.containsKey(\"Content-Length\")) {\n\t\t\tList values = headers.get(\"Content-Length\");\n\t\t\tif (values != null) {\n\t\t\t\treturn Long.valueOf(values.get(0));\n\t\t\t}\n\t\t}\n\t\treturn ContentDescriptor.UNKNOWN_LENGTH;\n\t}\n\n\tprivate void updateVersion(DocumentDescriptor descriptor,\n\t\t\tMultivaluedMap headers) {\n\t\tlong version = DocumentDescriptor.UNKNOWN_VERSION;\n\t\tif (headers.containsKey(\"ETag\")) {\n\t\t\tList values = headers.get(\"ETag\");\n\t\t\tif (values != null) {\n\t\t\t\t// trim the double quotes\n\t\t\t\tString value = values.get(0);\n\t\t\t\tversion = Long.valueOf(value.substring(1, value.length() - 1));\n\t\t\t}\n\t\t}\n\t\tdescriptor.setVersion(version);\n\t}\n\n\tprivate WebResource.Builder addTransactionCookie(\n\t\t\tWebResource.Builder builder, String transactionId) {\n\t\tif (transactionId != null) {\n\t\t\tint pos = transactionId.indexOf(\"_\");\n\t\t\tif (pos != -1) {\n\t\t\t\tString hostId = transactionId.substring(0, pos);\n\t\t\t\tbuilder.cookie(new Cookie(\"HostId\", hostId));\n\t\t\t} else {\n\t\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\t\"transaction id without host id separator: \"+transactionId\n\t\t\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\treturn builder;\n\t}\n\n\tprivate WebResource.Builder addVersionHeader(DocumentDescriptor desc,\n\t\t\tWebResource.Builder builder, String name) {\n\t\tif (desc != null && desc instanceof DocumentDescriptorImpl\n\t\t\t\t&& !((DocumentDescriptorImpl) desc).isInternal()) {\n\t\t\tlong version = desc.getVersion();\n\t\t\tif (version != DocumentDescriptor.UNKNOWN_VERSION) {\n\t\t\t\treturn builder.header(name, \"\\\"\" + String.valueOf(version)\n\t\t\t\t\t\t+ \"\\\"\");\n\t\t\t}\n\t\t}\n\t\treturn builder;\n\t}\n\n\t@Override\n\tpublic T search(RequestLogger reqlog, Class as, QueryDefinition queryDef, String mimetype,\n\t\t\tlong start, long len, QueryView view, String transactionId\n\t) throws ForbiddenUserException, FailedRequestException {\n\t\tMultivaluedMap params = new MultivaluedMapImpl();\n\n\t\tif (start > 1) {\n\t\t\tparams.add(\"start\", Long.toString(start));\n\t\t}\n\n\t\tif (len > 0) {\n\t\t\tparams.add(\"pageLength\", Long.toString(len));\n\t\t}\n\n\t\tif (transactionId != null) {\n\t\t\tparams.add(\"txid\", transactionId);\n\t\t}\n\n\t\tif (view != null && view != QueryView.DEFAULT) {\n\t\t\tif (view == QueryView.ALL) {\n\t\t\t\tparams.add(\"view\", \"all\");\n\t\t\t} else if (view == QueryView.RESULTS) {\n\t\t\t\tparams.add(\"view\", \"results\");\n\t\t\t} else if (view == QueryView.FACETS) {\n\t\t\t\tparams.add(\"view\", \"facets\");\n\t\t\t} else if (view == QueryView.METADATA) {\n\t\t\t\tparams.add(\"view\", \"metadata\");\n\t\t\t}\n\t\t}\n\n\t\tT entity = search(reqlog, as, queryDef, mimetype, params);\n\n\t\tlogRequest(\n\t\t\t\treqlog,\n\t\t\t\t\"searched starting at %s with length %s in %s transaction with %s mime type\",\n\t\t\t\tstart, len, transactionId, mimetype);\n\t\t\n\t\treturn entity;\n\t}\n\t@Override\n\tpublic T search(\n\t\t\tRequestLogger reqlog, Class as, QueryDefinition queryDef, String mimetype, String view\n\t) throws ForbiddenUserException, FailedRequestException {\n\t\tMultivaluedMap params = new MultivaluedMapImpl();\n\n\t\tif (view != null) {\n\t\t\tparams.add(\"view\", view);\n\t\t}\n\n\t\treturn search(reqlog, as, queryDef, mimetype, params);\n\t}\n\tprivate T search(RequestLogger reqlog, Class as, QueryDefinition queryDef, String mimetype,\n\t\t\tMultivaluedMap params\n\t) throws ForbiddenUserException, FailedRequestException {\n\n\t\tString directory = queryDef.getDirectory();\n\t\tif (directory != null) {\n\t\t\taddEncodedParam(params, \"directory\", directory);\n\t\t}\n\n\t\taddEncodedParam(params, \"collection\", queryDef.getCollections());\n\n\t\tString optionsName = queryDef.getOptionsName();\n\t\tif (optionsName != null && optionsName.length() > 0) {\n\t\t\taddEncodedParam(params, \"options\", optionsName);\n\t\t}\n\n\t\tServerTransform transform = queryDef.getResponseTransform();\n\t\tif (transform != null) {\n\t\t\ttransform.merge(params);\n\t\t}\n\n\t\tWebResource.Builder builder = null;\n\t\tString structure = null;\n\t\tHandleImplementation baseHandle = null;\n\n\t\tif (queryDef instanceof RawQueryDefinition) {\n\t\t\tif (logger.isDebugEnabled())\n\t\t\t\tlogger.debug(\"Raw search\");\n\n\t\t\tStructureWriteHandle handle =\n\t\t\t\t((RawQueryDefinition) queryDef).getHandle();\n\n\t\t\tbaseHandle = HandleAccessor.checkHandle(handle, \"search\");\n\n\t\t\tFormat payloadFormat = baseHandle.getFormat();\n\t\t\tif (payloadFormat == Format.UNKNOWN)\n\t\t\t\tpayloadFormat = null;\n\t\t\telse if (payloadFormat != Format.XML && payloadFormat != Format.JSON)\n\t\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\t\"Cannot perform raw search for \"+payloadFormat.name());\n\n\t\t\tString payloadMimetype = baseHandle.getMimetype();\n\t\t\tif (payloadFormat != null) {\n\t\t\t\tif (payloadMimetype == null)\n\t\t\t\t\tpayloadMimetype = payloadFormat.getDefaultMimetype();\n\t\t\t\tparams.add(\"format\", payloadFormat.toString().toLowerCase());\n\t\t\t} else if (payloadMimetype == null) {\n\t\t\t\tpayloadMimetype = \"application/xml\";\n\t\t\t}\n\n\t\t\tString path = (queryDef instanceof RawQueryByExampleDefinition) ?\n\t\t\t\t\t\"qbe\" : \"search\";\n\n\t\t\tWebResource resource = connection.path(path).queryParams(params);\n\t\t\tbuilder = (payloadMimetype != null) ?\n\t\t\t\t\tresource.type(payloadMimetype).accept(mimetype) :\n\t\t\t\t\tresource.accept(mimetype);\n\t\t} else if (queryDef instanceof StringQueryDefinition) {\n\t\t\tString text = ((StringQueryDefinition) queryDef).getCriteria();\n\t\t\tif (logger.isDebugEnabled())\n\t\t\t\tlogger.debug(\"Searching for {}\", text);\n\n\t\t\tif (text != null) {\n\t\t\t\taddEncodedParam(params, \"q\", text);\n\t\t\t}\n\n\t\t\tbuilder = connection.path(\"search\").queryParams(params)\n\t\t\t\t.type(\"application/xml\").accept(mimetype);\n\t\t} else if (queryDef instanceof KeyValueQueryDefinition) {\n\t\t\tif (logger.isDebugEnabled())\n\t\t\t\tlogger.debug(\"Searching for keys/values\");\n\n\t\t\tMap pairs = ((KeyValueQueryDefinition) queryDef);\n\t\t\tfor (Map.Entry entry: pairs.entrySet()) {\n\t\t\t\tValueLocator loc = entry.getKey();\n\t\t\t\tif (loc instanceof KeyLocator) {\n\t\t\t\t\taddEncodedParam(params, \"key\", ((KeyLocator) loc).getKey());\n\t\t\t\t} else {\n\t\t\t\t\tElementLocator eloc = (ElementLocator) loc;\n\t\t\t\t\tparams.add(\"element\", eloc.getElement().toString());\n\t\t\t\t\tif (eloc.getAttribute() != null) {\n\t\t\t\t\t\tparams.add(\"attribute\", eloc.getAttribute().toString());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\taddEncodedParam(params, \"value\", entry.getValue());\n\t\t\t}\n\n\t\t\tbuilder = connection.path(\"keyvalue\").queryParams(params)\n\t\t\t\t\t.accept(mimetype);\n\t\t} else if (queryDef instanceof StructuredQueryDefinition) {\n\t\t\tstructure = ((StructuredQueryDefinition) queryDef).serialize();\n\n\t\t\tif (logger.isDebugEnabled())\n\t\t\t\tlogger.debug(\"Searching for structure {}\", structure);\n\n\t\t\tbuilder = connection.path(\"search\").queryParams(params)\n\t\t\t\t\t.type(\"application/xml\").accept(mimetype);\n\t\t} else if (queryDef instanceof DeleteQueryDefinition) {\n\t\t\tif (logger.isDebugEnabled())\n\t\t\t\tlogger.debug(\"Searching for deletes\");\n\n\t\t\tbuilder = connection.path(\"search\").queryParams(params)\n\t\t\t\t\t.accept(mimetype);\n\t\t} else {\n\t\t\tthrow new UnsupportedOperationException(\"Cannot search with \"\n\t\t\t\t\t+ queryDef.getClass().getName());\n\t\t}\n\n\t\tif (params.containsKey(\"txid\")) {\n\t\t\tbuilder = addTransactionCookie(builder, params.getFirst(\"txid\"));\n\t\t}\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\t\tif (queryDef instanceof StringQueryDefinition) {\n\t\t\t\tresponse = doGet(builder);\n\t\t\t} else if (queryDef instanceof KeyValueQueryDefinition) {\n\t\t\t\tresponse = doGet(builder);\n\t\t\t} else if (queryDef instanceof StructuredQueryDefinition) {\n\t\t\t\tresponse = doPost(reqlog, builder, structure, true);\n\t\t\t} else if (queryDef instanceof DeleteQueryDefinition) {\n\t\t\t\tresponse = doGet(builder);\n\t\t\t} else if (queryDef instanceof RawQueryDefinition) {\n\t\t\t\tresponse = doPost(reqlog, builder, baseHandle.sendContent(), true);\n\t\t\t} else {\n\t\t\t\tthrow new UnsupportedOperationException(\"Cannot search with \"\n\t\t\t\t\t\t+ queryDef.getClass().getName());\n\t\t\t}\n\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t}\n\t\tif (status == ClientResponse.Status.FORBIDDEN) {\n\t\t\tthrow new ForbiddenUserException(\"User is not allowed to search\",\n\t\t\t\t\textractErrorFields(response));\n\t\t}\n\t\tif (status != ClientResponse.Status.OK) {\n\t\t\tthrow new FailedRequestException(\"search failed: \"\n\t\t\t\t\t+ status.getReasonPhrase(), extractErrorFields(response));\n\t\t}\n\n\t\tT entity = response.hasEntity() ? response.getEntity(as) : null;\n\t\tif (entity == null || (as != InputStream.class && as != Reader.class))\n\t\t\tresponse.close();\n\n\t\treturn entity;\n\t}\n\n\t@Override\n\tpublic void deleteSearch(RequestLogger reqlog, DeleteQueryDefinition queryDef,\n\t\t\tString transactionId) throws ForbiddenUserException,\n\t\t\tFailedRequestException {\n\t\tMultivaluedMap params = new MultivaluedMapImpl();\n\n\t\tif (queryDef.getDirectory() != null) {\n\t\t\taddEncodedParam(params, \"directory\", queryDef.getDirectory());\n\t\t}\n\n\t\taddEncodedParam(params, \"collection\", queryDef.getCollections());\n\n\t\tif (transactionId != null) {\n\t\t\tparams.add(\"txid\", transactionId);\n\t\t}\n\n\t\tWebResource webResource = connection.path(\"search\").queryParams(params);\n\n\t\tWebResource.Builder builder = webResource.getRequestBuilder();\n\t\tbuilder = addTransactionCookie(builder, transactionId);\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\t\tresponse = builder.delete(ClientResponse.class);\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t}\n\t\tif (status == ClientResponse.Status.FORBIDDEN) {\n\t\t\tthrow new ForbiddenUserException(\"User is not allowed to delete\",\n\t\t\t\t\textractErrorFields(response));\n\t\t}\n\n\t\tif (status != ClientResponse.Status.NO_CONTENT) {\n\t\t\tthrow new FailedRequestException(\"delete failed: \"\n\t\t\t\t\t+ status.getReasonPhrase(), extractErrorFields(response));\n\t\t}\n\t\t\n\t\tlogRequest(\n\t\t\t\treqlog,\n\t\t\t\t\"deleted search results in %s transaction\",\n\t\t\t\ttransactionId);\n\t}\n\n\t@Override\n\tpublic T values(Class as, ValuesDefinition valDef, String mimetype,\n\t\t\tString transactionId) throws ForbiddenUserException,\n\t\t\tFailedRequestException {\n\t\tMultivaluedMap docParams = new MultivaluedMapImpl();\n\n\t\tString optionsName = valDef.getOptionsName();\n\t\tif (optionsName != null && optionsName.length() > 0) {\n\t\t\taddEncodedParam(docParams, \"options\", optionsName);\n\t\t}\n\n\t\tif (valDef.getAggregate() != null) {\n\t\t\taddEncodedParam(docParams, \"aggregate\", valDef.getAggregate());\n\t\t}\n\n\t\tif (valDef.getAggregatePath() != null) {\n\t\t\taddEncodedParam(docParams, \"aggregatePath\",\n\t\t\t\t\tvalDef.getAggregatePath());\n\t\t}\n\n\t\tif (valDef.getView() != null) {\n\t\t\tdocParams.add(\"view\", valDef.getView());\n\t\t}\n\n\t\tif (valDef.getDirection() != null) {\n\t\t\tif (valDef.getDirection() == ValuesDefinition.Direction.ASCENDING) {\n\t\t\t\tdocParams.add(\"direction\", \"ascending\");\n\t\t\t} else {\n\t\t\t\tdocParams.add(\"direction\", \"descending\");\n\t\t\t}\n\t\t}\n\n\t\tif (valDef.getFrequency() != null) {\n\t\t\tif (valDef.getFrequency() == ValuesDefinition.Frequency.FRAGMENT) {\n\t\t\t\tdocParams.add(\"frequency\", \"fragment\");\n\t\t\t} else {\n\t\t\t\tdocParams.add(\"frequency\", \"item\");\n\t\t\t}\n\t\t}\n\n\t\tHandleImplementation baseHandle = null;\n\n\t\tif (valDef.getQueryDefinition() != null) {\n\t\t\tValueQueryDefinition queryDef = valDef.getQueryDefinition();\n\n\t\t\tif (optionsName == null) {\n\t\t\t\toptionsName = queryDef.getOptionsName();\n\t\t\t\tif (optionsName != null) {\n\t\t\t\t\taddEncodedParam(docParams, \"options\", optionsName);\n\t\t\t\t}\n\t\t\t} else if (queryDef.getOptionsName() != null) {\n\t\t\t\tif (optionsName != queryDef.getOptionsName()\n\t\t\t\t\t\t&& logger.isWarnEnabled())\n\t\t\t\t\tlogger.warn(\"values definition options take precedence over query definition options\");\n\t\t\t}\n\n\t\t\tif (queryDef.getCollections() != null) {\n\t\t\t\tif (logger.isWarnEnabled())\n\t\t\t\t\tlogger.warn(\"collections scope ignored for values query\");\n\t\t\t}\n\t\t\tif (queryDef.getDirectory() != null) {\n\t\t\t\tif (logger.isWarnEnabled())\n\t\t\t\t\tlogger.warn(\"directory scope ignored for values query\");\n\t\t\t}\n\n\t\t\tif (queryDef instanceof StringQueryDefinition) {\n\t\t\t\tString text = ((StringQueryDefinition) queryDef).getCriteria();\n\t\t\t\tif (text != null) {\n\t\t\t\t\taddEncodedParam(docParams, \"q\", text);\n\t\t\t\t}\n\t\t\t} else if (queryDef instanceof StructuredQueryDefinition) {\n\t\t\t\tString structure = ((StructuredQueryDefinition) queryDef)\n\t\t\t\t\t\t.serialize();\n\t\t\t\tif (structure != null) {\n\t\t\t\t\taddEncodedParam(docParams, \"structuredQuery\", structure);\n\t\t\t\t}\n\t\t\t} else if (queryDef instanceof RawQueryDefinition) {\n StructureWriteHandle handle = ((RawQueryDefinition) queryDef).getHandle();\n baseHandle = HandleAccessor.checkHandle(handle, \"values\");\n } else {\n\t\t\t\tif (logger.isWarnEnabled())\n\t\t\t\t\tlogger.warn(\"unsupported query definition: \"\n\t\t\t\t\t\t\t+ queryDef.getClass().getName());\n\t\t\t}\n\n\t\t\tServerTransform transform = queryDef.getResponseTransform();\n\t\t\tif (transform != null) {\n\t\t\t\ttransform.merge(docParams);\n\t\t\t}\n\t\t}\n\n\t\tif (transactionId != null) {\n\t\t\tdocParams.add(\"txid\", transactionId);\n\t\t}\n\n\t\tString uri = \"values\";\n\t\tif (valDef.getName() != null) {\n\t\t\turi += \"/\" + valDef.getName();\n\t\t}\n\n\t\tWebResource.Builder builder = connection.path(uri)\n\t\t\t\t.queryParams(docParams).accept(mimetype);\n\t\tbuilder = addTransactionCookie(builder, transactionId);\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\n response = baseHandle == null ?\n doGet(builder) :\n doPost(null, builder.type(baseHandle.getMimetype()), baseHandle.sendContent(), baseHandle.isResendable());\n\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t}\n\t\tif (status == ClientResponse.Status.FORBIDDEN) {\n\t\t\tthrow new ForbiddenUserException(\"User is not allowed to search\",\n\t\t\t\t\textractErrorFields(response));\n\t\t}\n\t\tif (status != ClientResponse.Status.OK) {\n\t\t\tthrow new FailedRequestException(\"search failed: \"\n\t\t\t\t\t+ status.getReasonPhrase(), extractErrorFields(response));\n\t\t}\n\n\t\tT entity = response.hasEntity() ? response.getEntity(as) : null;\n\t\tif (entity == null || (as != InputStream.class && as != Reader.class))\n\t\t\tresponse.close();\n\n\t\treturn entity;\n\t\t\n\t}\n\n\t@Override\n\tpublic T valuesList(Class as, ValuesListDefinition valDef,\n\t\t\tString mimetype, String transactionId)\n\t\t\tthrows ForbiddenUserException, FailedRequestException {\n\t\tMultivaluedMap docParams = new MultivaluedMapImpl();\n\n\t\tString optionsName = valDef.getOptionsName();\n\t\tif (optionsName != null && optionsName.length() > 0) {\n\t\t\taddEncodedParam(docParams, \"options\", optionsName);\n\t\t}\n\n\t\tif (transactionId != null) {\n\t\t\tdocParams.add(\"txid\", transactionId);\n\t\t}\n\n\t\tString uri = \"values\";\n\n\t\tWebResource.Builder builder = connection.path(uri)\n\t\t\t\t.queryParams(docParams).accept(mimetype);\n\t\tbuilder = addTransactionCookie(builder, transactionId);\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\t\tresponse = builder.get(ClientResponse.class);\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t}\n\t\tif (status == ClientResponse.Status.FORBIDDEN) {\n\t\t\tthrow new ForbiddenUserException(\"User is not allowed to search\",\n\t\t\t\t\textractErrorFields(response));\n\t\t}\n\t\tif (status != ClientResponse.Status.OK) {\n\t\t\tthrow new FailedRequestException(\"search failed: \"\n\t\t\t\t\t+ status.getReasonPhrase(), extractErrorFields(response));\n\t\t}\n\n\t\tT entity = response.hasEntity() ? response.getEntity(as) : null;\n\t\tif (entity == null || (as != InputStream.class && as != Reader.class))\n\t\t\tresponse.close();\n\n\t\treturn entity;\n\t}\n\n\t@Override\n\tpublic T optionsList(Class as, String mimetype, String transactionId)\n\t\t\tthrows ForbiddenUserException, FailedRequestException {\n\t\tMultivaluedMap docParams = new MultivaluedMapImpl();\n\n\t\tif (transactionId != null) {\n\t\t\tdocParams.add(\"txid\", transactionId);\n\t\t}\n\n\t\tString uri = \"config/query\";\n\n\t\tWebResource.Builder builder = connection.path(uri)\n\t\t\t\t.queryParams(docParams).accept(mimetype);\n\t\tbuilder = addTransactionCookie(builder, transactionId);\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\t\tresponse = builder.get(ClientResponse.class);\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t}\n\t\tif (status == ClientResponse.Status.FORBIDDEN) {\n\t\t\tthrow new ForbiddenUserException(\"User is not allowed to search\",\n\t\t\t\t\textractErrorFields(response));\n\t\t}\n\t\tif (status != ClientResponse.Status.OK) {\n\t\t\tthrow new FailedRequestException(\"search failed: \"\n\t\t\t\t\t+ status.getReasonPhrase(), extractErrorFields(response));\n\t\t}\n\n\t\tT entity = response.hasEntity() ? response.getEntity(as) : null;\n\t\tif (entity == null || (as != InputStream.class && as != Reader.class))\n\t\t\tresponse.close();\n\n\t\treturn entity;\n\t}\n\n\t// namespaces, search options etc.\n\t@Override\n\tpublic T getValue(RequestLogger reqlog, String type, String key,\n\t\t\tboolean isNullable, String mimetype, Class as)\n\t\t\tthrows ResourceNotFoundException, ForbiddenUserException,\n\t\t\tFailedRequestException {\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Getting {}/{}\", type, key);\n\n\t\tWebResource.Builder builder = connection.path(type + \"/\" + key).accept(\n\t\t\t\tmimetype);\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\t\tresponse = builder.get(ClientResponse.class);\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t}\n\t\tif (status != ClientResponse.Status.OK) {\n\t\t\tif (status == ClientResponse.Status.NOT_FOUND) {\n\t\t\t\tresponse.close();\n\t\t\t\tif (!isNullable)\n\t\t\t\t\tthrow new ResourceNotFoundException(\"Could not get \" + type\n\t\t\t\t\t\t\t+ \"/\" + key);\n\t\t\t\treturn null;\n\t\t\t} else if (status == ClientResponse.Status.FORBIDDEN)\n\t\t\t\tthrow new ForbiddenUserException(\"User is not allowed to read \"\n\t\t\t\t\t\t+ type, extractErrorFields(response));\n\t\t\telse\n\t\t\t\tthrow new FailedRequestException(type + \" read failed: \"\n\t\t\t\t\t\t+ status.getReasonPhrase(),\n\t\t\t\t\t\textractErrorFields(response));\n\t\t}\n\n\t\tlogRequest(reqlog, \"read %s value with %s key and %s mime type\", type,\n\t\t\t\tkey, (mimetype != null) ? mimetype : null);\n\n\t\tT entity = response.hasEntity() ? response.getEntity(as) : null;\n\t\tif (entity == null || (as != InputStream.class && as != Reader.class))\n\t\t\tresponse.close();\n\n\t\treturn (reqlog != null) ? reqlog.copyContent(entity) : entity;\n\t}\n\n\t@Override\n\tpublic T getValues(RequestLogger reqlog, String type, String mimetype, Class as)\n\tthrows ForbiddenUserException, FailedRequestException {\n\t\treturn getValues(reqlog, type, null, mimetype, as);\n\t}\n\t@Override\n\tpublic T getValues(RequestLogger reqlog, String type, RequestParameters extraParams,\n\t\t\tString mimetype, Class as)\n\tthrows ForbiddenUserException, FailedRequestException {\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Getting {}\", type);\n\n\t\tMultivaluedMap requestParams = convertParams(extraParams);\n\n\t\tWebResource.Builder builder = (requestParams == null) ?\n\t\t\t\tconnection.path(type).accept(mimetype) :\n\t\t\t\tconnection.path(type).queryParams(requestParams).accept(mimetype);\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\t\tresponse = builder.get(ClientResponse.class);\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t}\n\t\tif (status == ClientResponse.Status.FORBIDDEN) {\n\t\t\tthrow new ForbiddenUserException(\"User is not allowed to read \"\n\t\t\t\t\t+ type, extractErrorFields(response));\n\t\t}\n\t\tif (status != ClientResponse.Status.OK) {\n\t\t\tthrow new FailedRequestException(type + \" read failed: \"\n\t\t\t\t\t+ status.getReasonPhrase(), extractErrorFields(response));\n\t\t}\n\n\t\tlogRequest(reqlog, \"read %s values with %s mime type\", type,\n\t\t\t\t(mimetype != null) ? mimetype : null);\n\n\t\tT entity = response.hasEntity() ? response.getEntity(as) : null;\n\t\tif (entity == null || (as != InputStream.class && as != Reader.class))\n\t\t\tresponse.close();\n\n\t\treturn (reqlog != null) ? reqlog.copyContent(entity) : entity;\n\t}\n\n\t@Override\n\tpublic void postValue(RequestLogger reqlog, String type, String key,\n\t\t\tString mimetype, Object value)\n\t\t\tthrows ResourceNotResendableException, ForbiddenUserException,\n\t\t\tFailedRequestException {\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Posting {}/{}\", type, key);\n\n\t\tputPostValueImpl(reqlog, \"post\", type, key, null, mimetype, value,\n\t\t\t\tClientResponse.Status.CREATED);\n\t}\n\t@Override\n\tpublic void postValue(RequestLogger reqlog, String type, String key,\n\t\t\tRequestParameters extraParams\n\t) throws ResourceNotResendableException, ForbiddenUserException, FailedRequestException\n\t{\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Posting {}/{}\", type, key);\n\n\t\tputPostValueImpl(reqlog, \"post\", type, key, extraParams, null, null,\n\t\t\t\tClientResponse.Status.NO_CONTENT);\n\t}\n\n\n\t@Override\n\tpublic void putValue(RequestLogger reqlog, String type, String key,\n\t\t\tString mimetype, Object value) throws ResourceNotFoundException,\n\t\t\tResourceNotResendableException, ForbiddenUserException,\n\t\t\tFailedRequestException {\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Putting {}/{}\", type, key);\n\n\t\tputPostValueImpl(reqlog, \"put\", type, key, null, mimetype, value,\n\t\t\t\tClientResponse.Status.NO_CONTENT, ClientResponse.Status.CREATED);\n\t}\n\n\t@Override\n\tpublic void putValue(RequestLogger reqlog, String type, String key,\n\t\t\tRequestParameters extraParams, String mimetype, Object value)\n\t\t\tthrows ResourceNotFoundException, ResourceNotResendableException,\n\t\t\tForbiddenUserException, FailedRequestException {\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Putting {}/{}\", type, key);\n\n\t\tputPostValueImpl(reqlog, \"put\", type, key, extraParams, mimetype,\n\t\t\t\tvalue, ClientResponse.Status.NO_CONTENT);\n\t}\n\n\tprivate void putPostValueImpl(RequestLogger reqlog, String method,\n\t\t\tString type, String key, RequestParameters extraParams,\n\t\t\tString mimetype, Object value,\n\t\t\tClientResponse.Status... expectedStatuses) {\n\t\tif (key != null) {\n\t\t\tlogRequest(reqlog, \"writing %s value with %s key and %s mime type\",\n\t\t\t\t\ttype, key, (mimetype != null) ? mimetype : null);\n\t\t} else {\n\t\t\tlogRequest(reqlog, \"writing %s values with %s mime type\", type,\n\t\t\t\t\t(mimetype != null) ? mimetype : null);\n\t\t}\n\n\t\tHandleImplementation handle = (value instanceof HandleImplementation) ?\n\t\t\t\t(HandleImplementation) value : null;\n\n\t\tMultivaluedMap requestParams = convertParams(extraParams);\n\n\t\tString connectPath = null;\n\t\tWebResource.Builder builder = null;\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\t\tObject nextValue = (handle != null) ? handle.sendContent() : value;\n\n\t\t\tObject sentValue = null;\n\t\t\tif (nextValue instanceof OutputStreamSender) {\n\t\t\t\tsentValue = new StreamingOutputImpl(\n\t\t\t\t\t\t(OutputStreamSender) nextValue, reqlog);\n\t\t\t} else {\n\t\t\t\tif (reqlog != null && retry == 0)\n\t\t\t\t\tsentValue = reqlog.copyContent(nextValue);\n\t\t\t\telse\n\t\t\t\t\tsentValue = nextValue;\n\t\t\t}\n\n\t\t\tboolean isStreaming = (isFirstRequest || handle == null) ? isStreaming(sentValue)\n\t\t\t\t\t: false;\n\n\t\t\tboolean isResendable = (handle == null) ? !isStreaming :\n\t\t\t\thandle.isResendable();\n\n\t\t\tif (\"put\".equals(method)) {\n\t\t\t\tif (isFirstRequest && isStreaming)\n\t\t\t\t\tmakeFirstRequest();\n\n\t\t\t\tif (builder == null) {\n\t\t\t\t\tconnectPath = (key != null) ? type + \"/\" + key : type;\n\t\t\t\t\tWebResource resource = (requestParams == null) ?\n\t\t\t\t\t\tconnection.path(connectPath) :\n\t\t\t\t\t\tconnection.path(connectPath).queryParams(requestParams);\n\t\t\t\t\tbuilder = (mimetype == null) ?\n\t\t\t\t\t\tresource.getRequestBuilder() : resource.type(mimetype);\n\t\t\t\t}\n\n\t\t\t\tresponse = (sentValue == null) ?\n\t\t\t\t\t\tbuilder.put(ClientResponse.class) :\n\t\t\t\t\t\tbuilder.put(ClientResponse.class, sentValue);\n\t\t\t} else if (\"post\".equals(method)) {\n\t\t\t\tif (isFirstRequest && isStreaming)\n\t\t\t\t\tmakeFirstRequest();\n\n\t\t\t\tif (builder == null) {\n\t\t\t\t\tconnectPath = type;\n\t\t\t\t\tWebResource resource = (requestParams == null) ?\n\t\t\t\t\t\tconnection.path(connectPath) :\n\t\t\t\t\t\tconnection.path(connectPath).queryParams(requestParams);\n\t\t\t\t\tbuilder = (mimetype == null) ?\n\t\t\t\t\t\tresource.getRequestBuilder() : resource.type(mimetype);\n\t\t\t\t}\n\n\t\t\t\tresponse = (sentValue == null) ?\n\t\t\t\t\tbuilder.post(ClientResponse.class) :\n\t\t\t\t\tbuilder.post(ClientResponse.class, sentValue);\n\t\t\t} else {\n\t\t\t\tthrow new MarkLogicInternalException(\"unknown method type \"\n\t\t\t\t\t\t+ method);\n\t\t\t}\n\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresponse.close();\n\n\t\t\tif (!isResendable)\n\t\t\t\tthrow new ResourceNotResendableException(\n\t\t\t\t\t\t\"Cannot retry request for \" + connectPath);\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t}\n\t\tif (status == ClientResponse.Status.FORBIDDEN)\n\t\t\tthrow new ForbiddenUserException(\"User is not allowed to write \"\n\t\t\t\t\t+ type, extractErrorFields(response));\n\t\tif (status == ClientResponse.Status.NOT_FOUND)\n\t\t\tthrow new ResourceNotFoundException(type + \" not found for write\",\n\t\t\t\t\textractErrorFields(response));\n\t\tboolean statusOk = false;\n\t\tfor (ClientResponse.Status expectedStatus : expectedStatuses) {\n\t\t\tstatusOk = statusOk || (status == expectedStatus);\n\t\t\tif (statusOk) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (!statusOk) {\n\t\t\tthrow new FailedRequestException(type + \" write failed: \"\n\t\t\t\t\t+ status.getReasonPhrase(), extractErrorFields(response));\n\t\t}\n\t\tresponse.close();\n\n\t}\n\n\t@Override\n\tpublic void deleteValue(RequestLogger reqlog, String type, String key)\n\t\t\tthrows ResourceNotFoundException, ForbiddenUserException,\n\t\t\tFailedRequestException {\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Deleting {}/{}\", type, key);\n\n\t\tWebResource builder = connection.path(type + \"/\" + key);\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\t\tresponse = builder.delete(ClientResponse.class);\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t}\n\t\tif (status == ClientResponse.Status.FORBIDDEN)\n\t\t\tthrow new ForbiddenUserException(\"User is not allowed to delete \"\n\t\t\t\t\t+ type, extractErrorFields(response));\n\t\tif (status == ClientResponse.Status.NOT_FOUND)\n\t\t\tthrow new ResourceNotFoundException(type + \" not found for delete\",\n\t\t\t\t\textractErrorFields(response));\n\t\tif (status != ClientResponse.Status.NO_CONTENT)\n\t\t\tthrow new FailedRequestException(\"delete failed: \"\n\t\t\t\t\t+ status.getReasonPhrase(), extractErrorFields(response));\n\n\t\tresponse.close();\n\n\t\tlogRequest(reqlog, \"deleted %s value with %s key\", type, key);\n\t}\n\n\t@Override\n\tpublic void deleteValues(RequestLogger reqlog, String type)\n\t\t\tthrows ForbiddenUserException, FailedRequestException {\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Deleting {}\", type);\n\n\t\tWebResource builder = connection.path(type);\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\t\tresponse = builder.delete(ClientResponse.class);\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t}\n\t\tif (status == ClientResponse.Status.FORBIDDEN)\n\t\t\tthrow new ForbiddenUserException(\"User is not allowed to delete \"\n\t\t\t\t\t+ type, extractErrorFields(response));\n\t\tif (status != ClientResponse.Status.NO_CONTENT)\n\t\t\tthrow new FailedRequestException(\"delete failed: \"\n\t\t\t\t\t+ status.getReasonPhrase(), extractErrorFields(response));\n\t\tresponse.close();\n\n\t\tlogRequest(reqlog, \"deleted %s values\", type);\n\t}\n\n\t@Override\n\tpublic R getResource(RequestLogger reqlog,\n\t\t\tString path, RequestParameters params, R output)\n\t\t\tthrows ResourceNotFoundException, ForbiddenUserException,\n\t\t\tFailedRequestException {\n\t\tHandleImplementation outputBase = HandleAccessor.checkHandle(output,\n\t\t\t\t\"read\");\n\n\t\tString mimetype = outputBase.getMimetype();\n\t\tClass as = outputBase.receiveAs();\n\n\t\tWebResource.Builder builder = makeGetBuilder(path, params, mimetype);\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\t\tresponse = doGet(builder);\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t}\n\t\tcheckStatus(response, status, \"read\", \"resource\", path,\n\t\t\t\tResponseStatus.OK_OR_NO_CONTENT);\n\n\t\tif (as != null) {\n\t\t\toutputBase.receiveContent(makeResult(reqlog, \"read\", \"resource\",\n\t\t\t\t\tresponse, as));\n\t\t} else {\n\t\t\tresponse.close();\n\t\t}\n\n\t\treturn output;\n\t}\n\n\t@Override\n\tpublic ServiceResultIterator getIteratedResource(RequestLogger reqlog,\n\t\t\tString path, RequestParameters params, String... mimetypes)\n\t\t\tthrows ResourceNotFoundException, ForbiddenUserException,\n\t\t\tFailedRequestException {\n\n\t\tWebResource.Builder builder = makeGetBuilder(path, params, null);\n\n\t\tMediaType multipartType = Boundary.addBoundary(MultiPartMediaTypes.MULTIPART_MIXED_TYPE);\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\t\tresponse = doGet(builder.accept(multipartType));\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t}\n\n\t\tcheckStatus(response, status, \"read\", \"resource\", path,\n\t\t\t\tResponseStatus.OK_OR_NO_CONTENT);\n\n\t\treturn makeResults(reqlog, \"read\", \"resource\", response);\n\t}\n\n\t@Override\n\tpublic R putResource(RequestLogger reqlog,\n\t\t\tString path, RequestParameters params, AbstractWriteHandle input,\n\t\t\tR output) throws ResourceNotFoundException,\n\t\t\tResourceNotResendableException, ForbiddenUserException,\n\t\t\tFailedRequestException {\n\t\tHandleImplementation inputBase = HandleAccessor.checkHandle(input,\n\t\t\t\t\"write\");\n\t\tHandleImplementation outputBase = HandleAccessor.checkHandle(output,\n\t\t\t\t\"read\");\n\n\t\tString inputMimetype = inputBase.getMimetype();\n\t\tboolean isResendable = inputBase.isResendable();\n\t\tString outputMimeType = null;\n\t\tClass as = null;\n\t\tif (outputBase != null) {\n\t\t\toutputMimeType = outputBase.getMimetype();\n\t\t\n\t\t\tas = outputBase.receiveAs();\n\t\t}\n\t\tWebResource.Builder builder = makePutBuilder(path, params,\n\t\t\t\tinputMimetype, outputMimeType);\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\t\tresponse = doPut(reqlog, builder, inputBase.sendContent(),\n\t\t\t\t\t!isResendable);\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresponse.close();\n\n\t\t\tif (!isResendable)\n\t\t\t\tthrow new ResourceNotResendableException(\n\t\t\t\t\t\t\"Cannot retry request for \" + path);\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t}\n\n\t\tcheckStatus(response, status, \"write\", \"resource\", path,\n\t\t\t\tResponseStatus.OK_OR_CREATED_OR_NO_CONTENT);\n\n\t\tif (as != null) {\n\t\t\toutputBase.receiveContent(makeResult(reqlog, \"write\", \"resource\",\n\t\t\t\t\tresponse, as));\n\t\t} else {\n\t\t\tresponse.close();\n\t\t}\n\n\t\treturn output;\n\t}\n\n\t@Override\n\tpublic R putResource(\n\t\t\tRequestLogger reqlog, String path, RequestParameters params,\n\t\t\tW[] input, R output) throws ResourceNotFoundException,\n\t\t\tResourceNotResendableException, ForbiddenUserException,\n\t\t\tFailedRequestException {\n\t\tif (input == null || input.length == 0)\n\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\"input not specified for multipart\");\n\n\t\tHandleImplementation outputBase = HandleAccessor.checkHandle(output,\n\t\t\t\t\"read\");\n\n\t\tString outputMimetype = outputBase.getMimetype();\n\t\tClass as = outputBase.receiveAs();\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\t\tMultiPart multiPart = new MultiPart();\n\t\t\tboolean hasStreamingPart = addParts(multiPart, reqlog, input);\n\n\t\t\tWebResource.Builder builder = makePutBuilder(path, params,\n\t\t\t\t\tmultiPart, outputMimetype);\n\n\t\t\tresponse = doPut(builder, multiPart, hasStreamingPart);\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresponse.close();\n\n\t\t\tif (hasStreamingPart)\n\t\t\t\tthrow new ResourceNotResendableException(\n\t\t\t\t\t\t\"Cannot retry request for \" + path);\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t}\n\n\t\tcheckStatus(response, status, \"write\", \"resource\", path,\n\t\t\t\tResponseStatus.OK_OR_CREATED_OR_NO_CONTENT);\n\n\t\tif (as != null) {\n\t\t\toutputBase.receiveContent(makeResult(reqlog, \"write\", \"resource\",\n\t\t\t\t\tresponse, as));\n\t\t} else {\n\t\t\tresponse.close();\n\t\t}\n\n\t\treturn output;\n\t}\n\n\t@Override\n\tpublic R postResource(RequestLogger reqlog,\n\t\t\tString path, RequestParameters params, AbstractWriteHandle input,\n\t\t\tR output) throws ResourceNotFoundException,\n\t\t\tResourceNotResendableException, ForbiddenUserException,\n\t\t\tFailedRequestException {\n\t\tHandleImplementation inputBase = HandleAccessor.checkHandle(input,\n\t\t\t\t\"write\");\n\t\tHandleImplementation outputBase = HandleAccessor.checkHandle(output,\n\t\t\t\t\"read\");\n\n\t\tString inputMimetype = inputBase.getMimetype();\n\t\tString outputMimetype = outputBase.getMimetype();\n\t\tboolean isResendable = inputBase.isResendable();\n\t\tClass as = outputBase.receiveAs();\n\n\t\tWebResource.Builder builder = makePostBuilder(path, params,\n\t\t\t\tinputMimetype, outputMimetype);\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\t\tresponse = doPost(reqlog, builder, inputBase.sendContent(),\n\t\t\t\t\t!isResendable);\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresponse.close();\n\n\t\t\tif (!isResendable)\n\t\t\t\tthrow new ResourceNotResendableException(\n\t\t\t\t\t\t\"Cannot retry request for \" + path);\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t}\n\n\t\tcheckStatus(response, status, \"apply\", \"resource\", path,\n\t\t\t\tResponseStatus.OK_OR_CREATED_OR_NO_CONTENT);\n\n\t\tif (as != null) {\n\t\t\toutputBase.receiveContent(makeResult(reqlog, \"apply\", \"resource\",\n\t\t\t\t\tresponse, as));\n\t\t} else {\n\t\t\tresponse.close();\n\t\t}\n\n\t\treturn output;\n\t}\n\n\t@Override\n\tpublic R postResource(\n\t\t\tRequestLogger reqlog, String path, RequestParameters params,\n\t\t\tW[] input, R output) throws ResourceNotFoundException,\n\t\t\tResourceNotResendableException, ForbiddenUserException,\n\t\t\tFailedRequestException {\n\t\tHandleImplementation outputBase = HandleAccessor.checkHandle(output,\n\t\t\t\t\"read\");\n\n\t\tString outputMimetype = outputBase.getMimetype();\n\t\tClass as = outputBase.receiveAs();\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\t\tMultiPart multiPart = new MultiPart();\n\t\t\tboolean hasStreamingPart = addParts(multiPart, reqlog, input);\n\n\t\t\tWebResource.Builder builder = makePostBuilder(path, params,\n\t\t\t\t\tmultiPart, outputMimetype);\n\n\t\t\tresponse = doPost(builder, multiPart, hasStreamingPart);\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresponse.close();\n\n\t\t\tif (hasStreamingPart)\n\t\t\t\tthrow new ResourceNotResendableException(\n\t\t\t\t\t\t\"Cannot retry request for \" + path);\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t}\n\n\t\tcheckStatus(response, status, \"apply\", \"resource\", path,\n\t\t\t\tResponseStatus.OK_OR_CREATED_OR_NO_CONTENT);\n\n\t\tif (as != null) {\n\t\t\toutputBase.receiveContent(makeResult(reqlog, \"apply\", \"resource\",\n\t\t\t\t\tresponse, as));\n\t\t} else {\n\t\t\tresponse.close();\n\t\t}\n\n\t\treturn output;\n\t}\n\n\t@Override\n\tpublic ServiceResultIterator postIteratedResource(RequestLogger reqlog,\n\t\t\tString path, RequestParameters params, AbstractWriteHandle input,\n\t\t\tString... outputMimetypes) throws ResourceNotFoundException,\n\t\t\tResourceNotResendableException, ForbiddenUserException,\n\t\t\tFailedRequestException {\n\t\tHandleImplementation inputBase = HandleAccessor.checkHandle(input,\n\t\t\t\t\"write\");\n\n\t\tString inputMimetype = inputBase.getMimetype();\n\t\tboolean isResendable = inputBase.isResendable();\n\n\t\tWebResource.Builder builder = makePostBuilder(path, params, inputMimetype, null);\n\n\t\tMediaType multipartType = Boundary.addBoundary(MultiPartMediaTypes.MULTIPART_MIXED_TYPE);\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\t\tObject value = inputBase.sendContent();\n\n\t\t\tresponse = doPost(reqlog, builder.accept(multipartType), value, !isResendable);\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresponse.close();\n\n\t\t\tif (!isResendable)\n\t\t\t\tthrow new ResourceNotResendableException(\n\t\t\t\t\t\t\"Cannot retry request for \" + path);\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t}\n\n\t\tcheckStatus(response, status, \"apply\", \"resource\", path,\n\t\t\t\tResponseStatus.OK_OR_CREATED_OR_NO_CONTENT);\n\n\t\treturn makeResults(reqlog, \"apply\", \"resource\", response);\n\t}\n\n\t@Override\n\tpublic ServiceResultIterator postIteratedResource(\n\t\t\tRequestLogger reqlog, String path, RequestParameters params,\n\t\t\tW[] input, String... outputMimetypes)\n\t\t\tthrows ResourceNotFoundException, ResourceNotResendableException,\n\t\t\tForbiddenUserException, FailedRequestException {\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\t\tMultiPart multiPart = new MultiPart();\n\t\t\tboolean hasStreamingPart = addParts(multiPart, reqlog, input);\n\n\t\t\tWebResource.Builder builder = makePostBuilder(\n\t\t\t\t\tpath,\n\t\t\t\t\tparams,\n\t\t\t\t\tmultiPart,\n\t\t\t\t\tBoundary.addBoundary(MultiPartMediaTypes.MULTIPART_MIXED_TYPE));\n\n\t\t\tresponse = doPost(builder, multiPart, hasStreamingPart);\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresponse.close();\n\n\t\t\tif (hasStreamingPart)\n\t\t\t\tthrow new ResourceNotResendableException(\n\t\t\t\t\t\t\"Cannot retry request for \" + path);\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t}\n\n\t\tcheckStatus(response, status, \"apply\", \"resource\", path,\n\t\t\t\tResponseStatus.OK_OR_CREATED_OR_NO_CONTENT);\n\n\t\treturn makeResults(reqlog, \"apply\", \"resource\", response);\n\t}\n\n\t@Override\n\tpublic R deleteResource(\n\t\t\tRequestLogger reqlog, String path, RequestParameters params,\n\t\t\tR output) throws ResourceNotFoundException, ForbiddenUserException,\n\t\t\tFailedRequestException {\n\t\tHandleImplementation outputBase = HandleAccessor.checkHandle(output,\n\t\t\t\t\"read\");\n\n\t\tString outputMimeType = null;\n\t\tClass as = null;\n\t\tif (outputBase != null) {\n\t\t\toutputMimeType = outputBase.getMimetype();\n\t\t\tas = outputBase.receiveAs();\n\t\t}\n\t\tWebResource.Builder builder = makeDeleteBuilder(reqlog, path, params,\n\t\t\t\toutputMimeType);\n\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\t\tresponse = doDelete(builder);\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t}\n\n\t\tcheckStatus(response, status, \"delete\", \"resource\", path,\n\t\t\t\tResponseStatus.OK_OR_NO_CONTENT);\n\n\t\tif (as != null) {\n\t\t\toutputBase.receiveContent(makeResult(reqlog, \"delete\", \"resource\",\n\t\t\t\t\tresponse, as));\n\t\t} else {\n\t\t\tresponse.close();\n\t\t}\n\n\t\treturn output;\n\t}\n\n\tprivate WebResource.Builder makeGetBuilder(String path,\n\t\t\tRequestParameters params, Object mimetype) {\n\t\tif (path == null)\n\t\t\tthrow new IllegalArgumentException(\"Read with null path\");\n\n\t\tWebResource.Builder builder = makeBuilder(path, convertParams(params),\n\t\t\t\tnull, mimetype);\n\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(String.format(\"Getting %s as %s\", path, mimetype));\n\n\t\treturn builder;\n\t}\n\n\tprivate ClientResponse doGet(WebResource.Builder builder) {\n\t\tClientResponse response = builder.get(ClientResponse.class);\n\n\t\tif (isFirstRequest)\n\t\t\tisFirstRequest = false;\n\n\t\treturn response;\n\t}\n\n\tprivate WebResource.Builder makePutBuilder(String path,\n\t\t\tRequestParameters params, String inputMimetype,\n\t\t\tString outputMimetype) {\n\t\tif (path == null)\n\t\t\tthrow new IllegalArgumentException(\"Write with null path\");\n\n\t\tWebResource.Builder builder = makeBuilder(path, convertParams(params),\n\t\t\t\tinputMimetype, outputMimetype);\n\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Putting {}\", path);\n\n\t\treturn builder;\n\t}\n\n\tprivate ClientResponse doPut(RequestLogger reqlog,\n\t\t\tWebResource.Builder builder, Object value, boolean isStreaming) {\n\t\tif (value == null)\n\t\t\tthrow new IllegalArgumentException(\"Resource write with null value\");\n\n\t\tif (isFirstRequest && isStreaming(value))\n\t\t\tmakeFirstRequest();\n\n\t\tClientResponse response = null;\n\t\tif (value instanceof OutputStreamSender) {\n\t\t\tresponse = builder\n\t\t\t\t\t.put(ClientResponse.class, new StreamingOutputImpl(\n\t\t\t\t\t\t\t(OutputStreamSender) value, reqlog));\n\t\t} else {\n\t\t\tif (reqlog != null)\n\t\t\t\tresponse = builder.put(ClientResponse.class,\n\t\t\t\t\t\treqlog.copyContent(value));\n\t\t\telse\n\t\t\t\tresponse = builder.put(ClientResponse.class, value);\n\t\t}\n\n\t\tif (isFirstRequest)\n\t\t\tisFirstRequest = false;\n\n\t\treturn response;\n\t}\n\n\tprivate WebResource.Builder makePutBuilder(String path,\n\t\t\tRequestParameters params, MultiPart multiPart, String outputMimetype) {\n\t\tif (path == null)\n\t\t\tthrow new IllegalArgumentException(\"Write with null path\");\n\n\t\tWebResource.Builder builder = makeBuilder(path, convertParams(params),\n\t\t\t\tBoundary.addBoundary(MultiPartMediaTypes.MULTIPART_MIXED_TYPE),\n\t\t\t\toutputMimetype);\n\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Putting multipart for {}\", path);\n\n\t\treturn builder;\n\t}\n\n\tprivate ClientResponse doPut(WebResource.Builder builder,\n\t\t\tMultiPart multiPart, boolean hasStreamingPart) {\n\t\tif (isFirstRequest)\n\t\t\tmakeFirstRequest();\n\n\t\tClientResponse response = builder.put(ClientResponse.class, multiPart);\n\n\t\tif (isFirstRequest)\n\t\t\tisFirstRequest = false;\n\n\t\treturn response;\n\t}\n\n\tprivate WebResource.Builder makePostBuilder(String path,\n\t\t\tRequestParameters params, Object inputMimetype,\n\t\t\tObject outputMimetype) {\n\t\tif (path == null)\n\t\t\tthrow new IllegalArgumentException(\"Apply with null path\");\n\n\t\tWebResource.Builder builder = makeBuilder(path, convertParams(params),\n\t\t\t\tinputMimetype, outputMimetype);\n\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Posting {}\", path);\n\n\t\treturn builder;\n\t}\n\n\tprivate ClientResponse doPost(RequestLogger reqlog,\n\t\t\tWebResource.Builder builder, Object value, boolean isStreaming) {\n\t\tif (isFirstRequest && isStreaming(value))\n\t\t\tmakeFirstRequest();\n\n\t\tClientResponse response = null;\n\t\tif (value instanceof OutputStreamSender) {\n\t\t\tresponse = builder\n\t\t\t\t\t.post(ClientResponse.class, new StreamingOutputImpl(\n\t\t\t\t\t\t\t(OutputStreamSender) value, reqlog));\n\t\t} else {\n\t\t\tif (reqlog != null)\n\t\t\t\tresponse = builder.post(ClientResponse.class,\n\t\t\t\t\t\treqlog.copyContent(value));\n\t\t\telse\n\t\t\t\tresponse = builder.post(ClientResponse.class, value);\n\t\t}\n\n\t\tif (isFirstRequest)\n\t\t\tisFirstRequest = false;\n\n\t\treturn response;\n\t}\n\n\tprivate WebResource.Builder makePostBuilder(String path,\n\t\t\tRequestParameters params, MultiPart multiPart, Object outputMimetype) {\n\t\tif (path == null)\n\t\t\tthrow new IllegalArgumentException(\"Apply with null path\");\n\n\t\tWebResource.Builder builder = makeBuilder(path, convertParams(params),\n\t\t\t\tBoundary.addBoundary(MultiPartMediaTypes.MULTIPART_MIXED_TYPE),\n\t\t\t\toutputMimetype);\n\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Posting multipart for {}\", path);\n\n\t\treturn builder;\n\t}\n\n\tprivate ClientResponse doPost(WebResource.Builder builder,\n\t\t\tMultiPart multiPart, boolean hasStreamingPart) {\n\t\tif (isFirstRequest)\n\t\t\tmakeFirstRequest();\n\n\t\tClientResponse response = builder.post(ClientResponse.class, multiPart);\n\n\t\tif (isFirstRequest)\n\t\t\tisFirstRequest = false;\n\n\t\treturn response;\n\t}\n\n\tprivate WebResource.Builder makeDeleteBuilder(RequestLogger reqlog,\n\t\t\tString path, RequestParameters params, String mimetype) {\n\t\tif (path == null)\n\t\t\tthrow new IllegalArgumentException(\"Delete with null path\");\n\n\t\tWebResource.Builder builder = makeBuilder(path, convertParams(params),\n\t\t\t\tnull, mimetype);\n\n\t\tif (logger.isDebugEnabled())\n\t\t\tlogger.debug(\"Deleting {}\", path);\n\n\t\treturn builder;\n\t}\n\n\tprivate ClientResponse doDelete(WebResource.Builder builder) {\n\t\tClientResponse response = builder.delete(ClientResponse.class);\n\n\t\tif (isFirstRequest)\n\t\t\tisFirstRequest = false;\n\n\t\treturn response;\n\t}\n\n\tprivate MultivaluedMap convertParams(\n\t\t\tRequestParameters params) {\n\t\tif (params == null || params.size() == 0)\n\t\t\treturn null;\n\n\t\tMultivaluedMap requestParams = new MultivaluedMapImpl();\n\t\tfor (Map.Entry> entry : params.entrySet()) {\n\t\t\taddEncodedParam(requestParams, entry.getKey(), entry.getValue());\n\t\t}\n\n\t\treturn requestParams;\n\t}\n\n\tprivate void addEncodedParam(MultivaluedMap params,\n\t\t\tString key, List values) {\n\t\tList encodedParams = encodeParamValues(values);\n\t\tif (encodedParams != null && encodedParams.size() > 0)\n\t\t\tparams.put(key, encodedParams);\n\t}\n\n\tprivate void addEncodedParam(MultivaluedMap params,\n\t\t\tString key, String[] values) {\n\t\tList encodedParams = encodeParamValues(values);\n\t\tif (encodedParams != null && encodedParams.size() > 0)\n\t\t\tparams.put(key, encodedParams);\n\t}\n\n\tprivate void addEncodedParam(MultivaluedMap params,\n\t\t\tString key, String value) {\n\t\tvalue = encodeParamValue(value);\n\t\tif (value == null)\n\t\t\treturn;\n\n\t\tparams.add(key, value);\n\t}\n\n\tprivate List encodeParamValues(List oldValues) {\n\t\tif (oldValues == null)\n\t\t\treturn null;\n\n\t\tint oldSize = oldValues.size();\n\t\tif (oldSize == 0)\n\t\t\treturn null;\n\n\t\tList newValues = new ArrayList(oldSize);\n\t\tfor (String value : oldValues) {\n\t\t\tString newValue = encodeParamValue(value);\n\t\t\tif (newValue == null)\n\t\t\t\tcontinue;\n\t\t\tnewValues.add(newValue);\n\t\t}\n\n\t\treturn newValues;\n\t}\n\n\tprivate List encodeParamValues(String[] oldValues) {\n\t\tif (oldValues == null)\n\t\t\treturn null;\n\n\t\tint oldSize = oldValues.length;\n\t\tif (oldSize == 0)\n\t\t\treturn null;\n\n\t\tList newValues = new ArrayList(oldSize);\n\t\tfor (String value : oldValues) {\n\t\t\tString newValue = encodeParamValue(value);\n\t\t\tif (newValue == null)\n\t\t\t\tcontinue;\n\t\t\tnewValues.add(newValue);\n\t\t}\n\n\t\treturn newValues;\n\t}\n\n\tprivate String encodeParamValue(String value) {\n\t\tif (value == null)\n\t\t\treturn null;\n\n\t\treturn UriComponent.encode(value, UriComponent.Type.QUERY_PARAM)\n\t\t\t\t.replace(\"+\", \"%20\");\n\t}\n\n\tprivate boolean addParts(\n\t\t\tMultiPart multiPart, RequestLogger reqlog, W[] input) {\n\t\treturn addParts(multiPart, reqlog, null, input);\n\t}\n\n\tprivate boolean addParts(\n\t\t\tMultiPart multiPart, RequestLogger reqlog, String[] mimetypes,\n\t\t\tW[] input) {\n\t\tif (mimetypes != null && mimetypes.length != input.length)\n\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\"Mismatch between mimetypes and input\");\n\n\t\tmultiPart.setMediaType(new MediaType(\"multipart\", \"mixed\"));\n\n\t\tboolean hasStreamingPart = false;\n\t\tfor (int i = 0; i < input.length; i++) {\n\t\t\tAbstractWriteHandle handle = input[i];\n\t\t\tHandleImplementation handleBase = HandleAccessor.checkHandle(\n\t\t\t\t\thandle, \"write\");\n\t\t\tObject value = handleBase.sendContent();\n\t\t\tString inputMimetype = (mimetypes != null) ? mimetypes[i]\n\t\t\t\t\t: handleBase.getMimetype();\n\n\t\t\tif (!hasStreamingPart)\n\t\t\t\thasStreamingPart = !handleBase.isResendable();\n\n\t\t\tString[] typeParts = (inputMimetype != null && inputMimetype\n\t\t\t\t\t.contains(\"/\")) ? inputMimetype.split(\"/\", 2) : null;\n\n\t\t\tMediaType typePart = (typeParts != null) ? new MediaType(\n\t\t\t\t\ttypeParts[0], typeParts[1]) : MediaType.WILDCARD_TYPE;\n\n\t\t\tBodyPart bodyPart = null;\n\t\t\tif (value instanceof OutputStreamSender) {\n\t\t\t\tbodyPart = new BodyPart(new StreamingOutputImpl(\n\t\t\t\t\t\t(OutputStreamSender) value, reqlog), typePart);\n\t\t\t} else {\n\t\t\t\tif (reqlog != null)\n\t\t\t\t\tbodyPart = new BodyPart(reqlog.copyContent(value), typePart);\n\t\t\t\telse\n\t\t\t\t\tbodyPart = new BodyPart(value, typePart);\n\t\t\t}\n\n\t\t\tmultiPart = multiPart.bodyPart(bodyPart);\n\t\t}\n\n\t\treturn hasStreamingPart;\n\t}\n\n\tprivate WebResource.Builder makeBuilder(String path,\n\t\t\tMultivaluedMap params, Object inputMimetype,\n\t\t\tObject outputMimetype) {\n\t\tWebResource resource = (params == null) ? connection.path(path)\n\t\t\t\t: connection.path(path).queryParams(params);\n\n\t\tWebResource.Builder builder = resource.getRequestBuilder();\n\n\t\tif (inputMimetype == null) {\n\t\t} else if (inputMimetype instanceof String) {\n\t\t\tbuilder = builder.type((String) inputMimetype);\n\t\t} else if (inputMimetype instanceof MediaType) {\n\t\t\tbuilder = builder.type((MediaType) inputMimetype);\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\"Unknown input mimetype specifier \"\n\t\t\t\t\t\t\t+ inputMimetype.getClass().getName());\n\t\t}\n\n\t\tif (outputMimetype == null) {\n\t\t} else if (outputMimetype instanceof String) {\n\t\t\tbuilder = builder.accept((String) outputMimetype);\n\t\t} else if (outputMimetype instanceof MediaType) {\n\t\t\tbuilder = builder.accept((MediaType) outputMimetype);\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\"Unknown output mimetype specifier \"\n\t\t\t\t\t\t\t+ outputMimetype.getClass().getName());\n\t\t}\n\n\t\treturn builder;\n\t}\n\n\tprivate void checkStatus(ClientResponse response,\n\t\t\tClientResponse.Status status, String operation, String entityType,\n\t\t\tString path, ResponseStatus expected) {\n\t\tif (!expected.isExpected(status)) {\n\t\t\tif (status == ClientResponse.Status.NOT_FOUND) {\n\t\t\t\tthrow new ResourceNotFoundException(\"Could not \" + operation\n\t\t\t\t\t\t+ \" \" + entityType + \" at \" + path,\n\t\t\t\t\t\textractErrorFields(response));\n\t\t\t}\n\t\t\tif (status == ClientResponse.Status.FORBIDDEN) {\n\t\t\t\tthrow new ForbiddenUserException(\"User is not allowed to \"\n\t\t\t\t\t\t+ operation + \" \" + entityType + \" at \" + path,\n\t\t\t\t\t\textractErrorFields(response));\n\t\t\t}\n\t\t\tthrow new FailedRequestException(\"failed to \" + operation + \" \"\n\t\t\t\t\t+ entityType + \" at \" + path + \": \"\n\t\t\t\t\t+ status.getReasonPhrase(), extractErrorFields(response));\n\t\t}\n\t}\n\n\tprivate T makeResult(RequestLogger reqlog, String operation,\n\t\t\tString entityType, ClientResponse response, Class as) {\n\t\tif (as == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\tlogRequest(reqlog, \"%s for %s\", operation, entityType);\n\n\t\tT entity = response.hasEntity() ? response.getEntity(as) : null;\n\t\tif (entity == null || (as != InputStream.class && as != Reader.class))\n\t\t\tresponse.close();\n\n\t\treturn (reqlog != null) ? reqlog.copyContent(entity) : entity;\n\t}\n\n\tprivate ServiceResultIterator makeResults(RequestLogger reqlog,\n\t\t\tString operation, String entityType, ClientResponse response) {\n\t\tlogRequest(reqlog, \"%s for %s\", operation, entityType);\n\n\t\tMultiPart entity = response.hasEntity() ?\n\t\t\t\tresponse.getEntity(MultiPart.class) : null;\n\t\tif (entity == null)\n\t\t\treturn null;\n\n\t\tList partList = entity.getBodyParts();\n\t\tif (partList == null || partList.size() == 0) {\n\t\t\tresponse.close();\n\t\t\treturn null;\n\t\t}\n\n\t\treturn new JerseyResultIterator(reqlog, response, partList);\n\t}\n\n\tprivate boolean isStreaming(Object value) {\n\t\treturn !(value instanceof String || value instanceof byte[] || value instanceof File);\n\t}\n\n\tprivate void logRequest(RequestLogger reqlog, String message,\n\t\t\tObject... params) {\n\t\tif (reqlog == null)\n\t\t\treturn;\n\n\t\tPrintStream out = reqlog.getPrintStream();\n\t\tif (out == null)\n\t\t\treturn;\n\n\t\tif (params == null || params.length == 0) {\n\t\t\tout.println(message);\n\t\t} else {\n\t\t\tout.format(message, params);\n\t\t\tout.println();\n\t\t}\n\t}\n\n\tprivate String stringJoin(Collection collection, String separator,\n\t\t\tString defaultValue) {\n\t\tif (collection == null || collection.size() == 0)\n\t\t\treturn defaultValue;\n\n\t\tStringBuilder builder = null;\n\t\tfor (Object value : collection) {\n\t\t\tif (builder == null)\n\t\t\t\tbuilder = new StringBuilder();\n\t\t\telse\n\t\t\t\tbuilder.append(separator);\n\n\t\t\tbuilder.append(value);\n\t\t}\n\n\t\treturn (builder != null) ? builder.toString() : null;\n\t}\n\n\tprivate int calculateDelay(Random rand, int iteration) {\n\t\tint base = (1 << iteration) * delayMultiplier;\n\t\treturn delayFloor + base + randRetry.nextInt((iteration + 1 < maxRetries) ? base : 100);\n\t}\n\n\tpublic class JerseyResult implements ServiceResult {\n\t\tprivate RequestLogger reqlog;\n\t\tprivate BodyPart part;\n\t\tprivate boolean extractedHeaders = false;\n\t\tprivate Format format;\n\t\tprivate String mimetype;\n\t\tprivate long length;\n\n\t\tpublic JerseyResult(RequestLogger reqlog, BodyPart part) {\n\t\t\tsuper();\n\t\t\tthis.reqlog = reqlog;\n\t\t\tthis.part = part;\n\t\t}\n\n\t\t@Override\n\t\tpublic R getContent(R handle) {\n\t\t\tif (part == null)\n\t\t\t\tthrow new IllegalStateException(\"Content already retrieved\");\n\n\t\t\tHandleImplementation handleBase = HandleAccessor.as(handle);\n\n\t\t\textractHeaders();\n\t\t\tupdateFormat(handleBase, format);\n\t\t\tupdateMimetype(handleBase, mimetype);\n\t\t\tupdateLength(handleBase, length);\n\n\t\t\tObject contentEntity = part.getEntityAs(handleBase.receiveAs());\n\t\t\thandleBase.receiveContent((reqlog != null) ? reqlog\n\t\t\t\t\t.copyContent(contentEntity) : contentEntity);\n\n\t\t\tpart = null;\n\t\t\treqlog = null;\n\n\t\t\treturn handle;\n\t\t}\n\n\t\t@Override\n\t\tpublic Format getFormat() {\n\t\t\textractHeaders();\n\t\t\treturn format;\n\t\t}\n\n\t\t@Override\n\t\tpublic String getMimetype() {\n\t\t\textractHeaders();\n\t\t\treturn mimetype;\n\t\t}\n\n\t\t@Override\n\t\tpublic long getLength() {\n\t\t\textractHeaders();\n\t\t\treturn length;\n\t\t}\n\n\t\tprivate void extractHeaders() {\n\t\t\tif (part == null || extractedHeaders)\n\t\t\t\treturn;\n\t\t\tMultivaluedMap headers = part.getHeaders();\n\t\t\tformat = getHeaderFormat(headers);\n\t\t\tmimetype = getHeaderMimetype(headers);\n\t\t\tlength = getHeaderLength(headers);\n\t\t\textractedHeaders = true;\n\t\t}\n\t}\n\n\tpublic class JerseyResultIterator implements ServiceResultIterator {\n\t\tprivate RequestLogger reqlog;\n\t\tprivate ClientResponse response;\n\t\tprivate Iterator partQueue;\n\n\t\tpublic JerseyResultIterator(RequestLogger reqlog,\n\t\t\t\tClientResponse response, List partList) {\n\t\t\tsuper();\n\t\t\tif (response != null) {\n\t\t\t\tif (partList != null && partList.size() > 0) {\n\t\t\t\t\tthis.reqlog = reqlog;\n\t\t\t\t\tthis.response = response;\n\t\t\t\t\tthis.partQueue = new ConcurrentLinkedQueue(\n\t\t\t\t\t\t\tpartList).iterator();\n\t\t\t\t} else {\n\t\t\t\t\tresponse.close();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean hasNext() {\n\t\t\tif (partQueue == null)\n\t\t\t\treturn false;\n\t\t\tboolean hasNext = partQueue.hasNext();\n\t\t\tif (!partQueue.hasNext())\n\t\t\t\tclose();\n\t\t\treturn hasNext;\n\t\t}\n\n\t\t@Override\n\t\tpublic ServiceResult next() {\n\t\t\tif (partQueue == null)\n\t\t\t\treturn null;\n\n\t\t\tServiceResult result = new JerseyResult(reqlog, partQueue.next());\n\t\t\tif (!partQueue.hasNext())\n\t\t\t\tclose();\n\n\t\t\treturn result;\n\t\t}\n\n\t\t@Override\n\t\tpublic void remove() {\n\t\t\tif (partQueue == null)\n\t\t\t\treturn;\n\t\t\tpartQueue.remove();\n\t\t\tif (!partQueue.hasNext())\n\t\t\t\tclose();\n\t\t}\n\n\t\t@Override\n\t\tpublic void close() {\n\t\t\tif (response != null) {\n\t\t\t\tresponse.close();\n\t\t\t\tresponse = null;\n\t\t\t}\n\t\t\tpartQueue = null;\n\t\t\treqlog = null;\n\t\t}\n\n\t\t@Override\n\t\tprotected void finalize() throws Throwable {\n\t\t\tclose();\n\t\t\tsuper.finalize();\n\t\t}\n\t}\n\n\t@Override\n\tpublic HttpClient getClientImplementation() {\n\t\tif (client == null)\n\t\t\treturn null;\n\t\treturn client.getClientHandler().getHttpClient();\n\t}\n\n\t@Override\n\tpublic T suggest(Class as, SuggestDefinition suggestionDef) {\n\t\tMultivaluedMap params = new MultivaluedMapImpl();\n\n\t\tString suggestCriteria = suggestionDef.getStringCriteria();\n\t\tString[] queries = suggestionDef.getQueryStrings();\n\t\tString optionsName = suggestionDef.getOptionsName();\n\t\tInteger limit = suggestionDef.getLimit();\n\t\tInteger cursorPosition = suggestionDef.getCursorPosition();\n\n\t\tif (suggestCriteria != null) {\n\t\t\tparams.add(\"partial-q\", suggestCriteria);\n\t\t}\n\t\tif (optionsName != null) {\n\t\t\tparams.add(\"options\", optionsName);\n\t\t}\n\t\tif (limit != null) {\n\t\t\tparams.add(\"limit\", Long.toString(limit));\n\t\t}\n\t\tif (cursorPosition != null) {\n\t\t\tparams.add(\"cursor-position\", Long.toString(cursorPosition));\n\t\t}\n\t\tif (queries != null) {\n\t\t\tfor (String stringQuery : queries) {\n\t\t\t\tparams.add(\"q\", stringQuery);\n\t\t\t}\n\t\t}\n\t\tWebResource.Builder builder = null;\n\t\tbuilder = connection.path(\"suggest\").queryParams(params)\n\t\t\t\t.accept(\"application/xml\");\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\t\tresponse = builder.get(ClientResponse.class);\n\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t}\n\t\tif (status == ClientResponse.Status.FORBIDDEN) {\n\t\t\tthrow new ForbiddenUserException(\n\t\t\t\t\t\"User is not allowed to get suggestions\",\n\t\t\t\t\textractErrorFields(response));\n\t\t}\n\t\tif (status != ClientResponse.Status.OK) {\n\t\t\tthrow new FailedRequestException(\"Suggest call failed: \"\n\t\t\t\t\t+ status.getReasonPhrase(), extractErrorFields(response));\n\t\t}\n\n\t\tT entity = response.hasEntity() ? response.getEntity(as) : null;\n\t\tif (entity == null || (as != InputStream.class && as != Reader.class))\n\t\t\tresponse.close();\n\n\t\treturn entity;\n\t}\n\n\t@Override\n\tpublic InputStream match(StructureWriteHandle document,\n\t\t\tString[] candidateRules, String mimeType, ServerTransform transform) {\n\t\tMultivaluedMap params = new MultivaluedMapImpl();\n\n\t\tHandleImplementation baseHandle = HandleAccessor.checkHandle(document, \"match\");\n\t\tif (candidateRules.length > 0) {\n\t\t\tfor (String candidateRule : candidateRules) {\n\t\t\t\tparams.add(\"rule\", candidateRule);\n\t\t\t}\n\t\t}\n\t\tif (transform != null) {\n\t\t\ttransform.merge(params);\n\t\t}\n\t\tWebResource.Builder builder = null;\n\t\tbuilder = connection.path(\"alert/match\").queryParams(params)\n\t\t\t\t.accept(\"application/xml\").type(mimeType);\n\t\t\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\t\tresponse = doPost(null, builder, baseHandle.sendContent(), false);\n\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t}\n\t\tif (status == ClientResponse.Status.FORBIDDEN) {\n\t\t\tthrow new ForbiddenUserException(\"User is not allowed to match\",\n\t\t\t\t\textractErrorFields(response));\n\t\t}\n\t\tif (status != ClientResponse.Status.OK) {\n\t\t\tthrow new FailedRequestException(\"match failed: \"\n\t\t\t\t\t+ status.getReasonPhrase(), extractErrorFields(response));\n\t\t}\n\n\t\tInputStream entity = response.hasEntity() ?\n\t\t\t\tresponse.getEntity(InputStream.class) : null;\n\t\tif (entity == null)\n\t\t\tresponse.close();\n\t\t\n\t\treturn entity;\n\t}\n\n\t@Override\n\tpublic InputStream match(QueryDefinition queryDef,\n\t\t\tlong start, long pageLength, String[] candidateRules, ServerTransform transform) {\n\t\tif (queryDef == null) {\n\t\t\tthrow new IllegalArgumentException(\"Cannot match null query\");\n\t\t}\n\n\t\tMultivaluedMap params = new MultivaluedMapImpl();\n\n\t\tif (start > 1) {\n\t\t\tparams.add(\"start\", Long.toString(start));\n\t\t}\n\t\tif (pageLength >= 0) {\n\t\t\tparams.add(\"pageLength\", Long.toString(pageLength));\n\t\t}\n\t\tif (transform != null) {\n\t\t\ttransform.merge(params);\n\t\t}\n\t\tif (candidateRules.length > 0) {\n\t\t\tfor (String candidateRule : candidateRules) {\n\t\t\t\tparams.add(\"rule\", candidateRule);\n\t\t\t}\n\t\t}\n\n\t\tif (queryDef.getOptionsName() != null) {\n\t\t\tparams.add(\"options\", queryDef.getOptionsName());\n\t\t}\n\n\t\tWebResource.Builder builder = null;\n\t\tString structure = null;\n\t\tHandleImplementation baseHandle = null;\n\n\t\tif (queryDef instanceof RawQueryDefinition) {\n\t\t\tStructureWriteHandle handle = ((RawQueryDefinition) queryDef).getHandle();\n\t\t\tbaseHandle = HandleAccessor.checkHandle(handle, \"match\");\n\n\t\t\tif (logger.isDebugEnabled())\n\t\t\t\tlogger.debug(\"Searching for structure {}\", structure);\n\n\t\t\tbuilder = connection.path(\"alert/match\").queryParams(params)\n\t\t\t\t\t.type(\"application/xml\").accept(\"application/xml\");\n\t\t} else if (queryDef instanceof StringQueryDefinition) {\n\t\t\tString text = ((StringQueryDefinition) queryDef).getCriteria();\n\t\t\tif (logger.isDebugEnabled())\n\t\t\t\tlogger.debug(\"Searching for {} in transaction {}\", text);\n\n\t\t\tif (text != null) {\n\t\t\t\taddEncodedParam(params, \"q\", text);\n\t\t\t}\n\n\t\t\tbuilder = connection.path(\"alert/match\").queryParams(params)\n\t\t\t\t\t.accept(\"application/xml\");\n\t\t} else if (queryDef instanceof StructuredQueryDefinition) {\n\t\t\tstructure = ((StructuredQueryDefinition) queryDef).serialize();\n\n\t\t\tif (logger.isDebugEnabled())\n\t\t\t\tlogger.debug(\"Searching for structure {} in transaction {}\",\n\t\t\t\t\t\tstructure);\n\n\t\t\tbuilder = connection.path(\"alert/match\").queryParams(params)\n\t\t\t\t\t.type(\"application/xml\").accept(\"application/xml\");\n\t\t} else {\n\t\t\tthrow new UnsupportedOperationException(\"Cannot match with \"\n\t\t\t\t\t+ queryDef.getClass().getName());\n\t\t}\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\t\tif (queryDef instanceof StringQueryDefinition) {\n\t\t\t\tresponse = builder.get(ClientResponse.class);\n\t\t\t} else if (queryDef instanceof StructuredQueryDefinition) {\n\t\t\t\tresponse = builder.post(ClientResponse.class, structure);\n\t\t\t} else if (queryDef instanceof RawQueryDefinition) {\n\t\t\t\tresponse = doPost(null, builder, baseHandle.sendContent(), false);\n\t\t\t} else {\n\t\t\t\tthrow new UnsupportedOperationException(\"Cannot match with \"\n\t\t\t\t\t\t+ queryDef.getClass().getName());\n\t\t\t}\n\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t}\n\t\tif (status == ClientResponse.Status.FORBIDDEN) {\n\t\t\tthrow new ForbiddenUserException(\"User is not allowed to match\",\n\t\t\t\t\textractErrorFields(response));\n\t\t}\n\t\tif (status != ClientResponse.Status.OK) {\n\t\t\tthrow new FailedRequestException(\"match failed: \"\n\t\t\t\t\t+ status.getReasonPhrase(), extractErrorFields(response));\n\t\t}\n\n\t\tInputStream entity = response.hasEntity() ?\n\t\t\t\tresponse.getEntity(InputStream.class) : null;\n\t\tif (entity == null)\n\t\t\tresponse.close();\n\t\t\n\t\treturn entity;\n\t}\n\n\t@Override\n\tpublic InputStream match(String[] docIds, String[] candidateRules, ServerTransform transform) {\n\t\tMultivaluedMap params = new MultivaluedMapImpl();\n\n\t\tif (docIds.length > 0) {\n\t\t\tfor (String docId : docIds) {\n\t\t\t\tparams.add(\"uri\", docId);\n\t\t\t}\n\t\t}\n\t\tif (candidateRules.length > 0) {\n\t\t\tfor (String candidateRule : candidateRules) {\n\t\t\t\tparams.add(\"rule\", candidateRule);\n\t\t\t}\n\t\t}\n\t\tif (transform != null) {\n\t\t\ttransform.merge(params);\n\t\t}\n\t\tWebResource.Builder builder = connection.path(\"alert/match\").queryParams(params)\n\t\t\t\t.accept(\"application/xml\");\n\t\t\n\t\tClientResponse response = null;\n\t\tClientResponse.Status status = null;\n\t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\t\tresponse = doGet(builder);\n\n\t\t\tstatus = response.getClientResponseStatus();\n\n\t\t\tif (isFirstRequest)\n\t\t\t\tisFirstRequest = false;\n\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t}\n\t\tif (status == ClientResponse.Status.FORBIDDEN) {\n\t\t\tthrow new ForbiddenUserException(\"User is not allowed to match\",\n\t\t\t\t\textractErrorFields(response));\n\t\t}\n\t\tif (status != ClientResponse.Status.OK) {\n\t\t\tthrow new FailedRequestException(\"match failed: \"\n\t\t\t\t\t+ status.getReasonPhrase(), extractErrorFields(response));\n\t\t}\n\n\t\tInputStream entity = response.hasEntity() ?\n\t\t\t\tresponse.getEntity(InputStream.class) : null;\n\t\tif (entity == null)\n\t\t\tresponse.close();\n\t\t\n\t\treturn entity;\n\t}\n}\n"},"message":{"kind":"string","value":"Bug:24201 improved retry loop under failover for REST requests\n\ngit-svn-id: 2087087167f935058d19856144d26af79f295c86@152832 62cac252-8da6-4816-9e9d-6dc37b19578c\n"},"old_file":{"kind":"string","value":"src/main/java/com/marklogic/client/impl/JerseyServices.java"},"subject":{"kind":"string","value":"Bug:24201 improved retry loop under failover for REST requests"},"git_diff":{"kind":"string","value":"rc/main/java/com/marklogic/client/impl/JerseyServices.java\n import java.util.Iterator;\n import java.util.List;\n import java.util.Map;\nimport java.util.Properties;\n import java.util.Random;\n import java.util.Set;\n import java.util.concurrent.ConcurrentLinkedQueue;\n \n \tstatic final private String DOCUMENT_URI_PREFIX = \"/documents?uri=\";\n \n\tstatic final private int DELAY_FLOOR = 125;\n\tstatic final private int DELAY_CEILING = 2000;\n\tstatic final private int DELAY_MULTIPLIER = 20;\n\tstatic final private int DEFAULT_MAX_DELAY = 120000;\n\tstatic final private int DEFAULT_MIN_RETRY = 8;\n\n\tstatic final private String MAX_DELAY_PROP = \"com.marklogic.client.maximumRetrySeconds\";\n\tstatic final private String MIN_RETRY_PROP = \"com.marklogic.client.minimumRetries\";\n\n \tstatic protected class HostnameVerifierAdapter extends AbstractVerifier {\n \t\tprivate SSLHostnameVerifier verifier;\n \n \tprivate WebResource connection;\n \n \tprivate Random randRetry = new Random();\n\tprivate int maxRetries = 8;\n\tprivate int delayFloor = 60;\n\tprivate int delayMultiplier = 40;\n\n\tprivate int maxDelay = DEFAULT_MAX_DELAY;\n\tprivate int minRetry = DEFAULT_MIN_RETRY;\n \n \tprivate boolean isFirstRequest = false;\n \n \t\tString baseUri = ((context == null) ? \"http\" : \"https\") + \"://\" + host\n \t\t\t\t+ \":\" + port + \"/v1/\";\n \n\t\tProperties props = System.getProperties();\n\n\t\tif (props.containsKey(MAX_DELAY_PROP)) {\n\t\t\tString maxDelayStr = props.getProperty(MAX_DELAY_PROP);\n\t\t\tif (maxDelayStr != null && maxDelayStr.length() > 0) {\n\t\t\t\tint max = Integer.parseInt(maxDelayStr);\n\t\t\t\tif (max > 0) {\n\t\t\t\t\tmaxDelay = max * 1000;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (props.containsKey(MIN_RETRY_PROP)) {\n\t\t\tString minRetryStr = props.getProperty(MIN_RETRY_PROP);\n\t\t\tif (minRetryStr != null && minRetryStr.length() > 0) {\n\t\t\t\tint min = Integer.parseInt(minRetryStr);\n\t\t\t\tif (min > 0) {\n\t\t\t\t\tminRetry = min;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n \t\t// TODO: integrated control of HTTP Client and Jersey Client logging\n\t\tif (System.getProperty(\"org.apache.commons.logging.Log\") == null) {\n\t\tif (!props.containsKey(\"org.apache.commons.logging.Log\")) {\n \t\t\tSystem.setProperty(\"org.apache.commons.logging.Log\",\n \t\t\t\t\"org.apache.commons.logging.impl.SimpleLog\");\n \t\t}\n\t\tif (System.getProperty(\"org.apache.commons.logging.simplelog.log.org.apache.http\") == null) {\n\t\tif (!props.containsKey(\"org.apache.commons.logging.simplelog.log.org.apache.http\")) {\n \t\t\tSystem.setProperty(\n \t\t\t\t\"org.apache.commons.logging.simplelog.log.org.apache.http\",\n \t\t\t\t\"warn\");\n \t\t}\n\t\tif (System.getProperty(\"org.apache.commons.logging.simplelog.log.org.apache.http.wire\") == null) {\n\t\tif (!props.containsKey(\"org.apache.commons.logging.simplelog.log.org.apache.http.wire\")) {\n \t\t\tSystem.setProperty(\n \t\t\t\t\"org.apache.commons.logging.simplelog.log.org.apache.http.wire\",\n \t\t\t\t\"warn\");\n \n \t\tClientResponse response = null;\n \t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n \t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n \t\t\tresponse = builder.delete(ClientResponse.class);\n \t\t\tstatus = response.getClientResponseStatus();\n \n \t\t\tif (isFirstRequest)\n \t\t\t\tisFirstRequest = false;\n \n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\t\tbreak;\n \t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n \t\t}\n \t\tif (status == ClientResponse.Status.NOT_FOUND) {\n \t\t\tresponse.close();\n \n \t\tClientResponse response = null;\n \t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n \t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n \t\t\tresponse = builder.get(ClientResponse.class);\n \t\t\tstatus = response.getClientResponseStatus();\n \n \t\t\tif (isFirstRequest)\n \t\t\t\tisFirstRequest = false;\n \n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\t\tbreak;\n \t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n \t\t}\n \t\tif (status == ClientResponse.Status.NOT_FOUND)\n \t\t\tthrow new ResourceNotFoundException(\n \t\tClass as = handleBase.receiveAs();\n \t\tObject entity = response.hasEntity() ? response.getEntity(as) : null;\n \n// TODO: test assignable from, not identical to\n\t\tif (entity == null || (as != InputStream.class && as != Reader.class))\n\t\tif (entity == null ||\n\t\t\t\t(!InputStream.class.isAssignableFrom(as) && !Reader.class.isAssignableFrom(as)))\n \t\t\tresponse.close();\n \n \t\thandleBase.receiveContent((reqlog != null) ? reqlog.copyContent(entity)\n \n \t\tClientResponse response = null;\n \t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n \t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n \t\t\tresponse = builder.accept(multipartType).get(ClientResponse.class);\n \t\t\tstatus = response.getClientResponseStatus();\n \n \t\t\tif (isFirstRequest)\n \t\t\t\tisFirstRequest = false;\n \n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\t\tbreak;\n \t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n \t\t}\n \t\tif (status == ClientResponse.Status.NOT_FOUND)\n \t\t\tthrow new ResourceNotFoundException(\n \n \t\tClientResponse response = null;\n \t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n \t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n \t\t\tresponse = builder.head();\n \t\t\tstatus = response.getClientResponseStatus();\n \n \t\t\tif (isFirstRequest)\n \t\t\t\tisFirstRequest = false;\n \n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\t\tbreak;\n \t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t}\t\t\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n\t\t}\n \t\tif (status != ClientResponse.Status.OK) {\n \t\t\tif (status == ClientResponse.Status.NOT_FOUND) {\n \t\t\t\tresponse.close();\n \t\tClientResponse response = null;\n \t\tClientResponse.Status status = null;\n \t\tMultivaluedMap responseHeaders = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n \t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n \t\t\tObject value = handleBase.sendContent();\n \t\t\tif (value == null)\n \t\t\t\tthrow new IllegalArgumentException(\n \t\t\t\tisFirstRequest = false;\n \n \t\t\tresponseHeaders = response.getHeaders();\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(responseHeaders.getFirst(\"Retry-After\"))) {\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\t\tbreak;\n \t\t\t}\n\t\t\tresponse.close();\n\n\t\t\tif (!isResendable)\n\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tresponse.close();\n\n\t\t\tif (!isResendable) {\n \t\t\t\tthrow new ResourceNotResendableException(\n \t\t\t\t\t\t\"Cannot retry request for \" +\n \t\t\t\t\t\t ((uri != null) ? uri : \"new document\"));\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\t\t\t}\n\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n \t\t}\n \t\tif (status == ClientResponse.Status.NOT_FOUND)\n \t\t\tthrow new ResourceNotFoundException(\n \t\t\tthrow new FailedRequestException(\"Precondition Failed\", failure);\n \t\t}\n \t\tif (status != ClientResponse.Status.CREATED\n\t\t\t\t&& status != ClientResponse.Status.NO_CONTENT)\n\t\t\t\t&& status != ClientResponse.Status.NO_CONTENT) {\n \t\t\tthrow new FailedRequestException(\"write failed: \"\n \t\t\t\t\t+ status.getReasonPhrase(), extractErrorFields(response));\n\t\t}\n \n \t\tif (uri == null) {\n \t\t\tString location = responseHeaders.getFirst(\"Location\");\n \t\tClientResponse response = null;\n \t\tClientResponse.Status status = null;\n \t\tMultivaluedMap responseHeaders = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n \t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n \t\t\tMultiPart multiPart = new MultiPart();\n \t\t\tboolean hasStreamingPart = addParts(multiPart, reqlog,\n \t\t\t\t\tnew String[] { metadataMimetype, contentMimetype },\n \t\t\t\tisFirstRequest = false;\n \n \t\t\tresponseHeaders = response.getHeaders();\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(responseHeaders.getFirst(\"Retry-After\"))) {\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\t\tbreak;\n \t\t\t}\n\t\t\tresponse.close();\n\n\t\t\tif (hasStreamingPart)\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tresponse.close();\n\n\t\t\tif (hasStreamingPart) {\n \t\t\t\tthrow new ResourceNotResendableException(\n \t\t\t\t\t\t\"Cannot retry request for \" +\n \t\t\t\t\t\t((uri != null) ? uri : \"new document\"));\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\t\t\t}\n\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n \t\t}\n \t\tif (status == ClientResponse.Status.NOT_FOUND) {\n \t\t\tresponse.close();\n \t\t\tthrow new FailedRequestException(\"Precondition Failed\", failure);\n \t\t}\n \t\tif (status != ClientResponse.Status.CREATED\n\t\t\t\t&& status != ClientResponse.Status.NO_CONTENT)\n\t\t\t\t&& status != ClientResponse.Status.NO_CONTENT) {\n \t\t\tthrow new FailedRequestException(\"write failed: \"\n \t\t\t\t\t+ status.getReasonPhrase(), extractErrorFields(response));\n\t\t}\n \n \t\tif (uri == null) {\n \t\t\tString location = responseHeaders.getFirst(\"Location\");\n \n \t\tClientResponse response = null;\n \t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n \t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n \t\t\tresponse = resource.post(ClientResponse.class);\n \t\t\tstatus = response.getClientResponseStatus();\n \n \t\t\tif (isFirstRequest)\n \t\t\t\tisFirstRequest = false;\n \n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\t\tbreak;\n \t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n \t\t}\n \t\tif (status == ClientResponse.Status.FORBIDDEN)\n \t\t\tthrow new ForbiddenUserException(\n \t\t\t\t\t\"transaction open failed to provide location\");\n \t\tif (!location.contains(\"/\"))\n \t\t\tthrow new MarkLogicInternalException(\n\t\t\t\t\t\"transaction open produced invalid location \" + location);\n\t\t\t\t\t\"transaction open produced invalid location: \" + location);\n \n \t\treturn location.substring(location.lastIndexOf(\"/\") + 1);\n \t}\n \n \t\tClientResponse response = null;\n \t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n \t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n \t\t\tresponse = builder.post(ClientResponse.class);\n \t\t\tstatus = response.getClientResponseStatus();\n \n \t\t\tif (isFirstRequest)\n \t\t\t\tisFirstRequest = false;\n \n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\t\tbreak;\n \t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n \t\t}\n \t\tif (status == ClientResponse.Status.FORBIDDEN)\n \t\t\tthrow new ForbiddenUserException(\n \n \t\tClientResponse response = null;\n \t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n \t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n \t\t\tif (queryDef instanceof StringQueryDefinition) {\n \t\t\t\tresponse = doGet(builder);\n \t\t\t} else if (queryDef instanceof KeyValueQueryDefinition) {\n \t\t\tif (isFirstRequest)\n \t\t\t\tisFirstRequest = false;\n \n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\t\tbreak;\n \t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n \t\t}\n \t\tif (status == ClientResponse.Status.FORBIDDEN) {\n \t\t\tthrow new ForbiddenUserException(\"User is not allowed to search\",\n \n \t\tClientResponse response = null;\n \t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n \t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n \t\t\tresponse = builder.delete(ClientResponse.class);\n \t\t\tstatus = response.getClientResponseStatus();\n \n \t\t\tif (isFirstRequest)\n \t\t\t\tisFirstRequest = false;\n \n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\t\tbreak;\n \t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n \t\t}\n \t\tif (status == ClientResponse.Status.FORBIDDEN) {\n \t\t\tthrow new ForbiddenUserException(\"User is not allowed to delete\",\n \n \t\tClientResponse response = null;\n \t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n \t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n \n response = baseHandle == null ?\n doGet(builder) :\n \t\t\tif (isFirstRequest)\n \t\t\t\tisFirstRequest = false;\n \n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\t\tbreak;\n \t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n \t\t}\n \t\tif (status == ClientResponse.Status.FORBIDDEN) {\n \t\t\tthrow new ForbiddenUserException(\"User is not allowed to search\",\n \n \t\tClientResponse response = null;\n \t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n \t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n \t\t\tresponse = builder.get(ClientResponse.class);\n \t\t\tstatus = response.getClientResponseStatus();\n \n \t\t\tif (isFirstRequest)\n \t\t\t\tisFirstRequest = false;\n \n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\t\tbreak;\n \t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n \t\t}\n \t\tif (status == ClientResponse.Status.FORBIDDEN) {\n \t\t\tthrow new ForbiddenUserException(\"User is not allowed to search\",\n \n \t\tClientResponse response = null;\n \t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n \t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n \t\t\tresponse = builder.get(ClientResponse.class);\n \t\t\tstatus = response.getClientResponseStatus();\n \n \t\t\tif (isFirstRequest)\n \t\t\t\tisFirstRequest = false;\n \n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\t\tbreak;\n \t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n \t\t}\n \t\tif (status == ClientResponse.Status.FORBIDDEN) {\n \t\t\tthrow new ForbiddenUserException(\"User is not allowed to search\",\n \n \t\tClientResponse response = null;\n \t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n \t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n \t\t\tresponse = builder.get(ClientResponse.class);\n \t\t\tstatus = response.getClientResponseStatus();\n \n \t\t\tif (isFirstRequest)\n \t\t\t\tisFirstRequest = false;\n \n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\t\tbreak;\n \t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n \t\t}\n \t\tif (status != ClientResponse.Status.OK) {\n \t\t\tif (status == ClientResponse.Status.NOT_FOUND) {\n \n \t\tClientResponse response = null;\n \t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n \t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n \t\t\tresponse = builder.get(ClientResponse.class);\n \t\t\tstatus = response.getClientResponseStatus();\n \n \t\t\tif (isFirstRequest)\n \t\t\t\tisFirstRequest = false;\n \n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\t\tbreak;\n \t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n \t\t}\n \t\tif (status == ClientResponse.Status.FORBIDDEN) {\n \t\t\tthrow new ForbiddenUserException(\"User is not allowed to read \"\n \n \t\tClientResponse response = null;\n \t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n \t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n \t\t\tObject nextValue = (handle != null) ? handle.sendContent() : value;\n \n \t\t\tObject sentValue = null;\n \t\t\tif (isFirstRequest)\n \t\t\t\tisFirstRequest = false;\n \n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\t\tbreak;\n \t\t\t}\n\t\t\tresponse.close();\n\n\t\t\tif (!isResendable)\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tresponse.close();\n\n\t\t\tif (!isResendable) {\n \t\t\t\tthrow new ResourceNotResendableException(\n \t\t\t\t\t\t\"Cannot retry request for \" + connectPath);\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\t\t\t}\n\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n \t\t}\n \t\tif (status == ClientResponse.Status.FORBIDDEN)\n \t\t\tthrow new ForbiddenUserException(\"User is not allowed to write \"\n \n \t\tClientResponse response = null;\n \t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n \t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n \t\t\tresponse = builder.delete(ClientResponse.class);\n \t\t\tstatus = response.getClientResponseStatus();\n \n \t\t\tif (isFirstRequest)\n \t\t\t\tisFirstRequest = false;\n \n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\t\tbreak;\n \t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n \t\t}\n \t\tif (status == ClientResponse.Status.FORBIDDEN)\n \t\t\tthrow new ForbiddenUserException(\"User is not allowed to delete \"\n \n \t\tClientResponse response = null;\n \t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n \t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n \t\t\tresponse = builder.delete(ClientResponse.class);\n \t\t\tstatus = response.getClientResponseStatus();\n \n \t\t\tif (isFirstRequest)\n \t\t\t\tisFirstRequest = false;\n \n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\t\tbreak;\n \t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n \t\t}\n \t\tif (status == ClientResponse.Status.FORBIDDEN)\n \t\t\tthrow new ForbiddenUserException(\"User is not allowed to delete \"\n \n \t\tClientResponse response = null;\n \t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n \t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n \t\t\tresponse = doGet(builder);\n \t\t\tstatus = response.getClientResponseStatus();\n \n \t\t\tif (isFirstRequest)\n \t\t\t\tisFirstRequest = false;\n \n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\t\tbreak;\n \t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n \t\t}\n \t\tcheckStatus(response, status, \"read\", \"resource\", path,\n \t\t\t\tResponseStatus.OK_OR_NO_CONTENT);\n \n \t\tClientResponse response = null;\n \t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n \t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n \t\t\tresponse = doGet(builder.accept(multipartType));\n \t\t\tstatus = response.getClientResponseStatus();\n \n \t\t\tif (isFirstRequest)\n \t\t\t\tisFirstRequest = false;\n \n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\t\tbreak;\n \t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n \t\t}\n \n \t\tcheckStatus(response, status, \"read\", \"resource\", path,\n \n \t\tClientResponse response = null;\n \t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n \t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n \t\t\tresponse = doPut(reqlog, builder, inputBase.sendContent(),\n \t\t\t\t\t!isResendable);\n \t\t\tstatus = response.getClientResponseStatus();\n \t\t\tif (isFirstRequest)\n \t\t\t\tisFirstRequest = false;\n \n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\t\tbreak;\n \t\t\t}\n\t\t\tresponse.close();\n\n\t\t\tif (!isResendable)\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tresponse.close();\n\n\t\t\tif (!isResendable) {\n \t\t\t\tthrow new ResourceNotResendableException(\n \t\t\t\t\t\t\"Cannot retry request for \" + path);\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\t\t\t}\n\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n \t\t}\n \n \t\tcheckStatus(response, status, \"write\", \"resource\", path,\n \n \t\tClientResponse response = null;\n \t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n \t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n \t\t\tMultiPart multiPart = new MultiPart();\n \t\t\tboolean hasStreamingPart = addParts(multiPart, reqlog, input);\n \n \t\t\tif (isFirstRequest)\n \t\t\t\tisFirstRequest = false;\n \n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\t\tbreak;\n \t\t\t}\n\t\t\tresponse.close();\n\n\t\t\tif (hasStreamingPart)\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tresponse.close();\n\n\t\t\tif (hasStreamingPart) {\n \t\t\t\tthrow new ResourceNotResendableException(\n \t\t\t\t\t\t\"Cannot retry request for \" + path);\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\t\t\t}\n\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n \t\t}\n \n \t\tcheckStatus(response, status, \"write\", \"resource\", path,\n \n \t\tClientResponse response = null;\n \t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n \t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n \t\t\tresponse = doPost(reqlog, builder, inputBase.sendContent(),\n \t\t\t\t\t!isResendable);\n \t\t\tstatus = response.getClientResponseStatus();\n \t\t\tif (isFirstRequest)\n \t\t\t\tisFirstRequest = false;\n \n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\t\tbreak;\n \t\t\t}\n\t\t\tresponse.close();\n\n\t\t\tif (!isResendable)\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tresponse.close();\n\n\t\t\tif (!isResendable) {\n \t\t\t\tthrow new ResourceNotResendableException(\n \t\t\t\t\t\t\"Cannot retry request for \" + path);\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\t\t\t}\n\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n \t\t}\n \n \t\tcheckStatus(response, status, \"apply\", \"resource\", path,\n \n \t\tClientResponse response = null;\n \t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n \t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n \t\t\tMultiPart multiPart = new MultiPart();\n \t\t\tboolean hasStreamingPart = addParts(multiPart, reqlog, input);\n \n \t\t\tif (isFirstRequest)\n \t\t\t\tisFirstRequest = false;\n \n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\t\tbreak;\n \t\t\t}\n\t\t\tresponse.close();\n\n\t\t\tif (hasStreamingPart)\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tresponse.close();\n\n\t\t\tif (hasStreamingPart) {\n \t\t\t\tthrow new ResourceNotResendableException(\n \t\t\t\t\t\t\"Cannot retry request for \" + path);\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\t\t\t}\n\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n \t\t}\n \n \t\tcheckStatus(response, status, \"apply\", \"resource\", path,\n \n \t\tClientResponse response = null;\n \t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n \t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n \t\t\tObject value = inputBase.sendContent();\n \n \t\t\tresponse = doPost(reqlog, builder.accept(multipartType), value, !isResendable);\n \t\t\tif (isFirstRequest)\n \t\t\t\tisFirstRequest = false;\n \n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\t\tbreak;\n \t\t\t}\n\t\t\tresponse.close();\n\n\t\t\tif (!isResendable)\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tresponse.close();\n\n\t\t\tif (!isResendable) {\n \t\t\t\tthrow new ResourceNotResendableException(\n \t\t\t\t\t\t\"Cannot retry request for \" + path);\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\t\t\t}\n\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n \t\t}\n \n \t\tcheckStatus(response, status, \"apply\", \"resource\", path,\n \t\t\tForbiddenUserException, FailedRequestException {\n \t\tClientResponse response = null;\n \t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n \t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n \t\t\tMultiPart multiPart = new MultiPart();\n \t\t\tboolean hasStreamingPart = addParts(multiPart, reqlog, input);\n \n \t\t\tif (isFirstRequest)\n \t\t\t\tisFirstRequest = false;\n \n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\t\tbreak;\n \t\t\t}\n\t\t\tresponse.close();\n\n\t\t\tif (hasStreamingPart)\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tresponse.close();\n\n\t\t\tif (hasStreamingPart) {\n \t\t\t\tthrow new ResourceNotResendableException(\n \t\t\t\t\t\t\"Cannot retry request for \" + path);\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\t\t\t}\n\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n \t\t}\n \n \t\tcheckStatus(response, status, \"apply\", \"resource\", path,\n \n \t\tClientResponse response = null;\n \t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n \t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n \t\t\tresponse = doDelete(builder);\n \t\t\tstatus = response.getClientResponseStatus();\n \n \t\t\tif (isFirstRequest)\n \t\t\t\tisFirstRequest = false;\n \n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\t\tbreak;\n \t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n \t\t}\n \n \t\tcheckStatus(response, status, \"delete\", \"resource\", path,\n \t\treturn (builder != null) ? builder.toString() : null;\n \t}\n \n\tprivate int calculateDelay(Random rand, int iteration) {\n\t\tint base = (1 << iteration) * delayMultiplier;\n\t\treturn delayFloor + base + randRetry.nextInt((iteration + 1 < maxRetries) ? base : 100);\n\tprivate int calculateDelay(Random rand, int i) {\n\t\tint min =\n\t\t\t(i > 6) ? DELAY_CEILING :\n\t\t\t(i == 0) ? DELAY_FLOOR :\n\t\t\t DELAY_FLOOR + (1 << i) * DELAY_MULTIPLIER;\n\t\tint range =\n\t\t\t(i > 6) ? DELAY_FLOOR :\n\t\t\t(i == 0) ? 2 * DELAY_MULTIPLIER :\n\t\t\t(i == 6) ? DELAY_CEILING - min :\n\t\t\t\t (1 << i) * DELAY_MULTIPLIER;\n\t\treturn min + randRetry.nextInt(range);\n \t}\n \n \tpublic class JerseyResult implements ServiceResult {\n \t\t\t\t.accept(\"application/xml\");\n \t\tClientResponse response = null;\n \t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n \t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n \t\t\tresponse = builder.get(ClientResponse.class);\n \n \t\t\tstatus = response.getClientResponseStatus();\n \t\t\tif (isFirstRequest)\n \t\t\t\tisFirstRequest = false;\n \n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\t\tbreak;\n \t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n \t\t}\n \t\tif (status == ClientResponse.Status.FORBIDDEN) {\n \t\t\tthrow new ForbiddenUserException(\n \t\t\n \t\tClientResponse response = null;\n \t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n \t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n \t\t\tresponse = doPost(null, builder, baseHandle.sendContent(), false);\n \n \t\t\tstatus = response.getClientResponseStatus();\n \t\t\tif (isFirstRequest)\n \t\t\t\tisFirstRequest = false;\n \n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\t\tbreak;\n \t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n \t\t}\n \t\tif (status == ClientResponse.Status.FORBIDDEN) {\n \t\t\tthrow new ForbiddenUserException(\"User is not allowed to match\",\n \t\t}\n \t\tClientResponse response = null;\n \t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n \t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n \t\t\tif (queryDef instanceof StringQueryDefinition) {\n \t\t\t\tresponse = builder.get(ClientResponse.class);\n \t\t\t} else if (queryDef instanceof StructuredQueryDefinition) {\n \t\t\tif (isFirstRequest)\n \t\t\t\tisFirstRequest = false;\n \n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\t\tbreak;\n \t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n \t\t}\n \t\tif (status == ClientResponse.Status.FORBIDDEN) {\n \t\t\tthrow new ForbiddenUserException(\"User is not allowed to match\",\n \t\t\n \t\tClientResponse response = null;\n \t\tClientResponse.Status status = null;\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint nextDelay = 0;\n \t\tint retry = 0;\n\t\tfor (; retry < maxRetries; retry++) {\n\t\tfor (; retry < minRetry || (System.currentTimeMillis() - startTime) < maxDelay; retry++) {\n\t\t\tif (nextDelay > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(nextDelay);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t}\n\n \t\t\tresponse = doGet(builder);\n \n \t\t\tstatus = response.getClientResponseStatus();\n \t\t\tif (isFirstRequest)\n \t\t\t\tisFirstRequest = false;\n \n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE\n\t\t\t\t\t|| !\"1\".equals(response.getHeaders()\n\t\t\t\t\t\t\t.getFirst(\"Retry-After\"))) {\n\t\t\tif (status != ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\t\tbreak;\n \t\t\t}\n\t\t\tresponse.close();\n\n\t\t\ttry {\n\t\t\t\tThread.sleep(calculateDelay(randRetry, retry));\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t}\n\t\tif (retry >= maxRetries) {\n\t\t\tresponse.close();\n\n\t\t\tMultivaluedMap responseHeaders = response.getHeaders();\n\t\t\tString retryAfterRaw = responseHeaders.getFirst(\"Retry-After\");\n\t\t\tint retryAfter = (retryAfterRaw != null) ? Integer.valueOf(retryAfterRaw) : -1;\n\n\t\t\tresponse.close();\n\n\t\t\tnextDelay = Math.max(retryAfter, calculateDelay(randRetry, retry));\n\t\t}\n\t\tif (status == ClientResponse.Status.SERVICE_UNAVAILABLE) {\n \t\t\tthrow new FailedRequestException(\n\t\t\t\t\t\"Service unavailable and retries exhausted\");\n\t\t\t\t\t\"Service unavailable and maximum retry period elapsed: \"+\n\t\t\t\t\t\t Math.round((System.currentTimeMillis() - startTime) / 1000)+\n\t\t\t\t\t\t \" seconds after \"+retry+\" retries\");\n \t\t}\n \t\tif (status == ClientResponse.Status.FORBIDDEN) {\n \t\t\tthrow new ForbiddenUserException(\"User is not allowed to match\","}}},{"rowIdx":1970,"cells":{"lang":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"67e67f1f760e4daeab973087b751144e3701afaf"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"speckjs/gulp-speckjs"},"new_contents":{"kind":"string","value":"var through = require('through2');\nvar glob = require('glob');\nvar gutil = require('gulp-util');\nvar PluginError = gutil.PluginError;\nvar speckjs = require('speckjs');\nvar extend = require('util')._extend;\n\nconst PLUGIN_NAME = 'gulp-speckjs';\n\nmodule.exports = function(options) {\n\n var source;\n var defaults = {\n testFW: 'tape',\n logs: true\n };\n options = extend(defaults, options);\n\n return through.obj(function(file, enc, cb) {\n if (file.isNull()) {\n cb(null, file);\n }\n\n options.onBuild = function(output){\n file.contents = new Buffer(output);\n if (options.logs) {\n gutil.log(gutil.colors.green('Boom! ') + options.testFW + ' spec file compiled' );\n }\n cb(null, file);\n };\n\n if (file.isBuffer()) {\n try {\n\n source = {\n name: file.path,\n content: file.contents.toString()\n };\n\n speckjs.build(source, options);\n\n } catch(error) {\n this.emit('error', new PluginError(PLUGIN_NAME, error));\n return cb(error);\n }\n }\n if (file.isStream()) {\n var source = '';\n file.on('readable',function(buffer){\n var chunk = buffer.read().toString();\n source += chunk;\n });\n file.on('end',function(){\n try {\n\n source = {\n name: file.path,\n content: source\n };\n speckjs.build(source, options);\n\n } catch(error) {\n this.emit('error', new PluginError(PLUGIN_NAME, error));\n return cb(error);\n }\n });\n }\n });\n};\n"},"new_file":{"kind":"string","value":"index.js"},"old_contents":{"kind":"string","value":"//File to hold the gulp task being called in our gulpfile\nvar gutil = require('gulp-util');\nvar through = require('through2');\n// var glob = require('glob');\nvar gutil = require('gulp-util');\nvar path = require('path');\nvar PluginError = gutil.PluginError;\nvar speck = require('speckjs');\n\n//pass files and options into function\nmodule.exports = function(options){\n//Need to add some kind of options or default options logic\nvar defOption;\noptions = options || defOption;\nvar files = [];\nvar stream = through.obj(function (file, enc, cb) {\n if (file.isNull()) {\n cb(null, file);\n return;\n }\n if (file.isStream()) {\n cb(new gutil.PluginError('gulp-speckjs', 'Streaming not supported'));\n return;\n }\n //Grab each file\n //Run speckbuild on each file -- foreach?\n //Write string produced from that to a file with file name as origin file + w/e is in options\n });\nreturn stream;\n};\n"},"message":{"kind":"string","value":"Main gulp plugin logic\n"},"old_file":{"kind":"string","value":"index.js"},"subject":{"kind":"string","value":"Main gulp plugin logic"},"git_diff":{"kind":"string","value":"ndex.js\n//File to hold the gulp task being called in our gulpfile\nvar through = require('through2');\nvar glob = require('glob');\n var gutil = require('gulp-util');\nvar through = require('through2');\n// var glob = require('glob');\nvar gutil = require('gulp-util');\nvar path = require('path');\n var PluginError = gutil.PluginError;\nvar speck = require('speckjs');\nvar speckjs = require('speckjs');\nvar extend = require('util')._extend;\n \n//pass files and options into function\nmodule.exports = function(options){\n//Need to add some kind of options or default options logic\nvar defOption;\noptions = options || defOption;\nvar files = [];\nvar stream = through.obj(function (file, enc, cb) {\nconst PLUGIN_NAME = 'gulp-speckjs';\n\nmodule.exports = function(options) {\n\n var source;\n var defaults = {\n testFW: 'tape',\n logs: true\n };\n options = extend(defaults, options);\n\n return through.obj(function(file, enc, cb) {\n if (file.isNull()) {\n cb(null, file);\n return;\n }\n\n options.onBuild = function(output){\n file.contents = new Buffer(output);\n if (options.logs) {\n gutil.log(gutil.colors.green('Boom! ') + options.testFW + ' spec file compiled' );\n }\n cb(null, file);\n };\n\n if (file.isBuffer()) {\n try {\n\n source = {\n name: file.path,\n content: file.contents.toString()\n };\n\n speckjs.build(source, options);\n\n } catch(error) {\n this.emit('error', new PluginError(PLUGIN_NAME, error));\n return cb(error);\n }\n }\n if (file.isStream()) {\n cb(new gutil.PluginError('gulp-speckjs', 'Streaming not supported'));\n return;\n var source = '';\n file.on('readable',function(buffer){\n var chunk = buffer.read().toString();\n source += chunk;\n });\n file.on('end',function(){\n try {\n\n source = {\n name: file.path,\n content: source\n };\n speckjs.build(source, options);\n\n } catch(error) {\n this.emit('error', new PluginError(PLUGIN_NAME, error));\n return cb(error);\n }\n });\n }\n //Grab each file\n //Run speckbuild on each file -- foreach?\n //Write string produced from that to a file with file name as origin file + w/e is in options\n });\nreturn stream;\n };"}}},{"rowIdx":1971,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"f21d8a0ce702aa5ee0eee0291a97868a28ecf163"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"SpineEventEngine/base,SpineEventEngine/base,SpineEventEngine/base"},"new_contents":{"kind":"string","value":"/*\n * Copyright 2017, TeamDev Ltd. All rights reserved.\n *\n * Redistribution and use in source and/or binary forms, with or without\n * modification, must retain the above copyright notice and the following\n * disclaimer.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\npackage io.spine.tools.protodoc;\n\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport static java.util.regex.Pattern.DOTALL;\nimport static java.util.regex.Pattern.compile;\n\n/**\n * A formatting action, which handles {@code

    } tags.\n *\n * 

    The action removes the tags inserted by the Protobuf compiler,\n * i.e. the first opening tag and the last closing tag.\n *\n * @author Dmytro Grankin\n */\nclass PreTagFormatting implements FormattingAction {\n\n static final String CLOSING_PRE = \"

    \";\n static final String OPENING_PRE = \"
    \";\n    private static final Pattern PATTERN_OPENING_PRE = compile(OPENING_PRE);\n    private static final Pattern NOT_FORMATTED_DOC_PATTERN =\n            compile(\"^/\\\\*\\\\*[\\\\s*]*
    .*
    [\\\\s*]+.*[\\\\s*]*\\\\*/$\", DOTALL);\n\n /**\n * Obtains the formatted representation of the specified text.\n *\n * @param javadoc the Javadoc to format\n * @return the text without generated {@code
    } tags\n     */\n    @Override\n    public String execute(String javadoc) {\n        if (!shouldFormat(javadoc)) {\n            return javadoc;\n        }\n\n        final Matcher matcher = PATTERN_OPENING_PRE.matcher(javadoc);\n        final String withoutOpeningPre = matcher.replaceFirst(\"\");\n        return removeLastClosingPre(withoutOpeningPre);\n    }\n\n    private static String removeLastClosingPre(String text) {\n        final int tagIndex = text.lastIndexOf(CLOSING_PRE);\n        final String beforeTag = text.substring(0, tagIndex);\n        final String afterTag = text.substring(tagIndex + CLOSING_PRE.length());\n        return beforeTag + afterTag;\n    }\n\n    /**\n     * Determines whether the specified Javadoc should be formatted.\n     *\n     * 

    For map getters, the compiler generates Javadocs without {@code pre} tags.\n * So, Javadocs for such methods should not be formatted.\n *\n * @param javadoc the Javadoc to test\n * @return {@code true} if the Javadoc contains opening and closing {@code pre} tag\n */\n private static boolean shouldFormat(String javadoc) {\n return NOT_FORMATTED_DOC_PATTERN.matcher(javadoc).matches();\n }\n}\n"},"new_file":{"kind":"string","value":"src/main/java/io/spine/tools/protodoc/PreTagFormatting.java"},"old_contents":{"kind":"string","value":"/*\n * Copyright 2017, TeamDev Ltd. All rights reserved.\n *\n * Redistribution and use in source and/or binary forms, with or without\n * modification, must retain the above copyright notice and the following\n * disclaimer.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\npackage io.spine.tools.protodoc;\n\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\n/**\n * A formatting action, which handles {@code

    } tags.\n *\n * 

    The action removes the tags inserted by the Protobuf compiler,\n * i.e. the first opening tag and the last closing tag.\n *\n * @author Dmytro Grankin\n */\nclass PreTagFormatting implements FormattingAction {\n\n static final String CLOSING_PRE = \"

    \";\n static final String OPENING_PRE = \"
    \";\n    private static final Pattern PATTERN_OPENING_PRE = Pattern.compile(OPENING_PRE);\n    private static final Pattern NOT_FORMATTED_DOC_PATTERN = Pattern.compile(\"^/\\\\*\\\\*[\\\\s*]*
    .*
    [\\\\s*]+.*[\\\\s*]*\\\\*/$\", Pattern.DOTALL);\n\n /**\n * Obtains the formatted representation of the specified text.\n *\n * @param javadoc the Javadoc to format\n * @return the text without generated {@code
    } tags\n     */\n    @Override\n    public String execute(String javadoc) {\n        if (!shouldFormat(javadoc)) {\n            return javadoc;\n        }\n\n        final Matcher matcher = PATTERN_OPENING_PRE.matcher(javadoc);\n        final String withoutOpeningPre = matcher.replaceFirst(\"\");\n        return removeLastClosingPre(withoutOpeningPre);\n    }\n\n    private static String removeLastClosingPre(String text) {\n        final int tagIndex = text.lastIndexOf(CLOSING_PRE);\n        final String beforeTag = text.substring(0, tagIndex);\n        final String afterTag = text.substring(tagIndex + CLOSING_PRE.length());\n        return beforeTag + afterTag;\n    }\n\n    /**\n     * Determines whether the specified Javadoc should be formatted.\n     *\n     * 

    For map getters, the compiler generates Javadocs without {@code pre} tags.\n * So, Javadocs for such methods should not be formatted.\n *\n * @param javadoc the Javadoc to test\n * @return {@code true} if the Javadoc contains opening and closing {@code pre} tag\n */\n private static boolean shouldFormat(String javadoc) {\n return NOT_FORMATTED_DOC_PATTERN.matcher(javadoc).matches();\n }\n}\n"},"message":{"kind":"string","value":"Fix code wrapping.\n"},"old_file":{"kind":"string","value":"src/main/java/io/spine/tools/protodoc/PreTagFormatting.java"},"subject":{"kind":"string","value":"Fix code wrapping."},"git_diff":{"kind":"string","value":"rc/main/java/io/spine/tools/protodoc/PreTagFormatting.java\n import java.util.regex.Matcher;\n import java.util.regex.Pattern;\n \nimport static java.util.regex.Pattern.DOTALL;\nimport static java.util.regex.Pattern.compile;\n\n /**\n * A formatting action, which handles {@code

    } tags.\n  *\n \n     static final String CLOSING_PRE = \"
    \";\n static final String OPENING_PRE = \"
    \";\n    private static final Pattern PATTERN_OPENING_PRE = Pattern.compile(OPENING_PRE);\n    private static final Pattern NOT_FORMATTED_DOC_PATTERN = Pattern.compile(\"^/\\\\*\\\\*[\\\\s*]*
    .*
    [\\\\s*]+.*[\\\\s*]*\\\\*/$\", Pattern.DOTALL);\n private static final Pattern PATTERN_OPENING_PRE = compile(OPENING_PRE);\n private static final Pattern NOT_FORMATTED_DOC_PATTERN =\n compile(\"^/\\\\*\\\\*[\\\\s*]*
    .*
    [\\\\s*]+.*[\\\\s*]*\\\\*/$\", DOTALL);\n \n /**\n * Obtains the formatted representation of the specified text."}}},{"rowIdx":1972,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"lgpl-2.1"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"7fd86ad80d6ae0048a0620098833f97e70da3c2b"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"romani/checkstyle,checkstyle/checkstyle,checkstyle/checkstyle,romani/checkstyle,rnveach/checkstyle,rnveach/checkstyle,rnveach/checkstyle,romani/checkstyle,checkstyle/checkstyle,checkstyle/checkstyle,checkstyle/checkstyle,checkstyle/checkstyle,romani/checkstyle,rnveach/checkstyle,rnveach/checkstyle,romani/checkstyle,rnveach/checkstyle,romani/checkstyle"},"new_contents":{"kind":"string","value":"////////////////////////////////////////////////////////////////////////////////\n// checkstyle: Checks Java source code for adherence to a set of rules.\n// Copyright (C) 2001-2021 the original author or authors.\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 2.1 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n////////////////////////////////////////////////////////////////////////////////\n\npackage com.puppycrawl.tools.checkstyle.api;\n\nimport com.puppycrawl.tools.checkstyle.grammar.GeneratedJavaTokenTypes;\n\n/**\n * Contains the constants for all the tokens contained in the Abstract\n * Syntax Tree.\n *\n *

    Implementation detail: This class has been introduced to break\n * the circular dependency between packages.

    \n *\n * @noinspection ClassWithTooManyDependents\n */\npublic final class TokenTypes {\n\n /**\n * The end of file token. This is the root node for the source\n * file. It's children are an optional package definition, zero\n * or more import statements, and one or more class or interface\n * definitions.\n *\n * @see #PACKAGE_DEF\n * @see #IMPORT\n * @see #CLASS_DEF\n * @see #INTERFACE_DEF\n **/\n public static final int EOF = GeneratedJavaTokenTypes.EOF;\n /**\n * Modifiers for type, method, and field declarations. The\n * modifiers element is always present even though it may have no\n * children.\n *\n * @see Java\n * Language Specification, &sect;8\n * @see #LITERAL_PUBLIC\n * @see #LITERAL_PROTECTED\n * @see #LITERAL_PRIVATE\n * @see #ABSTRACT\n * @see #LITERAL_STATIC\n * @see #FINAL\n * @see #LITERAL_TRANSIENT\n * @see #LITERAL_VOLATILE\n * @see #LITERAL_SYNCHRONIZED\n * @see #LITERAL_NATIVE\n * @see #STRICTFP\n * @see #ANNOTATION\n * @see #LITERAL_DEFAULT\n **/\n public static final int MODIFIERS = GeneratedJavaTokenTypes.MODIFIERS;\n\n /**\n * An object block. These are children of class, interface, enum,\n * annotation and enum constant declarations.\n * Also, object blocks are children of the new keyword when defining\n * anonymous inner types.\n *\n * @see #LCURLY\n * @see #INSTANCE_INIT\n * @see #STATIC_INIT\n * @see #CLASS_DEF\n * @see #CTOR_DEF\n * @see #METHOD_DEF\n * @see #VARIABLE_DEF\n * @see #RCURLY\n * @see #INTERFACE_DEF\n * @see #LITERAL_NEW\n * @see #ENUM_DEF\n * @see #ENUM_CONSTANT_DEF\n * @see #ANNOTATION_DEF\n **/\n public static final int OBJBLOCK = GeneratedJavaTokenTypes.OBJBLOCK;\n /**\n * A list of statements.\n *\n *

    For example:

    \n *
    \n     * if (c == 1) {\n     *     c = 0;\n     * }\n     * 
    \n *

    parses as:

    \n *
    \n     * LITERAL_IF -&gt; if\n     *  |--LPAREN -&gt; (\n     *  |--EXPR -&gt; EXPR\n     *  |   `--EQUAL -&gt; ==\n     *  |       |--IDENT -&gt; c\n     *  |       `--NUM_INT -&gt; 1\n     *  |--RPAREN -&gt; )\n     *  `--SLIST -&gt; {\n     *      |--EXPR -&gt; EXPR\n     *      |   `--ASSIGN -&gt; =\n     *      |       |--IDENT -&gt; c\n     *      |       `--NUM_INT -&gt; 0\n     *      |--SEMI -&gt; ;\n     *      `--RCURLY -&gt; }\n     * 
    \n *\n * @see #RCURLY\n * @see #EXPR\n * @see #LABELED_STAT\n * @see #LITERAL_THROWS\n * @see #LITERAL_RETURN\n * @see #SEMI\n * @see #METHOD_DEF\n * @see #CTOR_DEF\n * @see #LITERAL_FOR\n * @see #LITERAL_WHILE\n * @see #LITERAL_IF\n * @see #LITERAL_ELSE\n * @see #CASE_GROUP\n **/\n public static final int SLIST = GeneratedJavaTokenTypes.SLIST;\n /**\n * A constructor declaration.\n *\n *

    For example:

    \n *
    \n     * public SpecialEntry(int value, String text)\n     * {\n     *   this.value = value;\n     *   this.text = text;\n     * }\n     * 
    \n *

    parses as:

    \n *
    \n     * +--CTOR_DEF\n     *     |\n     *     +--MODIFIERS\n     *         |\n     *         +--LITERAL_PUBLIC (public)\n     *     +--IDENT (SpecialEntry)\n     *     +--LPAREN (()\n     *     +--PARAMETERS\n     *         |\n     *         +--PARAMETER_DEF\n     *             |\n     *             +--MODIFIERS\n     *             +--TYPE\n     *                 |\n     *                 +--LITERAL_INT (int)\n     *             +--IDENT (value)\n     *         +--COMMA (,)\n     *         +--PARAMETER_DEF\n     *             |\n     *             +--MODIFIERS\n     *             +--TYPE\n     *                 |\n     *                 +--IDENT (String)\n     *             +--IDENT (text)\n     *     +--RPAREN ())\n     *     +--SLIST ({)\n     *         |\n     *         +--EXPR\n     *             |\n     *             +--ASSIGN (=)\n     *                 |\n     *                 +--DOT (.)\n     *                     |\n     *                     +--LITERAL_THIS (this)\n     *                     +--IDENT (value)\n     *                 +--IDENT (value)\n     *         +--SEMI (;)\n     *         +--EXPR\n     *             |\n     *             +--ASSIGN (=)\n     *                 |\n     *                 +--DOT (.)\n     *                     |\n     *                     +--LITERAL_THIS (this)\n     *                     +--IDENT (text)\n     *                 +--IDENT (text)\n     *         +--SEMI (;)\n     *         +--RCURLY (})\n     * 
    \n *\n * @see #OBJBLOCK\n * @see #CLASS_DEF\n **/\n public static final int CTOR_DEF = GeneratedJavaTokenTypes.CTOR_DEF;\n /**\n * A method declaration. The children are modifiers, type parameters,\n * return type, method name, parameter list, an optional throws list, and\n * statement list. The statement list is omitted if the method\n * declaration appears in an interface declaration. Method\n * declarations may appear inside object blocks of class\n * declarations, interface declarations, enum declarations,\n * enum constant declarations or anonymous inner-class declarations.\n *\n *

    For example:

    \n *\n *
    \n     *  public static int square(int x)\n     *  {\n     *    return x*x;\n     *  }\n     * 
    \n *\n *

    parses as:

    \n *\n *
    \n     * --METHOD_DEF -&gt; METHOD_DEF\n     *    |--MODIFIERS -&gt; MODIFIERS\n     *    |   |--LITERAL_PUBLIC -&gt; public\n     *    |   `--LITERAL_STATIC -&gt; static\n     *    |--TYPE -&gt; TYPE\n     *    |   `--LITERAL_INT -&gt; int\n     *    |--IDENT -&gt; square\n     *    |--LPAREN -&gt; (\n     *    |--PARAMETERS -&gt; PARAMETERS\n     *    |   `--PARAMETER_DEF -&gt; PARAMETER_DEF\n     *    |       |--MODIFIERS -&gt; MODIFIERS\n     *    |       |--TYPE -&gt; TYPE\n     *    |       |   `--LITERAL_INT -&gt; int\n     *    |       `--IDENT -&gt; x\n     *    |--RPAREN -&gt; )\n     *    `--SLIST -&gt; {\n     *        |--LITERAL_RETURN -&gt; return\n     *        |   |--EXPR -&gt; EXPR\n     *        |   |   `--STAR -&gt; *\n     *        |   |       |--IDENT -&gt; x\n     *        |   |       `--IDENT -&gt; x\n     *        |   `--SEMI -&gt; ;\n     *        `--RCURLY -&gt; }\n     * 
    \n *\n * @see #MODIFIERS\n * @see #TYPE_PARAMETERS\n * @see #TYPE\n * @see #IDENT\n * @see #PARAMETERS\n * @see #LITERAL_THROWS\n * @see #SLIST\n * @see #OBJBLOCK\n **/\n public static final int METHOD_DEF = GeneratedJavaTokenTypes.METHOD_DEF;\n /**\n * A field or local variable declaration. The children are\n * modifiers, type, the identifier name, and an optional\n * assignment statement.\n *\n *

    For example:

    \n *
    \n     * final int PI = 3.14;\n     * 
    \n *

    parses as:

    \n *
    \n     * VARIABLE_DEF -&gt; VARIABLE_DEF\n     *  |--MODIFIERS -&gt; MODIFIERS\n     *  |   `--FINAL -&gt; final\n     *  |--TYPE -&gt; TYPE\n     *  |   `--LITERAL_INT -&gt; int\n     *  |--IDENT -&gt; PI\n     *  |--ASSIGN -&gt; =\n     *  |   `--EXPR -&gt; EXPR\n     *  |       `--NUM_FLOAT -&gt; 3.14\n     *  `--SEMI -&gt; ;\n     * 
    \n *\n * @see #MODIFIERS\n * @see #TYPE\n * @see #IDENT\n * @see #ASSIGN\n **/\n public static final int VARIABLE_DEF =\n GeneratedJavaTokenTypes.VARIABLE_DEF;\n\n /**\n * An instance initializer. Zero or more instance initializers\n * may appear in class and enum definitions. This token will be a child\n * of the object block of the declaring type.\n *\n * @see Java\n * Language Specification&sect;8.6\n * @see #SLIST\n * @see #OBJBLOCK\n **/\n public static final int INSTANCE_INIT =\n GeneratedJavaTokenTypes.INSTANCE_INIT;\n\n /**\n * A static initialization block. Zero or more static\n * initializers may be children of the object block of a class\n * or enum declaration (interfaces cannot have static initializers). The\n * first and only child is a statement list.\n *\n * @see Java\n * Language Specification, &sect;8.7\n * @see #SLIST\n * @see #OBJBLOCK\n **/\n public static final int STATIC_INIT =\n GeneratedJavaTokenTypes.STATIC_INIT;\n\n /**\n * A type. This is either a return type of a method or a type of\n * a variable or field. The first child of this element is the\n * actual type. This may be a primitive type, an identifier, a\n * dot which is the root of a fully qualified type, or an array of\n * any of these. The second child may be type arguments to the type.\n *\n *

    For example:

    \n *
    boolean var = true;
    \n *

    parses as:

    \n *
    \n     * |--VARIABLE_DEF -&gt; VARIABLE_DEF\n     * |   |--MODIFIERS -&gt; MODIFIERS\n     * |   |--TYPE -&gt; TYPE\n     * |   |   `--LITERAL_BOOLEAN -&gt; boolean\n     * |   |--IDENT -&gt; var\n     * |   `--ASSIGN -&gt; =\n     * |       `--EXPR -&gt; EXPR\n     * |           `--LITERAL_TRUE -&gt; true\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see #VARIABLE_DEF\n * @see #METHOD_DEF\n * @see #PARAMETER_DEF\n * @see #IDENT\n * @see #DOT\n * @see #LITERAL_VOID\n * @see #LITERAL_BOOLEAN\n * @see #LITERAL_BYTE\n * @see #LITERAL_CHAR\n * @see #LITERAL_SHORT\n * @see #LITERAL_INT\n * @see #LITERAL_FLOAT\n * @see #LITERAL_LONG\n * @see #LITERAL_DOUBLE\n * @see #ARRAY_DECLARATOR\n * @see #TYPE_ARGUMENTS\n **/\n public static final int TYPE = GeneratedJavaTokenTypes.TYPE;\n /**\n * A class declaration.\n *\n *

    For example:

    \n *
    \n     * public class MyClass\n     *   implements Serializable\n     * {\n     * }\n     * 
    \n *

    parses as:

    \n *
    \n     * +--CLASS_DEF\n     *     |\n     *     +--MODIFIERS\n     *         |\n     *         +--LITERAL_PUBLIC (public)\n     *     +--LITERAL_CLASS (class)\n     *     +--IDENT (MyClass)\n     *     +--EXTENDS_CLAUSE\n     *     +--IMPLEMENTS_CLAUSE\n     *         |\n     *         +--IDENT (Serializable)\n     *     +--OBJBLOCK\n     *         |\n     *         +--LCURLY ({)\n     *         +--RCURLY (})\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;8\n * @see #MODIFIERS\n * @see #IDENT\n * @see #EXTENDS_CLAUSE\n * @see #IMPLEMENTS_CLAUSE\n * @see #OBJBLOCK\n * @see #LITERAL_NEW\n **/\n public static final int CLASS_DEF = GeneratedJavaTokenTypes.CLASS_DEF;\n /**\n * An interface declaration.\n *\n *

    For example:

    \n *\n *
    \n     *   public interface MyInterface\n     *   {\n     *   }\n     *\n     * 
    \n *\n *

    parses as:

    \n *\n *
    \n     * +--INTERFACE_DEF\n     *     |\n     *     +--MODIFIERS\n     *         |\n     *         +--LITERAL_PUBLIC (public)\n     *     +--LITERAL_INTERFACE (interface)\n     *     +--IDENT (MyInterface)\n     *     +--EXTENDS_CLAUSE\n     *     +--OBJBLOCK\n     *         |\n     *         +--LCURLY ({)\n     *         +--RCURLY (})\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;9\n * @see #MODIFIERS\n * @see #IDENT\n * @see #EXTENDS_CLAUSE\n * @see #OBJBLOCK\n **/\n public static final int INTERFACE_DEF =\n GeneratedJavaTokenTypes.INTERFACE_DEF;\n\n /**\n * The package declaration. This is optional, but if it is\n * included, then there is only one package declaration per source\n * file and it must be the first non-comment in the file. A package\n * declaration may be annotated in which case the annotations comes\n * before the rest of the declaration (and are the first children).\n *\n *

    For example:

    \n *\n *
    \n     *   package com.puppycrawl.tools.checkstyle.api;\n     * 
    \n *\n *

    parses as:

    \n *\n *
    \n     * PACKAGE_DEF -&gt; package\n     * |--ANNOTATIONS -&gt; ANNOTATIONS\n     * |--DOT -&gt; .\n     * |   |--DOT -&gt; .\n     * |   |   |--DOT -&gt; .\n     * |   |   |   |--DOT -&gt; .\n     * |   |   |   |   |--IDENT -&gt; com\n     * |   |   |   |   `--IDENT -&gt; puppycrawl\n     * |   |   |   `--IDENT -&gt; tools\n     * |   |   `--IDENT -&gt; checkstyle\n     * |   `--IDENT -&gt; api\n     * `--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification &sect;7.4\n * @see #DOT\n * @see #IDENT\n * @see #SEMI\n * @see #ANNOTATIONS\n * @see FullIdent\n **/\n public static final int PACKAGE_DEF = GeneratedJavaTokenTypes.PACKAGE_DEF;\n /**\n * An array declaration.\n *\n *

    If the array declaration represents a type, then the type of\n * the array elements is the first child. Multidimensional arrays\n * may be regarded as arrays of arrays. In other words, the first\n * child of the array declaration is another array\n * declaration.

    \n *\n *

    For example:

    \n *
    \n     *   int[] x;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--VARIABLE_DEF -&gt; VARIABLE_DEF\n     * |   |--MODIFIERS -&gt; MODIFIERS\n     * |   |--TYPE -&gt; TYPE\n     * |   |   `--ARRAY_DECLARATOR -&gt; [\n     * |   |       |--LITERAL_INT -&gt; int\n     * |   |       `--RBRACK -&gt; ]\n     * |   |--IDENT -&gt; x\n     * |--SEMI -&gt; ;\n     * 
    \n *\n *

    The array declaration may also represent an inline array\n * definition. In this case, the first child will be either an\n * expression specifying the length of the array or an array\n * initialization block.

    \n *\n * @see Java\n * Language Specification &sect;10\n * @see #TYPE\n * @see #ARRAY_INIT\n **/\n public static final int ARRAY_DECLARATOR =\n GeneratedJavaTokenTypes.ARRAY_DECLARATOR;\n\n /**\n * An extends clause. This appear as part of class and interface\n * definitions. This element appears even if the\n * {@code extends} keyword is not explicitly used. The child\n * is an optional identifier.\n *\n *

    For example:

    \n *\n *
    \n     * extends java.util.LinkedList\n     * 
    \n *\n *

    parses as:

    \n *
    \n     * +--EXTENDS_CLAUSE\n     *     |\n     *     +--DOT (.)\n     *         |\n     *         +--DOT (.)\n     *             |\n     *             +--IDENT (java)\n     *             +--IDENT (util)\n     *         +--IDENT (LinkedList)\n     * 
    \n *\n * @see #IDENT\n * @see #DOT\n * @see #CLASS_DEF\n * @see #INTERFACE_DEF\n * @see FullIdent\n **/\n public static final int EXTENDS_CLAUSE =\n GeneratedJavaTokenTypes.EXTENDS_CLAUSE;\n\n /**\n * An implements clause. This always appears in a class or enum\n * declaration, even if there are no implemented interfaces. The\n * children are a comma separated list of zero or more\n * identifiers.\n *\n *

    For example:

    \n *
    \n     * implements Serializable, Comparable\n     * 
    \n *

    parses as:

    \n *
    \n     * +--IMPLEMENTS_CLAUSE\n     *     |\n     *     +--IDENT (Serializable)\n     *     +--COMMA (,)\n     *     +--IDENT (Comparable)\n     * 
    \n *\n * @see #IDENT\n * @see #DOT\n * @see #COMMA\n * @see #CLASS_DEF\n * @see #ENUM_DEF\n **/\n public static final int IMPLEMENTS_CLAUSE =\n GeneratedJavaTokenTypes.IMPLEMENTS_CLAUSE;\n\n /**\n * A list of parameters to a method or constructor. The children\n * are zero or more parameter declarations separated by commas.\n *\n *

    For example

    \n *
    \n     * int start, int end\n     * 
    \n *

    parses as:

    \n *
    \n     * +--PARAMETERS\n     *     |\n     *     +--PARAMETER_DEF\n     *         |\n     *         +--MODIFIERS\n     *         +--TYPE\n     *             |\n     *             +--LITERAL_INT (int)\n     *         +--IDENT (start)\n     *     +--COMMA (,)\n     *     +--PARAMETER_DEF\n     *         |\n     *         +--MODIFIERS\n     *         +--TYPE\n     *             |\n     *             +--LITERAL_INT (int)\n     *         +--IDENT (end)\n     * 
    \n *\n * @see #PARAMETER_DEF\n * @see #COMMA\n * @see #METHOD_DEF\n * @see #CTOR_DEF\n **/\n public static final int PARAMETERS = GeneratedJavaTokenTypes.PARAMETERS;\n /**\n * A parameter declaration. The last parameter in a list of parameters may\n * be variable length (indicated by the ELLIPSIS child node immediately\n * after the TYPE child).\n *\n * @see #MODIFIERS\n * @see #TYPE\n * @see #IDENT\n * @see #PARAMETERS\n * @see #ELLIPSIS\n **/\n public static final int PARAMETER_DEF =\n GeneratedJavaTokenTypes.PARAMETER_DEF;\n\n /**\n * A labeled statement.\n *\n *

    For example:

    \n *
    \n     * outside: ;\n     * 
    \n *

    parses as:

    \n *
    \n     * +--LABELED_STAT (:)\n     *     |\n     *     +--IDENT (outside)\n     *     +--EMPTY_STAT (;)\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;14.7\n * @see #SLIST\n **/\n public static final int LABELED_STAT =\n GeneratedJavaTokenTypes.LABELED_STAT;\n\n /**\n * A type-cast.\n *\n *

    For example:

    \n *
    \n     * (String)it.next()\n     * 
    \n *

    parses as:

    \n *
    \n     * `--TYPECAST -&gt; (\n     *     |--TYPE -&gt; TYPE\n     *     |   `--IDENT -&gt; String\n     *     |--RPAREN -&gt; )\n     *     `--METHOD_CALL -&gt; (\n     *         |--DOT -&gt; .\n     *         |   |--IDENT -&gt; it\n     *         |   `--IDENT -&gt; next\n     *         |--ELIST -&gt; ELIST\n     *         `--RPAREN -&gt; )\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.16\n * @see #EXPR\n * @see #TYPE\n * @see #TYPE_ARGUMENTS\n * @see #RPAREN\n **/\n public static final int TYPECAST = GeneratedJavaTokenTypes.TYPECAST;\n /**\n * The array index operator.\n *\n *

    For example:

    \n *
    \n     * ar[2] = 5;\n     * 
    \n *

    parses as:

    \n *
    \n     * +--EXPR\n     *     |\n     *     +--ASSIGN (=)\n     *         |\n     *         +--INDEX_OP ([)\n     *             |\n     *             +--IDENT (ar)\n     *             +--EXPR\n     *                 |\n     *                 +--NUM_INT (2)\n     *         +--NUM_INT (5)\n     * +--SEMI (;)\n     * 
    \n *\n * @see #EXPR\n **/\n public static final int INDEX_OP = GeneratedJavaTokenTypes.INDEX_OP;\n /**\n * The {@code ++} (postfix increment) operator.\n *\n *

    For example:

    \n *
    \n     * a++;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--POST_INC -&gt; ++\n     * |       `--IDENT -&gt; a\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.14.1\n * @see #EXPR\n * @see #INC\n **/\n public static final int POST_INC = GeneratedJavaTokenTypes.POST_INC;\n /**\n * The {@code --} (postfix decrement) operator.\n *\n *

    For example:

    \n *
    \n     * a--;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--POST_DEC -&gt; --\n     * |       `--IDENT -&gt; a\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.14.2\n * @see #EXPR\n * @see #DEC\n **/\n public static final int POST_DEC = GeneratedJavaTokenTypes.POST_DEC;\n /**\n * A method call. A method call may have type arguments however these\n * are attached to the appropriate node in the qualified method name.\n *\n *

    For example:

    \n *
    \n     * Integer.parseInt(\"123\");\n     * 
    \n *\n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--METHOD_CALL -&gt; (\n     * |       |--DOT -&gt; .\n     * |       |   |--IDENT -&gt; Integer\n     * |       |   `--IDENT -&gt; parseInt\n     * |       |--ELIST -&gt; ELIST\n     * |       |   `--EXPR -&gt; EXPR\n     * |       |       `--STRING_LITERAL -&gt; \"123\"\n     * |       `--RPAREN -&gt; )\n     * |--SEMI -&gt; ;\n     * 
    \n *\n *\n * @see #IDENT\n * @see #TYPE_ARGUMENTS\n * @see #DOT\n * @see #ELIST\n * @see #RPAREN\n * @see FullIdent\n **/\n public static final int METHOD_CALL = GeneratedJavaTokenTypes.METHOD_CALL;\n\n /**\n * A reference to a method or constructor without arguments. Part of Java 8 syntax.\n * The token should be used for subscribing for double colon literal.\n * {@link #DOUBLE_COLON} token does not appear in the tree.\n *\n *

    For example:

    \n *
    \n     * String::compareToIgnoreCase\n     * 
    \n *\n *

    parses as:\n *

    \n     * +--METHOD_REF (::)\n     *     |\n     *     +--IDENT (String)\n     *     +--IDENT (compareToIgnoreCase)\n     * 
    \n *\n * @see #IDENT\n * @see #DOUBLE_COLON\n */\n public static final int METHOD_REF = GeneratedJavaTokenTypes.METHOD_REF;\n /**\n * An expression. Operators with lower precedence appear at a\n * higher level in the tree than operators with higher precedence.\n * Parentheses are siblings to the operator they enclose.\n *\n *

    For example:

    \n *
    \n     * x = 4 + 3 * 5 + (30 + 26) / 4 + 5 % 4 + (1&lt;&lt;3);\n     * 
    \n *

    parses as:

    \n *
    \n     * +--EXPR\n     *     |\n     *     +--ASSIGN (=)\n     *         |\n     *         +--IDENT (x)\n     *         +--PLUS (+)\n     *             |\n     *             +--PLUS (+)\n     *                 |\n     *                 +--PLUS (+)\n     *                     |\n     *                     +--PLUS (+)\n     *                         |\n     *                         +--NUM_INT (4)\n     *                         +--STAR (*)\n     *                             |\n     *                             +--NUM_INT (3)\n     *                             +--NUM_INT (5)\n     *                     +--DIV (/)\n     *                         |\n     *                         +--LPAREN (()\n     *                         +--PLUS (+)\n     *                             |\n     *                             +--NUM_INT (30)\n     *                             +--NUM_INT (26)\n     *                         +--RPAREN ())\n     *                         +--NUM_INT (4)\n     *                 +--MOD (%)\n     *                     |\n     *                     +--NUM_INT (5)\n     *                     +--NUM_INT (4)\n     *             +--LPAREN (()\n     *             +--SL (&lt;&lt;)\n     *                 |\n     *                 +--NUM_INT (1)\n     *                 +--NUM_INT (3)\n     *             +--RPAREN ())\n     * +--SEMI (;)\n     * 
    \n *\n * @see #ELIST\n * @see #ASSIGN\n * @see #LPAREN\n * @see #RPAREN\n **/\n public static final int EXPR = GeneratedJavaTokenTypes.EXPR;\n /**\n * An array initialization. This may occur as part of an array\n * declaration or inline with {@code new}.\n *\n *

    For example:

    \n *
    \n     *   int[] y =\n     *     {\n     *       1,\n     *       2,\n     *     };\n     * 
    \n *

    parses as:

    \n *
    \n     * |--VARIABLE_DEF -&gt; VARIABLE_DEF\n     * |   |--MODIFIERS -&gt; MODIFIERS\n     * |   |--TYPE -&gt; TYPE\n     * |   |   `--ARRAY_DECLARATOR -&gt; [\n     * |   |       |--LITERAL_INT -&gt; int\n     * |   |       `--RBRACK -&gt; ]\n     * |   |--IDENT -&gt; y\n     * |   `--ASSIGN -&gt; =\n     * |       `--ARRAY_INIT -&gt; {\n     * |           |--EXPR -&gt; EXPR\n     * |           |   `--NUM_INT -&gt; 1\n     * |           |--COMMA -&gt; ,\n     * |           |--EXPR -&gt; EXPR\n     * |           |   `--NUM_INT -&gt; 2\n     * |           |--COMMA -&gt; ,\n     * |           `--RCURLY -&gt; }\n     * |--SEMI -&gt; ;\n     * 
    \n *\n *

    Also consider:

    \n *
    \n     *   int[] z = new int[]\n     *     {\n     *       1,\n     *       2,\n     *     };\n     * 
    \n *

    which parses as:

    \n *
    \n     * |--VARIABLE_DEF -&gt; VARIABLE_DEF\n     * |   |--MODIFIERS -&gt; MODIFIERS\n     * |   |--TYPE -&gt; TYPE\n     * |   |   `--ARRAY_DECLARATOR -&gt; [\n     * |   |       |--LITERAL_INT -&gt; int\n     * |   |       `--RBRACK -&gt; ]\n     * |   |--IDENT -&gt; z\n     * |   `--ASSIGN -&gt; =\n     * |       `--EXPR -&gt; EXPR\n     * |           `--LITERAL_NEW -&gt; new\n     * |               |--LITERAL_INT -&gt; int\n     * |               |--ARRAY_DECLARATOR -&gt; [\n     * |               |   `--RBRACK -&gt; ]\n     * |               `--ARRAY_INIT -&gt; {\n     * |                   |--EXPR -&gt; EXPR\n     * |                   |   `--NUM_INT -&gt; 1\n     * |                   |--COMMA -&gt; ,\n     * |                   |--EXPR -&gt; EXPR\n     * |                   |   `--NUM_INT -&gt; 2\n     * |                   |--COMMA -&gt; ,\n     * |                   `--RCURLY -&gt; }\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see #ARRAY_DECLARATOR\n * @see #TYPE\n * @see #LITERAL_NEW\n * @see #COMMA\n **/\n public static final int ARRAY_INIT = GeneratedJavaTokenTypes.ARRAY_INIT;\n /**\n * An import declaration. Import declarations are option, but\n * must appear after the package declaration and before the first type\n * declaration.\n *\n *

    For example:

    \n *\n *
    \n     *   import java.io.IOException;\n     * 
    \n *\n *

    parses as:

    \n *\n *
    \n     * IMPORT -&gt; import\n     * |--DOT -&gt; .\n     * |   |--DOT -&gt; .\n     * |   |   |--IDENT -&gt; java\n     * |   |   `--IDENT -&gt; io\n     * |   `--IDENT -&gt; IOException\n     * `--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification &sect;7.5\n * @see #DOT\n * @see #IDENT\n * @see #STAR\n * @see #SEMI\n * @see FullIdent\n **/\n public static final int IMPORT = GeneratedJavaTokenTypes.IMPORT;\n /**\n * The {@code -} (unary minus) operator.\n *\n * @see Java\n * Language Specification, &sect;15.15.4\n * @see #EXPR\n **/\n public static final int UNARY_MINUS = GeneratedJavaTokenTypes.UNARY_MINUS;\n /**\n * The {@code +} (unary plus) operator.\n *

    For example:

    \n *
    \n     * a = + b;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--ASSIGN -&gt; =\n     * |       |--IDENT -&gt; a\n     * |       `--UNARY_PLUS -&gt; +\n     * |           `--IDENT -&gt; b\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.15.3\n * @see #EXPR\n **/\n public static final int UNARY_PLUS = GeneratedJavaTokenTypes.UNARY_PLUS;\n /**\n * A group of case clauses. Case clauses with no associated\n * statements are grouped together into a case group. The last\n * child is a statement list containing the statements to execute\n * upon a match.\n *\n *

    For example:

    \n *
    \n     * case 0:\n     * case 1:\n     * case 2:\n     *   x = 3;\n     *   break;\n     * 
    \n *

    parses as:

    \n *
    \n     * +--CASE_GROUP\n     *     |\n     *     +--LITERAL_CASE (case)\n     *         |\n     *         +--EXPR\n     *             |\n     *             +--NUM_INT (0)\n     *     +--LITERAL_CASE (case)\n     *         |\n     *         +--EXPR\n     *             |\n     *             +--NUM_INT (1)\n     *     +--LITERAL_CASE (case)\n     *         |\n     *         +--EXPR\n     *             |\n     *             +--NUM_INT (2)\n     *     +--SLIST\n     *         |\n     *         +--EXPR\n     *             |\n     *             +--ASSIGN (=)\n     *                 |\n     *                 +--IDENT (x)\n     *                 +--NUM_INT (3)\n     *         +--SEMI (;)\n     *         +--LITERAL_BREAK (break)\n     *             |\n     *             +--SEMI (;)\n     * 
    \n *\n * @see #LITERAL_CASE\n * @see #LITERAL_DEFAULT\n * @see #LITERAL_SWITCH\n * @see #LITERAL_YIELD\n **/\n public static final int CASE_GROUP = GeneratedJavaTokenTypes.CASE_GROUP;\n /**\n * An expression list. The children are a comma separated list of\n * expressions.\n *\n * @see #LITERAL_NEW\n * @see #FOR_INIT\n * @see #FOR_ITERATOR\n * @see #EXPR\n * @see #METHOD_CALL\n * @see #CTOR_CALL\n * @see #SUPER_CTOR_CALL\n **/\n public static final int ELIST = GeneratedJavaTokenTypes.ELIST;\n /**\n * A for loop initializer. This is a child of\n * {@code LITERAL_FOR}. The children of this element may be\n * a comma separated list of variable declarations, an expression\n * list, or empty.\n *\n * @see #VARIABLE_DEF\n * @see #ELIST\n * @see #LITERAL_FOR\n **/\n public static final int FOR_INIT = GeneratedJavaTokenTypes.FOR_INIT;\n /**\n * A for loop condition. This is a child of\n * {@code LITERAL_FOR}. The child of this element is an\n * optional expression.\n *\n * @see #EXPR\n * @see #LITERAL_FOR\n **/\n public static final int FOR_CONDITION =\n GeneratedJavaTokenTypes.FOR_CONDITION;\n\n /**\n * A for loop iterator. This is a child of\n * {@code LITERAL_FOR}. The child of this element is an\n * optional expression list.\n *\n * @see #ELIST\n * @see #LITERAL_FOR\n **/\n public static final int FOR_ITERATOR =\n GeneratedJavaTokenTypes.FOR_ITERATOR;\n\n /**\n * The empty statement. This goes in place of an\n * {@code SLIST} for a {@code for} or {@code while}\n * loop body.\n *\n * @see Java\n * Language Specification, &sect;14.6\n * @see #LITERAL_FOR\n * @see #LITERAL_WHILE\n **/\n public static final int EMPTY_STAT = GeneratedJavaTokenTypes.EMPTY_STAT;\n /**\n * The {@code final} keyword.\n *\n * @see #MODIFIERS\n **/\n public static final int FINAL = GeneratedJavaTokenTypes.FINAL;\n /**\n * The {@code abstract} keyword.\n *\n *

    For example:

    \n *
    \n     *  public abstract class MyClass\n     *  {\n     *  }\n     * 
    \n *

    parses as:

    \n *
    \n     * --CLASS_DEF\n     *    |--MODIFIERS\n     *    |   |--LITERAL_PUBLIC (public)\n     *    |   `--ABSTRACT (abstract)\n     *    |--LITERAL_CLASS (class)\n     *    |--IDENT (MyClass)\n     *    `--OBJBLOCK\n     *        |--LCURLY ({)\n     *        `--RCURLY (})\n     * 
    \n *\n * @see #MODIFIERS\n **/\n public static final int ABSTRACT = GeneratedJavaTokenTypes.ABSTRACT;\n /**\n * The {@code strictfp} keyword.\n *\n *

    For example:

    \n *
    public strictfp class Test {}
    \n *\n *

    parses as:

    \n *
    \n     * CLASS_DEF -&gt; CLASS_DEF\n     * |--MODIFIERS -&gt; MODIFIERS\n     * |   |--LITERAL_PUBLIC -&gt; public\n     * |   `--STRICTFP -&gt; strictfp\n     * |--LITERAL_CLASS -&gt; class\n     * |--IDENT -&gt; Test\n     * `--OBJBLOCK -&gt; OBJBLOCK\n     *     |--LCURLY -&gt; {\n     *     `--RCURLY -&gt; }\n     * 
    \n *\n * @see #MODIFIERS\n **/\n public static final int STRICTFP = GeneratedJavaTokenTypes.STRICTFP;\n /**\n * A super constructor call.\n *\n * @see #ELIST\n * @see #RPAREN\n * @see #SEMI\n * @see #CTOR_CALL\n **/\n public static final int SUPER_CTOR_CALL =\n GeneratedJavaTokenTypes.SUPER_CTOR_CALL;\n\n /**\n * A constructor call.\n *\n *

    For example:

    \n *
    \n     * this(1);\n     * 
    \n *

    parses as:

    \n *
    \n     * +--CTOR_CALL (this)\n     *     |\n     *     +--LPAREN (()\n     *     +--ELIST\n     *         |\n     *         +--EXPR\n     *             |\n     *             +--NUM_INT (1)\n     *     +--RPAREN ())\n     *     +--SEMI (;)\n     * 
    \n *\n * @see #ELIST\n * @see #RPAREN\n * @see #SEMI\n * @see #SUPER_CTOR_CALL\n **/\n public static final int CTOR_CALL = GeneratedJavaTokenTypes.CTOR_CALL;\n\n /**\n * The statement terminator ({@code ;}). Depending on the\n * context, this make occur as a sibling, a child, or not at all.\n *\n *

    For example:

    \n *
    \n     * for(;;);\n     * 
    \n *

    parses as:

    \n *
    \n     * LITERAL_FOR -&gt; for\n     *  |--LPAREN -&gt; (\n     *  |--FOR_INIT -&gt; FOR_INIT\n     *  |--SEMI -&gt; ;\n     *  |--FOR_CONDITION -&gt; FOR_CONDITION\n     *  |--SEMI -&gt; ;\n     *  |--FOR_ITERATOR -&gt; FOR_ITERATOR\n     *  |--RPAREN -&gt; )\n     *  `--EMPTY_STAT -&gt; ;\n     * 
    \n *\n * @see #PACKAGE_DEF\n * @see #IMPORT\n * @see #SLIST\n * @see #ARRAY_INIT\n * @see #LITERAL_FOR\n **/\n public static final int SEMI = GeneratedJavaTokenTypes.SEMI;\n\n /**\n * The {@code ]} symbol.\n *\n * @see #INDEX_OP\n * @see #ARRAY_DECLARATOR\n **/\n public static final int RBRACK = GeneratedJavaTokenTypes.RBRACK;\n /**\n * The {@code void} keyword.\n *\n * @see #TYPE\n **/\n public static final int LITERAL_VOID =\n GeneratedJavaTokenTypes.LITERAL_void;\n\n /**\n * The {@code boolean} keyword.\n *\n * @see #TYPE\n **/\n public static final int LITERAL_BOOLEAN =\n GeneratedJavaTokenTypes.LITERAL_boolean;\n\n /**\n * The {@code byte} keyword.\n *\n * @see #TYPE\n **/\n public static final int LITERAL_BYTE =\n GeneratedJavaTokenTypes.LITERAL_byte;\n\n /**\n * The {@code char} keyword.\n *\n * @see #TYPE\n **/\n public static final int LITERAL_CHAR =\n GeneratedJavaTokenTypes.LITERAL_char;\n\n /**\n * The {@code short} keyword.\n *\n * @see #TYPE\n **/\n public static final int LITERAL_SHORT =\n GeneratedJavaTokenTypes.LITERAL_short;\n\n /**\n * The {@code int} keyword.\n *\n * @see #TYPE\n **/\n public static final int LITERAL_INT = GeneratedJavaTokenTypes.LITERAL_int;\n /**\n * The {@code float} keyword.\n *\n * @see #TYPE\n **/\n public static final int LITERAL_FLOAT =\n GeneratedJavaTokenTypes.LITERAL_float;\n\n /**\n * The {@code long} keyword.\n *\n * @see #TYPE\n **/\n public static final int LITERAL_LONG =\n GeneratedJavaTokenTypes.LITERAL_long;\n\n /**\n * The {@code double} keyword.\n *\n * @see #TYPE\n **/\n public static final int LITERAL_DOUBLE =\n GeneratedJavaTokenTypes.LITERAL_double;\n\n /**\n * An identifier. These can be names of types, subpackages,\n * fields, methods, parameters, and local variables.\n **/\n public static final int IDENT = GeneratedJavaTokenTypes.IDENT;\n /**\n * The &#46; (dot) operator.\n *\n *

    For example:

    \n *
    \n     * return person.name;\n     * 
    \n *

    parses as:

    \n *
    \n     * --LITERAL_RETURN -&gt; return\n     *    |--EXPR -&gt; EXPR\n     *    |   `--DOT -&gt; .\n     *    |       |--IDENT -&gt; person\n     *    |       `--IDENT -&gt; name\n     *    `--SEMI -&gt; ;\n     * 
    \n *\n * @see FullIdent\n * @noinspection HtmlTagCanBeJavadocTag\n **/\n public static final int DOT = GeneratedJavaTokenTypes.DOT;\n /**\n * The {@code *} (multiplication or wildcard) operator.\n *\n *

    For example:

    \n *
    \n     * f = m * a;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--ASSIGN -&gt; =\n     * |       |--IDENT -&gt; f\n     * |       `--STAR -&gt; *\n     * |           |--IDENT -&gt; m\n     * |           `--IDENT -&gt; a\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;7.5.2\n * @see Java\n * Language Specification, &sect;15.17.1\n * @see #EXPR\n * @see #IMPORT\n **/\n public static final int STAR = GeneratedJavaTokenTypes.STAR;\n /**\n * The {@code private} keyword.\n *\n * @see #MODIFIERS\n **/\n public static final int LITERAL_PRIVATE =\n GeneratedJavaTokenTypes.LITERAL_private;\n\n /**\n * The {@code public} keyword.\n *\n * @see #MODIFIERS\n **/\n public static final int LITERAL_PUBLIC =\n GeneratedJavaTokenTypes.LITERAL_public;\n\n /**\n * The {@code protected} keyword.\n *\n * @see #MODIFIERS\n **/\n public static final int LITERAL_PROTECTED =\n GeneratedJavaTokenTypes.LITERAL_protected;\n\n /**\n * The {@code static} keyword.\n *\n * @see #MODIFIERS\n **/\n public static final int LITERAL_STATIC =\n GeneratedJavaTokenTypes.LITERAL_static;\n\n /**\n * The {@code transient} keyword.\n *\n * @see #MODIFIERS\n **/\n public static final int LITERAL_TRANSIENT =\n GeneratedJavaTokenTypes.LITERAL_transient;\n\n /**\n * The {@code native} keyword.\n *\n * @see #MODIFIERS\n **/\n public static final int LITERAL_NATIVE =\n GeneratedJavaTokenTypes.LITERAL_native;\n\n /**\n * The {@code synchronized} keyword. This may be used as a\n * modifier of a method or in the definition of a synchronized\n * block.\n *\n *

    For example:

    \n *\n *
    \n     * synchronized(this)\n     * {\n     *   x++;\n     * }\n     * 
    \n *\n *

    parses as:

    \n *\n *
    \n     * |--LITERAL_SYNCHRONIZED -&gt; synchronized\n     * |   |--LPAREN -&gt; (\n     * |   |--EXPR -&gt; EXPR\n     * |   |   `--LITERAL_THIS -&gt; this\n     * |   |--RPAREN -&gt; )\n     * |   `--SLIST -&gt; {\n     * |       |--EXPR -&gt; EXPR\n     * |       |   `--POST_INC -&gt; ++\n     * |       |       `--IDENT -&gt; x\n     * |       |--SEMI -&gt; ;\n     * |       `--RCURLY -&gt; }\n     * `--RCURLY -&gt; }\n     * 
    \n *\n * @see #MODIFIERS\n * @see #LPAREN\n * @see #EXPR\n * @see #RPAREN\n * @see #SLIST\n * @see #RCURLY\n **/\n public static final int LITERAL_SYNCHRONIZED =\n GeneratedJavaTokenTypes.LITERAL_synchronized;\n\n /**\n * The {@code volatile} keyword.\n *\n * @see #MODIFIERS\n **/\n public static final int LITERAL_VOLATILE =\n GeneratedJavaTokenTypes.LITERAL_volatile;\n\n /**\n * The {@code class} keyword. This element appears both\n * as part of a class declaration, and inline to reference a\n * class object.\n *\n *

    For example:

    \n *\n *
    \n     * int.class\n     * 
    \n *

    parses as:

    \n *
    \n     * +--EXPR\n     *     |\n     *     +--DOT (.)\n     *         |\n     *         +--LITERAL_INT (int)\n     *         +--LITERAL_CLASS (class)\n     * 
    \n *\n * @see #DOT\n * @see #IDENT\n * @see #CLASS_DEF\n * @see FullIdent\n **/\n public static final int LITERAL_CLASS =\n GeneratedJavaTokenTypes.LITERAL_class;\n\n /**\n * The {@code interface} keyword. This token appears in\n * interface definition.\n *\n * @see #INTERFACE_DEF\n **/\n public static final int LITERAL_INTERFACE =\n GeneratedJavaTokenTypes.LITERAL_interface;\n\n /**\n * A left curly brace ({).\n *\n * @see #OBJBLOCK\n * @see #ARRAY_INIT\n * @see #SLIST\n **/\n public static final int LCURLY = GeneratedJavaTokenTypes.LCURLY;\n /**\n * A right curly brace (}).\n *\n * @see #OBJBLOCK\n * @see #ARRAY_INIT\n * @see #SLIST\n **/\n public static final int RCURLY = GeneratedJavaTokenTypes.RCURLY;\n /**\n * The {@code ,} (comma) operator.\n *\n * @see #ARRAY_INIT\n * @see #FOR_INIT\n * @see #FOR_ITERATOR\n * @see #LITERAL_THROWS\n * @see #IMPLEMENTS_CLAUSE\n **/\n public static final int COMMA = GeneratedJavaTokenTypes.COMMA;\n\n /**\n * A left parenthesis ({@code (}).\n *\n * @see #LITERAL_FOR\n * @see #LITERAL_NEW\n * @see #EXPR\n * @see #LITERAL_SWITCH\n * @see #LITERAL_CATCH\n **/\n public static final int LPAREN = GeneratedJavaTokenTypes.LPAREN;\n /**\n * A right parenthesis ({@code )}).\n *\n * @see #LITERAL_FOR\n * @see #LITERAL_NEW\n * @see #METHOD_CALL\n * @see #TYPECAST\n * @see #EXPR\n * @see #LITERAL_SWITCH\n * @see #LITERAL_CATCH\n **/\n public static final int RPAREN = GeneratedJavaTokenTypes.RPAREN;\n /**\n * The {@code this} keyword.\n *\n * @see #EXPR\n * @see #CTOR_CALL\n **/\n public static final int LITERAL_THIS =\n GeneratedJavaTokenTypes.LITERAL_this;\n\n /**\n * The {@code super} keyword.\n *\n * @see #EXPR\n * @see #SUPER_CTOR_CALL\n **/\n public static final int LITERAL_SUPER =\n GeneratedJavaTokenTypes.LITERAL_super;\n\n /**\n * The {@code =} (assignment) operator.\n *\n *

    For example:

    \n *
    \n     * a = b;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--ASSIGN -&gt; =\n     * |       |--IDENT -&gt; a\n     * |       `--IDENT -&gt; b\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.26.1\n * @see #EXPR\n **/\n public static final int ASSIGN = GeneratedJavaTokenTypes.ASSIGN;\n /**\n * The {@code throws} keyword. The children are a number of\n * one or more identifiers separated by commas.\n *\n * @see Java\n * Language Specification, &sect;8.4.4\n * @see #IDENT\n * @see #DOT\n * @see #COMMA\n * @see #METHOD_DEF\n * @see #CTOR_DEF\n * @see FullIdent\n **/\n public static final int LITERAL_THROWS =\n GeneratedJavaTokenTypes.LITERAL_throws;\n\n /**\n * The {@code :} (colon) operator. This will appear as part\n * of the conditional operator ({@code ? :}).\n *\n * @see #QUESTION\n * @see #LABELED_STAT\n * @see #CASE_GROUP\n **/\n public static final int COLON = GeneratedJavaTokenTypes.COLON;\n\n /**\n * The {@code ::} (double colon) separator.\n * It is part of Java 8 syntax that is used for method reference.\n * The token does not appear in tree, {@link #METHOD_REF} should be used instead.\n *\n * @see #METHOD_REF\n */\n public static final int DOUBLE_COLON = GeneratedJavaTokenTypes.DOUBLE_COLON;\n /**\n * The {@code if} keyword.\n *\n *

    For example:

    \n *
    \n     * if (optimistic)\n     * {\n     *   message = \"half full\";\n     * }\n     * else\n     * {\n     *   message = \"half empty\";\n     * }\n     * 
    \n *

    parses as:

    \n *
    \n     * LITERAL_IF -&gt; if\n     *  |--LPAREN -&gt; (\n     *  |--EXPR -&gt; EXPR\n     *  |   `--IDENT -&gt; optimistic\n     *  |--RPAREN -&gt; )\n     *  |--SLIST -&gt; {\n     *  |   |--EXPR -&gt; EXPR\n     *  |   |   `--ASSIGN -&gt; =\n     *  |   |       |--IDENT -&gt; message\n     *  |   |       `--STRING_LITERAL -&gt; \"half full\"\n     *  |   |--SEMI -&gt; ;\n     *  |   `--RCURLY -&gt; }\n     *  `--LITERAL_ELSE -&gt; else\n     *      `--SLIST -&gt; {\n     *          |--EXPR -&gt; EXPR\n     *          |   `--ASSIGN -&gt; =\n     *          |       |--IDENT -&gt; message\n     *          |       `--STRING_LITERAL -&gt; \"half empty\"\n     *          |--SEMI -&gt; ;\n     *          `--RCURLY -&gt; }\n     * 
    \n *\n * @see #LPAREN\n * @see #EXPR\n * @see #RPAREN\n * @see #SLIST\n * @see #EMPTY_STAT\n * @see #LITERAL_ELSE\n **/\n public static final int LITERAL_IF = GeneratedJavaTokenTypes.LITERAL_if;\n /**\n * The {@code for} keyword. The children are {@code (},\n * an initializer, a condition, an iterator, a {@code )} and\n * either a statement list, a single expression, or an empty\n * statement.\n *\n *

    For example:

    \n *
    \n     * for(int i = 0, n = myArray.length; i &lt; n; i++)\n     * {\n     * }\n     * 
    \n *\n *

    parses as:

    \n *
    \n     * +--LITERAL_FOR (for)\n     *     |\n     *     +--LPAREN (()\n     *     +--FOR_INIT\n     *         |\n     *         +--VARIABLE_DEF\n     *             |\n     *             +--MODIFIERS\n     *             +--TYPE\n     *                 |\n     *                 +--LITERAL_INT (int)\n     *             +--IDENT (i)\n     *             +--ASSIGN (=)\n     *                 |\n     *                 +--EXPR\n     *                     |\n     *                     +--NUM_INT (0)\n     *         +--COMMA (,)\n     *         +--VARIABLE_DEF\n     *             |\n     *             +--MODIFIERS\n     *             +--TYPE\n     *                 |\n     *                 +--LITERAL_INT (int)\n     *             +--IDENT (n)\n     *             +--ASSIGN (=)\n     *                 |\n     *                 +--EXPR\n     *                     |\n     *                     +--DOT (.)\n     *                         |\n     *                         +--IDENT (myArray)\n     *                         +--IDENT (length)\n     *     +--SEMI (;)\n     *     +--FOR_CONDITION\n     *         |\n     *         +--EXPR\n     *             |\n     *             +--LT (&lt;)\n     *                 |\n     *                 +--IDENT (i)\n     *                 +--IDENT (n)\n     *     +--SEMI (;)\n     *     +--FOR_ITERATOR\n     *         |\n     *         +--ELIST\n     *             |\n     *             +--EXPR\n     *                 |\n     *                 +--POST_INC (++)\n     *                     |\n     *                     +--IDENT (i)\n     *     +--RPAREN ())\n     *     +--SLIST ({)\n     *         |\n     *         +--RCURLY (})\n     * 
    \n *\n * @see #LPAREN\n * @see #FOR_INIT\n * @see #SEMI\n * @see #FOR_CONDITION\n * @see #FOR_ITERATOR\n * @see #RPAREN\n * @see #SLIST\n * @see #EMPTY_STAT\n * @see #EXPR\n **/\n public static final int LITERAL_FOR = GeneratedJavaTokenTypes.LITERAL_for;\n /**\n * The {@code while} keyword.\n *\n *

    For example:

    \n *
    \n     * while(line != null)\n     * {\n     *   process(line);\n     *   line = in.readLine();\n     * }\n     * 
    \n *

    parses as:

    \n *
    \n     * +--LITERAL_WHILE (while)\n     *     |\n     *     +--LPAREN (()\n     *     +--EXPR\n     *         |\n     *         +--NOT_EQUAL (!=)\n     *             |\n     *             +--IDENT (line)\n     *             +--LITERAL_NULL (null)\n     *     +--RPAREN ())\n     *     +--SLIST ({)\n     *         |\n     *         +--EXPR\n     *             |\n     *             +--METHOD_CALL (()\n     *                 |\n     *                 +--IDENT (process)\n     *                 +--ELIST\n     *                     |\n     *                     +--EXPR\n     *                         |\n     *                         +--IDENT (line)\n     *                 +--RPAREN ())\n     *         +--SEMI (;)\n     *         +--EXPR\n     *             |\n     *             +--ASSIGN (=)\n     *                 |\n     *                 +--IDENT (line)\n     *                 +--METHOD_CALL (()\n     *                     |\n     *                     +--DOT (.)\n     *                         |\n     *                         +--IDENT (in)\n     *                         +--IDENT (readLine)\n     *                     +--ELIST\n     *                     +--RPAREN ())\n     *         +--SEMI (;)\n     *         +--RCURLY (})\n     * 
    \n **/\n public static final int LITERAL_WHILE =\n GeneratedJavaTokenTypes.LITERAL_while;\n\n /**\n * The {@code do} keyword. Note the the while token does not\n * appear as part of the do-while construct.\n *\n *

    For example:

    \n *
    \n     * do\n     * {\n     *   x = rand.nextInt(10);\n     * }\n     * while(x &lt; 5);\n     * 
    \n *

    parses as:

    \n *
    \n     * +--LITERAL_DO (do)\n     *     |\n     *     +--SLIST ({)\n     *         |\n     *         +--EXPR\n     *             |\n     *             +--ASSIGN (=)\n     *                 |\n     *                 +--IDENT (x)\n     *                 +--METHOD_CALL (()\n     *                     |\n     *                     +--DOT (.)\n     *                         |\n     *                         +--IDENT (rand)\n     *                         +--IDENT (nextInt)\n     *                     +--ELIST\n     *                         |\n     *                         +--EXPR\n     *                             |\n     *                             +--NUM_INT (10)\n     *                     +--RPAREN ())\n     *         +--SEMI (;)\n     *         +--RCURLY (})\n     *     +--DO_WHILE (while)\n     *     +--LPAREN (()\n     *     +--EXPR\n     *         |\n     *         +--LT (&lt;)\n     *             |\n     *             +--IDENT (x)\n     *             +--NUM_INT (5)\n     *     +--RPAREN ())\n     *     +--SEMI (;)\n     * 
    \n *\n * @see #SLIST\n * @see #EXPR\n * @see #EMPTY_STAT\n * @see #LPAREN\n * @see #RPAREN\n * @see #SEMI\n **/\n public static final int LITERAL_DO = GeneratedJavaTokenTypes.LITERAL_do;\n /**\n * Literal {@code while} in do-while loop.\n *\n *

    For example:

    \n *
    \n     * do {\n     *\n     * } while (a &gt; 0);\n     * 
    \n *

    parses as:

    \n *
    \n     * --LITERAL_DO -&gt; do\n     *    |--SLIST -&gt; {\n     *    |   `--RCURLY -&gt; }\n     *    |--DO_WHILE -&gt; while\n     *    |--LPAREN -&gt; (\n     *    |--EXPR -&gt; EXPR\n     *    |   `--GT -&gt; &gt;\n     *    |       |--IDENT -&gt; a\n     *    |       `--NUM_INT -&gt; 0\n     *    |--RPAREN -&gt; )\n     *    `--SEMI -&gt; ;\n     * 
    \n *\n * @see #LITERAL_DO\n */\n public static final int DO_WHILE = GeneratedJavaTokenTypes.DO_WHILE;\n /**\n * The {@code break} keyword. The first child is an optional\n * identifier and the last child is a semicolon.\n *\n * @see #IDENT\n * @see #SEMI\n * @see #SLIST\n **/\n public static final int LITERAL_BREAK =\n GeneratedJavaTokenTypes.LITERAL_break;\n\n /**\n * The {@code continue} keyword. The first child is an\n * optional identifier and the last child is a semicolon.\n *\n * @see #IDENT\n * @see #SEMI\n * @see #SLIST\n **/\n public static final int LITERAL_CONTINUE =\n GeneratedJavaTokenTypes.LITERAL_continue;\n\n /**\n * The {@code return} keyword. The first child is an\n * optional expression for the return value. The last child is a\n * semi colon.\n *\n * @see #EXPR\n * @see #SEMI\n * @see #SLIST\n **/\n public static final int LITERAL_RETURN =\n GeneratedJavaTokenTypes.LITERAL_return;\n\n /**\n * The {@code switch} keyword.\n *\n *

    For example:

    \n *
    \n     * switch(type)\n     * {\n     *   case 0:\n     *     background = Color.blue;\n     *     break;\n     *   case 1:\n     *     background = Color.red;\n     *     break;\n     *   default:\n     *     background = Color.green;\n     *     break;\n     * }\n     * 
    \n *

    parses as:

    \n *
    \n     * +--LITERAL_SWITCH (switch)\n     *     |\n     *     +--LPAREN (()\n     *     +--EXPR\n     *         |\n     *         +--IDENT (type)\n     *     +--RPAREN ())\n     *     +--LCURLY ({)\n     *     +--CASE_GROUP\n     *         |\n     *         +--LITERAL_CASE (case)\n     *             |\n     *             +--EXPR\n     *                 |\n     *                 +--NUM_INT (0)\n     *         +--SLIST\n     *             |\n     *             +--EXPR\n     *                 |\n     *                 +--ASSIGN (=)\n     *                     |\n     *                     +--IDENT (background)\n     *                     +--DOT (.)\n     *                         |\n     *                         +--IDENT (Color)\n     *                         +--IDENT (blue)\n     *             +--SEMI (;)\n     *             +--LITERAL_BREAK (break)\n     *                 |\n     *                 +--SEMI (;)\n     *     +--CASE_GROUP\n     *         |\n     *         +--LITERAL_CASE (case)\n     *             |\n     *             +--EXPR\n     *                 |\n     *                 +--NUM_INT (1)\n     *         +--SLIST\n     *             |\n     *             +--EXPR\n     *                 |\n     *                 +--ASSIGN (=)\n     *                     |\n     *                     +--IDENT (background)\n     *                     +--DOT (.)\n     *                         |\n     *                         +--IDENT (Color)\n     *                         +--IDENT (red)\n     *             +--SEMI (;)\n     *             +--LITERAL_BREAK (break)\n     *                 |\n     *                 +--SEMI (;)\n     *     +--CASE_GROUP\n     *         |\n     *         +--LITERAL_DEFAULT (default)\n     *         +--SLIST\n     *             |\n     *             +--EXPR\n     *                 |\n     *                 +--ASSIGN (=)\n     *                     |\n     *                     +--IDENT (background)\n     *                     +--DOT (.)\n     *                         |\n     *                         +--IDENT (Color)\n     *                         +--IDENT (green)\n     *             +--SEMI (;)\n     *             +--LITERAL_BREAK (break)\n     *                 |\n     *                 +--SEMI (;)\n     *     +--RCURLY (})\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;14.10\n * @see #LPAREN\n * @see #EXPR\n * @see #RPAREN\n * @see #LCURLY\n * @see #CASE_GROUP\n * @see #RCURLY\n * @see #SLIST\n * @see #SWITCH_RULE\n **/\n public static final int LITERAL_SWITCH =\n GeneratedJavaTokenTypes.LITERAL_switch;\n\n /**\n * The {@code throw} keyword. The first child is an\n * expression that evaluates to a {@code Throwable} instance.\n *\n * @see Java\n * Language Specification, &sect;14.17\n * @see #SLIST\n * @see #EXPR\n **/\n public static final int LITERAL_THROW =\n GeneratedJavaTokenTypes.LITERAL_throw;\n\n /**\n * The {@code else} keyword. This appears as a child of an\n * {@code if} statement.\n *\n * @see #SLIST\n * @see #EXPR\n * @see #EMPTY_STAT\n * @see #LITERAL_IF\n **/\n public static final int LITERAL_ELSE =\n GeneratedJavaTokenTypes.LITERAL_else;\n\n /**\n * The {@code case} keyword. The first child is a constant\n * expression that evaluates to an integer.\n *\n * @see #CASE_GROUP\n * @see #EXPR\n **/\n public static final int LITERAL_CASE =\n GeneratedJavaTokenTypes.LITERAL_case;\n\n /**\n * The {@code default} keyword. This element has no\n * children.\n *\n * @see #CASE_GROUP\n * @see #MODIFIERS\n * @see #SWITCH_RULE\n **/\n public static final int LITERAL_DEFAULT =\n GeneratedJavaTokenTypes.LITERAL_default;\n\n /**\n * The {@code try} keyword. The children are a statement\n * list, zero or more catch blocks and then an optional finally\n * block.\n *\n *

    For example:

    \n *
    \n     * try\n     * {\n     *   FileReader in = new FileReader(\"abc.txt\");\n     * }\n     * catch(IOException ioe)\n     * {\n     * }\n     * finally\n     * {\n     * }\n     * 
    \n *

    parses as:

    \n *
    \n     * +--LITERAL_TRY (try)\n     *     |\n     *     +--SLIST ({)\n     *         |\n     *         +--VARIABLE_DEF\n     *             |\n     *             +--MODIFIERS\n     *             +--TYPE\n     *                 |\n     *                 +--IDENT (FileReader)\n     *             +--IDENT (in)\n     *             +--ASSIGN (=)\n     *                 |\n     *                 +--EXPR\n     *                     |\n     *                     +--LITERAL_NEW (new)\n     *                         |\n     *                         +--IDENT (FileReader)\n     *                         +--LPAREN (()\n     *                         +--ELIST\n     *                             |\n     *                             +--EXPR\n     *                                 |\n     *                                 +--STRING_LITERAL (\"abc.txt\")\n     *                         +--RPAREN ())\n     *         +--SEMI (;)\n     *         +--RCURLY (})\n     *     +--LITERAL_CATCH (catch)\n     *         |\n     *         +--LPAREN (()\n     *         +--PARAMETER_DEF\n     *             |\n     *             +--MODIFIERS\n     *             +--TYPE\n     *                 |\n     *                 +--IDENT (IOException)\n     *             +--IDENT (ioe)\n     *         +--RPAREN ())\n     *         +--SLIST ({)\n     *             |\n     *             +--RCURLY (})\n     *     +--LITERAL_FINALLY (finally)\n     *         |\n     *         +--SLIST ({)\n     *             |\n     *             +--RCURLY (})\n     * +--RCURLY (})\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;14.19\n * @see #SLIST\n * @see #LITERAL_CATCH\n * @see #LITERAL_FINALLY\n **/\n public static final int LITERAL_TRY = GeneratedJavaTokenTypes.LITERAL_try;\n\n /**\n * The Java 7 try-with-resources construct.\n *\n *

    For example:

    \n *
    \n     * try (Foo foo = new Foo(); Bar bar = new Bar()) { }\n     * 
    \n *

    parses as:

    \n *
    \n     * +--LITERAL_TRY (try)\n     *     |\n     *     +--RESOURCE_SPECIFICATION\n     *         |\n     *         +--LPAREN (()\n     *         +--RESOURCES\n     *             |\n     *             +--RESOURCE\n     *                 |\n     *                 +--MODIFIERS\n     *                 +--TYPE\n     *                     |\n     *                     +--IDENT (Foo)\n     *                 +--IDENT (foo)\n     *                 +--ASSIGN (=)\n     *                 +--EXPR\n     *                    |\n     *                    +--LITERAL_NEW (new)\n     *                       |\n     *                       +--IDENT (Foo)\n     *                       +--LPAREN (()\n     *                       +--ELIST\n     *                       +--RPAREN ())\n     *             +--SEMI (;)\n     *             +--RESOURCE\n     *                 |\n     *                 +--MODIFIERS\n     *                 +--TYPE\n     *                     |\n     *                     +--IDENT (Bar)\n     *                 +--IDENT (bar)\n     *                 +--ASSIGN (=)\n     *                 +--EXPR\n     *                    |\n     *                    +--LITERAL_NEW (new)\n     *                       |\n     *                       +--IDENT (Bar)\n     *                       +--LPAREN (()\n     *                       +--ELIST\n     *                       +--RPAREN ())\n     *         +--RPAREN ())\n     *     +--SLIST ({)\n     *         +--RCURLY (})\n     * 
    \n *\n *

    Also consider:

    \n *
    \n     * try (BufferedReader br = new BufferedReader(new FileReader(path)))\n     * {\n     *  return br.readLine();\n     * }\n     * 
    \n *

    which parses as:

    \n *
    \n     * +--LITERAL_TRY (try)\n     *     |\n     *     +--RESOURCE_SPECIFICATION\n     *         |\n     *         +--LPAREN (()\n     *         +--RESOURCES\n     *             |\n     *             +--RESOURCE\n     *                 |\n     *                 +--MODIFIERS\n     *                 +--TYPE\n     *                     |\n     *                     +--IDENT (BufferedReader)\n     *                 +--IDENT (br)\n     *                 +--ASSIGN (=)\n     *                 +--EXPR\n     *                     |\n     *                     +--LITERAL_NEW (new)\n     *                         |\n     *                         +--IDENT (FileReader)\n     *                         +--LPAREN (()\n     *                         +--ELIST\n     *                             |\n     *                             +--EXPR\n     *                                 |\n     *                                 +--LITERAL_NEW (new)\n     *                                     |\n     *                                     +--IDENT (BufferedReader)\n     *                                     +--LPAREN (()\n     *                                     +--ELIST\n     *                                         |\n     *                                         +--EXPR\n     *                                             |\n     *                                             +--IDENT (path)\n     *                                     +--RPAREN ())\n     *                         +--RPAREN ())\n     *         +--RPAREN ())\n     *     +--SLIST ({)\n     *         |\n     *         +--LITERAL_RETURN (return)\n     *             |\n     *             +--EXPR\n     *                 |\n     *                 +--METHOD_CALL (()\n     *                     |\n     *                     +--DOT (.)\n     *                         |\n     *                         +--IDENT (br)\n     *                         +--IDENT (readLine)\n     *                     +--ELIST\n     *                     +--RPAREN ())\n     *             +--SEMI (;)\n     *         +--RCURLY (})\n     * 
    \n *\n * @see #LPAREN\n * @see #RESOURCES\n * @see #RESOURCE\n * @see #SEMI\n * @see #RPAREN\n * @see #LITERAL_TRY\n **/\n public static final int RESOURCE_SPECIFICATION =\n GeneratedJavaTokenTypes.RESOURCE_SPECIFICATION;\n\n /**\n * A list of resources in the Java 7 try-with-resources construct.\n * This is a child of RESOURCE_SPECIFICATION.\n *\n * @see #RESOURCE_SPECIFICATION\n **/\n public static final int RESOURCES =\n GeneratedJavaTokenTypes.RESOURCES;\n\n /**\n * A resource in the Java 7 try-with-resources construct.\n * This is a child of RESOURCES.\n *\n * @see #RESOURCES\n * @see #RESOURCE_SPECIFICATION\n **/\n public static final int RESOURCE =\n GeneratedJavaTokenTypes.RESOURCE;\n\n /**\n * The {@code catch} keyword.\n *\n * @see #LPAREN\n * @see #PARAMETER_DEF\n * @see #RPAREN\n * @see #SLIST\n * @see #LITERAL_TRY\n **/\n public static final int LITERAL_CATCH =\n GeneratedJavaTokenTypes.LITERAL_catch;\n\n /**\n * The {@code finally} keyword.\n *\n * @see #SLIST\n * @see #LITERAL_TRY\n **/\n public static final int LITERAL_FINALLY =\n GeneratedJavaTokenTypes.LITERAL_finally;\n\n /**\n * The {@code +=} (addition assignment) operator.\n *\n *

    For example:

    \n *
    \n     * a += b;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--PLUS_ASSIGN -&gt; +=\n     * |       |--IDENT -&gt; a\n     * |       `--IDENT -&gt; b\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.26.2\n * @see #EXPR\n **/\n public static final int PLUS_ASSIGN = GeneratedJavaTokenTypes.PLUS_ASSIGN;\n /**\n * The {@code -=} (subtraction assignment) operator.\n *\n *

    For example:

    \n *
    \n     * a -= b;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--MINUS_ASSIGN -&gt; -=\n     * |       |--IDENT -&gt; a\n     * |       `--IDENT -&gt; b\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.26.2\n * @see #EXPR\n **/\n public static final int MINUS_ASSIGN =\n GeneratedJavaTokenTypes.MINUS_ASSIGN;\n\n /**\n * The {@code *=} (multiplication assignment) operator.\n *\n *

    For example:

    \n *
    \n     * a *= b;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--STAR_ASSIGN -&gt; *=\n     * |       |--IDENT -&gt; a\n     * |       `--IDENT -&gt; b\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.26.2\n * @see #EXPR\n **/\n public static final int STAR_ASSIGN = GeneratedJavaTokenTypes.STAR_ASSIGN;\n /**\n * The {@code /=} (division assignment) operator.\n *\n *

    For example:

    \n *
    \n     * a /= b;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--DIV_ASSIGN -&gt; /=\n     * |       |--IDENT -&gt; a\n     * |       `--IDENT -&gt; b\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.26.2\n * @see #EXPR\n **/\n public static final int DIV_ASSIGN = GeneratedJavaTokenTypes.DIV_ASSIGN;\n /**\n * The {@code %=} (remainder assignment) operator.\n *

    For example:

    \n *
    a %= 2;
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--MOD_ASSIGN -&gt; %=\n     * |       |--IDENT -&gt; a\n     * |       `--NUM_INT -&gt; 2\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.26.2\n * @see #EXPR\n **/\n public static final int MOD_ASSIGN = GeneratedJavaTokenTypes.MOD_ASSIGN;\n /**\n * The {@code >>=} (signed right shift assignment)\n * operator.\n *\n *

    For example:

    \n *
    \n     * a &gt;&gt;= b;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--SR_ASSIGN -&gt; &gt;&gt;=\n     * |       |--IDENT -&gt; a\n     * |       `--IDENT -&gt; b\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.26.2\n * @see #EXPR\n **/\n public static final int SR_ASSIGN = GeneratedJavaTokenTypes.SR_ASSIGN;\n /**\n * The {@code >>>=} (unsigned right shift assignment)\n * operator.\n *\n *

    For example:

    \n *
    \n     * a &gt;&gt;&gt;= b;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--BSR_ASSIGN -&gt; &gt;&gt;&gt;=\n     * |       |--IDENT -&gt; a\n     * |       `--IDENT -&gt; b\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.26.2\n * @see #EXPR\n **/\n public static final int BSR_ASSIGN = GeneratedJavaTokenTypes.BSR_ASSIGN;\n /**\n * The {@code <<=} (left shift assignment) operator.\n *\n * @see Java\n * Language Specification, &sect;15.26.2\n * @see #EXPR\n **/\n public static final int SL_ASSIGN = GeneratedJavaTokenTypes.SL_ASSIGN;\n /**\n * The {@code &=} (bitwise AND assignment) operator.\n *\n *

    For example:

    \n *
    \n     * a &amp;= b;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--BAND_ASSIGN -&gt; &amp;=\n     * |       |--IDENT -&gt; a\n     * |       `--IDENT -&gt; b\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.26.2\n * @see #EXPR\n **/\n public static final int BAND_ASSIGN = GeneratedJavaTokenTypes.BAND_ASSIGN;\n /**\n * The {@code ^=} (bitwise exclusive OR assignment) operator.\n *\n * @see Java\n * Language Specification, &sect;15.26.2\n * @see #EXPR\n **/\n public static final int BXOR_ASSIGN = GeneratedJavaTokenTypes.BXOR_ASSIGN;\n /**\n * The {@code |=} (bitwise OR assignment) operator.\n *\n *

    For example:

    \n *
    \n     * a |= b;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--BOR_ASSIGN -&gt; |=\n     * |       |--IDENT -&gt; a\n     * |       `--IDENT -&gt; b\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.26.2\n * @see #EXPR\n **/\n public static final int BOR_ASSIGN = GeneratedJavaTokenTypes.BOR_ASSIGN;\n /**\n * The &#63; (conditional) operator. Technically,\n * the colon is also part of this operator, but it appears as a\n * separate token.\n *\n *

    For example:

    \n *
    \n     * (quantity == 1) ? \"\": \"s\"\n     * 
    \n *

    \n * parses as:\n *

    \n *
    \n     * +--QUESTION (?)\n     *     |\n     *     +--LPAREN (()\n     *     +--EQUAL (==)\n     *         |\n     *         +--IDENT (quantity)\n     *         +--NUM_INT (1)\n     *     +--RPAREN ())\n     *     +--STRING_LITERAL (\"\")\n     *     +--COLON (:)\n     *     +--STRING_LITERAL (\"s\")\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.25\n * @see #EXPR\n * @see #COLON\n * @noinspection HtmlTagCanBeJavadocTag\n **/\n public static final int QUESTION = GeneratedJavaTokenTypes.QUESTION;\n /**\n * The {@code ||} (conditional OR) operator.\n *\n * @see Java\n * Language Specification, &sect;15.24\n * @see #EXPR\n **/\n public static final int LOR = GeneratedJavaTokenTypes.LOR;\n /**\n * The {@code &&} (conditional AND) operator.\n *\n * @see Java\n * Language Specification, &sect;15.23\n * @see #EXPR\n **/\n public static final int LAND = GeneratedJavaTokenTypes.LAND;\n /**\n * The {@code |} (bitwise OR) operator.\n *\n *

    For example:

    \n *
    \n     * a = a | b;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--ASSIGN -&gt; =\n     * |       |--IDENT -&gt; a\n     * |       `--BOR -&gt; |\n     * |           |--IDENT -&gt; a\n     * |           `--IDENT -&gt; b\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.22.1\n * @see #EXPR\n **/\n public static final int BOR = GeneratedJavaTokenTypes.BOR;\n /**\n * The {@code ^} (bitwise exclusive OR) operator.\n *\n * @see Java\n * Language Specification, &sect;15.22.1\n * @see #EXPR\n **/\n public static final int BXOR = GeneratedJavaTokenTypes.BXOR;\n /**\n * The {@code &} (bitwise AND) operator.\n *\n *

    For example:

    \n *
    \n     * c = a &amp; b;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--ASSIGN -&gt; =\n     * |       |--IDENT -&gt; c\n     * |       `--BAND -&gt; &amp;\n     * |           |--IDENT -&gt; a\n     * |           `--IDENT -&gt; b\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.22.1\n * @see #EXPR\n **/\n public static final int BAND = GeneratedJavaTokenTypes.BAND;\n /**\n * The &#33;= (not equal) operator.\n *\n *

    For example:

    \n *
    \n     * a != b;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--NOT_EQUAL -&gt; !=\n     * |       |--IDENT -&gt; a\n     * |       `--IDENT -&gt; b\n     * `--SEMI -&gt; ;\n     * 
    \n *\n * @see #EXPR\n * @noinspection HtmlTagCanBeJavadocTag\n **/\n public static final int NOT_EQUAL = GeneratedJavaTokenTypes.NOT_EQUAL;\n /**\n * The {@code ==} (equal) operator.\n *\n *

    For example:

    \n *
    \n     * return a == b;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--EQUAL -&gt; ==\n     * |       |--IDENT -&gt; a\n     * |       `--IDENT -&gt; b\n     * `--SEMI -&gt; ;\n     * 
    \n *\n * @see #EXPR\n **/\n public static final int EQUAL = GeneratedJavaTokenTypes.EQUAL;\n /**\n * The {@code <} (less than) operator.\n *\n * @see #EXPR\n **/\n public static final int LT = GeneratedJavaTokenTypes.LT;\n /**\n * The {@code >} (greater than) operator.\n *\n * @see #EXPR\n **/\n public static final int GT = GeneratedJavaTokenTypes.GT;\n /**\n * The {@code <=} (less than or equal) operator.\n *\n * @see #EXPR\n **/\n public static final int LE = GeneratedJavaTokenTypes.LE;\n /**\n * The {@code >=} (greater than or equal) operator.\n *\n * @see #EXPR\n **/\n public static final int GE = GeneratedJavaTokenTypes.GE;\n /**\n * The {@code instanceof} operator. The first child is an\n * object reference or something that evaluates to an object\n * reference. The second child is a reference type.\n *\n * @see Java\n * Language Specification, &sect;15.20.2\n * @see #EXPR\n * @see #METHOD_CALL\n * @see #IDENT\n * @see #DOT\n * @see #TYPE\n * @see FullIdent\n **/\n public static final int LITERAL_INSTANCEOF =\n GeneratedJavaTokenTypes.LITERAL_instanceof;\n\n /**\n * The {@code <<} (shift left) operator.\n *\n *

    For example:

    \n *
    \n     * a = a &lt;&lt; b;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--ASSIGN -&gt; =\n     * |       |--IDENT -&gt; a\n     * |       `--SR -&gt; &lt;&lt;\n     * |           |--IDENT -&gt; a\n     * |           `--IDENT -&gt; b\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.19\n * @see #EXPR\n **/\n public static final int SL = GeneratedJavaTokenTypes.SL;\n /**\n * The {@code >>} (signed shift right) operator.\n *\n *

    For example:

    \n *
    \n     * a = a &gt;&gt; b;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--ASSIGN -&gt; =\n     * |       |--IDENT -&gt; a\n     * |       `--SR -&gt; &gt;&gt;\n     * |           |--IDENT -&gt; a\n     * |           `--IDENT -&gt; b\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.19\n * @see #EXPR\n **/\n public static final int SR = GeneratedJavaTokenTypes.SR;\n /**\n * The {@code >>>} (unsigned shift right) operator.\n *\n *

    For example:

    \n *
    \n     * a &gt;&gt;&gt; b;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--BSR -&gt; &gt;&gt;&gt;\n     * |       |--IDENT -&gt; a\n     * |       `--IDENT -&gt; b\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.19\n * @see #EXPR\n **/\n public static final int BSR = GeneratedJavaTokenTypes.BSR;\n /**\n * The {@code +} (addition) operator.\n *\n * @see Java\n * Language Specification, &sect;15.18\n * @see #EXPR\n **/\n public static final int PLUS = GeneratedJavaTokenTypes.PLUS;\n /**\n * The {@code -} (subtraction) operator.\n *\n *

    For example:

    \n *
    \n     * c = a - b;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--ASSIGN -&gt; =\n     * |       |--IDENT -&gt; c\n     * |       `--MINUS -&gt; -\n     * |           |--IDENT -&gt; a\n     * |           `--IDENT -&gt; b\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.18\n * @see #EXPR\n **/\n public static final int MINUS = GeneratedJavaTokenTypes.MINUS;\n /**\n * The {@code /} (division) operator.\n *\n *

    For example:

    \n *
    \n     * a = 4 / 2;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--ASSIGN -&gt; =\n     * |       |--IDENT -&gt; a\n     * |       `--DIV -&gt; /\n     * |           |--NUM_INT -&gt; 4\n     * |           `--NUM_INT -&gt; 2\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.17.2\n * @see #EXPR\n **/\n public static final int DIV = GeneratedJavaTokenTypes.DIV;\n /**\n * The {@code %} (remainder) operator.\n *\n * @see Java\n * Language Specification, &sect;15.17.3\n * @see #EXPR\n **/\n public static final int MOD = GeneratedJavaTokenTypes.MOD;\n /**\n * The {@code ++} (prefix increment) operator.\n *\n * @see Java\n * Language Specification, &sect;15.15.1\n * @see #EXPR\n * @see #POST_INC\n **/\n public static final int INC = GeneratedJavaTokenTypes.INC;\n /**\n * The {@code --} (prefix decrement) operator.\n *\n *

    For example:

    \n *
    \n     * --a;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--DEC -&gt; --\n     * |       `--IDENT -&gt; a\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.15.2\n * @see #EXPR\n * @see #POST_DEC\n **/\n public static final int DEC = GeneratedJavaTokenTypes.DEC;\n /**\n * The {@code ~} (bitwise complement) operator.\n *\n *

    For example:

    \n *
    \n     * a = ~ a;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--ASSIGN -&gt; =\n     * |       |--IDENT -&gt; a\n     * |       `--BNOT -&gt; ~\n     * |           `--IDENT -&gt; a\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.15.5\n * @see #EXPR\n **/\n public static final int BNOT = GeneratedJavaTokenTypes.BNOT;\n /**\n * The &#33; (logical complement) operator.\n *\n * @see Java\n * Language Specification, &sect;15.15.6\n * @see #EXPR\n * @noinspection HtmlTagCanBeJavadocTag\n **/\n public static final int LNOT = GeneratedJavaTokenTypes.LNOT;\n /**\n * The {@code true} keyword.\n *\n * @see Java\n * Language Specification, &sect;3.10.3\n * @see #EXPR\n * @see #LITERAL_FALSE\n **/\n public static final int LITERAL_TRUE =\n GeneratedJavaTokenTypes.LITERAL_true;\n\n /**\n * The {@code false} keyword.\n *\n * @see Java\n * Language Specification, &sect;3.10.3\n * @see #EXPR\n * @see #LITERAL_TRUE\n **/\n public static final int LITERAL_FALSE =\n GeneratedJavaTokenTypes.LITERAL_false;\n\n /**\n * The {@code null} keyword.\n *\n * @see Java\n * Language Specification, &sect;3.10.7\n * @see #EXPR\n **/\n public static final int LITERAL_NULL =\n GeneratedJavaTokenTypes.LITERAL_null;\n\n /**\n * The {@code new} keyword. This element is used to define\n * new instances of objects, new arrays, and new anonymous inner\n * classes.\n *\n *

    For example:

    \n *\n *
    \n     * new ArrayList(50)\n     * 
    \n *\n *

    parses as:

    \n *
    \n     * +--LITERAL_NEW (new)\n     *     |\n     *     +--IDENT (ArrayList)\n     *     +--LPAREN (()\n     *     +--ELIST\n     *         |\n     *         +--EXPR\n     *             |\n     *             +--NUM_INT (50)\n     *     +--RPAREN ())\n     * 
    \n *\n *

    For example:

    \n *
    \n     * new float[]\n     *   {\n     *     3.0f,\n     *     4.0f\n     *   };\n     * 
    \n *\n *

    parses as:

    \n *
    \n     * +--LITERAL_NEW (new)\n     *     |\n     *     +--LITERAL_FLOAT (float)\n     *     +--ARRAY_DECLARATOR ([)\n     *     +--ARRAY_INIT ({)\n     *         |\n     *         +--EXPR\n     *             |\n     *             +--NUM_FLOAT (3.0f)\n     *         +--COMMA (,)\n     *         +--EXPR\n     *             |\n     *             +--NUM_FLOAT (4.0f)\n     *         +--RCURLY (})\n     * 
    \n *\n *

    For example:

    \n *
    \n     * new FilenameFilter()\n     * {\n     *   public boolean accept(File dir, String name)\n     *   {\n     *     return name.endsWith(\".java\");\n     *   }\n     * }\n     * 
    \n *\n *

    parses as:

    \n *
    \n     * +--LITERAL_NEW (new)\n     *     |\n     *     +--IDENT (FilenameFilter)\n     *     +--LPAREN (()\n     *     +--ELIST\n     *     +--RPAREN ())\n     *     +--OBJBLOCK\n     *         |\n     *         +--LCURLY ({)\n     *         +--METHOD_DEF\n     *             |\n     *             +--MODIFIERS\n     *                 |\n     *                 +--LITERAL_PUBLIC (public)\n     *             +--TYPE\n     *                 |\n     *                 +--LITERAL_BOOLEAN (boolean)\n     *             +--IDENT (accept)\n     *             +--PARAMETERS\n     *                 |\n     *                 +--PARAMETER_DEF\n     *                     |\n     *                     +--MODIFIERS\n     *                     +--TYPE\n     *                         |\n     *                         +--IDENT (File)\n     *                     +--IDENT (dir)\n     *                 +--COMMA (,)\n     *                 +--PARAMETER_DEF\n     *                     |\n     *                     +--MODIFIERS\n     *                     +--TYPE\n     *                         |\n     *                         +--IDENT (String)\n     *                     +--IDENT (name)\n     *             +--SLIST ({)\n     *                 |\n     *                 +--LITERAL_RETURN (return)\n     *                     |\n     *                     +--EXPR\n     *                         |\n     *                         +--METHOD_CALL (()\n     *                             |\n     *                             +--DOT (.)\n     *                                 |\n     *                                 +--IDENT (name)\n     *                                 +--IDENT (endsWith)\n     *                             +--ELIST\n     *                                 |\n     *                                 +--EXPR\n     *                                     |\n     *                                     +--STRING_LITERAL (\".java\")\n     *                             +--RPAREN ())\n     *                     +--SEMI (;)\n     *                 +--RCURLY (})\n     *         +--RCURLY (})\n     * 
    \n *\n * @see #IDENT\n * @see #DOT\n * @see #LPAREN\n * @see #ELIST\n * @see #RPAREN\n * @see #OBJBLOCK\n * @see #ARRAY_INIT\n * @see FullIdent\n **/\n public static final int LITERAL_NEW = GeneratedJavaTokenTypes.LITERAL_new;\n /**\n * An integer literal. These may be specified in decimal,\n * hexadecimal, or octal form.\n *\n *

    For example:

    \n *
    \n     * a = 3;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--ASSIGN -&gt; =\n     * |       |--IDENT -&gt; a\n     * |       `--NUM_INT -&gt; 3\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;3.10.1\n * @see #EXPR\n * @see #NUM_LONG\n **/\n public static final int NUM_INT = GeneratedJavaTokenTypes.NUM_INT;\n /**\n * A character literal. This is a (possibly escaped) character\n * enclosed in single quotes.\n *\n *

    For example:

    \n *
    \n     * return 'a';\n     * 
    \n *

    parses as:

    \n *
    \n     * --LITERAL_RETURN -&gt; return\n     *    |--EXPR -&gt; EXPR\n     *    |   `--CHAR_LITERAL -&gt; 'a'\n     *    `--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;3.10.4\n * @see #EXPR\n **/\n public static final int CHAR_LITERAL =\n GeneratedJavaTokenTypes.CHAR_LITERAL;\n\n /**\n * A string literal. This is a sequence of (possibly escaped)\n * characters enclosed in double quotes.\n *

    For example:

    \n *
    String str = \"StringLiteral\";
    \n *\n *

    parses as:

    \n *
    \n     *  |--VARIABLE_DEF -&gt; VARIABLE_DEF\n     *  |   |--MODIFIERS -&gt; MODIFIERS\n     *  |   |--TYPE -&gt; TYPE\n     *  |   |   `--IDENT -&gt; String\n     *  |   |--IDENT -&gt; str\n     *  |   `--ASSIGN -&gt; =\n     *  |       `--EXPR -&gt; EXPR\n     *  |           `--STRING_LITERAL -&gt; \"StringLiteral\"\n     *  |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;3.10.5\n * @see #EXPR\n **/\n public static final int STRING_LITERAL =\n GeneratedJavaTokenTypes.STRING_LITERAL;\n\n /**\n * A single precision floating point literal. This is a floating\n * point number with an {@code F} or {@code f} suffix.\n *\n *

    For example:

    \n *
    \n     * a = 3.14f;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--ASSIGN -&gt; =\n     * |       |--IDENT -&gt; a\n     * |       `--NUM_FLOAT -&gt; 3.14f\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;3.10.2\n * @see #EXPR\n * @see #NUM_DOUBLE\n **/\n public static final int NUM_FLOAT = GeneratedJavaTokenTypes.NUM_FLOAT;\n /**\n * A long integer literal. These are almost the same as integer\n * literals, but they have an {@code L} or {@code l}\n * (ell) suffix.\n *\n *

    For example:

    \n *
    \n     * a = 3l;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--ASSIGN -&gt; =\n     * |       |--IDENT -&gt; a\n     * |       `--NUM_LONG -&gt; 3l\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;3.10.1\n * @see #EXPR\n * @see #NUM_INT\n **/\n public static final int NUM_LONG = GeneratedJavaTokenTypes.NUM_LONG;\n /**\n * A double precision floating point literal. This is a floating\n * point number with an optional {@code D} or {@code d}\n * suffix.\n *\n *

    For example:

    \n *
    \n     * a = 3.14d;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--ASSIGN -&gt; =\n     * |       |--IDENT -&gt; a\n     * |       `--NUM_DOUBLE -&gt; 3.14d\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;3.10.2\n * @see #EXPR\n * @see #NUM_FLOAT\n **/\n public static final int NUM_DOUBLE = GeneratedJavaTokenTypes.NUM_DOUBLE;\n\n /**\n * The {@code assert} keyword. This is only for Java 1.4 and\n * later.\n *\n *

    For example:

    \n *
    \n     * assert(x==4);\n     * 
    \n *

    parses as:

    \n *
    \n     * +--LITERAL_ASSERT (assert)\n     *     |\n     *     +--EXPR\n     *         |\n     *         +--LPAREN (()\n     *         +--EQUAL (==)\n     *             |\n     *             +--IDENT (x)\n     *             +--NUM_INT (4)\n     *         +--RPAREN ())\n     *     +--SEMI (;)\n     * 
    \n **/\n public static final int LITERAL_ASSERT = GeneratedJavaTokenTypes.ASSERT;\n\n /**\n * A static import declaration. Static import declarations are optional,\n * but must appear after the package declaration and before the type\n * declaration.\n *\n *

    For example:

    \n *
    \n     * import static java.io.IOException;\n     * 
    \n *

    parses as:

    \n *
    \n     * STATIC_IMPORT -&gt; import\n     * |--LITERAL_STATIC -&gt; static\n     * |--DOT -&gt; .\n     * |   |--DOT -&gt; .\n     * |   |   |--IDENT -&gt; java\n     * |   |   `--IDENT -&gt; io\n     * |   `--IDENT -&gt; IOException\n     * `--SEMI -&gt; ;\n     * 
    \n *\n * @see \n * JSR201\n * @see #LITERAL_STATIC\n * @see #DOT\n * @see #IDENT\n * @see #STAR\n * @see #SEMI\n * @see FullIdent\n **/\n public static final int STATIC_IMPORT =\n GeneratedJavaTokenTypes.STATIC_IMPORT;\n\n /**\n * An enum declaration. Its notable children are\n * enum constant declarations followed by\n * any construct that may be expected in a class body.\n *\n *

    For example:

    \n *
    \n     * public enum MyEnum\n     *   implements Serializable\n     * {\n     *     FIRST_CONSTANT,\n     *     SECOND_CONSTANT;\n     *\n     *     public void someMethod()\n     *     {\n     *     }\n     * }\n     * 
    \n *

    parses as:

    \n *
    \n     * +--ENUM_DEF\n     *     |\n     *     +--MODIFIERS\n     *         |\n     *         +--LITERAL_PUBLIC (public)\n     *     +--ENUM (enum)\n     *     +--IDENT (MyEnum)\n     *     +--EXTENDS_CLAUSE\n     *     +--IMPLEMENTS_CLAUSE\n     *         |\n     *         +--IDENT (Serializable)\n     *     +--OBJBLOCK\n     *         |\n     *         +--LCURLY ({)\n     *         +--ENUM_CONSTANT_DEF\n     *             |\n     *             +--IDENT (FIRST_CONSTANT)\n     *         +--COMMA (,)\n     *         +--ENUM_CONSTANT_DEF\n     *             |\n     *             +--IDENT (SECOND_CONSTANT)\n     *         +--SEMI (;)\n     *         +--METHOD_DEF\n     *             |\n     *             +--MODIFIERS\n     *                 |\n     *                 +--LITERAL_PUBLIC (public)\n     *             +--TYPE\n     *                 |\n     *                 +--LITERAL_void (void)\n     *             +--IDENT (someMethod)\n     *             +--LPAREN (()\n     *             +--PARAMETERS\n     *             +--RPAREN ())\n     *             +--SLIST ({)\n     *                 |\n     *                 +--RCURLY (})\n     *         +--RCURLY (})\n     * 
    \n *\n * @see \n * JSR201\n * @see #MODIFIERS\n * @see #ENUM\n * @see #IDENT\n * @see #EXTENDS_CLAUSE\n * @see #IMPLEMENTS_CLAUSE\n * @see #OBJBLOCK\n * @see #LITERAL_NEW\n * @see #ENUM_CONSTANT_DEF\n **/\n public static final int ENUM_DEF =\n GeneratedJavaTokenTypes.ENUM_DEF;\n\n /**\n * The {@code enum} keyword. This element appears\n * as part of an enum declaration.\n **/\n public static final int ENUM =\n GeneratedJavaTokenTypes.ENUM;\n\n /**\n * An enum constant declaration. Its notable children are annotations,\n * arguments and object block akin to an anonymous\n * inner class' body.\n *\n *

    For example:

    \n *
    \n     * SOME_CONSTANT(1)\n     * {\n     *     public void someMethodOverriddenFromMainBody()\n     *     {\n     *     }\n     * }\n     * 
    \n *

    parses as:

    \n *
    \n     * +--ENUM_CONSTANT_DEF\n     *     |\n     *     +--ANNOTATIONS\n     *     +--IDENT (SOME_CONSTANT)\n     *     +--LPAREN (()\n     *     +--ELIST\n     *         |\n     *         +--EXPR\n     *             |\n     *             +--NUM_INT (1)\n     *     +--RPAREN ())\n     *     +--OBJBLOCK\n     *         |\n     *         +--LCURLY ({)\n     *         |\n     *         +--METHOD_DEF\n     *             |\n     *             +--MODIFIERS\n     *                 |\n     *                 +--LITERAL_PUBLIC (public)\n     *             +--TYPE\n     *                 |\n     *                 +--LITERAL_void (void)\n     *             +--IDENT (someMethodOverriddenFromMainBody)\n     *             +--LPAREN (()\n     *             +--PARAMETERS\n     *             +--RPAREN ())\n     *             +--SLIST ({)\n     *                 |\n     *                 +--RCURLY (})\n     *         +--RCURLY (})\n     * 
    \n *\n * @see \n * JSR201\n * @see #ANNOTATIONS\n * @see #MODIFIERS\n * @see #IDENT\n * @see #ELIST\n * @see #OBJBLOCK\n **/\n public static final int ENUM_CONSTANT_DEF =\n GeneratedJavaTokenTypes.ENUM_CONSTANT_DEF;\n\n /**\n * A for-each clause. This is a child of\n * {@code LITERAL_FOR}. The children of this element may be\n * a parameter definition, the colon literal and an expression.\n *\n *

    For example:

    \n *
    \n     * for (int value : values) {\n     *     doSmth();\n     * }\n     * 
    \n *

    parses as:

    \n *
    \n     * --LITERAL_FOR (for)\n     *    |--LPAREN (()\n     *    |--FOR_EACH_CLAUSE\n     *    |   |--VARIABLE_DEF\n     *    |   |   |--MODIFIERS\n     *    |   |   |--TYPE\n     *    |   |   |   `--LITERAL_INT (int)\n     *    |   |   `--IDENT (value)\n     *    |   |--COLON (:)\n     *    |   `--EXPR\n     *    |       `--IDENT (values\n     *    |--RPAREN ())\n     *    `--SLIST ({)\n     *        |--EXPR\n     *        |   `--METHOD_CALL (()\n     *        |       |--IDENT (doSmth)\n     *        |       |--ELIST\n     *        |       `--RPAREN ())\n     *        |--SEMI (;)\n     *        `--RCURLY (})\n     *\n     * 
    \n *\n * @see #VARIABLE_DEF\n * @see #ELIST\n * @see #LITERAL_FOR\n **/\n public static final int FOR_EACH_CLAUSE =\n GeneratedJavaTokenTypes.FOR_EACH_CLAUSE;\n\n /**\n * An annotation declaration. The notable children are the name of the\n * annotation type, annotation field declarations and (constant) fields.\n *\n *

    For example:

    \n *
    \n     * public @interface MyAnnotation\n     * {\n     *     int someValue();\n     * }\n     * 
    \n *

    parses as:

    \n *
    \n     * +--ANNOTATION_DEF\n     *     |\n     *     +--MODIFIERS\n     *         |\n     *         +--LITERAL_PUBLIC (public)\n     *     +--AT (@)\n     *     +--LITERAL_INTERFACE (interface)\n     *     +--IDENT (MyAnnotation)\n     *     +--OBJBLOCK\n     *         |\n     *         +--LCURLY ({)\n     *         +--ANNOTATION_FIELD_DEF\n     *             |\n     *             +--MODIFIERS\n     *             +--TYPE\n     *                 |\n     *                 +--LITERAL_INT (int)\n     *             +--IDENT (someValue)\n     *             +--LPAREN (()\n     *             +--RPAREN ())\n     *             +--SEMI (;)\n     *         +--RCURLY (})\n     * 
    \n *\n * @see \n * JSR201\n * @see #MODIFIERS\n * @see #LITERAL_INTERFACE\n * @see #IDENT\n * @see #OBJBLOCK\n * @see #ANNOTATION_FIELD_DEF\n **/\n public static final int ANNOTATION_DEF =\n GeneratedJavaTokenTypes.ANNOTATION_DEF;\n\n /**\n * An annotation field declaration. The notable children are modifiers,\n * field type, field name and an optional default value (a conditional\n * compile-time constant expression). Default values may also by\n * annotations.\n *\n *

    For example:

    \n *\n *
    \n     *     String someField() default \"Hello world\";\n     * 
    \n *\n *

    parses as:

    \n *\n *
    \n     * +--ANNOTATION_FIELD_DEF\n     *     |\n     *     +--MODIFIERS\n     *     +--TYPE\n     *         |\n     *         +--IDENT (String)\n     *     +--IDENT (someField)\n     *     +--LPAREN (()\n     *     +--RPAREN ())\n     *     +--LITERAL_DEFAULT (default)\n     *     +--STRING_LITERAL (\"Hello world\")\n     *     +--SEMI (;)\n     * 
    \n *\n * @see \n * JSR201\n * @see #MODIFIERS\n * @see #TYPE\n * @see #LITERAL_DEFAULT\n */\n public static final int ANNOTATION_FIELD_DEF =\n GeneratedJavaTokenTypes.ANNOTATION_FIELD_DEF;\n\n // note: &#064; is the html escape for '@',\n // used here to avoid confusing the javadoc tool\n /**\n * A collection of annotations on a package or enum constant.\n * A collections of annotations will only occur on these nodes\n * as all other nodes that may be qualified with an annotation can\n * be qualified with any other modifier and hence these annotations\n * would be contained in a {@link #MODIFIERS} node.\n *\n *

    For example:

    \n *\n *
    \n     *     &#064;MyAnnotation package blah;\n     * 
    \n *\n *

    parses as:

    \n *\n *
    \n     * +--PACKAGE_DEF (package)\n     *     |\n     *     +--ANNOTATIONS\n     *         |\n     *         +--ANNOTATION\n     *             |\n     *             +--AT (&#064;)\n     *             +--IDENT (MyAnnotation)\n     *     +--IDENT (blah)\n     *     +--SEMI (;)\n     * 
    \n *\n * @see \n * JSR201\n * @see #ANNOTATION\n * @see #AT\n * @see #IDENT\n */\n public static final int ANNOTATIONS =\n GeneratedJavaTokenTypes.ANNOTATIONS;\n\n // note: &#064; is the html escape for '@',\n // used here to avoid confusing the javadoc tool\n /**\n * An annotation of a package, type, field, parameter or variable.\n * An annotation may occur anywhere modifiers occur (it is a\n * type of modifier) and may also occur prior to a package definition.\n * The notable children are: The annotation name and either a single\n * default annotation value or a sequence of name value pairs.\n * Annotation values may also be annotations themselves.\n *\n *

    For example:

    \n *\n *
    \n     *     &#064;MyAnnotation(someField1 = \"Hello\",\n     *                    someField2 = &#064;SomeOtherAnnotation)\n     * 
    \n *\n *

    parses as:

    \n *\n *
    \n     * +--ANNOTATION\n     *     |\n     *     +--AT (&#064;)\n     *     +--IDENT (MyAnnotation)\n     *     +--LPAREN (()\n     *     +--ANNOTATION_MEMBER_VALUE_PAIR\n     *         |\n     *         +--IDENT (someField1)\n     *         +--ASSIGN (=)\n     *         +--ANNOTATION\n     *             |\n     *             +--AT (&#064;)\n     *             +--IDENT (SomeOtherAnnotation)\n     *     +--ANNOTATION_MEMBER_VALUE_PAIR\n     *         |\n     *         +--IDENT (someField2)\n     *         +--ASSIGN (=)\n     *         +--STRING_LITERAL (\"Hello\")\n     *     +--RPAREN ())\n     * 
    \n *\n * @see \n * JSR201\n * @see #MODIFIERS\n * @see #IDENT\n * @see #ANNOTATION_MEMBER_VALUE_PAIR\n */\n public static final int ANNOTATION =\n GeneratedJavaTokenTypes.ANNOTATION;\n\n /**\n * An initialization of an annotation member with a value.\n * Its children are the name of the member, the assignment literal\n * and the (compile-time constant conditional expression) value.\n *\n * @see \n * JSR201\n * @see #ANNOTATION\n * @see #IDENT\n */\n public static final int ANNOTATION_MEMBER_VALUE_PAIR =\n GeneratedJavaTokenTypes.ANNOTATION_MEMBER_VALUE_PAIR;\n\n /**\n * An annotation array member initialization.\n * Initializers can not be nested.\n * An initializer may be present as a default to an annotation\n * member, as the single default value to an annotation\n * (e.g. @Annotation({1,2})) or as the value of an annotation\n * member value pair.\n *\n *

    For example:

    \n *\n *
    \n     *     { 1, 2 }\n     * 
    \n *\n *

    parses as:

    \n *\n *
    \n     * +--ANNOTATION_ARRAY_INIT ({)\n     *     |\n     *     +--NUM_INT (1)\n     *     +--COMMA (,)\n     *     +--NUM_INT (2)\n     *     +--RCURLY (})\n     * 
    \n *\n * @see \n * JSR201\n * @see #ANNOTATION\n * @see #IDENT\n * @see #ANNOTATION_MEMBER_VALUE_PAIR\n */\n public static final int ANNOTATION_ARRAY_INIT =\n GeneratedJavaTokenTypes.ANNOTATION_ARRAY_INIT;\n\n /**\n * A list of type parameters to a class, interface or\n * method definition. Children are LT, at least one\n * TYPE_PARAMETER, zero or more of: a COMMAs followed by a single\n * TYPE_PARAMETER and a final GT.\n *\n *

    For example:

    \n *\n *
    \n     * public class MyClass&lt;A, B&gt; {\n     *\n     * }\n     * 
    \n *\n *

    parses as:

    \n *\n *
    \n     * CLASS_DEF -&gt; CLASS_DEF\n     * |--MODIFIERS -&gt; MODIFIERS\n     * |   `--LITERAL_PUBLIC -&gt; public\n     * |--LITERAL_CLASS -&gt; class\n     * |--IDENT -&gt; MyClass\n     * |--TYPE_PARAMETERS -&gt; TYPE_PARAMETERS\n     * |   |--GENERIC_START -&gt; &lt;\n     * |   |--TYPE_PARAMETER -&gt; TYPE_PARAMETER\n     * |   |   `--IDENT -&gt; A\n     * |   |--COMMA -&gt; ,\n     * |   |--TYPE_PARAMETER -&gt; TYPE_PARAMETER\n     * |   |   `--IDENT -&gt; B\n     * |   `--GENERIC_END -&gt; &gt;\n     * `--OBJBLOCK -&gt; OBJBLOCK\n     *     |--LCURLY -&gt; {\n     *     `--RCURLY -&gt; }\n     * 
    \n *\n * @see \n * JSR14\n * @see #GENERIC_START\n * @see #GENERIC_END\n * @see #TYPE_PARAMETER\n * @see #COMMA\n */\n public static final int TYPE_PARAMETERS =\n GeneratedJavaTokenTypes.TYPE_PARAMETERS;\n\n /**\n * A type parameter to a class, interface or method definition.\n * Children are the type name and an optional TYPE_UPPER_BOUNDS.\n *\n *

    For example:

    \n *\n *
    \n     * public class MyClass &lt;A extends Collection&gt; {\n     *\n     * }\n     * 
    \n *\n *

    parses as:

    \n *\n *
    \n     * CLASS_DEF -&gt; CLASS_DEF\n     * |--MODIFIERS -&gt; MODIFIERS\n     * |   `--LITERAL_PUBLIC -&gt; public\n     * |--LITERAL_CLASS -&gt; class\n     * |--IDENT -&gt; MyClass\n     * |--TYPE_PARAMETERS -&gt; TYPE_PARAMETERS\n     * |   |--GENERIC_START -&gt; &lt;\n     * |   |--TYPE_PARAMETER -&gt; TYPE_PARAMETER\n     * |   |   |--IDENT -&gt; A\n     * |   |   `--TYPE_UPPER_BOUNDS -&gt; extends\n     * |   |       `--IDENT -&gt; Collection\n     * |   `--GENERIC_END -&gt; &gt;\n     * `--OBJBLOCK -&gt; OBJBLOCK\n     *     |--LCURLY -&gt; {\n     *     `--RCURLY -&gt; }\n     * 
    \n *\n * @see \n * JSR14\n * @see #IDENT\n * @see #WILDCARD_TYPE\n * @see #TYPE_UPPER_BOUNDS\n */\n public static final int TYPE_PARAMETER =\n GeneratedJavaTokenTypes.TYPE_PARAMETER;\n\n /**\n * A list of type arguments to a type reference or\n * a method/ctor invocation. Children are GENERIC_START, at least one\n * TYPE_ARGUMENT, zero or more of a COMMAs followed by a single\n * TYPE_ARGUMENT, and a final GENERIC_END.\n *\n *

    For example:

    \n *\n *
    \n     *     public Collection&lt;?&gt; a;\n     * 
    \n *\n *

    parses as:

    \n *\n *
    \n     * +--VARIABLE_DEF\n     *     |\n     *     +--MODIFIERS\n     *         |\n     *         +--LITERAL_PUBLIC (public)\n     *     +--TYPE\n     *         |\n     *         +--IDENT (Collection)\n     *             |\n     *             +--TYPE_ARGUMENTS\n     *                 |\n     *                 +--GENERIC_START (&lt;)\n     *                 +--TYPE_ARGUMENT\n     *                     |\n     *                     +--WILDCARD_TYPE (?)\n     *                 +--GENERIC_END (&gt;)\n     *     +--IDENT (a)\n     *     +--SEMI (;)\n     * 
    \n *\n * @see #GENERIC_START\n * @see #GENERIC_END\n * @see #TYPE_ARGUMENT\n * @see #COMMA\n */\n public static final int TYPE_ARGUMENTS =\n GeneratedJavaTokenTypes.TYPE_ARGUMENTS;\n\n /**\n * A type arguments to a type reference or a method/ctor invocation.\n * Children are either: type name or wildcard type with possible type\n * upper or lower bounds.\n *\n *

    For example:

    \n *\n *
    \n     *     ? super List\n     * 
    \n *\n *

    parses as:

    \n *\n *
    \n     * +--TYPE_ARGUMENT\n     *     |\n     *     +--WILDCARD_TYPE (?)\n     *     +--TYPE_LOWER_BOUNDS\n     *         |\n     *         +--IDENT (List)\n     * 
    \n *\n * @see \n * JSR14\n * @see #WILDCARD_TYPE\n * @see #TYPE_UPPER_BOUNDS\n * @see #TYPE_LOWER_BOUNDS\n */\n public static final int TYPE_ARGUMENT =\n GeneratedJavaTokenTypes.TYPE_ARGUMENT;\n\n /**\n * The type that refers to all types. This node has no children.\n *\n * @see \n * JSR14\n * @see #TYPE_ARGUMENT\n * @see #TYPE_UPPER_BOUNDS\n * @see #TYPE_LOWER_BOUNDS\n */\n public static final int WILDCARD_TYPE =\n GeneratedJavaTokenTypes.WILDCARD_TYPE;\n\n /**\n * An upper bounds on a wildcard type argument or type parameter.\n * This node has one child - the type that is being used for\n * the bounding.\n *

    For example:

    \n *
    List&lt;? extends Number&gt; list;
    \n *\n *

    parses as:

    \n *
    \n     * --VARIABLE_DEF -&gt; VARIABLE_DEF\n     *  |--MODIFIERS -&gt; MODIFIERS\n     *  |--TYPE -&gt; TYPE\n     *  |   |--IDENT -&gt; List\n     *  |   `--TYPE_ARGUMENTS -&gt; TYPE_ARGUMENTS\n     *  |       |--GENERIC_START -&gt; &lt;\n     *  |       |--TYPE_ARGUMENT -&gt; TYPE_ARGUMENT\n     *  |       |   |--WILDCARD_TYPE -&gt; ?\n     *  |       |   `--TYPE_UPPER_BOUNDS -&gt; extends\n     *  |       |       `--IDENT -&gt; Number\n     *  |       `--GENERIC_END -&gt; &gt;\n     *  |--IDENT -&gt; list\n     *  `--SEMI -&gt; ;\n     *  
    \n *\n * @see \n * JSR14\n * @see #TYPE_PARAMETER\n * @see #TYPE_ARGUMENT\n * @see #WILDCARD_TYPE\n */\n public static final int TYPE_UPPER_BOUNDS =\n GeneratedJavaTokenTypes.TYPE_UPPER_BOUNDS;\n\n /**\n * A lower bounds on a wildcard type argument. This node has one child\n * - the type that is being used for the bounding.\n *\n *

    For example:

    \n *
    List&lt;? super Integer&gt; list;
    \n *\n *

    parses as:

    \n *
    \n     *  --VARIABLE_DEF -&gt; VARIABLE_DEF\n     *     |--MODIFIERS -&gt; MODIFIERS\n     *     |--TYPE -&gt; TYPE\n     *     |   |--IDENT -&gt; List\n     *     |   `--TYPE_ARGUMENTS -&gt; TYPE_ARGUMENTS\n     *     |       |--GENERIC_START -&gt; &lt;\n     *     |       |--TYPE_ARGUMENT -&gt; TYPE_ARGUMENT\n     *     |       |   |--WILDCARD_TYPE -&gt; ?\n     *     |       |   `--TYPE_LOWER_BOUNDS -&gt; super\n     *     |       |       `--IDENT -&gt; Integer\n     *     |       `--GENERIC_END -&gt; &gt;\n     *     |--IDENT -&gt; list\n     *     `--SEMI -&gt; ;\n     *  
    \n *\n * @see \n * JSR14\n * @see #TYPE_ARGUMENT\n * @see #WILDCARD_TYPE\n */\n public static final int TYPE_LOWER_BOUNDS =\n GeneratedJavaTokenTypes.TYPE_LOWER_BOUNDS;\n\n /**\n * An {@code @} symbol - signifying an annotation instance or the prefix\n * to the interface literal signifying the definition of an annotation\n * declaration.\n *\n * @see \n * JSR201\n */\n public static final int AT = GeneratedJavaTokenTypes.AT;\n\n /**\n * A triple dot for variable-length parameters. This token only ever occurs\n * in a parameter declaration immediately after the type of the parameter.\n *\n * @see \n * JSR201\n */\n public static final int ELLIPSIS = GeneratedJavaTokenTypes.ELLIPSIS;\n\n /**\n * The {@code &} symbol when used to extend a generic upper or lower bounds constrain\n * or a type cast expression with an additional interface.\n *\n *

    Generic type bounds extension:\n * {@code class Comparable}

    \n *
    \n     * CLASS_DEF -&gt; CLASS_DEF\n     * |--MODIFIERS -&gt; MODIFIERS\n     * |--LITERAL_CLASS -&gt; class\n     * |--IDENT -&gt; Comparable\n     * |--TYPE_PARAMETERS -&gt; TYPE_PARAMETERS\n     *     |--GENERIC_START -&gt; &lt;\n     *     |--TYPE_PARAMETER -&gt; TYPE_PARAMETER\n     *     |   |--IDENT -&gt; T\n     *     |   `--TYPE_UPPER_BOUNDS -&gt; extends\n     *     |       |--IDENT -&gt; Serializable\n     *     |       |--TYPE_EXTENSION_AND -&gt; &#38;\n     *     |       `--IDENT -&gt; CharSequence\n     *     `--GENERIC_END -&gt; &gt;\n     * 
    \n *\n *

    Type cast extension:\n * {@code return (Serializable & CharSequence) null;}

    \n *
    \n     * --LITERAL_RETURN -&gt; return\n     *    |--EXPR -&gt; EXPR\n     *    |   `--TYPECAST -&gt; (\n     *    |       |--TYPE -&gt; TYPE\n     *    |       |   `--IDENT -&gt; Serializable\n     *    |       |--TYPE_EXTENSION_AND -&gt; &#38;\n     *    |       |--TYPE -&gt; TYPE\n     *    |       |   `--IDENT -&gt; CharSequence\n     *    |       |--RPAREN -&gt; )\n     *    |       `--LITERAL_NULL -&gt; null\n     *    `--SEMI -&gt; ;\n     * 
    \n *\n * @see #EXTENDS_CLAUSE\n * @see #TYPECAST\n * @see \n * Java Language Specification, &sect;4.4\n * @see \n * Java Language Specification, &sect;15.16\n */\n public static final int TYPE_EXTENSION_AND =\n GeneratedJavaTokenTypes.TYPE_EXTENSION_AND;\n\n /**\n * A {@code <} symbol signifying the start of type arguments or type parameters.\n */\n public static final int GENERIC_START =\n GeneratedJavaTokenTypes.GENERIC_START;\n\n /**\n * A {@code >} symbol signifying the end of type arguments or type parameters.\n */\n public static final int GENERIC_END = GeneratedJavaTokenTypes.GENERIC_END;\n\n /**\n * Special lambda symbol {@code ->}.\n */\n public static final int LAMBDA = GeneratedJavaTokenTypes.LAMBDA;\n\n /**\n * Beginning of single line comment: '//'.\n *\n *
    \n     * +--SINGLE_LINE_COMMENT\n     *         |\n     *         +--COMMENT_CONTENT\n     * 
    \n */\n public static final int SINGLE_LINE_COMMENT =\n GeneratedJavaTokenTypes.SINGLE_LINE_COMMENT;\n\n /**\n * Beginning of block comment: '/*'.\n *

    For example:

    \n *
    \n     * /&#42; Comment content\n     * &#42;/\n     * 
    \n *

    parses as:

    \n *
    \n     * --BLOCK_COMMENT_BEGIN -&gt; /&#42;\n     *    |--COMMENT_CONTENT -&gt;  Comment content\\r\\n\n     *    `--BLOCK_COMMENT_END -&gt; &#42;/\n     * 
    \n */\n public static final int BLOCK_COMMENT_BEGIN =\n GeneratedJavaTokenTypes.BLOCK_COMMENT_BEGIN;\n\n /**\n * End of block comment: '&#42;/'.\n *\n *
    \n     * +--BLOCK_COMMENT_BEGIN\n     *         |\n     *         +--COMMENT_CONTENT\n     *         +--BLOCK_COMMENT_END\n     * 
    \n */\n public static final int BLOCK_COMMENT_END =\n GeneratedJavaTokenTypes.BLOCK_COMMENT_END;\n\n /**\n * Text of single-line or block comment.\n *\n *
    \n     * +--SINGLE_LINE_COMMENT\n     *         |\n     *         +--COMMENT_CONTENT\n     * 
    \n *\n *
    \n     * +--BLOCK_COMMENT_BEGIN\n     *         |\n     *         +--COMMENT_CONTENT\n     *         +--BLOCK_COMMENT_END\n     * 
    \n */\n public static final int COMMENT_CONTENT =\n GeneratedJavaTokenTypes.COMMENT_CONTENT;\n\n /**\n * A pattern variable definition; when conditionally matched,\n * this variable is assigned with the defined type.\n *\n *

    For example:

    \n *
    \n     * if (obj instanceof String str) { }\n     * 
    \n *

    parses as:

    \n *
    \n     * LITERAL_IF (if)\n     *  |--LPAREN (()\n     *  |--EXPR\n     *  |   `--LITERAL_INSTANCEOF (instanceof)\n     *  |       |--IDENT (obj)\n     *  |       `--PATTERN_VARIABLE_DEF\n     *  |            |--TYPE\n     *  |            |   `--IDENT (String)\n     *  |            `--IDENT (str)\n     *  |--RPAREN ())\n     *  `--SLIST ({)\n     *      `--RCURLY (})\n     * 
    \n *\n * @see #LITERAL_INSTANCEOF\n * @since 8.35\n */\n public static final int PATTERN_VARIABLE_DEF =\n GeneratedJavaTokenTypes.PATTERN_VARIABLE_DEF;\n\n /**\n * The {@code record} keyword. This element appears\n * as part of a record declaration.\n *\n * @since 8.35\n **/\n public static final int LITERAL_RECORD =\n GeneratedJavaTokenTypes.LITERAL_record;\n\n /**\n * A declaration of a record specifies a name, a header, and a body.\n * The header lists the components of the record, which are the variables\n * that make up its state.\n *\n *

    For example:

    \n *
    \n     * public record MyRecord () {\n     *\n     * }\n     * 
    \n *

    parses as:

    \n *
    \n     * RECORD_DEF -&gt; RECORD_DEF\n     * |--MODIFIERS -&gt; MODIFIERS\n     * |   `--LITERAL_PUBLIC -&gt; public\n     * |--LITERAL_RECORD -&gt; record\n     * |--IDENT -&gt; MyRecord\n     * |--LPAREN -&gt; (\n     * |--RECORD_COMPONENTS -&gt; RECORD_COMPONENTS\n     * |--RPAREN -&gt; )\n     * `--OBJBLOCK -&gt; OBJBLOCK\n     *     |--LCURLY -&gt; {\n     *     `--RCURLY -&gt; }\n     * 
    \n *\n * @since 8.35\n */\n public static final int RECORD_DEF =\n GeneratedJavaTokenTypes.RECORD_DEF;\n\n /**\n * Record components are a (possibly empty) list containing the components of a record, which\n * are the variables that make up its state.\n *\n *

    For example:

    \n *
    \n     * public record myRecord (Comp x, Comp y) { }\n     * 
    \n *

    parses as:

    \n *
    \n     * RECORD_DEF -&gt; RECORD_DEF\n     *  |--MODIFIERS -&gt; MODIFIERS\n     *  |   `--LITERAL_PUBLIC -&gt; public\n     *  |--LITERAL_RECORD -&gt; record\n     *  |--IDENT -&gt; myRecord\n     *  |--LPAREN -&gt; (\n     *  |--RECORD_COMPONENTS -&gt; RECORD_COMPONENTS\n     *  |   |--RECORD_COMPONENT_DEF -&gt; RECORD_COMPONENT_DEF\n     *  |   |   |--ANNOTATIONS -&gt; ANNOTATIONS\n     *  |   |   |--TYPE -&gt; TYPE\n     *  |   |   |   `--IDENT -&gt; Comp\n     *  |   |   `--IDENT -&gt; x\n     *  |   |--COMMA -&gt; ,\n     *  |   `--RECORD_COMPONENT_DEF -&gt; RECORD_COMPONENT_DEF\n     *  |       |--ANNOTATIONS -&gt; ANNOTATIONS\n     *  |       |--TYPE -&gt; TYPE\n     *  |       |   `--IDENT -&gt; Comp\n     *  |       `--IDENT -&gt; y\n     *  |--RPAREN -&gt; )\n     *  `--OBJBLOCK -&gt; OBJBLOCK\n     *      |--LCURLY -&gt; {\n     *      `--RCURLY -&gt; }\n     * 
    \n *\n * @since 8.36\n */\n public static final int RECORD_COMPONENTS =\n GeneratedJavaTokenTypes.RECORD_COMPONENTS;\n\n /**\n * A record component is a variable that comprises the state of a record. Record components\n * have annotations (possibly), a type definition, and an identifier. They can also be of\n * variable arity ('...').\n *\n *

    For example:

    \n *
    \n     * public record MyRecord(Comp x, Comp... comps) {\n     *\n     * }\n     * 
    \n *

    parses as:

    \n *
    \n     * RECORD_DEF -&gt; RECORD_DEF\n     * |--MODIFIERS -&gt; MODIFIERS\n     * |   `--LITERAL_PUBLIC -&gt; public\n     * |--LITERAL_RECORD -&gt; record\n     * |--IDENT -&gt; MyRecord\n     * |--LPAREN -&gt; (\n     * |--RECORD_COMPONENTS -&gt; RECORD_COMPONENTS\n     * |   |--RECORD_COMPONENT_DEF -&gt; RECORD_COMPONENT_DEF\n     * |   |   |--ANNOTATIONS -&gt; ANNOTATIONS\n     * |   |   |--TYPE -&gt; TYPE\n     * |   |   |   `--IDENT -&gt; Comp\n     * |   |   `--IDENT -&gt; x\n     * |   |--COMMA -&gt; ,\n     * |   `--RECORD_COMPONENT_DEF -&gt; RECORD_COMPONENT_DEF\n     * |       |--ANNOTATIONS -&gt; ANNOTATIONS\n     * |       |--TYPE -&gt; TYPE\n     * |       |   `--IDENT -&gt; Comp\n     * |       |--ELLIPSIS -&gt; ...\n     * |       `--IDENT -&gt; comps\n     * |--RPAREN -&gt; )\n     * `--OBJBLOCK -&gt; OBJBLOCK\n     *     |--LCURLY -&gt; {\n     *     `--RCURLY -&gt; }\n     * 
    \n *\n * @since 8.36\n */\n public static final int RECORD_COMPONENT_DEF =\n GeneratedJavaTokenTypes.RECORD_COMPONENT_DEF;\n\n /**\n * A compact canonical constructor eliminates the list of formal parameters; they are\n * declared implicitly.\n *\n *

    For example:

    \n *
    \n     * public record myRecord () {\n     *     public myRecord{}\n     * }\n     * 
    \n *

    parses as:

    \n *
    \n     * RECORD_DEF\n     * |--MODIFIERS\n     * |   `--LITERAL_PUBLIC (public)\n     * |--LITERAL_RECORD (record)\n     * |--IDENT (myRecord)\n     * |--LPAREN (()\n     * |--RECORD_COMPONENTS\n     * |--RPAREN ())\n     * `--OBJBLOCK\n     *     |--LCURLY ({)\n     *     |--COMPACT_CTOR_DEF\n     *     |   |--MODIFIERS\n     *     |   |   `--LITERAL_PUBLIC (public)\n     *     |   |--IDENT (myRecord)\n     *     |   `--SLIST ({)\n     *     |       `--RCURLY (})\n     *     `--RCURLY (})\n     * 
    \n *\n * @since 8.36\n */\n public static final int COMPACT_CTOR_DEF =\n GeneratedJavaTokenTypes.COMPACT_CTOR_DEF;\n\n /**\n * Beginning of a Java 14 Text Block literal,\n * delimited by three double quotes.\n *\n *

    For example:

    \n *
    \n     *         String hello = \"\"\"\n     *                 Hello, world!\n     *                 \"\"\";\n     * 
    \n *

    parses as:

    \n *
    \n     * |--VARIABLE_DEF -&gt; VARIABLE_DEF\n     * |   |--MODIFIERS -&gt; MODIFIERS\n     * |   |--TYPE -&gt; TYPE\n     * |   |   `--IDENT -&gt; String\n     * |   |--IDENT -&gt; hello\n     * |   `--ASSIGN -&gt; =\n     * |       `--EXPR -&gt; EXPR\n     * |           `--TEXT_BLOCK_LITERAL_BEGIN -&gt; \"\"\"\n     * |               |--TEXT_BLOCK_CONTENT -&gt; \\n                Hello, world!\\n\n     * |               `--TEXT_BLOCK_LITERAL_END -&gt; \"\"\"\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @since 8.36\n */\n public static final int TEXT_BLOCK_LITERAL_BEGIN =\n GeneratedJavaTokenTypes.TEXT_BLOCK_LITERAL_BEGIN;\n\n /**\n * Content of a Java 14 text block. This is a\n * sequence of characters, possibly escaped with '\\'. Actual line terminators\n * are represented by '\\n'.\n *\n *

    For example:

    \n *
    \n     *         String hello = \"\"\"\n     *                 Hello, world!\n     *                 \"\"\";\n     * 
    \n *

    parses as:

    \n *
    \n     * |--VARIABLE_DEF -&gt; VARIABLE_DEF\n     * |   |--MODIFIERS -&gt; MODIFIERS\n     * |   |--TYPE -&gt; TYPE\n     * |   |   `--IDENT -&gt; String\n     * |   |--IDENT -&gt; hello\n     * |   `--ASSIGN -&gt; =\n     * |       `--EXPR -&gt; EXPR\n     * |           `--TEXT_BLOCK_LITERAL_BEGIN -&gt; \"\"\"\n     * |               |--TEXT_BLOCK_CONTENT -&gt; \\n                Hello, world!\\n\n     * |               `--TEXT_BLOCK_LITERAL_END -&gt; \"\"\"\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @since 8.36\n */\n public static final int TEXT_BLOCK_CONTENT =\n GeneratedJavaTokenTypes.TEXT_BLOCK_CONTENT;\n\n /**\n * End of a Java 14 text block literal, delimited by three\n * double quotes.\n *\n *

    For example:

    \n *
    \n     *         String hello = \"\"\"\n     *                 Hello, world!\n     *                 \"\"\";\n     * 
    \n *

    parses as:

    \n *
    \n     * |--VARIABLE_DEF\n     * |   |--MODIFIERS\n     * |   |--TYPE\n     * |   |   `--IDENT (String)\n     * |   |--IDENT (hello)\n     * |   |--ASSIGN (=)\n     * |   |   `--EXPR\n     * |   |       `--TEXT_BLOCK_LITERAL_BEGIN (\"\"\")\n     * |   |           |--TEXT_BLOCK_CONTENT (\\n                Hello, world!\\n                    )\n     * |   |           `--TEXT_BLOCK_LITERAL_END (\"\"\")\n     * |   `--SEMI (;)\n     * 
    \n *\n * @since 8.36\n */\n public static final int TEXT_BLOCK_LITERAL_END =\n GeneratedJavaTokenTypes.TEXT_BLOCK_LITERAL_END;\n\n /**\n * The {@code yield} keyword. This element appears\n * as part of a yield statement.\n *\n *

    For example:

    \n *
    \n     * int yield = 0; // not a keyword here\n     * return switch (mode) {\n     *    case \"a\", \"b\":\n     *        yield 1;\n     *    default:\n     *        yield - 1;\n     * };\n     * 
    \n *

    parses as:

    \n *
    \n     * |--VARIABLE_DEF\n     * |   |--MODIFIERS\n     * |   |--TYPE\n     * |   |   `--LITERAL_INT (int)\n     * |   |--IDENT (yield)\n     * |   `--ASSIGN (=)\n     * |       `--EXPR\n     * |           `--NUM_INT (0)\n     * |--SEMI (;)\n     * |--LITERAL_RETURN (return)\n     * |   |--EXPR\n     * |   |   `--LITERAL_SWITCH (switch)\n     * |   |       |--LPAREN (()\n     * |   |       |--EXPR\n     * |   |       |   `--IDENT (mode)\n     * |   |       |--RPAREN ())\n     * |   |       |--LCURLY ({)\n     * |   |       |--CASE_GROUP\n     * |   |       |   |--LITERAL_CASE (case)\n     * |   |       |   |   |--EXPR\n     * |   |       |   |   |   `--STRING_LITERAL (\"a\")\n     * |   |       |   |   |--COMMA (,)\n     * |   |       |   |   |--EXPR\n     * |   |       |   |   |   `--STRING_LITERAL (\"b\")\n     * |   |       |   |   `--COLON (:)\n     * |   |       |   `--SLIST\n     * |   |       |       `--LITERAL_YIELD (yield)\n     * |   |       |           |--EXPR\n     * |   |       |           |   `--NUM_INT (1)\n     * |   |       |           `--SEMI (;)\n     * |   |       |--CASE_GROUP\n     * |   |       |   |--LITERAL_DEFAULT (default)\n     * |   |       |   |   `--COLON (:)\n     * |   |       |   `--SLIST\n     * |   |       |       `--LITERAL_YIELD (yield)\n     * |   |       |           |--EXPR\n     * |   |       |           |   `--UNARY_MINUS (-)\n     * |   |       |           |       `--NUM_INT (1)\n     * |   |       |           `--SEMI (;)\n     * |   |       `--RCURLY (})\n     * |   `--SEMI (;)\n     * 
    \n *\n *\n * @see #LITERAL_SWITCH\n * @see #CASE_GROUP\n * @see #SLIST\n * @see #SWITCH_RULE\n *\n * @see \n * Java Language Specification, &sect;14.21\n *\n * @since 8.36\n */\n public static final int LITERAL_YIELD =\n GeneratedJavaTokenTypes.LITERAL_yield;\n\n /**\n * Switch Expressions.\n *\n *

    For example:

    \n *
    \n     * return switch (day) {\n     *     case SAT, SUN {@code ->} \"Weekend\";\n     *     default {@code ->} \"Working day\";\n     * };\n     * 
    \n *

    parses as:

    \n *
    \n     *  LITERAL_RETURN (return)\n     *   |--EXPR\n     *   |   `--LITERAL_SWITCH (switch)\n     *   |       |--LPAREN (()\n     *   |       |--EXPR\n     *   |       |   `--IDENT (day)\n     *   |       |--RPAREN ())\n     *   |       |--LCURLY ({)\n     *   |       |--SWITCH_RULE\n     *   |       |   |--LITERAL_CASE (case)\n     *   |       |   |   |--EXPR\n     *   |       |   |   |   `--IDENT (SAT)\n     *   |       |   |   |--COMMA (,)\n     *   |       |   |   `--EXPR\n     *   |       |   |       `--IDENT (SUN)\n     *   |       |   |--LAMBDA {@code ->}\n     *   |       |   |--EXPR\n     *   |       |   |   `--STRING_LITERAL (\"Weekend\")\n     *   |       |   `--SEMI (;)\n     *   |       |--SWITCH_RULE\n     *   |       |   |--LITERAL_DEFAULT (default)\n     *   |       |   |--LAMBDA {@code ->}\n     *   |       |   |--EXPR\n     *   |       |   |   `--STRING_LITERAL (\"Working day\")\n     *   |       |   `--SEMI (;)\n     *   |       `--RCURLY (})\n     *   `--SEMI (;)\n     * 
    \n *\n * @see #LITERAL_CASE\n * @see #LITERAL_DEFAULT\n * @see #LITERAL_SWITCH\n * @see #LITERAL_YIELD\n *\n * @see \n * Java Language Specification, &sect;14.21\n *\n * @since 8.36\n */\n public static final int SWITCH_RULE =\n GeneratedJavaTokenTypes.SWITCH_RULE;\n\n /** Prevent instantiation. */\n private TokenTypes() {\n }\n\n}\n"},"new_file":{"kind":"string","value":"src/main/java/com/puppycrawl/tools/checkstyle/api/TokenTypes.java"},"old_contents":{"kind":"string","value":"////////////////////////////////////////////////////////////////////////////////\n// checkstyle: Checks Java source code for adherence to a set of rules.\n// Copyright (C) 2001-2021 the original author or authors.\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 2.1 of the License, or (at your option) any later version.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n////////////////////////////////////////////////////////////////////////////////\n\npackage com.puppycrawl.tools.checkstyle.api;\n\nimport com.puppycrawl.tools.checkstyle.grammar.GeneratedJavaTokenTypes;\n\n/**\n * Contains the constants for all the tokens contained in the Abstract\n * Syntax Tree.\n *\n *

    Implementation detail: This class has been introduced to break\n * the circular dependency between packages.

    \n *\n * @noinspection ClassWithTooManyDependents\n */\npublic final class TokenTypes {\n\n /**\n * The end of file token. This is the root node for the source\n * file. It's children are an optional package definition, zero\n * or more import statements, and one or more class or interface\n * definitions.\n *\n * @see #PACKAGE_DEF\n * @see #IMPORT\n * @see #CLASS_DEF\n * @see #INTERFACE_DEF\n **/\n public static final int EOF = GeneratedJavaTokenTypes.EOF;\n /**\n * Modifiers for type, method, and field declarations. The\n * modifiers element is always present even though it may have no\n * children.\n *\n * @see Java\n * Language Specification, &sect;8\n * @see #LITERAL_PUBLIC\n * @see #LITERAL_PROTECTED\n * @see #LITERAL_PRIVATE\n * @see #ABSTRACT\n * @see #LITERAL_STATIC\n * @see #FINAL\n * @see #LITERAL_TRANSIENT\n * @see #LITERAL_VOLATILE\n * @see #LITERAL_SYNCHRONIZED\n * @see #LITERAL_NATIVE\n * @see #STRICTFP\n * @see #ANNOTATION\n * @see #LITERAL_DEFAULT\n **/\n public static final int MODIFIERS = GeneratedJavaTokenTypes.MODIFIERS;\n\n /**\n * An object block. These are children of class, interface, enum,\n * annotation and enum constant declarations.\n * Also, object blocks are children of the new keyword when defining\n * anonymous inner types.\n *\n * @see #LCURLY\n * @see #INSTANCE_INIT\n * @see #STATIC_INIT\n * @see #CLASS_DEF\n * @see #CTOR_DEF\n * @see #METHOD_DEF\n * @see #VARIABLE_DEF\n * @see #RCURLY\n * @see #INTERFACE_DEF\n * @see #LITERAL_NEW\n * @see #ENUM_DEF\n * @see #ENUM_CONSTANT_DEF\n * @see #ANNOTATION_DEF\n **/\n public static final int OBJBLOCK = GeneratedJavaTokenTypes.OBJBLOCK;\n /**\n * A list of statements.\n *\n *

    For example:

    \n *
    \n     * if (c == 1) {\n     *     c = 0;\n     * }\n     * 
    \n *

    parses as:

    \n *
    \n     * LITERAL_IF -&gt; if\n     *  |--LPAREN -&gt; (\n     *  |--EXPR -&gt; EXPR\n     *  |   `--EQUAL -&gt; ==\n     *  |       |--IDENT -&gt; c\n     *  |       `--NUM_INT -&gt; 1\n     *  |--RPAREN -&gt; )\n     *  `--SLIST -&gt; {\n     *      |--EXPR -&gt; EXPR\n     *      |   `--ASSIGN -&gt; =\n     *      |       |--IDENT -&gt; c\n     *      |       `--NUM_INT -&gt; 0\n     *      |--SEMI -&gt; ;\n     *      `--RCURLY -&gt; }\n     * 
    \n *\n * @see #RCURLY\n * @see #EXPR\n * @see #LABELED_STAT\n * @see #LITERAL_THROWS\n * @see #LITERAL_RETURN\n * @see #SEMI\n * @see #METHOD_DEF\n * @see #CTOR_DEF\n * @see #LITERAL_FOR\n * @see #LITERAL_WHILE\n * @see #LITERAL_IF\n * @see #LITERAL_ELSE\n * @see #CASE_GROUP\n **/\n public static final int SLIST = GeneratedJavaTokenTypes.SLIST;\n /**\n * A constructor declaration.\n *\n *

    For example:

    \n *
    \n     * public SpecialEntry(int value, String text)\n     * {\n     *   this.value = value;\n     *   this.text = text;\n     * }\n     * 
    \n *

    parses as:

    \n *
    \n     * +--CTOR_DEF\n     *     |\n     *     +--MODIFIERS\n     *         |\n     *         +--LITERAL_PUBLIC (public)\n     *     +--IDENT (SpecialEntry)\n     *     +--LPAREN (()\n     *     +--PARAMETERS\n     *         |\n     *         +--PARAMETER_DEF\n     *             |\n     *             +--MODIFIERS\n     *             +--TYPE\n     *                 |\n     *                 +--LITERAL_INT (int)\n     *             +--IDENT (value)\n     *         +--COMMA (,)\n     *         +--PARAMETER_DEF\n     *             |\n     *             +--MODIFIERS\n     *             +--TYPE\n     *                 |\n     *                 +--IDENT (String)\n     *             +--IDENT (text)\n     *     +--RPAREN ())\n     *     +--SLIST ({)\n     *         |\n     *         +--EXPR\n     *             |\n     *             +--ASSIGN (=)\n     *                 |\n     *                 +--DOT (.)\n     *                     |\n     *                     +--LITERAL_THIS (this)\n     *                     +--IDENT (value)\n     *                 +--IDENT (value)\n     *         +--SEMI (;)\n     *         +--EXPR\n     *             |\n     *             +--ASSIGN (=)\n     *                 |\n     *                 +--DOT (.)\n     *                     |\n     *                     +--LITERAL_THIS (this)\n     *                     +--IDENT (text)\n     *                 +--IDENT (text)\n     *         +--SEMI (;)\n     *         +--RCURLY (})\n     * 
    \n *\n * @see #OBJBLOCK\n * @see #CLASS_DEF\n **/\n public static final int CTOR_DEF = GeneratedJavaTokenTypes.CTOR_DEF;\n /**\n * A method declaration. The children are modifiers, type parameters,\n * return type, method name, parameter list, an optional throws list, and\n * statement list. The statement list is omitted if the method\n * declaration appears in an interface declaration. Method\n * declarations may appear inside object blocks of class\n * declarations, interface declarations, enum declarations,\n * enum constant declarations or anonymous inner-class declarations.\n *\n *

    For example:

    \n *\n *
    \n     *  public static int square(int x)\n     *  {\n     *    return x*x;\n     *  }\n     * 
    \n *\n *

    parses as:

    \n *\n *
    \n     * --METHOD_DEF -&gt; METHOD_DEF\n     *    |--MODIFIERS -&gt; MODIFIERS\n     *    |   |--LITERAL_PUBLIC -&gt; public\n     *    |   `--LITERAL_STATIC -&gt; static\n     *    |--TYPE -&gt; TYPE\n     *    |   `--LITERAL_INT -&gt; int\n     *    |--IDENT -&gt; square\n     *    |--LPAREN -&gt; (\n     *    |--PARAMETERS -&gt; PARAMETERS\n     *    |   `--PARAMETER_DEF -&gt; PARAMETER_DEF\n     *    |       |--MODIFIERS -&gt; MODIFIERS\n     *    |       |--TYPE -&gt; TYPE\n     *    |       |   `--LITERAL_INT -&gt; int\n     *    |       `--IDENT -&gt; x\n     *    |--RPAREN -&gt; )\n     *    `--SLIST -&gt; {\n     *        |--LITERAL_RETURN -&gt; return\n     *        |   |--EXPR -&gt; EXPR\n     *        |   |   `--STAR -&gt; *\n     *        |   |       |--IDENT -&gt; x\n     *        |   |       `--IDENT -&gt; x\n     *        |   `--SEMI -&gt; ;\n     *        `--RCURLY -&gt; }\n     * 
    \n *\n * @see #MODIFIERS\n * @see #TYPE_PARAMETERS\n * @see #TYPE\n * @see #IDENT\n * @see #PARAMETERS\n * @see #LITERAL_THROWS\n * @see #SLIST\n * @see #OBJBLOCK\n **/\n public static final int METHOD_DEF = GeneratedJavaTokenTypes.METHOD_DEF;\n /**\n * A field or local variable declaration. The children are\n * modifiers, type, the identifier name, and an optional\n * assignment statement.\n *\n * @see #MODIFIERS\n * @see #TYPE\n * @see #IDENT\n * @see #ASSIGN\n **/\n public static final int VARIABLE_DEF =\n GeneratedJavaTokenTypes.VARIABLE_DEF;\n\n /**\n * An instance initializer. Zero or more instance initializers\n * may appear in class and enum definitions. This token will be a child\n * of the object block of the declaring type.\n *\n * @see Java\n * Language Specification&sect;8.6\n * @see #SLIST\n * @see #OBJBLOCK\n **/\n public static final int INSTANCE_INIT =\n GeneratedJavaTokenTypes.INSTANCE_INIT;\n\n /**\n * A static initialization block. Zero or more static\n * initializers may be children of the object block of a class\n * or enum declaration (interfaces cannot have static initializers). The\n * first and only child is a statement list.\n *\n * @see Java\n * Language Specification, &sect;8.7\n * @see #SLIST\n * @see #OBJBLOCK\n **/\n public static final int STATIC_INIT =\n GeneratedJavaTokenTypes.STATIC_INIT;\n\n /**\n * A type. This is either a return type of a method or a type of\n * a variable or field. The first child of this element is the\n * actual type. This may be a primitive type, an identifier, a\n * dot which is the root of a fully qualified type, or an array of\n * any of these. The second child may be type arguments to the type.\n *\n *

    For example:

    \n *
    boolean var = true;
    \n *

    parses as:

    \n *
    \n     * |--VARIABLE_DEF -&gt; VARIABLE_DEF\n     * |   |--MODIFIERS -&gt; MODIFIERS\n     * |   |--TYPE -&gt; TYPE\n     * |   |   `--LITERAL_BOOLEAN -&gt; boolean\n     * |   |--IDENT -&gt; var\n     * |   `--ASSIGN -&gt; =\n     * |       `--EXPR -&gt; EXPR\n     * |           `--LITERAL_TRUE -&gt; true\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see #VARIABLE_DEF\n * @see #METHOD_DEF\n * @see #PARAMETER_DEF\n * @see #IDENT\n * @see #DOT\n * @see #LITERAL_VOID\n * @see #LITERAL_BOOLEAN\n * @see #LITERAL_BYTE\n * @see #LITERAL_CHAR\n * @see #LITERAL_SHORT\n * @see #LITERAL_INT\n * @see #LITERAL_FLOAT\n * @see #LITERAL_LONG\n * @see #LITERAL_DOUBLE\n * @see #ARRAY_DECLARATOR\n * @see #TYPE_ARGUMENTS\n **/\n public static final int TYPE = GeneratedJavaTokenTypes.TYPE;\n /**\n * A class declaration.\n *\n *

    For example:

    \n *
    \n     * public class MyClass\n     *   implements Serializable\n     * {\n     * }\n     * 
    \n *

    parses as:

    \n *
    \n     * +--CLASS_DEF\n     *     |\n     *     +--MODIFIERS\n     *         |\n     *         +--LITERAL_PUBLIC (public)\n     *     +--LITERAL_CLASS (class)\n     *     +--IDENT (MyClass)\n     *     +--EXTENDS_CLAUSE\n     *     +--IMPLEMENTS_CLAUSE\n     *         |\n     *         +--IDENT (Serializable)\n     *     +--OBJBLOCK\n     *         |\n     *         +--LCURLY ({)\n     *         +--RCURLY (})\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;8\n * @see #MODIFIERS\n * @see #IDENT\n * @see #EXTENDS_CLAUSE\n * @see #IMPLEMENTS_CLAUSE\n * @see #OBJBLOCK\n * @see #LITERAL_NEW\n **/\n public static final int CLASS_DEF = GeneratedJavaTokenTypes.CLASS_DEF;\n /**\n * An interface declaration.\n *\n *

    For example:

    \n *\n *
    \n     *   public interface MyInterface\n     *   {\n     *   }\n     *\n     * 
    \n *\n *

    parses as:

    \n *\n *
    \n     * +--INTERFACE_DEF\n     *     |\n     *     +--MODIFIERS\n     *         |\n     *         +--LITERAL_PUBLIC (public)\n     *     +--LITERAL_INTERFACE (interface)\n     *     +--IDENT (MyInterface)\n     *     +--EXTENDS_CLAUSE\n     *     +--OBJBLOCK\n     *         |\n     *         +--LCURLY ({)\n     *         +--RCURLY (})\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;9\n * @see #MODIFIERS\n * @see #IDENT\n * @see #EXTENDS_CLAUSE\n * @see #OBJBLOCK\n **/\n public static final int INTERFACE_DEF =\n GeneratedJavaTokenTypes.INTERFACE_DEF;\n\n /**\n * The package declaration. This is optional, but if it is\n * included, then there is only one package declaration per source\n * file and it must be the first non-comment in the file. A package\n * declaration may be annotated in which case the annotations comes\n * before the rest of the declaration (and are the first children).\n *\n *

    For example:

    \n *\n *
    \n     *   package com.puppycrawl.tools.checkstyle.api;\n     * 
    \n *\n *

    parses as:

    \n *\n *
    \n     * PACKAGE_DEF -&gt; package\n     * |--ANNOTATIONS -&gt; ANNOTATIONS\n     * |--DOT -&gt; .\n     * |   |--DOT -&gt; .\n     * |   |   |--DOT -&gt; .\n     * |   |   |   |--DOT -&gt; .\n     * |   |   |   |   |--IDENT -&gt; com\n     * |   |   |   |   `--IDENT -&gt; puppycrawl\n     * |   |   |   `--IDENT -&gt; tools\n     * |   |   `--IDENT -&gt; checkstyle\n     * |   `--IDENT -&gt; api\n     * `--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification &sect;7.4\n * @see #DOT\n * @see #IDENT\n * @see #SEMI\n * @see #ANNOTATIONS\n * @see FullIdent\n **/\n public static final int PACKAGE_DEF = GeneratedJavaTokenTypes.PACKAGE_DEF;\n /**\n * An array declaration.\n *\n *

    If the array declaration represents a type, then the type of\n * the array elements is the first child. Multidimensional arrays\n * may be regarded as arrays of arrays. In other words, the first\n * child of the array declaration is another array\n * declaration.

    \n *\n *

    For example:

    \n *
    \n     *   int[] x;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--VARIABLE_DEF -&gt; VARIABLE_DEF\n     * |   |--MODIFIERS -&gt; MODIFIERS\n     * |   |--TYPE -&gt; TYPE\n     * |   |   `--ARRAY_DECLARATOR -&gt; [\n     * |   |       |--LITERAL_INT -&gt; int\n     * |   |       `--RBRACK -&gt; ]\n     * |   |--IDENT -&gt; x\n     * |--SEMI -&gt; ;\n     * 
    \n *\n *

    The array declaration may also represent an inline array\n * definition. In this case, the first child will be either an\n * expression specifying the length of the array or an array\n * initialization block.

    \n *\n * @see Java\n * Language Specification &sect;10\n * @see #TYPE\n * @see #ARRAY_INIT\n **/\n public static final int ARRAY_DECLARATOR =\n GeneratedJavaTokenTypes.ARRAY_DECLARATOR;\n\n /**\n * An extends clause. This appear as part of class and interface\n * definitions. This element appears even if the\n * {@code extends} keyword is not explicitly used. The child\n * is an optional identifier.\n *\n *

    For example:

    \n *\n *
    \n     * extends java.util.LinkedList\n     * 
    \n *\n *

    parses as:

    \n *
    \n     * +--EXTENDS_CLAUSE\n     *     |\n     *     +--DOT (.)\n     *         |\n     *         +--DOT (.)\n     *             |\n     *             +--IDENT (java)\n     *             +--IDENT (util)\n     *         +--IDENT (LinkedList)\n     * 
    \n *\n * @see #IDENT\n * @see #DOT\n * @see #CLASS_DEF\n * @see #INTERFACE_DEF\n * @see FullIdent\n **/\n public static final int EXTENDS_CLAUSE =\n GeneratedJavaTokenTypes.EXTENDS_CLAUSE;\n\n /**\n * An implements clause. This always appears in a class or enum\n * declaration, even if there are no implemented interfaces. The\n * children are a comma separated list of zero or more\n * identifiers.\n *\n *

    For example:

    \n *
    \n     * implements Serializable, Comparable\n     * 
    \n *

    parses as:

    \n *
    \n     * +--IMPLEMENTS_CLAUSE\n     *     |\n     *     +--IDENT (Serializable)\n     *     +--COMMA (,)\n     *     +--IDENT (Comparable)\n     * 
    \n *\n * @see #IDENT\n * @see #DOT\n * @see #COMMA\n * @see #CLASS_DEF\n * @see #ENUM_DEF\n **/\n public static final int IMPLEMENTS_CLAUSE =\n GeneratedJavaTokenTypes.IMPLEMENTS_CLAUSE;\n\n /**\n * A list of parameters to a method or constructor. The children\n * are zero or more parameter declarations separated by commas.\n *\n *

    For example

    \n *
    \n     * int start, int end\n     * 
    \n *

    parses as:

    \n *
    \n     * +--PARAMETERS\n     *     |\n     *     +--PARAMETER_DEF\n     *         |\n     *         +--MODIFIERS\n     *         +--TYPE\n     *             |\n     *             +--LITERAL_INT (int)\n     *         +--IDENT (start)\n     *     +--COMMA (,)\n     *     +--PARAMETER_DEF\n     *         |\n     *         +--MODIFIERS\n     *         +--TYPE\n     *             |\n     *             +--LITERAL_INT (int)\n     *         +--IDENT (end)\n     * 
    \n *\n * @see #PARAMETER_DEF\n * @see #COMMA\n * @see #METHOD_DEF\n * @see #CTOR_DEF\n **/\n public static final int PARAMETERS = GeneratedJavaTokenTypes.PARAMETERS;\n /**\n * A parameter declaration. The last parameter in a list of parameters may\n * be variable length (indicated by the ELLIPSIS child node immediately\n * after the TYPE child).\n *\n * @see #MODIFIERS\n * @see #TYPE\n * @see #IDENT\n * @see #PARAMETERS\n * @see #ELLIPSIS\n **/\n public static final int PARAMETER_DEF =\n GeneratedJavaTokenTypes.PARAMETER_DEF;\n\n /**\n * A labeled statement.\n *\n *

    For example:

    \n *
    \n     * outside: ;\n     * 
    \n *

    parses as:

    \n *
    \n     * +--LABELED_STAT (:)\n     *     |\n     *     +--IDENT (outside)\n     *     +--EMPTY_STAT (;)\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;14.7\n * @see #SLIST\n **/\n public static final int LABELED_STAT =\n GeneratedJavaTokenTypes.LABELED_STAT;\n\n /**\n * A type-cast.\n *\n *

    For example:

    \n *
    \n     * (String)it.next()\n     * 
    \n *

    parses as:

    \n *
    \n     * `--TYPECAST -&gt; (\n     *     |--TYPE -&gt; TYPE\n     *     |   `--IDENT -&gt; String\n     *     |--RPAREN -&gt; )\n     *     `--METHOD_CALL -&gt; (\n     *         |--DOT -&gt; .\n     *         |   |--IDENT -&gt; it\n     *         |   `--IDENT -&gt; next\n     *         |--ELIST -&gt; ELIST\n     *         `--RPAREN -&gt; )\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.16\n * @see #EXPR\n * @see #TYPE\n * @see #TYPE_ARGUMENTS\n * @see #RPAREN\n **/\n public static final int TYPECAST = GeneratedJavaTokenTypes.TYPECAST;\n /**\n * The array index operator.\n *\n *

    For example:

    \n *
    \n     * ar[2] = 5;\n     * 
    \n *

    parses as:

    \n *
    \n     * +--EXPR\n     *     |\n     *     +--ASSIGN (=)\n     *         |\n     *         +--INDEX_OP ([)\n     *             |\n     *             +--IDENT (ar)\n     *             +--EXPR\n     *                 |\n     *                 +--NUM_INT (2)\n     *         +--NUM_INT (5)\n     * +--SEMI (;)\n     * 
    \n *\n * @see #EXPR\n **/\n public static final int INDEX_OP = GeneratedJavaTokenTypes.INDEX_OP;\n /**\n * The {@code ++} (postfix increment) operator.\n *\n *

    For example:

    \n *
    \n     * a++;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--POST_INC -&gt; ++\n     * |       `--IDENT -&gt; a\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.14.1\n * @see #EXPR\n * @see #INC\n **/\n public static final int POST_INC = GeneratedJavaTokenTypes.POST_INC;\n /**\n * The {@code --} (postfix decrement) operator.\n *\n *

    For example:

    \n *
    \n     * a--;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--POST_DEC -&gt; --\n     * |       `--IDENT -&gt; a\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.14.2\n * @see #EXPR\n * @see #DEC\n **/\n public static final int POST_DEC = GeneratedJavaTokenTypes.POST_DEC;\n /**\n * A method call. A method call may have type arguments however these\n * are attached to the appropriate node in the qualified method name.\n *\n *

    For example:

    \n *
    \n     * Integer.parseInt(\"123\");\n     * 
    \n *\n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--METHOD_CALL -&gt; (\n     * |       |--DOT -&gt; .\n     * |       |   |--IDENT -&gt; Integer\n     * |       |   `--IDENT -&gt; parseInt\n     * |       |--ELIST -&gt; ELIST\n     * |       |   `--EXPR -&gt; EXPR\n     * |       |       `--STRING_LITERAL -&gt; \"123\"\n     * |       `--RPAREN -&gt; )\n     * |--SEMI -&gt; ;\n     * 
    \n *\n *\n * @see #IDENT\n * @see #TYPE_ARGUMENTS\n * @see #DOT\n * @see #ELIST\n * @see #RPAREN\n * @see FullIdent\n **/\n public static final int METHOD_CALL = GeneratedJavaTokenTypes.METHOD_CALL;\n\n /**\n * A reference to a method or constructor without arguments. Part of Java 8 syntax.\n * The token should be used for subscribing for double colon literal.\n * {@link #DOUBLE_COLON} token does not appear in the tree.\n *\n *

    For example:

    \n *
    \n     * String::compareToIgnoreCase\n     * 
    \n *\n *

    parses as:\n *

    \n     * +--METHOD_REF (::)\n     *     |\n     *     +--IDENT (String)\n     *     +--IDENT (compareToIgnoreCase)\n     * 
    \n *\n * @see #IDENT\n * @see #DOUBLE_COLON\n */\n public static final int METHOD_REF = GeneratedJavaTokenTypes.METHOD_REF;\n /**\n * An expression. Operators with lower precedence appear at a\n * higher level in the tree than operators with higher precedence.\n * Parentheses are siblings to the operator they enclose.\n *\n *

    For example:

    \n *
    \n     * x = 4 + 3 * 5 + (30 + 26) / 4 + 5 % 4 + (1&lt;&lt;3);\n     * 
    \n *

    parses as:

    \n *
    \n     * +--EXPR\n     *     |\n     *     +--ASSIGN (=)\n     *         |\n     *         +--IDENT (x)\n     *         +--PLUS (+)\n     *             |\n     *             +--PLUS (+)\n     *                 |\n     *                 +--PLUS (+)\n     *                     |\n     *                     +--PLUS (+)\n     *                         |\n     *                         +--NUM_INT (4)\n     *                         +--STAR (*)\n     *                             |\n     *                             +--NUM_INT (3)\n     *                             +--NUM_INT (5)\n     *                     +--DIV (/)\n     *                         |\n     *                         +--LPAREN (()\n     *                         +--PLUS (+)\n     *                             |\n     *                             +--NUM_INT (30)\n     *                             +--NUM_INT (26)\n     *                         +--RPAREN ())\n     *                         +--NUM_INT (4)\n     *                 +--MOD (%)\n     *                     |\n     *                     +--NUM_INT (5)\n     *                     +--NUM_INT (4)\n     *             +--LPAREN (()\n     *             +--SL (&lt;&lt;)\n     *                 |\n     *                 +--NUM_INT (1)\n     *                 +--NUM_INT (3)\n     *             +--RPAREN ())\n     * +--SEMI (;)\n     * 
    \n *\n * @see #ELIST\n * @see #ASSIGN\n * @see #LPAREN\n * @see #RPAREN\n **/\n public static final int EXPR = GeneratedJavaTokenTypes.EXPR;\n /**\n * An array initialization. This may occur as part of an array\n * declaration or inline with {@code new}.\n *\n *

    For example:

    \n *
    \n     *   int[] y =\n     *     {\n     *       1,\n     *       2,\n     *     };\n     * 
    \n *

    parses as:

    \n *
    \n     * |--VARIABLE_DEF -&gt; VARIABLE_DEF\n     * |   |--MODIFIERS -&gt; MODIFIERS\n     * |   |--TYPE -&gt; TYPE\n     * |   |   `--ARRAY_DECLARATOR -&gt; [\n     * |   |       |--LITERAL_INT -&gt; int\n     * |   |       `--RBRACK -&gt; ]\n     * |   |--IDENT -&gt; y\n     * |   `--ASSIGN -&gt; =\n     * |       `--ARRAY_INIT -&gt; {\n     * |           |--EXPR -&gt; EXPR\n     * |           |   `--NUM_INT -&gt; 1\n     * |           |--COMMA -&gt; ,\n     * |           |--EXPR -&gt; EXPR\n     * |           |   `--NUM_INT -&gt; 2\n     * |           |--COMMA -&gt; ,\n     * |           `--RCURLY -&gt; }\n     * |--SEMI -&gt; ;\n     * 
    \n *\n *

    Also consider:

    \n *
    \n     *   int[] z = new int[]\n     *     {\n     *       1,\n     *       2,\n     *     };\n     * 
    \n *

    which parses as:

    \n *
    \n     * |--VARIABLE_DEF -&gt; VARIABLE_DEF\n     * |   |--MODIFIERS -&gt; MODIFIERS\n     * |   |--TYPE -&gt; TYPE\n     * |   |   `--ARRAY_DECLARATOR -&gt; [\n     * |   |       |--LITERAL_INT -&gt; int\n     * |   |       `--RBRACK -&gt; ]\n     * |   |--IDENT -&gt; z\n     * |   `--ASSIGN -&gt; =\n     * |       `--EXPR -&gt; EXPR\n     * |           `--LITERAL_NEW -&gt; new\n     * |               |--LITERAL_INT -&gt; int\n     * |               |--ARRAY_DECLARATOR -&gt; [\n     * |               |   `--RBRACK -&gt; ]\n     * |               `--ARRAY_INIT -&gt; {\n     * |                   |--EXPR -&gt; EXPR\n     * |                   |   `--NUM_INT -&gt; 1\n     * |                   |--COMMA -&gt; ,\n     * |                   |--EXPR -&gt; EXPR\n     * |                   |   `--NUM_INT -&gt; 2\n     * |                   |--COMMA -&gt; ,\n     * |                   `--RCURLY -&gt; }\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see #ARRAY_DECLARATOR\n * @see #TYPE\n * @see #LITERAL_NEW\n * @see #COMMA\n **/\n public static final int ARRAY_INIT = GeneratedJavaTokenTypes.ARRAY_INIT;\n /**\n * An import declaration. Import declarations are option, but\n * must appear after the package declaration and before the first type\n * declaration.\n *\n *

    For example:

    \n *\n *
    \n     *   import java.io.IOException;\n     * 
    \n *\n *

    parses as:

    \n *\n *
    \n     * IMPORT -&gt; import\n     * |--DOT -&gt; .\n     * |   |--DOT -&gt; .\n     * |   |   |--IDENT -&gt; java\n     * |   |   `--IDENT -&gt; io\n     * |   `--IDENT -&gt; IOException\n     * `--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification &sect;7.5\n * @see #DOT\n * @see #IDENT\n * @see #STAR\n * @see #SEMI\n * @see FullIdent\n **/\n public static final int IMPORT = GeneratedJavaTokenTypes.IMPORT;\n /**\n * The {@code -} (unary minus) operator.\n *\n * @see Java\n * Language Specification, &sect;15.15.4\n * @see #EXPR\n **/\n public static final int UNARY_MINUS = GeneratedJavaTokenTypes.UNARY_MINUS;\n /**\n * The {@code +} (unary plus) operator.\n *

    For example:

    \n *
    \n     * a = + b;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--ASSIGN -&gt; =\n     * |       |--IDENT -&gt; a\n     * |       `--UNARY_PLUS -&gt; +\n     * |           `--IDENT -&gt; b\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.15.3\n * @see #EXPR\n **/\n public static final int UNARY_PLUS = GeneratedJavaTokenTypes.UNARY_PLUS;\n /**\n * A group of case clauses. Case clauses with no associated\n * statements are grouped together into a case group. The last\n * child is a statement list containing the statements to execute\n * upon a match.\n *\n *

    For example:

    \n *
    \n     * case 0:\n     * case 1:\n     * case 2:\n     *   x = 3;\n     *   break;\n     * 
    \n *

    parses as:

    \n *
    \n     * +--CASE_GROUP\n     *     |\n     *     +--LITERAL_CASE (case)\n     *         |\n     *         +--EXPR\n     *             |\n     *             +--NUM_INT (0)\n     *     +--LITERAL_CASE (case)\n     *         |\n     *         +--EXPR\n     *             |\n     *             +--NUM_INT (1)\n     *     +--LITERAL_CASE (case)\n     *         |\n     *         +--EXPR\n     *             |\n     *             +--NUM_INT (2)\n     *     +--SLIST\n     *         |\n     *         +--EXPR\n     *             |\n     *             +--ASSIGN (=)\n     *                 |\n     *                 +--IDENT (x)\n     *                 +--NUM_INT (3)\n     *         +--SEMI (;)\n     *         +--LITERAL_BREAK (break)\n     *             |\n     *             +--SEMI (;)\n     * 
    \n *\n * @see #LITERAL_CASE\n * @see #LITERAL_DEFAULT\n * @see #LITERAL_SWITCH\n * @see #LITERAL_YIELD\n **/\n public static final int CASE_GROUP = GeneratedJavaTokenTypes.CASE_GROUP;\n /**\n * An expression list. The children are a comma separated list of\n * expressions.\n *\n * @see #LITERAL_NEW\n * @see #FOR_INIT\n * @see #FOR_ITERATOR\n * @see #EXPR\n * @see #METHOD_CALL\n * @see #CTOR_CALL\n * @see #SUPER_CTOR_CALL\n **/\n public static final int ELIST = GeneratedJavaTokenTypes.ELIST;\n /**\n * A for loop initializer. This is a child of\n * {@code LITERAL_FOR}. The children of this element may be\n * a comma separated list of variable declarations, an expression\n * list, or empty.\n *\n * @see #VARIABLE_DEF\n * @see #ELIST\n * @see #LITERAL_FOR\n **/\n public static final int FOR_INIT = GeneratedJavaTokenTypes.FOR_INIT;\n /**\n * A for loop condition. This is a child of\n * {@code LITERAL_FOR}. The child of this element is an\n * optional expression.\n *\n * @see #EXPR\n * @see #LITERAL_FOR\n **/\n public static final int FOR_CONDITION =\n GeneratedJavaTokenTypes.FOR_CONDITION;\n\n /**\n * A for loop iterator. This is a child of\n * {@code LITERAL_FOR}. The child of this element is an\n * optional expression list.\n *\n * @see #ELIST\n * @see #LITERAL_FOR\n **/\n public static final int FOR_ITERATOR =\n GeneratedJavaTokenTypes.FOR_ITERATOR;\n\n /**\n * The empty statement. This goes in place of an\n * {@code SLIST} for a {@code for} or {@code while}\n * loop body.\n *\n * @see Java\n * Language Specification, &sect;14.6\n * @see #LITERAL_FOR\n * @see #LITERAL_WHILE\n **/\n public static final int EMPTY_STAT = GeneratedJavaTokenTypes.EMPTY_STAT;\n /**\n * The {@code final} keyword.\n *\n * @see #MODIFIERS\n **/\n public static final int FINAL = GeneratedJavaTokenTypes.FINAL;\n /**\n * The {@code abstract} keyword.\n *\n *

    For example:

    \n *
    \n     *  public abstract class MyClass\n     *  {\n     *  }\n     * 
    \n *

    parses as:

    \n *
    \n     * --CLASS_DEF\n     *    |--MODIFIERS\n     *    |   |--LITERAL_PUBLIC (public)\n     *    |   `--ABSTRACT (abstract)\n     *    |--LITERAL_CLASS (class)\n     *    |--IDENT (MyClass)\n     *    `--OBJBLOCK\n     *        |--LCURLY ({)\n     *        `--RCURLY (})\n     * 
    \n *\n * @see #MODIFIERS\n **/\n public static final int ABSTRACT = GeneratedJavaTokenTypes.ABSTRACT;\n /**\n * The {@code strictfp} keyword.\n *\n *

    For example:

    \n *
    public strictfp class Test {}
    \n *\n *

    parses as:

    \n *
    \n     * CLASS_DEF -&gt; CLASS_DEF\n     * |--MODIFIERS -&gt; MODIFIERS\n     * |   |--LITERAL_PUBLIC -&gt; public\n     * |   `--STRICTFP -&gt; strictfp\n     * |--LITERAL_CLASS -&gt; class\n     * |--IDENT -&gt; Test\n     * `--OBJBLOCK -&gt; OBJBLOCK\n     *     |--LCURLY -&gt; {\n     *     `--RCURLY -&gt; }\n     * 
    \n *\n * @see #MODIFIERS\n **/\n public static final int STRICTFP = GeneratedJavaTokenTypes.STRICTFP;\n /**\n * A super constructor call.\n *\n * @see #ELIST\n * @see #RPAREN\n * @see #SEMI\n * @see #CTOR_CALL\n **/\n public static final int SUPER_CTOR_CALL =\n GeneratedJavaTokenTypes.SUPER_CTOR_CALL;\n\n /**\n * A constructor call.\n *\n *

    For example:

    \n *
    \n     * this(1);\n     * 
    \n *

    parses as:

    \n *
    \n     * +--CTOR_CALL (this)\n     *     |\n     *     +--LPAREN (()\n     *     +--ELIST\n     *         |\n     *         +--EXPR\n     *             |\n     *             +--NUM_INT (1)\n     *     +--RPAREN ())\n     *     +--SEMI (;)\n     * 
    \n *\n * @see #ELIST\n * @see #RPAREN\n * @see #SEMI\n * @see #SUPER_CTOR_CALL\n **/\n public static final int CTOR_CALL = GeneratedJavaTokenTypes.CTOR_CALL;\n\n /**\n * The statement terminator ({@code ;}). Depending on the\n * context, this make occur as a sibling, a child, or not at all.\n *\n *

    For example:

    \n *
    \n     * for(;;);\n     * 
    \n *

    parses as:

    \n *
    \n     * LITERAL_FOR -&gt; for\n     *  |--LPAREN -&gt; (\n     *  |--FOR_INIT -&gt; FOR_INIT\n     *  |--SEMI -&gt; ;\n     *  |--FOR_CONDITION -&gt; FOR_CONDITION\n     *  |--SEMI -&gt; ;\n     *  |--FOR_ITERATOR -&gt; FOR_ITERATOR\n     *  |--RPAREN -&gt; )\n     *  `--EMPTY_STAT -&gt; ;\n     * 
    \n *\n * @see #PACKAGE_DEF\n * @see #IMPORT\n * @see #SLIST\n * @see #ARRAY_INIT\n * @see #LITERAL_FOR\n **/\n public static final int SEMI = GeneratedJavaTokenTypes.SEMI;\n\n /**\n * The {@code ]} symbol.\n *\n * @see #INDEX_OP\n * @see #ARRAY_DECLARATOR\n **/\n public static final int RBRACK = GeneratedJavaTokenTypes.RBRACK;\n /**\n * The {@code void} keyword.\n *\n * @see #TYPE\n **/\n public static final int LITERAL_VOID =\n GeneratedJavaTokenTypes.LITERAL_void;\n\n /**\n * The {@code boolean} keyword.\n *\n * @see #TYPE\n **/\n public static final int LITERAL_BOOLEAN =\n GeneratedJavaTokenTypes.LITERAL_boolean;\n\n /**\n * The {@code byte} keyword.\n *\n * @see #TYPE\n **/\n public static final int LITERAL_BYTE =\n GeneratedJavaTokenTypes.LITERAL_byte;\n\n /**\n * The {@code char} keyword.\n *\n * @see #TYPE\n **/\n public static final int LITERAL_CHAR =\n GeneratedJavaTokenTypes.LITERAL_char;\n\n /**\n * The {@code short} keyword.\n *\n * @see #TYPE\n **/\n public static final int LITERAL_SHORT =\n GeneratedJavaTokenTypes.LITERAL_short;\n\n /**\n * The {@code int} keyword.\n *\n * @see #TYPE\n **/\n public static final int LITERAL_INT = GeneratedJavaTokenTypes.LITERAL_int;\n /**\n * The {@code float} keyword.\n *\n * @see #TYPE\n **/\n public static final int LITERAL_FLOAT =\n GeneratedJavaTokenTypes.LITERAL_float;\n\n /**\n * The {@code long} keyword.\n *\n * @see #TYPE\n **/\n public static final int LITERAL_LONG =\n GeneratedJavaTokenTypes.LITERAL_long;\n\n /**\n * The {@code double} keyword.\n *\n * @see #TYPE\n **/\n public static final int LITERAL_DOUBLE =\n GeneratedJavaTokenTypes.LITERAL_double;\n\n /**\n * An identifier. These can be names of types, subpackages,\n * fields, methods, parameters, and local variables.\n **/\n public static final int IDENT = GeneratedJavaTokenTypes.IDENT;\n /**\n * The &#46; (dot) operator.\n *\n *

    For example:

    \n *
    \n     * return person.name;\n     * 
    \n *

    parses as:

    \n *
    \n     * --LITERAL_RETURN -&gt; return\n     *    |--EXPR -&gt; EXPR\n     *    |   `--DOT -&gt; .\n     *    |       |--IDENT -&gt; person\n     *    |       `--IDENT -&gt; name\n     *    `--SEMI -&gt; ;\n     * 
    \n *\n * @see FullIdent\n * @noinspection HtmlTagCanBeJavadocTag\n **/\n public static final int DOT = GeneratedJavaTokenTypes.DOT;\n /**\n * The {@code *} (multiplication or wildcard) operator.\n *\n *

    For example:

    \n *
    \n     * f = m * a;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--ASSIGN -&gt; =\n     * |       |--IDENT -&gt; f\n     * |       `--STAR -&gt; *\n     * |           |--IDENT -&gt; m\n     * |           `--IDENT -&gt; a\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;7.5.2\n * @see Java\n * Language Specification, &sect;15.17.1\n * @see #EXPR\n * @see #IMPORT\n **/\n public static final int STAR = GeneratedJavaTokenTypes.STAR;\n /**\n * The {@code private} keyword.\n *\n * @see #MODIFIERS\n **/\n public static final int LITERAL_PRIVATE =\n GeneratedJavaTokenTypes.LITERAL_private;\n\n /**\n * The {@code public} keyword.\n *\n * @see #MODIFIERS\n **/\n public static final int LITERAL_PUBLIC =\n GeneratedJavaTokenTypes.LITERAL_public;\n\n /**\n * The {@code protected} keyword.\n *\n * @see #MODIFIERS\n **/\n public static final int LITERAL_PROTECTED =\n GeneratedJavaTokenTypes.LITERAL_protected;\n\n /**\n * The {@code static} keyword.\n *\n * @see #MODIFIERS\n **/\n public static final int LITERAL_STATIC =\n GeneratedJavaTokenTypes.LITERAL_static;\n\n /**\n * The {@code transient} keyword.\n *\n * @see #MODIFIERS\n **/\n public static final int LITERAL_TRANSIENT =\n GeneratedJavaTokenTypes.LITERAL_transient;\n\n /**\n * The {@code native} keyword.\n *\n * @see #MODIFIERS\n **/\n public static final int LITERAL_NATIVE =\n GeneratedJavaTokenTypes.LITERAL_native;\n\n /**\n * The {@code synchronized} keyword. This may be used as a\n * modifier of a method or in the definition of a synchronized\n * block.\n *\n *

    For example:

    \n *\n *
    \n     * synchronized(this)\n     * {\n     *   x++;\n     * }\n     * 
    \n *\n *

    parses as:

    \n *\n *
    \n     * |--LITERAL_SYNCHRONIZED -&gt; synchronized\n     * |   |--LPAREN -&gt; (\n     * |   |--EXPR -&gt; EXPR\n     * |   |   `--LITERAL_THIS -&gt; this\n     * |   |--RPAREN -&gt; )\n     * |   `--SLIST -&gt; {\n     * |       |--EXPR -&gt; EXPR\n     * |       |   `--POST_INC -&gt; ++\n     * |       |       `--IDENT -&gt; x\n     * |       |--SEMI -&gt; ;\n     * |       `--RCURLY -&gt; }\n     * `--RCURLY -&gt; }\n     * 
    \n *\n * @see #MODIFIERS\n * @see #LPAREN\n * @see #EXPR\n * @see #RPAREN\n * @see #SLIST\n * @see #RCURLY\n **/\n public static final int LITERAL_SYNCHRONIZED =\n GeneratedJavaTokenTypes.LITERAL_synchronized;\n\n /**\n * The {@code volatile} keyword.\n *\n * @see #MODIFIERS\n **/\n public static final int LITERAL_VOLATILE =\n GeneratedJavaTokenTypes.LITERAL_volatile;\n\n /**\n * The {@code class} keyword. This element appears both\n * as part of a class declaration, and inline to reference a\n * class object.\n *\n *

    For example:

    \n *\n *
    \n     * int.class\n     * 
    \n *

    parses as:

    \n *
    \n     * +--EXPR\n     *     |\n     *     +--DOT (.)\n     *         |\n     *         +--LITERAL_INT (int)\n     *         +--LITERAL_CLASS (class)\n     * 
    \n *\n * @see #DOT\n * @see #IDENT\n * @see #CLASS_DEF\n * @see FullIdent\n **/\n public static final int LITERAL_CLASS =\n GeneratedJavaTokenTypes.LITERAL_class;\n\n /**\n * The {@code interface} keyword. This token appears in\n * interface definition.\n *\n * @see #INTERFACE_DEF\n **/\n public static final int LITERAL_INTERFACE =\n GeneratedJavaTokenTypes.LITERAL_interface;\n\n /**\n * A left curly brace ({).\n *\n * @see #OBJBLOCK\n * @see #ARRAY_INIT\n * @see #SLIST\n **/\n public static final int LCURLY = GeneratedJavaTokenTypes.LCURLY;\n /**\n * A right curly brace (}).\n *\n * @see #OBJBLOCK\n * @see #ARRAY_INIT\n * @see #SLIST\n **/\n public static final int RCURLY = GeneratedJavaTokenTypes.RCURLY;\n /**\n * The {@code ,} (comma) operator.\n *\n * @see #ARRAY_INIT\n * @see #FOR_INIT\n * @see #FOR_ITERATOR\n * @see #LITERAL_THROWS\n * @see #IMPLEMENTS_CLAUSE\n **/\n public static final int COMMA = GeneratedJavaTokenTypes.COMMA;\n\n /**\n * A left parenthesis ({@code (}).\n *\n * @see #LITERAL_FOR\n * @see #LITERAL_NEW\n * @see #EXPR\n * @see #LITERAL_SWITCH\n * @see #LITERAL_CATCH\n **/\n public static final int LPAREN = GeneratedJavaTokenTypes.LPAREN;\n /**\n * A right parenthesis ({@code )}).\n *\n * @see #LITERAL_FOR\n * @see #LITERAL_NEW\n * @see #METHOD_CALL\n * @see #TYPECAST\n * @see #EXPR\n * @see #LITERAL_SWITCH\n * @see #LITERAL_CATCH\n **/\n public static final int RPAREN = GeneratedJavaTokenTypes.RPAREN;\n /**\n * The {@code this} keyword.\n *\n * @see #EXPR\n * @see #CTOR_CALL\n **/\n public static final int LITERAL_THIS =\n GeneratedJavaTokenTypes.LITERAL_this;\n\n /**\n * The {@code super} keyword.\n *\n * @see #EXPR\n * @see #SUPER_CTOR_CALL\n **/\n public static final int LITERAL_SUPER =\n GeneratedJavaTokenTypes.LITERAL_super;\n\n /**\n * The {@code =} (assignment) operator.\n *\n *

    For example:

    \n *
    \n     * a = b;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--ASSIGN -&gt; =\n     * |       |--IDENT -&gt; a\n     * |       `--IDENT -&gt; b\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.26.1\n * @see #EXPR\n **/\n public static final int ASSIGN = GeneratedJavaTokenTypes.ASSIGN;\n /**\n * The {@code throws} keyword. The children are a number of\n * one or more identifiers separated by commas.\n *\n * @see Java\n * Language Specification, &sect;8.4.4\n * @see #IDENT\n * @see #DOT\n * @see #COMMA\n * @see #METHOD_DEF\n * @see #CTOR_DEF\n * @see FullIdent\n **/\n public static final int LITERAL_THROWS =\n GeneratedJavaTokenTypes.LITERAL_throws;\n\n /**\n * The {@code :} (colon) operator. This will appear as part\n * of the conditional operator ({@code ? :}).\n *\n * @see #QUESTION\n * @see #LABELED_STAT\n * @see #CASE_GROUP\n **/\n public static final int COLON = GeneratedJavaTokenTypes.COLON;\n\n /**\n * The {@code ::} (double colon) separator.\n * It is part of Java 8 syntax that is used for method reference.\n * The token does not appear in tree, {@link #METHOD_REF} should be used instead.\n *\n * @see #METHOD_REF\n */\n public static final int DOUBLE_COLON = GeneratedJavaTokenTypes.DOUBLE_COLON;\n /**\n * The {@code if} keyword.\n *\n *

    For example:

    \n *
    \n     * if (optimistic)\n     * {\n     *   message = \"half full\";\n     * }\n     * else\n     * {\n     *   message = \"half empty\";\n     * }\n     * 
    \n *

    parses as:

    \n *
    \n     * LITERAL_IF -&gt; if\n     *  |--LPAREN -&gt; (\n     *  |--EXPR -&gt; EXPR\n     *  |   `--IDENT -&gt; optimistic\n     *  |--RPAREN -&gt; )\n     *  |--SLIST -&gt; {\n     *  |   |--EXPR -&gt; EXPR\n     *  |   |   `--ASSIGN -&gt; =\n     *  |   |       |--IDENT -&gt; message\n     *  |   |       `--STRING_LITERAL -&gt; \"half full\"\n     *  |   |--SEMI -&gt; ;\n     *  |   `--RCURLY -&gt; }\n     *  `--LITERAL_ELSE -&gt; else\n     *      `--SLIST -&gt; {\n     *          |--EXPR -&gt; EXPR\n     *          |   `--ASSIGN -&gt; =\n     *          |       |--IDENT -&gt; message\n     *          |       `--STRING_LITERAL -&gt; \"half empty\"\n     *          |--SEMI -&gt; ;\n     *          `--RCURLY -&gt; }\n     * 
    \n *\n * @see #LPAREN\n * @see #EXPR\n * @see #RPAREN\n * @see #SLIST\n * @see #EMPTY_STAT\n * @see #LITERAL_ELSE\n **/\n public static final int LITERAL_IF = GeneratedJavaTokenTypes.LITERAL_if;\n /**\n * The {@code for} keyword. The children are {@code (},\n * an initializer, a condition, an iterator, a {@code )} and\n * either a statement list, a single expression, or an empty\n * statement.\n *\n *

    For example:

    \n *
    \n     * for(int i = 0, n = myArray.length; i &lt; n; i++)\n     * {\n     * }\n     * 
    \n *\n *

    parses as:

    \n *
    \n     * +--LITERAL_FOR (for)\n     *     |\n     *     +--LPAREN (()\n     *     +--FOR_INIT\n     *         |\n     *         +--VARIABLE_DEF\n     *             |\n     *             +--MODIFIERS\n     *             +--TYPE\n     *                 |\n     *                 +--LITERAL_INT (int)\n     *             +--IDENT (i)\n     *             +--ASSIGN (=)\n     *                 |\n     *                 +--EXPR\n     *                     |\n     *                     +--NUM_INT (0)\n     *         +--COMMA (,)\n     *         +--VARIABLE_DEF\n     *             |\n     *             +--MODIFIERS\n     *             +--TYPE\n     *                 |\n     *                 +--LITERAL_INT (int)\n     *             +--IDENT (n)\n     *             +--ASSIGN (=)\n     *                 |\n     *                 +--EXPR\n     *                     |\n     *                     +--DOT (.)\n     *                         |\n     *                         +--IDENT (myArray)\n     *                         +--IDENT (length)\n     *     +--SEMI (;)\n     *     +--FOR_CONDITION\n     *         |\n     *         +--EXPR\n     *             |\n     *             +--LT (&lt;)\n     *                 |\n     *                 +--IDENT (i)\n     *                 +--IDENT (n)\n     *     +--SEMI (;)\n     *     +--FOR_ITERATOR\n     *         |\n     *         +--ELIST\n     *             |\n     *             +--EXPR\n     *                 |\n     *                 +--POST_INC (++)\n     *                     |\n     *                     +--IDENT (i)\n     *     +--RPAREN ())\n     *     +--SLIST ({)\n     *         |\n     *         +--RCURLY (})\n     * 
    \n *\n * @see #LPAREN\n * @see #FOR_INIT\n * @see #SEMI\n * @see #FOR_CONDITION\n * @see #FOR_ITERATOR\n * @see #RPAREN\n * @see #SLIST\n * @see #EMPTY_STAT\n * @see #EXPR\n **/\n public static final int LITERAL_FOR = GeneratedJavaTokenTypes.LITERAL_for;\n /**\n * The {@code while} keyword.\n *\n *

    For example:

    \n *
    \n     * while(line != null)\n     * {\n     *   process(line);\n     *   line = in.readLine();\n     * }\n     * 
    \n *

    parses as:

    \n *
    \n     * +--LITERAL_WHILE (while)\n     *     |\n     *     +--LPAREN (()\n     *     +--EXPR\n     *         |\n     *         +--NOT_EQUAL (!=)\n     *             |\n     *             +--IDENT (line)\n     *             +--LITERAL_NULL (null)\n     *     +--RPAREN ())\n     *     +--SLIST ({)\n     *         |\n     *         +--EXPR\n     *             |\n     *             +--METHOD_CALL (()\n     *                 |\n     *                 +--IDENT (process)\n     *                 +--ELIST\n     *                     |\n     *                     +--EXPR\n     *                         |\n     *                         +--IDENT (line)\n     *                 +--RPAREN ())\n     *         +--SEMI (;)\n     *         +--EXPR\n     *             |\n     *             +--ASSIGN (=)\n     *                 |\n     *                 +--IDENT (line)\n     *                 +--METHOD_CALL (()\n     *                     |\n     *                     +--DOT (.)\n     *                         |\n     *                         +--IDENT (in)\n     *                         +--IDENT (readLine)\n     *                     +--ELIST\n     *                     +--RPAREN ())\n     *         +--SEMI (;)\n     *         +--RCURLY (})\n     * 
    \n **/\n public static final int LITERAL_WHILE =\n GeneratedJavaTokenTypes.LITERAL_while;\n\n /**\n * The {@code do} keyword. Note the the while token does not\n * appear as part of the do-while construct.\n *\n *

    For example:

    \n *
    \n     * do\n     * {\n     *   x = rand.nextInt(10);\n     * }\n     * while(x &lt; 5);\n     * 
    \n *

    parses as:

    \n *
    \n     * +--LITERAL_DO (do)\n     *     |\n     *     +--SLIST ({)\n     *         |\n     *         +--EXPR\n     *             |\n     *             +--ASSIGN (=)\n     *                 |\n     *                 +--IDENT (x)\n     *                 +--METHOD_CALL (()\n     *                     |\n     *                     +--DOT (.)\n     *                         |\n     *                         +--IDENT (rand)\n     *                         +--IDENT (nextInt)\n     *                     +--ELIST\n     *                         |\n     *                         +--EXPR\n     *                             |\n     *                             +--NUM_INT (10)\n     *                     +--RPAREN ())\n     *         +--SEMI (;)\n     *         +--RCURLY (})\n     *     +--DO_WHILE (while)\n     *     +--LPAREN (()\n     *     +--EXPR\n     *         |\n     *         +--LT (&lt;)\n     *             |\n     *             +--IDENT (x)\n     *             +--NUM_INT (5)\n     *     +--RPAREN ())\n     *     +--SEMI (;)\n     * 
    \n *\n * @see #SLIST\n * @see #EXPR\n * @see #EMPTY_STAT\n * @see #LPAREN\n * @see #RPAREN\n * @see #SEMI\n **/\n public static final int LITERAL_DO = GeneratedJavaTokenTypes.LITERAL_do;\n /**\n * Literal {@code while} in do-while loop.\n *\n *

    For example:

    \n *
    \n     * do {\n     *\n     * } while (a &gt; 0);\n     * 
    \n *

    parses as:

    \n *
    \n     * --LITERAL_DO -&gt; do\n     *    |--SLIST -&gt; {\n     *    |   `--RCURLY -&gt; }\n     *    |--DO_WHILE -&gt; while\n     *    |--LPAREN -&gt; (\n     *    |--EXPR -&gt; EXPR\n     *    |   `--GT -&gt; &gt;\n     *    |       |--IDENT -&gt; a\n     *    |       `--NUM_INT -&gt; 0\n     *    |--RPAREN -&gt; )\n     *    `--SEMI -&gt; ;\n     * 
    \n *\n * @see #LITERAL_DO\n */\n public static final int DO_WHILE = GeneratedJavaTokenTypes.DO_WHILE;\n /**\n * The {@code break} keyword. The first child is an optional\n * identifier and the last child is a semicolon.\n *\n * @see #IDENT\n * @see #SEMI\n * @see #SLIST\n **/\n public static final int LITERAL_BREAK =\n GeneratedJavaTokenTypes.LITERAL_break;\n\n /**\n * The {@code continue} keyword. The first child is an\n * optional identifier and the last child is a semicolon.\n *\n * @see #IDENT\n * @see #SEMI\n * @see #SLIST\n **/\n public static final int LITERAL_CONTINUE =\n GeneratedJavaTokenTypes.LITERAL_continue;\n\n /**\n * The {@code return} keyword. The first child is an\n * optional expression for the return value. The last child is a\n * semi colon.\n *\n * @see #EXPR\n * @see #SEMI\n * @see #SLIST\n **/\n public static final int LITERAL_RETURN =\n GeneratedJavaTokenTypes.LITERAL_return;\n\n /**\n * The {@code switch} keyword.\n *\n *

    For example:

    \n *
    \n     * switch(type)\n     * {\n     *   case 0:\n     *     background = Color.blue;\n     *     break;\n     *   case 1:\n     *     background = Color.red;\n     *     break;\n     *   default:\n     *     background = Color.green;\n     *     break;\n     * }\n     * 
    \n *

    parses as:

    \n *
    \n     * +--LITERAL_SWITCH (switch)\n     *     |\n     *     +--LPAREN (()\n     *     +--EXPR\n     *         |\n     *         +--IDENT (type)\n     *     +--RPAREN ())\n     *     +--LCURLY ({)\n     *     +--CASE_GROUP\n     *         |\n     *         +--LITERAL_CASE (case)\n     *             |\n     *             +--EXPR\n     *                 |\n     *                 +--NUM_INT (0)\n     *         +--SLIST\n     *             |\n     *             +--EXPR\n     *                 |\n     *                 +--ASSIGN (=)\n     *                     |\n     *                     +--IDENT (background)\n     *                     +--DOT (.)\n     *                         |\n     *                         +--IDENT (Color)\n     *                         +--IDENT (blue)\n     *             +--SEMI (;)\n     *             +--LITERAL_BREAK (break)\n     *                 |\n     *                 +--SEMI (;)\n     *     +--CASE_GROUP\n     *         |\n     *         +--LITERAL_CASE (case)\n     *             |\n     *             +--EXPR\n     *                 |\n     *                 +--NUM_INT (1)\n     *         +--SLIST\n     *             |\n     *             +--EXPR\n     *                 |\n     *                 +--ASSIGN (=)\n     *                     |\n     *                     +--IDENT (background)\n     *                     +--DOT (.)\n     *                         |\n     *                         +--IDENT (Color)\n     *                         +--IDENT (red)\n     *             +--SEMI (;)\n     *             +--LITERAL_BREAK (break)\n     *                 |\n     *                 +--SEMI (;)\n     *     +--CASE_GROUP\n     *         |\n     *         +--LITERAL_DEFAULT (default)\n     *         +--SLIST\n     *             |\n     *             +--EXPR\n     *                 |\n     *                 +--ASSIGN (=)\n     *                     |\n     *                     +--IDENT (background)\n     *                     +--DOT (.)\n     *                         |\n     *                         +--IDENT (Color)\n     *                         +--IDENT (green)\n     *             +--SEMI (;)\n     *             +--LITERAL_BREAK (break)\n     *                 |\n     *                 +--SEMI (;)\n     *     +--RCURLY (})\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;14.10\n * @see #LPAREN\n * @see #EXPR\n * @see #RPAREN\n * @see #LCURLY\n * @see #CASE_GROUP\n * @see #RCURLY\n * @see #SLIST\n * @see #SWITCH_RULE\n **/\n public static final int LITERAL_SWITCH =\n GeneratedJavaTokenTypes.LITERAL_switch;\n\n /**\n * The {@code throw} keyword. The first child is an\n * expression that evaluates to a {@code Throwable} instance.\n *\n * @see Java\n * Language Specification, &sect;14.17\n * @see #SLIST\n * @see #EXPR\n **/\n public static final int LITERAL_THROW =\n GeneratedJavaTokenTypes.LITERAL_throw;\n\n /**\n * The {@code else} keyword. This appears as a child of an\n * {@code if} statement.\n *\n * @see #SLIST\n * @see #EXPR\n * @see #EMPTY_STAT\n * @see #LITERAL_IF\n **/\n public static final int LITERAL_ELSE =\n GeneratedJavaTokenTypes.LITERAL_else;\n\n /**\n * The {@code case} keyword. The first child is a constant\n * expression that evaluates to an integer.\n *\n * @see #CASE_GROUP\n * @see #EXPR\n **/\n public static final int LITERAL_CASE =\n GeneratedJavaTokenTypes.LITERAL_case;\n\n /**\n * The {@code default} keyword. This element has no\n * children.\n *\n * @see #CASE_GROUP\n * @see #MODIFIERS\n * @see #SWITCH_RULE\n **/\n public static final int LITERAL_DEFAULT =\n GeneratedJavaTokenTypes.LITERAL_default;\n\n /**\n * The {@code try} keyword. The children are a statement\n * list, zero or more catch blocks and then an optional finally\n * block.\n *\n *

    For example:

    \n *
    \n     * try\n     * {\n     *   FileReader in = new FileReader(\"abc.txt\");\n     * }\n     * catch(IOException ioe)\n     * {\n     * }\n     * finally\n     * {\n     * }\n     * 
    \n *

    parses as:

    \n *
    \n     * +--LITERAL_TRY (try)\n     *     |\n     *     +--SLIST ({)\n     *         |\n     *         +--VARIABLE_DEF\n     *             |\n     *             +--MODIFIERS\n     *             +--TYPE\n     *                 |\n     *                 +--IDENT (FileReader)\n     *             +--IDENT (in)\n     *             +--ASSIGN (=)\n     *                 |\n     *                 +--EXPR\n     *                     |\n     *                     +--LITERAL_NEW (new)\n     *                         |\n     *                         +--IDENT (FileReader)\n     *                         +--LPAREN (()\n     *                         +--ELIST\n     *                             |\n     *                             +--EXPR\n     *                                 |\n     *                                 +--STRING_LITERAL (\"abc.txt\")\n     *                         +--RPAREN ())\n     *         +--SEMI (;)\n     *         +--RCURLY (})\n     *     +--LITERAL_CATCH (catch)\n     *         |\n     *         +--LPAREN (()\n     *         +--PARAMETER_DEF\n     *             |\n     *             +--MODIFIERS\n     *             +--TYPE\n     *                 |\n     *                 +--IDENT (IOException)\n     *             +--IDENT (ioe)\n     *         +--RPAREN ())\n     *         +--SLIST ({)\n     *             |\n     *             +--RCURLY (})\n     *     +--LITERAL_FINALLY (finally)\n     *         |\n     *         +--SLIST ({)\n     *             |\n     *             +--RCURLY (})\n     * +--RCURLY (})\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;14.19\n * @see #SLIST\n * @see #LITERAL_CATCH\n * @see #LITERAL_FINALLY\n **/\n public static final int LITERAL_TRY = GeneratedJavaTokenTypes.LITERAL_try;\n\n /**\n * The Java 7 try-with-resources construct.\n *\n *

    For example:

    \n *
    \n     * try (Foo foo = new Foo(); Bar bar = new Bar()) { }\n     * 
    \n *

    parses as:

    \n *
    \n     * +--LITERAL_TRY (try)\n     *     |\n     *     +--RESOURCE_SPECIFICATION\n     *         |\n     *         +--LPAREN (()\n     *         +--RESOURCES\n     *             |\n     *             +--RESOURCE\n     *                 |\n     *                 +--MODIFIERS\n     *                 +--TYPE\n     *                     |\n     *                     +--IDENT (Foo)\n     *                 +--IDENT (foo)\n     *                 +--ASSIGN (=)\n     *                 +--EXPR\n     *                    |\n     *                    +--LITERAL_NEW (new)\n     *                       |\n     *                       +--IDENT (Foo)\n     *                       +--LPAREN (()\n     *                       +--ELIST\n     *                       +--RPAREN ())\n     *             +--SEMI (;)\n     *             +--RESOURCE\n     *                 |\n     *                 +--MODIFIERS\n     *                 +--TYPE\n     *                     |\n     *                     +--IDENT (Bar)\n     *                 +--IDENT (bar)\n     *                 +--ASSIGN (=)\n     *                 +--EXPR\n     *                    |\n     *                    +--LITERAL_NEW (new)\n     *                       |\n     *                       +--IDENT (Bar)\n     *                       +--LPAREN (()\n     *                       +--ELIST\n     *                       +--RPAREN ())\n     *         +--RPAREN ())\n     *     +--SLIST ({)\n     *         +--RCURLY (})\n     * 
    \n *\n *

    Also consider:

    \n *
    \n     * try (BufferedReader br = new BufferedReader(new FileReader(path)))\n     * {\n     *  return br.readLine();\n     * }\n     * 
    \n *

    which parses as:

    \n *
    \n     * +--LITERAL_TRY (try)\n     *     |\n     *     +--RESOURCE_SPECIFICATION\n     *         |\n     *         +--LPAREN (()\n     *         +--RESOURCES\n     *             |\n     *             +--RESOURCE\n     *                 |\n     *                 +--MODIFIERS\n     *                 +--TYPE\n     *                     |\n     *                     +--IDENT (BufferedReader)\n     *                 +--IDENT (br)\n     *                 +--ASSIGN (=)\n     *                 +--EXPR\n     *                     |\n     *                     +--LITERAL_NEW (new)\n     *                         |\n     *                         +--IDENT (FileReader)\n     *                         +--LPAREN (()\n     *                         +--ELIST\n     *                             |\n     *                             +--EXPR\n     *                                 |\n     *                                 +--LITERAL_NEW (new)\n     *                                     |\n     *                                     +--IDENT (BufferedReader)\n     *                                     +--LPAREN (()\n     *                                     +--ELIST\n     *                                         |\n     *                                         +--EXPR\n     *                                             |\n     *                                             +--IDENT (path)\n     *                                     +--RPAREN ())\n     *                         +--RPAREN ())\n     *         +--RPAREN ())\n     *     +--SLIST ({)\n     *         |\n     *         +--LITERAL_RETURN (return)\n     *             |\n     *             +--EXPR\n     *                 |\n     *                 +--METHOD_CALL (()\n     *                     |\n     *                     +--DOT (.)\n     *                         |\n     *                         +--IDENT (br)\n     *                         +--IDENT (readLine)\n     *                     +--ELIST\n     *                     +--RPAREN ())\n     *             +--SEMI (;)\n     *         +--RCURLY (})\n     * 
    \n *\n * @see #LPAREN\n * @see #RESOURCES\n * @see #RESOURCE\n * @see #SEMI\n * @see #RPAREN\n * @see #LITERAL_TRY\n **/\n public static final int RESOURCE_SPECIFICATION =\n GeneratedJavaTokenTypes.RESOURCE_SPECIFICATION;\n\n /**\n * A list of resources in the Java 7 try-with-resources construct.\n * This is a child of RESOURCE_SPECIFICATION.\n *\n * @see #RESOURCE_SPECIFICATION\n **/\n public static final int RESOURCES =\n GeneratedJavaTokenTypes.RESOURCES;\n\n /**\n * A resource in the Java 7 try-with-resources construct.\n * This is a child of RESOURCES.\n *\n * @see #RESOURCES\n * @see #RESOURCE_SPECIFICATION\n **/\n public static final int RESOURCE =\n GeneratedJavaTokenTypes.RESOURCE;\n\n /**\n * The {@code catch} keyword.\n *\n * @see #LPAREN\n * @see #PARAMETER_DEF\n * @see #RPAREN\n * @see #SLIST\n * @see #LITERAL_TRY\n **/\n public static final int LITERAL_CATCH =\n GeneratedJavaTokenTypes.LITERAL_catch;\n\n /**\n * The {@code finally} keyword.\n *\n * @see #SLIST\n * @see #LITERAL_TRY\n **/\n public static final int LITERAL_FINALLY =\n GeneratedJavaTokenTypes.LITERAL_finally;\n\n /**\n * The {@code +=} (addition assignment) operator.\n *\n *

    For example:

    \n *
    \n     * a += b;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--PLUS_ASSIGN -&gt; +=\n     * |       |--IDENT -&gt; a\n     * |       `--IDENT -&gt; b\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.26.2\n * @see #EXPR\n **/\n public static final int PLUS_ASSIGN = GeneratedJavaTokenTypes.PLUS_ASSIGN;\n /**\n * The {@code -=} (subtraction assignment) operator.\n *\n *

    For example:

    \n *
    \n     * a -= b;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--MINUS_ASSIGN -&gt; -=\n     * |       |--IDENT -&gt; a\n     * |       `--IDENT -&gt; b\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.26.2\n * @see #EXPR\n **/\n public static final int MINUS_ASSIGN =\n GeneratedJavaTokenTypes.MINUS_ASSIGN;\n\n /**\n * The {@code *=} (multiplication assignment) operator.\n *\n *

    For example:

    \n *
    \n     * a *= b;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--STAR_ASSIGN -&gt; *=\n     * |       |--IDENT -&gt; a\n     * |       `--IDENT -&gt; b\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.26.2\n * @see #EXPR\n **/\n public static final int STAR_ASSIGN = GeneratedJavaTokenTypes.STAR_ASSIGN;\n /**\n * The {@code /=} (division assignment) operator.\n *\n *

    For example:

    \n *
    \n     * a /= b;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--DIV_ASSIGN -&gt; /=\n     * |       |--IDENT -&gt; a\n     * |       `--IDENT -&gt; b\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.26.2\n * @see #EXPR\n **/\n public static final int DIV_ASSIGN = GeneratedJavaTokenTypes.DIV_ASSIGN;\n /**\n * The {@code %=} (remainder assignment) operator.\n *

    For example:

    \n *
    a %= 2;
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--MOD_ASSIGN -&gt; %=\n     * |       |--IDENT -&gt; a\n     * |       `--NUM_INT -&gt; 2\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.26.2\n * @see #EXPR\n **/\n public static final int MOD_ASSIGN = GeneratedJavaTokenTypes.MOD_ASSIGN;\n /**\n * The {@code >>=} (signed right shift assignment)\n * operator.\n *\n *

    For example:

    \n *
    \n     * a &gt;&gt;= b;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--SR_ASSIGN -&gt; &gt;&gt;=\n     * |       |--IDENT -&gt; a\n     * |       `--IDENT -&gt; b\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.26.2\n * @see #EXPR\n **/\n public static final int SR_ASSIGN = GeneratedJavaTokenTypes.SR_ASSIGN;\n /**\n * The {@code >>>=} (unsigned right shift assignment)\n * operator.\n *\n *

    For example:

    \n *
    \n     * a &gt;&gt;&gt;= b;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--BSR_ASSIGN -&gt; &gt;&gt;&gt;=\n     * |       |--IDENT -&gt; a\n     * |       `--IDENT -&gt; b\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.26.2\n * @see #EXPR\n **/\n public static final int BSR_ASSIGN = GeneratedJavaTokenTypes.BSR_ASSIGN;\n /**\n * The {@code <<=} (left shift assignment) operator.\n *\n * @see Java\n * Language Specification, &sect;15.26.2\n * @see #EXPR\n **/\n public static final int SL_ASSIGN = GeneratedJavaTokenTypes.SL_ASSIGN;\n /**\n * The {@code &=} (bitwise AND assignment) operator.\n *\n *

    For example:

    \n *
    \n     * a &amp;= b;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--BAND_ASSIGN -&gt; &amp;=\n     * |       |--IDENT -&gt; a\n     * |       `--IDENT -&gt; b\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.26.2\n * @see #EXPR\n **/\n public static final int BAND_ASSIGN = GeneratedJavaTokenTypes.BAND_ASSIGN;\n /**\n * The {@code ^=} (bitwise exclusive OR assignment) operator.\n *\n * @see Java\n * Language Specification, &sect;15.26.2\n * @see #EXPR\n **/\n public static final int BXOR_ASSIGN = GeneratedJavaTokenTypes.BXOR_ASSIGN;\n /**\n * The {@code |=} (bitwise OR assignment) operator.\n *\n *

    For example:

    \n *
    \n     * a |= b;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--BOR_ASSIGN -&gt; |=\n     * |       |--IDENT -&gt; a\n     * |       `--IDENT -&gt; b\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.26.2\n * @see #EXPR\n **/\n public static final int BOR_ASSIGN = GeneratedJavaTokenTypes.BOR_ASSIGN;\n /**\n * The &#63; (conditional) operator. Technically,\n * the colon is also part of this operator, but it appears as a\n * separate token.\n *\n *

    For example:

    \n *
    \n     * (quantity == 1) ? \"\": \"s\"\n     * 
    \n *

    \n * parses as:\n *

    \n *
    \n     * +--QUESTION (?)\n     *     |\n     *     +--LPAREN (()\n     *     +--EQUAL (==)\n     *         |\n     *         +--IDENT (quantity)\n     *         +--NUM_INT (1)\n     *     +--RPAREN ())\n     *     +--STRING_LITERAL (\"\")\n     *     +--COLON (:)\n     *     +--STRING_LITERAL (\"s\")\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.25\n * @see #EXPR\n * @see #COLON\n * @noinspection HtmlTagCanBeJavadocTag\n **/\n public static final int QUESTION = GeneratedJavaTokenTypes.QUESTION;\n /**\n * The {@code ||} (conditional OR) operator.\n *\n * @see Java\n * Language Specification, &sect;15.24\n * @see #EXPR\n **/\n public static final int LOR = GeneratedJavaTokenTypes.LOR;\n /**\n * The {@code &&} (conditional AND) operator.\n *\n * @see Java\n * Language Specification, &sect;15.23\n * @see #EXPR\n **/\n public static final int LAND = GeneratedJavaTokenTypes.LAND;\n /**\n * The {@code |} (bitwise OR) operator.\n *\n *

    For example:

    \n *
    \n     * a = a | b;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--ASSIGN -&gt; =\n     * |       |--IDENT -&gt; a\n     * |       `--BOR -&gt; |\n     * |           |--IDENT -&gt; a\n     * |           `--IDENT -&gt; b\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.22.1\n * @see #EXPR\n **/\n public static final int BOR = GeneratedJavaTokenTypes.BOR;\n /**\n * The {@code ^} (bitwise exclusive OR) operator.\n *\n * @see Java\n * Language Specification, &sect;15.22.1\n * @see #EXPR\n **/\n public static final int BXOR = GeneratedJavaTokenTypes.BXOR;\n /**\n * The {@code &} (bitwise AND) operator.\n *\n *

    For example:

    \n *
    \n     * c = a &amp; b;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--ASSIGN -&gt; =\n     * |       |--IDENT -&gt; c\n     * |       `--BAND -&gt; &amp;\n     * |           |--IDENT -&gt; a\n     * |           `--IDENT -&gt; b\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.22.1\n * @see #EXPR\n **/\n public static final int BAND = GeneratedJavaTokenTypes.BAND;\n /**\n * The &#33;= (not equal) operator.\n *\n *

    For example:

    \n *
    \n     * a != b;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--NOT_EQUAL -&gt; !=\n     * |       |--IDENT -&gt; a\n     * |       `--IDENT -&gt; b\n     * `--SEMI -&gt; ;\n     * 
    \n *\n * @see #EXPR\n * @noinspection HtmlTagCanBeJavadocTag\n **/\n public static final int NOT_EQUAL = GeneratedJavaTokenTypes.NOT_EQUAL;\n /**\n * The {@code ==} (equal) operator.\n *\n *

    For example:

    \n *
    \n     * return a == b;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--EQUAL -&gt; ==\n     * |       |--IDENT -&gt; a\n     * |       `--IDENT -&gt; b\n     * `--SEMI -&gt; ;\n     * 
    \n *\n * @see #EXPR\n **/\n public static final int EQUAL = GeneratedJavaTokenTypes.EQUAL;\n /**\n * The {@code <} (less than) operator.\n *\n * @see #EXPR\n **/\n public static final int LT = GeneratedJavaTokenTypes.LT;\n /**\n * The {@code >} (greater than) operator.\n *\n * @see #EXPR\n **/\n public static final int GT = GeneratedJavaTokenTypes.GT;\n /**\n * The {@code <=} (less than or equal) operator.\n *\n * @see #EXPR\n **/\n public static final int LE = GeneratedJavaTokenTypes.LE;\n /**\n * The {@code >=} (greater than or equal) operator.\n *\n * @see #EXPR\n **/\n public static final int GE = GeneratedJavaTokenTypes.GE;\n /**\n * The {@code instanceof} operator. The first child is an\n * object reference or something that evaluates to an object\n * reference. The second child is a reference type.\n *\n * @see Java\n * Language Specification, &sect;15.20.2\n * @see #EXPR\n * @see #METHOD_CALL\n * @see #IDENT\n * @see #DOT\n * @see #TYPE\n * @see FullIdent\n **/\n public static final int LITERAL_INSTANCEOF =\n GeneratedJavaTokenTypes.LITERAL_instanceof;\n\n /**\n * The {@code <<} (shift left) operator.\n *\n *

    For example:

    \n *
    \n     * a = a &lt;&lt; b;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--ASSIGN -&gt; =\n     * |       |--IDENT -&gt; a\n     * |       `--SR -&gt; &lt;&lt;\n     * |           |--IDENT -&gt; a\n     * |           `--IDENT -&gt; b\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.19\n * @see #EXPR\n **/\n public static final int SL = GeneratedJavaTokenTypes.SL;\n /**\n * The {@code >>} (signed shift right) operator.\n *\n *

    For example:

    \n *
    \n     * a = a &gt;&gt; b;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--ASSIGN -&gt; =\n     * |       |--IDENT -&gt; a\n     * |       `--SR -&gt; &gt;&gt;\n     * |           |--IDENT -&gt; a\n     * |           `--IDENT -&gt; b\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.19\n * @see #EXPR\n **/\n public static final int SR = GeneratedJavaTokenTypes.SR;\n /**\n * The {@code >>>} (unsigned shift right) operator.\n *\n *

    For example:

    \n *
    \n     * a &gt;&gt;&gt; b;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--BSR -&gt; &gt;&gt;&gt;\n     * |       |--IDENT -&gt; a\n     * |       `--IDENT -&gt; b\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.19\n * @see #EXPR\n **/\n public static final int BSR = GeneratedJavaTokenTypes.BSR;\n /**\n * The {@code +} (addition) operator.\n *\n * @see Java\n * Language Specification, &sect;15.18\n * @see #EXPR\n **/\n public static final int PLUS = GeneratedJavaTokenTypes.PLUS;\n /**\n * The {@code -} (subtraction) operator.\n *\n *

    For example:

    \n *
    \n     * c = a - b;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--ASSIGN -&gt; =\n     * |       |--IDENT -&gt; c\n     * |       `--MINUS -&gt; -\n     * |           |--IDENT -&gt; a\n     * |           `--IDENT -&gt; b\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.18\n * @see #EXPR\n **/\n public static final int MINUS = GeneratedJavaTokenTypes.MINUS;\n /**\n * The {@code /} (division) operator.\n *\n *

    For example:

    \n *
    \n     * a = 4 / 2;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--ASSIGN -&gt; =\n     * |       |--IDENT -&gt; a\n     * |       `--DIV -&gt; /\n     * |           |--NUM_INT -&gt; 4\n     * |           `--NUM_INT -&gt; 2\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.17.2\n * @see #EXPR\n **/\n public static final int DIV = GeneratedJavaTokenTypes.DIV;\n /**\n * The {@code %} (remainder) operator.\n *\n * @see Java\n * Language Specification, &sect;15.17.3\n * @see #EXPR\n **/\n public static final int MOD = GeneratedJavaTokenTypes.MOD;\n /**\n * The {@code ++} (prefix increment) operator.\n *\n * @see Java\n * Language Specification, &sect;15.15.1\n * @see #EXPR\n * @see #POST_INC\n **/\n public static final int INC = GeneratedJavaTokenTypes.INC;\n /**\n * The {@code --} (prefix decrement) operator.\n *\n *

    For example:

    \n *
    \n     * --a;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--DEC -&gt; --\n     * |       `--IDENT -&gt; a\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.15.2\n * @see #EXPR\n * @see #POST_DEC\n **/\n public static final int DEC = GeneratedJavaTokenTypes.DEC;\n /**\n * The {@code ~} (bitwise complement) operator.\n *\n *

    For example:

    \n *
    \n     * a = ~ a;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--ASSIGN -&gt; =\n     * |       |--IDENT -&gt; a\n     * |       `--BNOT -&gt; ~\n     * |           `--IDENT -&gt; a\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;15.15.5\n * @see #EXPR\n **/\n public static final int BNOT = GeneratedJavaTokenTypes.BNOT;\n /**\n * The &#33; (logical complement) operator.\n *\n * @see Java\n * Language Specification, &sect;15.15.6\n * @see #EXPR\n * @noinspection HtmlTagCanBeJavadocTag\n **/\n public static final int LNOT = GeneratedJavaTokenTypes.LNOT;\n /**\n * The {@code true} keyword.\n *\n * @see Java\n * Language Specification, &sect;3.10.3\n * @see #EXPR\n * @see #LITERAL_FALSE\n **/\n public static final int LITERAL_TRUE =\n GeneratedJavaTokenTypes.LITERAL_true;\n\n /**\n * The {@code false} keyword.\n *\n * @see Java\n * Language Specification, &sect;3.10.3\n * @see #EXPR\n * @see #LITERAL_TRUE\n **/\n public static final int LITERAL_FALSE =\n GeneratedJavaTokenTypes.LITERAL_false;\n\n /**\n * The {@code null} keyword.\n *\n * @see Java\n * Language Specification, &sect;3.10.7\n * @see #EXPR\n **/\n public static final int LITERAL_NULL =\n GeneratedJavaTokenTypes.LITERAL_null;\n\n /**\n * The {@code new} keyword. This element is used to define\n * new instances of objects, new arrays, and new anonymous inner\n * classes.\n *\n *

    For example:

    \n *\n *
    \n     * new ArrayList(50)\n     * 
    \n *\n *

    parses as:

    \n *
    \n     * +--LITERAL_NEW (new)\n     *     |\n     *     +--IDENT (ArrayList)\n     *     +--LPAREN (()\n     *     +--ELIST\n     *         |\n     *         +--EXPR\n     *             |\n     *             +--NUM_INT (50)\n     *     +--RPAREN ())\n     * 
    \n *\n *

    For example:

    \n *
    \n     * new float[]\n     *   {\n     *     3.0f,\n     *     4.0f\n     *   };\n     * 
    \n *\n *

    parses as:

    \n *
    \n     * +--LITERAL_NEW (new)\n     *     |\n     *     +--LITERAL_FLOAT (float)\n     *     +--ARRAY_DECLARATOR ([)\n     *     +--ARRAY_INIT ({)\n     *         |\n     *         +--EXPR\n     *             |\n     *             +--NUM_FLOAT (3.0f)\n     *         +--COMMA (,)\n     *         +--EXPR\n     *             |\n     *             +--NUM_FLOAT (4.0f)\n     *         +--RCURLY (})\n     * 
    \n *\n *

    For example:

    \n *
    \n     * new FilenameFilter()\n     * {\n     *   public boolean accept(File dir, String name)\n     *   {\n     *     return name.endsWith(\".java\");\n     *   }\n     * }\n     * 
    \n *\n *

    parses as:

    \n *
    \n     * +--LITERAL_NEW (new)\n     *     |\n     *     +--IDENT (FilenameFilter)\n     *     +--LPAREN (()\n     *     +--ELIST\n     *     +--RPAREN ())\n     *     +--OBJBLOCK\n     *         |\n     *         +--LCURLY ({)\n     *         +--METHOD_DEF\n     *             |\n     *             +--MODIFIERS\n     *                 |\n     *                 +--LITERAL_PUBLIC (public)\n     *             +--TYPE\n     *                 |\n     *                 +--LITERAL_BOOLEAN (boolean)\n     *             +--IDENT (accept)\n     *             +--PARAMETERS\n     *                 |\n     *                 +--PARAMETER_DEF\n     *                     |\n     *                     +--MODIFIERS\n     *                     +--TYPE\n     *                         |\n     *                         +--IDENT (File)\n     *                     +--IDENT (dir)\n     *                 +--COMMA (,)\n     *                 +--PARAMETER_DEF\n     *                     |\n     *                     +--MODIFIERS\n     *                     +--TYPE\n     *                         |\n     *                         +--IDENT (String)\n     *                     +--IDENT (name)\n     *             +--SLIST ({)\n     *                 |\n     *                 +--LITERAL_RETURN (return)\n     *                     |\n     *                     +--EXPR\n     *                         |\n     *                         +--METHOD_CALL (()\n     *                             |\n     *                             +--DOT (.)\n     *                                 |\n     *                                 +--IDENT (name)\n     *                                 +--IDENT (endsWith)\n     *                             +--ELIST\n     *                                 |\n     *                                 +--EXPR\n     *                                     |\n     *                                     +--STRING_LITERAL (\".java\")\n     *                             +--RPAREN ())\n     *                     +--SEMI (;)\n     *                 +--RCURLY (})\n     *         +--RCURLY (})\n     * 
    \n *\n * @see #IDENT\n * @see #DOT\n * @see #LPAREN\n * @see #ELIST\n * @see #RPAREN\n * @see #OBJBLOCK\n * @see #ARRAY_INIT\n * @see FullIdent\n **/\n public static final int LITERAL_NEW = GeneratedJavaTokenTypes.LITERAL_new;\n /**\n * An integer literal. These may be specified in decimal,\n * hexadecimal, or octal form.\n *\n *

    For example:

    \n *
    \n     * a = 3;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--ASSIGN -&gt; =\n     * |       |--IDENT -&gt; a\n     * |       `--NUM_INT -&gt; 3\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;3.10.1\n * @see #EXPR\n * @see #NUM_LONG\n **/\n public static final int NUM_INT = GeneratedJavaTokenTypes.NUM_INT;\n /**\n * A character literal. This is a (possibly escaped) character\n * enclosed in single quotes.\n *\n *

    For example:

    \n *
    \n     * return 'a';\n     * 
    \n *

    parses as:

    \n *
    \n     * --LITERAL_RETURN -&gt; return\n     *    |--EXPR -&gt; EXPR\n     *    |   `--CHAR_LITERAL -&gt; 'a'\n     *    `--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;3.10.4\n * @see #EXPR\n **/\n public static final int CHAR_LITERAL =\n GeneratedJavaTokenTypes.CHAR_LITERAL;\n\n /**\n * A string literal. This is a sequence of (possibly escaped)\n * characters enclosed in double quotes.\n *

    For example:

    \n *
    String str = \"StringLiteral\";
    \n *\n *

    parses as:

    \n *
    \n     *  |--VARIABLE_DEF -&gt; VARIABLE_DEF\n     *  |   |--MODIFIERS -&gt; MODIFIERS\n     *  |   |--TYPE -&gt; TYPE\n     *  |   |   `--IDENT -&gt; String\n     *  |   |--IDENT -&gt; str\n     *  |   `--ASSIGN -&gt; =\n     *  |       `--EXPR -&gt; EXPR\n     *  |           `--STRING_LITERAL -&gt; \"StringLiteral\"\n     *  |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;3.10.5\n * @see #EXPR\n **/\n public static final int STRING_LITERAL =\n GeneratedJavaTokenTypes.STRING_LITERAL;\n\n /**\n * A single precision floating point literal. This is a floating\n * point number with an {@code F} or {@code f} suffix.\n *\n *

    For example:

    \n *
    \n     * a = 3.14f;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--ASSIGN -&gt; =\n     * |       |--IDENT -&gt; a\n     * |       `--NUM_FLOAT -&gt; 3.14f\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;3.10.2\n * @see #EXPR\n * @see #NUM_DOUBLE\n **/\n public static final int NUM_FLOAT = GeneratedJavaTokenTypes.NUM_FLOAT;\n /**\n * A long integer literal. These are almost the same as integer\n * literals, but they have an {@code L} or {@code l}\n * (ell) suffix.\n *\n *

    For example:

    \n *
    \n     * a = 3l;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--ASSIGN -&gt; =\n     * |       |--IDENT -&gt; a\n     * |       `--NUM_LONG -&gt; 3l\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;3.10.1\n * @see #EXPR\n * @see #NUM_INT\n **/\n public static final int NUM_LONG = GeneratedJavaTokenTypes.NUM_LONG;\n /**\n * A double precision floating point literal. This is a floating\n * point number with an optional {@code D} or {@code d}\n * suffix.\n *\n *

    For example:

    \n *
    \n     * a = 3.14d;\n     * 
    \n *

    parses as:

    \n *
    \n     * |--EXPR -&gt; EXPR\n     * |   `--ASSIGN -&gt; =\n     * |       |--IDENT -&gt; a\n     * |       `--NUM_DOUBLE -&gt; 3.14d\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @see Java\n * Language Specification, &sect;3.10.2\n * @see #EXPR\n * @see #NUM_FLOAT\n **/\n public static final int NUM_DOUBLE = GeneratedJavaTokenTypes.NUM_DOUBLE;\n\n /**\n * The {@code assert} keyword. This is only for Java 1.4 and\n * later.\n *\n *

    For example:

    \n *
    \n     * assert(x==4);\n     * 
    \n *

    parses as:

    \n *
    \n     * +--LITERAL_ASSERT (assert)\n     *     |\n     *     +--EXPR\n     *         |\n     *         +--LPAREN (()\n     *         +--EQUAL (==)\n     *             |\n     *             +--IDENT (x)\n     *             +--NUM_INT (4)\n     *         +--RPAREN ())\n     *     +--SEMI (;)\n     * 
    \n **/\n public static final int LITERAL_ASSERT = GeneratedJavaTokenTypes.ASSERT;\n\n /**\n * A static import declaration. Static import declarations are optional,\n * but must appear after the package declaration and before the type\n * declaration.\n *\n *

    For example:

    \n *
    \n     * import static java.io.IOException;\n     * 
    \n *

    parses as:

    \n *
    \n     * STATIC_IMPORT -&gt; import\n     * |--LITERAL_STATIC -&gt; static\n     * |--DOT -&gt; .\n     * |   |--DOT -&gt; .\n     * |   |   |--IDENT -&gt; java\n     * |   |   `--IDENT -&gt; io\n     * |   `--IDENT -&gt; IOException\n     * `--SEMI -&gt; ;\n     * 
    \n *\n * @see \n * JSR201\n * @see #LITERAL_STATIC\n * @see #DOT\n * @see #IDENT\n * @see #STAR\n * @see #SEMI\n * @see FullIdent\n **/\n public static final int STATIC_IMPORT =\n GeneratedJavaTokenTypes.STATIC_IMPORT;\n\n /**\n * An enum declaration. Its notable children are\n * enum constant declarations followed by\n * any construct that may be expected in a class body.\n *\n *

    For example:

    \n *
    \n     * public enum MyEnum\n     *   implements Serializable\n     * {\n     *     FIRST_CONSTANT,\n     *     SECOND_CONSTANT;\n     *\n     *     public void someMethod()\n     *     {\n     *     }\n     * }\n     * 
    \n *

    parses as:

    \n *
    \n     * +--ENUM_DEF\n     *     |\n     *     +--MODIFIERS\n     *         |\n     *         +--LITERAL_PUBLIC (public)\n     *     +--ENUM (enum)\n     *     +--IDENT (MyEnum)\n     *     +--EXTENDS_CLAUSE\n     *     +--IMPLEMENTS_CLAUSE\n     *         |\n     *         +--IDENT (Serializable)\n     *     +--OBJBLOCK\n     *         |\n     *         +--LCURLY ({)\n     *         +--ENUM_CONSTANT_DEF\n     *             |\n     *             +--IDENT (FIRST_CONSTANT)\n     *         +--COMMA (,)\n     *         +--ENUM_CONSTANT_DEF\n     *             |\n     *             +--IDENT (SECOND_CONSTANT)\n     *         +--SEMI (;)\n     *         +--METHOD_DEF\n     *             |\n     *             +--MODIFIERS\n     *                 |\n     *                 +--LITERAL_PUBLIC (public)\n     *             +--TYPE\n     *                 |\n     *                 +--LITERAL_void (void)\n     *             +--IDENT (someMethod)\n     *             +--LPAREN (()\n     *             +--PARAMETERS\n     *             +--RPAREN ())\n     *             +--SLIST ({)\n     *                 |\n     *                 +--RCURLY (})\n     *         +--RCURLY (})\n     * 
    \n *\n * @see \n * JSR201\n * @see #MODIFIERS\n * @see #ENUM\n * @see #IDENT\n * @see #EXTENDS_CLAUSE\n * @see #IMPLEMENTS_CLAUSE\n * @see #OBJBLOCK\n * @see #LITERAL_NEW\n * @see #ENUM_CONSTANT_DEF\n **/\n public static final int ENUM_DEF =\n GeneratedJavaTokenTypes.ENUM_DEF;\n\n /**\n * The {@code enum} keyword. This element appears\n * as part of an enum declaration.\n **/\n public static final int ENUM =\n GeneratedJavaTokenTypes.ENUM;\n\n /**\n * An enum constant declaration. Its notable children are annotations,\n * arguments and object block akin to an anonymous\n * inner class' body.\n *\n *

    For example:

    \n *
    \n     * SOME_CONSTANT(1)\n     * {\n     *     public void someMethodOverriddenFromMainBody()\n     *     {\n     *     }\n     * }\n     * 
    \n *

    parses as:

    \n *
    \n     * +--ENUM_CONSTANT_DEF\n     *     |\n     *     +--ANNOTATIONS\n     *     +--IDENT (SOME_CONSTANT)\n     *     +--LPAREN (()\n     *     +--ELIST\n     *         |\n     *         +--EXPR\n     *             |\n     *             +--NUM_INT (1)\n     *     +--RPAREN ())\n     *     +--OBJBLOCK\n     *         |\n     *         +--LCURLY ({)\n     *         |\n     *         +--METHOD_DEF\n     *             |\n     *             +--MODIFIERS\n     *                 |\n     *                 +--LITERAL_PUBLIC (public)\n     *             +--TYPE\n     *                 |\n     *                 +--LITERAL_void (void)\n     *             +--IDENT (someMethodOverriddenFromMainBody)\n     *             +--LPAREN (()\n     *             +--PARAMETERS\n     *             +--RPAREN ())\n     *             +--SLIST ({)\n     *                 |\n     *                 +--RCURLY (})\n     *         +--RCURLY (})\n     * 
    \n *\n * @see \n * JSR201\n * @see #ANNOTATIONS\n * @see #MODIFIERS\n * @see #IDENT\n * @see #ELIST\n * @see #OBJBLOCK\n **/\n public static final int ENUM_CONSTANT_DEF =\n GeneratedJavaTokenTypes.ENUM_CONSTANT_DEF;\n\n /**\n * A for-each clause. This is a child of\n * {@code LITERAL_FOR}. The children of this element may be\n * a parameter definition, the colon literal and an expression.\n *\n *

    For example:

    \n *
    \n     * for (int value : values) {\n     *     doSmth();\n     * }\n     * 
    \n *

    parses as:

    \n *
    \n     * --LITERAL_FOR (for)\n     *    |--LPAREN (()\n     *    |--FOR_EACH_CLAUSE\n     *    |   |--VARIABLE_DEF\n     *    |   |   |--MODIFIERS\n     *    |   |   |--TYPE\n     *    |   |   |   `--LITERAL_INT (int)\n     *    |   |   `--IDENT (value)\n     *    |   |--COLON (:)\n     *    |   `--EXPR\n     *    |       `--IDENT (values\n     *    |--RPAREN ())\n     *    `--SLIST ({)\n     *        |--EXPR\n     *        |   `--METHOD_CALL (()\n     *        |       |--IDENT (doSmth)\n     *        |       |--ELIST\n     *        |       `--RPAREN ())\n     *        |--SEMI (;)\n     *        `--RCURLY (})\n     *\n     * 
    \n *\n * @see #VARIABLE_DEF\n * @see #ELIST\n * @see #LITERAL_FOR\n **/\n public static final int FOR_EACH_CLAUSE =\n GeneratedJavaTokenTypes.FOR_EACH_CLAUSE;\n\n /**\n * An annotation declaration. The notable children are the name of the\n * annotation type, annotation field declarations and (constant) fields.\n *\n *

    For example:

    \n *
    \n     * public @interface MyAnnotation\n     * {\n     *     int someValue();\n     * }\n     * 
    \n *

    parses as:

    \n *
    \n     * +--ANNOTATION_DEF\n     *     |\n     *     +--MODIFIERS\n     *         |\n     *         +--LITERAL_PUBLIC (public)\n     *     +--AT (@)\n     *     +--LITERAL_INTERFACE (interface)\n     *     +--IDENT (MyAnnotation)\n     *     +--OBJBLOCK\n     *         |\n     *         +--LCURLY ({)\n     *         +--ANNOTATION_FIELD_DEF\n     *             |\n     *             +--MODIFIERS\n     *             +--TYPE\n     *                 |\n     *                 +--LITERAL_INT (int)\n     *             +--IDENT (someValue)\n     *             +--LPAREN (()\n     *             +--RPAREN ())\n     *             +--SEMI (;)\n     *         +--RCURLY (})\n     * 
    \n *\n * @see \n * JSR201\n * @see #MODIFIERS\n * @see #LITERAL_INTERFACE\n * @see #IDENT\n * @see #OBJBLOCK\n * @see #ANNOTATION_FIELD_DEF\n **/\n public static final int ANNOTATION_DEF =\n GeneratedJavaTokenTypes.ANNOTATION_DEF;\n\n /**\n * An annotation field declaration. The notable children are modifiers,\n * field type, field name and an optional default value (a conditional\n * compile-time constant expression). Default values may also by\n * annotations.\n *\n *

    For example:

    \n *\n *
    \n     *     String someField() default \"Hello world\";\n     * 
    \n *\n *

    parses as:

    \n *\n *
    \n     * +--ANNOTATION_FIELD_DEF\n     *     |\n     *     +--MODIFIERS\n     *     +--TYPE\n     *         |\n     *         +--IDENT (String)\n     *     +--IDENT (someField)\n     *     +--LPAREN (()\n     *     +--RPAREN ())\n     *     +--LITERAL_DEFAULT (default)\n     *     +--STRING_LITERAL (\"Hello world\")\n     *     +--SEMI (;)\n     * 
    \n *\n * @see \n * JSR201\n * @see #MODIFIERS\n * @see #TYPE\n * @see #LITERAL_DEFAULT\n */\n public static final int ANNOTATION_FIELD_DEF =\n GeneratedJavaTokenTypes.ANNOTATION_FIELD_DEF;\n\n // note: &#064; is the html escape for '@',\n // used here to avoid confusing the javadoc tool\n /**\n * A collection of annotations on a package or enum constant.\n * A collections of annotations will only occur on these nodes\n * as all other nodes that may be qualified with an annotation can\n * be qualified with any other modifier and hence these annotations\n * would be contained in a {@link #MODIFIERS} node.\n *\n *

    For example:

    \n *\n *
    \n     *     &#064;MyAnnotation package blah;\n     * 
    \n *\n *

    parses as:

    \n *\n *
    \n     * +--PACKAGE_DEF (package)\n     *     |\n     *     +--ANNOTATIONS\n     *         |\n     *         +--ANNOTATION\n     *             |\n     *             +--AT (&#064;)\n     *             +--IDENT (MyAnnotation)\n     *     +--IDENT (blah)\n     *     +--SEMI (;)\n     * 
    \n *\n * @see \n * JSR201\n * @see #ANNOTATION\n * @see #AT\n * @see #IDENT\n */\n public static final int ANNOTATIONS =\n GeneratedJavaTokenTypes.ANNOTATIONS;\n\n // note: &#064; is the html escape for '@',\n // used here to avoid confusing the javadoc tool\n /**\n * An annotation of a package, type, field, parameter or variable.\n * An annotation may occur anywhere modifiers occur (it is a\n * type of modifier) and may also occur prior to a package definition.\n * The notable children are: The annotation name and either a single\n * default annotation value or a sequence of name value pairs.\n * Annotation values may also be annotations themselves.\n *\n *

    For example:

    \n *\n *
    \n     *     &#064;MyAnnotation(someField1 = \"Hello\",\n     *                    someField2 = &#064;SomeOtherAnnotation)\n     * 
    \n *\n *

    parses as:

    \n *\n *
    \n     * +--ANNOTATION\n     *     |\n     *     +--AT (&#064;)\n     *     +--IDENT (MyAnnotation)\n     *     +--LPAREN (()\n     *     +--ANNOTATION_MEMBER_VALUE_PAIR\n     *         |\n     *         +--IDENT (someField1)\n     *         +--ASSIGN (=)\n     *         +--ANNOTATION\n     *             |\n     *             +--AT (&#064;)\n     *             +--IDENT (SomeOtherAnnotation)\n     *     +--ANNOTATION_MEMBER_VALUE_PAIR\n     *         |\n     *         +--IDENT (someField2)\n     *         +--ASSIGN (=)\n     *         +--STRING_LITERAL (\"Hello\")\n     *     +--RPAREN ())\n     * 
    \n *\n * @see \n * JSR201\n * @see #MODIFIERS\n * @see #IDENT\n * @see #ANNOTATION_MEMBER_VALUE_PAIR\n */\n public static final int ANNOTATION =\n GeneratedJavaTokenTypes.ANNOTATION;\n\n /**\n * An initialization of an annotation member with a value.\n * Its children are the name of the member, the assignment literal\n * and the (compile-time constant conditional expression) value.\n *\n * @see \n * JSR201\n * @see #ANNOTATION\n * @see #IDENT\n */\n public static final int ANNOTATION_MEMBER_VALUE_PAIR =\n GeneratedJavaTokenTypes.ANNOTATION_MEMBER_VALUE_PAIR;\n\n /**\n * An annotation array member initialization.\n * Initializers can not be nested.\n * An initializer may be present as a default to an annotation\n * member, as the single default value to an annotation\n * (e.g. @Annotation({1,2})) or as the value of an annotation\n * member value pair.\n *\n *

    For example:

    \n *\n *
    \n     *     { 1, 2 }\n     * 
    \n *\n *

    parses as:

    \n *\n *
    \n     * +--ANNOTATION_ARRAY_INIT ({)\n     *     |\n     *     +--NUM_INT (1)\n     *     +--COMMA (,)\n     *     +--NUM_INT (2)\n     *     +--RCURLY (})\n     * 
    \n *\n * @see \n * JSR201\n * @see #ANNOTATION\n * @see #IDENT\n * @see #ANNOTATION_MEMBER_VALUE_PAIR\n */\n public static final int ANNOTATION_ARRAY_INIT =\n GeneratedJavaTokenTypes.ANNOTATION_ARRAY_INIT;\n\n /**\n * A list of type parameters to a class, interface or\n * method definition. Children are LT, at least one\n * TYPE_PARAMETER, zero or more of: a COMMAs followed by a single\n * TYPE_PARAMETER and a final GT.\n *\n *

    For example:

    \n *\n *
    \n     * public class MyClass&lt;A, B&gt; {\n     *\n     * }\n     * 
    \n *\n *

    parses as:

    \n *\n *
    \n     * CLASS_DEF -&gt; CLASS_DEF\n     * |--MODIFIERS -&gt; MODIFIERS\n     * |   `--LITERAL_PUBLIC -&gt; public\n     * |--LITERAL_CLASS -&gt; class\n     * |--IDENT -&gt; MyClass\n     * |--TYPE_PARAMETERS -&gt; TYPE_PARAMETERS\n     * |   |--GENERIC_START -&gt; &lt;\n     * |   |--TYPE_PARAMETER -&gt; TYPE_PARAMETER\n     * |   |   `--IDENT -&gt; A\n     * |   |--COMMA -&gt; ,\n     * |   |--TYPE_PARAMETER -&gt; TYPE_PARAMETER\n     * |   |   `--IDENT -&gt; B\n     * |   `--GENERIC_END -&gt; &gt;\n     * `--OBJBLOCK -&gt; OBJBLOCK\n     *     |--LCURLY -&gt; {\n     *     `--RCURLY -&gt; }\n     * 
    \n *\n * @see \n * JSR14\n * @see #GENERIC_START\n * @see #GENERIC_END\n * @see #TYPE_PARAMETER\n * @see #COMMA\n */\n public static final int TYPE_PARAMETERS =\n GeneratedJavaTokenTypes.TYPE_PARAMETERS;\n\n /**\n * A type parameter to a class, interface or method definition.\n * Children are the type name and an optional TYPE_UPPER_BOUNDS.\n *\n *

    For example:

    \n *\n *
    \n     * public class MyClass &lt;A extends Collection&gt; {\n     *\n     * }\n     * 
    \n *\n *

    parses as:

    \n *\n *
    \n     * CLASS_DEF -&gt; CLASS_DEF\n     * |--MODIFIERS -&gt; MODIFIERS\n     * |   `--LITERAL_PUBLIC -&gt; public\n     * |--LITERAL_CLASS -&gt; class\n     * |--IDENT -&gt; MyClass\n     * |--TYPE_PARAMETERS -&gt; TYPE_PARAMETERS\n     * |   |--GENERIC_START -&gt; &lt;\n     * |   |--TYPE_PARAMETER -&gt; TYPE_PARAMETER\n     * |   |   |--IDENT -&gt; A\n     * |   |   `--TYPE_UPPER_BOUNDS -&gt; extends\n     * |   |       `--IDENT -&gt; Collection\n     * |   `--GENERIC_END -&gt; &gt;\n     * `--OBJBLOCK -&gt; OBJBLOCK\n     *     |--LCURLY -&gt; {\n     *     `--RCURLY -&gt; }\n     * 
    \n *\n * @see \n * JSR14\n * @see #IDENT\n * @see #WILDCARD_TYPE\n * @see #TYPE_UPPER_BOUNDS\n */\n public static final int TYPE_PARAMETER =\n GeneratedJavaTokenTypes.TYPE_PARAMETER;\n\n /**\n * A list of type arguments to a type reference or\n * a method/ctor invocation. Children are GENERIC_START, at least one\n * TYPE_ARGUMENT, zero or more of a COMMAs followed by a single\n * TYPE_ARGUMENT, and a final GENERIC_END.\n *\n *

    For example:

    \n *\n *
    \n     *     public Collection&lt;?&gt; a;\n     * 
    \n *\n *

    parses as:

    \n *\n *
    \n     * +--VARIABLE_DEF\n     *     |\n     *     +--MODIFIERS\n     *         |\n     *         +--LITERAL_PUBLIC (public)\n     *     +--TYPE\n     *         |\n     *         +--IDENT (Collection)\n     *             |\n     *             +--TYPE_ARGUMENTS\n     *                 |\n     *                 +--GENERIC_START (&lt;)\n     *                 +--TYPE_ARGUMENT\n     *                     |\n     *                     +--WILDCARD_TYPE (?)\n     *                 +--GENERIC_END (&gt;)\n     *     +--IDENT (a)\n     *     +--SEMI (;)\n     * 
    \n *\n * @see #GENERIC_START\n * @see #GENERIC_END\n * @see #TYPE_ARGUMENT\n * @see #COMMA\n */\n public static final int TYPE_ARGUMENTS =\n GeneratedJavaTokenTypes.TYPE_ARGUMENTS;\n\n /**\n * A type arguments to a type reference or a method/ctor invocation.\n * Children are either: type name or wildcard type with possible type\n * upper or lower bounds.\n *\n *

    For example:

    \n *\n *
    \n     *     ? super List\n     * 
    \n *\n *

    parses as:

    \n *\n *
    \n     * +--TYPE_ARGUMENT\n     *     |\n     *     +--WILDCARD_TYPE (?)\n     *     +--TYPE_LOWER_BOUNDS\n     *         |\n     *         +--IDENT (List)\n     * 
    \n *\n * @see \n * JSR14\n * @see #WILDCARD_TYPE\n * @see #TYPE_UPPER_BOUNDS\n * @see #TYPE_LOWER_BOUNDS\n */\n public static final int TYPE_ARGUMENT =\n GeneratedJavaTokenTypes.TYPE_ARGUMENT;\n\n /**\n * The type that refers to all types. This node has no children.\n *\n * @see \n * JSR14\n * @see #TYPE_ARGUMENT\n * @see #TYPE_UPPER_BOUNDS\n * @see #TYPE_LOWER_BOUNDS\n */\n public static final int WILDCARD_TYPE =\n GeneratedJavaTokenTypes.WILDCARD_TYPE;\n\n /**\n * An upper bounds on a wildcard type argument or type parameter.\n * This node has one child - the type that is being used for\n * the bounding.\n *

    For example:

    \n *
    List&lt;? extends Number&gt; list;
    \n *\n *

    parses as:

    \n *
    \n     * --VARIABLE_DEF -&gt; VARIABLE_DEF\n     *  |--MODIFIERS -&gt; MODIFIERS\n     *  |--TYPE -&gt; TYPE\n     *  |   |--IDENT -&gt; List\n     *  |   `--TYPE_ARGUMENTS -&gt; TYPE_ARGUMENTS\n     *  |       |--GENERIC_START -&gt; &lt;\n     *  |       |--TYPE_ARGUMENT -&gt; TYPE_ARGUMENT\n     *  |       |   |--WILDCARD_TYPE -&gt; ?\n     *  |       |   `--TYPE_UPPER_BOUNDS -&gt; extends\n     *  |       |       `--IDENT -&gt; Number\n     *  |       `--GENERIC_END -&gt; &gt;\n     *  |--IDENT -&gt; list\n     *  `--SEMI -&gt; ;\n     *  
    \n *\n * @see \n * JSR14\n * @see #TYPE_PARAMETER\n * @see #TYPE_ARGUMENT\n * @see #WILDCARD_TYPE\n */\n public static final int TYPE_UPPER_BOUNDS =\n GeneratedJavaTokenTypes.TYPE_UPPER_BOUNDS;\n\n /**\n * A lower bounds on a wildcard type argument. This node has one child\n * - the type that is being used for the bounding.\n *\n *

    For example:

    \n *
    List&lt;? super Integer&gt; list;
    \n *\n *

    parses as:

    \n *
    \n     *  --VARIABLE_DEF -&gt; VARIABLE_DEF\n     *     |--MODIFIERS -&gt; MODIFIERS\n     *     |--TYPE -&gt; TYPE\n     *     |   |--IDENT -&gt; List\n     *     |   `--TYPE_ARGUMENTS -&gt; TYPE_ARGUMENTS\n     *     |       |--GENERIC_START -&gt; &lt;\n     *     |       |--TYPE_ARGUMENT -&gt; TYPE_ARGUMENT\n     *     |       |   |--WILDCARD_TYPE -&gt; ?\n     *     |       |   `--TYPE_LOWER_BOUNDS -&gt; super\n     *     |       |       `--IDENT -&gt; Integer\n     *     |       `--GENERIC_END -&gt; &gt;\n     *     |--IDENT -&gt; list\n     *     `--SEMI -&gt; ;\n     *  
    \n *\n * @see \n * JSR14\n * @see #TYPE_ARGUMENT\n * @see #WILDCARD_TYPE\n */\n public static final int TYPE_LOWER_BOUNDS =\n GeneratedJavaTokenTypes.TYPE_LOWER_BOUNDS;\n\n /**\n * An {@code @} symbol - signifying an annotation instance or the prefix\n * to the interface literal signifying the definition of an annotation\n * declaration.\n *\n * @see \n * JSR201\n */\n public static final int AT = GeneratedJavaTokenTypes.AT;\n\n /**\n * A triple dot for variable-length parameters. This token only ever occurs\n * in a parameter declaration immediately after the type of the parameter.\n *\n * @see \n * JSR201\n */\n public static final int ELLIPSIS = GeneratedJavaTokenTypes.ELLIPSIS;\n\n /**\n * The {@code &} symbol when used to extend a generic upper or lower bounds constrain\n * or a type cast expression with an additional interface.\n *\n *

    Generic type bounds extension:\n * {@code class Comparable}

    \n *
    \n     * CLASS_DEF -&gt; CLASS_DEF\n     * |--MODIFIERS -&gt; MODIFIERS\n     * |--LITERAL_CLASS -&gt; class\n     * |--IDENT -&gt; Comparable\n     * |--TYPE_PARAMETERS -&gt; TYPE_PARAMETERS\n     *     |--GENERIC_START -&gt; &lt;\n     *     |--TYPE_PARAMETER -&gt; TYPE_PARAMETER\n     *     |   |--IDENT -&gt; T\n     *     |   `--TYPE_UPPER_BOUNDS -&gt; extends\n     *     |       |--IDENT -&gt; Serializable\n     *     |       |--TYPE_EXTENSION_AND -&gt; &#38;\n     *     |       `--IDENT -&gt; CharSequence\n     *     `--GENERIC_END -&gt; &gt;\n     * 
    \n *\n *

    Type cast extension:\n * {@code return (Serializable & CharSequence) null;}

    \n *
    \n     * --LITERAL_RETURN -&gt; return\n     *    |--EXPR -&gt; EXPR\n     *    |   `--TYPECAST -&gt; (\n     *    |       |--TYPE -&gt; TYPE\n     *    |       |   `--IDENT -&gt; Serializable\n     *    |       |--TYPE_EXTENSION_AND -&gt; &#38;\n     *    |       |--TYPE -&gt; TYPE\n     *    |       |   `--IDENT -&gt; CharSequence\n     *    |       |--RPAREN -&gt; )\n     *    |       `--LITERAL_NULL -&gt; null\n     *    `--SEMI -&gt; ;\n     * 
    \n *\n * @see #EXTENDS_CLAUSE\n * @see #TYPECAST\n * @see \n * Java Language Specification, &sect;4.4\n * @see \n * Java Language Specification, &sect;15.16\n */\n public static final int TYPE_EXTENSION_AND =\n GeneratedJavaTokenTypes.TYPE_EXTENSION_AND;\n\n /**\n * A {@code <} symbol signifying the start of type arguments or type parameters.\n */\n public static final int GENERIC_START =\n GeneratedJavaTokenTypes.GENERIC_START;\n\n /**\n * A {@code >} symbol signifying the end of type arguments or type parameters.\n */\n public static final int GENERIC_END = GeneratedJavaTokenTypes.GENERIC_END;\n\n /**\n * Special lambda symbol {@code ->}.\n */\n public static final int LAMBDA = GeneratedJavaTokenTypes.LAMBDA;\n\n /**\n * Beginning of single line comment: '//'.\n *\n *
    \n     * +--SINGLE_LINE_COMMENT\n     *         |\n     *         +--COMMENT_CONTENT\n     * 
    \n */\n public static final int SINGLE_LINE_COMMENT =\n GeneratedJavaTokenTypes.SINGLE_LINE_COMMENT;\n\n /**\n * Beginning of block comment: '/*'.\n *

    For example:

    \n *
    \n     * /&#42; Comment content\n     * &#42;/\n     * 
    \n *

    parses as:

    \n *
    \n     * --BLOCK_COMMENT_BEGIN -&gt; /&#42;\n     *    |--COMMENT_CONTENT -&gt;  Comment content\\r\\n\n     *    `--BLOCK_COMMENT_END -&gt; &#42;/\n     * 
    \n */\n public static final int BLOCK_COMMENT_BEGIN =\n GeneratedJavaTokenTypes.BLOCK_COMMENT_BEGIN;\n\n /**\n * End of block comment: '&#42;/'.\n *\n *
    \n     * +--BLOCK_COMMENT_BEGIN\n     *         |\n     *         +--COMMENT_CONTENT\n     *         +--BLOCK_COMMENT_END\n     * 
    \n */\n public static final int BLOCK_COMMENT_END =\n GeneratedJavaTokenTypes.BLOCK_COMMENT_END;\n\n /**\n * Text of single-line or block comment.\n *\n *
    \n     * +--SINGLE_LINE_COMMENT\n     *         |\n     *         +--COMMENT_CONTENT\n     * 
    \n *\n *
    \n     * +--BLOCK_COMMENT_BEGIN\n     *         |\n     *         +--COMMENT_CONTENT\n     *         +--BLOCK_COMMENT_END\n     * 
    \n */\n public static final int COMMENT_CONTENT =\n GeneratedJavaTokenTypes.COMMENT_CONTENT;\n\n /**\n * A pattern variable definition; when conditionally matched,\n * this variable is assigned with the defined type.\n *\n *

    For example:

    \n *
    \n     * if (obj instanceof String str) { }\n     * 
    \n *

    parses as:

    \n *
    \n     * LITERAL_IF (if)\n     *  |--LPAREN (()\n     *  |--EXPR\n     *  |   `--LITERAL_INSTANCEOF (instanceof)\n     *  |       |--IDENT (obj)\n     *  |       `--PATTERN_VARIABLE_DEF\n     *  |            |--TYPE\n     *  |            |   `--IDENT (String)\n     *  |            `--IDENT (str)\n     *  |--RPAREN ())\n     *  `--SLIST ({)\n     *      `--RCURLY (})\n     * 
    \n *\n * @see #LITERAL_INSTANCEOF\n * @since 8.35\n */\n public static final int PATTERN_VARIABLE_DEF =\n GeneratedJavaTokenTypes.PATTERN_VARIABLE_DEF;\n\n /**\n * The {@code record} keyword. This element appears\n * as part of a record declaration.\n *\n * @since 8.35\n **/\n public static final int LITERAL_RECORD =\n GeneratedJavaTokenTypes.LITERAL_record;\n\n /**\n * A declaration of a record specifies a name, a header, and a body.\n * The header lists the components of the record, which are the variables\n * that make up its state.\n *\n *

    For example:

    \n *
    \n     * public record MyRecord () {\n     *\n     * }\n     * 
    \n *

    parses as:

    \n *
    \n     * RECORD_DEF -&gt; RECORD_DEF\n     * |--MODIFIERS -&gt; MODIFIERS\n     * |   `--LITERAL_PUBLIC -&gt; public\n     * |--LITERAL_RECORD -&gt; record\n     * |--IDENT -&gt; MyRecord\n     * |--LPAREN -&gt; (\n     * |--RECORD_COMPONENTS -&gt; RECORD_COMPONENTS\n     * |--RPAREN -&gt; )\n     * `--OBJBLOCK -&gt; OBJBLOCK\n     *     |--LCURLY -&gt; {\n     *     `--RCURLY -&gt; }\n     * 
    \n *\n * @since 8.35\n */\n public static final int RECORD_DEF =\n GeneratedJavaTokenTypes.RECORD_DEF;\n\n /**\n * Record components are a (possibly empty) list containing the components of a record, which\n * are the variables that make up its state.\n *\n *

    For example:

    \n *
    \n     * public record myRecord (Comp x, Comp y) { }\n     * 
    \n *

    parses as:

    \n *
    \n     * RECORD_DEF -&gt; RECORD_DEF\n     *  |--MODIFIERS -&gt; MODIFIERS\n     *  |   `--LITERAL_PUBLIC -&gt; public\n     *  |--LITERAL_RECORD -&gt; record\n     *  |--IDENT -&gt; myRecord\n     *  |--LPAREN -&gt; (\n     *  |--RECORD_COMPONENTS -&gt; RECORD_COMPONENTS\n     *  |   |--RECORD_COMPONENT_DEF -&gt; RECORD_COMPONENT_DEF\n     *  |   |   |--ANNOTATIONS -&gt; ANNOTATIONS\n     *  |   |   |--TYPE -&gt; TYPE\n     *  |   |   |   `--IDENT -&gt; Comp\n     *  |   |   `--IDENT -&gt; x\n     *  |   |--COMMA -&gt; ,\n     *  |   `--RECORD_COMPONENT_DEF -&gt; RECORD_COMPONENT_DEF\n     *  |       |--ANNOTATIONS -&gt; ANNOTATIONS\n     *  |       |--TYPE -&gt; TYPE\n     *  |       |   `--IDENT -&gt; Comp\n     *  |       `--IDENT -&gt; y\n     *  |--RPAREN -&gt; )\n     *  `--OBJBLOCK -&gt; OBJBLOCK\n     *      |--LCURLY -&gt; {\n     *      `--RCURLY -&gt; }\n     * 
    \n *\n * @since 8.36\n */\n public static final int RECORD_COMPONENTS =\n GeneratedJavaTokenTypes.RECORD_COMPONENTS;\n\n /**\n * A record component is a variable that comprises the state of a record. Record components\n * have annotations (possibly), a type definition, and an identifier. They can also be of\n * variable arity ('...').\n *\n *

    For example:

    \n *
    \n     * public record MyRecord(Comp x, Comp... comps) {\n     *\n     * }\n     * 
    \n *

    parses as:

    \n *
    \n     * RECORD_DEF -&gt; RECORD_DEF\n     * |--MODIFIERS -&gt; MODIFIERS\n     * |   `--LITERAL_PUBLIC -&gt; public\n     * |--LITERAL_RECORD -&gt; record\n     * |--IDENT -&gt; MyRecord\n     * |--LPAREN -&gt; (\n     * |--RECORD_COMPONENTS -&gt; RECORD_COMPONENTS\n     * |   |--RECORD_COMPONENT_DEF -&gt; RECORD_COMPONENT_DEF\n     * |   |   |--ANNOTATIONS -&gt; ANNOTATIONS\n     * |   |   |--TYPE -&gt; TYPE\n     * |   |   |   `--IDENT -&gt; Comp\n     * |   |   `--IDENT -&gt; x\n     * |   |--COMMA -&gt; ,\n     * |   `--RECORD_COMPONENT_DEF -&gt; RECORD_COMPONENT_DEF\n     * |       |--ANNOTATIONS -&gt; ANNOTATIONS\n     * |       |--TYPE -&gt; TYPE\n     * |       |   `--IDENT -&gt; Comp\n     * |       |--ELLIPSIS -&gt; ...\n     * |       `--IDENT -&gt; comps\n     * |--RPAREN -&gt; )\n     * `--OBJBLOCK -&gt; OBJBLOCK\n     *     |--LCURLY -&gt; {\n     *     `--RCURLY -&gt; }\n     * 
    \n *\n * @since 8.36\n */\n public static final int RECORD_COMPONENT_DEF =\n GeneratedJavaTokenTypes.RECORD_COMPONENT_DEF;\n\n /**\n * A compact canonical constructor eliminates the list of formal parameters; they are\n * declared implicitly.\n *\n *

    For example:

    \n *
    \n     * public record myRecord () {\n     *     public myRecord{}\n     * }\n     * 
    \n *

    parses as:

    \n *
    \n     * RECORD_DEF\n     * |--MODIFIERS\n     * |   `--LITERAL_PUBLIC (public)\n     * |--LITERAL_RECORD (record)\n     * |--IDENT (myRecord)\n     * |--LPAREN (()\n     * |--RECORD_COMPONENTS\n     * |--RPAREN ())\n     * `--OBJBLOCK\n     *     |--LCURLY ({)\n     *     |--COMPACT_CTOR_DEF\n     *     |   |--MODIFIERS\n     *     |   |   `--LITERAL_PUBLIC (public)\n     *     |   |--IDENT (myRecord)\n     *     |   `--SLIST ({)\n     *     |       `--RCURLY (})\n     *     `--RCURLY (})\n     * 
    \n *\n * @since 8.36\n */\n public static final int COMPACT_CTOR_DEF =\n GeneratedJavaTokenTypes.COMPACT_CTOR_DEF;\n\n /**\n * Beginning of a Java 14 Text Block literal,\n * delimited by three double quotes.\n *\n *

    For example:

    \n *
    \n     *         String hello = \"\"\"\n     *                 Hello, world!\n     *                 \"\"\";\n     * 
    \n *

    parses as:

    \n *
    \n     * |--VARIABLE_DEF -&gt; VARIABLE_DEF\n     * |   |--MODIFIERS -&gt; MODIFIERS\n     * |   |--TYPE -&gt; TYPE\n     * |   |   `--IDENT -&gt; String\n     * |   |--IDENT -&gt; hello\n     * |   `--ASSIGN -&gt; =\n     * |       `--EXPR -&gt; EXPR\n     * |           `--TEXT_BLOCK_LITERAL_BEGIN -&gt; \"\"\"\n     * |               |--TEXT_BLOCK_CONTENT -&gt; \\n                Hello, world!\\n\n     * |               `--TEXT_BLOCK_LITERAL_END -&gt; \"\"\"\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @since 8.36\n */\n public static final int TEXT_BLOCK_LITERAL_BEGIN =\n GeneratedJavaTokenTypes.TEXT_BLOCK_LITERAL_BEGIN;\n\n /**\n * Content of a Java 14 text block. This is a\n * sequence of characters, possibly escaped with '\\'. Actual line terminators\n * are represented by '\\n'.\n *\n *

    For example:

    \n *
    \n     *         String hello = \"\"\"\n     *                 Hello, world!\n     *                 \"\"\";\n     * 
    \n *

    parses as:

    \n *
    \n     * |--VARIABLE_DEF -&gt; VARIABLE_DEF\n     * |   |--MODIFIERS -&gt; MODIFIERS\n     * |   |--TYPE -&gt; TYPE\n     * |   |   `--IDENT -&gt; String\n     * |   |--IDENT -&gt; hello\n     * |   `--ASSIGN -&gt; =\n     * |       `--EXPR -&gt; EXPR\n     * |           `--TEXT_BLOCK_LITERAL_BEGIN -&gt; \"\"\"\n     * |               |--TEXT_BLOCK_CONTENT -&gt; \\n                Hello, world!\\n\n     * |               `--TEXT_BLOCK_LITERAL_END -&gt; \"\"\"\n     * |--SEMI -&gt; ;\n     * 
    \n *\n * @since 8.36\n */\n public static final int TEXT_BLOCK_CONTENT =\n GeneratedJavaTokenTypes.TEXT_BLOCK_CONTENT;\n\n /**\n * End of a Java 14 text block literal, delimited by three\n * double quotes.\n *\n *

    For example:

    \n *
    \n     *         String hello = \"\"\"\n     *                 Hello, world!\n     *                 \"\"\";\n     * 
    \n *

    parses as:

    \n *
    \n     * |--VARIABLE_DEF\n     * |   |--MODIFIERS\n     * |   |--TYPE\n     * |   |   `--IDENT (String)\n     * |   |--IDENT (hello)\n     * |   |--ASSIGN (=)\n     * |   |   `--EXPR\n     * |   |       `--TEXT_BLOCK_LITERAL_BEGIN (\"\"\")\n     * |   |           |--TEXT_BLOCK_CONTENT (\\n                Hello, world!\\n                    )\n     * |   |           `--TEXT_BLOCK_LITERAL_END (\"\"\")\n     * |   `--SEMI (;)\n     * 
    \n *\n * @since 8.36\n */\n public static final int TEXT_BLOCK_LITERAL_END =\n GeneratedJavaTokenTypes.TEXT_BLOCK_LITERAL_END;\n\n /**\n * The {@code yield} keyword. This element appears\n * as part of a yield statement.\n *\n *

    For example:

    \n *
    \n     * int yield = 0; // not a keyword here\n     * return switch (mode) {\n     *    case \"a\", \"b\":\n     *        yield 1;\n     *    default:\n     *        yield - 1;\n     * };\n     * 
    \n *

    parses as:

    \n *
    \n     * |--VARIABLE_DEF\n     * |   |--MODIFIERS\n     * |   |--TYPE\n     * |   |   `--LITERAL_INT (int)\n     * |   |--IDENT (yield)\n     * |   `--ASSIGN (=)\n     * |       `--EXPR\n     * |           `--NUM_INT (0)\n     * |--SEMI (;)\n     * |--LITERAL_RETURN (return)\n     * |   |--EXPR\n     * |   |   `--LITERAL_SWITCH (switch)\n     * |   |       |--LPAREN (()\n     * |   |       |--EXPR\n     * |   |       |   `--IDENT (mode)\n     * |   |       |--RPAREN ())\n     * |   |       |--LCURLY ({)\n     * |   |       |--CASE_GROUP\n     * |   |       |   |--LITERAL_CASE (case)\n     * |   |       |   |   |--EXPR\n     * |   |       |   |   |   `--STRING_LITERAL (\"a\")\n     * |   |       |   |   |--COMMA (,)\n     * |   |       |   |   |--EXPR\n     * |   |       |   |   |   `--STRING_LITERAL (\"b\")\n     * |   |       |   |   `--COLON (:)\n     * |   |       |   `--SLIST\n     * |   |       |       `--LITERAL_YIELD (yield)\n     * |   |       |           |--EXPR\n     * |   |       |           |   `--NUM_INT (1)\n     * |   |       |           `--SEMI (;)\n     * |   |       |--CASE_GROUP\n     * |   |       |   |--LITERAL_DEFAULT (default)\n     * |   |       |   |   `--COLON (:)\n     * |   |       |   `--SLIST\n     * |   |       |       `--LITERAL_YIELD (yield)\n     * |   |       |           |--EXPR\n     * |   |       |           |   `--UNARY_MINUS (-)\n     * |   |       |           |       `--NUM_INT (1)\n     * |   |       |           `--SEMI (;)\n     * |   |       `--RCURLY (})\n     * |   `--SEMI (;)\n     * 
    \n *\n *\n * @see #LITERAL_SWITCH\n * @see #CASE_GROUP\n * @see #SLIST\n * @see #SWITCH_RULE\n *\n * @see \n * Java Language Specification, &sect;14.21\n *\n * @since 8.36\n */\n public static final int LITERAL_YIELD =\n GeneratedJavaTokenTypes.LITERAL_yield;\n\n /**\n * Switch Expressions.\n *\n *

    For example:

    \n *
    \n     * return switch (day) {\n     *     case SAT, SUN {@code ->} \"Weekend\";\n     *     default {@code ->} \"Working day\";\n     * };\n     * 
    \n *

    parses as:

    \n *
    \n     *  LITERAL_RETURN (return)\n     *   |--EXPR\n     *   |   `--LITERAL_SWITCH (switch)\n     *   |       |--LPAREN (()\n     *   |       |--EXPR\n     *   |       |   `--IDENT (day)\n     *   |       |--RPAREN ())\n     *   |       |--LCURLY ({)\n     *   |       |--SWITCH_RULE\n     *   |       |   |--LITERAL_CASE (case)\n     *   |       |   |   |--EXPR\n     *   |       |   |   |   `--IDENT (SAT)\n     *   |       |   |   |--COMMA (,)\n     *   |       |   |   `--EXPR\n     *   |       |   |       `--IDENT (SUN)\n     *   |       |   |--LAMBDA {@code ->}\n     *   |       |   |--EXPR\n     *   |       |   |   `--STRING_LITERAL (\"Weekend\")\n     *   |       |   `--SEMI (;)\n     *   |       |--SWITCH_RULE\n     *   |       |   |--LITERAL_DEFAULT (default)\n     *   |       |   |--LAMBDA {@code ->}\n     *   |       |   |--EXPR\n     *   |       |   |   `--STRING_LITERAL (\"Working day\")\n     *   |       |   `--SEMI (;)\n     *   |       `--RCURLY (})\n     *   `--SEMI (;)\n     * 
    \n *\n * @see #LITERAL_CASE\n * @see #LITERAL_DEFAULT\n * @see #LITERAL_SWITCH\n * @see #LITERAL_YIELD\n *\n * @see \n * Java Language Specification, &sect;14.21\n *\n * @since 8.36\n */\n public static final int SWITCH_RULE =\n GeneratedJavaTokenTypes.SWITCH_RULE;\n\n /** Prevent instantiation. */\n private TokenTypes() {\n }\n\n}\n"},"message":{"kind":"string","value":"Issue #9595: Update example of AST for TokenTypes.VARIABLE_DEF\n"},"old_file":{"kind":"string","value":"src/main/java/com/puppycrawl/tools/checkstyle/api/TokenTypes.java"},"subject":{"kind":"string","value":"Issue #9595: Update example of AST for TokenTypes.VARIABLE_DEF"},"git_diff":{"kind":"string","value":"rc/main/java/com/puppycrawl/tools/checkstyle/api/TokenTypes.java\n * A field or local variable declaration. The children are\n * modifiers, type, the identifier name, and an optional\n * assignment statement.\n *\n *

    For example:

    \n *
    \n     * final int PI = 3.14;\n     * 
    \n *

    parses as:

    \n *
    \n     * VARIABLE_DEF -&gt; VARIABLE_DEF\n     *  |--MODIFIERS -&gt; MODIFIERS\n     *  |   `--FINAL -&gt; final\n     *  |--TYPE -&gt; TYPE\n     *  |   `--LITERAL_INT -&gt; int\n     *  |--IDENT -&gt; PI\n     *  |--ASSIGN -&gt; =\n     *  |   `--EXPR -&gt; EXPR\n     *  |       `--NUM_FLOAT -&gt; 3.14\n     *  `--SEMI -&gt; ;\n     * 
    \n *\n * @see #MODIFIERS\n * @see #TYPE"}}},{"rowIdx":1973,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"f3836a35f87ff8ecf0517f17926c7b45b231c5a0"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"LeafToDus/My-Blog,GJson/My-Blog,GJson/My-Blog,LeafToDus/My-Blog,LeafToDus/My-Blog,GJson/My-Blog,LeafToDus/My-Blog,GJson/My-Blog"},"new_contents":{"kind":"string","value":"package com.my.blog.website.utils;\n\nimport com.my.blog.website.exception.TipException;\nimport com.my.blog.website.constant.WebConst;\nimport com.my.blog.website.controller.admin.AttachController;\nimport com.my.blog.website.modal.Vo.UserVo;\nimport org.apache.commons.lang3.StringUtils;\nimport org.commonmark.node.Node;\nimport org.commonmark.parser.Parser;\nimport org.commonmark.renderer.html.HtmlRenderer;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.jdbc.datasource.DriverManagerDataSource;\n\nimport javax.imageio.ImageIO;\nimport javax.servlet.http.Cookie;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport javax.servlet.http.HttpSession;\nimport javax.sql.DataSource;\nimport java.awt.*;\nimport java.io.*;\nimport java.security.MessageDigest;\nimport java.security.NoSuchAlgorithmException;\nimport java.text.Normalizer;\nimport java.util.Date;\nimport java.util.Properties;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\n/**\n * Tale工具类\n *

    \n * Created by 13 on 2017/2/21.\n */\npublic class TaleUtils {\n private static final Logger LOGGER = LoggerFactory.getLogger(TaleUtils.class);\n\n private static DataSource newDataSource;\n /**\n * 一个月\n */\n private static final int one_month = 30 * 24 * 60 * 60;\n /**\n * 匹配邮箱正则\n */\n private static final Pattern VALID_EMAIL_ADDRESS_REGEX =\n Pattern.compile(\"^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\\\.[A-Z]{2,6}$\", Pattern.CASE_INSENSITIVE);\n private static final Pattern SLUG_REGEX = Pattern.compile(\"^[A-Za-z0-9_-]{5,100}$\", Pattern.CASE_INSENSITIVE);\n /**\n * markdown解析器\n */\n private static Parser parser = Parser.builder().build();\n /**\n * 获取文件所在目录\n */\n private static String location = TaleUtils.class.getClassLoader().getResource(\"\").getPath();\n\n /**\n * 判断是否是邮箱\n *\n * @param emailStr\n * @return\n */\n public static boolean isEmail(String emailStr) {\n Matcher matcher = VALID_EMAIL_ADDRESS_REGEX.matcher(emailStr);\n return matcher.find();\n }\n\n /**\n * @param fileName 获取jar外部的文件\n * @return 返回属性\n */\n private static Properties getPropFromFile(String fileName) {\n Properties properties = new Properties();\n try {\n// 默认是classPath路径\n InputStream resourceAsStream = new FileInputStream(fileName);\n properties.load(resourceAsStream);\n } catch (TipException | IOException e) {\n LOGGER.error(\"get properties file fail={}\", e.getMessage());\n }\n return properties;\n }\n\n /**\n * md5加密\n *\n * @param source 数据源\n * @return 加密字符串\n */\n public static String MD5encode(String source) {\n if (StringUtils.isBlank(source)) {\n return null;\n }\n MessageDigest messageDigest = null;\n try {\n messageDigest = MessageDigest.getInstance(\"MD5\");\n } catch (NoSuchAlgorithmException ignored) {\n }\n byte[] encode = messageDigest.digest(source.getBytes());\n StringBuilder hexString = new StringBuilder();\n for (byte anEncode : encode) {\n String hex = Integer.toHexString(0xff & anEncode);\n if (hex.length() == 1) {\n hexString.append('0');\n }\n hexString.append(hex);\n }\n return hexString.toString();\n }\n\n /**\n * 获取新的数据源\n *\n * @return\n */\n public static DataSource getNewDataSource() {\n if (newDataSource == null) synchronized (TaleUtils.class) {\n if (newDataSource == null) {\n Properties properties = TaleUtils.getPropFromFile(\"application-jdbc.properties\");\n if (properties.size() == 0) {\n return newDataSource;\n }\n DriverManagerDataSource managerDataSource = new DriverManagerDataSource();\n managerDataSource.setDriverClassName(\"com.mysql.jdbc.Driver\");\n managerDataSource.setPassword(properties.getProperty(\"spring.datasource.password\"));\n String str = \"jdbc:mysql://\" + properties.getProperty(\"spring.datasource.url\") + \"/\" + properties.getProperty(\"spring.datasource.dbname\") + \"?useUnicode=true&characterEncoding=utf-8&useSSL=false\";\n managerDataSource.setUrl(str);\n managerDataSource.setUsername(properties.getProperty(\"spring.datasource.username\"));\n newDataSource = managerDataSource;\n }\n }\n return newDataSource;\n }\n\n /**\n * 返回当前登录用户\n *\n * @return\n */\n public static UserVo getLoginUser(HttpServletRequest request) {\n HttpSession session = request.getSession();\n if (null == session) {\n return null;\n }\n return (UserVo) session.getAttribute(WebConst.LOGIN_SESSION_KEY);\n }\n\n\n /**\n * 获取cookie中的用户id\n *\n * @param request\n * @return\n */\n public static Integer getCookieUid(HttpServletRequest request) {\n if (null != request) {\n Cookie cookie = cookieRaw(WebConst.USER_IN_COOKIE, request);\n if (cookie != null && cookie.getValue() != null) {\n try {\n String uid = Tools.deAes(cookie.getValue(), WebConst.AES_SALT);\n return StringUtils.isNotBlank(uid) && Tools.isNumber(uid) ? Integer.valueOf(uid) : null;\n } catch (Exception e) {\n }\n }\n }\n return null;\n }\n\n /**\n * 从cookies中获取指定cookie\n *\n * @param name 名称\n * @param request 请求\n * @return cookie\n */\n private static Cookie cookieRaw(String name, HttpServletRequest request) {\n javax.servlet.http.Cookie[] servletCookies = request.getCookies();\n if (servletCookies == null) {\n return null;\n }\n for (javax.servlet.http.Cookie c : servletCookies) {\n if (c.getName().equals(name)) {\n return c;\n }\n }\n return null;\n }\n\n /**\n * 设置记住密码cookie\n *\n * @param response\n * @param uid\n */\n public static void setCookie(HttpServletResponse response, Integer uid) {\n try {\n String val = Tools.enAes(uid.toString(), WebConst.AES_SALT);\n boolean isSSL = false;\n Cookie cookie = new Cookie(WebConst.USER_IN_COOKIE, val);\n cookie.setPath(\"/\");\n cookie.setMaxAge(60*30);\n cookie.setSecure(isSSL);\n response.addCookie(cookie);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n /**\n * 提取html中的文字\n *\n * @param html\n * @return\n */\n public static String htmlToText(String html) {\n if (StringUtils.isNotBlank(html)) {\n return html.replaceAll(\"(?s)<[^>]*>(\\\\s*<[^>]*>)*\", \" \");\n }\n return \"\";\n }\n\n /**\n * markdown转换为html\n *\n * @param markdown\n * @return\n */\n public static String mdToHtml(String markdown) {\n if (StringUtils.isBlank(markdown)) {\n return \"\";\n }\n Node document = parser.parse(markdown);\n HtmlRenderer renderer = HtmlRenderer.builder().build();\n String content = renderer.render(document);\n content = Commons.emoji(content);\n return content;\n }\n\n /**\n * 退出登录状态\n *\n * @param session\n * @param response\n */\n public static void logout(HttpSession session, HttpServletResponse response) {\n session.removeAttribute(WebConst.LOGIN_SESSION_KEY);\n Cookie cookie = new Cookie(WebConst.USER_IN_COOKIE, \"\");\n cookie.setMaxAge(0);\n response.addCookie(cookie);\n try {\n response.sendRedirect(Commons.site_url());\n } catch (IOException e) {\n LOGGER.error(e.getMessage(), e);\n }\n }\n\n /**\n * 替换HTML脚本\n *\n * @param value\n * @return\n */\n public static String cleanXSS(String value) {\n //You'll need to remove the spaces from the html entities below\n value = value.replaceAll(\"<\", \"&lt;\").replaceAll(\">\", \"&gt;\");\n value = value.replaceAll(\"\\\\(\", \"&#40;\").replaceAll(\"\\\\)\", \"&#41;\");\n value = value.replaceAll(\"'\", \"&#39;\");\n value = value.replaceAll(\"eval\\\\((.*)\\\\)\", \"\");\n value = value.replaceAll(\"[\\\\\\\"\\\\\\'][\\\\s]*javascript:(.*)[\\\\\\\"\\\\\\']\", \"\\\"\\\"\");\n value = value.replaceAll(\"script\", \"\");\n return value;\n }\n\n /**\n * 过滤XSS注入\n *\n * @param value\n * @return\n */\n public static String filterXSS(String value) {\n String cleanValue = null;\n if (value != null) {\n cleanValue = Normalizer.normalize(value, Normalizer.Form.NFD);\n // Avoid null characters\n cleanValue = cleanValue.replaceAll(\"\\0\", \"\");\n\n // Avoid anything between script tags\n Pattern scriptPattern = Pattern.compile(\"\", Pattern.CASE_INSENSITIVE);\n cleanValue = scriptPattern.matcher(cleanValue).replaceAll(\"\");\n\n // Avoid anything in a src='...' type of expression\n scriptPattern = Pattern.compile(\"src[\\r\\n]*=[\\r\\n]*\\\\\\'(.*?)\\\\\\'\", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);\n cleanValue = scriptPattern.matcher(cleanValue).replaceAll(\"\");\n\n scriptPattern = Pattern.compile(\"src[\\r\\n]*=[\\r\\n]*\\\\\\\"(.*?)\\\\\\\"\", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);\n cleanValue = scriptPattern.matcher(cleanValue).replaceAll(\"\");\n\n // Remove any lonesome tag\n scriptPattern = Pattern.compile(\"\", Pattern.CASE_INSENSITIVE);\n cleanValue = scriptPattern.matcher(cleanValue).replaceAll(\"\");\n\n // Remove any lonesome \");\n// }\n return content;\n }\n\n /**\n * 退出登录状态\n *\n * @param session\n * @param response\n */\n public static void logout(HttpSession session, HttpServletResponse response) {\n session.removeAttribute(WebConst.LOGIN_SESSION_KEY);\n Cookie cookie = new Cookie(WebConst.USER_IN_COOKIE, \"\");\n cookie.setMaxAge(0);\n response.addCookie(cookie);\n try {\n response.sendRedirect(Commons.site_url());\n } catch (IOException e) {\n LOGGER.error(e.getMessage(), e);\n }\n }\n\n /**\n * 替换HTML脚本\n *\n * @param value\n * @return\n */\n public static String cleanXSS(String value) {\n //You'll need to remove the spaces from the html entities below\n value = value.replaceAll(\"<\", \"&lt;\").replaceAll(\">\", \"&gt;\");\n value = value.replaceAll(\"\\\\(\", \"&#40;\").replaceAll(\"\\\\)\", \"&#41;\");\n value = value.replaceAll(\"'\", \"&#39;\");\n value = value.replaceAll(\"eval\\\\((.*)\\\\)\", \"\");\n value = value.replaceAll(\"[\\\\\\\"\\\\\\'][\\\\s]*javascript:(.*)[\\\\\\\"\\\\\\']\", \"\\\"\\\"\");\n value = value.replaceAll(\"script\", \"\");\n return value;\n }\n\n /**\n * 过滤XSS注入\n *\n * @param value\n * @return\n */\n public static String filterXSS(String value) {\n String cleanValue = null;\n if (value != null) {\n cleanValue = Normalizer.normalize(value, Normalizer.Form.NFD);\n // Avoid null characters\n cleanValue = cleanValue.replaceAll(\"\\0\", \"\");\n\n // Avoid anything between script tags\n Pattern scriptPattern = Pattern.compile(\"\", Pattern.CASE_INSENSITIVE);\n cleanValue = scriptPattern.matcher(cleanValue).replaceAll(\"\");\n\n // Avoid anything in a src='...' type of expression\n scriptPattern = Pattern.compile(\"src[\\r\\n]*=[\\r\\n]*\\\\\\'(.*?)\\\\\\'\", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);\n cleanValue = scriptPattern.matcher(cleanValue).replaceAll(\"\");\n\n scriptPattern = Pattern.compile(\"src[\\r\\n]*=[\\r\\n]*\\\\\\\"(.*?)\\\\\\\"\", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);\n cleanValue = scriptPattern.matcher(cleanValue).replaceAll(\"\");\n\n // Remove any lonesome tag\n scriptPattern = Pattern.compile(\"\", Pattern.CASE_INSENSITIVE);\n cleanValue = scriptPattern.matcher(cleanValue).replaceAll(\"\");\n\n // Remove any lonesome \");\n// }\n return content;\n }\n "}}},{"rowIdx":1974,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"24ddb66e2cf1da48eefd2ad6c6a66eb5ef137ffd"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"henrichg/PhoneProfilesPlus"},"new_contents":{"kind":"string","value":"package sk.henrichg.phoneprofilesplus;\n\nimport android.annotation.SuppressLint;\nimport android.app.Activity;\nimport android.app.ActivityManager;\nimport android.app.NotificationManager;\nimport android.app.PendingIntent;\nimport android.content.BroadcastReceiver;\nimport android.content.ComponentName;\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.content.Intent;\nimport android.content.IntentFilter;\nimport android.content.SharedPreferences;\nimport android.content.SharedPreferences.Editor;\nimport android.content.pm.LabeledIntent;\nimport android.content.pm.PackageInfo;\nimport android.content.pm.ResolveInfo;\nimport android.media.AudioManager;\nimport android.net.Uri;\nimport android.os.AsyncTask;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.os.Environment;\nimport android.os.Handler;\nimport android.util.Log;\nimport android.view.LayoutInflater;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.view.ViewTreeObserver;\nimport android.widget.AdapterView;\nimport android.widget.AdapterView.OnItemSelectedListener;\nimport android.widget.ImageView;\nimport android.widget.Toast;\n\nimport com.crashlytics.android.Crashlytics;\nimport com.getkeepsafe.taptargetview.TapTarget;\nimport com.getkeepsafe.taptargetview.TapTargetSequence;\nimport com.google.android.material.bottomnavigation.BottomNavigationView;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.ObjectInputStream;\nimport java.io.ObjectOutputStream;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\nimport androidx.annotation.NonNull;\nimport androidx.appcompat.app.AlertDialog;\nimport androidx.appcompat.app.AppCompatActivity;\nimport androidx.appcompat.widget.AppCompatSpinner;\nimport androidx.appcompat.widget.Toolbar;\nimport androidx.appcompat.widget.TooltipCompat;\nimport androidx.core.app.NotificationCompat;\nimport androidx.core.content.ContextCompat;\nimport androidx.core.content.FileProvider;\nimport androidx.fragment.app.Fragment;\nimport androidx.localbroadcastmanager.content.LocalBroadcastManager;\nimport me.drakeet.support.toast.ToastCompat;\nimport sk.henrichg.phoneprofilesplus.EditorEventListFragment.OnStartEventPreferences;\nimport sk.henrichg.phoneprofilesplus.EditorProfileListFragment.OnStartProfilePreferences;\n\npublic class EditorProfilesActivity extends AppCompatActivity\n implements OnStartProfilePreferences,\n OnStartEventPreferences\n{\n\n //private static volatile EditorProfilesActivity instance;\n\n private ImageView eventsRunStopIndicator;\n\n private static boolean savedInstanceStateChanged;\n\n private static ApplicationsCache applicationsCache;\n\n private AsyncTask importAsyncTask = null;\n private AsyncTask exportAsyncTask = null;\n static boolean doImport = false;\n private AlertDialog importProgressDialog = null;\n private AlertDialog exportProgressDialog = null;\n\n private static final String SP_EDITOR_SELECTED_VIEW = \"editor_selected_view\";\n private static final String SP_EDITOR_PROFILES_VIEW_SELECTED_ITEM = \"editor_profiles_view_selected_item\";\n static final String SP_EDITOR_EVENTS_VIEW_SELECTED_ITEM = \"editor_events_view_selected_item\";\n\n private static final int DSI_PROFILES_ALL = 0;\n private static final int DSI_PROFILES_SHOW_IN_ACTIVATOR = 1;\n private static final int DSI_PROFILES_NO_SHOW_IN_ACTIVATOR = 2;\n private static final int DSI_EVENTS_START_ORDER = 0;\n private static final int DSI_EVENTS_ALL = 1;\n private static final int DSI_EVENTS_NOT_STOPPED = 2;\n private static final int DSI_EVENTS_RUNNING = 3;\n private static final int DSI_EVENTS_PAUSED = 4;\n private static final int DSI_EVENTS_STOPPED = 5;\n\n static final String EXTRA_NEW_PROFILE_MODE = \"new_profile_mode\";\n static final String EXTRA_PREDEFINED_PROFILE_INDEX = \"predefined_profile_index\";\n static final String EXTRA_NEW_EVENT_MODE = \"new_event_mode\";\n static final String EXTRA_PREDEFINED_EVENT_INDEX = \"predefined_event_index\";\n\n // request code for startActivityForResult with intent BackgroundActivateProfileActivity\n static final int REQUEST_CODE_ACTIVATE_PROFILE = 6220;\n // request code for startActivityForResult with intent ProfilesPrefsActivity\n private static final int REQUEST_CODE_PROFILE_PREFERENCES = 6221;\n // request code for startActivityForResult with intent EventPreferencesActivity\n private static final int REQUEST_CODE_EVENT_PREFERENCES = 6222;\n // request code for startActivityForResult with intent PhoneProfilesActivity\n private static final int REQUEST_CODE_APPLICATION_PREFERENCES = 6229;\n // request code for startActivityForResult with intent \"phoneprofiles.intent.action.EXPORTDATA\"\n private static final int REQUEST_CODE_REMOTE_EXPORT = 6250;\n\n public boolean targetHelpsSequenceStarted;\n public static final String PREF_START_TARGET_HELPS = \"editor_profiles_activity_start_target_helps\";\n public static final String PREF_START_TARGET_HELPS_DEFAULT_PROFILE = \"editor_profile_activity_start_target_helps_default_profile\";\n public static final String PREF_START_TARGET_HELPS_FILTER_SPINNER = \"editor_profile_activity_start_target_helps_filter_spinner\";\n @SuppressWarnings(\"WeakerAccess\")\n public static final String PREF_START_TARGET_HELPS_RUN_STOP_INDICATOR = \"editor_profile_activity_start_target_helps_run_stop_indicator\";\n @SuppressWarnings(\"WeakerAccess\")\n public static final String PREF_START_TARGET_HELPS_BOTTOM_NAVIGATION = \"editor_profile_activity_start_target_helps_bottom_navigation\";\n\n private Toolbar editorToolbar;\n //Toolbar bottomToolbar;\n //private DrawerLayout drawerLayout;\n //private PPScrimInsetsFrameLayout drawerRoot;\n //private ListView drawerListView;\n //private ActionBarDrawerToggle drawerToggle;\n //private BottomNavigationView bottomNavigationView;\n private AppCompatSpinner filterSpinner;\n //private AppCompatSpinner orderSpinner;\n //private View headerView;\n //private ImageView drawerHeaderFilterImage;\n //private TextView drawerHeaderFilterTitle;\n //private TextView drawerHeaderFilterSubtitle;\n private BottomNavigationView bottomNavigationView;\n\n //private String[] drawerItemsTitle;\n //private String[] drawerItemsSubtitle;\n //private Integer[] drawerItemsIcon;\n\n private int editorSelectedView = 0;\n private int filterProfilesSelectedItem = 0;\n private int filterEventsSelectedItem = 0;\n\n private boolean startTargetHelps;\n\n AddProfileDialog addProfileDialog;\n AddEventDialog addEventDialog;\n\n private final BroadcastReceiver refreshGUIBroadcastReceiver = new BroadcastReceiver() {\n @Override\n public void onReceive( Context context, Intent intent ) {\n boolean refresh = intent.getBooleanExtra(RefreshActivitiesBroadcastReceiver.EXTRA_REFRESH, true);\n boolean refreshIcons = intent.getBooleanExtra(RefreshActivitiesBroadcastReceiver.EXTRA_REFRESH_ICONS, false);\n long profileId = intent.getLongExtra(PPApplication.EXTRA_PROFILE_ID, 0);\n long eventId = intent.getLongExtra(PPApplication.EXTRA_EVENT_ID, 0);\n // not change selection in editor if refresh is outside editor\n EditorProfilesActivity.this.refreshGUI(refresh, refreshIcons, false, profileId, eventId);\n }\n };\n\n private final BroadcastReceiver showTargetHelpsBroadcastReceiver = new BroadcastReceiver() {\n @Override\n public void onReceive( Context context, Intent intent ) {\n Fragment fragment = EditorProfilesActivity.this.getSupportFragmentManager().findFragmentById(R.id.editor_list_container);\n if (fragment != null) {\n if (fragment instanceof EditorProfileListFragment)\n ((EditorProfileListFragment) fragment).showTargetHelps();\n else\n ((EditorEventListFragment) fragment).showTargetHelps();\n }\n }\n };\n\n private final BroadcastReceiver finishBroadcastReceiver = new BroadcastReceiver() {\n @Override\n public void onReceive( Context context, Intent intent ) {\n PPApplication.logE(\"EditorProfilesActivity.finishBroadcastReceiver\", \"xxx\");\n String action = intent.getAction();\n if (action.equals(PPApplication.ACTION_FINISH_ACTIVITY)) {\n String what = intent.getStringExtra(PPApplication.EXTRA_WHAT_FINISH);\n if (what.equals(\"editor\")) {\n try {\n EditorProfilesActivity.this.finishAffinity();\n } catch (Exception ignored) {}\n }\n }\n }\n };\n\n @SuppressLint({\"NewApi\", \"RestrictedApi\"})\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n GlobalGUIRoutines.setTheme(this, false, true/*, true*/, false);\n //GlobalGUIRoutines.setLanguage(this);\n\n savedInstanceStateChanged = (savedInstanceState != null);\n\n createApplicationsCache();\n\n /*if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)\n setContentView(R.layout.activity_editor_list_onepane_19);\n else*/\n setContentView(R.layout.activity_editor_list_onepane);\n setTaskDescription(new ActivityManager.TaskDescription(getString(R.string.app_name)));\n\n //drawerLayout = findViewById(R.id.editor_list_drawer_layout);\n\n /*\n if (Build.VERSION.SDK_INT >= 21) {\n drawerLayout.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {\n @Override\n public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {\n int statusBarHeight = insets.getSystemWindowInsetTop();\n PPApplication.logE(\"EditorProfilesActivity.onApplyWindowInsets\", \"statusBarHeight=\"+statusBarHeight);\n Rect rect = insets.getSystemWindowInsets();\n PPApplication.logE(\"EditorProfilesActivity.onApplyWindowInsets\", \"rect.top=\"+rect.top);\n rect.top = rect.top + statusBarHeight;\n return insets.replaceSystemWindowInsets(rect);\n }\n }\n );\n }\n */\n\n //overridePendingTransition(R.anim.fade_in, R.anim.fade_out);\n\n //String appTheme = ApplicationPreferences.applicationTheme(getApplicationContext(), true);\n\n /*\n if ((Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)) {\n Window w = getWindow(); // in Activity's onCreate() for instance\n //w.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);\n w.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);\n\n // create our manager instance after the content view is set\n SystemBarTintManager tintManager = new SystemBarTintManager(this);\n // enable status bar tint\n tintManager.setStatusBarTintEnabled(true);\n // set a custom tint color for status bar\n switch (appTheme) {\n case \"color\":\n tintManager.setStatusBarTintColor(ContextCompat.getColor(getBaseContext(), R.color.primary));\n break;\n case \"white\":\n tintManager.setStatusBarTintColor(ContextCompat.getColor(getBaseContext(), R.color.primaryDark19_white));\n break;\n default:\n tintManager.setStatusBarTintColor(ContextCompat.getColor(getBaseContext(), R.color.primary_dark));\n break;\n }\n }\n */\n\n //if (android.os.Build.VERSION.SDK_INT >= 21)\n //\tgetWindow().setNavigationBarColor(R.attr.colorPrimary);\n\n //setWindowContentOverlayCompat();\n\n /*\t// add profile list into list container\n EditorProfileListFragment fragment = new EditorProfileListFragment();\n getSupportFragmentManager().beginTransaction()\n .replace(R.id.editor_list_container, fragment, \"EditorProfileListFragment\").commit(); */\n\n /*\n drawerRoot = findViewById(R.id.editor_drawer_root);\n\n // set status bar background for Activity body layout\n switch (appTheme) {\n case \"color\":\n drawerLayout.setStatusBarBackground(R.color.primaryDark);\n break;\n case \"white\":\n drawerLayout.setStatusBarBackground(R.color.primaryDark_white);\n break;\n case \"dark\":\n drawerLayout.setStatusBarBackground(R.color.primaryDark_dark);\n break;\n case \"dlight\":\n drawerLayout.setStatusBarBackground(R.color.primaryDark_dark);\n break;\n }\n\n drawerListView = findViewById(R.id.editor_drawer_list);\n //noinspection ConstantConditions\n headerView = ((LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE)).\n inflate(R.layout.editor_drawer_list_header, drawerListView, false);\n drawerListView.addHeaderView(headerView, null, false);\n drawerHeaderFilterImage = findViewById(R.id.editor_drawer_list_header_icon);\n drawerHeaderFilterTitle = findViewById(R.id.editor_drawer_list_header_title);\n drawerHeaderFilterSubtitle = findViewById(R.id.editor_drawer_list_header_subtitle);\n\n // set header padding for notches\n //if (Build.VERSION.SDK_INT >= 21) {\n drawerRoot.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {\n @Override\n public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {\n headerView.setPadding(\n headerView.getPaddingLeft(),\n headerView.getPaddingTop() + insets.getSystemWindowInsetTop(),\n headerView.getPaddingRight(),\n headerView.getPaddingBottom());\n insets.consumeSystemWindowInsets();\n drawerRoot.setOnApplyWindowInsetsListener(null);\n return insets;\n }\n });\n //}\n\n //if (Build.VERSION.SDK_INT < 21)\n // drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);\n\n // actionbar titles\n drawerItemsTitle = new String[] {\n getResources().getString(R.string.editor_drawer_title_profiles),\n getResources().getString(R.string.editor_drawer_title_profiles),\n getResources().getString(R.string.editor_drawer_title_profiles),\n getResources().getString(R.string.editor_drawer_title_events),\n getResources().getString(R.string.editor_drawer_title_events),\n getResources().getString(R.string.editor_drawer_title_events),\n getResources().getString(R.string.editor_drawer_title_events),\n getResources().getString(R.string.editor_drawer_title_events)\n };\n\n // drawer item titles\n drawerItemsSubtitle = new String[] {\n getResources().getString(R.string.editor_drawer_list_item_profiles_all),\n getResources().getString(R.string.editor_drawer_list_item_profiles_show_in_activator),\n getResources().getString(R.string.editor_drawer_list_item_profiles_no_show_in_activator),\n getResources().getString(R.string.editor_drawer_list_item_events_start_order),\n getResources().getString(R.string.editor_drawer_list_item_events_all),\n getResources().getString(R.string.editor_drawer_list_item_events_running),\n getResources().getString(R.string.editor_drawer_list_item_events_paused),\n getResources().getString(R.string.editor_drawer_list_item_events_stopped)\n };\n\n drawerItemsIcon = new Integer[] {\n R.drawable.ic_events_drawer_profile_filter_2,\n R.drawable.ic_events_drawer_profile_filter_0,\n R.drawable.ic_events_drawer_profile_filter_1,\n R.drawable.ic_events_drawer_event_filter_2,\n R.drawable.ic_events_drawer_event_filter_2,\n R.drawable.ic_events_drawer_event_filter_0,\n R.drawable.ic_events_drawer_event_filter_1,\n R.drawable.ic_events_drawer_event_filter_3,\n };\n\n\n // Pass string arrays to EditorDrawerListAdapter\n // use action bar themed context\n //drawerAdapter = new EditorDrawerListAdapter(drawerListView, getSupportActionBar().getThemedContext(), drawerItemsTitle, drawerItemsSubtitle, drawerItemsIcon);\n EditorDrawerListAdapter drawerAdapter = new EditorDrawerListAdapter(getBaseContext(), drawerItemsTitle, drawerItemsSubtitle, drawerItemsIcon);\n \n // Set the MenuListAdapter to the ListView\n drawerListView.setAdapter(drawerAdapter);\n \n // Capture listview menu item click\n drawerListView.setOnItemClickListener(new DrawerItemClickListener());\n */\n\n editorToolbar = findViewById(R.id.editor_toolbar);\n setSupportActionBar(editorToolbar);\n if (getSupportActionBar() != null) {\n getSupportActionBar().setTitle(R.string.title_activity_editor);\n }\n\n //bottomToolbar = findViewById(R.id.editor_list_bottom_bar);\n\n /*\n // Enable ActionBar app icon to behave as action to toggle nav drawer\n if (getSupportActionBar() != null) {\n getSupportActionBar().setHomeButtonEnabled(true);\n getSupportActionBar().setDisplayHomeAsUpEnabled(true);\n }\n */\n\n /*\n // is required. This adds hamburger icon in toolbar\n drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.editor_drawer_open, R.string.editor_drawer_open)\n {\n public void onDrawerClosed(View view) {\n super.onDrawerClosed(view);\n }\n \n public void onDrawerOpened(View drawerView) {\n super.onDrawerOpened(drawerView);\n }\n // this disable animation\n //@Override\n //public void onDrawerSlide(View drawerView, float slideOffset)\n //{\n // if(drawerView!=null && drawerView == drawerRoot){\n // super.onDrawerSlide(drawerView, 0);\n // }else{\n // super.onDrawerSlide(drawerView, slideOffset);\n // }\n //}\n };\n drawerLayout.addDrawerListener(drawerToggle);\n */\n\n bottomNavigationView = findViewById(R.id.editor_list_bottom_navigation);\n bottomNavigationView.setOnNavigationItemSelectedListener(\n new BottomNavigationView.OnNavigationItemSelectedListener() {\n @Override\n public boolean onNavigationItemSelected(@NonNull MenuItem item) {\n switch (item.getItemId()) {\n case R.id.menu_profiles_view:\n //Log.e(\"EditorProfilesActivity.onNavigationItemSelected\", \"menu_profiles_view\");\n String[] filterItems = new String[] {\n getString(R.string.editor_drawer_title_profiles) + \" - \" + getString(R.string.editor_drawer_list_item_profiles_all),\n getString(R.string.editor_drawer_title_profiles) + \" - \" + getString(R.string.editor_drawer_list_item_profiles_show_in_activator),\n getString(R.string.editor_drawer_title_profiles) + \" - \" + getString(R.string.editor_drawer_list_item_profiles_no_show_in_activator),\n };\n GlobalGUIRoutines.HighlightedSpinnerAdapter filterSpinnerAdapter = new GlobalGUIRoutines.HighlightedSpinnerAdapter(\n EditorProfilesActivity.this,\n R.layout.highlighted_filter_spinner,\n filterItems);\n filterSpinnerAdapter.setDropDownViewResource(R.layout.highlighted_spinner_dropdown);\n filterSpinner.setAdapter(filterSpinnerAdapter);\n selectFilterItem(0, filterProfilesSelectedItem, false, startTargetHelps);\n Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.editor_list_container);\n if (fragment instanceof EditorProfileListFragment)\n ((EditorProfileListFragment)fragment).showHeaderAndBottomToolbar();\n break;\n case R.id.menu_events_view:\n //Log.e(\"EditorProfilesActivity.onNavigationItemSelected\", \"menu_events_view\");\n filterItems = new String[] {\n getString(R.string.editor_drawer_title_events) + \" - \" + getString(R.string.editor_drawer_list_item_events_start_order),\n getString(R.string.editor_drawer_title_events) + \" - \" + getString(R.string.editor_drawer_list_item_events_all),\n getString(R.string.editor_drawer_title_events) + \" - \" + getString(R.string.editor_drawer_list_item_events_not_stopped),\n getString(R.string.editor_drawer_title_events) + \" - \" + getString(R.string.editor_drawer_list_item_events_running),\n getString(R.string.editor_drawer_title_events) + \" - \" + getString(R.string.editor_drawer_list_item_events_paused),\n getString(R.string.editor_drawer_title_events) + \" - \" + getString(R.string.editor_drawer_list_item_events_stopped)\n };\n filterSpinnerAdapter = new GlobalGUIRoutines.HighlightedSpinnerAdapter(\n EditorProfilesActivity.this,\n R.layout.highlighted_filter_spinner,\n filterItems);\n filterSpinnerAdapter.setDropDownViewResource(R.layout.highlighted_spinner_dropdown);\n filterSpinner.setAdapter(filterSpinnerAdapter);\n selectFilterItem(1, filterEventsSelectedItem, false, startTargetHelps);\n fragment = getSupportFragmentManager().findFragmentById(R.id.editor_list_container);\n if (fragment instanceof EditorEventListFragment) {\n ((EditorEventListFragment)fragment).showHeaderAndBottomToolbar();\n }\n break;\n }\n return true;\n }\n });\n\n filterSpinner = findViewById(R.id.editor_filter_spinner);\n String[] filterItems = new String[] {\n getString(R.string.editor_drawer_title_profiles) + \" - \" + getString(R.string.editor_drawer_list_item_profiles_all),\n getString(R.string.editor_drawer_title_profiles) + \" - \" + getString(R.string.editor_drawer_list_item_profiles_show_in_activator),\n getString(R.string.editor_drawer_title_profiles) + \" - \" + getString(R.string.editor_drawer_list_item_profiles_no_show_in_activator)\n };\n GlobalGUIRoutines.HighlightedSpinnerAdapter filterSpinnerAdapter = new GlobalGUIRoutines.HighlightedSpinnerAdapter(\n this,\n R.layout.highlighted_filter_spinner,\n filterItems);\n filterSpinnerAdapter.setDropDownViewResource(R.layout.highlighted_spinner_dropdown);\n filterSpinner.setPopupBackgroundResource(R.drawable.popupmenu_background);\n filterSpinner.setSupportBackgroundTintList(ContextCompat.getColorStateList(this/*getBaseContext()*/, R.color.highlighted_spinner_all));\n/* switch (appTheme) {\n case \"dark\":\n filterSpinner.setSupportBackgroundTintList(ContextCompat.getColorStateList(getBaseContext(), R.color.editorFilterTitleColor_dark));\n //filterSpinner.setPopupBackgroundResource(R.drawable.popupmenu_background_dark);\n break;\n case \"white\":\n filterSpinner.setSupportBackgroundTintList(ContextCompat.getColorStateList(getBaseContext(), R.color.editorFilterTitleColor_white));\n //filterSpinner.setPopupBackgroundResource(R.drawable.popupmenu_background_white);\n break;\n// case \"dlight\":\n// filterSpinner.setSupportBackgroundTintList(ContextCompat.getColorStateList(getBaseContext(), R.color.editorFilterTitleColor));\n// filterSpinner.setPopupBackgroundResource(R.drawable.popupmenu_background_dlight);\n// break;\n default:\n filterSpinner.setSupportBackgroundTintList(ContextCompat.getColorStateList(getBaseContext(), R.color.editorFilterTitleColor));\n //filterSpinner.setPopupBackgroundResource(R.drawable.popupmenu_background_white);\n break;\n }*/\n filterSpinner.setAdapter(filterSpinnerAdapter);\n filterSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {\n\n public void onItemSelected(AdapterView parent, View view, int position, long id) {\n ((GlobalGUIRoutines.HighlightedSpinnerAdapter)filterSpinner.getAdapter()).setSelection(position);\n selectFilterItem(editorSelectedView, position, true, true);\n }\n\n public void onNothingSelected(AdapterView parent) {\n }\n });\n\n eventsRunStopIndicator = findViewById(R.id.editor_list_run_stop_indicator);\n TooltipCompat.setTooltipText(eventsRunStopIndicator, getString(R.string.editor_activity_targetHelps_trafficLightIcon_title));\n eventsRunStopIndicator.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n RunStopIndicatorPopupWindow popup = new RunStopIndicatorPopupWindow(getDataWrapper(), EditorProfilesActivity.this);\n\n View contentView = popup.getContentView();\n contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);\n int popupWidth = contentView.getMeasuredWidth();\n //int popupHeight = contentView.getMeasuredHeight();\n //Log.d(\"ActivateProfileActivity.eventsRunStopIndicator.onClick\",\"popupWidth=\"+popupWidth);\n //Log.d(\"ActivateProfileActivity.eventsRunStopIndicator.onClick\",\"popupHeight=\"+popupHeight);\n\n int[] runStopIndicatorLocation = new int[2];\n //eventsRunStopIndicator.getLocationOnScreen(runStopIndicatorLocation);\n eventsRunStopIndicator.getLocationInWindow(runStopIndicatorLocation);\n\n int x = 0;\n int y = 0;\n\n if (runStopIndicatorLocation[0] + eventsRunStopIndicator.getWidth() - popupWidth < 0)\n x = -(runStopIndicatorLocation[0] + eventsRunStopIndicator.getWidth() - popupWidth);\n\n popup.setClippingEnabled(false); // disabled for draw outside activity\n popup.showOnAnchor(eventsRunStopIndicator, RelativePopupWindow.VerticalPosition.ALIGN_TOP,\n RelativePopupWindow.HorizontalPosition.ALIGN_RIGHT, x, y, false);\n }\n });\n \n // set drawer item and order\n //if ((savedInstanceState != null) || (ApplicationPreferences.applicationEditorSaveEditorState(getApplicationContext())))\n //{\n ApplicationPreferences.getSharedPreferences(this);\n //filterSelectedItem = ApplicationPreferences.preferences.getInt(SP_EDITOR_DRAWER_SELECTED_ITEM, 1);\n editorSelectedView = ApplicationPreferences.preferences.getInt(SP_EDITOR_SELECTED_VIEW, 0);\n filterProfilesSelectedItem = ApplicationPreferences.preferences.getInt(SP_EDITOR_PROFILES_VIEW_SELECTED_ITEM, 0);\n filterEventsSelectedItem = ApplicationPreferences.preferences.getInt(SP_EDITOR_EVENTS_VIEW_SELECTED_ITEM, 0);\n //}\n\n startTargetHelps = false;\n if (editorSelectedView == 0)\n bottomNavigationView.setSelectedItemId(R.id.menu_profiles_view);\n else\n bottomNavigationView.setSelectedItemId(R.id.menu_events_view);\n /*\n if (editorSelectedView == 0)\n selectFilterItem(filterProfilesSelectedItem, false, false, false);\n else\n selectFilterItem(filterEventsSelectedItem, false, false, false);\n */\n\n /*\n // not working good, all activity is under status bar\n ViewCompat.setOnApplyWindowInsetsListener(drawerLayout, new OnApplyWindowInsetsListener() {\n @Override\n public WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) {\n int statusBarSize = insets.getSystemWindowInsetTop();\n PPApplication.logE(\"EditorProfilesActivity.onApplyWindowInsets\", \"statusBarSize=\"+statusBarSize);\n return insets;\n }\n });\n */\n\n getApplicationContext().registerReceiver(finishBroadcastReceiver, new IntentFilter(PPApplication.ACTION_FINISH_ACTIVITY));\n }\n\n @Override\n protected void onStart()\n {\n super.onStart();\n PPApplication.logE(\"EditorProfilesActivity.onStart\", \"xxx\");\n\n Intent intent = new Intent(PPApplication.ACTION_FINISH_ACTIVITY);\n intent.putExtra(PPApplication.EXTRA_WHAT_FINISH, \"activator\");\n getApplicationContext().sendBroadcast(intent);\n\n LocalBroadcastManager.getInstance(this).registerReceiver(refreshGUIBroadcastReceiver,\n new IntentFilter(PPApplication.PACKAGE_NAME + \".RefreshEditorGUIBroadcastReceiver\"));\n LocalBroadcastManager.getInstance(this).registerReceiver(showTargetHelpsBroadcastReceiver,\n new IntentFilter(PPApplication.PACKAGE_NAME + \".ShowEditorTargetHelpsBroadcastReceiver\"));\n\n refreshGUI(true, false, true, 0, 0);\n\n // this is for list widget header\n if (!PPApplication.getApplicationStarted(getApplicationContext(), true))\n {\n if (PPApplication.logEnabled()) {\n PPApplication.logE(\"EditorProfilesActivity.onStart\", \"application is not started\");\n PPApplication.logE(\"EditorProfilesActivity.onStart\", \"service instance=\" + PhoneProfilesService.getInstance());\n if (PhoneProfilesService.getInstance() != null)\n PPApplication.logE(\"EditorProfilesActivity.onStart\", \"service hasFirstStart=\" + PhoneProfilesService.getInstance().getServiceHasFirstStart());\n }\n // start PhoneProfilesService\n //PPApplication.firstStartServiceStarted = false;\n PPApplication.setApplicationStarted(getApplicationContext(), true);\n Intent serviceIntent = new Intent(getApplicationContext(), PhoneProfilesService.class);\n //serviceIntent.putExtra(PhoneProfilesService.EXTRA_ONLY_START, true);\n serviceIntent.putExtra(PhoneProfilesService.EXTRA_DEACTIVATE_PROFILE, true);\n serviceIntent.putExtra(PhoneProfilesService.EXTRA_ACTIVATE_PROFILES, true);\n PPApplication.startPPService(this, serviceIntent);\n }\n else\n {\n if ((PhoneProfilesService.getInstance() == null) || (!PhoneProfilesService.getInstance().getServiceHasFirstStart())) {\n if (PPApplication.logEnabled()) {\n PPApplication.logE(\"EditorProfilesActivity.onStart\", \"application is started\");\n PPApplication.logE(\"EditorProfilesActivity.onStart\", \"service instance=\" + PhoneProfilesService.getInstance());\n if (PhoneProfilesService.getInstance() != null)\n PPApplication.logE(\"EditorProfilesActivity.onStart\", \"service hasFirstStart=\" + PhoneProfilesService.getInstance().getServiceHasFirstStart());\n }\n // start PhoneProfilesService\n //PPApplication.firstStartServiceStarted = false;\n Intent serviceIntent = new Intent(getApplicationContext(), PhoneProfilesService.class);\n //serviceIntent.putExtra(PhoneProfilesService.EXTRA_ONLY_START, true);\n serviceIntent.putExtra(PhoneProfilesService.EXTRA_DEACTIVATE_PROFILE, true);\n serviceIntent.putExtra(PhoneProfilesService.EXTRA_ACTIVATE_PROFILES, false);\n PPApplication.startPPService(this, serviceIntent);\n }\n else {\n PPApplication.logE(\"EditorProfilesActivity.onStart\", \"application and service is started\");\n }\n }\n }\n\n @Override\n protected void onStop()\n {\n super.onStop();\n PPApplication.logE(\"EditorProfilesActivity.onStop\", \"xxx\");\n\n LocalBroadcastManager.getInstance(this).unregisterReceiver(refreshGUIBroadcastReceiver);\n LocalBroadcastManager.getInstance(this).unregisterReceiver(showTargetHelpsBroadcastReceiver);\n\n if ((addProfileDialog != null) && (addProfileDialog.mDialog != null) && addProfileDialog.mDialog.isShowing())\n addProfileDialog.mDialog.dismiss();\n if ((addEventDialog != null) && (addEventDialog.mDialog != null) && addEventDialog.mDialog.isShowing())\n addEventDialog.mDialog.dismiss();\n }\n\n @Override\n protected void onDestroy()\n {\n super.onDestroy();\n\n if ((importProgressDialog != null) && importProgressDialog.isShowing()) {\n importProgressDialog.dismiss();\n importProgressDialog = null;\n }\n if ((exportProgressDialog != null) && exportProgressDialog.isShowing()) {\n exportProgressDialog.dismiss();\n exportProgressDialog = null;\n }\n if ((importAsyncTask != null) && !importAsyncTask.getStatus().equals(AsyncTask.Status.FINISHED)){\n importAsyncTask.cancel(true);\n doImport = false;\n }\n if ((exportAsyncTask != null) && !exportAsyncTask.getStatus().equals(AsyncTask.Status.FINISHED)){\n exportAsyncTask.cancel(true);\n }\n\n if (!savedInstanceStateChanged)\n {\n // no destroy caches on orientation change\n if (applicationsCache != null)\n applicationsCache.clearCache(true);\n applicationsCache = null;\n }\n\n getApplicationContext().unregisterReceiver(finishBroadcastReceiver);\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n // Inflate the menu; this adds items to the action bar if it is present.\n editorToolbar.inflateMenu(R.menu.editor_top_bar);\n return true;\n }\n\n private static void onNextLayout(final View view, final Runnable runnable) {\n final ViewTreeObserver observer = view.getViewTreeObserver();\n observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {\n @Override\n public void onGlobalLayout() {\n final ViewTreeObserver trueObserver;\n\n if (observer.isAlive()) {\n trueObserver = observer;\n } else {\n trueObserver = view.getViewTreeObserver();\n }\n\n trueObserver.removeOnGlobalLayoutListener(this);\n\n runnable.run();\n }\n });\n }\n\n @SuppressLint(\"AlwaysShowAction\")\n @Override\n public boolean onPrepareOptionsMenu(Menu menu) {\n boolean ret = super.onPrepareOptionsMenu(menu);\n\n MenuItem menuItem;\n\n //menuItem = menu.findItem(R.id.menu_import_export);\n //menuItem.setTitle(getResources().getString(R.string.menu_import_export) + \" >\");\n\n // change global events run/stop menu item title\n menuItem = menu.findItem(R.id.menu_run_stop_events);\n if (menuItem != null)\n {\n if (Event.getGlobalEventsRunning(getApplicationContext()))\n {\n menuItem.setTitle(R.string.menu_stop_events);\n menuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);\n }\n else\n {\n menuItem.setTitle(R.string.menu_run_events);\n menuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);\n }\n }\n\n menuItem = menu.findItem(R.id.menu_restart_events);\n if (menuItem != null)\n {\n menuItem.setVisible(Event.getGlobalEventsRunning(getApplicationContext()));\n menuItem.setEnabled(PPApplication.getApplicationStarted(getApplicationContext(), true));\n }\n\n menuItem = menu.findItem(R.id.menu_dark_theme);\n if (menuItem != null)\n {\n String appTheme = ApplicationPreferences.applicationTheme(getApplicationContext(), false);\n if (!appTheme.equals(\"night_mode\")) {\n menuItem.setVisible(true);\n if (appTheme.equals(\"dark\"))\n menuItem.setTitle(R.string.menu_dark_theme_off);\n else\n menuItem.setTitle(R.string.menu_dark_theme_on);\n }\n else\n menuItem.setVisible(false);\n }\n\n menuItem = menu.findItem(R.id.menu_email_debug_logs_to_author);\n if (menuItem != null)\n {\n menuItem.setVisible(PPApplication.logIntoFile || PPApplication.crashIntoFile);\n }\n\n menuItem = menu.findItem(R.id.menu_test_crash);\n if (menuItem != null)\n {\n menuItem.setVisible(BuildConfig.DEBUG);\n }\n\n onNextLayout(editorToolbar, new Runnable() {\n @Override\n public void run() {\n showTargetHelps();\n }\n });\n\n return ret;\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n\n Intent intent;\n\n DataWrapper dataWrapper = getDataWrapper();\n\n switch (item.getItemId()) {\n/* case android.R.id.home:\n// if (drawerLayout.isDrawerOpen(drawerRoot)) {\n// drawerLayout.closeDrawer(drawerRoot);\n// } else {\n// drawerLayout.openDrawer(drawerRoot);\n// }\n return super.onOptionsItemSelected(item);*/\n case R.id.menu_restart_events:\n //getDataWrapper().addActivityLog(DatabaseHandler.ALTYPE_RESTARTEVENTS, null, null, null, 0);\n\n // ignore manual profile activation\n // and unblock forceRun events\n PPApplication.logE(\"$$$ restartEvents\",\"from EditorProfilesActivity.onOptionsItemSelected menu_restart_events\");\n if (dataWrapper != null)\n dataWrapper.restartEventsWithAlert(this);\n return true;\n case R.id.menu_run_stop_events:\n if (dataWrapper != null)\n dataWrapper.runStopEventsWithAlert(this, null, false);\n return true;\n case R.id.menu_activity_log:\n intent = new Intent(getBaseContext(), ActivityLogActivity.class);\n startActivity(intent);\n return true;\n case R.id.important_info:\n intent = new Intent(getBaseContext(), ImportantInfoActivity.class);\n startActivity(intent);\n return true;\n case R.id.menu_settings:\n intent = new Intent(getBaseContext(), PhoneProfilesPrefsActivity.class);\n startActivityForResult(intent, REQUEST_CODE_APPLICATION_PREFERENCES);\n return true;\n case R.id.menu_dark_theme:\n String theme = ApplicationPreferences.applicationTheme(getApplicationContext(), false);\n if (!theme.equals(\"night_mode\")) {\n if (theme.equals(\"dark\")) {\n SharedPreferences preferences = ApplicationPreferences.getSharedPreferences(getApplicationContext());\n //theme = preferences.getString(ApplicationPreferences.PREF_APPLICATION_NOT_DARK_THEME, \"white\");\n //theme = ApplicationPreferences.applicationNightModeOffTheme(getApplicationContext());\n Editor editor = preferences.edit();\n editor.putString(ApplicationPreferences.PREF_APPLICATION_THEME, \"white\"/*theme*/);\n editor.apply();\n } else {\n SharedPreferences preferences = ApplicationPreferences.getSharedPreferences(getApplicationContext());\n Editor editor = preferences.edit();\n //editor.putString(ApplicationPreferences.PREF_APPLICATION_NOT_DARK_THEME, theme);\n editor.putString(ApplicationPreferences.PREF_APPLICATION_THEME, \"dark\");\n editor.apply();\n }\n GlobalGUIRoutines.switchNightMode(getApplicationContext(), false);\n GlobalGUIRoutines.reloadActivity(this, true);\n }\n return true;\n case R.id.menu_export:\n exportData(false, false);\n\n return true;\n case R.id.menu_export_and_email:\n exportData(true, false);\n\n return true;\n case R.id.menu_import:\n importData();\n\n return true;\n /*case R.id.menu_help:\n try {\n Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"https://github.com/henrichg/PhoneProfilesPlus/wiki\"));\n startActivity(myIntent);\n } catch (ActivityNotFoundException e) {\n ToastCompat.makeText(getApplicationContext(), \"No application can handle this request.\"\n + \" Please install a web browser\", Toast.LENGTH_LONG).show();\n }\n return true;*/\n case R.id.menu_email_to_author:\n intent = new Intent(Intent.ACTION_SENDTO);\n intent.setData(Uri.parse(\"mailto:\")); // only email apps should handle this\n String[] email = { \"henrich.gron@gmail.com\" };\n intent.putExtra(Intent.EXTRA_EMAIL, email);\n String packageVersion = \"\";\n try {\n PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);\n packageVersion = \" - v\" + pInfo.versionName + \" (\" + PPApplication.getVersionCode(pInfo) + \")\";\n } catch (Exception ignored) {\n }\n intent.putExtra(Intent.EXTRA_SUBJECT, \"PhoneProfilesPlus\" + packageVersion + \" - \" + getString(R.string.about_application_support_subject));\n intent.putExtra(Intent.EXTRA_TEXT, AboutApplicationActivity.getEmailBodyText(/*AboutApplicationActivity.EMAIL_BODY_SUPPORT, */this));\n try {\n startActivity(Intent.createChooser(intent, getString(R.string.email_chooser)));\n } catch (Exception ignored) {}\n\n return true;\n case R.id.menu_export_and_email_to_author:\n exportData(true, true);\n\n return true;\n case R.id.menu_email_debug_logs_to_author:\n ArrayList uris = new ArrayList<>();\n\n File sd = getApplicationContext().getExternalFilesDir(null);\n\n File logFile = new File(sd, PPApplication.LOG_FILENAME);\n if (logFile.exists()) {\n Uri fileUri = FileProvider.getUriForFile(this, getPackageName() + \".provider\", logFile);\n uris.add(fileUri);\n }\n\n File crashFile = new File(sd, TopExceptionHandler.CRASH_FILENAME);\n if (crashFile.exists()) {\n Uri fileUri = FileProvider.getUriForFile(this, getPackageName() + \".provider\", crashFile);\n uris.add(fileUri);\n }\n\n if (uris.size() != 0) {\n String emailAddress = \"henrich.gron@gmail.com\";\n Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(\n \"mailto\", emailAddress, null));\n\n packageVersion = \"\";\n try {\n PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);\n packageVersion = \" - v\" + pInfo.versionName + \" (\" + PPApplication.getVersionCode(pInfo) + \")\";\n } catch (Exception ignored) {}\n emailIntent.putExtra(Intent.EXTRA_SUBJECT, \"PhoneProfilesPlus\" + packageVersion + \" - \" + getString(R.string.email_debug_log_files_subject));\n emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);\n\n List resolveInfo = getPackageManager().queryIntentActivities(emailIntent, 0);\n List intents = new ArrayList<>();\n for (ResolveInfo info : resolveInfo) {\n intent = new Intent(Intent.ACTION_SEND_MULTIPLE);\n intent.setComponent(new ComponentName(info.activityInfo.packageName, info.activityInfo.name));\n intent.putExtra(Intent.EXTRA_EMAIL, new String[]{emailAddress});\n intent.putExtra(Intent.EXTRA_SUBJECT, \"PhoneProfilesPlus\" + packageVersion + \" - \" + getString(R.string.email_debug_log_files_subject));\n intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);\n intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris); //ArrayList of attachment Uri's\n intents.add(new LabeledIntent(intent, info.activityInfo.packageName, info.loadLabel(getPackageManager()), info.icon));\n }\n try {\n Intent chooser = Intent.createChooser(intents.remove(intents.size() - 1), getString(R.string.email_chooser));\n //noinspection ToArrayCallWithZeroLengthArrayArgument\n chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents.toArray(new LabeledIntent[intents.size()]));\n startActivity(chooser);\n } catch (Exception ignored) {}\n }\n else {\n // toast notification\n Toast msg = ToastCompat.makeText(getApplicationContext(), getString(R.string.toast_debug_log_files_not_exists),\n Toast.LENGTH_SHORT);\n msg.show();\n }\n\n return true;\n case R.id.menu_about:\n intent = new Intent(getBaseContext(), AboutApplicationActivity.class);\n startActivity(intent);\n return true;\n case R.id.menu_exit:\n AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);\n dialogBuilder.setTitle(R.string.exit_application_alert_title);\n dialogBuilder.setMessage(R.string.exit_application_alert_message);\n //dialogBuilder.setIcon(android.R.drawable.ic_dialog_alert);\n dialogBuilder.setPositiveButton(R.string.alert_button_yes, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int which) {\n PPApplication.logE(\"PPApplication.exitApp\", \"from EditorProfileActivity.onOptionsItemSelected shutdown=false\");\n\n IgnoreBatteryOptimizationNotification.setShowIgnoreBatteryOptimizationNotificationOnStart(getApplicationContext(), true);\n SharedPreferences settings = ApplicationPreferences.getSharedPreferences(getApplicationContext());\n SharedPreferences.Editor editor = settings.edit();\n editor.putBoolean(ApplicationPreferences.PREF_APPLICATION_EVENT_NEVER_ASK_FOR_ENABLE_RUN, false);\n editor.putBoolean(ApplicationPreferences.PREF_APPLICATION_NEVER_ASK_FOR_GRANT_ROOT, false);\n editor.apply();\n\n PPApplication.exitApp(true, getApplicationContext(), EditorProfilesActivity.this.getDataWrapper(),\n EditorProfilesActivity.this, false/*, true, true*/);\n }\n });\n dialogBuilder.setNegativeButton(R.string.alert_button_no, null);\n AlertDialog dialog = dialogBuilder.create();\n /*dialog.setOnShowListener(new DialogInterface.OnShowListener() {\n @Override\n public void onShow(DialogInterface dialog) {\n Button positive = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_POSITIVE);\n if (positive != null) positive.setAllCaps(false);\n Button negative = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_NEGATIVE);\n if (negative != null) negative.setAllCaps(false);\n }\n });*/\n if (!isFinishing())\n dialog.show();\n return true;\n case R.id.menu_test_crash:\n //TODO throw new RuntimeException(\"test Crashlytics + TopExceptionHandler\");\n Crashlytics.getInstance().crash();\n return true;\n default:\n return super.onOptionsItemSelected(item);\n }\n }\n\n /*\n // fix for bug in LG stock ROM Android <= 4.1\n // https://code.google.com/p/android/issues/detail?id=78154\n @Override\n public boolean onKeyDown(int keyCode, KeyEvent event) {\n String manufacturer = PPApplication.getROMManufacturer();\n if ((keyCode == KeyEvent.KEYCODE_MENU) &&\n (Build.VERSION.SDK_INT <= 16) &&\n (manufacturer != null) && (manufacturer.compareTo(\"lge\") == 0)) {\n return true;\n }\n return super.onKeyDown(keyCode, event);\n }\n\n @Override\n public boolean onKeyUp(int keyCode, KeyEvent event) {\n String manufacturer = PPApplication.getROMManufacturer();\n if ((keyCode == KeyEvent.KEYCODE_MENU) &&\n (Build.VERSION.SDK_INT <= 16) &&\n (manufacturer != null) && (manufacturer.compareTo(\"lge\") == 0)) {\n openOptionsMenu();\n return true;\n }\n return super.onKeyUp(keyCode, event);\n }\n */\n\n /////\n\n /*\n // ListView click listener in the navigation drawer\n private class DrawerItemClickListener implements\n ListView.OnItemClickListener {\n\n public void onItemClick(AdapterView parent, View view, int position, long id) {\n // header is position=0\n if (position > 0)\n selectFilterItem(position, true, false, true);\n }\n }\n */\n\n private void selectFilterItem(int selectedView, int position, boolean fromClickListener, boolean startTargetHelps) {\n if (PPApplication.logEnabled()) {\n PPApplication.logE(\"EditorProfilesActivity.selectFilterItem\", \"editorSelectedView=\" + editorSelectedView);\n PPApplication.logE(\"EditorProfilesActivity.selectFilterItem\", \"selectedView=\" + selectedView);\n PPApplication.logE(\"EditorProfilesActivity.selectFilterItem\", \"position=\" + position);\n }\n\n boolean viewChanged = false;\n Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.editor_list_container);\n if (fragment instanceof EditorProfileListFragment) {\n if (selectedView != 0)\n viewChanged = true;\n } else\n if (fragment instanceof EditorEventListFragment) {\n if (selectedView != 1)\n viewChanged = true;\n }\n else\n viewChanged = true;\n\n int filterSelectedItem;\n if (selectedView == 0) {\n PPApplication.logE(\"EditorProfilesActivity.selectFilterItem\", \"filterProfilesSelectedItem=\" + filterProfilesSelectedItem);\n filterSelectedItem = filterProfilesSelectedItem;\n }\n else {\n PPApplication.logE(\"EditorProfilesActivity.selectFilterItem\", \"filterEventsSelectedItem=\" + filterEventsSelectedItem);\n filterSelectedItem = filterEventsSelectedItem;\n }\n\n if (viewChanged || (position != filterSelectedItem))\n {\n if (viewChanged) {\n // stop running AsyncTask\n if (fragment instanceof EditorProfileListFragment) {\n if (((EditorProfileListFragment) fragment).isAsyncTaskPendingOrRunning()) {\n ((EditorProfileListFragment) fragment).stopRunningAsyncTask();\n }\n } else if (fragment instanceof EditorEventListFragment) {\n if (((EditorEventListFragment) fragment).isAsyncTaskPendingOrRunning()) {\n ((EditorEventListFragment) fragment).stopRunningAsyncTask();\n }\n }\n }\n\n editorSelectedView = selectedView;\n if (editorSelectedView == 0) {\n filterProfilesSelectedItem = position;\n filterSelectedItem = position;\n PPApplication.logE(\"EditorProfilesActivity.selectFilterItem\", \"filterProfilesSelectedItem=\" + filterProfilesSelectedItem);\n }\n else {\n filterEventsSelectedItem = position;\n filterSelectedItem = position;\n PPApplication.logE(\"EditorProfilesActivity.selectFilterItem\", \"filterEventsSelectedItem=\" + filterEventsSelectedItem);\n }\n\n // save into shared preferences\n ApplicationPreferences.getSharedPreferences(this);\n Editor editor = ApplicationPreferences.preferences.edit();\n editor.putInt(SP_EDITOR_SELECTED_VIEW, editorSelectedView);\n editor.putInt(SP_EDITOR_PROFILES_VIEW_SELECTED_ITEM, filterProfilesSelectedItem);\n editor.putInt(SP_EDITOR_EVENTS_VIEW_SELECTED_ITEM, filterEventsSelectedItem);\n editor.apply();\n\n Bundle arguments;\n\n int profilesFilterType;\n int eventsFilterType;\n //int eventsOrderType = getEventsOrderType();\n\n switch (editorSelectedView) {\n case 0:\n switch (filterProfilesSelectedItem) {\n case DSI_PROFILES_ALL:\n profilesFilterType = EditorProfileListFragment.FILTER_TYPE_ALL;\n PPApplication.logE(\"EditorProfilesActivity.selectFilterItem\", \"profilesFilterType=FILTER_TYPE_ALL\");\n if (viewChanged) {\n fragment = new EditorProfileListFragment();\n arguments = new Bundle();\n arguments.putInt(EditorProfileListFragment.FILTER_TYPE_ARGUMENT, profilesFilterType);\n arguments.putBoolean(EditorProfileListFragment.START_TARGET_HELPS_ARGUMENT, startTargetHelps);\n fragment.setArguments(arguments);\n getSupportFragmentManager().beginTransaction()\n .replace(R.id.editor_list_container, fragment, \"EditorProfileListFragment\")\n .commitAllowingStateLoss();\n }\n else {\n //noinspection ConstantConditions\n EditorProfileListFragment displayedFragment = (EditorProfileListFragment)fragment;\n displayedFragment.changeFragmentFilter(profilesFilterType, startTargetHelps);\n }\n break;\n case DSI_PROFILES_SHOW_IN_ACTIVATOR:\n profilesFilterType = EditorProfileListFragment.FILTER_TYPE_SHOW_IN_ACTIVATOR;\n PPApplication.logE(\"EditorProfilesActivity.selectFilterItem\", \"profilesFilterType=FILTER_TYPE_SHOW_IN_ACTIVATOR\");\n if (viewChanged) {\n fragment = new EditorProfileListFragment();\n arguments = new Bundle();\n arguments.putInt(EditorProfileListFragment.FILTER_TYPE_ARGUMENT, profilesFilterType);\n arguments.putBoolean(EditorProfileListFragment.START_TARGET_HELPS_ARGUMENT, startTargetHelps);\n fragment.setArguments(arguments);\n getSupportFragmentManager().beginTransaction()\n .replace(R.id.editor_list_container, fragment, \"EditorProfileListFragment\")\n .commitAllowingStateLoss();\n }\n else {\n //noinspection ConstantConditions\n EditorProfileListFragment displayedFragment = (EditorProfileListFragment)fragment;\n displayedFragment.changeFragmentFilter(profilesFilterType, startTargetHelps);\n }\n break;\n case DSI_PROFILES_NO_SHOW_IN_ACTIVATOR:\n profilesFilterType = EditorProfileListFragment.FILTER_TYPE_NO_SHOW_IN_ACTIVATOR;\n PPApplication.logE(\"EditorProfilesActivity.selectFilterItem\", \"profilesFilterType=FILTER_TYPE_NO_SHOW_IN_ACTIVATOR\");\n if (viewChanged) {\n fragment = new EditorProfileListFragment();\n arguments = new Bundle();\n arguments.putInt(EditorProfileListFragment.FILTER_TYPE_ARGUMENT, profilesFilterType);\n arguments.putBoolean(EditorProfileListFragment.START_TARGET_HELPS_ARGUMENT, startTargetHelps);\n fragment.setArguments(arguments);\n getSupportFragmentManager().beginTransaction()\n .replace(R.id.editor_list_container, fragment, \"EditorProfileListFragment\")\n .commitAllowingStateLoss();\n }\n else {\n //noinspection ConstantConditions\n EditorProfileListFragment displayedFragment = (EditorProfileListFragment)fragment;\n displayedFragment.changeFragmentFilter(profilesFilterType, startTargetHelps);\n }\n break;\n }\n break;\n case 1:\n switch (filterEventsSelectedItem) {\n case DSI_EVENTS_START_ORDER:\n eventsFilterType = EditorEventListFragment.FILTER_TYPE_START_ORDER;\n PPApplication.logE(\"EditorProfilesActivity.selectFilterItem\", \"eventsFilterType=FILTER_TYPE_START_ORDER\");\n if (viewChanged) {\n fragment = new EditorEventListFragment();\n arguments = new Bundle();\n arguments.putInt(EditorEventListFragment.FILTER_TYPE_ARGUMENT, eventsFilterType);\n arguments.putBoolean(EditorEventListFragment.START_TARGET_HELPS_ARGUMENT, startTargetHelps);\n fragment.setArguments(arguments);\n getSupportFragmentManager().beginTransaction()\n .replace(R.id.editor_list_container, fragment, \"EditorEventListFragment\")\n .commitAllowingStateLoss();\n }\n else {\n //noinspection ConstantConditions\n EditorEventListFragment displayedFragment = (EditorEventListFragment)fragment;\n displayedFragment.changeFragmentFilter(eventsFilterType, startTargetHelps);\n }\n break;\n case DSI_EVENTS_ALL:\n eventsFilterType = EditorEventListFragment.FILTER_TYPE_ALL;\n PPApplication.logE(\"EditorProfilesActivity.selectFilterItem\", \"eventsFilterType=FILTER_TYPE_ALL\");\n if (viewChanged) {\n fragment = new EditorEventListFragment();\n arguments = new Bundle();\n arguments.putInt(EditorEventListFragment.FILTER_TYPE_ARGUMENT, eventsFilterType);\n arguments.putBoolean(EditorEventListFragment.START_TARGET_HELPS_ARGUMENT, startTargetHelps);\n fragment.setArguments(arguments);\n getSupportFragmentManager().beginTransaction()\n .replace(R.id.editor_list_container, fragment, \"EditorEventListFragment\")\n .commitAllowingStateLoss();\n }\n else {\n //noinspection ConstantConditions\n EditorEventListFragment displayedFragment = (EditorEventListFragment)fragment;\n displayedFragment.changeFragmentFilter(eventsFilterType, startTargetHelps);\n }\n break;\n case DSI_EVENTS_NOT_STOPPED:\n eventsFilterType = EditorEventListFragment.FILTER_TYPE_NOT_STOPPED;\n PPApplication.logE(\"EditorProfilesActivity.selectFilterItem\", \"eventsFilterType=FILTER_TYPE_NOT_STOPPED\");\n if (viewChanged) {\n fragment = new EditorEventListFragment();\n arguments = new Bundle();\n arguments.putInt(EditorEventListFragment.FILTER_TYPE_ARGUMENT, eventsFilterType);\n arguments.putBoolean(EditorEventListFragment.START_TARGET_HELPS_ARGUMENT, startTargetHelps);\n fragment.setArguments(arguments);\n getSupportFragmentManager().beginTransaction()\n .replace(R.id.editor_list_container, fragment, \"EditorEventListFragment\")\n .commitAllowingStateLoss();\n }\n else {\n //noinspection ConstantConditions\n EditorEventListFragment displayedFragment = (EditorEventListFragment)fragment;\n displayedFragment.changeFragmentFilter(eventsFilterType, startTargetHelps);\n }\n break;\n case DSI_EVENTS_RUNNING:\n eventsFilterType = EditorEventListFragment.FILTER_TYPE_RUNNING;\n PPApplication.logE(\"EditorProfilesActivity.selectFilterItem\", \"eventsFilterType=FILTER_TYPE_RUNNING\");\n if (viewChanged) {\n fragment = new EditorEventListFragment();\n arguments = new Bundle();\n arguments.putInt(EditorEventListFragment.FILTER_TYPE_ARGUMENT, eventsFilterType);\n arguments.putBoolean(EditorEventListFragment.START_TARGET_HELPS_ARGUMENT, startTargetHelps);\n fragment.setArguments(arguments);\n getSupportFragmentManager().beginTransaction()\n .replace(R.id.editor_list_container, fragment, \"EditorEventListFragment\")\n .commitAllowingStateLoss();\n }\n else {\n //noinspection ConstantConditions\n EditorEventListFragment displayedFragment = (EditorEventListFragment)fragment;\n displayedFragment.changeFragmentFilter(eventsFilterType, startTargetHelps);\n }\n break;\n case DSI_EVENTS_PAUSED:\n eventsFilterType = EditorEventListFragment.FILTER_TYPE_PAUSED;\n PPApplication.logE(\"EditorProfilesActivity.selectFilterItem\", \"eventsFilterType=FILTER_TYPE_PAUSED\");\n if (viewChanged) {\n fragment = new EditorEventListFragment();\n arguments = new Bundle();\n arguments.putInt(EditorEventListFragment.FILTER_TYPE_ARGUMENT, eventsFilterType);\n arguments.putBoolean(EditorEventListFragment.START_TARGET_HELPS_ARGUMENT, startTargetHelps);\n fragment.setArguments(arguments);\n getSupportFragmentManager().beginTransaction()\n .replace(R.id.editor_list_container, fragment, \"EditorEventListFragment\")\n .commitAllowingStateLoss();\n }\n else {\n //noinspection ConstantConditions\n EditorEventListFragment displayedFragment = (EditorEventListFragment)fragment;\n displayedFragment.changeFragmentFilter(eventsFilterType, startTargetHelps);\n }\n break;\n case DSI_EVENTS_STOPPED:\n eventsFilterType = EditorEventListFragment.FILTER_TYPE_STOPPED;\n PPApplication.logE(\"EditorProfilesActivity.selectFilterItem\", \"eventsFilterType=FILTER_TYPE_STOPPED\");\n if (viewChanged) {\n fragment = new EditorEventListFragment();\n arguments = new Bundle();\n arguments.putInt(EditorEventListFragment.FILTER_TYPE_ARGUMENT, eventsFilterType);\n arguments.putBoolean(EditorEventListFragment.START_TARGET_HELPS_ARGUMENT, startTargetHelps);\n fragment.setArguments(arguments);\n getSupportFragmentManager().beginTransaction()\n .replace(R.id.editor_list_container, fragment, \"EditorEventListFragment\")\n .commitAllowingStateLoss();\n }\n else {\n //noinspection ConstantConditions\n EditorEventListFragment displayedFragment = (EditorEventListFragment)fragment;\n displayedFragment.changeFragmentFilter(eventsFilterType, startTargetHelps);\n }\n break;\n }\n break;\n }\n }\n\n /*\n // header is position=0\n drawerListView.setItemChecked(drawerSelectedItem, true);\n // Get the title and icon followed by the position\n //editorToolbar.setSubtitle(drawerItemsTitle[drawerSelectedItem - 1]);\n //setIcon(drawerItemsIcon[drawerSelectedItem-1]);\n drawerHeaderFilterImage.setImageResource(drawerItemsIcon[drawerSelectedItem -1]);\n drawerHeaderFilterTitle.setText(drawerItemsTitle[drawerSelectedItem - 1]);\n */\n if (!fromClickListener)\n filterSpinner.setSelection(filterSelectedItem);\n\n //bottomToolbar.setVisibility(View.VISIBLE);\n\n // set filter status bar title\n //setStatusBarTitle();\n \n }\n\n @Override\n public void onActivityResult(int requestCode, int resultCode, Intent data)\n {\n super.onActivityResult(requestCode, resultCode, data);\n\n if (requestCode == REQUEST_CODE_ACTIVATE_PROFILE)\n {\n Fragment _fragment = getSupportFragmentManager().findFragmentById(R.id.editor_list_container);\n if (_fragment instanceof EditorProfileListFragment) {\n EditorProfileListFragment fragment = (EditorProfileListFragment) getSupportFragmentManager().findFragmentById(R.id.editor_list_container);\n if (fragment != null)\n fragment.doOnActivityResult(requestCode, resultCode, data);\n }\n }\n else\n if (requestCode == REQUEST_CODE_PROFILE_PREFERENCES)\n {\n if ((resultCode == RESULT_OK) && (data != null))\n {\n long profile_id = data.getLongExtra(PPApplication.EXTRA_PROFILE_ID, 0);\n int newProfileMode = data.getIntExtra(EXTRA_NEW_PROFILE_MODE, EditorProfileListFragment.EDIT_MODE_UNDEFINED);\n //int predefinedProfileIndex = data.getIntExtra(EXTRA_PREDEFINED_PROFILE_INDEX, 0);\n\n if (profile_id > 0)\n {\n Profile profile = DatabaseHandler.getInstance(getApplicationContext()).getProfile(profile_id, false);\n if (profile != null) {\n // generate bitmaps\n profile.generateIconBitmap(getBaseContext(), false, 0, false);\n profile.generatePreferencesIndicator(getBaseContext(), false, 0);\n\n // redraw list fragment , notifications, widgets after finish ProfilesPrefsActivity\n redrawProfileListFragment(profile, newProfileMode);\n\n //Profile mappedProfile = profile; //Profile.getMappedProfile(profile, getApplicationContext());\n //Permissions.grantProfilePermissions(getApplicationContext(), profile, false, true,\n // /*true, false, 0,*/ PPApplication.STARTUP_SOURCE_EDITOR, false, true, false);\n EditorProfilesActivity.displayRedTextToPreferencesNotification(profile, null, getApplicationContext());\n }\n }\n\n /*Intent serviceIntent = new Intent(getApplicationContext(), PhoneProfilesService.class);\n serviceIntent.putExtra(PhoneProfilesService.EXTRA_ONLY_START, false);\n serviceIntent.putExtra(PhoneProfilesService.EXTRA_REREGISTER_RECEIVERS_AND_WORKERS, true);\n PPApplication.startPPService(this, serviceIntent);*/\n Intent commandIntent = new Intent(PhoneProfilesService.ACTION_COMMAND);\n //commandIntent.putExtra(PhoneProfilesService.EXTRA_ONLY_START, false);\n commandIntent.putExtra(PhoneProfilesService.EXTRA_REREGISTER_RECEIVERS_AND_WORKERS, true);\n PPApplication.runCommand(this, commandIntent);\n }\n else\n if (data != null) {\n boolean restart = data.getBooleanExtra(PhoneProfilesPrefsActivity.EXTRA_RESET_EDITOR, false);\n if (restart) {\n // refresh activity for special changes\n GlobalGUIRoutines.reloadActivity(this, true);\n }\n }\n }\n else\n if (requestCode == REQUEST_CODE_EVENT_PREFERENCES)\n {\n if ((resultCode == RESULT_OK) && (data != null))\n {\n // redraw list fragment after finish EventPreferencesActivity\n long event_id = data.getLongExtra(PPApplication.EXTRA_EVENT_ID, 0L);\n int newEventMode = data.getIntExtra(EXTRA_NEW_EVENT_MODE, EditorEventListFragment.EDIT_MODE_UNDEFINED);\n //int predefinedEventIndex = data.getIntExtra(EXTRA_PREDEFINED_EVENT_INDEX, 0);\n\n if (event_id > 0)\n {\n Event event = DatabaseHandler.getInstance(getApplicationContext()).getEvent(event_id);\n\n // redraw list fragment , notifications, widgets after finish EventPreferencesActivity\n redrawEventListFragment(event, newEventMode);\n\n //Permissions.grantEventPermissions(getApplicationContext(), event, true, false);\n EditorProfilesActivity.displayRedTextToPreferencesNotification(null, event, getApplicationContext());\n }\n\n /*Intent serviceIntent = new Intent(getApplicationContext(), PhoneProfilesService.class);\n serviceIntent.putExtra(PhoneProfilesService.EXTRA_ONLY_START, false);\n serviceIntent.putExtra(PhoneProfilesService.EXTRA_REREGISTER_RECEIVERS_AND_WORKERS, true);\n PPApplication.startPPService(this, serviceIntent);*/\n Intent commandIntent = new Intent(PhoneProfilesService.ACTION_COMMAND);\n //commandIntent.putExtra(PhoneProfilesService.EXTRA_ONLY_START, false);\n commandIntent.putExtra(PhoneProfilesService.EXTRA_REREGISTER_RECEIVERS_AND_WORKERS, true);\n PPApplication.runCommand(this, commandIntent);\n\n IgnoreBatteryOptimizationNotification.showNotification(getApplicationContext());\n }\n else\n if (data != null) {\n boolean restart = data.getBooleanExtra(PhoneProfilesPrefsActivity.EXTRA_RESET_EDITOR, false);\n if (restart) {\n // refresh activity for special changes\n GlobalGUIRoutines.reloadActivity(this, true);\n }\n }\n }\n else\n if (requestCode == REQUEST_CODE_APPLICATION_PREFERENCES)\n {\n if (resultCode == RESULT_OK)\n {\n// Intent serviceIntent = new Intent(getApplicationContext(), PhoneProfilesService.class);\n// serviceIntent.putExtra(PhoneProfilesService.EXTRA_ONLY_START, false);\n// serviceIntent.putExtra(PhoneProfilesService.EXTRA_REREGISTER_RECEIVERS_AND_WORKERS, true);\n// PPApplication.startPPService(this, serviceIntent);\n// Intent commandIntent = new Intent(PhoneProfilesService.ACTION_COMMAND);\n// //commandIntent.putExtra(PhoneProfilesService.EXTRA_ONLY_START, false);\n// commandIntent.putExtra(PhoneProfilesService.EXTRA_REREGISTER_RECEIVERS_AND_WORKERS, true);\n// PPApplication.runCommand(this, commandIntent);\n\n// if (PhoneProfilesService.getInstance() != null) {\n//\n// boolean powerSaveMode = PPApplication.isPowerSaveMode;\n// if ((PhoneProfilesService.isGeofenceScannerStarted())) {\n// PhoneProfilesService.getGeofencesScanner().resetLocationUpdates(powerSaveMode, true);\n// }\n// PhoneProfilesService.getInstance().resetListeningOrientationSensors(powerSaveMode, true);\n// if (PhoneProfilesService.isPhoneStateScannerStarted())\n// PhoneProfilesService.phoneStateScanner.resetListening(powerSaveMode, true);\n//\n// }\n\n boolean restart = data.getBooleanExtra(PhoneProfilesPrefsActivity.EXTRA_RESET_EDITOR, false);\n PPApplication.logE(\"EditorProfilesActivity.onActivityResult\", \"restart=\"+restart);\n\n if (restart)\n {\n // refresh activity for special changes\n GlobalGUIRoutines.reloadActivity(this, true);\n }\n }\n }\n else\n if (requestCode == REQUEST_CODE_REMOTE_EXPORT)\n {\n if (resultCode == RESULT_OK)\n {\n doImportData(GlobalGUIRoutines.REMOTE_EXPORT_PATH);\n }\n }\n /*else\n if (requestCode == Permissions.REQUEST_CODE + Permissions.GRANT_TYPE_PROFILE) {\n if (data != null) {\n long profileId = data.getLongExtra(PPApplication.EXTRA_PROFILE_ID, 0);\n int startupSource = data.getIntExtra(PPApplication.EXTRA_STARTUP_SOURCE, 0);\n boolean mergedProfile = data.getBooleanExtra(Permissions.EXTRA_MERGED_PROFILE, false);\n boolean activateProfile = data.getBooleanExtra(Permissions.EXTRA_ACTIVATE_PROFILE, false);\n\n if (activateProfile && (getDataWrapper() != null)) {\n Profile profile = getDataWrapper().getProfileById(profileId, false, false, mergedProfile);\n getDataWrapper().activateProfileFromMainThread(profile, mergedProfile, startupSource, this);\n }\n }\n }*/\n else\n if (requestCode == Permissions.REQUEST_CODE + Permissions.GRANT_TYPE_EXPORT) {\n if (resultCode == RESULT_OK) {\n doExportData(false, false);\n }\n }\n else\n if (requestCode == Permissions.REQUEST_CODE + Permissions.GRANT_TYPE_EXPORT_AND_EMAIL) {\n if (resultCode == RESULT_OK) {\n doExportData(true, false);\n }\n }\n else\n if (requestCode == Permissions.REQUEST_CODE + Permissions.GRANT_TYPE_IMPORT) {\n if ((resultCode == RESULT_OK) && (data != null)) {\n doImportData(data.getStringExtra(Permissions.EXTRA_APPLICATION_DATA_PATH));\n }\n }\n else\n if (requestCode == Permissions.REQUEST_CODE + Permissions.GRANT_TYPE_EXPORT_AND_EMAIL_TO_AUTHOR) {\n if (resultCode == RESULT_OK) {\n doExportData(true, true);\n }\n }\n }\n\n /*\n @Override\n public void onBackPressed()\n {\n if (drawerLayout.isDrawerOpen(drawerRoot))\n drawerLayout.closeDrawer(drawerRoot);\n else\n super.onBackPressed();\n }\n */\n\n /*\n @Override\n public void openOptionsMenu() {\n Configuration config = getResources().getConfiguration();\n if ((config.screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) > Configuration.SCREENLAYOUT_SIZE_LARGE) {\n int originalScreenLayout = config.screenLayout;\n config.screenLayout = Configuration.SCREENLAYOUT_SIZE_LARGE;\n super.openOptionsMenu();\n config.screenLayout = originalScreenLayout;\n } else {\n super.openOptionsMenu();\n }\n }\n */\n\n private void importExportErrorDialog(int importExport, int dbResult, int appSettingsResult, int sharedProfileResult)\n {\n AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);\n String title;\n if (importExport == 1)\n title = getString(R.string.import_profiles_alert_title);\n else\n title = getString(R.string.export_profiles_alert_title);\n dialogBuilder.setTitle(title);\n String message;\n if (importExport == 1) {\n message = getString(R.string.import_profiles_alert_error) + \":\";\n if (dbResult != DatabaseHandler.IMPORT_OK) {\n if (dbResult == DatabaseHandler.IMPORT_ERROR_NEVER_VERSION)\n message = message + \"\\n• \" + getString(R.string.import_profiles_alert_error_database_newer_version);\n else\n message = message + \"\\n• \" + getString(R.string.import_profiles_alert_error_database_bug);\n }\n if (appSettingsResult == 0)\n message = message + \"\\n• \" + getString(R.string.import_profiles_alert_error_appSettings_bug);\n if (sharedProfileResult == 0)\n message = message + \"\\n• \" + getString(R.string.import_profiles_alert_error_sharedProfile_bug);\n }\n else\n message = getString(R.string.export_profiles_alert_error);\n dialogBuilder.setMessage(message);\n //dialogBuilder.setIcon(android.R.drawable.ic_dialog_alert);\n dialogBuilder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int which) {\n // refresh activity\n GlobalGUIRoutines.reloadActivity(EditorProfilesActivity.this, true);\n }\n });\n dialogBuilder.setOnCancelListener(new DialogInterface.OnCancelListener() {\n @Override\n public void onCancel(DialogInterface dialog) {\n // refresh activity\n GlobalGUIRoutines.reloadActivity(EditorProfilesActivity.this, true);\n }\n });\n AlertDialog dialog = dialogBuilder.create();\n /*dialog.setOnShowListener(new DialogInterface.OnShowListener() {\n @Override\n public void onShow(DialogInterface dialog) {\n Button positive = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_POSITIVE);\n if (positive != null) positive.setAllCaps(false);\n Button negative = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_NEGATIVE);\n if (negative != null) negative.setAllCaps(false);\n }\n });*/\n if (!isFinishing())\n dialog.show();\n }\n\n @SuppressWarnings(\"BooleanMethodIsAlwaysInverted\")\n private boolean importApplicationPreferences(File src, int what) {\n boolean res = true;\n ObjectInputStream input = null;\n try {\n try {\n input = new ObjectInputStream(new FileInputStream(src));\n Editor prefEdit;\n if (what == 1)\n prefEdit = getSharedPreferences(PPApplication.APPLICATION_PREFS_NAME, Activity.MODE_PRIVATE).edit();\n else\n prefEdit = getSharedPreferences(\"profile_preferences_default_profile\", Activity.MODE_PRIVATE).edit();\n prefEdit.clear();\n //noinspection unchecked\n Map entries = (Map) input.readObject();\n for (Entry entry : entries.entrySet()) {\n Object v = entry.getValue();\n String key = entry.getKey();\n\n if (v instanceof Boolean)\n prefEdit.putBoolean(key, (Boolean) v);\n else if (v instanceof Float)\n prefEdit.putFloat(key, (Float) v);\n else if (v instanceof Integer)\n prefEdit.putInt(key, (Integer) v);\n else if (v instanceof Long)\n prefEdit.putLong(key, (Long) v);\n else if (v instanceof String)\n prefEdit.putString(key, ((String) v));\n\n if (what == 1)\n {\n if (key.equals(ApplicationPreferences.PREF_APPLICATION_THEME))\n {\n if (v.equals(\"light\") || v.equals(\"material\") || v.equals(\"color\") || v.equals(\"dlight\")) {\n String defaultValue = \"white\";\n if (Build.VERSION.SDK_INT >= 28)\n defaultValue = \"night_mode\";\n prefEdit.putString(key, defaultValue);\n }\n }\n if (key.equals(ActivateProfileHelper.PREF_MERGED_RING_NOTIFICATION_VOLUMES))\n ActivateProfileHelper.setMergedRingNotificationVolumes(getApplicationContext(), true, prefEdit);\n if (key.equals(ApplicationPreferences.PREF_APPLICATION_FIRST_START))\n prefEdit.putBoolean(ApplicationPreferences.PREF_APPLICATION_FIRST_START, false);\n }\n\n /*if (what == 2) {\n if (key.equals(Profile.PREF_PROFILE_LOCK_DEVICE)) {\n if (v.equals(\"3\"))\n prefEdit.putString(Profile.PREF_PROFILE_LOCK_DEVICE, \"1\");\n }\n }*/\n }\n prefEdit.apply();\n if (what == 1) {\n // save version code\n try {\n Context appContext = getApplicationContext();\n PackageInfo pInfo = appContext.getPackageManager().getPackageInfo(appContext.getPackageName(), 0);\n int actualVersionCode = PPApplication.getVersionCode(pInfo);\n PPApplication.setSavedVersionCode(appContext, actualVersionCode);\n } catch (Exception ignored) {\n }\n }\n }/* catch (FileNotFoundException ignored) {\n // no error, this is OK\n }*/ catch (Exception e) {\n Log.e(\"EditorProfilesActivity.importApplicationPreferences\", Log.getStackTraceString(e));\n res = false;\n }\n }finally {\n try {\n if (input != null) {\n input.close();\n }\n } catch (IOException ignored) {\n }\n\n WifiScanWorker.setScanRequest(getApplicationContext(), false);\n WifiScanWorker.setWaitForResults(getApplicationContext(), false);\n WifiScanWorker.setWifiEnabledForScan(getApplicationContext(), false);\n\n BluetoothScanWorker.setScanRequest(getApplicationContext(), false);\n BluetoothScanWorker.setLEScanRequest(getApplicationContext(), false);\n BluetoothScanWorker.setWaitForResults(getApplicationContext(), false);\n BluetoothScanWorker.setWaitForLEResults(getApplicationContext(), false);\n BluetoothScanWorker.setBluetoothEnabledForScan(getApplicationContext(), false);\n BluetoothScanWorker.setScanKilled(getApplicationContext(), false);\n\n }\n return res;\n }\n\n private void doImportData(String applicationDataPath)\n {\n final EditorProfilesActivity activity = this;\n final String _applicationDataPath = applicationDataPath;\n\n if (Permissions.grantImportPermissions(activity.getApplicationContext(), activity, applicationDataPath)) {\n\n @SuppressLint(\"StaticFieldLeak\")\n class ImportAsyncTask extends AsyncTask {\n private final DataWrapper dataWrapper;\n private int dbError = DatabaseHandler.IMPORT_OK;\n private boolean appSettingsError = false;\n private boolean sharedProfileError = false;\n\n private ImportAsyncTask() {\n AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(activity);\n dialogBuilder.setMessage(R.string.import_profiles_alert_title);\n\n LayoutInflater inflater = (activity.getLayoutInflater());\n @SuppressLint(\"InflateParams\")\n View layout = inflater.inflate(R.layout.activity_progress_bar_dialog, null);\n dialogBuilder.setView(layout);\n\n importProgressDialog = dialogBuilder.create();\n\n this.dataWrapper = getDataWrapper();\n }\n\n @Override\n protected void onPreExecute() {\n super.onPreExecute();\n\n doImport = true;\n\n GlobalGUIRoutines.lockScreenOrientation(activity);\n importProgressDialog.setCancelable(false);\n importProgressDialog.setCanceledOnTouchOutside(false);\n if (!activity.isFinishing())\n importProgressDialog.show();\n\n Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.editor_list_container);\n if (fragment != null) {\n if (fragment instanceof EditorProfileListFragment)\n ((EditorProfileListFragment) fragment).removeAdapter();\n else\n ((EditorEventListFragment) fragment).removeAdapter();\n }\n }\n\n @Override\n protected Integer doInBackground(Void... params) {\n PPApplication.logE(\"PPApplication.exitApp\", \"from EditorProfilesActivity.doImportData shutdown=false\");\n if (dataWrapper != null) {\n PPApplication.exitApp(false, dataWrapper.context, dataWrapper, null, false/*, false, true*/);\n\n File sd = Environment.getExternalStorageDirectory();\n File exportFile = new File(sd, _applicationDataPath + \"/\" + GlobalGUIRoutines.EXPORT_APP_PREF_FILENAME);\n appSettingsError = !importApplicationPreferences(exportFile, 1);\n exportFile = new File(sd, _applicationDataPath + \"/\" + GlobalGUIRoutines.EXPORT_DEF_PROFILE_PREF_FILENAME);\n if (exportFile.exists())\n sharedProfileError = !importApplicationPreferences(exportFile, 2);\n\n dbError = DatabaseHandler.getInstance(this.dataWrapper.context).importDB(_applicationDataPath);\n if (dbError == DatabaseHandler.IMPORT_OK) {\n DatabaseHandler.getInstance(this.dataWrapper.context).updateAllEventsStatus(Event.ESTATUS_RUNNING, Event.ESTATUS_PAUSE);\n DatabaseHandler.getInstance(this.dataWrapper.context).updateAllEventsSensorsPassed(EventPreferences.SENSOR_PASSED_WAITING);\n DatabaseHandler.getInstance(this.dataWrapper.context).deactivateProfile();\n DatabaseHandler.getInstance(this.dataWrapper.context).unblockAllEvents();\n DatabaseHandler.getInstance(this.dataWrapper.context).disableNotAllowedPreferences();\n //this.dataWrapper.invalidateProfileList();\n //this.dataWrapper.invalidateEventList();\n //this.dataWrapper.invalidateEventTimelineList();\n Event.setEventsBlocked(getApplicationContext(), false);\n DatabaseHandler.getInstance(this.dataWrapper.context).unblockAllEvents();\n Event.setForceRunEventRunning(getApplicationContext(), false);\n }\n\n if (PPApplication.logEnabled()) {\n PPApplication.logE(\"EditorProfilesActivity.doImportData\", \"dbError=\" + dbError);\n PPApplication.logE(\"EditorProfilesActivity.doImportData\", \"appSettingsError=\" + appSettingsError);\n PPApplication.logE(\"EditorProfilesActivity.doImportData\", \"sharedProfileError=\" + sharedProfileError);\n }\n\n if (!appSettingsError) {\n ApplicationPreferences.getSharedPreferences(dataWrapper.context);\n /*Editor editor = ApplicationPreferences.preferences.edit();\n editor.putInt(SP_EDITOR_PROFILES_VIEW_SELECTED_ITEM, 0);\n editor.putInt(SP_EDITOR_EVENTS_VIEW_SELECTED_ITEM, 0);\n editor.putInt(EditorEventListFragment.SP_EDITOR_ORDER_SELECTED_ITEM, 0);\n editor.apply();*/\n\n Permissions.setAllShowRequestPermissions(getApplicationContext(), true);\n\n //WifiBluetoothScanner.setShowEnableLocationNotification(getApplicationContext(), true, WifiBluetoothScanner.SCANNER_TYPE_WIFI);\n //WifiBluetoothScanner.setShowEnableLocationNotification(getApplicationContext(), true, WifiBluetoothScanner.SCANNER_TYPE_BLUETOOTH);\n //PhoneStateScanner.setShowEnableLocationNotification(getApplicationContext(), true);\n }\n\n if ((dbError == DatabaseHandler.IMPORT_OK) && (!(appSettingsError || sharedProfileError)))\n return 1;\n else\n return 0;\n }\n else\n return 0;\n }\n\n @Override\n protected void onPostExecute(Integer result) {\n super.onPostExecute(result);\n\n doImport = false;\n\n if (!isFinishing()) {\n if ((importProgressDialog != null) && importProgressDialog.isShowing()) {\n if (!isDestroyed())\n importProgressDialog.dismiss();\n importProgressDialog = null;\n }\n GlobalGUIRoutines.unlockScreenOrientation(activity);\n }\n\n if (dataWrapper != null) {\n PPApplication.logE(\"DataWrapper.updateNotificationAndWidgets\", \"from EditorProfilesActivity.doImportData\");\n this.dataWrapper.updateNotificationAndWidgets(true);\n\n PPApplication.setApplicationStarted(this.dataWrapper.context, true);\n Intent serviceIntent = new Intent(this.dataWrapper.context, PhoneProfilesService.class);\n //serviceIntent.putExtra(PhoneProfilesService.EXTRA_ONLY_START, true);\n serviceIntent.putExtra(PhoneProfilesService.EXTRA_DEACTIVATE_PROFILE, true);\n serviceIntent.putExtra(PhoneProfilesService.EXTRA_ACTIVATE_PROFILES, true);\n PPApplication.startPPService(activity, serviceIntent);\n }\n\n if ((dataWrapper != null) && (dbError == DatabaseHandler.IMPORT_OK) && (!(appSettingsError || sharedProfileError))) {\n PPApplication.logE(\"EditorProfilesActivity.doImportData\", \"restore is ok\");\n\n // restart events\n //if (Event.getGlobalEventsRunning(this.dataWrapper.context)) {\n // this.dataWrapper.restartEventsWithDelay(3, false, false, DatabaseHandler.ALTYPE_UNDEFINED);\n //}\n\n this.dataWrapper.addActivityLog(DataWrapper.ALTYPE_DATA_IMPORT, null, null, null, 0);\n\n // toast notification\n Toast msg = ToastCompat.makeText(this.dataWrapper.context.getApplicationContext(),\n getResources().getString(R.string.toast_import_ok),\n Toast.LENGTH_SHORT);\n msg.show();\n\n // refresh activity\n if (!isFinishing())\n GlobalGUIRoutines.reloadActivity(activity, true);\n\n IgnoreBatteryOptimizationNotification.showNotification(this.dataWrapper.context.getApplicationContext());\n } else {\n PPApplication.logE(\"EditorProfilesActivity.doImportData\", \"error restore\");\n\n int appSettingsResult = 1;\n if (appSettingsError) appSettingsResult = 0;\n int sharedProfileResult = 1;\n if (sharedProfileError) sharedProfileResult = 0;\n if (!isFinishing())\n importExportErrorDialog(1, dbError, appSettingsResult, sharedProfileResult);\n }\n }\n\n }\n\n importAsyncTask = new ImportAsyncTask().execute();\n }\n }\n\n private void importDataAlert(/*boolean remoteExport*/)\n {\n //final boolean _remoteExport = remoteExport;\n\n AlertDialog.Builder dialogBuilder2 = new AlertDialog.Builder(this);\n /*if (remoteExport)\n {\n dialogBuilder2.setTitle(R.string.import_profiles_from_phoneprofiles_alert_title2);\n dialogBuilder2.setMessage(R.string.import_profiles_alert_message);\n //dialogBuilder2.setIcon(android.R.drawable.ic_dialog_alert);\n }\n else\n {*/\n dialogBuilder2.setTitle(R.string.import_profiles_alert_title);\n dialogBuilder2.setMessage(R.string.import_profiles_alert_message);\n //dialogBuilder2.setIcon(android.R.drawable.ic_dialog_alert);\n //}\n\n dialogBuilder2.setPositiveButton(R.string.alert_button_yes, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int which) {\n /*if (_remoteExport)\n {\n // start RemoteExportDataActivity\n Intent intent = new Intent(\"phoneprofiles.intent.action.EXPORTDATA\");\n\n final PackageManager packageManager = getPackageManager();\n List list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);\n if (list.size() > 0)\n startActivityForResult(intent, REQUEST_CODE_REMOTE_EXPORT);\n else\n importExportErrorDialog(1);\n }\n else*/\n doImportData(PPApplication.EXPORT_PATH);\n }\n });\n dialogBuilder2.setNegativeButton(R.string.alert_button_no, null);\n AlertDialog dialog = dialogBuilder2.create();\n /*dialog.setOnShowListener(new DialogInterface.OnShowListener() {\n @Override\n public void onShow(DialogInterface dialog) {\n Button positive = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_POSITIVE);\n if (positive != null) positive.setAllCaps(false);\n Button negative = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_NEGATIVE);\n if (negative != null) negative.setAllCaps(false);\n }\n });*/\n if (!isFinishing())\n dialog.show();\n }\n\n private void importData()\n {\n /*// test whether the PhoneProfile is installed\n PackageManager packageManager = getApplicationContext().getPackageManager();\n Intent phoneProfiles = packageManager.getLaunchIntentForPackage(\"sk.henrichg.phoneprofiles\");\n if (phoneProfiles != null)\n {\n // PhoneProfiles is installed\n\n AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);\n dialogBuilder.setTitle(R.string.import_profiles_from_phoneprofiles_alert_title);\n dialogBuilder.setMessage(R.string.import_profiles_from_phoneprofiles_alert_message);\n //dialogBuilder.setIcon(android.R.drawable.ic_dialog_alert);\n\n dialogBuilder.setPositiveButton(R.string.alert_button_yes, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int which) {\n importDataAlert(true);\n }\n });\n dialogBuilder.setNegativeButton(R.string.alert_button_no, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int which) {\n importDataAlert(false);\n }\n });\n AlertDialog dialog = dialogBuilder.create();\n dialog.setOnShowListener(new DialogInterface.OnShowListener() {\n @Override\n public void onShow(DialogInterface dialog) {\n Button positive = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_POSITIVE);\n if (positive != null) positive.setAllCaps(false);\n Button negative = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_NEGATIVE);\n if (negative != null) negative.setAllCaps(false);\n }\n });\n dialog.show();\n }\n else*/\n importDataAlert();\n }\n\n @SuppressLint(\"ApplySharedPref\")\n private boolean exportApplicationPreferences(File dst/*, int what*/) {\n boolean res = true;\n ObjectOutputStream output = null;\n try {\n try {\n output = new ObjectOutputStream(new FileOutputStream(dst));\n SharedPreferences pref;\n //if (what == 1)\n pref = getSharedPreferences(PPApplication.APPLICATION_PREFS_NAME, Activity.MODE_PRIVATE);\n //else\n // pref = getSharedPreferences(PPApplication.SHARED_PROFILE_PREFS_NAME, Activity.MODE_PRIVATE);\n SharedPreferences.Editor editor = pref.edit();\n\n AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);\n if (audioManager != null) {\n editor.putInt(\"maximumVolume_ring\", audioManager.getStreamMaxVolume(AudioManager.STREAM_RING));\n editor.putInt(\"maximumVolume_notification\", audioManager.getStreamMaxVolume(AudioManager.STREAM_NOTIFICATION));\n editor.putInt(\"maximumVolume_music\", audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));\n editor.putInt(\"maximumVolume_alarm\", audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM));\n editor.putInt(\"maximumVolume_system\", audioManager.getStreamMaxVolume(AudioManager.STREAM_SYSTEM));\n editor.putInt(\"maximumVolume_voiceCall\", audioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL));\n editor.putInt(\"maximumVolume_dtmf\", audioManager.getStreamMaxVolume(AudioManager.STREAM_DTMF));\n if (Build.VERSION.SDK_INT >= 26)\n editor.putInt(\"maximumVolume_accessibility\", audioManager.getStreamMaxVolume(AudioManager.STREAM_ACCESSIBILITY));\n editor.putInt(\"maximumVolume_bluetoothSCO\", audioManager.getStreamMaxVolume(ActivateProfileHelper.STREAM_BLUETOOTH_SCO));\n }\n\n editor.commit();\n output.writeObject(pref.getAll());\n } catch (FileNotFoundException ignored) {\n // this is OK\n } catch (IOException e) {\n res = false;\n }\n } finally {\n try {\n if (output != null) {\n output.flush();\n output.close();\n }\n } catch (IOException ignored) {\n }\n }\n return res;\n }\n\n private void exportData(final boolean email, final boolean toAuthor)\n {\n AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);\n dialogBuilder.setTitle(R.string.export_profiles_alert_title);\n dialogBuilder.setMessage(getString(R.string.export_profiles_alert_message) + \" \\\"\" + PPApplication.EXPORT_PATH + \"\\\".\\n\\n\" +\n getString(R.string.export_profiles_alert_message_note));\n //dialogBuilder.setIcon(android.R.drawable.ic_dialog_alert);\n\n dialogBuilder.setPositiveButton(R.string.alert_button_backup, new DialogInterface.OnClickListener() {\n\n public void onClick(DialogInterface dialog, int which) {\n doExportData(email, toAuthor);\n }\n });\n dialogBuilder.setNegativeButton(android.R.string.cancel, null);\n AlertDialog dialog = dialogBuilder.create();\n /*dialog.setOnShowListener(new DialogInterface.OnShowListener() {\n @Override\n public void onShow(DialogInterface dialog) {\n Button positive = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_POSITIVE);\n if (positive != null) positive.setAllCaps(false);\n Button negative = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_NEGATIVE);\n if (negative != null) negative.setAllCaps(false);\n }\n });*/\n if (!isFinishing())\n dialog.show();\n }\n\n private void doExportData(final boolean email, final boolean toAuthor)\n {\n final EditorProfilesActivity activity = this;\n\n if (Permissions.grantExportPermissions(activity.getApplicationContext(), activity, email, toAuthor)) {\n\n @SuppressLint(\"StaticFieldLeak\")\n class ExportAsyncTask extends AsyncTask {\n private final DataWrapper dataWrapper;\n\n private ExportAsyncTask() {\n AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(activity);\n dialogBuilder.setMessage(R.string.export_profiles_alert_title);\n\n LayoutInflater inflater = (activity.getLayoutInflater());\n @SuppressLint(\"InflateParams\")\n View layout = inflater.inflate(R.layout.activity_progress_bar_dialog, null);\n dialogBuilder.setView(layout);\n\n exportProgressDialog = dialogBuilder.create();\n\n this.dataWrapper = getDataWrapper();\n }\n\n @Override\n protected void onPreExecute() {\n super.onPreExecute();\n\n GlobalGUIRoutines.lockScreenOrientation(activity);\n exportProgressDialog.setCancelable(false);\n exportProgressDialog.setCanceledOnTouchOutside(false);\n if (!activity.isFinishing())\n exportProgressDialog.show();\n }\n\n @Override\n protected Integer doInBackground(Void... params) {\n\n if (this.dataWrapper != null) {\n int ret = DatabaseHandler.getInstance(this.dataWrapper.context).exportDB();\n if (ret == 1) {\n File sd = Environment.getExternalStorageDirectory();\n File exportFile = new File(sd, PPApplication.EXPORT_PATH + \"/\" + GlobalGUIRoutines.EXPORT_APP_PREF_FILENAME);\n if (exportApplicationPreferences(exportFile/*, 1*/)) {\n /*exportFile = new File(sd, PPApplication.EXPORT_PATH + \"/\" + GlobalGUIRoutines.EXPORT_DEF_PROFILE_PREF_FILENAME);\n if (!exportApplicationPreferences(exportFile, 2))\n ret = 0;*/\n ret = 1;\n } else\n ret = 0;\n }\n\n return ret;\n }\n else\n return 0;\n }\n\n @Override\n protected void onPostExecute(Integer result) {\n super.onPostExecute(result);\n\n if (!isFinishing()) {\n if ((exportProgressDialog != null) && exportProgressDialog.isShowing()) {\n if (!isDestroyed())\n exportProgressDialog.dismiss();\n exportProgressDialog = null;\n }\n GlobalGUIRoutines.unlockScreenOrientation(activity);\n }\n\n if ((dataWrapper != null) && (result == 1)) {\n\n Context context = this.dataWrapper.context.getApplicationContext();\n // toast notification\n Toast msg = ToastCompat.makeText(context, getString(R.string.toast_export_ok), Toast.LENGTH_SHORT);\n msg.show();\n\n if (email) {\n // email backup\n\n ArrayList uris = new ArrayList<>();\n\n File sd = Environment.getExternalStorageDirectory();\n\n File exportedDB = new File(sd, PPApplication.EXPORT_PATH + \"/\" + DatabaseHandler.EXPORT_DBFILENAME);\n Uri fileUri = FileProvider.getUriForFile(activity, context.getPackageName() + \".provider\", exportedDB);\n uris.add(fileUri);\n\n File appSettingsFile = new File(sd, PPApplication.EXPORT_PATH + \"/\" + GlobalGUIRoutines.EXPORT_APP_PREF_FILENAME);\n fileUri = FileProvider.getUriForFile(activity, context.getPackageName() + \".provider\", appSettingsFile);\n uris.add(fileUri);\n\n String emailAddress = \"\";\n if (toAuthor)\n emailAddress = \"henrich.gron@gmail.com\";\n Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(\n \"mailto\", emailAddress, null));\n\n String packageVersion = \"\";\n try {\n PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);\n packageVersion = \" - v\" + pInfo.versionName + \" (\" + PPApplication.getVersionCode(pInfo) + \")\";\n } catch (Exception e) {\n Log.e(\"EditorProfilesActivity.doExportData\", Log.getStackTraceString(e));\n }\n emailIntent.putExtra(Intent.EXTRA_SUBJECT, \"PhoneProfilesPlus\" + packageVersion + \" - \" + getString(R.string.menu_export));\n emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);\n\n List resolveInfo = getPackageManager().queryIntentActivities(emailIntent, 0);\n List intents = new ArrayList<>();\n for (ResolveInfo info : resolveInfo) {\n Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);\n intent.setComponent(new ComponentName(info.activityInfo.packageName, info.activityInfo.name));\n if (!emailAddress.isEmpty())\n intent.putExtra(Intent.EXTRA_EMAIL, new String[]{emailAddress});\n intent.putExtra(Intent.EXTRA_SUBJECT, \"PhoneProfilesPlus\" + packageVersion + \" - \" + getString(R.string.menu_export));\n intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);\n intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris); //ArrayList of attachment Uri's\n intents.add(new LabeledIntent(intent, info.activityInfo.packageName, info.loadLabel(getPackageManager()), info.icon));\n }\n try {\n Intent chooser = Intent.createChooser(intents.remove(intents.size() - 1), context.getString(R.string.email_chooser));\n //noinspection ToArrayCallWithZeroLengthArrayArgument\n chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents.toArray(new LabeledIntent[intents.size()]));\n startActivity(chooser);\n } catch (Exception e) {\n Log.e(\"EditorProfilesActivity.doExportData\", Log.getStackTraceString(e));\n }\n }\n\n } else {\n if (!isFinishing())\n importExportErrorDialog(2, 0, 0, 0);\n }\n }\n\n }\n\n exportAsyncTask = new ExportAsyncTask().execute();\n }\n\n }\n\n @Override\n protected void onPostCreate(Bundle savedInstanceState) {\n super.onPostCreate(savedInstanceState);\n // Sync the toggle state after onRestoreInstanceState has occurred.\n //drawerToggle.syncState();\n }\n \n @Override\n public void onSaveInstanceState(@NonNull Bundle outState) {\n super.onSaveInstanceState(outState);\n\n savedInstanceStateChanged = true;\n }\n\n @Override\n public void setTitle(CharSequence title) {\n if (getSupportActionBar() != null)\n getSupportActionBar().setTitle(title);\n }\n\n /*\n public void setIcon(int iconRes) {\n getSupportActionBar().setIcon(iconRes);\n }\n */\n\n /*\n @SuppressLint(\"SetTextI18n\")\n private void setStatusBarTitle()\n {\n // set filter status bar title\n String text = drawerItemsSubtitle[drawerSelectedItem-1];\n //filterStatusBarTitle.setText(drawerItemsTitle[drawerSelectedItem - 1] + \" - \" + text);\n drawerHeaderFilterSubtitle.setText(text);\n }\n */\n\n private void startProfilePreferenceActivity(Profile profile, int editMode, int predefinedProfileIndex) {\n Intent intent = new Intent(getBaseContext(), ProfilesPrefsActivity.class);\n if (editMode == EditorProfileListFragment.EDIT_MODE_INSERT)\n intent.putExtra(PPApplication.EXTRA_PROFILE_ID, 0L);\n else\n intent.putExtra(PPApplication.EXTRA_PROFILE_ID, profile._id);\n intent.putExtra(EXTRA_NEW_PROFILE_MODE, editMode);\n intent.putExtra(EXTRA_PREDEFINED_PROFILE_INDEX, predefinedProfileIndex);\n startActivityForResult(intent, REQUEST_CODE_PROFILE_PREFERENCES);\n }\n\n public void onStartProfilePreferences(Profile profile, int editMode, int predefinedProfileIndex/*, boolean startTargetHelps*/) {\n // In single-pane mode, simply start the profile preferences activity\n // for the profile position.\n if (((profile != null) ||\n (editMode == EditorProfileListFragment.EDIT_MODE_INSERT) ||\n (editMode == EditorProfileListFragment.EDIT_MODE_DUPLICATE))\n && (editMode != EditorProfileListFragment.EDIT_MODE_DELETE))\n startProfilePreferenceActivity(profile, editMode, predefinedProfileIndex);\n }\n\n private void redrawProfileListFragment(Profile profile, int newProfileMode /*int predefinedProfileIndex, boolean startTargetHelps*/) {\n // redraw list fragment, notification a widgets\n\n Fragment _fragment = getSupportFragmentManager().findFragmentById(R.id.editor_list_container);\n if (_fragment instanceof EditorProfileListFragment) {\n final EditorProfileListFragment fragment = (EditorProfileListFragment) getSupportFragmentManager().findFragmentById(R.id.editor_list_container);\n if (fragment != null) {\n // update profile, this rewrite profile in profileList\n fragment.activityDataWrapper.updateProfile(profile);\n\n boolean newProfile = ((newProfileMode == EditorProfileListFragment.EDIT_MODE_INSERT) ||\n (newProfileMode == EditorProfileListFragment.EDIT_MODE_DUPLICATE));\n fragment.updateListView(profile, newProfile, false, false, 0);\n\n Profile activeProfile = fragment.activityDataWrapper.getActivatedProfile(true,\n ApplicationPreferences.applicationEditorPrefIndicator(fragment.activityDataWrapper.context));\n fragment.updateHeader(activeProfile);\n PPApplication.showProfileNotification(/*getApplicationContext()*/true);\n PPApplication.logE(\"ActivateProfileHelper.updateGUI\", \"from EditorProfilesActivity.redrawProfileListFragment\");\n ActivateProfileHelper.updateGUI(fragment.activityDataWrapper.context, true, true);\n\n fragment.activityDataWrapper.setDynamicLauncherShortcutsFromMainThread();\n\n ((GlobalGUIRoutines.HighlightedSpinnerAdapter)filterSpinner.getAdapter()).setSelection(0);\n selectFilterItem(editorSelectedView, 0, false, true);\n }\n }\n }\n\n private void startEventPreferenceActivity(Event event, final int editMode, final int predefinedEventIndex) {\n boolean profileExists = true;\n long startProfileId = 0;\n long endProfileId = -1;\n if ((editMode == EditorEventListFragment.EDIT_MODE_INSERT) && (predefinedEventIndex > 0)) {\n if (getDataWrapper() != null) {\n // search names of start and end profiles\n String[] profileStartNamesArray = getResources().getStringArray(R.array.addEventPredefinedStartProfilesArray);\n String[] profileEndNamesArray = getResources().getStringArray(R.array.addEventPredefinedEndProfilesArray);\n\n startProfileId = getDataWrapper().getProfileIdByName(profileStartNamesArray[predefinedEventIndex], true);\n if (startProfileId == 0)\n profileExists = false;\n\n if (!profileEndNamesArray[predefinedEventIndex].isEmpty()) {\n endProfileId = getDataWrapper().getProfileIdByName(profileEndNamesArray[predefinedEventIndex], true);\n if (endProfileId == 0)\n profileExists = false;\n }\n }\n }\n\n if (profileExists) {\n Intent intent = new Intent(getBaseContext(), EventsPrefsActivity.class);\n if (editMode == EditorEventListFragment.EDIT_MODE_INSERT)\n intent.putExtra(PPApplication.EXTRA_EVENT_ID, 0L);\n else {\n intent.putExtra(PPApplication.EXTRA_EVENT_ID, event._id);\n intent.putExtra(PPApplication.EXTRA_EVENT_STATUS, event.getStatus());\n }\n intent.putExtra(EXTRA_NEW_EVENT_MODE, editMode);\n intent.putExtra(EXTRA_PREDEFINED_EVENT_INDEX, predefinedEventIndex);\n startActivityForResult(intent, REQUEST_CODE_EVENT_PREFERENCES);\n } else {\n final long _startProfileId = startProfileId;\n final long _endProfileId = endProfileId;\n\n AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);\n dialogBuilder.setTitle(R.string.menu_new_event);\n\n String startProfileName = \"\";\n String endProfileName = \"\";\n if (_startProfileId == 0) {\n // create profile\n int[] profileStartIndex = {0, 0, 0, 2, 4, 0, 5};\n startProfileName = getDataWrapper().getPredefinedProfile(profileStartIndex[predefinedEventIndex], false, getBaseContext())._name;\n }\n if (_endProfileId == 0) {\n // create profile\n int[] profileEndIndex = {0, 0, 0, 0, 0, 0, 6};\n endProfileName = getDataWrapper().getPredefinedProfile(profileEndIndex[predefinedEventIndex], false, getBaseContext())._name;\n }\n\n String message = \"\";\n if (!startProfileName.isEmpty())\n message = message + \" \\\"\" + startProfileName + \"\\\"\";\n if (!endProfileName.isEmpty()) {\n if (!message.isEmpty())\n message = message + \",\";\n message = message + \" \\\"\" + endProfileName + \"\\\"\";\n }\n message = getString(R.string.new_event_profiles_not_exists_alert_message1) + message + \" \" +\n getString(R.string.new_event_profiles_not_exists_alert_message2);\n\n dialogBuilder.setMessage(message);\n\n //dialogBuilder.setIcon(android.R.drawable.ic_dialog_alert);\n dialogBuilder.setPositiveButton(R.string.alert_button_yes, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int which) {\n if (_startProfileId == 0) {\n // create profile\n int[] profileStartIndex = {0, 0, 0, 2, 4, 0, 5};\n getDataWrapper().getPredefinedProfile(profileStartIndex[predefinedEventIndex], true, getBaseContext());\n }\n if (_endProfileId == 0) {\n // create profile\n int[] profileEndIndex = {0, 0, 0, 0, 0, 0, 6};\n getDataWrapper().getPredefinedProfile(profileEndIndex[predefinedEventIndex], true, getBaseContext());\n }\n\n Intent intent = new Intent(getBaseContext(), EventsPrefsActivity.class);\n intent.putExtra(PPApplication.EXTRA_EVENT_ID, 0L);\n intent.putExtra(EXTRA_NEW_EVENT_MODE, editMode);\n intent.putExtra(EXTRA_PREDEFINED_EVENT_INDEX, predefinedEventIndex);\n startActivityForResult(intent, REQUEST_CODE_EVENT_PREFERENCES);\n }\n });\n dialogBuilder.setNegativeButton(R.string.alert_button_no, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int which) {\n Intent intent = new Intent(getBaseContext(), EventsPrefsActivity.class);\n intent.putExtra(PPApplication.EXTRA_EVENT_ID, 0L);\n intent.putExtra(EXTRA_NEW_EVENT_MODE, editMode);\n intent.putExtra(EXTRA_PREDEFINED_EVENT_INDEX, predefinedEventIndex);\n startActivityForResult(intent, REQUEST_CODE_EVENT_PREFERENCES);\n }\n });\n AlertDialog dialog = dialogBuilder.create();\n /*dialog.setOnShowListener(new DialogInterface.OnShowListener() {\n @Override\n public void onShow(DialogInterface dialog) {\n Button positive = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_POSITIVE);\n if (positive != null) positive.setAllCaps(false);\n Button negative = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_NEGATIVE);\n if (negative != null) negative.setAllCaps(false);\n }\n });*/\n if (!isFinishing())\n dialog.show();\n }\n }\n\n public void onStartEventPreferences(Event event, int editMode, int predefinedEventIndex/*, boolean startTargetHelps*/) {\n if (((event != null) ||\n (editMode == EditorEventListFragment.EDIT_MODE_INSERT) ||\n (editMode == EditorEventListFragment.EDIT_MODE_DUPLICATE))\n && (editMode != EditorEventListFragment.EDIT_MODE_DELETE))\n startEventPreferenceActivity(event, editMode, predefinedEventIndex);\n }\n\n private void redrawEventListFragment(Event event, int newEventMode /*int predefinedEventIndex, boolean startTargetHelps*/) {\n // redraw list fragment, notification and widgets\n Fragment _fragment = getSupportFragmentManager().findFragmentById(R.id.editor_list_container);\n if (_fragment instanceof EditorEventListFragment) {\n EditorEventListFragment fragment = (EditorEventListFragment) getSupportFragmentManager().findFragmentById(R.id.editor_list_container);\n if (fragment != null) {\n // update event, this rewrite event in eventList\n fragment.activityDataWrapper.updateEvent(event);\n\n boolean newEvent = ((newEventMode == EditorEventListFragment.EDIT_MODE_INSERT) ||\n (newEventMode == EditorEventListFragment.EDIT_MODE_DUPLICATE));\n fragment.updateListView(event, newEvent, false, false, 0);\n\n Profile activeProfile = fragment.activityDataWrapper.getActivatedProfileFromDB(true,\n ApplicationPreferences.applicationEditorPrefIndicator(fragment.activityDataWrapper.context));\n fragment.updateHeader(activeProfile);\n\n ((GlobalGUIRoutines.HighlightedSpinnerAdapter)filterSpinner.getAdapter()).setSelection(0);\n selectFilterItem(editorSelectedView, 0, false, true);\n }\n }\n }\n\n public static ApplicationsCache getApplicationsCache()\n {\n return applicationsCache;\n }\n\n public static void createApplicationsCache()\n {\n if ((!savedInstanceStateChanged) || (applicationsCache == null))\n {\n if (applicationsCache != null)\n applicationsCache.clearCache(true);\n applicationsCache = new ApplicationsCache();\n }\n }\n\n private DataWrapper getDataWrapper()\n {\n Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.editor_list_container);\n if (fragment != null)\n {\n if (fragment instanceof EditorProfileListFragment)\n return ((EditorProfileListFragment)fragment).activityDataWrapper;\n else\n return ((EditorEventListFragment)fragment).activityDataWrapper;\n }\n else\n return null;\n }\n\n private void setEventsRunStopIndicator()\n {\n //boolean whiteTheme = ApplicationPreferences.applicationTheme(getApplicationContext(), true).equals(\"white\");\n if (Event.getGlobalEventsRunning(getApplicationContext()))\n {\n if (Event.getEventsBlocked(getApplicationContext())) {\n //if (whiteTheme)\n // eventsRunStopIndicator.setImageResource(R.drawable.ic_run_events_indicator_manual_activation_white);\n //else\n eventsRunStopIndicator.setImageResource(R.drawable.ic_run_events_indicator_manual_activation);\n }\n else {\n //if (whiteTheme)\n // eventsRunStopIndicator.setImageResource(R.drawable.ic_run_events_indicator_running_white);\n //else\n eventsRunStopIndicator.setImageResource(R.drawable.ic_run_events_indicator_running);\n }\n }\n else {\n //if (whiteTheme)\n // eventsRunStopIndicator.setImageResource(R.drawable.ic_run_events_indicator_stopped_white);\n //else\n eventsRunStopIndicator.setImageResource(R.drawable.ic_run_events_indicator_stopped);\n }\n }\n\n public void refreshGUI(final boolean refresh, final boolean refreshIcons, final boolean setPosition, final long profileId, final long eventId)\n {\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n if (doImport)\n return;\n\n setEventsRunStopIndicator();\n invalidateOptionsMenu();\n\n Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.editor_list_container);\n if (fragment != null) {\n if (fragment instanceof EditorProfileListFragment)\n ((EditorProfileListFragment) fragment).refreshGUI(refresh, refreshIcons, setPosition, profileId);\n else\n ((EditorEventListFragment) fragment).refreshGUI(refresh, refreshIcons, setPosition, eventId);\n }\n }\n });\n }\n\n /*\n private void setWindowContentOverlayCompat() {\n if (android.os.Build.VERSION.SDK_INT >= 20) {\n // Get the content view\n View contentView = findViewById(android.R.id.content);\n\n // Make sure it's a valid instance of a FrameLayout\n if (contentView instanceof FrameLayout) {\n TypedValue tv = new TypedValue();\n\n // Get the windowContentOverlay value of the current theme\n if (getTheme().resolveAttribute(\n android.R.attr.windowContentOverlay, tv, true)) {\n\n // If it's a valid resource, set it as the foreground drawable\n // for the content view\n if (tv.resourceId != 0) {\n ((FrameLayout) contentView).setForeground(\n getResources().getDrawable(tv.resourceId));\n }\n }\n }\n }\n }\n */\n\n private void showTargetHelps() {\n /*if (Build.VERSION.SDK_INT <= 19)\n // TapTarget.forToolbarMenuItem FC :-(\n // Toolbar.findViewById() returns null\n return;*/\n\n startTargetHelps = true;\n\n ApplicationPreferences.getSharedPreferences(this);\n\n boolean startTargetHelps = ApplicationPreferences.preferences.getBoolean(PREF_START_TARGET_HELPS, true);\n boolean showTargetHelpsFilterSpinner = ApplicationPreferences.preferences.getBoolean(EditorProfilesActivity.PREF_START_TARGET_HELPS_FILTER_SPINNER, true);\n boolean showTargetHelpsRunStopIndicator = ApplicationPreferences.preferences.getBoolean(EditorProfilesActivity.PREF_START_TARGET_HELPS_RUN_STOP_INDICATOR, true);\n boolean showTargetHelpsBottomNavigation = ApplicationPreferences.preferences.getBoolean(EditorProfilesActivity.PREF_START_TARGET_HELPS_BOTTOM_NAVIGATION, true);\n\n if (startTargetHelps || showTargetHelpsFilterSpinner || showTargetHelpsRunStopIndicator || showTargetHelpsBottomNavigation ||\n ApplicationPreferences.preferences.getBoolean(PREF_START_TARGET_HELPS_DEFAULT_PROFILE, true) ||\n ApplicationPreferences.preferences.getBoolean(EditorProfileListFragment.PREF_START_TARGET_HELPS, true) ||\n ApplicationPreferences.preferences.getBoolean(EditorProfileListAdapter.PREF_START_TARGET_HELPS, true) ||\n ApplicationPreferences.preferences.getBoolean(EditorProfileListAdapter.PREF_START_TARGET_HELPS_ORDER, true) ||\n ApplicationPreferences.preferences.getBoolean(EditorProfileListAdapter.PREF_START_TARGET_HELPS_SHOW_IN_ACTIVATOR, true) ||\n ApplicationPreferences.preferences.getBoolean(EditorEventListFragment.PREF_START_TARGET_HELPS, true) ||\n ApplicationPreferences.preferences.getBoolean(EditorEventListFragment.PREF_START_TARGET_HELPS_ORDER_SPINNER, true) ||\n ApplicationPreferences.preferences.getBoolean(EditorEventListAdapter.PREF_START_TARGET_HELPS, true) ||\n ApplicationPreferences.preferences.getBoolean(EditorEventListAdapter.PREF_START_TARGET_HELPS_ORDER, true) ||\n ApplicationPreferences.preferences.getBoolean(EditorEventListAdapter.PREF_START_TARGET_HELPS_STATUS, true)) {\n\n //Log.d(\"EditorProfilesActivity.showTargetHelps\", \"PREF_START_TARGET_HELPS_ORDER=true\");\n\n if (startTargetHelps || showTargetHelpsFilterSpinner || showTargetHelpsRunStopIndicator || showTargetHelpsBottomNavigation) {\n //Log.d(\"EditorProfilesActivity.showTargetHelps\", \"PREF_START_TARGET_HELPS=true\");\n\n Editor editor = ApplicationPreferences.preferences.edit();\n editor.putBoolean(PREF_START_TARGET_HELPS, false);\n editor.putBoolean(EditorProfilesActivity.PREF_START_TARGET_HELPS_FILTER_SPINNER, false);\n editor.putBoolean(EditorProfilesActivity.PREF_START_TARGET_HELPS_RUN_STOP_INDICATOR, false);\n editor.putBoolean(EditorProfilesActivity.PREF_START_TARGET_HELPS_BOTTOM_NAVIGATION, false);\n editor.apply();\n\n //TypedValue tv = new TypedValue();\n //getTheme().resolveAttribute(R.attr.colorAccent, tv, true);\n\n //final Display display = getWindowManager().getDefaultDisplay();\n\n //String appTheme = ApplicationPreferences.applicationTheme(getApplicationContext(), true);\n int outerCircleColor = R.color.tabTargetHelpOuterCircleColor;\n// if (appTheme.equals(\"dark\"))\n// outerCircleColor = R.color.tabTargetHelpOuterCircleColor_dark;\n int targetCircleColor = R.color.tabTargetHelpTargetCircleColor;\n// if (appTheme.equals(\"dark\"))\n// targetCircleColor = R.color.tabTargetHelpTargetCircleColor_dark;\n int textColor = R.color.tabTargetHelpTextColor;\n// if (appTheme.equals(\"dark\"))\n// textColor = R.color.tabTargetHelpTextColor_dark;\n\n //int[] screenLocation = new int[2];\n //filterSpinner.getLocationOnScreen(screenLocation);\n //filterSpinner.getLocationInWindow(screenLocation);\n //Rect filterSpinnerTarget = new Rect(0, 0, filterSpinner.getHeight(), filterSpinner.getHeight());\n //filterSpinnerTarget.offset(screenLocation[0] + 100, screenLocation[1]);\n\n /*\n eventsRunStopIndicator.getLocationOnScreen(screenLocation);\n //eventsRunStopIndicator.getLocationInWindow(screenLocation);\n Rect eventRunStopIndicatorTarget = new Rect(0, 0, eventsRunStopIndicator.getHeight(), eventsRunStopIndicator.getHeight());\n eventRunStopIndicatorTarget.offset(screenLocation[0], screenLocation[1]);\n */\n\n final TapTargetSequence sequence = new TapTargetSequence(this);\n List targets = new ArrayList<>();\n if (startTargetHelps) {\n\n // do not add it again\n showTargetHelpsFilterSpinner = false;\n showTargetHelpsRunStopIndicator = false;\n showTargetHelpsBottomNavigation = false;\n\n if (Event.getGlobalEventsRunning(getApplicationContext())) {\n /*targets.add(\n TapTarget.forToolbarNavigationIcon(editorToolbar, getString(R.string.editor_activity_targetHelps_navigationIcon_title), getString(R.string.editor_activity_targetHelps_navigationIcon_description))\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(true)\n .drawShadow(true)\n .id(1)\n );*/\n targets.add(\n //TapTarget.forBounds(filterSpinnerTarget, getString(R.string.editor_activity_targetHelps_filterSpinner_title), getString(R.string.editor_activity_targetHelps_filterSpinner_description))\n TapTarget.forView(filterSpinner, getString(R.string.editor_activity_targetHelps_filterSpinner_title), getString(R.string.editor_activity_targetHelps_filterSpinner_description))\n .transparentTarget(true)\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(true)\n .drawShadow(true)\n .id(1)\n );\n targets.add(\n TapTarget.forToolbarOverflow(editorToolbar, getString(R.string.editor_activity_targetHelps_applicationMenu_title), getString(R.string.editor_activity_targetHelps_applicationMenu_description))\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(true)\n .drawShadow(true)\n .id(2)\n );\n\n int id = 3;\n try {\n targets.add(\n TapTarget.forToolbarMenuItem(editorToolbar, R.id.menu_restart_events, getString(R.string.editor_activity_targetHelps_restartEvents_title), getString(R.string.editor_activity_targetHelps_restartEvents_description))\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(true)\n .drawShadow(true)\n .id(id)\n );\n ++id;\n } catch (Exception ignored) {\n } // not in action bar?\n try {\n targets.add(\n TapTarget.forToolbarMenuItem(editorToolbar, R.id.menu_activity_log, getString(R.string.editor_activity_targetHelps_activityLog_title), getString(R.string.editor_activity_targetHelps_activityLog_description))\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(true)\n .drawShadow(true)\n .id(id)\n );\n ++id;\n } catch (Exception ignored) {\n } // not in action bar?\n try {\n targets.add(\n TapTarget.forToolbarMenuItem(editorToolbar, R.id.important_info, getString(R.string.editor_activity_targetHelps_importantInfoButton_title), getString(R.string.editor_activity_targetHelps_importantInfoButton_description))\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(true)\n .drawShadow(true)\n .id(id)\n );\n ++id;\n } catch (Exception ignored) {\n } // not in action bar?\n\n targets.add(\n TapTarget.forView(eventsRunStopIndicator, getString(R.string.editor_activity_targetHelps_trafficLightIcon_title), getString(R.string.editor_activity_targetHelps_trafficLightIcon_description))\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(false)\n .drawShadow(true)\n .id(id)\n );\n ++id;\n\n targets.add(\n TapTarget.forView(bottomNavigationView.findViewById(R.id.menu_profiles_view), getString(R.string.editor_activity_targetHelps_bottomNavigationProfiles_title),\n getString(R.string.editor_activity_targetHelps_bottomNavigationProfiles_description) + \"\\n\" +\n getString(R.string.editor_activity_targetHelps_bottomNavigation_description_2))\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(true)\n .drawShadow(true)\n .id(id)\n );\n ++id;\n targets.add(\n TapTarget.forView(bottomNavigationView.findViewById(R.id.menu_events_view), getString(R.string.editor_activity_targetHelps_bottomNavigationEvents_title),\n getString(R.string.editor_activity_targetHelps_bottomNavigationEvents_description) + \"\\n\" +\n getString(R.string.editor_activity_targetHelps_bottomNavigation_description_2))\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(true)\n .drawShadow(true)\n .id(id)\n );\n ++id;\n } else {\n /*targets.add(\n TapTarget.forToolbarNavigationIcon(editorToolbar, getString(R.string.editor_activity_targetHelps_navigationIcon_title), getString(R.string.editor_activity_targetHelps_navigationIcon_description))\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(true)\n .drawShadow(true)\n .id(1)\n );*/\n targets.add(\n //TapTarget.forBounds(filterSpinnerTarget, getString(R.string.editor_activity_targetHelps_filterSpinner_title), getString(R.string.editor_activity_targetHelps_filterSpinner_description))\n TapTarget.forView(filterSpinner, getString(R.string.editor_activity_targetHelps_filterSpinner_title), getString(R.string.editor_activity_targetHelps_filterSpinner_description))\n .transparentTarget(true)\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(true)\n .drawShadow(true)\n .id(1)\n );\n targets.add(\n TapTarget.forToolbarOverflow(editorToolbar, getString(R.string.editor_activity_targetHelps_applicationMenu_title), getString(R.string.editor_activity_targetHelps_applicationMenu_description))\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(true)\n .drawShadow(true)\n .id(2)\n );\n\n int id = 3;\n try {\n targets.add(\n TapTarget.forToolbarMenuItem(editorToolbar, R.id.menu_run_stop_events, getString(R.string.editor_activity_targetHelps_runStopEvents_title), getString(R.string.editor_activity_targetHelps_runStopEvents_description))\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(true)\n .drawShadow(true)\n .id(id)\n );\n ++id;\n } catch (Exception ignored) {\n } // not in action bar?\n try {\n targets.add(\n TapTarget.forToolbarMenuItem(editorToolbar, R.id.menu_activity_log, getString(R.string.editor_activity_targetHelps_activityLog_title), getString(R.string.editor_activity_targetHelps_activityLog_description))\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(true)\n .drawShadow(true)\n .id(id)\n );\n ++id;\n } catch (Exception ignored) {\n } // not in action bar?\n try {\n targets.add(\n TapTarget.forToolbarMenuItem(editorToolbar, R.id.important_info, getString(R.string.editor_activity_targetHelps_importantInfoButton_title), getString(R.string.editor_activity_targetHelps_importantInfoButton_description))\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(true)\n .drawShadow(true)\n .id(id)\n );\n ++id;\n } catch (Exception ignored) {\n } // not in action bar?\n\n targets.add(\n TapTarget.forView(eventsRunStopIndicator, getString(R.string.editor_activity_targetHelps_trafficLightIcon_title), getString(R.string.editor_activity_targetHelps_trafficLightIcon_description))\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(false)\n .drawShadow(true)\n .id(id)\n );\n ++id;\n\n targets.add(\n TapTarget.forView(bottomNavigationView.findViewById(R.id.menu_profiles_view), getString(R.string.editor_activity_targetHelps_bottomNavigationProfiles_title),\n getString(R.string.editor_activity_targetHelps_bottomNavigationProfiles_description) + \"\\n\" +\n getString(R.string.editor_activity_targetHelps_bottomNavigation_description_2))\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(true)\n .drawShadow(true)\n .id(id)\n );\n ++id;\n targets.add(\n TapTarget.forView(bottomNavigationView.findViewById(R.id.menu_events_view), getString(R.string.editor_activity_targetHelps_bottomNavigationEvents_title),\n getString(R.string.editor_activity_targetHelps_bottomNavigationEvents_description) + \"\\n\" +\n getString(R.string.editor_activity_targetHelps_bottomNavigation_description_2))\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(true)\n .drawShadow(true)\n .id(id)\n );\n ++id;\n\n }\n }\n if (showTargetHelpsFilterSpinner) {\n targets.add(\n //TapTarget.forBounds(filterSpinnerTarget, getString(R.string.editor_activity_targetHelps_filterSpinner_title), getString(R.string.editor_activity_targetHelps_filterSpinner_description))\n TapTarget.forView(filterSpinner, getString(R.string.editor_activity_targetHelps_filterSpinner_title), getString(R.string.editor_activity_targetHelps_filterSpinner_description))\n .transparentTarget(true)\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(true)\n .drawShadow(true)\n .id(1)\n );\n }\n if (showTargetHelpsRunStopIndicator) {\n targets.add(\n TapTarget.forView(eventsRunStopIndicator, getString(R.string.editor_activity_targetHelps_trafficLightIcon_title), getString(R.string.editor_activity_targetHelps_trafficLightIcon_description))\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(false)\n .drawShadow(true)\n .id(1)\n );\n }\n if (showTargetHelpsBottomNavigation) {\n targets.add(\n TapTarget.forView(bottomNavigationView.findViewById(R.id.menu_profiles_view), getString(R.string.editor_activity_targetHelps_bottomNavigationProfiles_title),\n getString(R.string.editor_activity_targetHelps_bottomNavigationProfiles_description) + \"\\n\" +\n getString(R.string.editor_activity_targetHelps_bottomNavigation_description_2))\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(true)\n .drawShadow(true)\n .id(1)\n );\n targets.add(\n TapTarget.forView(bottomNavigationView.findViewById(R.id.menu_events_view), getString(R.string.editor_activity_targetHelps_bottomNavigationEvents_title),\n getString(R.string.editor_activity_targetHelps_bottomNavigationEvents_description) + \"\\n \" +\n getString(R.string.editor_activity_targetHelps_bottomNavigation_description_2))\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(true)\n .drawShadow(true)\n .id(2)\n );\n }\n\n sequence.targets(targets);\n\n sequence.listener(new TapTargetSequence.Listener() {\n // This listener will tell us when interesting(tm) events happen in regards\n // to the sequence\n @Override\n public void onSequenceFinish() {\n targetHelpsSequenceStarted = false;\n Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.editor_list_container);\n if (fragment != null) {\n if (fragment instanceof EditorProfileListFragment)\n ((EditorProfileListFragment) fragment).showTargetHelps();\n else\n ((EditorEventListFragment) fragment).showTargetHelps();\n }\n }\n\n @Override\n public void onSequenceStep(TapTarget lastTarget, boolean targetClicked) {\n //Log.d(\"TapTargetView\", \"Clicked on \" + lastTarget.id());\n }\n\n @Override\n public void onSequenceCanceled(TapTarget lastTarget) {\n targetHelpsSequenceStarted = false;\n Editor editor = ApplicationPreferences.preferences.edit();\n if (editorSelectedView == 0) {\n editor.putBoolean(EditorProfileListFragment.PREF_START_TARGET_HELPS, false);\n editor.putBoolean(EditorProfileListAdapter.PREF_START_TARGET_HELPS, false);\n if (filterProfilesSelectedItem == DSI_PROFILES_SHOW_IN_ACTIVATOR)\n editor.putBoolean(EditorProfileListAdapter.PREF_START_TARGET_HELPS_ORDER, false);\n if (filterProfilesSelectedItem == DSI_PROFILES_ALL)\n editor.putBoolean(EditorProfileListAdapter.PREF_START_TARGET_HELPS_SHOW_IN_ACTIVATOR, false);\n }\n else {\n editor.putBoolean(EditorEventListFragment.PREF_START_TARGET_HELPS, false);\n editor.putBoolean(EditorEventListAdapter.PREF_START_TARGET_HELPS, false);\n if (filterEventsSelectedItem == DSI_EVENTS_START_ORDER)\n editor.putBoolean(EditorEventListAdapter.PREF_START_TARGET_HELPS_ORDER, false);\n editor.putBoolean(EditorEventListAdapter.PREF_START_TARGET_HELPS_STATUS, false);\n }\n editor.apply();\n }\n });\n sequence.continueOnCancel(true)\n .considerOuterCircleCanceled(true);\n targetHelpsSequenceStarted = true;\n sequence.start();\n }\n else {\n //Log.d(\"EditorProfilesActivity.showTargetHelps\", \"PREF_START_TARGET_HELPS=false\");\n //final Context context = getApplicationContext();\n final Handler handler = new Handler(getMainLooper());\n handler.postDelayed(new Runnable() {\n @Override\n public void run() {\n Intent intent = new Intent(PPApplication.PACKAGE_NAME + \".ShowEditorTargetHelpsBroadcastReceiver\");\n LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);\n /*if (EditorProfilesActivity.getInstance() != null) {\n Fragment fragment = EditorProfilesActivity.getInstance().getFragmentManager().findFragmentById(R.id.editor_list_container);\n if (fragment != null) {\n if (fragment instanceof EditorProfileListFragment)\n ((EditorProfileListFragment) fragment).showTargetHelps();\n else\n ((EditorEventListFragment) fragment).showTargetHelps();\n }\n }*/\n }\n }, 500);\n }\n }\n }\n\n static boolean displayRedTextToPreferencesNotification(Profile profile, Event event, Context context) {\n if ((profile == null) && (event == null))\n return true;\n\n\n if ((profile != null) && (!ProfilesPrefsFragment.isRedTextNotificationRequired(profile, context)))\n return true;\n if ((event != null) && (!EventsPrefsFragment.isRedTextNotificationRequired(event, context)))\n return true;\n\n int notificationID = 0;\n\n String nTitle = \"\";\n String nText = \"\";\n\n Intent intent = null;\n\n if (profile != null) {\n intent = new Intent(context, ProfilesPrefsActivity.class);\n intent.putExtra(PPApplication.EXTRA_PROFILE_ID, profile._id);\n intent.putExtra(EditorProfilesActivity.EXTRA_NEW_PROFILE_MODE, EditorProfileListFragment.EDIT_MODE_EDIT);\n intent.putExtra(EditorProfilesActivity.EXTRA_PREDEFINED_PROFILE_INDEX, 0);\n }\n if (event != null) {\n intent = new Intent(context, EventsPrefsActivity.class);\n intent.putExtra(PPApplication.EXTRA_EVENT_ID, event._id);\n intent.putExtra(PPApplication.EXTRA_EVENT_STATUS, event.getStatus());\n intent.putExtra(EXTRA_NEW_EVENT_MODE, EditorEventListFragment.EDIT_MODE_EDIT);\n intent.putExtra(EXTRA_PREDEFINED_EVENT_INDEX, 0);\n }\n\n intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n\n if (profile != null) {\n nTitle = context.getString(R.string.profile_preferences_red_texts_title);\n nText = context.getString(R.string.profile_preferences_red_texts_text_1) + \" \" +\n \"\\\"\" + profile._name + \"\\\" \" +\n context.getString(R.string.preferences_red_texts_text_2) + \" \" +\n context.getString(R.string.preferences_red_texts_text_click);\n if (android.os.Build.VERSION.SDK_INT < 24) {\n nTitle = context.getString(R.string.app_name);\n nText = context.getString(R.string.profile_preferences_red_texts_title) + \": \" +\n context.getString(R.string.profile_preferences_red_texts_text_1) + \" \" +\n \"\\\"\" + profile._name + \"\\\" \" +\n context.getString(R.string.preferences_red_texts_text_2) + \" \" +\n context.getString(R.string.preferences_red_texts_text_click);\n }\n\n intent.putExtra(PPApplication.EXTRA_PROFILE_ID, profile._id);\n notificationID = 9999 + (int) profile._id;\n }\n\n if (event != null) {\n nTitle = context.getString(R.string.event_preferences_red_texts_title);\n nText = context.getString(R.string.event_preferences_red_texts_text_1) + \" \" +\n \"\\\"\" + event._name + \"\\\" \" +\n context.getString(R.string.preferences_red_texts_text_2) + \" \" +\n context.getString(R.string.preferences_red_texts_text_click);\n if (android.os.Build.VERSION.SDK_INT < 24) {\n nTitle = context.getString(R.string.app_name);\n nText = context.getString(R.string.event_preferences_red_texts_title) + \": \" +\n context.getString(R.string.event_preferences_red_texts_text_1) + \" \" +\n \"\\\"\" + event._name + \"\\\" \" +\n context.getString(R.string.preferences_red_texts_text_2) + \" \" +\n context.getString(R.string.preferences_red_texts_text_click);\n }\n\n intent.putExtra(PPApplication.EXTRA_EVENT_ID, event._id);\n notificationID = -(9999 + (int) event._id);\n }\n\n PPApplication.createGrantPermissionNotificationChannel(context);\n NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, PPApplication.GRANT_PERMISSION_NOTIFICATION_CHANNEL)\n .setColor(ContextCompat.getColor(context, R.color.notificationDecorationColor))\n .setSmallIcon(R.drawable.ic_exclamation_notify) // notification icon\n .setContentTitle(nTitle) // title for notification\n .setContentText(nText) // message for notification\n .setAutoCancel(true); // clear notification after click\n mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(nText));\n\n PendingIntent pi = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);\n mBuilder.setContentIntent(pi);\n\n mBuilder.setPriority(NotificationCompat.PRIORITY_MAX);\n mBuilder.setCategory(NotificationCompat.CATEGORY_RECOMMENDATION);\n mBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);\n mBuilder.setOnlyAlertOnce(true);\n\n NotificationManager mNotificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);\n if (mNotificationManager != null)\n mNotificationManager.notify(notificationID, mBuilder.build());\n\n return false;\n }\n\n static void showDialogAboutRedText(Profile profile, Event event, boolean forShowInActivator, boolean forRunStopEvent, Activity activity) {\n if (activity == null)\n return;\n\n String nTitle = \"\";\n String nText = \"\";\n\n if (profile != null) {\n nTitle = activity.getString(R.string.profile_preferences_red_texts_title);\n nText = activity.getString(R.string.profile_preferences_red_texts_text_1) + \" \" +\n \"\\\"\" + profile._name + \"\\\" \" +\n activity.getString(R.string.preferences_red_texts_text_2);\n if (android.os.Build.VERSION.SDK_INT < 24) {\n nTitle = activity.getString(R.string.app_name);\n nText = activity.getString(R.string.profile_preferences_red_texts_title) + \": \" +\n activity.getString(R.string.profile_preferences_red_texts_text_1) + \" \" +\n \"\\\"\" + profile._name + \"\\\" \" +\n activity.getString(R.string.preferences_red_texts_text_2);\n }\n if (forShowInActivator)\n nText = nText + \" \" + activity.getString(R.string.profile_preferences_red_texts_text_3);\n else\n nText = nText + \" \" + activity.getString(R.string.profile_preferences_red_texts_text_2);\n }\n\n if (event != null) {\n nTitle = activity.getString(R.string.event_preferences_red_texts_title);\n nText = activity.getString(R.string.event_preferences_red_texts_text_1) + \" \" +\n \"\\\"\" + event._name + \"\\\" \" +\n activity.getString(R.string.preferences_red_texts_text_2);\n if (android.os.Build.VERSION.SDK_INT < 24) {\n nTitle = activity.getString(R.string.app_name);\n nText = activity.getString(R.string.event_preferences_red_texts_title) + \": \" +\n activity.getString(R.string.event_preferences_red_texts_text_1) + \" \" +\n \"\\\"\" + event._name + \"\\\" \" +\n activity.getString(R.string.preferences_red_texts_text_2);\n }\n if (forRunStopEvent)\n nText = nText + \" \" + activity.getString(R.string.event_preferences_red_texts_text_2);\n else\n nText = nText + \" \" + activity.getString(R.string.profile_preferences_red_texts_text_2);\n }\n\n if ((profile != null) || (event != null)) {\n AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(activity);\n dialogBuilder.setTitle(nTitle);\n dialogBuilder.setMessage(nText);\n dialogBuilder.setPositiveButton(android.R.string.ok, null);\n AlertDialog dialog = dialogBuilder.create();\n if (!activity.isFinishing())\n dialog.show();\n }\n }\n\n}\n"},"new_file":{"kind":"string","value":"phoneProfilesPlus/src/main/java/sk/henrichg/phoneprofilesplus/EditorProfilesActivity.java"},"old_contents":{"kind":"string","value":"package sk.henrichg.phoneprofilesplus;\n\nimport android.annotation.SuppressLint;\nimport android.app.Activity;\nimport android.app.ActivityManager;\nimport android.app.NotificationManager;\nimport android.app.PendingIntent;\nimport android.content.BroadcastReceiver;\nimport android.content.ComponentName;\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.content.Intent;\nimport android.content.IntentFilter;\nimport android.content.SharedPreferences;\nimport android.content.SharedPreferences.Editor;\nimport android.content.pm.LabeledIntent;\nimport android.content.pm.PackageInfo;\nimport android.content.pm.ResolveInfo;\nimport android.media.AudioManager;\nimport android.net.Uri;\nimport android.os.AsyncTask;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.os.Environment;\nimport android.os.Handler;\nimport android.util.Log;\nimport android.view.LayoutInflater;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.view.ViewTreeObserver;\nimport android.widget.AdapterView;\nimport android.widget.AdapterView.OnItemSelectedListener;\nimport android.widget.ImageView;\nimport android.widget.Toast;\n\nimport com.crashlytics.android.Crashlytics;\nimport com.getkeepsafe.taptargetview.TapTarget;\nimport com.getkeepsafe.taptargetview.TapTargetSequence;\nimport com.google.android.material.bottomnavigation.BottomNavigationView;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.ObjectInputStream;\nimport java.io.ObjectOutputStream;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\nimport androidx.annotation.NonNull;\nimport androidx.appcompat.app.AlertDialog;\nimport androidx.appcompat.app.AppCompatActivity;\nimport androidx.appcompat.widget.AppCompatSpinner;\nimport androidx.appcompat.widget.Toolbar;\nimport androidx.appcompat.widget.TooltipCompat;\nimport androidx.core.app.NotificationCompat;\nimport androidx.core.content.ContextCompat;\nimport androidx.core.content.FileProvider;\nimport androidx.fragment.app.Fragment;\nimport androidx.localbroadcastmanager.content.LocalBroadcastManager;\nimport me.drakeet.support.toast.ToastCompat;\nimport sk.henrichg.phoneprofilesplus.EditorEventListFragment.OnStartEventPreferences;\nimport sk.henrichg.phoneprofilesplus.EditorProfileListFragment.OnStartProfilePreferences;\n\npublic class EditorProfilesActivity extends AppCompatActivity\n implements OnStartProfilePreferences,\n OnStartEventPreferences\n{\n\n //private static volatile EditorProfilesActivity instance;\n\n private ImageView eventsRunStopIndicator;\n\n private static boolean savedInstanceStateChanged;\n\n private static ApplicationsCache applicationsCache;\n\n private AsyncTask importAsyncTask = null;\n private AsyncTask exportAsyncTask = null;\n static boolean doImport = false;\n private AlertDialog importProgressDialog = null;\n private AlertDialog exportProgressDialog = null;\n\n private static final String SP_EDITOR_SELECTED_VIEW = \"editor_selected_view\";\n private static final String SP_EDITOR_PROFILES_VIEW_SELECTED_ITEM = \"editor_profiles_view_selected_item\";\n static final String SP_EDITOR_EVENTS_VIEW_SELECTED_ITEM = \"editor_events_view_selected_item\";\n\n private static final int DSI_PROFILES_ALL = 0;\n private static final int DSI_PROFILES_SHOW_IN_ACTIVATOR = 1;\n private static final int DSI_PROFILES_NO_SHOW_IN_ACTIVATOR = 2;\n private static final int DSI_EVENTS_START_ORDER = 0;\n private static final int DSI_EVENTS_ALL = 1;\n private static final int DSI_EVENTS_NOT_STOPPED = 2;\n private static final int DSI_EVENTS_RUNNING = 3;\n private static final int DSI_EVENTS_PAUSED = 4;\n private static final int DSI_EVENTS_STOPPED = 5;\n\n static final String EXTRA_NEW_PROFILE_MODE = \"new_profile_mode\";\n static final String EXTRA_PREDEFINED_PROFILE_INDEX = \"predefined_profile_index\";\n static final String EXTRA_NEW_EVENT_MODE = \"new_event_mode\";\n static final String EXTRA_PREDEFINED_EVENT_INDEX = \"predefined_event_index\";\n\n // request code for startActivityForResult with intent BackgroundActivateProfileActivity\n static final int REQUEST_CODE_ACTIVATE_PROFILE = 6220;\n // request code for startActivityForResult with intent ProfilesPrefsActivity\n private static final int REQUEST_CODE_PROFILE_PREFERENCES = 6221;\n // request code for startActivityForResult with intent EventPreferencesActivity\n private static final int REQUEST_CODE_EVENT_PREFERENCES = 6222;\n // request code for startActivityForResult with intent PhoneProfilesActivity\n private static final int REQUEST_CODE_APPLICATION_PREFERENCES = 6229;\n // request code for startActivityForResult with intent \"phoneprofiles.intent.action.EXPORTDATA\"\n private static final int REQUEST_CODE_REMOTE_EXPORT = 6250;\n\n public boolean targetHelpsSequenceStarted;\n public static final String PREF_START_TARGET_HELPS = \"editor_profiles_activity_start_target_helps\";\n public static final String PREF_START_TARGET_HELPS_DEFAULT_PROFILE = \"editor_profile_activity_start_target_helps_default_profile\";\n public static final String PREF_START_TARGET_HELPS_FILTER_SPINNER = \"editor_profile_activity_start_target_helps_filter_spinner\";\n @SuppressWarnings(\"WeakerAccess\")\n public static final String PREF_START_TARGET_HELPS_RUN_STOP_INDICATOR = \"editor_profile_activity_start_target_helps_run_stop_indicator\";\n @SuppressWarnings(\"WeakerAccess\")\n public static final String PREF_START_TARGET_HELPS_BOTTOM_NAVIGATION = \"editor_profile_activity_start_target_helps_bottom_navigation\";\n\n private Toolbar editorToolbar;\n //Toolbar bottomToolbar;\n //private DrawerLayout drawerLayout;\n //private PPScrimInsetsFrameLayout drawerRoot;\n //private ListView drawerListView;\n //private ActionBarDrawerToggle drawerToggle;\n //private BottomNavigationView bottomNavigationView;\n private AppCompatSpinner filterSpinner;\n //private AppCompatSpinner orderSpinner;\n //private View headerView;\n //private ImageView drawerHeaderFilterImage;\n //private TextView drawerHeaderFilterTitle;\n //private TextView drawerHeaderFilterSubtitle;\n private BottomNavigationView bottomNavigationView;\n\n //private String[] drawerItemsTitle;\n //private String[] drawerItemsSubtitle;\n //private Integer[] drawerItemsIcon;\n\n private int editorSelectedView = 0;\n private int filterProfilesSelectedItem = 0;\n private int filterEventsSelectedItem = 0;\n\n private boolean startTargetHelps;\n\n AddProfileDialog addProfileDialog;\n AddEventDialog addEventDialog;\n\n private final BroadcastReceiver refreshGUIBroadcastReceiver = new BroadcastReceiver() {\n @Override\n public void onReceive( Context context, Intent intent ) {\n boolean refresh = intent.getBooleanExtra(RefreshActivitiesBroadcastReceiver.EXTRA_REFRESH, true);\n boolean refreshIcons = intent.getBooleanExtra(RefreshActivitiesBroadcastReceiver.EXTRA_REFRESH_ICONS, false);\n long profileId = intent.getLongExtra(PPApplication.EXTRA_PROFILE_ID, 0);\n long eventId = intent.getLongExtra(PPApplication.EXTRA_EVENT_ID, 0);\n // not change selection in editor if refresh is outside editor\n EditorProfilesActivity.this.refreshGUI(refresh, refreshIcons, false, profileId, eventId);\n }\n };\n\n private final BroadcastReceiver showTargetHelpsBroadcastReceiver = new BroadcastReceiver() {\n @Override\n public void onReceive( Context context, Intent intent ) {\n Fragment fragment = EditorProfilesActivity.this.getSupportFragmentManager().findFragmentById(R.id.editor_list_container);\n if (fragment != null) {\n if (fragment instanceof EditorProfileListFragment)\n ((EditorProfileListFragment) fragment).showTargetHelps();\n else\n ((EditorEventListFragment) fragment).showTargetHelps();\n }\n }\n };\n\n private final BroadcastReceiver finishBroadcastReceiver = new BroadcastReceiver() {\n @Override\n public void onReceive( Context context, Intent intent ) {\n PPApplication.logE(\"EditorProfilesActivity.finishBroadcastReceiver\", \"xxx\");\n String action = intent.getAction();\n if (action.equals(PPApplication.ACTION_FINISH_ACTIVITY)) {\n String what = intent.getStringExtra(PPApplication.EXTRA_WHAT_FINISH);\n if (what.equals(\"editor\")) {\n try {\n EditorProfilesActivity.this.finishAffinity();\n } catch (Exception ignored) {}\n }\n }\n }\n };\n\n @SuppressLint({\"NewApi\", \"RestrictedApi\"})\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n GlobalGUIRoutines.setTheme(this, false, true/*, true*/, false);\n //GlobalGUIRoutines.setLanguage(this);\n\n savedInstanceStateChanged = (savedInstanceState != null);\n\n createApplicationsCache();\n\n /*if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)\n setContentView(R.layout.activity_editor_list_onepane_19);\n else*/\n setContentView(R.layout.activity_editor_list_onepane);\n setTaskDescription(new ActivityManager.TaskDescription(getString(R.string.app_name)));\n\n //drawerLayout = findViewById(R.id.editor_list_drawer_layout);\n\n /*\n if (Build.VERSION.SDK_INT >= 21) {\n drawerLayout.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {\n @Override\n public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {\n int statusBarHeight = insets.getSystemWindowInsetTop();\n PPApplication.logE(\"EditorProfilesActivity.onApplyWindowInsets\", \"statusBarHeight=\"+statusBarHeight);\n Rect rect = insets.getSystemWindowInsets();\n PPApplication.logE(\"EditorProfilesActivity.onApplyWindowInsets\", \"rect.top=\"+rect.top);\n rect.top = rect.top + statusBarHeight;\n return insets.replaceSystemWindowInsets(rect);\n }\n }\n );\n }\n */\n\n //overridePendingTransition(R.anim.fade_in, R.anim.fade_out);\n\n //String appTheme = ApplicationPreferences.applicationTheme(getApplicationContext(), true);\n\n /*\n if ((Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)) {\n Window w = getWindow(); // in Activity's onCreate() for instance\n //w.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);\n w.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);\n\n // create our manager instance after the content view is set\n SystemBarTintManager tintManager = new SystemBarTintManager(this);\n // enable status bar tint\n tintManager.setStatusBarTintEnabled(true);\n // set a custom tint color for status bar\n switch (appTheme) {\n case \"color\":\n tintManager.setStatusBarTintColor(ContextCompat.getColor(getBaseContext(), R.color.primary));\n break;\n case \"white\":\n tintManager.setStatusBarTintColor(ContextCompat.getColor(getBaseContext(), R.color.primaryDark19_white));\n break;\n default:\n tintManager.setStatusBarTintColor(ContextCompat.getColor(getBaseContext(), R.color.primary_dark));\n break;\n }\n }\n */\n\n //if (android.os.Build.VERSION.SDK_INT >= 21)\n //\tgetWindow().setNavigationBarColor(R.attr.colorPrimary);\n\n //setWindowContentOverlayCompat();\n\n /*\t// add profile list into list container\n EditorProfileListFragment fragment = new EditorProfileListFragment();\n getSupportFragmentManager().beginTransaction()\n .replace(R.id.editor_list_container, fragment, \"EditorProfileListFragment\").commit(); */\n\n /*\n drawerRoot = findViewById(R.id.editor_drawer_root);\n\n // set status bar background for Activity body layout\n switch (appTheme) {\n case \"color\":\n drawerLayout.setStatusBarBackground(R.color.primaryDark);\n break;\n case \"white\":\n drawerLayout.setStatusBarBackground(R.color.primaryDark_white);\n break;\n case \"dark\":\n drawerLayout.setStatusBarBackground(R.color.primaryDark_dark);\n break;\n case \"dlight\":\n drawerLayout.setStatusBarBackground(R.color.primaryDark_dark);\n break;\n }\n\n drawerListView = findViewById(R.id.editor_drawer_list);\n //noinspection ConstantConditions\n headerView = ((LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE)).\n inflate(R.layout.editor_drawer_list_header, drawerListView, false);\n drawerListView.addHeaderView(headerView, null, false);\n drawerHeaderFilterImage = findViewById(R.id.editor_drawer_list_header_icon);\n drawerHeaderFilterTitle = findViewById(R.id.editor_drawer_list_header_title);\n drawerHeaderFilterSubtitle = findViewById(R.id.editor_drawer_list_header_subtitle);\n\n // set header padding for notches\n //if (Build.VERSION.SDK_INT >= 21) {\n drawerRoot.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {\n @Override\n public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {\n headerView.setPadding(\n headerView.getPaddingLeft(),\n headerView.getPaddingTop() + insets.getSystemWindowInsetTop(),\n headerView.getPaddingRight(),\n headerView.getPaddingBottom());\n insets.consumeSystemWindowInsets();\n drawerRoot.setOnApplyWindowInsetsListener(null);\n return insets;\n }\n });\n //}\n\n //if (Build.VERSION.SDK_INT < 21)\n // drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);\n\n // actionbar titles\n drawerItemsTitle = new String[] {\n getResources().getString(R.string.editor_drawer_title_profiles),\n getResources().getString(R.string.editor_drawer_title_profiles),\n getResources().getString(R.string.editor_drawer_title_profiles),\n getResources().getString(R.string.editor_drawer_title_events),\n getResources().getString(R.string.editor_drawer_title_events),\n getResources().getString(R.string.editor_drawer_title_events),\n getResources().getString(R.string.editor_drawer_title_events),\n getResources().getString(R.string.editor_drawer_title_events)\n };\n\n // drawer item titles\n drawerItemsSubtitle = new String[] {\n getResources().getString(R.string.editor_drawer_list_item_profiles_all),\n getResources().getString(R.string.editor_drawer_list_item_profiles_show_in_activator),\n getResources().getString(R.string.editor_drawer_list_item_profiles_no_show_in_activator),\n getResources().getString(R.string.editor_drawer_list_item_events_start_order),\n getResources().getString(R.string.editor_drawer_list_item_events_all),\n getResources().getString(R.string.editor_drawer_list_item_events_running),\n getResources().getString(R.string.editor_drawer_list_item_events_paused),\n getResources().getString(R.string.editor_drawer_list_item_events_stopped)\n };\n\n drawerItemsIcon = new Integer[] {\n R.drawable.ic_events_drawer_profile_filter_2,\n R.drawable.ic_events_drawer_profile_filter_0,\n R.drawable.ic_events_drawer_profile_filter_1,\n R.drawable.ic_events_drawer_event_filter_2,\n R.drawable.ic_events_drawer_event_filter_2,\n R.drawable.ic_events_drawer_event_filter_0,\n R.drawable.ic_events_drawer_event_filter_1,\n R.drawable.ic_events_drawer_event_filter_3,\n };\n\n\n // Pass string arrays to EditorDrawerListAdapter\n // use action bar themed context\n //drawerAdapter = new EditorDrawerListAdapter(drawerListView, getSupportActionBar().getThemedContext(), drawerItemsTitle, drawerItemsSubtitle, drawerItemsIcon);\n EditorDrawerListAdapter drawerAdapter = new EditorDrawerListAdapter(getBaseContext(), drawerItemsTitle, drawerItemsSubtitle, drawerItemsIcon);\n \n // Set the MenuListAdapter to the ListView\n drawerListView.setAdapter(drawerAdapter);\n \n // Capture listview menu item click\n drawerListView.setOnItemClickListener(new DrawerItemClickListener());\n */\n\n editorToolbar = findViewById(R.id.editor_toolbar);\n setSupportActionBar(editorToolbar);\n if (getSupportActionBar() != null) {\n getSupportActionBar().setTitle(R.string.title_activity_editor);\n }\n\n //bottomToolbar = findViewById(R.id.editor_list_bottom_bar);\n\n /*\n // Enable ActionBar app icon to behave as action to toggle nav drawer\n if (getSupportActionBar() != null) {\n getSupportActionBar().setHomeButtonEnabled(true);\n getSupportActionBar().setDisplayHomeAsUpEnabled(true);\n }\n */\n\n /*\n // is required. This adds hamburger icon in toolbar\n drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.editor_drawer_open, R.string.editor_drawer_open)\n {\n public void onDrawerClosed(View view) {\n super.onDrawerClosed(view);\n }\n \n public void onDrawerOpened(View drawerView) {\n super.onDrawerOpened(drawerView);\n }\n // this disable animation\n //@Override\n //public void onDrawerSlide(View drawerView, float slideOffset)\n //{\n // if(drawerView!=null && drawerView == drawerRoot){\n // super.onDrawerSlide(drawerView, 0);\n // }else{\n // super.onDrawerSlide(drawerView, slideOffset);\n // }\n //}\n };\n drawerLayout.addDrawerListener(drawerToggle);\n */\n\n bottomNavigationView = findViewById(R.id.editor_list_bottom_navigation);\n bottomNavigationView.setOnNavigationItemSelectedListener(\n new BottomNavigationView.OnNavigationItemSelectedListener() {\n @Override\n public boolean onNavigationItemSelected(@NonNull MenuItem item) {\n switch (item.getItemId()) {\n case R.id.menu_profiles_view:\n //Log.e(\"EditorProfilesActivity.onNavigationItemSelected\", \"menu_profiles_view\");\n String[] filterItems = new String[] {\n getString(R.string.editor_drawer_title_profiles) + \" - \" + getString(R.string.editor_drawer_list_item_profiles_all),\n getString(R.string.editor_drawer_title_profiles) + \" - \" + getString(R.string.editor_drawer_list_item_profiles_show_in_activator),\n getString(R.string.editor_drawer_title_profiles) + \" - \" + getString(R.string.editor_drawer_list_item_profiles_no_show_in_activator),\n };\n GlobalGUIRoutines.HighlightedSpinnerAdapter filterSpinnerAdapter = new GlobalGUIRoutines.HighlightedSpinnerAdapter(\n EditorProfilesActivity.this,\n R.layout.highlighted_filter_spinner,\n filterItems);\n filterSpinnerAdapter.setDropDownViewResource(R.layout.highlighted_spinner_dropdown);\n filterSpinner.setAdapter(filterSpinnerAdapter);\n selectFilterItem(0, filterProfilesSelectedItem, false, startTargetHelps);\n Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.editor_list_container);\n if (fragment instanceof EditorProfileListFragment)\n ((EditorProfileListFragment)fragment).showHeaderAndBottomToolbar();\n break;\n case R.id.menu_events_view:\n //Log.e(\"EditorProfilesActivity.onNavigationItemSelected\", \"menu_events_view\");\n filterItems = new String[] {\n getString(R.string.editor_drawer_title_events) + \" - \" + getString(R.string.editor_drawer_list_item_events_start_order),\n getString(R.string.editor_drawer_title_events) + \" - \" + getString(R.string.editor_drawer_list_item_events_all),\n getString(R.string.editor_drawer_title_events) + \" - \" + getString(R.string.editor_drawer_list_item_events_not_stopped),\n getString(R.string.editor_drawer_title_events) + \" - \" + getString(R.string.editor_drawer_list_item_events_running),\n getString(R.string.editor_drawer_title_events) + \" - \" + getString(R.string.editor_drawer_list_item_events_paused),\n getString(R.string.editor_drawer_title_events) + \" - \" + getString(R.string.editor_drawer_list_item_events_stopped)\n };\n filterSpinnerAdapter = new GlobalGUIRoutines.HighlightedSpinnerAdapter(\n EditorProfilesActivity.this,\n R.layout.highlighted_filter_spinner,\n filterItems);\n filterSpinnerAdapter.setDropDownViewResource(R.layout.highlighted_spinner_dropdown);\n filterSpinner.setAdapter(filterSpinnerAdapter);\n selectFilterItem(1, filterEventsSelectedItem, false, startTargetHelps);\n fragment = getSupportFragmentManager().findFragmentById(R.id.editor_list_container);\n if (fragment instanceof EditorEventListFragment) {\n ((EditorEventListFragment)fragment).showHeaderAndBottomToolbar();\n }\n break;\n }\n return true;\n }\n });\n\n filterSpinner = findViewById(R.id.editor_filter_spinner);\n String[] filterItems = new String[] {\n getString(R.string.editor_drawer_title_profiles) + \" - \" + getString(R.string.editor_drawer_list_item_profiles_all),\n getString(R.string.editor_drawer_title_profiles) + \" - \" + getString(R.string.editor_drawer_list_item_profiles_show_in_activator),\n getString(R.string.editor_drawer_title_profiles) + \" - \" + getString(R.string.editor_drawer_list_item_profiles_no_show_in_activator)\n };\n GlobalGUIRoutines.HighlightedSpinnerAdapter filterSpinnerAdapter = new GlobalGUIRoutines.HighlightedSpinnerAdapter(\n this,\n R.layout.highlighted_filter_spinner,\n filterItems);\n filterSpinnerAdapter.setDropDownViewResource(R.layout.highlighted_spinner_dropdown);\n filterSpinner.setPopupBackgroundResource(R.drawable.popupmenu_background);\n filterSpinner.setSupportBackgroundTintList(ContextCompat.getColorStateList(this/*getBaseContext()*/, R.color.highlighted_spinner_all));\n/* switch (appTheme) {\n case \"dark\":\n filterSpinner.setSupportBackgroundTintList(ContextCompat.getColorStateList(getBaseContext(), R.color.editorFilterTitleColor_dark));\n //filterSpinner.setPopupBackgroundResource(R.drawable.popupmenu_background_dark);\n break;\n case \"white\":\n filterSpinner.setSupportBackgroundTintList(ContextCompat.getColorStateList(getBaseContext(), R.color.editorFilterTitleColor_white));\n //filterSpinner.setPopupBackgroundResource(R.drawable.popupmenu_background_white);\n break;\n// case \"dlight\":\n// filterSpinner.setSupportBackgroundTintList(ContextCompat.getColorStateList(getBaseContext(), R.color.editorFilterTitleColor));\n// filterSpinner.setPopupBackgroundResource(R.drawable.popupmenu_background_dlight);\n// break;\n default:\n filterSpinner.setSupportBackgroundTintList(ContextCompat.getColorStateList(getBaseContext(), R.color.editorFilterTitleColor));\n //filterSpinner.setPopupBackgroundResource(R.drawable.popupmenu_background_white);\n break;\n }*/\n filterSpinner.setAdapter(filterSpinnerAdapter);\n filterSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {\n\n public void onItemSelected(AdapterView parent, View view, int position, long id) {\n ((GlobalGUIRoutines.HighlightedSpinnerAdapter)filterSpinner.getAdapter()).setSelection(position);\n selectFilterItem(editorSelectedView, position, true, true);\n }\n\n public void onNothingSelected(AdapterView parent) {\n }\n });\n\n eventsRunStopIndicator = findViewById(R.id.editor_list_run_stop_indicator);\n TooltipCompat.setTooltipText(eventsRunStopIndicator, getString(R.string.editor_activity_targetHelps_trafficLightIcon_title));\n eventsRunStopIndicator.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n RunStopIndicatorPopupWindow popup = new RunStopIndicatorPopupWindow(getDataWrapper(), EditorProfilesActivity.this);\n\n View contentView = popup.getContentView();\n contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);\n int popupWidth = contentView.getMeasuredWidth();\n //int popupHeight = contentView.getMeasuredHeight();\n //Log.d(\"ActivateProfileActivity.eventsRunStopIndicator.onClick\",\"popupWidth=\"+popupWidth);\n //Log.d(\"ActivateProfileActivity.eventsRunStopIndicator.onClick\",\"popupHeight=\"+popupHeight);\n\n int[] runStopIndicatorLocation = new int[2];\n //eventsRunStopIndicator.getLocationOnScreen(runStopIndicatorLocation);\n eventsRunStopIndicator.getLocationInWindow(runStopIndicatorLocation);\n\n int x = 0;\n int y = 0;\n\n if (runStopIndicatorLocation[0] + eventsRunStopIndicator.getWidth() - popupWidth < 0)\n x = -(runStopIndicatorLocation[0] + eventsRunStopIndicator.getWidth() - popupWidth);\n\n popup.setClippingEnabled(false); // disabled for draw outside activity\n popup.showOnAnchor(eventsRunStopIndicator, RelativePopupWindow.VerticalPosition.ALIGN_TOP,\n RelativePopupWindow.HorizontalPosition.ALIGN_RIGHT, x, y, false);\n }\n });\n \n // set drawer item and order\n //if ((savedInstanceState != null) || (ApplicationPreferences.applicationEditorSaveEditorState(getApplicationContext())))\n //{\n ApplicationPreferences.getSharedPreferences(this);\n //filterSelectedItem = ApplicationPreferences.preferences.getInt(SP_EDITOR_DRAWER_SELECTED_ITEM, 1);\n editorSelectedView = ApplicationPreferences.preferences.getInt(SP_EDITOR_SELECTED_VIEW, 0);\n filterProfilesSelectedItem = ApplicationPreferences.preferences.getInt(SP_EDITOR_PROFILES_VIEW_SELECTED_ITEM, 0);\n filterEventsSelectedItem = ApplicationPreferences.preferences.getInt(SP_EDITOR_EVENTS_VIEW_SELECTED_ITEM, 0);\n //}\n\n startTargetHelps = false;\n if (editorSelectedView == 0)\n bottomNavigationView.setSelectedItemId(R.id.menu_profiles_view);\n else\n bottomNavigationView.setSelectedItemId(R.id.menu_events_view);\n /*\n if (editorSelectedView == 0)\n selectFilterItem(filterProfilesSelectedItem, false, false, false);\n else\n selectFilterItem(filterEventsSelectedItem, false, false, false);\n */\n\n /*\n // not working good, all activity is under status bar\n ViewCompat.setOnApplyWindowInsetsListener(drawerLayout, new OnApplyWindowInsetsListener() {\n @Override\n public WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) {\n int statusBarSize = insets.getSystemWindowInsetTop();\n PPApplication.logE(\"EditorProfilesActivity.onApplyWindowInsets\", \"statusBarSize=\"+statusBarSize);\n return insets;\n }\n });\n */\n\n getApplicationContext().registerReceiver(finishBroadcastReceiver, new IntentFilter(PPApplication.ACTION_FINISH_ACTIVITY));\n }\n\n @Override\n protected void onStart()\n {\n super.onStart();\n PPApplication.logE(\"EditorProfilesActivity.onStart\", \"xxx\");\n\n Intent intent = new Intent(PPApplication.ACTION_FINISH_ACTIVITY);\n intent.putExtra(PPApplication.EXTRA_WHAT_FINISH, \"activator\");\n getApplicationContext().sendBroadcast(intent);\n\n LocalBroadcastManager.getInstance(this).registerReceiver(refreshGUIBroadcastReceiver,\n new IntentFilter(PPApplication.PACKAGE_NAME + \".RefreshEditorGUIBroadcastReceiver\"));\n LocalBroadcastManager.getInstance(this).registerReceiver(showTargetHelpsBroadcastReceiver,\n new IntentFilter(PPApplication.PACKAGE_NAME + \".ShowEditorTargetHelpsBroadcastReceiver\"));\n\n refreshGUI(true, false, true, 0, 0);\n\n // this is for list widget header\n if (!PPApplication.getApplicationStarted(getApplicationContext(), true))\n {\n if (PPApplication.logEnabled()) {\n PPApplication.logE(\"EditorProfilesActivity.onStart\", \"application is not started\");\n PPApplication.logE(\"EditorProfilesActivity.onStart\", \"service instance=\" + PhoneProfilesService.getInstance());\n if (PhoneProfilesService.getInstance() != null)\n PPApplication.logE(\"EditorProfilesActivity.onStart\", \"service hasFirstStart=\" + PhoneProfilesService.getInstance().getServiceHasFirstStart());\n }\n // start PhoneProfilesService\n //PPApplication.firstStartServiceStarted = false;\n PPApplication.setApplicationStarted(getApplicationContext(), true);\n Intent serviceIntent = new Intent(getApplicationContext(), PhoneProfilesService.class);\n //serviceIntent.putExtra(PhoneProfilesService.EXTRA_ONLY_START, true);\n serviceIntent.putExtra(PhoneProfilesService.EXTRA_DEACTIVATE_PROFILE, true);\n serviceIntent.putExtra(PhoneProfilesService.EXTRA_ACTIVATE_PROFILES, true);\n PPApplication.startPPService(this, serviceIntent);\n }\n else\n {\n if ((PhoneProfilesService.getInstance() == null) || (!PhoneProfilesService.getInstance().getServiceHasFirstStart())) {\n if (PPApplication.logEnabled()) {\n PPApplication.logE(\"EditorProfilesActivity.onStart\", \"application is started\");\n PPApplication.logE(\"EditorProfilesActivity.onStart\", \"service instance=\" + PhoneProfilesService.getInstance());\n if (PhoneProfilesService.getInstance() != null)\n PPApplication.logE(\"EditorProfilesActivity.onStart\", \"service hasFirstStart=\" + PhoneProfilesService.getInstance().getServiceHasFirstStart());\n }\n // start PhoneProfilesService\n //PPApplication.firstStartServiceStarted = false;\n Intent serviceIntent = new Intent(getApplicationContext(), PhoneProfilesService.class);\n //serviceIntent.putExtra(PhoneProfilesService.EXTRA_ONLY_START, true);\n serviceIntent.putExtra(PhoneProfilesService.EXTRA_DEACTIVATE_PROFILE, true);\n serviceIntent.putExtra(PhoneProfilesService.EXTRA_ACTIVATE_PROFILES, false);\n PPApplication.startPPService(this, serviceIntent);\n }\n else {\n PPApplication.logE(\"EditorProfilesActivity.onStart\", \"application and service is started\");\n }\n }\n }\n\n @Override\n protected void onStop()\n {\n super.onStop();\n PPApplication.logE(\"EditorProfilesActivity.onStop\", \"xxx\");\n\n LocalBroadcastManager.getInstance(this).unregisterReceiver(refreshGUIBroadcastReceiver);\n LocalBroadcastManager.getInstance(this).unregisterReceiver(showTargetHelpsBroadcastReceiver);\n\n if ((addProfileDialog != null) && (addProfileDialog.mDialog != null) && addProfileDialog.mDialog.isShowing())\n addProfileDialog.mDialog.dismiss();\n if ((addEventDialog != null) && (addEventDialog.mDialog != null) && addEventDialog.mDialog.isShowing())\n addEventDialog.mDialog.dismiss();\n }\n\n @Override\n protected void onDestroy()\n {\n super.onDestroy();\n\n if ((importProgressDialog != null) && importProgressDialog.isShowing()) {\n importProgressDialog.dismiss();\n importProgressDialog = null;\n }\n if ((exportProgressDialog != null) && exportProgressDialog.isShowing()) {\n exportProgressDialog.dismiss();\n exportProgressDialog = null;\n }\n if ((importAsyncTask != null) && !importAsyncTask.getStatus().equals(AsyncTask.Status.FINISHED)){\n importAsyncTask.cancel(true);\n doImport = false;\n }\n if ((exportAsyncTask != null) && !exportAsyncTask.getStatus().equals(AsyncTask.Status.FINISHED)){\n exportAsyncTask.cancel(true);\n }\n\n if (!savedInstanceStateChanged)\n {\n // no destroy caches on orientation change\n if (applicationsCache != null)\n applicationsCache.clearCache(true);\n applicationsCache = null;\n }\n\n getApplicationContext().unregisterReceiver(finishBroadcastReceiver);\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n // Inflate the menu; this adds items to the action bar if it is present.\n editorToolbar.inflateMenu(R.menu.editor_top_bar);\n return true;\n }\n\n private static void onNextLayout(final View view, final Runnable runnable) {\n final ViewTreeObserver observer = view.getViewTreeObserver();\n observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {\n @Override\n public void onGlobalLayout() {\n final ViewTreeObserver trueObserver;\n\n if (observer.isAlive()) {\n trueObserver = observer;\n } else {\n trueObserver = view.getViewTreeObserver();\n }\n\n trueObserver.removeOnGlobalLayoutListener(this);\n\n runnable.run();\n }\n });\n }\n\n @SuppressLint(\"AlwaysShowAction\")\n @Override\n public boolean onPrepareOptionsMenu(Menu menu) {\n boolean ret = super.onPrepareOptionsMenu(menu);\n\n MenuItem menuItem;\n\n //menuItem = menu.findItem(R.id.menu_import_export);\n //menuItem.setTitle(getResources().getString(R.string.menu_import_export) + \" >\");\n\n // change global events run/stop menu item title\n menuItem = menu.findItem(R.id.menu_run_stop_events);\n if (menuItem != null)\n {\n if (Event.getGlobalEventsRunning(getApplicationContext()))\n {\n menuItem.setTitle(R.string.menu_stop_events);\n menuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);\n }\n else\n {\n menuItem.setTitle(R.string.menu_run_events);\n menuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);\n }\n }\n\n menuItem = menu.findItem(R.id.menu_restart_events);\n if (menuItem != null)\n {\n menuItem.setVisible(Event.getGlobalEventsRunning(getApplicationContext()));\n menuItem.setEnabled(PPApplication.getApplicationStarted(getApplicationContext(), true));\n }\n\n menuItem = menu.findItem(R.id.menu_dark_theme);\n if (menuItem != null)\n {\n String appTheme = ApplicationPreferences.applicationTheme(getApplicationContext(), false);\n if (!appTheme.equals(\"night_mode\")) {\n menuItem.setVisible(true);\n if (appTheme.equals(\"dark\"))\n menuItem.setTitle(R.string.menu_dark_theme_off);\n else\n menuItem.setTitle(R.string.menu_dark_theme_on);\n }\n else\n menuItem.setVisible(false);\n }\n\n menuItem = menu.findItem(R.id.menu_email_debug_logs_to_author);\n if (menuItem != null)\n {\n menuItem.setVisible(PPApplication.logIntoFile || PPApplication.crashIntoFile);\n }\n\n menuItem = menu.findItem(R.id.menu_test_crash);\n if (menuItem != null)\n {\n menuItem.setVisible(BuildConfig.DEBUG);\n }\n\n onNextLayout(editorToolbar, new Runnable() {\n @Override\n public void run() {\n showTargetHelps();\n }\n });\n\n return ret;\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n\n Intent intent;\n\n DataWrapper dataWrapper = getDataWrapper();\n\n switch (item.getItemId()) {\n/* case android.R.id.home:\n// if (drawerLayout.isDrawerOpen(drawerRoot)) {\n// drawerLayout.closeDrawer(drawerRoot);\n// } else {\n// drawerLayout.openDrawer(drawerRoot);\n// }\n return super.onOptionsItemSelected(item);*/\n case R.id.menu_restart_events:\n //getDataWrapper().addActivityLog(DatabaseHandler.ALTYPE_RESTARTEVENTS, null, null, null, 0);\n\n // ignore manual profile activation\n // and unblock forceRun events\n PPApplication.logE(\"$$$ restartEvents\",\"from EditorProfilesActivity.onOptionsItemSelected menu_restart_events\");\n if (dataWrapper != null)\n dataWrapper.restartEventsWithAlert(this);\n return true;\n case R.id.menu_run_stop_events:\n if (dataWrapper != null)\n dataWrapper.runStopEventsWithAlert(this, null, false);\n return true;\n case R.id.menu_activity_log:\n intent = new Intent(getBaseContext(), ActivityLogActivity.class);\n startActivity(intent);\n return true;\n case R.id.important_info:\n intent = new Intent(getBaseContext(), ImportantInfoActivity.class);\n startActivity(intent);\n return true;\n case R.id.menu_settings:\n intent = new Intent(getBaseContext(), PhoneProfilesPrefsActivity.class);\n startActivityForResult(intent, REQUEST_CODE_APPLICATION_PREFERENCES);\n return true;\n case R.id.menu_dark_theme:\n String theme = ApplicationPreferences.applicationTheme(getApplicationContext(), false);\n if (!theme.equals(\"night_mode\")) {\n if (theme.equals(\"dark\")) {\n SharedPreferences preferences = ApplicationPreferences.getSharedPreferences(getApplicationContext());\n //theme = preferences.getString(ApplicationPreferences.PREF_APPLICATION_NOT_DARK_THEME, \"white\");\n //theme = ApplicationPreferences.applicationNightModeOffTheme(getApplicationContext());\n Editor editor = preferences.edit();\n editor.putString(ApplicationPreferences.PREF_APPLICATION_THEME, \"white\"/*theme*/);\n editor.apply();\n } else {\n SharedPreferences preferences = ApplicationPreferences.getSharedPreferences(getApplicationContext());\n Editor editor = preferences.edit();\n //editor.putString(ApplicationPreferences.PREF_APPLICATION_NOT_DARK_THEME, theme);\n editor.putString(ApplicationPreferences.PREF_APPLICATION_THEME, \"dark\");\n editor.apply();\n }\n GlobalGUIRoutines.switchNightMode(getApplicationContext(), false);\n GlobalGUIRoutines.reloadActivity(this, true);\n }\n return true;\n case R.id.menu_export:\n exportData(false, false);\n\n return true;\n case R.id.menu_export_and_email:\n exportData(true, false);\n\n return true;\n case R.id.menu_import:\n importData();\n\n return true;\n /*case R.id.menu_help:\n try {\n Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"https://github.com/henrichg/PhoneProfilesPlus/wiki\"));\n startActivity(myIntent);\n } catch (ActivityNotFoundException e) {\n ToastCompat.makeText(getApplicationContext(), \"No application can handle this request.\"\n + \" Please install a web browser\", Toast.LENGTH_LONG).show();\n }\n return true;*/\n case R.id.menu_email_to_author:\n intent = new Intent(Intent.ACTION_SENDTO);\n intent.setData(Uri.parse(\"mailto:\")); // only email apps should handle this\n String[] email = { \"henrich.gron@gmail.com\" };\n intent.putExtra(Intent.EXTRA_EMAIL, email);\n String packageVersion = \"\";\n try {\n PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);\n packageVersion = \" - v\" + pInfo.versionName + \" (\" + PPApplication.getVersionCode(pInfo) + \")\";\n } catch (Exception ignored) {\n }\n intent.putExtra(Intent.EXTRA_SUBJECT, \"PhoneProfilesPlus\" + packageVersion + \" - \" + getString(R.string.about_application_support_subject));\n intent.putExtra(Intent.EXTRA_TEXT, AboutApplicationActivity.getEmailBodyText(/*AboutApplicationActivity.EMAIL_BODY_SUPPORT, */this));\n try {\n startActivity(Intent.createChooser(intent, getString(R.string.email_chooser)));\n } catch (Exception ignored) {}\n\n return true;\n case R.id.menu_export_and_email_to_author:\n exportData(true, true);\n\n return true;\n case R.id.menu_email_debug_logs_to_author:\n ArrayList uris = new ArrayList<>();\n\n File sd = getApplicationContext().getExternalFilesDir(null);\n\n File logFile = new File(sd, PPApplication.LOG_FILENAME);\n if (logFile.exists()) {\n Uri fileUri = FileProvider.getUriForFile(this, getPackageName() + \".provider\", logFile);\n uris.add(fileUri);\n }\n\n File crashFile = new File(sd, TopExceptionHandler.CRASH_FILENAME);\n if (crashFile.exists()) {\n Uri fileUri = FileProvider.getUriForFile(this, getPackageName() + \".provider\", crashFile);\n uris.add(fileUri);\n }\n\n if (uris.size() != 0) {\n String emailAddress = \"henrich.gron@gmail.com\";\n Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(\n \"mailto\", emailAddress, null));\n\n packageVersion = \"\";\n try {\n PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);\n packageVersion = \" - v\" + pInfo.versionName + \" (\" + PPApplication.getVersionCode(pInfo) + \")\";\n } catch (Exception ignored) {}\n emailIntent.putExtra(Intent.EXTRA_SUBJECT, \"PhoneProfilesPlus\" + packageVersion + \" - \" + getString(R.string.email_debug_log_files_subject));\n emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);\n\n List resolveInfo = getPackageManager().queryIntentActivities(emailIntent, 0);\n List intents = new ArrayList<>();\n for (ResolveInfo info : resolveInfo) {\n intent = new Intent(Intent.ACTION_SEND_MULTIPLE);\n intent.setComponent(new ComponentName(info.activityInfo.packageName, info.activityInfo.name));\n intent.putExtra(Intent.EXTRA_EMAIL, new String[]{emailAddress});\n intent.putExtra(Intent.EXTRA_SUBJECT, \"PhoneProfilesPlus\" + packageVersion + \" - \" + getString(R.string.email_debug_log_files_subject));\n intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);\n intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris); //ArrayList of attachment Uri's\n intents.add(new LabeledIntent(intent, info.activityInfo.packageName, info.loadLabel(getPackageManager()), info.icon));\n }\n try {\n Intent chooser = Intent.createChooser(intents.remove(intents.size() - 1), getString(R.string.email_chooser));\n //noinspection ToArrayCallWithZeroLengthArrayArgument\n chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents.toArray(new LabeledIntent[intents.size()]));\n startActivity(chooser);\n } catch (Exception ignored) {}\n }\n else {\n // toast notification\n Toast msg = ToastCompat.makeText(getApplicationContext(), getString(R.string.toast_debug_log_files_not_exists),\n Toast.LENGTH_SHORT);\n msg.show();\n }\n\n return true;\n case R.id.menu_about:\n intent = new Intent(getBaseContext(), AboutApplicationActivity.class);\n startActivity(intent);\n return true;\n case R.id.menu_exit:\n AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);\n dialogBuilder.setTitle(R.string.exit_application_alert_title);\n dialogBuilder.setMessage(R.string.exit_application_alert_message);\n //dialogBuilder.setIcon(android.R.drawable.ic_dialog_alert);\n dialogBuilder.setPositiveButton(R.string.alert_button_yes, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int which) {\n PPApplication.logE(\"PPApplication.exitApp\", \"from EditorProfileActivity.onOptionsItemSelected shutdown=false\");\n\n IgnoreBatteryOptimizationNotification.setShowIgnoreBatteryOptimizationNotificationOnStart(getApplicationContext(), true);\n SharedPreferences settings = ApplicationPreferences.getSharedPreferences(getApplicationContext());\n SharedPreferences.Editor editor = settings.edit();\n editor.putBoolean(ApplicationPreferences.PREF_APPLICATION_EVENT_NEVER_ASK_FOR_ENABLE_RUN, false);\n editor.putBoolean(ApplicationPreferences.PREF_APPLICATION_NEVER_ASK_FOR_GRANT_ROOT, false);\n editor.apply();\n\n PPApplication.exitApp(true, getApplicationContext(), EditorProfilesActivity.this.getDataWrapper(),\n EditorProfilesActivity.this, false/*, true, true*/);\n }\n });\n dialogBuilder.setNegativeButton(R.string.alert_button_no, null);\n AlertDialog dialog = dialogBuilder.create();\n /*dialog.setOnShowListener(new DialogInterface.OnShowListener() {\n @Override\n public void onShow(DialogInterface dialog) {\n Button positive = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_POSITIVE);\n if (positive != null) positive.setAllCaps(false);\n Button negative = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_NEGATIVE);\n if (negative != null) negative.setAllCaps(false);\n }\n });*/\n if (!isFinishing())\n dialog.show();\n return true;\n case R.id.menu_test_crash:\n //TODO throw new RuntimeException(\"test Crashlytics + TopExceptionHandler\");\n Crashlytics.getInstance().crash();\n return true;\n default:\n return super.onOptionsItemSelected(item);\n }\n }\n\n /*\n // fix for bug in LG stock ROM Android <= 4.1\n // https://code.google.com/p/android/issues/detail?id=78154\n @Override\n public boolean onKeyDown(int keyCode, KeyEvent event) {\n String manufacturer = PPApplication.getROMManufacturer();\n if ((keyCode == KeyEvent.KEYCODE_MENU) &&\n (Build.VERSION.SDK_INT <= 16) &&\n (manufacturer != null) && (manufacturer.compareTo(\"lge\") == 0)) {\n return true;\n }\n return super.onKeyDown(keyCode, event);\n }\n\n @Override\n public boolean onKeyUp(int keyCode, KeyEvent event) {\n String manufacturer = PPApplication.getROMManufacturer();\n if ((keyCode == KeyEvent.KEYCODE_MENU) &&\n (Build.VERSION.SDK_INT <= 16) &&\n (manufacturer != null) && (manufacturer.compareTo(\"lge\") == 0)) {\n openOptionsMenu();\n return true;\n }\n return super.onKeyUp(keyCode, event);\n }\n */\n\n /////\n\n /*\n // ListView click listener in the navigation drawer\n private class DrawerItemClickListener implements\n ListView.OnItemClickListener {\n\n public void onItemClick(AdapterView parent, View view, int position, long id) {\n // header is position=0\n if (position > 0)\n selectFilterItem(position, true, false, true);\n }\n }\n */\n\n private void selectFilterItem(int selectedView, int position, boolean fromClickListener, boolean startTargetHelps) {\n if (PPApplication.logEnabled()) {\n PPApplication.logE(\"EditorProfilesActivity.selectFilterItem\", \"editorSelectedView=\" + editorSelectedView);\n PPApplication.logE(\"EditorProfilesActivity.selectFilterItem\", \"selectedView=\" + selectedView);\n PPApplication.logE(\"EditorProfilesActivity.selectFilterItem\", \"position=\" + position);\n }\n\n boolean viewChanged = false;\n Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.editor_list_container);\n if (fragment instanceof EditorProfileListFragment) {\n if (selectedView != 0)\n viewChanged = true;\n } else\n if (fragment instanceof EditorEventListFragment) {\n if (selectedView != 1)\n viewChanged = true;\n }\n else\n viewChanged = true;\n\n int filterSelectedItem;\n if (selectedView == 0) {\n PPApplication.logE(\"EditorProfilesActivity.selectFilterItem\", \"filterProfilesSelectedItem=\" + filterProfilesSelectedItem);\n filterSelectedItem = filterProfilesSelectedItem;\n }\n else {\n PPApplication.logE(\"EditorProfilesActivity.selectFilterItem\", \"filterEventsSelectedItem=\" + filterEventsSelectedItem);\n filterSelectedItem = filterEventsSelectedItem;\n }\n\n if (viewChanged || (position != filterSelectedItem))\n {\n if (viewChanged) {\n // stop running AsyncTask\n if (fragment instanceof EditorProfileListFragment) {\n if (((EditorProfileListFragment) fragment).isAsyncTaskPendingOrRunning()) {\n ((EditorProfileListFragment) fragment).stopRunningAsyncTask();\n }\n } else if (fragment instanceof EditorEventListFragment) {\n if (((EditorEventListFragment) fragment).isAsyncTaskPendingOrRunning()) {\n ((EditorEventListFragment) fragment).stopRunningAsyncTask();\n }\n }\n }\n\n editorSelectedView = selectedView;\n if (editorSelectedView == 0) {\n filterProfilesSelectedItem = position;\n filterSelectedItem = position;\n PPApplication.logE(\"EditorProfilesActivity.selectFilterItem\", \"filterProfilesSelectedItem=\" + filterProfilesSelectedItem);\n }\n else {\n filterEventsSelectedItem = position;\n filterSelectedItem = position;\n PPApplication.logE(\"EditorProfilesActivity.selectFilterItem\", \"filterEventsSelectedItem=\" + filterEventsSelectedItem);\n }\n\n // save into shared preferences\n ApplicationPreferences.getSharedPreferences(this);\n Editor editor = ApplicationPreferences.preferences.edit();\n editor.putInt(SP_EDITOR_SELECTED_VIEW, editorSelectedView);\n editor.putInt(SP_EDITOR_PROFILES_VIEW_SELECTED_ITEM, filterProfilesSelectedItem);\n editor.putInt(SP_EDITOR_EVENTS_VIEW_SELECTED_ITEM, filterEventsSelectedItem);\n editor.apply();\n\n Bundle arguments;\n\n int profilesFilterType;\n int eventsFilterType;\n //int eventsOrderType = getEventsOrderType();\n\n switch (editorSelectedView) {\n case 0:\n switch (filterProfilesSelectedItem) {\n case DSI_PROFILES_ALL:\n profilesFilterType = EditorProfileListFragment.FILTER_TYPE_ALL;\n PPApplication.logE(\"EditorProfilesActivity.selectFilterItem\", \"profilesFilterType=FILTER_TYPE_ALL\");\n if (viewChanged) {\n fragment = new EditorProfileListFragment();\n arguments = new Bundle();\n arguments.putInt(EditorProfileListFragment.FILTER_TYPE_ARGUMENT, profilesFilterType);\n arguments.putBoolean(EditorProfileListFragment.START_TARGET_HELPS_ARGUMENT, startTargetHelps);\n fragment.setArguments(arguments);\n getSupportFragmentManager().beginTransaction()\n .replace(R.id.editor_list_container, fragment, \"EditorProfileListFragment\")\n .commitAllowingStateLoss();\n }\n else {\n //noinspection ConstantConditions\n EditorProfileListFragment displayedFragment = (EditorProfileListFragment)fragment;\n displayedFragment.changeFragmentFilter(profilesFilterType, startTargetHelps);\n }\n break;\n case DSI_PROFILES_SHOW_IN_ACTIVATOR:\n profilesFilterType = EditorProfileListFragment.FILTER_TYPE_SHOW_IN_ACTIVATOR;\n PPApplication.logE(\"EditorProfilesActivity.selectFilterItem\", \"profilesFilterType=FILTER_TYPE_SHOW_IN_ACTIVATOR\");\n if (viewChanged) {\n fragment = new EditorProfileListFragment();\n arguments = new Bundle();\n arguments.putInt(EditorProfileListFragment.FILTER_TYPE_ARGUMENT, profilesFilterType);\n arguments.putBoolean(EditorProfileListFragment.START_TARGET_HELPS_ARGUMENT, startTargetHelps);\n fragment.setArguments(arguments);\n getSupportFragmentManager().beginTransaction()\n .replace(R.id.editor_list_container, fragment, \"EditorProfileListFragment\")\n .commitAllowingStateLoss();\n }\n else {\n //noinspection ConstantConditions\n EditorProfileListFragment displayedFragment = (EditorProfileListFragment)fragment;\n displayedFragment.changeFragmentFilter(profilesFilterType, startTargetHelps);\n }\n break;\n case DSI_PROFILES_NO_SHOW_IN_ACTIVATOR:\n profilesFilterType = EditorProfileListFragment.FILTER_TYPE_NO_SHOW_IN_ACTIVATOR;\n PPApplication.logE(\"EditorProfilesActivity.selectFilterItem\", \"profilesFilterType=FILTER_TYPE_NO_SHOW_IN_ACTIVATOR\");\n if (viewChanged) {\n fragment = new EditorProfileListFragment();\n arguments = new Bundle();\n arguments.putInt(EditorProfileListFragment.FILTER_TYPE_ARGUMENT, profilesFilterType);\n arguments.putBoolean(EditorProfileListFragment.START_TARGET_HELPS_ARGUMENT, startTargetHelps);\n fragment.setArguments(arguments);\n getSupportFragmentManager().beginTransaction()\n .replace(R.id.editor_list_container, fragment, \"EditorProfileListFragment\")\n .commitAllowingStateLoss();\n }\n else {\n //noinspection ConstantConditions\n EditorProfileListFragment displayedFragment = (EditorProfileListFragment)fragment;\n displayedFragment.changeFragmentFilter(profilesFilterType, startTargetHelps);\n }\n break;\n }\n break;\n case 1:\n switch (filterEventsSelectedItem) {\n case DSI_EVENTS_START_ORDER:\n eventsFilterType = EditorEventListFragment.FILTER_TYPE_START_ORDER;\n PPApplication.logE(\"EditorProfilesActivity.selectFilterItem\", \"eventsFilterType=FILTER_TYPE_START_ORDER\");\n if (viewChanged) {\n fragment = new EditorEventListFragment();\n arguments = new Bundle();\n arguments.putInt(EditorEventListFragment.FILTER_TYPE_ARGUMENT, eventsFilterType);\n arguments.putBoolean(EditorEventListFragment.START_TARGET_HELPS_ARGUMENT, startTargetHelps);\n fragment.setArguments(arguments);\n getSupportFragmentManager().beginTransaction()\n .replace(R.id.editor_list_container, fragment, \"EditorEventListFragment\")\n .commitAllowingStateLoss();\n }\n else {\n //noinspection ConstantConditions\n EditorEventListFragment displayedFragment = (EditorEventListFragment)fragment;\n displayedFragment.changeFragmentFilter(eventsFilterType, startTargetHelps);\n }\n break;\n case DSI_EVENTS_ALL:\n eventsFilterType = EditorEventListFragment.FILTER_TYPE_ALL;\n PPApplication.logE(\"EditorProfilesActivity.selectFilterItem\", \"eventsFilterType=FILTER_TYPE_ALL\");\n if (viewChanged) {\n fragment = new EditorEventListFragment();\n arguments = new Bundle();\n arguments.putInt(EditorEventListFragment.FILTER_TYPE_ARGUMENT, eventsFilterType);\n arguments.putBoolean(EditorEventListFragment.START_TARGET_HELPS_ARGUMENT, startTargetHelps);\n fragment.setArguments(arguments);\n getSupportFragmentManager().beginTransaction()\n .replace(R.id.editor_list_container, fragment, \"EditorEventListFragment\")\n .commitAllowingStateLoss();\n }\n else {\n //noinspection ConstantConditions\n EditorEventListFragment displayedFragment = (EditorEventListFragment)fragment;\n displayedFragment.changeFragmentFilter(eventsFilterType, startTargetHelps);\n }\n break;\n case DSI_EVENTS_NOT_STOPPED:\n eventsFilterType = EditorEventListFragment.FILTER_TYPE_NOT_STOPPED;\n PPApplication.logE(\"EditorProfilesActivity.selectFilterItem\", \"eventsFilterType=FILTER_TYPE_NOT_STOPPED\");\n if (viewChanged) {\n fragment = new EditorEventListFragment();\n arguments = new Bundle();\n arguments.putInt(EditorEventListFragment.FILTER_TYPE_ARGUMENT, eventsFilterType);\n arguments.putBoolean(EditorEventListFragment.START_TARGET_HELPS_ARGUMENT, startTargetHelps);\n fragment.setArguments(arguments);\n getSupportFragmentManager().beginTransaction()\n .replace(R.id.editor_list_container, fragment, \"EditorEventListFragment\")\n .commitAllowingStateLoss();\n }\n else {\n //noinspection ConstantConditions\n EditorEventListFragment displayedFragment = (EditorEventListFragment)fragment;\n displayedFragment.changeFragmentFilter(eventsFilterType, startTargetHelps);\n }\n break;\n case DSI_EVENTS_RUNNING:\n eventsFilterType = EditorEventListFragment.FILTER_TYPE_RUNNING;\n PPApplication.logE(\"EditorProfilesActivity.selectFilterItem\", \"eventsFilterType=FILTER_TYPE_RUNNING\");\n if (viewChanged) {\n fragment = new EditorEventListFragment();\n arguments = new Bundle();\n arguments.putInt(EditorEventListFragment.FILTER_TYPE_ARGUMENT, eventsFilterType);\n arguments.putBoolean(EditorEventListFragment.START_TARGET_HELPS_ARGUMENT, startTargetHelps);\n fragment.setArguments(arguments);\n getSupportFragmentManager().beginTransaction()\n .replace(R.id.editor_list_container, fragment, \"EditorEventListFragment\")\n .commitAllowingStateLoss();\n }\n else {\n //noinspection ConstantConditions\n EditorEventListFragment displayedFragment = (EditorEventListFragment)fragment;\n displayedFragment.changeFragmentFilter(eventsFilterType, startTargetHelps);\n }\n break;\n case DSI_EVENTS_PAUSED:\n eventsFilterType = EditorEventListFragment.FILTER_TYPE_PAUSED;\n PPApplication.logE(\"EditorProfilesActivity.selectFilterItem\", \"eventsFilterType=FILTER_TYPE_PAUSED\");\n if (viewChanged) {\n fragment = new EditorEventListFragment();\n arguments = new Bundle();\n arguments.putInt(EditorEventListFragment.FILTER_TYPE_ARGUMENT, eventsFilterType);\n arguments.putBoolean(EditorEventListFragment.START_TARGET_HELPS_ARGUMENT, startTargetHelps);\n fragment.setArguments(arguments);\n getSupportFragmentManager().beginTransaction()\n .replace(R.id.editor_list_container, fragment, \"EditorEventListFragment\")\n .commitAllowingStateLoss();\n }\n else {\n //noinspection ConstantConditions\n EditorEventListFragment displayedFragment = (EditorEventListFragment)fragment;\n displayedFragment.changeFragmentFilter(eventsFilterType, startTargetHelps);\n }\n break;\n case DSI_EVENTS_STOPPED:\n eventsFilterType = EditorEventListFragment.FILTER_TYPE_STOPPED;\n PPApplication.logE(\"EditorProfilesActivity.selectFilterItem\", \"eventsFilterType=FILTER_TYPE_STOPPED\");\n if (viewChanged) {\n fragment = new EditorEventListFragment();\n arguments = new Bundle();\n arguments.putInt(EditorEventListFragment.FILTER_TYPE_ARGUMENT, eventsFilterType);\n arguments.putBoolean(EditorEventListFragment.START_TARGET_HELPS_ARGUMENT, startTargetHelps);\n fragment.setArguments(arguments);\n getSupportFragmentManager().beginTransaction()\n .replace(R.id.editor_list_container, fragment, \"EditorEventListFragment\")\n .commitAllowingStateLoss();\n }\n else {\n //noinspection ConstantConditions\n EditorEventListFragment displayedFragment = (EditorEventListFragment)fragment;\n displayedFragment.changeFragmentFilter(eventsFilterType, startTargetHelps);\n }\n break;\n }\n break;\n }\n }\n\n /*\n // header is position=0\n drawerListView.setItemChecked(drawerSelectedItem, true);\n // Get the title and icon followed by the position\n //editorToolbar.setSubtitle(drawerItemsTitle[drawerSelectedItem - 1]);\n //setIcon(drawerItemsIcon[drawerSelectedItem-1]);\n drawerHeaderFilterImage.setImageResource(drawerItemsIcon[drawerSelectedItem -1]);\n drawerHeaderFilterTitle.setText(drawerItemsTitle[drawerSelectedItem - 1]);\n */\n if (!fromClickListener)\n filterSpinner.setSelection(filterSelectedItem);\n\n //bottomToolbar.setVisibility(View.VISIBLE);\n\n // set filter status bar title\n //setStatusBarTitle();\n \n }\n\n @Override\n public void onActivityResult(int requestCode, int resultCode, Intent data)\n {\n super.onActivityResult(requestCode, resultCode, data);\n\n if (requestCode == REQUEST_CODE_ACTIVATE_PROFILE)\n {\n Fragment _fragment = getSupportFragmentManager().findFragmentById(R.id.editor_list_container);\n if (_fragment instanceof EditorProfileListFragment) {\n EditorProfileListFragment fragment = (EditorProfileListFragment) getSupportFragmentManager().findFragmentById(R.id.editor_list_container);\n if (fragment != null)\n fragment.doOnActivityResult(requestCode, resultCode, data);\n }\n }\n else\n if (requestCode == REQUEST_CODE_PROFILE_PREFERENCES)\n {\n if ((resultCode == RESULT_OK) && (data != null))\n {\n long profile_id = data.getLongExtra(PPApplication.EXTRA_PROFILE_ID, 0);\n int newProfileMode = data.getIntExtra(EXTRA_NEW_PROFILE_MODE, EditorProfileListFragment.EDIT_MODE_UNDEFINED);\n //int predefinedProfileIndex = data.getIntExtra(EXTRA_PREDEFINED_PROFILE_INDEX, 0);\n\n if (profile_id > 0)\n {\n Profile profile = DatabaseHandler.getInstance(getApplicationContext()).getProfile(profile_id, false);\n if (profile != null) {\n // generate bitmaps\n profile.generateIconBitmap(getBaseContext(), false, 0, false);\n profile.generatePreferencesIndicator(getBaseContext(), false, 0);\n\n // redraw list fragment , notifications, widgets after finish ProfilesPrefsActivity\n redrawProfileListFragment(profile, newProfileMode);\n\n //Profile mappedProfile = profile; //Profile.getMappedProfile(profile, getApplicationContext());\n //Permissions.grantProfilePermissions(getApplicationContext(), profile, false, true,\n // /*true, false, 0,*/ PPApplication.STARTUP_SOURCE_EDITOR, false, true, false);\n EditorProfilesActivity.displayRedTextToPreferencesNotification(profile, null, getApplicationContext());\n }\n }\n\n /*Intent serviceIntent = new Intent(getApplicationContext(), PhoneProfilesService.class);\n serviceIntent.putExtra(PhoneProfilesService.EXTRA_ONLY_START, false);\n serviceIntent.putExtra(PhoneProfilesService.EXTRA_REREGISTER_RECEIVERS_AND_WORKERS, true);\n PPApplication.startPPService(this, serviceIntent);*/\n Intent commandIntent = new Intent(PhoneProfilesService.ACTION_COMMAND);\n //commandIntent.putExtra(PhoneProfilesService.EXTRA_ONLY_START, false);\n commandIntent.putExtra(PhoneProfilesService.EXTRA_REREGISTER_RECEIVERS_AND_WORKERS, true);\n PPApplication.runCommand(this, commandIntent);\n }\n else\n if (data != null) {\n boolean restart = data.getBooleanExtra(PhoneProfilesPrefsActivity.EXTRA_RESET_EDITOR, false);\n if (restart) {\n // refresh activity for special changes\n GlobalGUIRoutines.reloadActivity(this, true);\n }\n }\n }\n else\n if (requestCode == REQUEST_CODE_EVENT_PREFERENCES)\n {\n if ((resultCode == RESULT_OK) && (data != null))\n {\n // redraw list fragment after finish EventPreferencesActivity\n long event_id = data.getLongExtra(PPApplication.EXTRA_EVENT_ID, 0L);\n int newEventMode = data.getIntExtra(EXTRA_NEW_EVENT_MODE, EditorEventListFragment.EDIT_MODE_UNDEFINED);\n //int predefinedEventIndex = data.getIntExtra(EXTRA_PREDEFINED_EVENT_INDEX, 0);\n\n if (event_id > 0)\n {\n Event event = DatabaseHandler.getInstance(getApplicationContext()).getEvent(event_id);\n\n // redraw list fragment , notifications, widgets after finish EventPreferencesActivity\n redrawEventListFragment(event, newEventMode);\n\n //Permissions.grantEventPermissions(getApplicationContext(), event, true, false);\n EditorProfilesActivity.displayRedTextToPreferencesNotification(null, event, getApplicationContext());\n }\n\n /*Intent serviceIntent = new Intent(getApplicationContext(), PhoneProfilesService.class);\n serviceIntent.putExtra(PhoneProfilesService.EXTRA_ONLY_START, false);\n serviceIntent.putExtra(PhoneProfilesService.EXTRA_REREGISTER_RECEIVERS_AND_WORKERS, true);\n PPApplication.startPPService(this, serviceIntent);*/\n Intent commandIntent = new Intent(PhoneProfilesService.ACTION_COMMAND);\n //commandIntent.putExtra(PhoneProfilesService.EXTRA_ONLY_START, false);\n commandIntent.putExtra(PhoneProfilesService.EXTRA_REREGISTER_RECEIVERS_AND_WORKERS, true);\n PPApplication.runCommand(this, commandIntent);\n\n IgnoreBatteryOptimizationNotification.showNotification(getApplicationContext());\n }\n else\n if (data != null) {\n boolean restart = data.getBooleanExtra(PhoneProfilesPrefsActivity.EXTRA_RESET_EDITOR, false);\n if (restart) {\n // refresh activity for special changes\n GlobalGUIRoutines.reloadActivity(this, true);\n }\n }\n }\n else\n if (requestCode == REQUEST_CODE_APPLICATION_PREFERENCES)\n {\n if (resultCode == RESULT_OK)\n {\n// Intent serviceIntent = new Intent(getApplicationContext(), PhoneProfilesService.class);\n// serviceIntent.putExtra(PhoneProfilesService.EXTRA_ONLY_START, false);\n// serviceIntent.putExtra(PhoneProfilesService.EXTRA_REREGISTER_RECEIVERS_AND_WORKERS, true);\n// PPApplication.startPPService(this, serviceIntent);\n// Intent commandIntent = new Intent(PhoneProfilesService.ACTION_COMMAND);\n// //commandIntent.putExtra(PhoneProfilesService.EXTRA_ONLY_START, false);\n// commandIntent.putExtra(PhoneProfilesService.EXTRA_REREGISTER_RECEIVERS_AND_WORKERS, true);\n// PPApplication.runCommand(this, commandIntent);\n\n// if (PhoneProfilesService.getInstance() != null) {\n//\n// boolean powerSaveMode = PPApplication.isPowerSaveMode;\n// if ((PhoneProfilesService.isGeofenceScannerStarted())) {\n// PhoneProfilesService.getGeofencesScanner().resetLocationUpdates(powerSaveMode, true);\n// }\n// PhoneProfilesService.getInstance().resetListeningOrientationSensors(powerSaveMode, true);\n// if (PhoneProfilesService.isPhoneStateScannerStarted())\n// PhoneProfilesService.phoneStateScanner.resetListening(powerSaveMode, true);\n//\n// }\n\n boolean restart = data.getBooleanExtra(PhoneProfilesPrefsActivity.EXTRA_RESET_EDITOR, false);\n PPApplication.logE(\"EditorProfilesActivity.onActivityResult\", \"restart=\"+restart);\n\n if (restart)\n {\n // refresh activity for special changes\n GlobalGUIRoutines.reloadActivity(this, true);\n }\n }\n }\n else\n if (requestCode == REQUEST_CODE_REMOTE_EXPORT)\n {\n if (resultCode == RESULT_OK)\n {\n doImportData(GlobalGUIRoutines.REMOTE_EXPORT_PATH);\n }\n }\n /*else\n if (requestCode == Permissions.REQUEST_CODE + Permissions.GRANT_TYPE_PROFILE) {\n if (data != null) {\n long profileId = data.getLongExtra(PPApplication.EXTRA_PROFILE_ID, 0);\n int startupSource = data.getIntExtra(PPApplication.EXTRA_STARTUP_SOURCE, 0);\n boolean mergedProfile = data.getBooleanExtra(Permissions.EXTRA_MERGED_PROFILE, false);\n boolean activateProfile = data.getBooleanExtra(Permissions.EXTRA_ACTIVATE_PROFILE, false);\n\n if (activateProfile && (getDataWrapper() != null)) {\n Profile profile = getDataWrapper().getProfileById(profileId, false, false, mergedProfile);\n getDataWrapper().activateProfileFromMainThread(profile, mergedProfile, startupSource, this);\n }\n }\n }*/\n else\n if (requestCode == Permissions.REQUEST_CODE + Permissions.GRANT_TYPE_EXPORT) {\n if (resultCode == RESULT_OK) {\n doExportData(false, false);\n }\n }\n else\n if (requestCode == Permissions.REQUEST_CODE + Permissions.GRANT_TYPE_EXPORT_AND_EMAIL) {\n if (resultCode == RESULT_OK) {\n doExportData(true, false);\n }\n }\n else\n if (requestCode == Permissions.REQUEST_CODE + Permissions.GRANT_TYPE_IMPORT) {\n if ((resultCode == RESULT_OK) && (data != null)) {\n doImportData(data.getStringExtra(Permissions.EXTRA_APPLICATION_DATA_PATH));\n }\n }\n else\n if (requestCode == Permissions.REQUEST_CODE + Permissions.GRANT_TYPE_EXPORT_AND_EMAIL_TO_AUTHOR) {\n if (resultCode == RESULT_OK) {\n doExportData(true, true);\n }\n }\n }\n\n /*\n @Override\n public void onBackPressed()\n {\n if (drawerLayout.isDrawerOpen(drawerRoot))\n drawerLayout.closeDrawer(drawerRoot);\n else\n super.onBackPressed();\n }\n */\n\n /*\n @Override\n public void openOptionsMenu() {\n Configuration config = getResources().getConfiguration();\n if ((config.screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) > Configuration.SCREENLAYOUT_SIZE_LARGE) {\n int originalScreenLayout = config.screenLayout;\n config.screenLayout = Configuration.SCREENLAYOUT_SIZE_LARGE;\n super.openOptionsMenu();\n config.screenLayout = originalScreenLayout;\n } else {\n super.openOptionsMenu();\n }\n }\n */\n\n private void importExportErrorDialog(int importExport, int dbResult, int appSettingsResult, int sharedProfileResult)\n {\n AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);\n String title;\n if (importExport == 1)\n title = getString(R.string.import_profiles_alert_title);\n else\n title = getString(R.string.export_profiles_alert_title);\n dialogBuilder.setTitle(title);\n String message;\n if (importExport == 1) {\n message = getString(R.string.import_profiles_alert_error) + \":\";\n if (dbResult != DatabaseHandler.IMPORT_OK) {\n if (dbResult == DatabaseHandler.IMPORT_ERROR_NEVER_VERSION)\n message = message + \"\\n• \" + getString(R.string.import_profiles_alert_error_database_newer_version);\n else\n message = message + \"\\n• \" + getString(R.string.import_profiles_alert_error_database_bug);\n }\n if (appSettingsResult == 0)\n message = message + \"\\n• \" + getString(R.string.import_profiles_alert_error_appSettings_bug);\n if (sharedProfileResult == 0)\n message = message + \"\\n• \" + getString(R.string.import_profiles_alert_error_sharedProfile_bug);\n }\n else\n message = getString(R.string.export_profiles_alert_error);\n dialogBuilder.setMessage(message);\n //dialogBuilder.setIcon(android.R.drawable.ic_dialog_alert);\n dialogBuilder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int which) {\n // refresh activity\n GlobalGUIRoutines.reloadActivity(EditorProfilesActivity.this, true);\n }\n });\n dialogBuilder.setOnCancelListener(new DialogInterface.OnCancelListener() {\n @Override\n public void onCancel(DialogInterface dialog) {\n // refresh activity\n GlobalGUIRoutines.reloadActivity(EditorProfilesActivity.this, true);\n }\n });\n AlertDialog dialog = dialogBuilder.create();\n /*dialog.setOnShowListener(new DialogInterface.OnShowListener() {\n @Override\n public void onShow(DialogInterface dialog) {\n Button positive = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_POSITIVE);\n if (positive != null) positive.setAllCaps(false);\n Button negative = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_NEGATIVE);\n if (negative != null) negative.setAllCaps(false);\n }\n });*/\n if (!isFinishing())\n dialog.show();\n }\n\n @SuppressWarnings(\"BooleanMethodIsAlwaysInverted\")\n private boolean importApplicationPreferences(File src, int what) {\n boolean res = true;\n ObjectInputStream input = null;\n try {\n try {\n input = new ObjectInputStream(new FileInputStream(src));\n Editor prefEdit;\n if (what == 1)\n prefEdit = getSharedPreferences(PPApplication.APPLICATION_PREFS_NAME, Activity.MODE_PRIVATE).edit();\n else\n prefEdit = getSharedPreferences(\"profile_preferences_default_profile\", Activity.MODE_PRIVATE).edit();\n prefEdit.clear();\n //noinspection unchecked\n Map entries = (Map) input.readObject();\n for (Entry entry : entries.entrySet()) {\n Object v = entry.getValue();\n String key = entry.getKey();\n\n if (v instanceof Boolean)\n prefEdit.putBoolean(key, (Boolean) v);\n else if (v instanceof Float)\n prefEdit.putFloat(key, (Float) v);\n else if (v instanceof Integer)\n prefEdit.putInt(key, (Integer) v);\n else if (v instanceof Long)\n prefEdit.putLong(key, (Long) v);\n else if (v instanceof String)\n prefEdit.putString(key, ((String) v));\n\n if (what == 1)\n {\n if (key.equals(ApplicationPreferences.PREF_APPLICATION_THEME))\n {\n if (v.equals(\"light\") || v.equals(\"material\") || v.equals(\"color\") || v.equals(\"dlight\")) {\n String defaultValue = \"white\";\n if (Build.VERSION.SDK_INT >= 28)\n defaultValue = \"night_mode\";\n prefEdit.putString(key, defaultValue);\n }\n }\n if (key.equals(ActivateProfileHelper.PREF_MERGED_RING_NOTIFICATION_VOLUMES))\n ActivateProfileHelper.setMergedRingNotificationVolumes(getApplicationContext(), true, prefEdit);\n if (key.equals(ApplicationPreferences.PREF_APPLICATION_FIRST_START))\n prefEdit.putBoolean(ApplicationPreferences.PREF_APPLICATION_FIRST_START, false);\n }\n\n /*if (what == 2) {\n if (key.equals(Profile.PREF_PROFILE_LOCK_DEVICE)) {\n if (v.equals(\"3\"))\n prefEdit.putString(Profile.PREF_PROFILE_LOCK_DEVICE, \"1\");\n }\n }*/\n }\n prefEdit.apply();\n if (what == 1) {\n // save version code\n try {\n Context appContext = getApplicationContext();\n PackageInfo pInfo = appContext.getPackageManager().getPackageInfo(appContext.getPackageName(), 0);\n int actualVersionCode = PPApplication.getVersionCode(pInfo);\n PPApplication.setSavedVersionCode(appContext, actualVersionCode);\n } catch (Exception ignored) {\n }\n }\n }/* catch (FileNotFoundException ignored) {\n // no error, this is OK\n }*/ catch (Exception e) {\n Log.e(\"EditorProfilesActivity.importApplicationPreferences\", Log.getStackTraceString(e));\n res = false;\n }\n }finally {\n try {\n if (input != null) {\n input.close();\n }\n } catch (IOException ignored) {\n }\n\n WifiScanWorker.setScanRequest(getApplicationContext(), false);\n WifiScanWorker.setWaitForResults(getApplicationContext(), false);\n WifiScanWorker.setWifiEnabledForScan(getApplicationContext(), false);\n\n BluetoothScanWorker.setScanRequest(getApplicationContext(), false);\n BluetoothScanWorker.setLEScanRequest(getApplicationContext(), false);\n BluetoothScanWorker.setWaitForResults(getApplicationContext(), false);\n BluetoothScanWorker.setWaitForLEResults(getApplicationContext(), false);\n BluetoothScanWorker.setBluetoothEnabledForScan(getApplicationContext(), false);\n BluetoothScanWorker.setScanKilled(getApplicationContext(), false);\n\n }\n return res;\n }\n\n private void doImportData(String applicationDataPath)\n {\n final EditorProfilesActivity activity = this;\n final String _applicationDataPath = applicationDataPath;\n\n if (Permissions.grantImportPermissions(activity.getApplicationContext(), activity, applicationDataPath)) {\n\n @SuppressLint(\"StaticFieldLeak\")\n class ImportAsyncTask extends AsyncTask {\n private final DataWrapper dataWrapper;\n private int dbError = DatabaseHandler.IMPORT_OK;\n private boolean appSettingsError = false;\n private boolean sharedProfileError = false;\n\n private ImportAsyncTask() {\n AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(activity);\n dialogBuilder.setMessage(R.string.import_profiles_alert_title);\n\n LayoutInflater inflater = (activity.getLayoutInflater());\n @SuppressLint(\"InflateParams\")\n View layout = inflater.inflate(R.layout.activity_progress_bar_dialog, null);\n dialogBuilder.setView(layout);\n\n importProgressDialog = dialogBuilder.create();\n\n this.dataWrapper = getDataWrapper();\n }\n\n @Override\n protected void onPreExecute() {\n super.onPreExecute();\n\n doImport = true;\n\n GlobalGUIRoutines.lockScreenOrientation(activity);\n importProgressDialog.setCancelable(false);\n importProgressDialog.setCanceledOnTouchOutside(false);\n if (!activity.isFinishing())\n importProgressDialog.show();\n\n Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.editor_list_container);\n if (fragment != null) {\n if (fragment instanceof EditorProfileListFragment)\n ((EditorProfileListFragment) fragment).removeAdapter();\n else\n ((EditorEventListFragment) fragment).removeAdapter();\n }\n }\n\n @Override\n protected Integer doInBackground(Void... params) {\n PPApplication.logE(\"PPApplication.exitApp\", \"from EditorProfilesActivity.doImportData shutdown=false\");\n if (dataWrapper != null) {\n PPApplication.exitApp(false, dataWrapper.context, dataWrapper, null, false/*, false, true*/);\n\n File sd = Environment.getExternalStorageDirectory();\n File exportFile = new File(sd, _applicationDataPath + \"/\" + GlobalGUIRoutines.EXPORT_APP_PREF_FILENAME);\n appSettingsError = !importApplicationPreferences(exportFile, 1);\n exportFile = new File(sd, _applicationDataPath + \"/\" + GlobalGUIRoutines.EXPORT_DEF_PROFILE_PREF_FILENAME);\n if (exportFile.exists())\n sharedProfileError = !importApplicationPreferences(exportFile, 2);\n\n dbError = DatabaseHandler.getInstance(this.dataWrapper.context).importDB(_applicationDataPath);\n if (dbError == DatabaseHandler.IMPORT_OK) {\n DatabaseHandler.getInstance(this.dataWrapper.context).updateAllEventsStatus(Event.ESTATUS_RUNNING, Event.ESTATUS_PAUSE);\n DatabaseHandler.getInstance(this.dataWrapper.context).updateAllEventsSensorsPassed(EventPreferences.SENSOR_PASSED_WAITING);\n DatabaseHandler.getInstance(this.dataWrapper.context).deactivateProfile();\n DatabaseHandler.getInstance(this.dataWrapper.context).unblockAllEvents();\n DatabaseHandler.getInstance(this.dataWrapper.context).disableNotAllowedPreferences();\n //this.dataWrapper.invalidateProfileList();\n //this.dataWrapper.invalidateEventList();\n //this.dataWrapper.invalidateEventTimelineList();\n Event.setEventsBlocked(getApplicationContext(), false);\n DatabaseHandler.getInstance(this.dataWrapper.context).unblockAllEvents();\n Event.setForceRunEventRunning(getApplicationContext(), false);\n }\n\n if (PPApplication.logEnabled()) {\n PPApplication.logE(\"EditorProfilesActivity.doImportData\", \"dbError=\" + dbError);\n PPApplication.logE(\"EditorProfilesActivity.doImportData\", \"appSettingsError=\" + appSettingsError);\n PPApplication.logE(\"EditorProfilesActivity.doImportData\", \"sharedProfileError=\" + sharedProfileError);\n }\n\n if (!appSettingsError) {\n ApplicationPreferences.getSharedPreferences(dataWrapper.context);\n /*Editor editor = ApplicationPreferences.preferences.edit();\n editor.putInt(SP_EDITOR_PROFILES_VIEW_SELECTED_ITEM, 0);\n editor.putInt(SP_EDITOR_EVENTS_VIEW_SELECTED_ITEM, 0);\n editor.putInt(EditorEventListFragment.SP_EDITOR_ORDER_SELECTED_ITEM, 0);\n editor.apply();*/\n\n Permissions.setAllShowRequestPermissions(getApplicationContext(), true);\n\n //WifiBluetoothScanner.setShowEnableLocationNotification(getApplicationContext(), true, WifiBluetoothScanner.SCANNER_TYPE_WIFI);\n //WifiBluetoothScanner.setShowEnableLocationNotification(getApplicationContext(), true, WifiBluetoothScanner.SCANNER_TYPE_BLUETOOTH);\n //PhoneStateScanner.setShowEnableLocationNotification(getApplicationContext(), true);\n }\n\n if ((dbError == DatabaseHandler.IMPORT_OK) && (!(appSettingsError || sharedProfileError)))\n return 1;\n else\n return 0;\n }\n else\n return 0;\n }\n\n @Override\n protected void onPostExecute(Integer result) {\n super.onPostExecute(result);\n\n doImport = false;\n\n if (!isFinishing()) {\n if ((importProgressDialog != null) && importProgressDialog.isShowing()) {\n if (!isDestroyed())\n importProgressDialog.dismiss();\n importProgressDialog = null;\n }\n GlobalGUIRoutines.unlockScreenOrientation(activity);\n }\n\n if (dataWrapper != null) {\n PPApplication.logE(\"DataWrapper.updateNotificationAndWidgets\", \"from EditorProfilesActivity.doImportData\");\n this.dataWrapper.updateNotificationAndWidgets(true);\n\n PPApplication.setApplicationStarted(this.dataWrapper.context, true);\n Intent serviceIntent = new Intent(this.dataWrapper.context, PhoneProfilesService.class);\n //serviceIntent.putExtra(PhoneProfilesService.EXTRA_ONLY_START, true);\n serviceIntent.putExtra(PhoneProfilesService.EXTRA_DEACTIVATE_PROFILE, true);\n serviceIntent.putExtra(PhoneProfilesService.EXTRA_ACTIVATE_PROFILES, true);\n PPApplication.startPPService(activity, serviceIntent);\n }\n\n if ((dataWrapper != null) && (dbError == DatabaseHandler.IMPORT_OK) && (!(appSettingsError || sharedProfileError))) {\n PPApplication.logE(\"EditorProfilesActivity.doImportData\", \"restore is ok\");\n\n // restart events\n //if (Event.getGlobalEventsRunning(this.dataWrapper.context)) {\n // this.dataWrapper.restartEventsWithDelay(3, false, false, DatabaseHandler.ALTYPE_UNDEFINED);\n //}\n\n this.dataWrapper.addActivityLog(DataWrapper.ALTYPE_DATA_IMPORT, null, null, null, 0);\n\n // toast notification\n Toast msg = ToastCompat.makeText(this.dataWrapper.context.getApplicationContext(),\n getResources().getString(R.string.toast_import_ok),\n Toast.LENGTH_SHORT);\n msg.show();\n\n // refresh activity\n if (!isFinishing())\n GlobalGUIRoutines.reloadActivity(activity, true);\n\n IgnoreBatteryOptimizationNotification.showNotification(this.dataWrapper.context.getApplicationContext());\n } else {\n PPApplication.logE(\"EditorProfilesActivity.doImportData\", \"error restore\");\n\n int appSettingsResult = 1;\n if (appSettingsError) appSettingsResult = 0;\n int sharedProfileResult = 1;\n if (sharedProfileError) sharedProfileResult = 0;\n if (!isFinishing())\n importExportErrorDialog(1, dbError, appSettingsResult, sharedProfileResult);\n }\n }\n\n }\n\n importAsyncTask = new ImportAsyncTask().execute();\n }\n }\n\n private void importDataAlert(/*boolean remoteExport*/)\n {\n //final boolean _remoteExport = remoteExport;\n\n AlertDialog.Builder dialogBuilder2 = new AlertDialog.Builder(this);\n /*if (remoteExport)\n {\n dialogBuilder2.setTitle(R.string.import_profiles_from_phoneprofiles_alert_title2);\n dialogBuilder2.setMessage(R.string.import_profiles_alert_message);\n //dialogBuilder2.setIcon(android.R.drawable.ic_dialog_alert);\n }\n else\n {*/\n dialogBuilder2.setTitle(R.string.import_profiles_alert_title);\n dialogBuilder2.setMessage(R.string.import_profiles_alert_message);\n //dialogBuilder2.setIcon(android.R.drawable.ic_dialog_alert);\n //}\n\n dialogBuilder2.setPositiveButton(R.string.alert_button_yes, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int which) {\n /*if (_remoteExport)\n {\n // start RemoteExportDataActivity\n Intent intent = new Intent(\"phoneprofiles.intent.action.EXPORTDATA\");\n\n final PackageManager packageManager = getPackageManager();\n List list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);\n if (list.size() > 0)\n startActivityForResult(intent, REQUEST_CODE_REMOTE_EXPORT);\n else\n importExportErrorDialog(1);\n }\n else*/\n doImportData(PPApplication.EXPORT_PATH);\n }\n });\n dialogBuilder2.setNegativeButton(R.string.alert_button_no, null);\n AlertDialog dialog = dialogBuilder2.create();\n /*dialog.setOnShowListener(new DialogInterface.OnShowListener() {\n @Override\n public void onShow(DialogInterface dialog) {\n Button positive = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_POSITIVE);\n if (positive != null) positive.setAllCaps(false);\n Button negative = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_NEGATIVE);\n if (negative != null) negative.setAllCaps(false);\n }\n });*/\n if (!isFinishing())\n dialog.show();\n }\n\n private void importData()\n {\n /*// test whether the PhoneProfile is installed\n PackageManager packageManager = getApplicationContext().getPackageManager();\n Intent phoneProfiles = packageManager.getLaunchIntentForPackage(\"sk.henrichg.phoneprofiles\");\n if (phoneProfiles != null)\n {\n // PhoneProfiles is installed\n\n AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);\n dialogBuilder.setTitle(R.string.import_profiles_from_phoneprofiles_alert_title);\n dialogBuilder.setMessage(R.string.import_profiles_from_phoneprofiles_alert_message);\n //dialogBuilder.setIcon(android.R.drawable.ic_dialog_alert);\n\n dialogBuilder.setPositiveButton(R.string.alert_button_yes, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int which) {\n importDataAlert(true);\n }\n });\n dialogBuilder.setNegativeButton(R.string.alert_button_no, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int which) {\n importDataAlert(false);\n }\n });\n AlertDialog dialog = dialogBuilder.create();\n dialog.setOnShowListener(new DialogInterface.OnShowListener() {\n @Override\n public void onShow(DialogInterface dialog) {\n Button positive = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_POSITIVE);\n if (positive != null) positive.setAllCaps(false);\n Button negative = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_NEGATIVE);\n if (negative != null) negative.setAllCaps(false);\n }\n });\n dialog.show();\n }\n else*/\n importDataAlert();\n }\n\n @SuppressLint(\"ApplySharedPref\")\n private boolean exportApplicationPreferences(File dst/*, int what*/) {\n boolean res = true;\n ObjectOutputStream output = null;\n try {\n try {\n output = new ObjectOutputStream(new FileOutputStream(dst));\n SharedPreferences pref;\n //if (what == 1)\n pref = getSharedPreferences(PPApplication.APPLICATION_PREFS_NAME, Activity.MODE_PRIVATE);\n //else\n // pref = getSharedPreferences(PPApplication.SHARED_PROFILE_PREFS_NAME, Activity.MODE_PRIVATE);\n SharedPreferences.Editor editor = pref.edit();\n\n AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);\n if (audioManager != null) {\n editor.putInt(\"maximumVolume_ring\", audioManager.getStreamMaxVolume(AudioManager.STREAM_RING));\n editor.putInt(\"maximumVolume_notification\", audioManager.getStreamMaxVolume(AudioManager.STREAM_NOTIFICATION));\n editor.putInt(\"maximumVolume_music\", audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));\n editor.putInt(\"maximumVolume_alarm\", audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM));\n editor.putInt(\"maximumVolume_system\", audioManager.getStreamMaxVolume(AudioManager.STREAM_SYSTEM));\n editor.putInt(\"maximumVolume_voiceCall\", audioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL));\n editor.putInt(\"maximumVolume_dtmf\", audioManager.getStreamMaxVolume(AudioManager.STREAM_DTMF));\n if (Build.VERSION.SDK_INT >= 26)\n editor.putInt(\"maximumVolume_accessibility\", audioManager.getStreamMaxVolume(AudioManager.STREAM_ACCESSIBILITY));\n editor.putInt(\"maximumVolume_bluetoothSCO\", audioManager.getStreamMaxVolume(ActivateProfileHelper.STREAM_BLUETOOTH_SCO));\n }\n\n editor.commit();\n output.writeObject(pref.getAll());\n } catch (FileNotFoundException ignored) {\n // this is OK\n } catch (IOException e) {\n res = false;\n }\n } finally {\n try {\n if (output != null) {\n output.flush();\n output.close();\n }\n } catch (IOException ignored) {\n }\n }\n return res;\n }\n\n private void exportData(final boolean email, final boolean toAuthor)\n {\n AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);\n dialogBuilder.setTitle(R.string.export_profiles_alert_title);\n dialogBuilder.setMessage(getString(R.string.export_profiles_alert_message) + \" \\\"\" + PPApplication.EXPORT_PATH + \"\\\".\\n\\n\" +\n getString(R.string.export_profiles_alert_message_note));\n //dialogBuilder.setIcon(android.R.drawable.ic_dialog_alert);\n\n dialogBuilder.setPositiveButton(R.string.alert_button_backup, new DialogInterface.OnClickListener() {\n\n public void onClick(DialogInterface dialog, int which) {\n doExportData(email, toAuthor);\n }\n });\n dialogBuilder.setNegativeButton(android.R.string.cancel, null);\n AlertDialog dialog = dialogBuilder.create();\n /*dialog.setOnShowListener(new DialogInterface.OnShowListener() {\n @Override\n public void onShow(DialogInterface dialog) {\n Button positive = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_POSITIVE);\n if (positive != null) positive.setAllCaps(false);\n Button negative = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_NEGATIVE);\n if (negative != null) negative.setAllCaps(false);\n }\n });*/\n if (!isFinishing())\n dialog.show();\n }\n\n private void doExportData(final boolean email, final boolean toAuthor)\n {\n final EditorProfilesActivity activity = this;\n\n if (Permissions.grantExportPermissions(activity.getApplicationContext(), activity, email, toAuthor)) {\n\n @SuppressLint(\"StaticFieldLeak\")\n class ExportAsyncTask extends AsyncTask {\n private final DataWrapper dataWrapper;\n\n private ExportAsyncTask() {\n AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(activity);\n dialogBuilder.setMessage(R.string.export_profiles_alert_title);\n\n LayoutInflater inflater = (activity.getLayoutInflater());\n @SuppressLint(\"InflateParams\")\n View layout = inflater.inflate(R.layout.activity_progress_bar_dialog, null);\n dialogBuilder.setView(layout);\n\n exportProgressDialog = dialogBuilder.create();\n\n this.dataWrapper = getDataWrapper();\n }\n\n @Override\n protected void onPreExecute() {\n super.onPreExecute();\n\n GlobalGUIRoutines.lockScreenOrientation(activity);\n exportProgressDialog.setCancelable(false);\n exportProgressDialog.setCanceledOnTouchOutside(false);\n if (!activity.isFinishing())\n exportProgressDialog.show();\n }\n\n @Override\n protected Integer doInBackground(Void... params) {\n\n if (this.dataWrapper != null) {\n int ret = DatabaseHandler.getInstance(this.dataWrapper.context).exportDB();\n if (ret == 1) {\n File sd = Environment.getExternalStorageDirectory();\n File exportFile = new File(sd, PPApplication.EXPORT_PATH + \"/\" + GlobalGUIRoutines.EXPORT_APP_PREF_FILENAME);\n if (exportApplicationPreferences(exportFile/*, 1*/)) {\n /*exportFile = new File(sd, PPApplication.EXPORT_PATH + \"/\" + GlobalGUIRoutines.EXPORT_DEF_PROFILE_PREF_FILENAME);\n if (!exportApplicationPreferences(exportFile, 2))\n ret = 0;*/\n ret = 1;\n } else\n ret = 0;\n }\n\n return ret;\n }\n else\n return 0;\n }\n\n @Override\n protected void onPostExecute(Integer result) {\n super.onPostExecute(result);\n\n if (!isFinishing()) {\n if ((exportProgressDialog != null) && exportProgressDialog.isShowing()) {\n if (!isDestroyed())\n exportProgressDialog.dismiss();\n exportProgressDialog = null;\n }\n GlobalGUIRoutines.unlockScreenOrientation(activity);\n }\n\n if ((dataWrapper != null) && (result == 1)) {\n\n Context context = this.dataWrapper.context.getApplicationContext();\n // toast notification\n Toast msg = ToastCompat.makeText(context, getString(R.string.toast_export_ok), Toast.LENGTH_SHORT);\n msg.show();\n\n if (email) {\n // email backup\n\n ArrayList uris = new ArrayList<>();\n\n File sd = Environment.getExternalStorageDirectory();\n\n File exportedDB = new File(sd, PPApplication.EXPORT_PATH + \"/\" + DatabaseHandler.EXPORT_DBFILENAME);\n Uri fileUri = FileProvider.getUriForFile(activity, context.getPackageName() + \".provider\", exportedDB);\n uris.add(fileUri);\n\n File appSettingsFile = new File(sd, PPApplication.EXPORT_PATH + \"/\" + GlobalGUIRoutines.EXPORT_APP_PREF_FILENAME);\n fileUri = FileProvider.getUriForFile(activity, context.getPackageName() + \".provider\", appSettingsFile);\n uris.add(fileUri);\n\n String emailAddress = \"\";\n if (toAuthor)\n emailAddress = \"henrich.gron@gmail.com\";\n Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(\n \"mailto\", emailAddress, null));\n\n String packageVersion = \"\";\n try {\n PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);\n packageVersion = \" - v\" + pInfo.versionName + \" (\" + PPApplication.getVersionCode(pInfo) + \")\";\n } catch (Exception e) {\n Log.e(\"EditorProfilesActivity.doExportData\", Log.getStackTraceString(e));\n }\n emailIntent.putExtra(Intent.EXTRA_SUBJECT, \"PhoneProfilesPlus\" + packageVersion + \" - \" + getString(R.string.menu_export));\n emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);\n\n List resolveInfo = getPackageManager().queryIntentActivities(emailIntent, 0);\n List intents = new ArrayList<>();\n for (ResolveInfo info : resolveInfo) {\n Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);\n intent.setComponent(new ComponentName(info.activityInfo.packageName, info.activityInfo.name));\n if (!emailAddress.isEmpty())\n intent.putExtra(Intent.EXTRA_EMAIL, new String[]{emailAddress});\n intent.putExtra(Intent.EXTRA_SUBJECT, \"PhoneProfilesPlus\" + packageVersion + \" - \" + getString(R.string.menu_export));\n intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);\n intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris); //ArrayList of attachment Uri's\n intents.add(new LabeledIntent(intent, info.activityInfo.packageName, info.loadLabel(getPackageManager()), info.icon));\n }\n try {\n Intent chooser = Intent.createChooser(intents.remove(intents.size() - 1), context.getString(R.string.email_chooser));\n //noinspection ToArrayCallWithZeroLengthArrayArgument\n chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents.toArray(new LabeledIntent[intents.size()]));\n startActivity(chooser);\n } catch (Exception e) {\n Log.e(\"EditorProfilesActivity.doExportData\", Log.getStackTraceString(e));\n }\n }\n\n } else {\n if (!isFinishing())\n importExportErrorDialog(2, 0, 0, 0);\n }\n }\n\n }\n\n exportAsyncTask = new ExportAsyncTask().execute();\n }\n\n }\n\n @Override\n protected void onPostCreate(Bundle savedInstanceState) {\n super.onPostCreate(savedInstanceState);\n // Sync the toggle state after onRestoreInstanceState has occurred.\n //drawerToggle.syncState();\n }\n \n @Override\n public void onSaveInstanceState(@NonNull Bundle outState) {\n super.onSaveInstanceState(outState);\n\n savedInstanceStateChanged = true;\n }\n\n @Override\n public void setTitle(CharSequence title) {\n if (getSupportActionBar() != null)\n getSupportActionBar().setTitle(title);\n }\n\n /*\n public void setIcon(int iconRes) {\n getSupportActionBar().setIcon(iconRes);\n }\n */\n\n /*\n @SuppressLint(\"SetTextI18n\")\n private void setStatusBarTitle()\n {\n // set filter status bar title\n String text = drawerItemsSubtitle[drawerSelectedItem-1];\n //filterStatusBarTitle.setText(drawerItemsTitle[drawerSelectedItem - 1] + \" - \" + text);\n drawerHeaderFilterSubtitle.setText(text);\n }\n */\n\n private void startProfilePreferenceActivity(Profile profile, int editMode, int predefinedProfileIndex) {\n Intent intent = new Intent(getBaseContext(), ProfilesPrefsActivity.class);\n if (editMode == EditorProfileListFragment.EDIT_MODE_INSERT)\n intent.putExtra(PPApplication.EXTRA_PROFILE_ID, 0L);\n else\n intent.putExtra(PPApplication.EXTRA_PROFILE_ID, profile._id);\n intent.putExtra(EXTRA_NEW_PROFILE_MODE, editMode);\n intent.putExtra(EXTRA_PREDEFINED_PROFILE_INDEX, predefinedProfileIndex);\n startActivityForResult(intent, REQUEST_CODE_PROFILE_PREFERENCES);\n }\n\n public void onStartProfilePreferences(Profile profile, int editMode, int predefinedProfileIndex/*, boolean startTargetHelps*/) {\n // In single-pane mode, simply start the profile preferences activity\n // for the profile position.\n if (((profile != null) ||\n (editMode == EditorProfileListFragment.EDIT_MODE_INSERT) ||\n (editMode == EditorProfileListFragment.EDIT_MODE_DUPLICATE))\n && (editMode != EditorProfileListFragment.EDIT_MODE_DELETE))\n startProfilePreferenceActivity(profile, editMode, predefinedProfileIndex);\n }\n\n private void redrawProfileListFragment(Profile profile, int newProfileMode /*int predefinedProfileIndex, boolean startTargetHelps*/) {\n // redraw list fragment, notification a widgets\n\n Fragment _fragment = getSupportFragmentManager().findFragmentById(R.id.editor_list_container);\n if (_fragment instanceof EditorProfileListFragment) {\n final EditorProfileListFragment fragment = (EditorProfileListFragment) getSupportFragmentManager().findFragmentById(R.id.editor_list_container);\n if (fragment != null) {\n // update profile, this rewrite profile in profileList\n fragment.activityDataWrapper.updateProfile(profile);\n\n boolean newProfile = ((newProfileMode == EditorProfileListFragment.EDIT_MODE_INSERT) ||\n (newProfileMode == EditorProfileListFragment.EDIT_MODE_DUPLICATE));\n fragment.updateListView(profile, newProfile, false, false, 0);\n\n Profile activeProfile = fragment.activityDataWrapper.getActivatedProfile(true,\n ApplicationPreferences.applicationEditorPrefIndicator(fragment.activityDataWrapper.context));\n fragment.updateHeader(activeProfile);\n PPApplication.showProfileNotification(/*getApplicationContext()*/true);\n PPApplication.logE(\"ActivateProfileHelper.updateGUI\", \"from EditorProfilesActivity.redrawProfileListFragment\");\n ActivateProfileHelper.updateGUI(fragment.activityDataWrapper.context, true, true);\n\n fragment.activityDataWrapper.setDynamicLauncherShortcutsFromMainThread();\n\n ((GlobalGUIRoutines.HighlightedSpinnerAdapter)filterSpinner.getAdapter()).setSelection(0);\n selectFilterItem(editorSelectedView, 0, false, true);\n }\n }\n }\n\n private void startEventPreferenceActivity(Event event, final int editMode, final int predefinedEventIndex) {\n boolean profileExists = true;\n long startProfileId = 0;\n long endProfileId = -1;\n if ((editMode == EditorEventListFragment.EDIT_MODE_INSERT) && (predefinedEventIndex > 0)) {\n if (getDataWrapper() != null) {\n // search names of start and end profiles\n String[] profileStartNamesArray = getResources().getStringArray(R.array.addEventPredefinedStartProfilesArray);\n String[] profileEndNamesArray = getResources().getStringArray(R.array.addEventPredefinedEndProfilesArray);\n\n startProfileId = getDataWrapper().getProfileIdByName(profileStartNamesArray[predefinedEventIndex], true);\n if (startProfileId == 0)\n profileExists = false;\n\n if (!profileEndNamesArray[predefinedEventIndex].isEmpty()) {\n endProfileId = getDataWrapper().getProfileIdByName(profileEndNamesArray[predefinedEventIndex], true);\n if (endProfileId == 0)\n profileExists = false;\n }\n }\n }\n\n if (profileExists) {\n Intent intent = new Intent(getBaseContext(), EventsPrefsActivity.class);\n if (editMode == EditorEventListFragment.EDIT_MODE_INSERT)\n intent.putExtra(PPApplication.EXTRA_EVENT_ID, 0L);\n else {\n intent.putExtra(PPApplication.EXTRA_EVENT_ID, event._id);\n intent.putExtra(PPApplication.EXTRA_EVENT_STATUS, event.getStatus());\n }\n intent.putExtra(EXTRA_NEW_EVENT_MODE, editMode);\n intent.putExtra(EXTRA_PREDEFINED_EVENT_INDEX, predefinedEventIndex);\n startActivityForResult(intent, REQUEST_CODE_EVENT_PREFERENCES);\n } else {\n final long _startProfileId = startProfileId;\n final long _endProfileId = endProfileId;\n\n AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);\n dialogBuilder.setTitle(R.string.menu_new_event);\n\n String startProfileName = \"\";\n String endProfileName = \"\";\n if (_startProfileId == 0) {\n // create profile\n int[] profileStartIndex = {0, 0, 0, 2, 4, 0, 5};\n startProfileName = getDataWrapper().getPredefinedProfile(profileStartIndex[predefinedEventIndex], false, getBaseContext())._name;\n }\n if (_endProfileId == 0) {\n // create profile\n int[] profileEndIndex = {0, 0, 0, 0, 0, 0, 6};\n endProfileName = getDataWrapper().getPredefinedProfile(profileEndIndex[predefinedEventIndex], false, getBaseContext())._name;\n }\n\n String message = \"\";\n if (!startProfileName.isEmpty())\n message = message + \" \\\"\" + startProfileName + \"\\\"\";\n if (!endProfileName.isEmpty()) {\n if (!message.isEmpty())\n message = message + \",\";\n message = message + \" \\\"\" + endProfileName + \"\\\"\";\n }\n message = getString(R.string.new_event_profiles_not_exists_alert_message1) + message + \" \" +\n getString(R.string.new_event_profiles_not_exists_alert_message2);\n\n dialogBuilder.setMessage(message);\n\n //dialogBuilder.setIcon(android.R.drawable.ic_dialog_alert);\n dialogBuilder.setPositiveButton(R.string.alert_button_yes, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int which) {\n if (_startProfileId == 0) {\n // create profile\n int[] profileStartIndex = {0, 0, 0, 2, 4, 0, 5};\n getDataWrapper().getPredefinedProfile(profileStartIndex[predefinedEventIndex], true, getBaseContext());\n }\n if (_endProfileId == 0) {\n // create profile\n int[] profileEndIndex = {0, 0, 0, 0, 0, 0, 6};\n getDataWrapper().getPredefinedProfile(profileEndIndex[predefinedEventIndex], true, getBaseContext());\n }\n\n Intent intent = new Intent(getBaseContext(), EventsPrefsActivity.class);\n intent.putExtra(PPApplication.EXTRA_EVENT_ID, 0L);\n intent.putExtra(EXTRA_NEW_EVENT_MODE, editMode);\n intent.putExtra(EXTRA_PREDEFINED_EVENT_INDEX, predefinedEventIndex);\n startActivityForResult(intent, REQUEST_CODE_EVENT_PREFERENCES);\n }\n });\n dialogBuilder.setNegativeButton(R.string.alert_button_no, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int which) {\n Intent intent = new Intent(getBaseContext(), EventsPrefsActivity.class);\n intent.putExtra(PPApplication.EXTRA_EVENT_ID, 0L);\n intent.putExtra(EXTRA_NEW_EVENT_MODE, editMode);\n intent.putExtra(EXTRA_PREDEFINED_EVENT_INDEX, predefinedEventIndex);\n startActivityForResult(intent, REQUEST_CODE_EVENT_PREFERENCES);\n }\n });\n AlertDialog dialog = dialogBuilder.create();\n /*dialog.setOnShowListener(new DialogInterface.OnShowListener() {\n @Override\n public void onShow(DialogInterface dialog) {\n Button positive = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_POSITIVE);\n if (positive != null) positive.setAllCaps(false);\n Button negative = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_NEGATIVE);\n if (negative != null) negative.setAllCaps(false);\n }\n });*/\n if (!isFinishing())\n dialog.show();\n }\n }\n\n public void onStartEventPreferences(Event event, int editMode, int predefinedEventIndex/*, boolean startTargetHelps*/) {\n if (((event != null) ||\n (editMode == EditorEventListFragment.EDIT_MODE_INSERT) ||\n (editMode == EditorEventListFragment.EDIT_MODE_DUPLICATE))\n && (editMode != EditorEventListFragment.EDIT_MODE_DELETE))\n startEventPreferenceActivity(event, editMode, predefinedEventIndex);\n }\n\n private void redrawEventListFragment(Event event, int newEventMode /*int predefinedEventIndex, boolean startTargetHelps*/) {\n // redraw list fragment, notification and widgets\n Fragment _fragment = getSupportFragmentManager().findFragmentById(R.id.editor_list_container);\n if (_fragment instanceof EditorEventListFragment) {\n EditorEventListFragment fragment = (EditorEventListFragment) getSupportFragmentManager().findFragmentById(R.id.editor_list_container);\n if (fragment != null) {\n // update event, this rewrite event in eventList\n fragment.activityDataWrapper.updateEvent(event);\n\n boolean newEvent = ((newEventMode == EditorEventListFragment.EDIT_MODE_INSERT) ||\n (newEventMode == EditorEventListFragment.EDIT_MODE_DUPLICATE));\n fragment.updateListView(event, newEvent, false, false, 0);\n\n Profile activeProfile = fragment.activityDataWrapper.getActivatedProfileFromDB(true,\n ApplicationPreferences.applicationEditorPrefIndicator(fragment.activityDataWrapper.context));\n fragment.updateHeader(activeProfile);\n\n ((GlobalGUIRoutines.HighlightedSpinnerAdapter)filterSpinner.getAdapter()).setSelection(0);\n selectFilterItem(editorSelectedView, 0, false, true);\n }\n }\n }\n\n public static ApplicationsCache getApplicationsCache()\n {\n return applicationsCache;\n }\n\n public static void createApplicationsCache()\n {\n if ((!savedInstanceStateChanged) || (applicationsCache == null))\n {\n if (applicationsCache != null)\n applicationsCache.clearCache(true);\n applicationsCache = new ApplicationsCache();\n }\n }\n\n private DataWrapper getDataWrapper()\n {\n Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.editor_list_container);\n if (fragment != null)\n {\n if (fragment instanceof EditorProfileListFragment)\n return ((EditorProfileListFragment)fragment).activityDataWrapper;\n else\n return ((EditorEventListFragment)fragment).activityDataWrapper;\n }\n else\n return null;\n }\n\n private void setEventsRunStopIndicator()\n {\n //boolean whiteTheme = ApplicationPreferences.applicationTheme(getApplicationContext(), true).equals(\"white\");\n if (Event.getGlobalEventsRunning(getApplicationContext()))\n {\n if (Event.getEventsBlocked(getApplicationContext())) {\n //if (whiteTheme)\n // eventsRunStopIndicator.setImageResource(R.drawable.ic_run_events_indicator_manual_activation_white);\n //else\n eventsRunStopIndicator.setImageResource(R.drawable.ic_run_events_indicator_manual_activation);\n }\n else {\n //if (whiteTheme)\n // eventsRunStopIndicator.setImageResource(R.drawable.ic_run_events_indicator_running_white);\n //else\n eventsRunStopIndicator.setImageResource(R.drawable.ic_run_events_indicator_running);\n }\n }\n else {\n //if (whiteTheme)\n // eventsRunStopIndicator.setImageResource(R.drawable.ic_run_events_indicator_stopped_white);\n //else\n eventsRunStopIndicator.setImageResource(R.drawable.ic_run_events_indicator_stopped);\n }\n }\n\n public void refreshGUI(final boolean refresh, final boolean refreshIcons, final boolean setPosition, final long profileId, final long eventId)\n {\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n if (doImport)\n return;\n\n setEventsRunStopIndicator();\n invalidateOptionsMenu();\n\n Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.editor_list_container);\n if (fragment != null) {\n if (fragment instanceof EditorProfileListFragment)\n ((EditorProfileListFragment) fragment).refreshGUI(refresh, refreshIcons, setPosition, profileId);\n else\n ((EditorEventListFragment) fragment).refreshGUI(refresh, refreshIcons, setPosition, eventId);\n }\n }\n });\n }\n\n /*\n private void setWindowContentOverlayCompat() {\n if (android.os.Build.VERSION.SDK_INT >= 20) {\n // Get the content view\n View contentView = findViewById(android.R.id.content);\n\n // Make sure it's a valid instance of a FrameLayout\n if (contentView instanceof FrameLayout) {\n TypedValue tv = new TypedValue();\n\n // Get the windowContentOverlay value of the current theme\n if (getTheme().resolveAttribute(\n android.R.attr.windowContentOverlay, tv, true)) {\n\n // If it's a valid resource, set it as the foreground drawable\n // for the content view\n if (tv.resourceId != 0) {\n ((FrameLayout) contentView).setForeground(\n getResources().getDrawable(tv.resourceId));\n }\n }\n }\n }\n }\n */\n\n private void showTargetHelps() {\n /*if (Build.VERSION.SDK_INT <= 19)\n // TapTarget.forToolbarMenuItem FC :-(\n // Toolbar.findViewById() returns null\n return;*/\n\n startTargetHelps = true;\n\n ApplicationPreferences.getSharedPreferences(this);\n\n boolean startTargetHelps = ApplicationPreferences.preferences.getBoolean(PREF_START_TARGET_HELPS, true);\n boolean showTargetHelpsFilterSpinner = ApplicationPreferences.preferences.getBoolean(EditorProfilesActivity.PREF_START_TARGET_HELPS_FILTER_SPINNER, true);\n boolean showTargetHelpsRunStopIndicator = ApplicationPreferences.preferences.getBoolean(EditorProfilesActivity.PREF_START_TARGET_HELPS_RUN_STOP_INDICATOR, true);\n boolean showTargetHelpsBottomNavigation = ApplicationPreferences.preferences.getBoolean(EditorProfilesActivity.PREF_START_TARGET_HELPS_BOTTOM_NAVIGATION, true);\n\n if (startTargetHelps || showTargetHelpsFilterSpinner || showTargetHelpsRunStopIndicator || showTargetHelpsBottomNavigation ||\n ApplicationPreferences.preferences.getBoolean(PREF_START_TARGET_HELPS_DEFAULT_PROFILE, true) ||\n ApplicationPreferences.preferences.getBoolean(EditorProfileListFragment.PREF_START_TARGET_HELPS, true) ||\n ApplicationPreferences.preferences.getBoolean(EditorProfileListAdapter.PREF_START_TARGET_HELPS, true) ||\n ApplicationPreferences.preferences.getBoolean(EditorProfileListAdapter.PREF_START_TARGET_HELPS_ORDER, true) ||\n ApplicationPreferences.preferences.getBoolean(EditorProfileListAdapter.PREF_START_TARGET_HELPS_SHOW_IN_ACTIVATOR, true) ||\n ApplicationPreferences.preferences.getBoolean(EditorEventListFragment.PREF_START_TARGET_HELPS, true) ||\n ApplicationPreferences.preferences.getBoolean(EditorEventListFragment.PREF_START_TARGET_HELPS_ORDER_SPINNER, true) ||\n ApplicationPreferences.preferences.getBoolean(EditorEventListAdapter.PREF_START_TARGET_HELPS, true) ||\n ApplicationPreferences.preferences.getBoolean(EditorEventListAdapter.PREF_START_TARGET_HELPS_ORDER, true) ||\n ApplicationPreferences.preferences.getBoolean(EditorEventListAdapter.PREF_START_TARGET_HELPS_STATUS, true)) {\n\n //Log.d(\"EditorProfilesActivity.showTargetHelps\", \"PREF_START_TARGET_HELPS_ORDER=true\");\n\n if (startTargetHelps || showTargetHelpsFilterSpinner || showTargetHelpsRunStopIndicator || showTargetHelpsBottomNavigation) {\n //Log.d(\"EditorProfilesActivity.showTargetHelps\", \"PREF_START_TARGET_HELPS=true\");\n\n Editor editor = ApplicationPreferences.preferences.edit();\n editor.putBoolean(PREF_START_TARGET_HELPS, false);\n editor.putBoolean(EditorProfilesActivity.PREF_START_TARGET_HELPS_FILTER_SPINNER, false);\n editor.putBoolean(EditorProfilesActivity.PREF_START_TARGET_HELPS_RUN_STOP_INDICATOR, false);\n editor.putBoolean(EditorProfilesActivity.PREF_START_TARGET_HELPS_BOTTOM_NAVIGATION, false);\n editor.apply();\n\n //TypedValue tv = new TypedValue();\n //getTheme().resolveAttribute(R.attr.colorAccent, tv, true);\n\n //final Display display = getWindowManager().getDefaultDisplay();\n\n //String appTheme = ApplicationPreferences.applicationTheme(getApplicationContext(), true);\n int outerCircleColor = R.color.tabTargetHelpOuterCircleColor;\n// if (appTheme.equals(\"dark\"))\n// outerCircleColor = R.color.tabTargetHelpOuterCircleColor_dark;\n int targetCircleColor = R.color.tabTargetHelpTargetCircleColor;\n// if (appTheme.equals(\"dark\"))\n// targetCircleColor = R.color.tabTargetHelpTargetCircleColor_dark;\n int textColor = R.color.tabTargetHelpTextColor;\n// if (appTheme.equals(\"dark\"))\n// textColor = R.color.tabTargetHelpTextColor_dark;\n\n //int[] screenLocation = new int[2];\n //filterSpinner.getLocationOnScreen(screenLocation);\n //filterSpinner.getLocationInWindow(screenLocation);\n //Rect filterSpinnerTarget = new Rect(0, 0, filterSpinner.getHeight(), filterSpinner.getHeight());\n //filterSpinnerTarget.offset(screenLocation[0] + 100, screenLocation[1]);\n\n /*\n eventsRunStopIndicator.getLocationOnScreen(screenLocation);\n //eventsRunStopIndicator.getLocationInWindow(screenLocation);\n Rect eventRunStopIndicatorTarget = new Rect(0, 0, eventsRunStopIndicator.getHeight(), eventsRunStopIndicator.getHeight());\n eventRunStopIndicatorTarget.offset(screenLocation[0], screenLocation[1]);\n */\n\n final TapTargetSequence sequence = new TapTargetSequence(this);\n List targets = new ArrayList<>();\n if (startTargetHelps) {\n\n // do not add it again\n showTargetHelpsFilterSpinner = false;\n showTargetHelpsRunStopIndicator = false;\n showTargetHelpsBottomNavigation = false;\n\n if (Event.getGlobalEventsRunning(getApplicationContext())) {\n /*targets.add(\n TapTarget.forToolbarNavigationIcon(editorToolbar, getString(R.string.editor_activity_targetHelps_navigationIcon_title), getString(R.string.editor_activity_targetHelps_navigationIcon_description))\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(true)\n .drawShadow(true)\n .id(1)\n );*/\n targets.add(\n //TapTarget.forBounds(filterSpinnerTarget, getString(R.string.editor_activity_targetHelps_filterSpinner_title), getString(R.string.editor_activity_targetHelps_filterSpinner_description))\n TapTarget.forView(filterSpinner, getString(R.string.editor_activity_targetHelps_filterSpinner_title), getString(R.string.editor_activity_targetHelps_filterSpinner_description))\n .transparentTarget(true)\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(true)\n .drawShadow(true)\n .id(1)\n );\n targets.add(\n TapTarget.forToolbarOverflow(editorToolbar, getString(R.string.editor_activity_targetHelps_applicationMenu_title), getString(R.string.editor_activity_targetHelps_applicationMenu_description))\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(true)\n .drawShadow(true)\n .id(2)\n );\n\n int id = 3;\n try {\n targets.add(\n TapTarget.forToolbarMenuItem(editorToolbar, R.id.menu_restart_events, getString(R.string.editor_activity_targetHelps_restartEvents_title), getString(R.string.editor_activity_targetHelps_restartEvents_description))\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(true)\n .drawShadow(true)\n .id(id)\n );\n ++id;\n } catch (Exception ignored) {\n } // not in action bar?\n try {\n targets.add(\n TapTarget.forToolbarMenuItem(editorToolbar, R.id.menu_activity_log, getString(R.string.editor_activity_targetHelps_activityLog_title), getString(R.string.editor_activity_targetHelps_activityLog_description))\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(true)\n .drawShadow(true)\n .id(id)\n );\n ++id;\n } catch (Exception ignored) {\n } // not in action bar?\n try {\n targets.add(\n TapTarget.forToolbarMenuItem(editorToolbar, R.id.important_info, getString(R.string.editor_activity_targetHelps_importantInfoButton_title), getString(R.string.editor_activity_targetHelps_importantInfoButton_description))\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(true)\n .drawShadow(true)\n .id(id)\n );\n ++id;\n } catch (Exception ignored) {\n } // not in action bar?\n\n targets.add(\n TapTarget.forView(eventsRunStopIndicator, getString(R.string.editor_activity_targetHelps_trafficLightIcon_title), getString(R.string.editor_activity_targetHelps_trafficLightIcon_description))\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(false)\n .drawShadow(true)\n .id(id)\n );\n ++id;\n\n targets.add(\n TapTarget.forView(bottomNavigationView.findViewById(R.id.menu_profiles_view), getString(R.string.editor_activity_targetHelps_bottomNavigationProfiles_title),\n getString(R.string.editor_activity_targetHelps_bottomNavigationProfiles_description) + \"\\n\" +\n getString(R.string.editor_activity_targetHelps_bottomNavigation_description_2))\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(true)\n .drawShadow(true)\n .id(id)\n );\n ++id;\n targets.add(\n TapTarget.forView(bottomNavigationView.findViewById(R.id.menu_events_view), getString(R.string.editor_activity_targetHelps_bottomNavigationEvents_title),\n getString(R.string.editor_activity_targetHelps_bottomNavigationEvents_description) + \"\\n\" +\n getString(R.string.editor_activity_targetHelps_bottomNavigation_description_2))\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(true)\n .drawShadow(true)\n .id(id)\n );\n ++id;\n } else {\n /*targets.add(\n TapTarget.forToolbarNavigationIcon(editorToolbar, getString(R.string.editor_activity_targetHelps_navigationIcon_title), getString(R.string.editor_activity_targetHelps_navigationIcon_description))\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(true)\n .drawShadow(true)\n .id(1)\n );*/\n targets.add(\n //TapTarget.forBounds(filterSpinnerTarget, getString(R.string.editor_activity_targetHelps_filterSpinner_title), getString(R.string.editor_activity_targetHelps_filterSpinner_description))\n TapTarget.forView(filterSpinner, getString(R.string.editor_activity_targetHelps_filterSpinner_title), getString(R.string.editor_activity_targetHelps_filterSpinner_description))\n .transparentTarget(true)\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(true)\n .drawShadow(true)\n .id(1)\n );\n targets.add(\n TapTarget.forToolbarOverflow(editorToolbar, getString(R.string.editor_activity_targetHelps_applicationMenu_title), getString(R.string.editor_activity_targetHelps_applicationMenu_description))\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(true)\n .drawShadow(true)\n .id(2)\n );\n\n int id = 3;\n try {\n targets.add(\n TapTarget.forToolbarMenuItem(editorToolbar, R.id.menu_run_stop_events, getString(R.string.editor_activity_targetHelps_runStopEvents_title), getString(R.string.editor_activity_targetHelps_runStopEvents_description))\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(true)\n .drawShadow(true)\n .id(id)\n );\n ++id;\n } catch (Exception ignored) {\n } // not in action bar?\n try {\n targets.add(\n TapTarget.forToolbarMenuItem(editorToolbar, R.id.menu_activity_log, getString(R.string.editor_activity_targetHelps_activityLog_title), getString(R.string.editor_activity_targetHelps_activityLog_description))\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(true)\n .drawShadow(true)\n .id(id)\n );\n ++id;\n } catch (Exception ignored) {\n } // not in action bar?\n try {\n targets.add(\n TapTarget.forToolbarMenuItem(editorToolbar, R.id.important_info, getString(R.string.editor_activity_targetHelps_importantInfoButton_title), getString(R.string.editor_activity_targetHelps_importantInfoButton_description))\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(true)\n .drawShadow(true)\n .id(id)\n );\n ++id;\n } catch (Exception ignored) {\n } // not in action bar?\n\n targets.add(\n TapTarget.forView(eventsRunStopIndicator, getString(R.string.editor_activity_targetHelps_trafficLightIcon_title), getString(R.string.editor_activity_targetHelps_trafficLightIcon_description))\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(false)\n .drawShadow(true)\n .id(id)\n );\n ++id;\n\n targets.add(\n TapTarget.forView(bottomNavigationView.findViewById(R.id.menu_profiles_view), getString(R.string.editor_activity_targetHelps_bottomNavigationProfiles_title),\n getString(R.string.editor_activity_targetHelps_bottomNavigationProfiles_description) + \"\\n\" +\n getString(R.string.editor_activity_targetHelps_bottomNavigation_description_2))\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(true)\n .drawShadow(true)\n .id(id)\n );\n ++id;\n targets.add(\n TapTarget.forView(bottomNavigationView.findViewById(R.id.menu_events_view), getString(R.string.editor_activity_targetHelps_bottomNavigationEvents_title),\n getString(R.string.editor_activity_targetHelps_bottomNavigationEvents_description) + \"\\n\" +\n getString(R.string.editor_activity_targetHelps_bottomNavigation_description_2))\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(true)\n .drawShadow(true)\n .id(id)\n );\n ++id;\n\n }\n }\n if (showTargetHelpsFilterSpinner) {\n targets.add(\n //TapTarget.forBounds(filterSpinnerTarget, getString(R.string.editor_activity_targetHelps_filterSpinner_title), getString(R.string.editor_activity_targetHelps_filterSpinner_description))\n TapTarget.forView(filterSpinner, getString(R.string.editor_activity_targetHelps_filterSpinner_title), getString(R.string.editor_activity_targetHelps_filterSpinner_description))\n .transparentTarget(true)\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(true)\n .drawShadow(true)\n .id(1)\n );\n }\n if (showTargetHelpsRunStopIndicator) {\n targets.add(\n TapTarget.forView(eventsRunStopIndicator, getString(R.string.editor_activity_targetHelps_trafficLightIcon_title), getString(R.string.editor_activity_targetHelps_trafficLightIcon_description))\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(false)\n .drawShadow(true)\n .id(1)\n );\n }\n if (showTargetHelpsBottomNavigation) {\n targets.add(\n TapTarget.forView(bottomNavigationView.findViewById(R.id.menu_profiles_view), getString(R.string.editor_activity_targetHelps_bottomNavigationProfiles_title),\n getString(R.string.editor_activity_targetHelps_bottomNavigationProfiles_description) + \"\\n\" +\n getString(R.string.editor_activity_targetHelps_bottomNavigation_description_2))\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(true)\n .drawShadow(true)\n .id(1)\n );\n targets.add(\n TapTarget.forView(bottomNavigationView.findViewById(R.id.menu_events_view), getString(R.string.editor_activity_targetHelps_bottomNavigationEvents_title),\n getString(R.string.editor_activity_targetHelps_bottomNavigationEvents_description) + \"\\n \" +\n getString(R.string.editor_activity_targetHelps_bottomNavigation_description_2))\n .outerCircleColor(outerCircleColor)\n .targetCircleColor(targetCircleColor)\n .textColor(textColor)\n .tintTarget(true)\n .drawShadow(true)\n .id(2)\n );\n }\n\n sequence.targets(targets);\n\n sequence.listener(new TapTargetSequence.Listener() {\n // This listener will tell us when interesting(tm) events happen in regards\n // to the sequence\n @Override\n public void onSequenceFinish() {\n targetHelpsSequenceStarted = false;\n Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.editor_list_container);\n if (fragment != null) {\n if (fragment instanceof EditorProfileListFragment)\n ((EditorProfileListFragment) fragment).showTargetHelps();\n else\n ((EditorEventListFragment) fragment).showTargetHelps();\n }\n }\n\n @Override\n public void onSequenceStep(TapTarget lastTarget, boolean targetClicked) {\n //Log.d(\"TapTargetView\", \"Clicked on \" + lastTarget.id());\n }\n\n @Override\n public void onSequenceCanceled(TapTarget lastTarget) {\n targetHelpsSequenceStarted = false;\n Editor editor = ApplicationPreferences.preferences.edit();\n if (editorSelectedView == 0) {\n editor.putBoolean(EditorProfileListFragment.PREF_START_TARGET_HELPS, false);\n editor.putBoolean(EditorProfileListAdapter.PREF_START_TARGET_HELPS, false);\n if (filterProfilesSelectedItem == DSI_PROFILES_SHOW_IN_ACTIVATOR)\n editor.putBoolean(EditorProfileListAdapter.PREF_START_TARGET_HELPS_ORDER, false);\n if (filterProfilesSelectedItem == DSI_PROFILES_ALL)\n editor.putBoolean(EditorProfileListAdapter.PREF_START_TARGET_HELPS_SHOW_IN_ACTIVATOR, false);\n }\n else {\n editor.putBoolean(EditorEventListFragment.PREF_START_TARGET_HELPS, false);\n editor.putBoolean(EditorEventListAdapter.PREF_START_TARGET_HELPS, false);\n if (filterEventsSelectedItem == DSI_EVENTS_START_ORDER)\n editor.putBoolean(EditorEventListAdapter.PREF_START_TARGET_HELPS_ORDER, false);\n editor.putBoolean(EditorEventListAdapter.PREF_START_TARGET_HELPS_STATUS, false);\n }\n editor.apply();\n }\n });\n sequence.continueOnCancel(true)\n .considerOuterCircleCanceled(true);\n targetHelpsSequenceStarted = true;\n sequence.start();\n }\n else {\n //Log.d(\"EditorProfilesActivity.showTargetHelps\", \"PREF_START_TARGET_HELPS=false\");\n //final Context context = getApplicationContext();\n final Handler handler = new Handler(getMainLooper());\n handler.postDelayed(new Runnable() {\n @Override\n public void run() {\n Intent intent = new Intent(PPApplication.PACKAGE_NAME + \".ShowEditorTargetHelpsBroadcastReceiver\");\n LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);\n /*if (EditorProfilesActivity.getInstance() != null) {\n Fragment fragment = EditorProfilesActivity.getInstance().getFragmentManager().findFragmentById(R.id.editor_list_container);\n if (fragment != null) {\n if (fragment instanceof EditorProfileListFragment)\n ((EditorProfileListFragment) fragment).showTargetHelps();\n else\n ((EditorEventListFragment) fragment).showTargetHelps();\n }\n }*/\n }\n }, 500);\n }\n }\n }\n\n static boolean displayRedTextToPreferencesNotification(Profile profile, Event event, Context context) {\n if ((profile == null) && (event == null))\n return true;\n\n\n if ((profile != null) && (!ProfilesPrefsFragment.isRedTextNotificationRequired(profile, context)))\n return true;\n if ((event != null) && (!EventsPrefsFragment.isRedTextNotificationRequired(event, context)))\n return true;\n\n int notificationID = 0;\n\n String nTitle = \"\";\n String nText = \"\";\n\n Intent intent = null;\n\n if (profile != null) {\n intent = new Intent(context, ProfilesPrefsActivity.class);\n intent.putExtra(PPApplication.EXTRA_PROFILE_ID, profile._id);\n intent.putExtra(EditorProfilesActivity.EXTRA_NEW_PROFILE_MODE, EditorProfileListFragment.EDIT_MODE_EDIT);\n intent.putExtra(EditorProfilesActivity.EXTRA_PREDEFINED_PROFILE_INDEX, 0);\n }\n if (event != null) {\n intent = new Intent(context, EventsPrefsActivity.class);\n intent.putExtra(PPApplication.EXTRA_EVENT_ID, event._id);\n intent.putExtra(PPApplication.EXTRA_EVENT_STATUS, event.getStatus());\n intent.putExtra(EXTRA_NEW_EVENT_MODE, EditorEventListFragment.EDIT_MODE_EDIT);\n intent.putExtra(EXTRA_PREDEFINED_EVENT_INDEX, 0);\n }\n\n intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n\n if (profile != null) {\n nTitle = context.getString(R.string.profile_preferences_red_texts_title);\n nText = context.getString(R.string.profile_preferences_red_texts_text_1) + \" \" +\n \"\\\"\" + profile._name + \"\\\" \" +\n context.getString(R.string.preferences_red_texts_text_2) + \" \" +\n context.getString(R.string.preferences_red_texts_text_click);\n if (android.os.Build.VERSION.SDK_INT < 24) {\n nTitle = context.getString(R.string.app_name);\n nText = context.getString(R.string.profile_preferences_red_texts_title) + \": \" +\n context.getString(R.string.profile_preferences_red_texts_text_1) + \" \" +\n \"\\\"\" + profile._name + \"\\\" \" +\n context.getString(R.string.preferences_red_texts_text_2) + \" \" +\n context.getString(R.string.preferences_red_texts_text_click);\n }\n\n intent.putExtra(PPApplication.EXTRA_PROFILE_ID, profile._id);\n notificationID = 9999 + (int) profile._id;\n }\n\n if (event != null) {\n nTitle = context.getString(R.string.event_preferences_red_texts_title);\n nText = context.getString(R.string.event_preferences_red_texts_text_1) + \" \" +\n \"\\\"\" + event._name + \"\\\" \" +\n context.getString(R.string.preferences_red_texts_text_2) + \" \" +\n context.getString(R.string.preferences_red_texts_text_click);\n if (android.os.Build.VERSION.SDK_INT < 24) {\n nTitle = context.getString(R.string.app_name);\n nText = context.getString(R.string.event_preferences_red_texts_title) + \": \" +\n context.getString(R.string.event_preferences_red_texts_text_1) + \" \" +\n \"\\\"\" + event._name + \"\\\" \" +\n context.getString(R.string.preferences_red_texts_text_2) + \" \" +\n context.getString(R.string.preferences_red_texts_text_click);\n }\n\n intent.putExtra(PPApplication.EXTRA_EVENT_ID, event._id);\n notificationID = -(9999 + (int) event._id);\n }\n\n PPApplication.createGrantPermissionNotificationChannel(context);\n NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, PPApplication.GRANT_PERMISSION_NOTIFICATION_CHANNEL)\n .setColor(ContextCompat.getColor(context, R.color.notificationDecorationColor))\n .setSmallIcon(R.drawable.ic_exclamation_notify) // notification icon\n .setContentTitle(nTitle) // title for notification\n .setContentText(nText) // message for notification\n .setAutoCancel(true); // clear notification after click\n mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(nText));\n\n PendingIntent pi = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);\n mBuilder.setContentIntent(pi);\n\n mBuilder.setPriority(NotificationCompat.PRIORITY_MAX);\n mBuilder.setCategory(NotificationCompat.CATEGORY_RECOMMENDATION);\n mBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);\n\n NotificationManager mNotificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);\n if (mNotificationManager != null)\n mNotificationManager.notify(notificationID, mBuilder.build());\n\n return false;\n }\n\n static void showDialogAboutRedText(Profile profile, Event event, boolean forShowInActivator, boolean forRunStopEvent, Activity activity) {\n if (activity == null)\n return;\n\n String nTitle = \"\";\n String nText = \"\";\n\n if (profile != null) {\n nTitle = activity.getString(R.string.profile_preferences_red_texts_title);\n nText = activity.getString(R.string.profile_preferences_red_texts_text_1) + \" \" +\n \"\\\"\" + profile._name + \"\\\" \" +\n activity.getString(R.string.preferences_red_texts_text_2);\n if (android.os.Build.VERSION.SDK_INT < 24) {\n nTitle = activity.getString(R.string.app_name);\n nText = activity.getString(R.string.profile_preferences_red_texts_title) + \": \" +\n activity.getString(R.string.profile_preferences_red_texts_text_1) + \" \" +\n \"\\\"\" + profile._name + \"\\\" \" +\n activity.getString(R.string.preferences_red_texts_text_2);\n }\n if (forShowInActivator)\n nText = nText + \" \" + activity.getString(R.string.profile_preferences_red_texts_text_3);\n else\n nText = nText + \" \" + activity.getString(R.string.profile_preferences_red_texts_text_2);\n }\n\n if (event != null) {\n nTitle = activity.getString(R.string.event_preferences_red_texts_title);\n nText = activity.getString(R.string.event_preferences_red_texts_text_1) + \" \" +\n \"\\\"\" + event._name + \"\\\" \" +\n activity.getString(R.string.preferences_red_texts_text_2);\n if (android.os.Build.VERSION.SDK_INT < 24) {\n nTitle = activity.getString(R.string.app_name);\n nText = activity.getString(R.string.event_preferences_red_texts_title) + \": \" +\n activity.getString(R.string.event_preferences_red_texts_text_1) + \" \" +\n \"\\\"\" + event._name + \"\\\" \" +\n activity.getString(R.string.preferences_red_texts_text_2);\n }\n if (forRunStopEvent)\n nText = nText + \" \" + activity.getString(R.string.event_preferences_red_texts_text_2);\n else\n nText = nText + \" \" + activity.getString(R.string.profile_preferences_red_texts_text_2);\n }\n\n if ((profile != null) || (event != null)) {\n AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(activity);\n dialogBuilder.setTitle(nTitle);\n dialogBuilder.setMessage(nText);\n dialogBuilder.setPositiveButton(android.R.string.ok, null);\n AlertDialog dialog = dialogBuilder.create();\n if (!activity.isFinishing())\n dialog.show();\n }\n }\n\n}\n"},"message":{"kind":"string","value":"Fixed alerting each notification about red texts in profiles/events.\n"},"old_file":{"kind":"string","value":"phoneProfilesPlus/src/main/java/sk/henrichg/phoneprofilesplus/EditorProfilesActivity.java"},"subject":{"kind":"string","value":"Fixed alerting each notification about red texts in profiles/events."},"git_diff":{"kind":"string","value":"honeProfilesPlus/src/main/java/sk/henrichg/phoneprofilesplus/EditorProfilesActivity.java\n mBuilder.setPriority(NotificationCompat.PRIORITY_MAX);\n mBuilder.setCategory(NotificationCompat.CATEGORY_RECOMMENDATION);\n mBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);\n mBuilder.setOnlyAlertOnce(true);\n \n NotificationManager mNotificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);\n if (mNotificationManager != null)"}}},{"rowIdx":1975,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"epl-1.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"75323dd8a3dea0701f45eb307e11aa4bf0fc5f77"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"crapo/sadlos2,crapo/sadlos2,crapo/sadlos2,crapo/sadlos2,crapo/sadlos2,crapo/sadlos2"},"new_contents":{"kind":"string","value":"/************************************************************************\n * Copyright © 2007-2016 - General Electric Company, All Rights Reserved\n *\n * Project: SADL\n *\n * Description: The Semantic Application Design Language (SADL) is a\n * language for building semantic models and expressing rules that\n * capture additional domain knowledge. The SADL-IDE (integrated\n * development environment) is a set of Eclipse plug-ins that\n * support the editing and testing of semantic models using the\n * SADL language.\n *\n * This software is distributed \"AS-IS\" without ANY WARRANTIES\n * and licensed under the Eclipse Public License - v 1.0\n * which is available at http://www.eclipse.org/org/documents/epl-v10.php\n *\n ***********************************************************************/\npackage com.ge.research.sadl.jena;\n\nimport static com.ge.research.sadl.processing.ISadlOntologyHelper.ContextBuilder.MISSING_SUBJECT;\nimport static com.ge.research.sadl.processing.ISadlOntologyHelper.GrammarContextIds.PROPOFSUBJECT_PROP;\nimport static com.ge.research.sadl.processing.ISadlOntologyHelper.GrammarContextIds.PROPOFSUBJECT_RIGHT;\nimport static com.ge.research.sadl.processing.ISadlOntologyHelper.GrammarContextIds.SADLPROPERTYINITIALIZER_PROPERTY;\nimport static com.ge.research.sadl.processing.ISadlOntologyHelper.GrammarContextIds.SADLPROPERTYINITIALIZER_VALUE;\nimport static com.ge.research.sadl.processing.ISadlOntologyHelper.GrammarContextIds.SADLSTATEMENT_SUPERELEMENT;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.ByteArrayOutputStream;\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.PrintStream;\nimport java.math.BigDecimal;\nimport java.net.MalformedURLException;\nimport java.net.URISyntaxException;\nimport java.nio.charset.Charset;\nimport java.nio.file.Paths;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.swing.text.html.HTMLDocument.HTMLReader.IsindexAction;\n\nimport org.eclipse.core.resources.IFile;\nimport org.eclipse.core.resources.IResource;\nimport org.eclipse.core.resources.IWorkspaceRoot;\nimport org.eclipse.core.resources.ResourcesPlugin;\nimport org.eclipse.core.runtime.OperationCanceledException;\nimport org.eclipse.core.runtime.Path;\nimport org.eclipse.emf.common.EMFPlugin;\nimport org.eclipse.emf.common.util.EList;\nimport org.eclipse.emf.common.util.TreeIterator;\nimport org.eclipse.emf.common.util.URI;\nimport org.eclipse.emf.ecore.EObject;\nimport org.eclipse.emf.ecore.resource.Resource;\nimport org.eclipse.xtext.diagnostics.Severity;\nimport org.eclipse.xtext.generator.IFileSystemAccess2;\nimport org.eclipse.xtext.naming.QualifiedName;\nimport org.eclipse.xtext.nodemodel.ICompositeNode;\nimport org.eclipse.xtext.nodemodel.util.NodeModelUtils;\nimport org.eclipse.xtext.resource.XtextResource;\nimport org.eclipse.xtext.scoping.IScope;\nimport org.eclipse.xtext.scoping.IScopeProvider;\nimport org.eclipse.xtext.service.OperationCanceledError;\nimport org.eclipse.xtext.util.CancelIndicator;\nimport org.eclipse.xtext.validation.CheckMode;\nimport org.eclipse.xtext.validation.CheckType;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.ge.research.sadl.builder.ConfigurationManagerForIdeFactory;\nimport com.ge.research.sadl.builder.IConfigurationManagerForIDE;\nimport com.ge.research.sadl.errorgenerator.generator.SadlErrorMessages;\nimport com.ge.research.sadl.external.ExternalEmfResource;\nimport com.ge.research.sadl.jena.JenaBasedSadlModelValidator.TypeCheckInfo;\nimport com.ge.research.sadl.jena.inference.SadlJenaModelGetterPutter;\nimport com.ge.research.sadl.model.CircularDefinitionException;\nimport com.ge.research.sadl.model.ConceptIdentifier;\nimport com.ge.research.sadl.model.ConceptName;\nimport com.ge.research.sadl.model.ConceptName.ConceptType;\nimport com.ge.research.sadl.model.ConceptName.RangeValueType;\nimport com.ge.research.sadl.model.DeclarationExtensions;\nimport com.ge.research.sadl.model.ModelError;\nimport com.ge.research.sadl.model.OntConceptType;\nimport com.ge.research.sadl.model.PrefixNotFoundException;\nimport com.ge.research.sadl.model.gp.BuiltinElement;\nimport com.ge.research.sadl.model.gp.BuiltinElement.BuiltinType;\nimport com.ge.research.sadl.model.gp.ConstantNode;\nimport com.ge.research.sadl.model.gp.EndWrite;\nimport com.ge.research.sadl.model.gp.Equation;\nimport com.ge.research.sadl.model.gp.Explain;\nimport com.ge.research.sadl.model.gp.GraphPatternElement;\nimport com.ge.research.sadl.model.gp.Junction;\nimport com.ge.research.sadl.model.gp.Junction.JunctionType;\nimport com.ge.research.sadl.model.gp.KnownNode;\n//import com.ge.research.sadl.model.gp.Literal;\nimport com.ge.research.sadl.model.gp.NamedNode;\nimport com.ge.research.sadl.model.gp.NamedNode.NodeType;\nimport com.ge.research.sadl.model.gp.Node;\nimport com.ge.research.sadl.model.gp.Print;\nimport com.ge.research.sadl.model.gp.ProxyNode;\nimport com.ge.research.sadl.model.gp.Query;\nimport com.ge.research.sadl.model.gp.Query.Order;\nimport com.ge.research.sadl.model.gp.Query.OrderingPair;\nimport com.ge.research.sadl.model.gp.RDFTypeNode;\nimport com.ge.research.sadl.model.gp.Read;\nimport com.ge.research.sadl.model.gp.Rule;\nimport com.ge.research.sadl.model.gp.SadlCommand;\nimport com.ge.research.sadl.model.gp.StartWrite;\nimport com.ge.research.sadl.model.gp.Test;\nimport com.ge.research.sadl.model.gp.TripleElement;\nimport com.ge.research.sadl.model.gp.TripleElement.TripleModifierType;\nimport com.ge.research.sadl.model.gp.TripleElement.TripleSourceType;\nimport com.ge.research.sadl.model.gp.VariableNode;\nimport com.ge.research.sadl.preferences.SadlPreferences;\nimport com.ge.research.sadl.processing.ISadlOntologyHelper.Context;\nimport com.ge.research.sadl.processing.OntModelProvider;\nimport com.ge.research.sadl.processing.SadlConstants;\nimport com.ge.research.sadl.processing.SadlConstants.OWL_FLAVOR;\nimport com.ge.research.sadl.processing.SadlModelProcessor;\nimport com.ge.research.sadl.processing.ValidationAcceptor;\nimport com.ge.research.sadl.processing.ValidationAcceptorExt;\nimport com.ge.research.sadl.reasoner.CircularDependencyException;\nimport com.ge.research.sadl.reasoner.ConfigurationException;\nimport com.ge.research.sadl.reasoner.ConfigurationManager;\nimport com.ge.research.sadl.reasoner.IReasoner;\nimport com.ge.research.sadl.reasoner.ITranslator;\nimport com.ge.research.sadl.reasoner.InvalidNameException;\nimport com.ge.research.sadl.reasoner.InvalidTypeException;\nimport com.ge.research.sadl.reasoner.SadlJenaModelGetter;\nimport com.ge.research.sadl.reasoner.TranslationException;\nimport com.ge.research.sadl.reasoner.utils.SadlUtils;\nimport com.ge.research.sadl.sADL.AskExpression;\nimport com.ge.research.sadl.sADL.BinaryOperation;\nimport com.ge.research.sadl.sADL.BooleanLiteral;\nimport com.ge.research.sadl.sADL.Constant;\nimport com.ge.research.sadl.sADL.ConstructExpression;\nimport com.ge.research.sadl.sADL.Declaration;\nimport com.ge.research.sadl.sADL.ElementInList;\nimport com.ge.research.sadl.sADL.EndWriteStatement;\nimport com.ge.research.sadl.sADL.EquationStatement;\nimport com.ge.research.sadl.sADL.ExplainStatement;\nimport com.ge.research.sadl.sADL.Expression;\nimport com.ge.research.sadl.sADL.ExpressionStatement;\nimport com.ge.research.sadl.sADL.ExternalEquationStatement;\nimport com.ge.research.sadl.sADL.Name;\nimport com.ge.research.sadl.sADL.NamedStructureAnnotation;\nimport com.ge.research.sadl.sADL.NumberLiteral;\nimport com.ge.research.sadl.sADL.OrderElement;\nimport com.ge.research.sadl.sADL.PrintStatement;\nimport com.ge.research.sadl.sADL.PropOfSubject;\nimport com.ge.research.sadl.sADL.QueryStatement;\nimport com.ge.research.sadl.sADL.ReadStatement;\nimport com.ge.research.sadl.sADL.RuleStatement;\nimport com.ge.research.sadl.sADL.SADLPackage;\nimport com.ge.research.sadl.sADL.SadlAllValuesCondition;\nimport com.ge.research.sadl.sADL.SadlAnnotation;\nimport com.ge.research.sadl.sADL.SadlBooleanLiteral;\nimport com.ge.research.sadl.sADL.SadlCanOnlyBeOneOf;\nimport com.ge.research.sadl.sADL.SadlCardinalityCondition;\nimport com.ge.research.sadl.sADL.SadlClassOrPropertyDeclaration;\nimport com.ge.research.sadl.sADL.SadlCondition;\nimport com.ge.research.sadl.sADL.SadlConstantLiteral;\nimport com.ge.research.sadl.sADL.SadlDataType;\nimport com.ge.research.sadl.sADL.SadlDataTypeFacet;\nimport com.ge.research.sadl.sADL.SadlDefaultValue;\nimport com.ge.research.sadl.sADL.SadlDifferentFrom;\nimport com.ge.research.sadl.sADL.SadlDisjointClasses;\nimport com.ge.research.sadl.sADL.SadlExplicitValue;\nimport com.ge.research.sadl.sADL.SadlHasValueCondition;\nimport com.ge.research.sadl.sADL.SadlImport;\nimport com.ge.research.sadl.sADL.SadlInstance;\nimport com.ge.research.sadl.sADL.SadlIntersectionType;\nimport com.ge.research.sadl.sADL.SadlIsAnnotation;\nimport com.ge.research.sadl.sADL.SadlIsInverseOf;\nimport com.ge.research.sadl.sADL.SadlIsSymmetrical;\nimport com.ge.research.sadl.sADL.SadlIsTransitive;\nimport com.ge.research.sadl.sADL.SadlModel;\nimport com.ge.research.sadl.sADL.SadlModelElement;\nimport com.ge.research.sadl.sADL.SadlMustBeOneOf;\nimport com.ge.research.sadl.sADL.SadlNecessaryAndSufficient;\nimport com.ge.research.sadl.sADL.SadlNestedInstance;\nimport com.ge.research.sadl.sADL.SadlNumberLiteral;\nimport com.ge.research.sadl.sADL.SadlParameterDeclaration;\nimport com.ge.research.sadl.sADL.SadlPrimitiveDataType;\nimport com.ge.research.sadl.sADL.SadlProperty;\nimport com.ge.research.sadl.sADL.SadlPropertyCondition;\nimport com.ge.research.sadl.sADL.SadlPropertyInitializer;\nimport com.ge.research.sadl.sADL.SadlPropertyRestriction;\nimport com.ge.research.sadl.sADL.SadlRangeRestriction;\nimport com.ge.research.sadl.sADL.SadlResource;\nimport com.ge.research.sadl.sADL.SadlSameAs;\nimport com.ge.research.sadl.sADL.SadlSimpleTypeReference;\nimport com.ge.research.sadl.sADL.SadlStringLiteral;\nimport com.ge.research.sadl.sADL.SadlTypeAssociation;\nimport com.ge.research.sadl.sADL.SadlTypeReference;\nimport com.ge.research.sadl.sADL.SadlUnaryExpression;\nimport com.ge.research.sadl.sADL.SadlUnionType;\nimport com.ge.research.sadl.sADL.SadlValueList;\nimport com.ge.research.sadl.sADL.SelectExpression;\nimport com.ge.research.sadl.sADL.StartWriteStatement;\nimport com.ge.research.sadl.sADL.StringLiteral;\nimport com.ge.research.sadl.sADL.SubjHasProp;\nimport com.ge.research.sadl.sADL.Sublist;\nimport com.ge.research.sadl.sADL.TestStatement;\nimport com.ge.research.sadl.sADL.UnaryExpression;\nimport com.ge.research.sadl.sADL.UnitExpression;\nimport com.ge.research.sadl.sADL.ValueRow;\nimport com.ge.research.sadl.sADL.ValueTable;\nimport com.ge.research.sadl.utils.PathToFileUriConverter;\n//import com.ge.research.sadl.server.ISadlServer;\n//import com.ge.research.sadl.server.SessionNotFoundException;\n//import com.ge.research.sadl.server.server.SadlServerImpl;\nimport com.ge.research.sadl.utils.ResourceManager;\nimport com.ge.research.sadl.utils.SadlASTUtils;\nimport com.google.common.base.Preconditions;\nimport com.google.common.collect.Iterables;\nimport com.hp.hpl.jena.ontology.AllValuesFromRestriction;\nimport com.hp.hpl.jena.ontology.AnnotationProperty;\nimport com.hp.hpl.jena.ontology.CardinalityRestriction;\nimport com.hp.hpl.jena.ontology.ComplementClass;\nimport com.hp.hpl.jena.ontology.DatatypeProperty;\nimport com.hp.hpl.jena.ontology.EnumeratedClass;\nimport com.hp.hpl.jena.ontology.HasValueRestriction;\nimport com.hp.hpl.jena.ontology.Individual;\nimport com.hp.hpl.jena.ontology.IntersectionClass;\nimport com.hp.hpl.jena.ontology.MaxCardinalityRestriction;\nimport com.hp.hpl.jena.ontology.MinCardinalityRestriction;\nimport com.hp.hpl.jena.ontology.ObjectProperty;\nimport com.hp.hpl.jena.ontology.OntClass;\nimport com.hp.hpl.jena.ontology.OntDocumentManager;\nimport com.hp.hpl.jena.ontology.OntModel;\nimport com.hp.hpl.jena.ontology.OntModelSpec;\nimport com.hp.hpl.jena.ontology.OntProperty;\nimport com.hp.hpl.jena.ontology.OntResource;\nimport com.hp.hpl.jena.ontology.Ontology;\nimport com.hp.hpl.jena.ontology.Restriction;\nimport com.hp.hpl.jena.ontology.SomeValuesFromRestriction;\nimport com.hp.hpl.jena.ontology.UnionClass;\nimport com.hp.hpl.jena.rdf.model.Literal;\nimport com.hp.hpl.jena.rdf.model.Model;\nimport com.hp.hpl.jena.rdf.model.ModelFactory;\nimport com.hp.hpl.jena.rdf.model.NodeIterator;\nimport com.hp.hpl.jena.rdf.model.Property;\nimport com.hp.hpl.jena.rdf.model.RDFList;\nimport com.hp.hpl.jena.rdf.model.RDFNode;\nimport com.hp.hpl.jena.rdf.model.RDFWriter;\nimport com.hp.hpl.jena.rdf.model.ResourceFactory;\nimport com.hp.hpl.jena.rdf.model.Statement;\nimport com.hp.hpl.jena.rdf.model.StmtIterator;\nimport com.hp.hpl.jena.reasoner.TriplePattern;\nimport com.hp.hpl.jena.sparql.JenaTransactionException;\nimport com.hp.hpl.jena.util.iterator.ExtendedIterator;\nimport com.hp.hpl.jena.vocabulary.OWL;\nimport com.hp.hpl.jena.vocabulary.OWL2;\nimport com.hp.hpl.jena.vocabulary.RDF;\nimport com.hp.hpl.jena.vocabulary.RDFS;\nimport com.hp.hpl.jena.vocabulary.XSD;\n\npublic class JenaBasedSadlModelProcessor extends SadlModelProcessor implements IJenaBasedModelProcessor {\n\tprivate static final Logger logger = LoggerFactory.getLogger(JenaBasedSadlModelProcessor.class);\n\n public final static String XSDNS = XSD.getURI();\n\n public final static Property xsdProperty( String local )\n { return ResourceFactory.createProperty( XSDNS + local ); }\n\n\tprivate Resource currentResource;\n\tprotected OntModel theJenaModel;\n\tprotected OntModelSpec spec;\n\tprivate OWL_FLAVOR owlFlavor = OWL_FLAVOR.OWL_DL;\n//\tprotected ISadlServer kServer = null;\n\t\n\tpublic enum AnnType {ALIAS, NOTE}\t\n\n\tprivate List comparisonOperators = Arrays.asList(\">=\",\">\",\"<=\",\"<\",\"==\",\"!=\",\"is\",\"=\",\"not\",\"unique\",\"in\",\"contains\",\"does\",/*\"not\",*/\"contain\");\n\tprivate List numericOperators = Arrays.asList(\"*\",\"+\",\"/\",\"-\",\"%\",\"^\");\n\tprivate List numericComparisonOperators = Arrays.asList(\">=\", \">\", \"<=\", \"<\");\n\tprivate List equalityInequalityComparisonOperators = Arrays.asList(\"==\", \"!=\", \"is\", \"=\");\n\tprivate List canBeNumericOperators = Arrays.asList(\">=\",\">\",\"<=\",\"<\",\"==\",\"!=\",\"is\",\"=\");\n\tpublic enum OPERATORS_RETURNING_BOOLEAN {contains, unique, is, gt, ge, lt, le, and, or, not, was, hasBeen}\n\t\n\tpublic enum BOOLEAN_LITERAL_TEST {BOOLEAN_TRUE, BOOLEAN_FALSE, NOT_BOOLEAN, NOT_BOOLEAN_NEGATED}\n\n\tprivate int vNum = 0;\t// used to create unique variables\n\tprivate List userDefinedVariables = new ArrayList();\n\t\n\t// A \"crule\" variable has a type, a number indicating its ordinal, and a name\n\t//\tThey are stored by type as key to a list of names, the index in the list is its ordinal number\n\tprivate Map> cruleVariables = null;\n\tprivate List preprocessedEObjects = null;\t\n\t\n\tprotected String modelName;\n\tprotected String modelAlias;\n\tprotected String modelNamespace;\n\tprivate OntDocumentManager jenaDocumentMgr;\n\tprotected IConfigurationManagerForIDE configMgr;\n\t\n\tprivate OntModel sadlBaseModel = null;\n\n\tprivate boolean importSadlListModel = false;\n\tprivate OntModel sadlListModel = null;\n\tprivate boolean importSadlDefaultsModel = false;\n\tprivate OntModel sadlDefaultsModel = null;\n\t\n\t\n\tprivate OntModel sadlImplicitModel = null;\n\tprivate OntModel sadlBuiltinFunctionModel = null;\n\n\tprotected JenaBasedSadlModelValidator modelValidator = null;\n\tprotected ValidationAcceptor issueAcceptor = null;\n\tprotected CancelIndicator cancelIndicator = null;\n\n\tprivate boolean lookingForFirstProperty = false;\t// in rules and other constructs, the first property may be significant (the binding, for example)\n\n\tprotected List importsInOrderOfAppearance = null;\t// an ordered set of import URIs, ordered by appearance in file.\n\tprivate List rules = null;\n\tprivate List equations = null;\n\tprivate Equation currentEquation = null;\n\tprivate List sadlCommands = null;\n\tprivate SadlCommand targetCommand = null;\n\t\n\tprivate List operationsPullingUp = null;\n\t\n\tint modelErrorCount = 0;\n\tint modelWarningCount = 0;\n\tint modelInfoCount = 0;\n\n\tprivate IntermediateFormTranslator intermediateFormTranslator = null;\n\n\tprotected boolean generationInProgress = false;\n\n\tpublic static String[] reservedFolderNames = {\"Graphs\", \"OwlModels\", \"Temp\", SadlConstants.SADL_IMPLICIT_MODEL_FOLDER};\n\tpublic static String[] reservedFileNames = {\"Project.sadl\",\"SadlBaseModel.sadl\", \"SadlListModel.sadl\", \n\t\t\t\"RulePatterns.sadl\", \"RulePatternsData.sadl\", \"SadlServicesConfigurationConcepts.sadl\", \n\t\t\t\"ServicesConfig.sadl\", \"defaults.sadl\", \"SadlImplicitModel.sadl\", \"SadlBuiltinFunctions.sadl\"};\n\tpublic static String[] reservedModelURIs = {SadlConstants.SADL_BASE_MODEL_URI,SadlConstants.SADL_LIST_MODEL_URI,\n\t\t\tSadlConstants.SADL_RULE_PATTERN_URI, SadlConstants.SADL_RULE_PATTERN_DATA_URI,\n\t\t\tSadlConstants.SADL_SERIVCES_CONFIGURATION_CONCEPTS_URI, SadlConstants.SADL_SERIVCES_CONFIGURATION_URI,\n\t\t\tSadlConstants.SADL_DEFAULTS_MODEL_URI};\n\tpublic static String[] reservedPrefixes = {SadlConstants.SADL_BASE_MODEL_PREFIX,SadlConstants.SADL_LIST_MODEL_PREFIX,\n\t\t\tSadlConstants.SADL_DEFAULTS_MODEL_PREFIX};\n\n\tprotected boolean includeImpliedPropertiesInTranslation = false;\t// should implied properties be included in translator output? default false\n\n\tprivate DeclarationExtensions declarationExtensions;\n\t\n\tpublic JenaBasedSadlModelProcessor() {\n\t\tlogger.debug(\"New \" + this.getClass().getCanonicalName() + \"' created\");\n\t\tsetDeclarationExtensions(new DeclarationExtensions());\n\t}\n\t/**\n\t * For TESTING\n\t * @return\n\t */\n\tpublic OntModel getTheJenaModel() {\n\t\treturn theJenaModel;\n\t}\n\t\n\tprotected void setCurrentResource(Resource currentResource) {\n\t\tthis.currentResource = currentResource;\n\t}\n\t\n\tpublic Resource getCurrentResource() {\n\t\treturn currentResource;\n\t}\n\n\t/* (non-Javadoc)\n\t * @see com.ge.research.sadl.jena.IJenaBasedModelProcessor#onGenerate(org.eclipse.emf.ecore.resource.Resource, org.eclipse.xtext.generator.IFileSystemAccess2, com.ge.research.sadl.processing.IModelProcessor.ProcessorContext)\n\t */\n\t@Override\n\tpublic void onGenerate(Resource resource, IFileSystemAccess2 fsa, ProcessorContext context) {\n\t\tgenerationInProgress = true;\n\t\tsetProcessorContext(context);\n\t\tList newMappings = new ArrayList();\n \tlogger.debug(\"onGenerate called for Resource '\" + resource.getURI() + \"'\");\n// \tSystem.out.println(\"onGenerate called for Resource '\" + resource.getURI() + \"'\");\n\t\t// save the model\n\t\tif (getTheJenaModel() == null) {\n\t\t\tOntModel m = OntModelProvider.find(resource);\n\t\t\ttheJenaModel = m;\n\t\t\tsetModelName(OntModelProvider.getModelName(resource));\n\t\t\tsetModelAlias(OntModelProvider.getModelPrefix(resource));\n\t\t}\n\t\tif (fsa !=null) {\n\t\t\tString format = getOwlModelFormat(context);\n\t\t\ttry {\n\t\t\t\tITranslator translator = null;\n\t\t\t\tList cmds = getSadlCommands();\n\t\t\t\tif (cmds != null) {\n\t\t\t\t\tIterator cmditr = cmds.iterator();\n\t\t\t\t\tList namedQueryList = null;\n\t\t\t\t\twhile (cmditr.hasNext()) {\n\t\t\t\t\t\tSadlCommand cmd = cmditr.next();\n\t\t\t\t\t\tif (cmd instanceof Query && ((Query)cmd).getName() != null) {\n\t\t\t\t\t\t\tif (translator == null) {\n\t\t\t\t\t\t\t\ttranslator = getConfigMgr(resource, format).getTranslator();\n\t\t\t\t\t\t\t\tnamedQueryList = new ArrayList();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tIndividual queryInst = getTheJenaModel().getIndividual(((Query)cmd).getFqName());\n\t\t\t\t\t\t\tif (queryInst != null && !namedQueryList.contains(queryInst.getURI())) {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tString translatedQuery = null;\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\ttranslatedQuery = translator.translateQuery(getTheJenaModel(), (Query)cmd);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcatch (UnsupportedOperationException e) {\n\t\t\t\t\t\t\t\t\t\tIReasoner defaultReasoner = getConfigMgr(resource, format).getOtherReasoner(ConfigurationManager.DEFAULT_REASONER);\n\t\t\t\t\t\t\t\t\t\ttranslator = getConfigMgr(resource, format).getTranslatorForReasoner(defaultReasoner);\n\t\t\t\t\t\t\t\t\t\ttranslatedQuery = translator.translateQuery(getTheJenaModel(), (Query)cmd);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tLiteral queryLit = getTheJenaModel().createTypedLiteral(translatedQuery);\n\t\t\t\t\t\t\t\t\tqueryInst.addProperty(RDFS.isDefinedBy, queryLit);\n\t\t\t\t\t\t\t\t\tnamedQueryList.add(queryInst.getURI());\n\t\t\t\t\t\t\t\t} catch (TranslationException e) {\n\t\t\t\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t\t\t\t} catch (InvalidNameException e) {\n\t\t\t\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (ConfigurationException e1) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te1.printStackTrace();\n\t\t\t}\n\n\n//\t\t\t// Output the OWL file for the ontology model\n\t\t\tURI lastSeg = fsa.getURI(resource.getURI().lastSegment());\n\t\t\tString owlFN = lastSeg.trimFileExtension().appendFileExtension(ResourceManager.getOwlFileExtension(format)).lastSegment().toString();\n\t\t\tRDFWriter w = getTheJenaModel().getWriter(format);\n\t\t\tw.setProperty(\"xmlbase\",getModelName());\n\t\t\tByteArrayOutputStream out = new ByteArrayOutputStream();\n\t\t\tw.write(getTheJenaModel().getBaseModel(), out, getModelName());\n\t\t\tCharset charset = Charset.forName(\"UTF-8\"); \n\t\t\tCharSequence seq = new String(out.toByteArray(), charset);\n\t\t\tfsa.generateFile(owlFN, seq);\n\t\t\t\n//\t\t\t// if there are equations, output them to a Prolog file\n//\t\t\tList eqs = getEquations();\n//\t\t\tif (eqs != null) {\n//\t\t\t\tStringBuilder sb = new StringBuilder();\n//\t\t\t\tfor (int i = 0; i < eqs.size(); i++) {\n//\t\t\t\t\tsb.append(eqs.get(i).toFullyQualifiedString());\n//\t\t\t\t\tsb.append(\"\\n\");\n//\t\t\t\t}\n//\t\t\t\tfsa.generateFile(lastSeg.appendFileExtension(\"pl\").lastSegment().toString(), sb.toString());\n//\t\t\t}\n\t\t\t\n\t\t\ttry {\n\t\t\t\tString modelFolder = getModelFolderPath(resource);\n\t\t\t\tSadlUtils su = new SadlUtils();\n\t\t\t\tString fn = SadlConstants.SADL_BASE_MODEL_FILENAME + \".\" + ResourceManager.getOwlFileExtension(format);\n\t\t\t\tif (!fileExists(fsa, fn)) {\n\t\t\t\t\tsadlBaseModel = OntModelProvider.getSadlBaseModel();\n\t\t\t\t\tif(sadlBaseModel != null) {\n\t\t\t\t\t\tRDFWriter w2 = sadlBaseModel.getWriter(format);\n\t\t\t\t\t\tw.setProperty(\"xmlbase\",SadlConstants.SADL_BASE_MODEL_URI);\n\t\t\t\t\t\tByteArrayOutputStream out2 = new ByteArrayOutputStream();\n\t\t\t\t\t\tw2.write(sadlBaseModel.getBaseModel(), out2, SadlConstants.SADL_BASE_MODEL_URI);\n\t\t\t\t\t\tCharSequence seq2 = new String(out2.toByteArray(), charset);\n\t\t\t\t\t\tfsa.generateFile(fn, seq2);\n\t\t\t\t\t\tString[] mapping = new String[3];\n\t\t\t\t\t\tmapping[0] = su.fileNameToFileUrl(modelFolder + \"/\" + fn);\n\t\t\t\t\t\tmapping[1] = SadlConstants.SADL_BASE_MODEL_URI;\n\t\t\t\t\t\tmapping[2] = SadlConstants.SADL_BASE_MODEL_PREFIX;\n\t\t\t\t\t\tnewMappings.add(mapping);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfn = SadlConstants.SADL_LIST_MODEL_FILENAME + \".\" + ResourceManager.getOwlFileExtension(format);\n\t\t\t\tif (!fileExists(fsa, fn)) {\n\t\t\t\t\tsadlListModel = OntModelProvider.getSadlListModel();\n\t\t\t\t\tif(sadlListModel != null) {\n\t\t\t\t\t\tRDFWriter w2 = sadlListModel.getWriter(format);\n\t\t\t\t\t\tw.setProperty(\"xmlbase\",SadlConstants.SADL_LIST_MODEL_URI);\n\t\t\t\t\t\tByteArrayOutputStream out2 = new ByteArrayOutputStream();\n\t\t\t\t\t\tw2.write(sadlListModel.getBaseModel(), out2, SadlConstants.SADL_LIST_MODEL_URI);\n\t\t\t\t\t\tCharSequence seq2 = new String(out2.toByteArray(), charset);\n\t\t\t\t\t\tfsa.generateFile(fn, seq2);\n\t\t\t\t\t\tString[] mapping = new String[3];\n\t\t\t\t\t\tmapping[0] = su.fileNameToFileUrl(modelFolder + \"/\" + fn);\n\t\t\t\t\t\tmapping[1] = SadlConstants.SADL_LIST_MODEL_URI;\n\t\t\t\t\t\tmapping[2] = SadlConstants.SADL_LIST_MODEL_PREFIX;\n\t\t\t\t\t\tnewMappings.add(mapping);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfn = SadlConstants.SADL_DEFAULTS_MODEL_FILENAME + \".\" + ResourceManager.getOwlFileExtension(format);\n\t\t\t\tif (!fileExists(fsa, fn)) {\n\t\t\t\t\tsadlDefaultsModel = OntModelProvider.getSadlDefaultsModel();\n\t\t\t\t\tif(sadlDefaultsModel != null) {\n\t\t\t\t\t\tRDFWriter w2 = sadlDefaultsModel.getWriter(format);\n\t\t\t\t\t\tw.setProperty(\"xmlbase\",SadlConstants.SADL_DEFAULTS_MODEL_URI);\n\t\t\t\t\t\tByteArrayOutputStream out2 = new ByteArrayOutputStream();\n\t\t\t\t\t\tw2.write(sadlDefaultsModel.getBaseModel(), out2, SadlConstants.SADL_DEFAULTS_MODEL_URI);\n\t\t\t\t\t\tCharSequence seq2 = new String(out2.toByteArray(), charset);\n\t\t\t\t\t\tfsa.generateFile(fn, seq2);\n\t\t\t\t\t\tString[] mapping = new String[3];\n\t\t\t\t\t\tmapping[0] = su.fileNameToFileUrl(modelFolder + \"/\" + fn);\n\t\t\t\t\t\tmapping[1] = SadlConstants.SADL_DEFAULTS_MODEL_URI;\n\t\t\t\t\t\tmapping[2] = SadlConstants.SADL_DEFAULTS_MODEL_PREFIX;\n\t\t\t\t\t\tnewMappings.add(mapping);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t//\t\t\t// Output the ont-policy.rdf mapping file: the mapping will have been updated already via onValidate\n\t//\t\t\tif (!fsa.isFile(UtilsForJena.ONT_POLICY_FILENAME)) {\n\t//\t\t\t\tfsa.generateFile(UtilsForJena.ONT_POLICY_FILENAME, getDefaultPolicyFileContent());\n\t//\t\t\t}\n\n\t\t\t\tString[] mapping = new String[3];\n\t\t\t\tmapping[0] = su.fileNameToFileUrl(modelFolder + \"/\" + owlFN);\n\t\t\t\tmapping[1] = getModelName();\n\t\t\t\tmapping[2] = getModelAlias();\n\n\t\t\t\tnewMappings.add(mapping);\n\t\t\t\t\n\t\t\t\t// Output the Rules and any other knowledge structures via the specified translator\n\t\t\t\tList otherContent = OntModelProvider.getOtherContent(resource);\n\t\t\t\tif (otherContent != null) {\n\t\t\t\t\tfor (int i = 0; i < otherContent.size(); i++) {\n\t\t\t\t\t\tObject oc = otherContent.get(i);\n\t\t\t\t\t\tif (oc instanceof List) {\n\t\t\t\t\t\t\tif (((List)oc).get(0) instanceof Equation) {\n\t\t\t\t\t\t\t\tsetEquations((List) oc); \n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (((List)oc).get(0) instanceof Rule) {\n\t\t\t\t\t\t\t\trules = (List) oc;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tList results = translateAndSaveModel(resource, owlFN, format, newMappings);\n\t\t\t\tif (results != null) {\n\t\t\t\t\tgenerationInProgress = false;\t// we need these errors to show up\n\t\t\t\t\tmodelErrorsToOutput(resource, results);\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch (Exception e) {\n\t\t\t\t\n\t\t\t}\n\t\t}\n\t\tgenerationInProgress = false;\n\t \tlogger.debug(\"onGenerate completed for Resource '\" + resource.getURI() + \"'\");\n\t}\n\t\n\t// akitta: get rid of this hack once https://github.com/eclipse/xtext-core/issues/180 is fixed\n\tprivate boolean fileExists(IFileSystemAccess2 fsa, String fileName) {\n\t\ttry {\n\t\t\treturn fsa.isFile(fileName);\n\t\t} catch (Exception e) {\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tprivate List translateAndSaveModel(Resource resource, String owlFN, String _repoType, List newMappings) {\n\t\tString modelFolderPathname = getModelFolderPath(resource);\n\t\ttry {\n//\t\t\tIConfigurationManagerForIDE configMgr = new ConfigurationManagerForIDE(modelFolderPathname , _repoType);\n\t\t\tif (newMappings != null) {\n\t\t\t\tgetConfigMgr(resource, _repoType).addMappings(newMappings, false, \"SADL\");\n\t\t\t}\n\t\t\tITranslator translator = getConfigMgr(resource, _repoType).getTranslator();\n\t\t\tList results = translator\n\t\t\t\t\t.translateAndSaveModel(getTheJenaModel(), getRules(),\n\t\t\t\t\t\t\tmodelFolderPathname, getModelName(), getImportsInOrderOfAppearance(), \n\t\t\t\t\t\t\towlFN);\n\t\t\tif (results != null) {\n\t\t\t\tmodelErrorsToOutput(resource, results);\n\t\t\t}\n\t\t\telse if (getOtherKnowledgeStructure(resource) != null) {\n\t\t\t\tresults = translator.translateAndSaveModelWithOtherStructure(getTheJenaModel(), getOtherKnowledgeStructure(resource), \n\t\t\t\t\t\tmodelFolderPathname, getModelName(), getImportsInOrderOfAppearance(), owlFN);\n\t\t\t\treturn results;\n\t\t\t}\n\t\t} catch (MalformedURLException e1) {\n\t\t\te1.printStackTrace();\n\t\t} catch (com.ge.research.sadl.reasoner.ConfigurationException e) {\n\t\t\te.printStackTrace();\n\t\t} catch (TranslationException e) {\n\t\t\te.printStackTrace();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t} catch (URISyntaxException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\t\n\t\t\n\t\treturn null;\n\t}\n\t\n\tprivate String getModelFolderPath(Resource resource) {\n\t\tfinal URI resourceUri = resource.getURI();\n\t\tfinal URI modelFolderUri = resourceUri\n\t\t\t\t.trimSegments(resourceUri.isFile() ? 1 : resourceUri.segmentCount() - 2)\n\t\t\t\t.appendSegment(UtilsForJena.OWL_MODELS_FOLDER_NAME);\n\t\t\n\t\tif (resourceUri.isPlatformResource()) {\n\t\t\t final IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(modelFolderUri.toPlatformString(true)));\n\t\t\t return file.getRawLocation().toPortableString();\n\t\t} else {\n\t\t\tfinal String modelFolderPathname = findModelFolderPath(resource.getURI());\n\t\t\treturn modelFolderPathname == null ? modelFolderUri.toFileString() : modelFolderPathname;\n\t\t}\n\t}\n\t\n\tstatic String findProjectPath(URI uri) {\n\t\tString modelFolder = findModelFolderPath(uri);\n\t\tif (modelFolder != null) {\n\t\t\treturn new File(modelFolder).getParent();\n\t\t}\n\t\treturn null;\n }\n\t\n public static String findModelFolderPath(URI uri){\n \tFile file = new File(uri.path());\n \tif(file != null){\n \t\tif(file.isDirectory()){\n \t\t\tif(file.getAbsolutePath().endsWith(UtilsForJena.OWL_MODELS_FOLDER_NAME)){\n \t\t\t\treturn file.getAbsolutePath();\n \t\t\t}\n \t\t\t\n \t\t\tfor(File child : file.listFiles()){\n \t\t\t\tif(child.getAbsolutePath().endsWith(UtilsForJena.OWL_MODELS_FOLDER_NAME)){\n \t\t\t\t\treturn child.getAbsolutePath();\n \t\t\t\t}\n \t\t\t}\n \t\t\t//Didn't find a project file in this directory, check parent\n \t\t\tif(file.getParentFile() != null){\n \t\t\t\treturn findModelFolderPath(uri.trimSegments(1));\n \t\t\t}\n \t\t}\n \t\tif(file.isFile() && file.getParentFile() != null){\n \t\t\treturn findModelFolderPath(uri.trimSegments(1));\n \t\t}\n \t}\n \t\n \treturn null;\n }\n\t\n\tprivate Object getOtherKnowledgeStructure(Resource resource) {\n\t\tif (getEquations(resource) != null) {\n\t\t\treturn getEquations(resource);\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprivate void modelErrorsToOutput(Resource resource, List errors) {\n\t\tfor (int i = 0; errors != null && i < errors.size(); i++) {\n\t\t\tModelError err = errors.get(i);\n\t\t\taddError(err.getErrorMsg(), resource.getContents().get(0));\n\t\t}\n\t}\n\t\n\t/**\n\t * Method to retrieve a list of the model's imports ordered according to appearance\n\t * @return\n\t */\n\tpublic List getImportsInOrderOfAppearance() {\n\t\treturn importsInOrderOfAppearance;\n\t}\n\n\tprivate void addOrderedImport(String importUri) {\n\t\tif (importsInOrderOfAppearance == null) {\n\t\t\timportsInOrderOfAppearance = new ArrayList();\n\t\t}\n\t\tif (!importsInOrderOfAppearance.contains(importUri)) {\n\t\t\timportsInOrderOfAppearance.add(importUri);\n\t\t}\n\t\t\n\t}\n\t\n\tprotected IMetricsProcessor metricsProcessor;\n\t\n\tpublic String getDefaultMakerSubjectUri() {\n\t\treturn null;\n\t}\n\n\tprivate ProcessorContext processorContext;\n\n\tprivate String reasonerClassName = null;\n\tprivate String translatorClassName = null;\n\n\tprotected boolean ignoreUnittedQuantities;\n\t\n\tprivate boolean useArticlesInValidation;\n\n\tprotected boolean domainAndRangeAsUnionClasses = true;\n\n\tprivate boolean typeCheckingWarningsOnly;\n\n\tprivate List allImpliedPropertyClasses = null;\n\n\tprivate ArrayList intermediateFormResults = null;\n\n\tprivate EObject hostEObject = null;\n\n public static void refreshResource(Resource newRsrc) {\n \ttry {\n \t\tURI uri = newRsrc.getURI();\n \t\turi = newRsrc.getResourceSet().getURIConverter().normalize(uri);\n \t\tString scheme = uri.scheme();\n \t\tif (\"platform\".equals(scheme) && uri.segmentCount() > 1 &&\n \t\t\t\t\"resource\".equals(uri.segment(0)))\n \t\t{\n \t\t\tStringBuffer platformResourcePath = new StringBuffer();\n \t\t\tfor (int j = 1, size = uri.segmentCount() - 1; j < size; ++j)\n \t\t\t{\n \t\t\t\tplatformResourcePath.append('/');\n \t\t\t\tplatformResourcePath.append(uri.segment(j));\n \t\t\t}\n \t\t\tIResource r = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(platformResourcePath.toString()));\n \t\t\tr.refreshLocal(IResource.DEPTH_INFINITE, null);\n \t\t}\n \t}\n \tcatch (Throwable t) {\n \t\t// this will happen if in test environment\n \t}\n\t}\n\n @Override\n public void validate(Context context, SadlResource candidate) {\n \tValidationAcceptor savedIssueAccpetor = this.issueAcceptor;\n \tsetIssueAcceptor(context.getAcceptor());\n \t\n \tString contextId = context.getGrammarContextId().orNull();\n \tOntModel ontModel = context.getOntModel();\n \tSadlResource subject = context.getSubject();\n \tSystem.out.println(\"Subject: \" + getDeclarationExtensions().getConceptUri(subject));\n \tSystem.out.println(\"Candidate: \" + getDeclarationExtensions().getConceptUri(candidate));\n \t\n\t\ttry {\n\t \tif (subject == MISSING_SUBJECT) {\n\t \t\treturn;\n\t \t}\n\t\t\tswitch (contextId) {\n\t\t\t\tcase SADLPROPERTYINITIALIZER_PROPERTY: {\n\t\t\t\t\tOntConceptType candtype = getDeclarationExtensions().getOntConceptType(candidate);\n\t\t\t\t\tif (!isProperty(candtype)) {\n\t\t\t\t\t\tcontext.getAcceptor().add(\"No\", candidate, Severity.ERROR);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tmodelValidator.checkPropertyDomain(ontModel, subject, candidate, candidate, true);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tcase SADLPROPERTYINITIALIZER_VALUE: {\n\t\t\t\t\tSadlResource prop = context.getRestrictions().iterator().next();\n\t\t\t\t\tOntConceptType proptype = getDeclarationExtensions().getOntConceptType(prop);\n\t\t\t\t\tif (proptype.equals(OntConceptType.DATATYPE_PROPERTY)) {\n\t\t\t\t\t\tcontext.getAcceptor().add(\"No\", candidate, Severity.ERROR);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (proptype.equals(OntConceptType.CLASS_PROPERTY)) {\n\t\t\t\t\t\tOntConceptType candtype = getDeclarationExtensions().getOntConceptType(candidate);\n\t\t\t\t\t\tif (!candtype.equals(OntConceptType.INSTANCE)) {\n\t\t\t\t\t\t\tcontext.getAcceptor().add(\"No\", candidate, Severity.ERROR);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tIterator ritr = context.getRestrictions().iterator();\n\t\t\t\t\twhile (ritr.hasNext()) {\n\t\t\t\t\t\tSystem.out.println(\"Restriction: \" + getDeclarationExtensions().getConceptUri(ritr.next()));\n\t\t\t\t\t}\n\t\t\t\t\tmodelValidator.checkPropertyDomain(ontModel, subject, prop, subject, true);\n\t\t\t\t\tStringBuilder errorMessageBuilder = new StringBuilder();\n\t\t\t\t\tif (!modelValidator.validateBinaryOperationByParts(candidate, prop, candidate, \"is\", errorMessageBuilder)) {\n\t\t\t\t\t\tcontext.getAcceptor().add(errorMessageBuilder.toString(), candidate, Severity.ERROR);\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tcase SADLSTATEMENT_SUPERELEMENT: {\n\t\t\t\t\tOntConceptType candtype = getDeclarationExtensions().getOntConceptType(candidate);\n\t\t\t\t\tif (candtype.equals(OntConceptType.CLASS) ||\n\t\t\t\t\t\t\tcandtype.equals(OntConceptType.CLASS_LIST) ||\n\t\t\t\t\t\t\tcandtype.equals(OntConceptType.CLASS_PROPERTY) ||\n\t\t\t\t\t\t\tcandtype.equals(OntConceptType.DATATYPE) ||\n\t\t\t\t\t\t\tcandtype.equals(OntConceptType.DATATYPE_LIST) ||\n\t\t\t\t\t\t\tcandtype.equals(OntConceptType.DATATYPE_PROPERTY) ||\n\t\t\t\t\t\t\tcandtype.equals(OntConceptType.RDF_PROPERTY)) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tcontext.getAcceptor().add(\"No\", candidate, Severity.ERROR);\n\t\t\t\t}\n\t\t\t\tcase PROPOFSUBJECT_RIGHT: {\n\t\t\t\t\tOntConceptType subjtype = getDeclarationExtensions().getOntConceptType(subject);\n\t\t\t\t\tOntConceptType candtype = getDeclarationExtensions().getOntConceptType(candidate);\n\t\t\t\t\tif ((candtype.equals(OntConceptType.CLASS) || candtype.equals(OntConceptType.INSTANCE)) && isProperty(subjtype)) {\n\t\t\t\t\t\tmodelValidator.checkPropertyDomain(ontModel, candidate, subject, candidate, true);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tcontext.getAcceptor().add(\"No\", candidate, Severity.ERROR);\n\t\t\t\t\treturn;\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\tcase PROPOFSUBJECT_PROP: {\n\t\t\t\t\tOntConceptType subjtype = getDeclarationExtensions().getOntConceptType(subject);\n\t\t\t\t\tOntConceptType candtype = getDeclarationExtensions().getOntConceptType(candidate);\n\t\t\t\t\tif ((candtype.equals(OntConceptType.CLASS) || candtype.equals(OntConceptType.INSTANCE)) && isProperty(subjtype)) {\n\t\t\t\t\t\tmodelValidator.checkPropertyDomain(ontModel, candidate, subject, candidate, true);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tcontext.getAcceptor().add(\"No\", candidate, Severity.ERROR);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tdefault: {\n\t\t\t\t\t// Ignored\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (InvalidTypeException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t} catch (CircularDefinitionException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t\tfinally {\n\t\t\tif (savedIssueAccpetor != null) {\n\t\t\t\tsetIssueAcceptor(savedIssueAccpetor);\n\t\t\t}\n\t\t}\n }\n \n\t@Override\n\tpublic boolean isSupported(String fileExtension) {\n\t\treturn \"sadl\".equals(fileExtension);\n\t}\n\n /* (non-Javadoc)\n\t * @see com.ge.research.sadl.jena.IJenaBasedModelProcessor#onValidate(org.eclipse.emf.ecore.resource.Resource, com.ge.research.sadl.processing.ValidationAcceptor, org.eclipse.xtext.validation.CheckMode, com.ge.research.sadl.processing.IModelProcessor.ProcessorContext)\n\t */\n @Override\n\tpublic void onValidate(Resource resource, ValidationAcceptor issueAcceptor, CheckMode mode, ProcessorContext context) {\n \t\tlogger.debug(\"onValidate called for Resource '\" + resource.getURI() + \"'\");\n\t\tif (mode.shouldCheck(CheckType.EXPENSIVE)) {\n\t\t\t// do expensive validation, i.e. those that should only be done when 'validate' action was invoked. \n\t\t}\n\t\tsetIssueAcceptor(issueAcceptor);\n\t\tsetProcessorContext(context);\n\t\tsetCancelIndicator(cancelIndicator);\n\t\tif (resource.getContents().size() < 1) {\n\t\t\treturn;\n\t\t}\n\t\tsetCurrentResource(resource);\n\t\tSadlModel model = (SadlModel) resource.getContents().get(0);\n\t\tString modelActualUrl =resource.getURI().lastSegment();\n\t\tvalidateResourcePathAndName(resource, model, modelActualUrl);\n\t\tString modelName = model.getBaseUri();\n\t\tsetModelName(modelName);\n\t\tsetModelNamespace(assureNamespaceEndsWithHash(modelName));\n\t\tsetModelAlias(model.getAlias());\n\t\tif (getModelAlias() == null) {\n\t\t\tsetModelAlias(\"\");\n\t\t}\n\t\t\n\t\ttry {\n\t\t\ttheJenaModel = prepareEmptyOntModel(resource);\n\t\t} catch (ConfigurationException e1) {\n\t\t\te1.printStackTrace();\n\t\t\taddError(SadlErrorMessages.CONFIGURATION_ERROR.get(e1.getMessage()), model);\n\t\t\taddError(e1.getMessage(), model);\n\t\t\treturn; // this is a fatal error\n\t\t}\n\t\tgetTheJenaModel().setNsPrefix(getModelAlias(), getModelNamespace());\n\t\tOntology modelOntology = getTheJenaModel().createOntology(modelName);\n\t\tlogger.debug(\"Ontology '\" + modelName + \"' created\");\n\t\tmodelOntology.addComment(\"This ontology was created from a SADL file '\"\n\t\t\t\t+ modelActualUrl + \"' and should not be directly edited.\", \"en\");\n\t\t\n\t\tString modelVersion = model.getVersion();\n\t\tif (modelVersion != null) {\n\t\t\tmodelOntology.addVersionInfo(modelVersion);\n\t\t}\n\n\t\tEList anns = model.getAnnotations();\n\t\taddAnnotationsToResource(modelOntology, anns);\n\t\t\n\t\tOntModelProvider.registerResource(resource);\n\n\t\ttry {\n\t\t\t//Add SadlBaseModel to everything except the SadlImplicitModel\n\t\t\tif(!resource.getURI().lastSegment().equals(SadlConstants.SADL_IMPLICIT_MODEL_FILENAME)){\n\t\t\t\taddSadlBaseModelImportToJenaModel(resource);\n\t\t\t}\n\t\t\t// Add the SadlImplicitModel to everything except itself and the SadlBuilinFunctions\n\t\t\tif (!resource.getURI().lastSegment().equals(SadlConstants.SADL_IMPLICIT_MODEL_FILENAME) &&\n\t\t\t\t\t!resource.getURI().lastSegment().equals(SadlConstants.SADL_BUILTIN_FUNCTIONS_FILENAME)) {\n\t\t\t\taddImplicitSadlModelImportToJenaModel(resource, context);\n\t\t\t\taddImplicitBuiltinFunctionModelImportToJenaModel(resource, context);\n\n\t\t\t}\n\t\t} catch (IOException e1) {\n\t\t\te1.printStackTrace();\n\t\t} catch (ConfigurationException e1) {\n\t\t\te1.printStackTrace();\n\t\t} catch (URISyntaxException e1) {\n\t\t\te1.printStackTrace();\n\t\t} catch (JenaProcessorException e1) {\n\t\t\te1.printStackTrace();\n\t\t}\n\t\t\n\t\tprocessModelImports(modelOntology, resource.getURI(), model);\n\n\t\tboolean enableMetricsCollection = true;\t// no longer a preference\n\t\ttry {\n\t\t\tif (enableMetricsCollection) {\n\t\t\t\tif (!isSyntheticUri(null, resource)) {\n\t\t\t\t\tsetMetricsProcessor(new MetricsProcessor(modelName, resource, getConfigMgr(resource, getOwlModelFormat(context)), this));\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (JenaProcessorException e1) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te1.printStackTrace();\n\t\t} catch (ConfigurationException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\n\t\tString impPropDW = context.getPreferenceValues().getPreference(SadlPreferences.USE_IMPLIED_PROPERTIES_IN_TRANSLATION);\n\t\tif (impPropDW != null) {\n\t\t\tincludeImpliedPropertiesInTranslation = Boolean.parseBoolean(impPropDW);\n\t\t}\n\n\t\tsetTypeCheckingWarningsOnly(true);\n\t\tString typechecking = context.getPreferenceValues().getPreference(SadlPreferences.TYPE_CHECKING_WARNING_ONLY);\n\t\tif (typechecking != null) {\n\t\t\tsetTypeCheckingWarningsOnly(Boolean.parseBoolean(typechecking));\n\t\t}\n\t\tignoreUnittedQuantities = true;\n\t\tString ignoreUnits = context.getPreferenceValues().getPreference(SadlPreferences.IGNORE_UNITTEDQUANTITIES);\n\t\tif (ignoreUnits != null) {\n\t\t\tignoreUnittedQuantities = Boolean.parseBoolean(ignoreUnits);\n\t\t}\n\t\t\n\t\tsetUseArticlesInValidation(false);\n\t\tString useArticles = context.getPreferenceValues().getPreference(SadlPreferences.P_USE_ARTICLES_IN_VALIDATION);\n\t\tif (useArticles != null) {\n\t\t\tsetUseArticlesInValidation(Boolean.parseBoolean(useArticles));\n\t\t}\n\t\t\n\t\tdomainAndRangeAsUnionClasses = true;\n\t\tString domainAndRangeAsUnionClassesStr = context.getPreferenceValues().getPreference(SadlPreferences.CREATE_DOMAIN_AND_RANGE_AS_UNION_CLASSES);\n\t\tif (domainAndRangeAsUnionClassesStr != null) {\n\t\t\tdomainAndRangeAsUnionClasses = Boolean.parseBoolean(domainAndRangeAsUnionClassesStr);\n\t\t}\n\n\t\t// create validator for expressions\n\t\tinitializeModelValidator();\n\t\tinitializeAllImpliedPropertyClasses();\n\t\t\n\t\t// process rest of parse tree\n\t\tList elements = model.getElements();\n\t\tif (elements != null) {\n\t\t\tIterator elitr = elements.iterator();\n\t\t\twhile (elitr.hasNext()) {\n\t\t\t\t// check for cancelation from time to time\n\t\t\t\tif (context.getCancelIndicator().isCanceled()) {\n\t\t\t\t\tthrow new OperationCanceledException();\n\t\t\t\t}\n\t\t\t\tSadlModelElement element = elitr.next();\n\t\t\t\tprocessModelElement(element);\n\t\t\t}\n\t\t}\n \tlogger.debug(\"onValidate completed for Resource '\" + resource.getURI() + \"'\");\n \tif (getSadlCommands() != null && getSadlCommands().size() > 0) {\n \t\tOntModelProvider.attach(model.eResource(), getTheJenaModel(), getModelName(), getModelAlias(), getSadlCommands());\n \t}\n \telse {\n \t\tOntModelProvider.attach(model.eResource(), getTheJenaModel(), getModelName(), getModelAlias());\n \t}\n \tif (rules != null && rules.size() > 0) {\n \t\tList other = OntModelProvider.getOtherContent(model.eResource());\n \t\tif (other != null) {\n \t\t\tother.add(rules);\n \t\t}\n \t\telse {\n \t\t\tOntModelProvider.addOtherContent(model.eResource(), rules);\n \t\t}\n \t}\n\t\tif (issueAcceptor instanceof ValidationAcceptorExt) {\n\t\t\tfinal ValidationAcceptorExt acceptor = (ValidationAcceptorExt) issueAcceptor;\n\t\t\ttry {\n\t\t\t\tif (!resource.getURI().lastSegment().equals(\"SadlImplicitModel.sadl\") &&\n\t\t\t\t\t!resource.getURI().lastSegment().equals(SadlConstants.SADL_BUILTIN_FUNCTIONS_FILENAME)) {\n//\t\t\t\t\tSystem.out.println(\"Metrics for '\" + resource.getURI().lastSegment() + \"':\");\n\t\t\t\t\tif (acceptor.getErrorCount() > 0) {\n\t\t\t\t\t\tString msg = \" Model totals: \" + countPlusLabel(acceptor.getErrorCount(), \"error\") + \", \" + \n\t\t\t\t\t\t\t\tcountPlusLabel(acceptor.getWarningCount(), \"warning\") + \", \" + \n\t\t\t\t\t\t\t\tcountPlusLabel(acceptor.getInfoCount(), \"info\");\n//\t\t\t\t\t\tSystem.out.flush();\n\t\t\t\t\t\tSystem.err.println(\"No OWL model output generated for '\" + resource.getURI() + \"'.\");\n\t\t\t\t\t\tSystem.err.println(msg);\n\t\t\t\t\t\tSystem.err.flush();\n\t\t\t\t\t}\n//\t\t\t\t\telse {\n//\t\t\t\t\t\tSystem.out.println(msg);\n//\t\t\t\t\t}\n\t\t\t\t\tif (!isSyntheticUri(null, resource)) {\n\t\t\t\t\t\t// don't do metrics on JUnit tests\n\t\t\t\t\t\tif (getMetricsProcessor() != null) {\n\t\t\t\t\t\t\tgetMetricsProcessor().saveMetrics(ConfigurationManager.RDF_XML_ABBREV_FORMAT);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (IOException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (IllegalStateException e) {\n\t\t\t\t// this is OK--will happen during standalone testing\n\t\t\t} catch (ConfigurationException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (URISyntaxException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t}\n\tprotected void processModelElement(SadlModelElement element) {\n\t\ttry {\n\t\t\tif (element instanceof SadlClassOrPropertyDeclaration) {\n\t\t\t\tprocessSadlClassOrPropertyDeclaration((SadlClassOrPropertyDeclaration) element);\t\n\t\t\t}\n\t\t\telse if (element instanceof SadlProperty) {\n\t\t\t\tprocessSadlProperty(null, (SadlProperty) element);\n\t\t\t}\n\t\t\telse if (element instanceof SadlNecessaryAndSufficient) {\n\t\t\t\tprocessSadlNecessaryAndSufficient((SadlNecessaryAndSufficient)element);\n\t\t\t}\n\t\t\telse if (element instanceof SadlDifferentFrom) {\n\t\t\t\tprocessSadlDifferentFrom((SadlDifferentFrom)element);\n\t\t\t}\n\t\t\telse if (element instanceof SadlInstance) {\n\t\t\t\tprocessSadlInstance((SadlInstance) element);\n\t\t\t}\n\t\t\telse if (element instanceof SadlDisjointClasses) {\n\t\t\t\tprocessSadlDisjointClasses((SadlDisjointClasses)element);\n\t\t\t}\n\t\t\telse if (element instanceof SadlSameAs) {\n\t\t\t\tprocessSadlSameAs((SadlSameAs)element);\n\t\t\t}\n\t\t\telse if (element instanceof RuleStatement) {\n\t\t\t\tprocessStatement((RuleStatement)element);\n\t\t\t}\n\t\t\telse if (element instanceof EquationStatement) {\n\t\t\t\tprocessStatement((EquationStatement)element);\n\t\t\t}\n\t\t\telse if (element instanceof PrintStatement) {\n\t\t\t\tprocessStatement((PrintStatement)element);\n\t\t\t}\n\t\t\telse if (element instanceof ReadStatement) {\n\t\t\t\tprocessStatement((ReadStatement)element);\n\t\t\t}\n\t\t\telse if (element instanceof StartWriteStatement) {\n\t\t\t\tprocessStatement((StartWriteStatement)element);\n\t\t\t}\n\t\t\telse if (element instanceof EndWriteStatement) {\n\t\t\t\tprocessStatement((EndWriteStatement)element);\n\t\t\t}\n\t\t\telse if (element instanceof ExplainStatement) {\n\t\t\t\tprocessStatement((ExplainStatement)element);\n\t\t\t}\n\t\t\telse if (element instanceof QueryStatement) {\n\t\t\t\tprocessStatement((QueryStatement)element);\n\t\t\t}\n\t\t\telse if (element instanceof SadlResource) {\n\t\t\t\tif (!SadlASTUtils.isUnit(element)) {\n\t\t\t\t\tprocessStatement((SadlResource)element);\t\t\t\t\t\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (element instanceof TestStatement) {\n\t\t\t\tprocessStatement((TestStatement)element);\n\t\t\t}\n\t\t\telse if (element instanceof ExternalEquationStatement) {\n\t\t\t\tprocessStatement((ExternalEquationStatement)element);\n\t\t\t}\n\t\t\telse if (element instanceof ExpressionStatement) {\n\t\t\t\tObject rawResult = processExpression(((ExpressionStatement)element).getExpr());\n\t\t\t\tif (isSyntheticUri(null, element.eResource())) {\n\t\t\t\t\t// for tests, do not expand; expansion, if desired, will be done upon retrieval\n\t\t\t\t\taddIntermediateFormResult(rawResult);\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// for IDE, expand and also add as info marker\n\t\t\t\t\tObject intForm = getIfTranslator().expandProxyNodes(rawResult, false, true);\n\t\t\t\t\taddIntermediateFormResult(intForm);\t\t\t\t\t\n\t\t\t\t\taddInfo(intForm.toString(), element);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthrow new JenaProcessorException(\"onValidate for element of type '\" + element.getClass().getCanonicalName() + \"' not implemented\");\n\t\t\t}\n\t\t}\n\t\tcatch (JenaProcessorException e) {\n\t\t\taddError(e.getMessage(), element);\n\t\t} catch (InvalidNameException e) {\n\t\t\te.printStackTrace();\n\t\t} catch (InvalidTypeException e) {\n\t\t\te.printStackTrace();\n\t\t} catch (TranslationException e) {\n\t\t\te.printStackTrace();\n\t\t} catch (CircularDefinitionException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t\tcatch (Throwable t) {\n\t\t\tt.printStackTrace();\n\t\t}\n\t}\n\t\n\tprivate PathToFileUriConverter getUriConverter(Resource resource) {\n\t\treturn ((XtextResource) resource).getResourceServiceProvider().get(PathToFileUriConverter.class);\n\t}\n \n\tprotected void validateResourcePathAndName(Resource resource, SadlModel model, String modelActualUrl) {\n\t\tif (!isReservedFolder(resource, model)) {\n\t\t\tif (isReservedName(resource)) {\n\t\t\t\tif (!isSyntheticUri(null, resource)) {\n\t\t\t\t\taddError(SadlErrorMessages.RESERVED_NAME.get(modelActualUrl), model);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n \n\tprivate void addImplicitBuiltinFunctionModelImportToJenaModel(Resource resource, ProcessorContext context) throws ConfigurationException, IOException, URISyntaxException, JenaProcessorException {\n\t\tif (isSyntheticUri(null, resource)) {\n\t\t\t// test case: get SadlImplicitModel OWL model from the OntModelProvider\n\t\t\tURI simTestUri = URI.createURI(SadlConstants.SADL_BUILTIN_FUNCTIONS_SYNTHETIC_URI);\n\t\t\ttry {\n\t\t\t\tsadlBuiltinFunctionModel = OntModelProvider.find(resource.getResourceSet().getResource(simTestUri, true));\n\t\t\t}\n\t\t\tcatch (Exception e) {\n\t\t\t\t// this happens if the test case doesn't cause the implicit model to be loaded--here now for backward compatibility but test cases should be fixed?\n\t\t\t\tsadlBuiltinFunctionModel = null;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tjava.nio.file.Path implfn = checkImplicitBuiltinFunctionModelExistence(resource, context);\n\t\t\tif (implfn != null) {\n\t\t\t\tfinal URI uri = getUri(resource, implfn);\n\t\t\t\tResource imrsrc = resource.getResourceSet().getResource(uri, true);\n\t\t\t\tif (sadlBuiltinFunctionModel == null) {\n\t\t\t\t\tif (imrsrc instanceof XtextResource) {\n\t\t\t\t\t\tsadlBuiltinFunctionModel = OntModelProvider.find((XtextResource)imrsrc);\n\t\t\t\t\t}\n\t\t\t\t\telse if (imrsrc instanceof ExternalEmfResource) {\n\t\t\t\t\t\tsadlBuiltinFunctionModel = ((ExternalEmfResource) imrsrc).getJenaModel();\n\t\t\t\t\t}\n\t\t\t\t\tif (sadlBuiltinFunctionModel == null) {\n\t\t\t\t\t\tif (imrsrc instanceof XtextResource) {\n\t\t\t\t\t\t\t((XtextResource) imrsrc).getResourceServiceProvider().getResourceValidator().validate(imrsrc, CheckMode.FAST_ONLY, cancelIndicator);\n\t\t\t\t\t\t\tsadlBuiltinFunctionModel = OntModelProvider.find(imrsrc);\n\t\t\t\t\t\t\tOntModelProvider.attach(imrsrc, sadlBuiltinFunctionModel, SadlConstants.SADL_BUILTIN_FUNCTIONS_URI, SadlConstants.SADL_BUILTIN_FUNCTIONS_ALIAS);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tIConfigurationManagerForIDE cm = getConfigMgr(resource, getOwlModelFormat(context));\n\t\t\t\t\t\t\tif (cm.getModelGetter() == null) {\n\t\t\t\t\t\t\t\tcm.setModelGetter(new SadlJenaModelGetter(cm, null));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcm.getModelGetter().getOntModel(SadlConstants.SADL_BUILTIN_FUNCTIONS_URI,\n\t\t\t\t\t\t\t\t\tResourceManager.getProjectUri(resource).appendSegment(ResourceManager.OWLDIR)\n\t\t\t\t\t\t\t\t\t\t\t.appendFragment(SadlConstants.OWL_BUILTIN_FUNCTIONS_FILENAME)\n\t\t\t\t\t\t\t\t\t\t\t.toFileString(),\n\t\t\t\t\t\t\t\t\tgetOwlModelFormat(context));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (sadlBuiltinFunctionModel != null) {\n\t\t\taddImportToJenaModel(getModelName(), SadlConstants.SADL_BUILTIN_FUNCTIONS_URI, SadlConstants.SADL_BUILTIN_FUNCTIONS_ALIAS, sadlBuiltinFunctionModel);\n\t\t}\n\t}\n\t\n\t/**\n\t * \n\t * @param anyResource any resource is just to \n\t * @param resourcePath the Java NIO path of the resource to load as a `platform:/resource/` if the Eclipse platform is running, otherwise\n\t * \tloads it as a file resource. \n\t */\n\tprivate URI getUri(Resource anyResource, java.nio.file.Path resourcePath) {\n\t\tPreconditions.checkArgument(anyResource instanceof XtextResource, \"Expected an Xtext resource. Got: \" + anyResource);\n\t\tif (EMFPlugin.IS_ECLIPSE_RUNNING) {\n\t\t\tIWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();\n\t\t\tjava.nio.file.Path workspaceRootPath = Paths.get(workspaceRoot.getLocationURI());\n\t\t\tjava.nio.file.Path relativePath = workspaceRootPath.relativize(resourcePath);\n\t\t\tPath relativeResourcePath = new Path(relativePath.toString());\n\t\t\treturn URI.createPlatformResourceURI(relativeResourcePath.toOSString(), true);\n\t\t} else {\n\t\t\tfinal PathToFileUriConverter uriConverter = getUriConverter(anyResource);\n\t\t\treturn uriConverter.createFileUri(resourcePath);\n\t\t}\n\t\t\n\t}\n\t\n\tprivate java.nio.file.Path checkImplicitBuiltinFunctionModelExistence(Resource resource, ProcessorContext context) throws IOException, ConfigurationException {\n\t\tUtilsForJena ufj = new UtilsForJena();\n\t\tString policyFileUrl = ufj.getPolicyFilename(resource);\n\t\tString policyFilename = policyFileUrl != null ? ufj.fileUrlToFileName(policyFileUrl) : null;\n\t\tif (policyFilename != null) {\n\t\t\tFile projectFolder = new File(policyFilename).getParentFile().getParentFile();\n\t\t\tif(projectFolder == null){\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tString relPath = SadlConstants.SADL_IMPLICIT_MODEL_FOLDER + \"/\" + SadlConstants.SADL_BUILTIN_FUNCTIONS_FILENAME;\n\t\t\tString platformPath = projectFolder.getName() + \"/\" + relPath;\n\t\t\tString implicitSadlModelFN = projectFolder + \"/\" + relPath;\n\t\t\tFile implicitModelFile = new File(implicitSadlModelFN);\n\t\t\tif (!implicitModelFile.exists()) {\n\t\t\t\tcreateBuiltinFunctionImplicitModel(projectFolder.getAbsolutePath());\n\t\t\t\ttry {\n\t\t\t\t\tResource newRsrc = resource.getResourceSet().createResource(URI.createPlatformResourceURI(platformPath, false)); \n\t\t\t\t\tnewRsrc.load(resource.getResourceSet().getLoadOptions());\n\t\t\t\t\trefreshResource(newRsrc);\n\t\t\t\t}\n\t\t\t\tcatch (Throwable t) {}\n\t\t\t}\n\t\t\treturn implicitModelFile.getAbsoluteFile().toPath();\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprivate void addImplicitSadlModelImportToJenaModel(Resource resource, ProcessorContext context) throws IOException, ConfigurationException, URISyntaxException, JenaProcessorException {\n\t\tif (isSyntheticUri(null, resource)) {\n\t\t\t// test case: get SadlImplicitModel OWL model from the OntModelProvider\n\t\t\tURI simTestUri = URI.createURI(SadlConstants.SADL_IMPLICIT_MODEL_SYNTHETIC_URI);\n\t\t\ttry {\n\t\t\t\tsadlImplicitModel = OntModelProvider.find(resource.getResourceSet().getResource(simTestUri, true));\n\t\t\t}\n\t\t\tcatch (Exception e) {\n\t\t\t\t// this happens if the test case doesn't cause the implicit model to be loaded--here now for backward compatibility but test cases should be fixed?\n\t\t\t\tsadlImplicitModel = null;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tjava.nio.file.Path implfn = checkImplicitSadlModelExistence(resource, context);\n\t\t\tif (implfn != null) {\n\t\t\t\tfinal URI uri = getUri(resource, implfn);\n\t\t\t\tResource imrsrc = resource.getResourceSet().getResource(uri, true);\n\t\t\t\tif (sadlImplicitModel == null) {\n\t\t\t\t\tif (imrsrc instanceof XtextResource) {\n\t\t\t\t\t\tsadlImplicitModel = OntModelProvider.find((XtextResource)imrsrc);\n\t\t\t\t\t}\n\t\t\t\t\telse if (imrsrc instanceof ExternalEmfResource) {\n\t\t\t\t\t\tsadlImplicitModel = ((ExternalEmfResource) imrsrc).getJenaModel();\n\t\t\t\t\t}\n\t\t\t\t\tif (sadlImplicitModel == null) {\n\t\t\t\t\t\tif (imrsrc instanceof XtextResource) {\n\t\t\t\t\t\t\t((XtextResource) imrsrc).getResourceServiceProvider().getResourceValidator().validate(imrsrc, CheckMode.FAST_ONLY, cancelIndicator);\n\t\t\t\t\t\t\tsadlImplicitModel = OntModelProvider.find(imrsrc);\n\t\t\t\t\t\t\tOntModelProvider.attach(imrsrc, sadlImplicitModel, SadlConstants.SADL_IMPLICIT_MODEL_URI, SadlConstants.SADL_IMPLICIT_MODEL_PREFIX);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tIConfigurationManagerForIDE cm = getConfigMgr(resource, getOwlModelFormat(context));\n\t\t\t\t\t\t\tif (cm.getModelGetter() == null) {\n\t\t\t\t\t\t\t\tcm.setModelGetter(new SadlJenaModelGetter(cm, null));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcm.getModelGetter().getOntModel(SadlConstants.SADL_IMPLICIT_MODEL_URI,\n\t\t\t\t\t\t\t\t\tResourceManager.getProjectUri(resource).appendSegment(ResourceManager.OWLDIR)\n\t\t\t\t\t\t\t\t\t\t\t.appendFragment(SadlConstants.OWL_IMPLICIT_MODEL_FILENAME)\n\t\t\t\t\t\t\t\t\t\t\t.toFileString(),\n\t\t\t\t\t\t\t\t\tgetOwlModelFormat(context));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (sadlImplicitModel != null) {\n\t\t\taddImportToJenaModel(getModelName(), SadlConstants.SADL_IMPLICIT_MODEL_URI, SadlConstants.SADL_IMPLICIT_MODEL_PREFIX, sadlImplicitModel);\n\t\t}\n\t}\n\t\n\tprivate void addSadlBaseModelImportToJenaModel(Resource resource) throws IOException, ConfigurationException, URISyntaxException, JenaProcessorException {\n\t\tif (sadlBaseModel == null) {\n\t\t\tsadlBaseModel = OntModelProvider.getSadlBaseModel();\n\t\t\tif (sadlBaseModel == null) {\n\t\t\t\tsadlBaseModel = getOntModelFromString(resource, getSadlBaseModel());\n\t\t\t\tOntModelProvider.setSadlBaseModel(sadlBaseModel);\n\t\t\t}\n\t\t}\n\t\taddImportToJenaModel(getModelName(), SadlConstants.SADL_BASE_MODEL_URI, SadlConstants.SADL_BASE_MODEL_PREFIX, sadlBaseModel);\n\t}\n\t\n\tprotected void addAnnotationsToResource(OntResource modelOntology, EList anns) {\n\t\tIterator iter = anns.iterator();\n\t\twhile (iter.hasNext()) {\n\t\t\tSadlAnnotation ann = iter.next();\n\t\t\tString anntype = ann.getType();\n\t\t\tEList annContents = ann.getContents();\n\t\t\tIterator anniter = annContents.iterator();\n\t\t\twhile (anniter.hasNext()) {\n\t\t\t\tString annContent = anniter.next();\n\t\t\t\tif (anntype.equalsIgnoreCase(AnnType.ALIAS.toString())) {\n\t\t\t\t\tmodelOntology.addLabel(annContent, \"en\");\n\t\t\t\t}\n\t\t\t\telse if (anntype.equalsIgnoreCase(AnnType.NOTE.toString())) {\n\t\t\t\t\tmodelOntology.addComment(annContent, \"en\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic OntModel prepareEmptyOntModel(Resource resource) throws ConfigurationException {\n\t\ttry {\n\t\t\tIConfigurationManagerForIDE cm = getConfigMgr(resource, getOwlModelFormat(getProcessorContext()));\n\t\t\tOntDocumentManager owlDocMgr = cm.getJenaDocumentMgr();\n\t\t\tOntModelSpec spec = new OntModelSpec(OntModelSpec.OWL_MEM);\n\t\t\tsetSpec(spec);\n\t\t\tString modelFolderPathname = getModelFolderPath(resource);\n\t\t\tif (modelFolderPathname != null && !modelFolderPathname.startsWith(SYNTHETIC_FROM_TEST)) {\n\t\t\t\tFile mff = new File(modelFolderPathname);\n\t\t\t\tmff.mkdirs();\n\t\t\t\tspec.setImportModelGetter(new SadlJenaModelGetterPutter(spec, modelFolderPathname));\n\t\t\t}\n\t\t\tif (owlDocMgr != null) {\n\t\t\t\tspec.setDocumentManager(owlDocMgr);\n\t\t\t\towlDocMgr.setProcessImports(true);\n\t\t\t}\n\t\t\treturn ModelFactory.createOntologyModel(spec);\n\t\t}\n\t\tcatch (ConfigurationException e) {\n\t\t\te.printStackTrace();\n\t\t\tthrow e;\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t\tthrow new ConfigurationException(e.getMessage(), e);\n\t\t}\n\t}\n\t\n\tprivate void setProcessorContext(ProcessorContext ctx) {\n\t\tprocessorContext = ctx;\n\t}\n\t\n\tprivate ProcessorContext getProcessorContext() {\n\t\treturn processorContext;\n\t}\n\t\n\tprotected String countPlusLabel(int count, String label) {\n\t\tif (count == 0 || count > 1) {\n\t\t\tlabel = label + \"s\";\n\t\t}\n\t\treturn \"\" + count + \" \" + label;\n\t}\n\n\tprivate void addImportToJenaModel(String modelName, String importUri, String importPrefix, Model importedOntModel) {\n\t\tgetTheJenaModel().getDocumentManager().addModel(importUri, importedOntModel, true);\n\t\tOntology modelOntology = getTheJenaModel().createOntology(modelName);\n\t\tif (importPrefix == null) {\n\t\t\ttry {\n\t\t\t\timportPrefix = getConfigMgr(getCurrentResource(), getOwlModelFormat(getProcessorContext())).getGlobalPrefix(importUri);\n\t\t\t} catch (ConfigurationException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\tif (importPrefix != null) {\n\t\t\tgetTheJenaModel().setNsPrefix(importPrefix, importUri);\n\t\t}\n\t\tcom.hp.hpl.jena.rdf.model.Resource importedOntology = getTheJenaModel().createResource(importUri);\n\t\tmodelOntology.addImport(importedOntology);\n\t\tgetTheJenaModel().addSubModel(importedOntModel);\n\t\tgetTheJenaModel().addLoadedImport(importUri);\n//\t\tgetTheJenaModel().loadImports();\n//\t\tIConfigurationManagerForIDE cm;\n//\t\ttry {\n//\t\t\tcm = getConfigMgr(getCurrentResource(), getOwlModelFormat(getProcessorContext()));\n//\t\t\tcm.loadImportedModel(modelOntology, getTheJenaModel(), importUri, cm.getAltUrlFromPublicUri(importUri));\n//\t\t} catch (ConfigurationException e) {\n//\t\t\tthrow new JenaTransactionException(\"Unable to load imported model '\" + importUri + \"'\", e);\n//\t\t}\n\t\taddOrderedImport(importUri);\n\t}\n\n//\t/**\n//\t * Method to determine the OWL model URI and actual URL for each import and add that, along with the prefix,\n//\t * to the Jena OntDocumentManager so that it will be loaded when we do a Jena loadImports\n//\t * @param sadlImports -- the list of imports to \n//\t * @return \n//\t */\n//\tprivate List getIndirectImportResources(SadlModel model) {\n//\t\tEList implist = model.getImports();\n//\t\tIterator impitr = implist.iterator();\n//\t\tif (impitr.hasNext()) {\n//\t\t\tList importedResources = new ArrayList();\n//\t\t\twhile (impitr.hasNext()) {\n//\t\t\t\tSadlImport simport = impitr.next();\n//\t\t\t\tSadlModel importedModel = simport.getImportedResource();\n//\t\t\t\tif (importedModel != null) {\n//\t\t\t\t\tString importUri = importedModel.getBaseUri();\n//\t\t\t\t\tString importPrefix = simport.getAlias();\n//\t\t \t\tif (importPrefix != null) {\n//\t\t \t\t\tgetTheJenaModel().setNsPrefix(importPrefix, assureNamespaceEndsWithHash(importUri));\n//\t\t \t\t}\n//\t\t\t \timportedResources.add(importedModel.eResource());\n//\t\t\t\t}\n//\t\t\t\telse {\n//\t\t\t\t\taddError(\"Unable to obtain import URI\", simport);\n//\t\t\t\t}\n//\t\t\t\tList moreImports = getIndirectImportResources(importedModel);\n//\t\t\t\tif (moreImports != null) {\n//\t\t\t\t\timportedResources.addAll(moreImports);\n//\t\t\t\t}\n//\t\t\t}\n//\t\t\treturn importedResources;\n//\t\t}\n//\t\treturn null;\n//\t}\n\t\n\t/**\n\t * Method to check for erroneous use of a reserved folder name\n\t * @param resource\n\t * @param model\n\t * @return\n\t */\n\tprivate boolean isReservedFolder(Resource resource, SadlModel model) {\n\t\tURI prjuri = ResourceManager.getProjectUri(resource);\n\t\tif (prjuri == null) {\n\t\t\treturn false;\t// this is the path that JUnit tests will follow\n\t\t}\n\t\tURI rsrcuri = resource.getURI();\n\t\tString[] rsrcsegs = rsrcuri.segments();\n\t\tString[] prjsegs = prjuri.segments();\n\t\tif (rsrcsegs.length > prjsegs.length) {\n\t\t\tString topPrjFolder = rsrcsegs[prjsegs.length];\n\t\t\tfor (String fnm:reservedFolderNames) {\n\t\t\t\tif (topPrjFolder.equals(fnm)) {\n\t\t\t\t\tif (fnm.equals(SadlConstants.SADL_IMPLICIT_MODEL_FOLDER)) {\n\t\t\t\t\t\tif (!isReservedName(resource)) {\n\t\t\t\t\t\t\t// only reserved names allowed here\n\t\t\t\t\t\t\taddError(SadlErrorMessages.RESERVED_FOLDER.get(fnm), model);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\taddError(SadlErrorMessages.RESERVED_FOLDER.get(fnm), model);\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate boolean isReservedName(Resource resource) {\n\t\tString nm = resource.getURI().lastSegment();\n\t\tfor (String rnm:reservedFileNames) {\n\t\t\tif (rnm.equals(nm)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprivate void processStatement(SadlResource element) throws TranslationException {\n\t\tObject srobj = processExpression(element);\n\t\tint i = 0;\n\t}\n\t\n\tpublic Test[] processStatement(TestStatement element) throws JenaProcessorException {\n\t\tTest[] generatedTests = null;\n\t\tTest sadlTest = null;\n\t\tboolean done = false;\n\t\ttry {\n\t\t\tEList tests = element.getTests();\n\t\t\tfor (int tidx = 0; tidx < tests.size(); tidx++) {\n\t\t\t\tExpression expr = tests.get(tidx);\n\t\t\t\t// we know it's a Test so create one and set as translation target\n\t\t\t\tTest test = new Test();\n\t\t\t\tfinal ICompositeNode node = NodeModelUtils.findActualNodeFor(element);\n\t\t\t\tif (node != null) {\n\t\t\t\t\ttest.setOffset(node.getOffset() - 1);\n\t\t\t\t\ttest.setLength(node.getLength());\n\t\t\t\t}\n\t\t\t\tsetTarget(test);\n\t\n\t\t\t\t// now translate the test expression\n\t\t\t\tObject testtrans = processExpression(expr);\n\t\t\t\t\n\t\t\t\t// Examine testtrans, the results of the translation.\n\t\t\t\t// The recognition of various Test patterns, so that the LHS, RHS, Comparison of the Test can be\n\t\t\t\t// properly set is best done on the translation before the ProxyNodes are expanded--their expansion\n\t\t\t\t// destroys needed information and introduces ambiguity\n\t\t\t\n\t\t\t\tif (testtrans instanceof BuiltinElement \n\t\t\t\t\t\t&& IntermediateFormTranslator.isComparisonBuiltin(((BuiltinElement)testtrans).getFuncName())) {\n\t\t\t\t\tList args = ((BuiltinElement)testtrans).getArguments();\n\t\t\t\t\tif (args != null && args.size() == 2) {\n\t\t\t\t\t\ttest.setCompName(((BuiltinElement)testtrans).getFuncType());\n\t\t\t\t\t\tObject lhsObj = getIfTranslator().expandProxyNodes(args.get(0), false, true);\n\t\t\t\t\t\tObject rhsObj = getIfTranslator().expandProxyNodes(args.get(1), false, true);\n\t\t\t\t\t\ttest.setLhs((lhsObj != null && lhsObj instanceof List && ((List)lhsObj).size() > 0) ? lhsObj : args.get(0));\n\t\t\t\t\t\ttest.setRhs((rhsObj != null && rhsObj instanceof List && ((List)rhsObj).size() > 0) ? rhsObj : args.get(1));\n\t\t\t\t\t\tgeneratedTests = new Test[1];\n\t\t\t\t\t\tgeneratedTests[0] = test;\n\t\t\t\t\t\tdone = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (testtrans instanceof TripleElement) {\n\t\t\t\t\tif (((TripleElement)testtrans).getModifierType() != null &&\n\t\t\t\t\t\t\t!((TripleElement)testtrans).getModifierType().equals(TripleModifierType.None)) {\n\t\t\t\t\t\t// Filtered query with modification\n\t\t\t\t\t\tTripleModifierType ttype = ((TripleElement)testtrans).getModifierType();\n\t\t\t\t\t\tObject trans = getIfTranslator().expandProxyNodes(testtrans, false, true);\n\t\t\t\t\t\tif ((trans != null && trans instanceof List && ((List)trans).size() > 0)) {\n\t\t\t\t\t\t\tif (ttype.equals(TripleModifierType.Not)) {\n\t\t\t\t\t\t\t\tif (changeFilterDirection(trans)) {\n\t\t\t\t\t\t\t\t\t((TripleElement)testtrans).setType(TripleModifierType.None);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ttest.setLhs(trans);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tif (ttype.equals(TripleModifierType.Not)) {\n\t\t\t\t\t\t\t\tchangeFilterDirection(testtrans);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ttest.setLhs(testtrans);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tgeneratedTests = new Test[1];\n\t\t\t\t\t\tgeneratedTests[0] = test;\n\t\t\t\t\t\tdone = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (!done) {\n\t\t\t\t\t// expand ProxyNodes and see what we can do with the expanded form\n\t\t\t\t\tList expanded = new ArrayList();\n\t\t\t\t\tObject testExpanded = getIfTranslator().expandProxyNodes(testtrans, false, true);\n\t\t\t\t\tboolean treatAsMultipleTests = false; {\n\t\t\t\t\t\tif (testExpanded instanceof List) {\n\t\t\t\t\t\t\ttreatAsMultipleTests = containsMultipleTests((List) testExpanded);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (treatAsMultipleTests && testExpanded instanceof List) {\n\t\t\t\t\t\tfor (int i = 0; i < ((List)testExpanded).size(); i++) {\n\t\t\t\t\t\t\texpanded.add(((List)testExpanded).get(i));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\texpanded.add(testExpanded);\n\t\t\t\t\t}\n\t\n\t\t\t\t\tif (expanded.size() == 0) {\n\t\t\t\t\t\tgeneratedTests = new Test[1];\n\t\t\t\t\t\tgeneratedTests[0] = test;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tgeneratedTests = new Test[expanded.size()];\n\t\t\n\t\t\t\t\t\tfor (int i = 0; expanded != null && i < expanded.size(); i++) {\n\t\t\t\t\t\t\tObject testgpe = expanded.get(i);\n\t\t\t\t\t\t\tif (i > 0) {\n\t\t\t\t\t\t\t\t// not the first element; need a new Test\n\t\t\t\t\t\t\t\ttest = new Test();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tgeneratedTests[i] = test;\n\t\t\n\t\t\t\t\t\t\t// Case 3: the test translates into a TripleElement\n\t\t\t\t\t\t\tif (testgpe instanceof TripleElement) {\n\t\t\t\t\t\t\t\ttest.setLhs(testgpe); \n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (!done && testgpe instanceof List) {\n\t\t\t\t\t\t\t\ttest.setLhs(testgpe);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tfor (int i = 0; generatedTests != null && i < generatedTests.length; i++) {\n\t\t\t\tsadlTest = generatedTests[i];\n\t\t\t\tapplyImpliedProperties(sadlTest, tests.get(0));\n\t\t\t\tgetIfTranslator().postProcessTest(sadlTest, element);\n//\t\t\t\tICompositeNode node = NodeModelUtils.findActualNodeFor(element);\n//\t\t\t\tif (node != null) {\n//\t\t\t\t\t\ttest.setLineNo(node.getStartLine());\n//\t\t\t\t\t\ttest.setLength(node.getLength());\n//\t\t\t\t\t\ttest.setOffset(node.getOffset());\n//\t\t\t\t}\n\t\t\n\t\t\t\tlogger.debug(\"Test translation: {}\", sadlTest);\n\t\t\t\tList transErrors = getIfTranslator().getErrors();\n\t\t\t\tfor (int j = 0; transErrors != null && j < transErrors.size(); j++) {\n\t\t\t\t\tIFTranslationError err = transErrors.get(j);\n\t\t\t\t\ttry {\n\t\t\t\t\t\taddError(err.getLocalizedMessage(), element);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (Exception e) {\n\t\t\t\t\t\t// this will happen for standalone testing where there is no Eclipse Workspace\n\t\t\t\t\t\tlogger.error(\"Test: \" + sadlTest.toString());\n\t\t\t\t\t\tlogger.error(\" Translation error: \" + err.getLocalizedMessage() + \n\t\t\t\t\t\t\t\t(err.getCause() != null ? (\" (\" + err.getCause().getLocalizedMessage() + \")\") : \"\"));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tvalidateTest(element, sadlTest);\n\t\t\t\taddSadlCommand(sadlTest);\n\t\t\t}\n\t\t\treturn generatedTests;\n\t\t} catch (InvalidNameException e) {\n\t\t\taddError(SadlErrorMessages.INVALID_NAME.get(\"test\", e.getMessage()), element);\n\t\t\te.printStackTrace();\n\t\t} catch (InvalidTypeException e) {\n\t\t\taddError(SadlErrorMessages.INVALID_PROP_TYPE.get(e.getMessage()), element);\n\t\t\te.printStackTrace();\n\t\t} catch (TranslationException e) {\n\t\t\taddError(SadlErrorMessages.TEST_TRANSLATION_EXCEPTION.get(e.getMessage()), element);\n//\t\t\te.printStackTrace();\n\t\t}\n\t\treturn generatedTests;\n\t}\n\t\n\tprivate void applyImpliedProperties(Test sadlTest, Expression element) throws TranslationException {\n\t\tsadlTest.setLhs(applyImpliedPropertiesToSide(sadlTest.getLhs(), element));\n\t\tsadlTest.setRhs(applyImpliedPropertiesToSide(sadlTest.getRhs(), element));\n\t}\n\t\n\tprivate Object applyImpliedPropertiesToSide(Object side, Expression element) throws TranslationException {\n\t\tMap> impprops = OntModelProvider.getAllImpliedProperties(getCurrentResource());\n\t\tif (impprops != null) {\n\t\t\tIterator imppropitr = impprops.keySet().iterator();\n\t\t\twhile (imppropitr.hasNext()) {\n\t\t\t\tEObject eobj = imppropitr.next();\n\t\t\t\tString uri = null;\n\t\t\t\tif (eobj instanceof SadlResource) {\n\t\t\t\t\turi = getDeclarationExtensions().getConceptUri((SadlResource)eobj);\n\t\t\t\t}\n\t\t\t\telse if (eobj instanceof Name) {\n\t\t\t\t\turi = getDeclarationExtensions().getConceptUri(((Name)eobj).getName());\n\t\t\t\t}\n\t\t\t\tif (uri != null) {\n\t\t\t\t\tif (side instanceof NamedNode) {\n\t\t\t\t\t\tif (((NamedNode)side).toFullyQualifiedString().equals(uri)) {\n\t\t\t\t\t\t\tList props = impprops.get(eobj);\n\t\t\t\t\t\t\tif (props != null && props.size() > 0) {\n\t\t\t\t\t\t\t\tif (props.size() > 1) {\n\t\t\t\t\t\t\t\t\tthrow new TranslationException(\"More than 1 implied property found!\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t// apply impliedProperties\n\t\t\t\t\t\t\t\tNamedNode pred = new NamedNode(props.get(0).getURI());\n\t\t\t\t\t\t\t\tif (props.get(0) instanceof DatatypeProperty) {\n\t\t\t\t\t\t\t\t\tpred.setNodeType(NodeType.DataTypeProperty);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse if (props.get(0) instanceof ObjectProperty) {\n\t\t\t\t\t\t\t\t\tpred.setNodeType(NodeType.ObjectProperty);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\tpred.setNodeType(NodeType.PropertyNode);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn new TripleElement((NamedNode)side, pred, new VariableNode(getNewVar(element)));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn side;\t\t\n\t}\n\t\n\tpublic VariableNode createVariable(SadlResource sr) throws IOException, PrefixNotFoundException, InvalidNameException, InvalidTypeException, TranslationException, ConfigurationException {\n\t\tVariableNode var = createVariable(getDeclarationExtensions().getConceptUri(sr));\n\t\tif (var.getType() != null) {\n\t\t\treturn var;\t// all done\n\t\t}\n\t\tSadlResource decl = getDeclarationExtensions().getDeclaration(sr);\n\t\tEObject defnContainer = decl.eContainer();\n\t\ttry {\n\t\t\tTypeCheckInfo tci = null;\n\t\t\tif (defnContainer instanceof BinaryOperation) {\n\t\t\t\tif (((BinaryOperation)defnContainer).getLeft().equals(decl)) {\n\t\t\t\t\tExpression defn = ((BinaryOperation)defnContainer).getRight();\n\t\t\t\t\ttci = getModelValidator().getType(defn);\n\t\t\t\t}\n\t\t\t\telse if (((BinaryOperation)defnContainer).getLeft() instanceof PropOfSubject) {\n\t\t\t\t\ttci = getModelValidator().getType(((BinaryOperation)defnContainer).getLeft());\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (defnContainer instanceof SadlParameterDeclaration) {\n\t\t\t\tSadlTypeReference type = ((SadlParameterDeclaration)defnContainer).getType();\n\t\t\t\ttci = getModelValidator().getType(type);\n\t\t\t}\n\t\t\telse if (defnContainer instanceof SubjHasProp) {\n\t\t\t\tif (((SubjHasProp)defnContainer).getLeft().equals(decl)) {\n\t\t\t\t\t// need domain of property\n\t\t\t\t\tExpression pexpr = ((SubjHasProp)defnContainer).getProp();\n\t\t\t\t\tif (pexpr instanceof SadlResource) {\n\t\t\t\t\t\tString puri = getDeclarationExtensions().getConceptUri((SadlResource)pexpr);\n\t\t\t\t\t\tOntConceptType ptype = getDeclarationExtensions().getOntConceptType((SadlResource)pexpr);\n\t\t\t\t\t\tif (isProperty(ptype)) {\n\t\t\t\t\t\t\tProperty prop = getTheJenaModel().getProperty(puri);\n\t\t\t\t\t\t\ttci = getModelValidator().getTypeInfoFromDomain(new ConceptName(puri), prop, defnContainer);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\taddError(\"Right of SubjHasProp not handled (\" + ptype.toString() + \")\", defnContainer);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\taddError(\"Right of SubjHasProp not a Name (\" + pexpr.getClass().toString() + \")\", defnContainer);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (((SubjHasProp)defnContainer).getRight().equals(decl)) {\n\t\t\t\t\t// need range of property\n\t\t\t\t\ttci = getModelValidator().getType(((SubjHasProp)defnContainer).getProp());\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (!isContainedBy(sr, QueryStatement.class)) {\n\t\t\t\taddError(\"Unhandled variable definition\", sr);\n\t\t\t}\n\t\t\tif (tci != null && tci.getTypeCheckType() instanceof ConceptName) {\n\t\t\t\tif (var.getType() == null) {\n\t\t\t\t\tvar.setType(conceptNameToNamedNode((ConceptName)tci.getTypeCheckType()));\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (!var.getType().toFullyQualifiedString().equals(tci.getTypeCheckType().toString())) {\n\t\t\t\t\t\taddError(\"Changing type of variable '\" + var.getName() + \"' from '\" + var.getType().toFullyQualifiedString() + \"' to '\" + tci.getTypeCheckType().toString() + \"' not allowed.\", sr);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (URISyntaxException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t} catch (DontTypeCheckException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t} catch (CircularDefinitionException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t} catch (CircularDependencyException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t} catch (PropertyWithoutRangeException e) {\n\t\t\taddError(\"Property does not have a range\", defnContainer);\n\t\t}\n\t\treturn var;\n\t}\n\n\tprivate boolean isContainedBy(EObject eobj, Class cls) {\n\t\tif (eobj.eContainer() != null) {\n// TODO fix this to be generic\n\t\t\tif (eobj.eContainer() instanceof QueryStatement) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn isContainedBy(eobj.eContainer(), cls);\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprotected VariableNode createVariable(String name) throws IOException, PrefixNotFoundException, InvalidNameException, InvalidTypeException, TranslationException, ConfigurationException {\n\t\tObject trgt = getTarget();\n\t\tif (trgt instanceof Rule) {\n\t\t\tif (((Rule)trgt).getVariable(name) != null) {\n\t\t\t\treturn ((Rule)trgt).getVariable(name);\n\t\t\t}\n\t\t}\n\t\telse if (trgt instanceof Query) {\n\t\t\tif (((Query)trgt).getVariable(name) != null) {\n\t\t\t\treturn ((Query)trgt).getVariable(name);\n\t\t\t}\n\t\t}\n\t\telse if (trgt instanceof Test) {\n\t\t\t// TODO\n\t\t}\n\t\tVariableNode newVar = new VariableNode(name);\n\t\tif (trgt instanceof Rule) {\n\t\t\t((Rule)trgt).addRuleVariable(newVar);\n\t\t}\n\t\telse if (trgt instanceof Query) {\n\t\t\t((Query)trgt).addVariable(newVar);\n\t\t}\n\t\telse if (trgt instanceof Test) {\n\t\t\t// TODO\n\t\t}\n\t\treturn newVar;\n\t}\n\t\n\tprivate boolean containsMultipleTests(List testtrans) {\n\t\tif (testtrans.size() == 1) {\n\t\t\treturn false;\n\t\t}\n\t\tList vars = new ArrayList();\n\t\tfor (int i = 0; i < testtrans.size(); i++) {\n\t\t\tGraphPatternElement gpe = testtrans.get(i);\n\t\t\tif (gpe instanceof TripleElement) {\n\t\t\t\tNode anode = ((TripleElement)gpe).getSubject();\n\t\t\t\tif (vars.contains(anode)) {\n\t\t\t\t\treturn false; // there are vars between patterns\n\t\t\t\t}\n\t\t\t\telse if (anode instanceof VariableNode) {\n\t\t\t\t\tvars.add((VariableNode) anode);\n\t\t\t\t}\n\t\t\t\tanode = ((TripleElement)gpe).getObject();\n\t\t\t\tif (vars.contains(anode)) {\n\t\t\t\t\treturn false; // there are vars between patterns\n\t\t\t\t}\n\t\t\t\telse if (anode instanceof VariableNode){\n\t\t\t\t\tvars.add((VariableNode) anode);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (gpe instanceof BuiltinElement) {\n\t\t\t\tList args = ((BuiltinElement)gpe).getArguments();\n\t\t\t\tfor (int j = 0; args != null && j < args.size(); j++) {\n\t\t\t\t\tNode anode = args.get(j);\n\t\t\t\t\tif (anode instanceof VariableNode && vars.contains(anode)) {\n\t\t\t\t\t\treturn false; // there are vars between patterns\n\t\t\t\t\t}\n\t\t\t\t\telse if (anode instanceof VariableNode) {\n\t\t\t\t\t\tvars.add((VariableNode) anode);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n private boolean changeFilterDirection(Object patterns) {\n\t\tif (patterns instanceof List) {\n\t\t\tfor (int i = 0; i < ((List)patterns).size(); i++) {\n\t\t\t\tObject litem = ((List)patterns).get(i);\n\t\t\t\tif (litem instanceof BuiltinElement) {\n\t\t\t\t\tIntermediateFormTranslator.builtinComparisonComplement((BuiltinElement)litem);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate int validateTest(EObject object, Test test) {\n\t\tint numErrors = 0;\n\t\tObject lhs = test.getLhs();\n\t\tif (lhs instanceof GraphPatternElement) {\n\t\t\tnumErrors += validateGraphPatternElement(object, (GraphPatternElement)lhs);\n\t\t}\n\t\telse if (lhs instanceof List) {\n\t\t\tfor (int i = 0; i < ((List)lhs).size(); i++) {\n\t\t\t\tObject lhsinst = ((List)lhs).get(i);\n\t\t\t\tif (lhsinst instanceof GraphPatternElement) {\n\t\t\t\t\tnumErrors += validateGraphPatternElement(object, (GraphPatternElement)lhsinst);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tObject rhs = test.getLhs();\n\t\tif (rhs instanceof GraphPatternElement) {\n\t\t\tnumErrors += validateGraphPatternElement(object, (GraphPatternElement)rhs);\n\t\t}\n\t\telse if (rhs instanceof List) {\n\t\t\tfor (int i = 0; i < ((List)rhs).size(); i++) {\n\t\t\t\tObject rhsinst = ((List)rhs).get(i);\n\t\t\t\tif (rhsinst instanceof GraphPatternElement) {\n\t\t\t\t\tnumErrors += validateGraphPatternElement(object, (GraphPatternElement)rhsinst);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn numErrors;\n\t}\n\t\n /**\n * This method checks a GraphPatternElement for errors and warnings and generates the same if found.\n * \n * @param gpe\n * @return\n */\n private int validateGraphPatternElement(EObject object, GraphPatternElement gpe) {\n \tint numErrors = 0;\n\t\tif (gpe instanceof TripleElement) {\n\t\t\tif (((TripleElement) gpe).getSubject() instanceof NamedNode &&\n\t\t\t\t\t((NamedNode)((TripleElement)gpe).getSubject()).getNodeType().equals(NodeType.PropertyNode)) {\n\t\t\t\taddError(SadlErrorMessages.UNEXPECTED_TRIPLE.get(((NamedNode)((TripleElement)gpe).getSubject()).getName()), object);\n\t\t\t\tnumErrors++;\n\t\t\t}\n\t\t\tif (((TripleElement) gpe).getObject() instanceof NamedNode &&\n\t\t\t\t\t((NamedNode)((TripleElement)gpe).getObject()).getNodeType().equals(NodeType.PropertyNode)) {\n\t\t\t\tif (!(((TripleElement)gpe).getPredicate() instanceof NamedNode) || \n\t\t\t\t\t\t!((NamedNode)((TripleElement)gpe).getPredicate()).getNamespace().equals(OWL.NAMESPACE.getNameSpace())) {\n\t\t\t\t\taddError(SadlErrorMessages.UNEXPECTED_TRIPLE.get(((NamedNode)((TripleElement)gpe).getSubject()).getName()), object);\n\t\t\t\t\tnumErrors++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (((TripleElement) gpe).getPredicate() instanceof NamedNode &&\n\t\t\t\t\t!(((NamedNode)((TripleElement)gpe).getPredicate()).getNodeType().equals(NodeType.PropertyNode)) &&\n\t\t\t\t\t!(((NamedNode)((TripleElement)gpe).getPredicate()).getNodeType().equals(NodeType.ObjectProperty)) &&\n\t\t\t\t\t!(((NamedNode)((TripleElement)gpe).getPredicate()).getNodeType().equals(NodeType.DataTypeProperty))) {\n\t\t\t\tif (((NamedNode)((TripleElement)gpe).getPredicate()).getNodeType().equals(NodeType.VariableNode)) {\n\t\t\t\t\taddWarning(SadlErrorMessages.VARIABLE_INSTEAD_OF_PROP.get(((NamedNode)((TripleElement)gpe).getPredicate()).getName()), object);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\taddError(SadlErrorMessages.EXPECTED_A.get(\"property as triple pattern predicate rather than \" + \n\t\t\t\t\t\t\t((NamedNode)((TripleElement)gpe).getPredicate()).getNodeType().toString() + \" \" + \n\t\t\t\t\t\t\t((NamedNode)((TripleElement)gpe).getPredicate()).getName()), object);\n\t\t\t\t\tnumErrors++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if (gpe instanceof BuiltinElement) {\n\t\t\tif (((BuiltinElement)gpe).getFuncType().equals(BuiltinType.Not)) {\n\t\t\t\tList args = ((BuiltinElement)gpe).getArguments();\n\t\t\t\tif (args != null && args.size() == 1 && args.get(0) instanceof KnownNode) {\n\t\t\t\t\taddError(SadlErrorMessages.PHRASE_NOT_KNOWN.toString(), object);\n\t\t\t\t\taddError(\"Phrase 'not known' is not a valid graph pattern; did you mean 'is not known'?\", object);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (gpe.getNext() != null) {\n\t\t\tnumErrors += validateGraphPatternElement(object, gpe.getNext());\n\t\t}\n\t\treturn numErrors;\n\t}\n \n\tprivate void processStatement(ExplainStatement element) throws JenaProcessorException, InvalidNameException, InvalidTypeException, TranslationException {\n\t\tString ruleName = element.getRulename() != null ? declarationExtensions.getConcreteName(element.getRulename()) : null;\n\t\tif (ruleName != null) {\n\t\t\tExplain cmd = new Explain(ruleName);\n\t\t\taddSadlCommand(cmd);\n\t\t}\n\t\telse {\n\t\t\tObject result = processExpression(element.getExpr());\n\t\t\tif (result instanceof GraphPatternElement) {\n\t\t\t\tExplain cmd = new Explain((GraphPatternElement)result);\n\t\t\t\taddSadlCommand(cmd);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthrow new TranslationException(\"Unhandled ExplainStatement: \" + result.toString());\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprivate void processStatement(StartWriteStatement element) throws JenaProcessorException {\n\t\tString dataOnly = element.getDataOnly();\n\t\tStartWrite cmd = new StartWrite(dataOnly != null);\n\t\taddSadlCommand(cmd);\n\t}\n\t\n\tprivate void processStatement(EndWriteStatement element) throws JenaProcessorException {\n\t\tString outputFN = element.getFilename();\n\t\tEndWrite cmd = new EndWrite(outputFN);\n\t\taddSadlCommand(cmd);\n\t}\n\t\n\tprivate void processStatement(ReadStatement element) throws JenaProcessorException {\n\t\tString filename = element.getFilename();\n\t\tString templateFilename = element.getTemplateFilename();\n\t\tRead readCmd = new Read(filename, templateFilename);\n\t\taddSadlCommand(readCmd);\n\t}\n\t\n\tprivate void processStatement(PrintStatement element) throws JenaProcessorException {\n\t\tString dispStr = ((PrintStatement)element).getDisplayString();\n\t\tPrint print = new Print(dispStr);\n\t\tString mdl = ((PrintStatement)element).getModel();\n\t\tif (mdl != null) {\n\t\t\tprint.setModel(mdl);\n\t\t}\n\t\taddSadlCommand(print);\n\t}\n\t\n\tpublic Query processStatement(QueryStatement element) throws JenaProcessorException, InvalidNameException, InvalidTypeException, TranslationException, CircularDefinitionException {\n\t\tExpression qexpr = element.getExpr();\n\t\tif (qexpr != null) {\n\t\t\tif (qexpr instanceof Name) {\n\t\t\t\tOntConceptType qntype = getDeclarationExtensions().getOntConceptType(((Name)qexpr).getName());\n\t\t\t\tif (qntype.equals(OntConceptType.STRUCTURE_NAME)) {\n\t\t\t\t\t// this is just a named query declared elsewhere\n\t\t\t\t\tSadlResource qdecl = getDeclarationExtensions().getDeclaration(((Name)qexpr).getName());\n\t\t\t\t\tEObject qdeclcont = qdecl.eContainer();\n\t\t\t\t\tif (qdeclcont instanceof QueryStatement) {\n\t\t\t\t\t\tqexpr = ((QueryStatement)qdeclcont).getExpr();\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\taddError(\"Unexpected named structure name whose definition is not a query statement\", qexpr);\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tObject qobj = processExpression(qexpr);\n\t\t\tQuery query = null;\n\t\t\tif (qobj instanceof Query) {\n\t\t\t\tquery = (Query) qobj;\n\t\t\t}\n\t\t\telse if (qobj == null) {\n\t\t\t\t// maybe this is a query by name?\n\t\t\t\tif (qexpr instanceof Name) {\n\t\t\t\t\t SadlResource qnm = ((Name)qexpr).getName();\n\t\t\t\t\t String qnmuri = getDeclarationExtensions().getConceptUri(qnm);\n\t\t\t\t\t if (qnmuri != null) {\n\t\t\t\t\t\t Individual qinst = getTheJenaModel().getIndividual(qnmuri);\n\t\t\t\t\t\t if (qinst != null) {\n\t\t\t\t\t\t\t StmtIterator stmtitr = qinst.listProperties();\n\t\t\t\t\t\t\t while (stmtitr.hasNext()) {\n\t\t\t\t\t\t\t\t System.out.println(stmtitr.nextStatement().toString());\n\t\t\t\t\t\t\t }\n\t\t\t\t\t\t }\n\t\t\t\t\t }\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tquery = processQuery(qobj);\n\t\t\t}\n\t\t\tif (query != null) {\n\t\t\t\tif (element.getName() != null) {\n\t\t\t\t\tString uri = declarationExtensions.getConceptUri(element.getName());\n\t\t\t\t\tquery.setFqName(uri);\n\t\t\t\t\tOntClass nqcls = getTheJenaModel().getOntClass(SadlConstants.SADL_IMPLICIT_MODEL_NAMEDQUERY_CLASS_URI);\n\t\t\t\t\tif (nqcls != null) {\n\t\t\t\t\t\tIndividual nqry = getTheJenaModel().createIndividual(uri, nqcls);\n\t\t\t\t\t\t// Add annotations, if any\n\t\t\t\t\t\tEList annotations = element.getAnnotations();\n\t\t\t\t\t\tif (annotations != null && annotations.size() > 0) {\n\t\t\t\t\t\t\taddNamedStructureAnnotations(nqry, annotations);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\t\t\t\t\n\t\t\t\t}\n\t\t\t\tif (element.getStart().equals(\"Graph\")) {\n\t\t\t\t\tquery.setGraph(true);\n\t\t\t\t}\n\t\t\t\tfinal ICompositeNode node = NodeModelUtils.findActualNodeFor(element);\n\t\t\t\tif (node != null) {\n\t\t\t\t\tquery.setOffset(node.getOffset() - 1);\n\t\t\t\t\tquery.setLength(node.getLength());\n\t\t\t\t}\n\t\t\t\tquery = addExpandedPropertiesToQuery(query, qexpr);\n\t\t\t\taddSadlCommand(query);\n\t\t\t\treturn query;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t// this is a reference to a named query defined elsewhere\n\t\t\tSadlResource sr = element.getName();\n\t\t\tSadlResource sr2 = declarationExtensions.getDeclaration(sr);\n\t\t\tif (sr2 != null) {\n\t\t\tEObject cont = sr2.eContainer();\n\t\t\t\tif (cont instanceof QueryStatement && ((QueryStatement)cont).getExpr() != null) {\n\t\t\t\t\treturn processStatement((QueryStatement)cont);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\tprivate Query addExpandedPropertiesToQuery(Query query, Expression expr) {\n\t\tList vars = query.getVariables();\n\t\tList elements = query.getPatterns();\n\t\tif (elements != null) {\n\t\t\tList triplesToAdd = null;\n\t\t\tfor (GraphPatternElement e: elements) {\n\t\t\t\tif (e instanceof TripleElement) {\n\t\t\t\t\tNode subj = ((TripleElement)e).getSubject();\n\t\t\t\t\tNode obj = ((TripleElement)e).getObject();\n\t\t\t\t\tboolean implicitObject = false;\n\t\t\t\t\tif (obj == null) {\n\t\t\t\t\t\tobj = new VariableNode(getIfTranslator().getNewVar());\n\t\t\t\t\t\t((TripleElement) e).setObject(obj);\n\t\t\t\t\t\timplicitObject = true;\n\t\t\t\t\t}\n\t\t\t\t\tif (implicitObject || obj instanceof VariableNode) {\n\t\t\t\t\t\tVariableNode vn = (VariableNode) ((TripleElement)e).getObject();\n\t\t\t\t\t\t//\t\t\t\t\tif (vars != null && vars.contains(vn.getName())) {\n\t\t\t\t\t\tNode pred = ((TripleElement)e).getPredicate();\n\t\t\t\t\t\tConceptName predcn = new ConceptName(pred.toFullyQualifiedString());\n\t\t\t\t\t\tProperty predProp = getTheJenaModel().getProperty(pred.toFullyQualifiedString());\n\t\t\t\t\t\tsetPropertyConceptNameType(predcn, predProp);\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tTypeCheckInfo tci = getModelValidator().getTypeInfoFromRange(predcn, predProp, null);\n\t\t\t\t\t\t\tif (tci != null) {\n\t\t\t\t\t\t\t\tConceptIdentifier tct = tci.getTypeCheckType();\n\t\t\t\t\t\t\t\tif (tct instanceof ConceptName) {\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\tOntClass rngcls = getTheJenaModel().getOntClass(((ConceptName)tct).getUri());\n\t\t\t\t\t\t\t\t\t\tif (rngcls != null) {\n\t\t\t\t\t\t\t\t\t\t\tList expandedProps = getExpandedProperties(rngcls);\n\t\t\t\t\t\t\t\t\t\t\tif (expandedProps != null) {\n\t\t\t\t\t\t\t\t\t\t\t\tfor (int i = 0; i < expandedProps.size(); i++) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tString epstr = expandedProps.get(i);\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (!subjPredMatch(elements, vn, epstr)) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tNamedNode propnode = new NamedNode(epstr, NodeType.ObjectProperty);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tString vnameprefix = (subj instanceof NamedNode) ? ((NamedNode)subj).getName() : \"x\";\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (pred instanceof NamedNode) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tvnameprefix += \"_\" + ((NamedNode)pred).getName();\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tVariableNode newvar = new VariableNode(vnameprefix + \"_\" + propnode.getName()); //getIfTranslator().getNewVar());\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tTripleElement newtriple = new TripleElement(vn, propnode, newvar);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (vars == null) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tvars = new ArrayList();\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tquery.setVariables(vars);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tvars.add(newvar);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (triplesToAdd == null) triplesToAdd = new ArrayList();\n\t\t\t\t\t\t\t\t\t\t\t\t\t\ttriplesToAdd.add(newtriple);\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t} catch (InvalidNameException e1) {\n\t\t\t\t\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\t\t\t\t\te1.printStackTrace();\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (DontTypeCheckException e1) {\n\t\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\t\te1.printStackTrace();\n\t\t\t\t\t\t} catch (InvalidTypeException e1) {\n\t\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\t\te1.printStackTrace();\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//\t\t\t\t\t}\n\t\t\t\t\t\tcatch (TranslationException e2) {\n\t\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\t\te2.printStackTrace();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (triplesToAdd == null && implicitObject) {\n\t\t\t\t\t\tquery.getVariables().add(((VariableNode)obj));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (triplesToAdd != null) {\n\t\t\t\tfor (int i = 0; i < triplesToAdd.size(); i++) {\n\t\t\t\t\tquery.addPattern(triplesToAdd.get(i));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn query;\n\t}\n\t\n\tpublic void setPropertyConceptNameType(ConceptName predcn, Property predProp) {\n\t\tif (predProp instanceof ObjectProperty) {\n\t\t\tpredcn.setType(ConceptType.OBJECTPROPERTY);\n\t\t}\n\t\telse if (predProp instanceof DatatypeProperty) {\n\t\t\tpredcn.setType(ConceptType.DATATYPEPROPERTY);\n\t\t}\n\t\telse if (predProp instanceof AnnotationProperty) {\n\t\t\tpredcn.setType(ConceptType.ANNOTATIONPROPERTY);\n\t\t}\n\t\telse {\n\t\t\tpredcn.setType(ConceptType.RDFPROPERTY);\n\t\t}\n\t}\n\t\n\tprivate boolean subjPredMatch(List elements, VariableNode vn, String epstr) {\n\t\tfor (int i = 0; elements != null && i < elements.size(); i++) {\n\t\t\tGraphPatternElement gp = elements.get(i);\n\t\t\tif (gp instanceof TripleElement) {\n\t\t\t\tTripleElement tr = (TripleElement)gp;\n\t\t\t\tif (tr.getSubject().equals(vn) && tr.getPredicate().toFullyQualifiedString().equals(epstr)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tpublic Query processExpression(SelectExpression expr) throws InvalidNameException, InvalidTypeException, TranslationException {\n\t\treturn processAsk(expr);\n\t}\n\t\n\tpublic Query processExpression(ConstructExpression expr) throws InvalidNameException, InvalidTypeException, TranslationException {\n\t\treturn processAsk(expr);\n\t}\n\t\n\tpublic Query processExpression(AskExpression expr) throws InvalidNameException, InvalidTypeException, TranslationException {\n\t\treturn processAsk(expr);\n\t}\n\t\n\tprivate Query processAsk(Expression expr) {\n\t\tQuery query = new Query();\n\t\tquery.setContext(expr);\n\t\tsetTarget(query);\n//\t\tif (parent != null) {\n//\t\t\tgetIfTranslator().setEncapsulatingTarget(parent);\n//\t\t}\n\t\t\n\t\t// get variables and other information from the SelectExpression\n\t\tEList varList = null;\n\t\tExpression whexpr = null;\n\t\tif (expr instanceof SelectExpression) {\n\t\t\twhexpr = ((SelectExpression) expr).getWhereExpression();\n\t\t\tquery.setKeyword(\"select\");\n\t\t\tif (((SelectExpression)expr).isDistinct()) {\n\t\t\t\tquery.setDistinct(true);\n\t\t\t}\n\t\t\tvarList = ((SelectExpression)expr).getSelectFrom();\n\t\t\tif (varList != null) {\n\t\t\t\tList names = new ArrayList();\n\t\t\t\tfor (int i = 0; i < varList.size(); i++) {\n\t\t\t\t\tObject var = null;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tvar = processExpression(varList.get(i));\n\t\t\t\t\t} catch (TranslationException e2) {\n\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\te2.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t\tTypeCheckInfo tci = null;\n\t\t\t\t\ttry {\n\t\t\t\t\t\ttci = modelValidator.getType(varList.get(i));\n\t\t\t\t\t} catch (DontTypeCheckException e1) {\n\t\t\t\t\t\t// OK to not type check\n\t\t\t\t\t} catch (CircularDefinitionException e1) {\n\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\te1.printStackTrace();\n\t\t\t\t\t} catch (URISyntaxException e1) {\n\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\te1.printStackTrace();\n\t\t\t\t\t} catch (IOException e1) {\n\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\te1.printStackTrace();\n\t\t\t\t\t} catch (ConfigurationException e1) {\n\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\te1.printStackTrace();\n\t\t\t\t\t} catch (CircularDependencyException e) {\n\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t} catch (PropertyWithoutRangeException e) {\n\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t} catch (InvalidNameException e) {\n\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t} catch (TranslationException e) {\n\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t} catch (InvalidTypeException e) {\n\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t\tif (!(var instanceof VariableNode)) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tOntConceptType vtype = getDeclarationExtensions().getOntConceptType(varList.get(i));\n\t\t\t\t\t\t\tif (vtype.equals(OntConceptType.VARIABLE)) {\n\t\t\t\t\t\t\t\tint k = 0;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (CircularDefinitionException e) {\n\t\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t\t}\n//\t\t\t\t\t\tthrow new InvalidNameException(\"'\" + var.toString() + \"' isn't a variable as expected in query select names.\");\n\t\t\t\t\t\tif (var != null) {\n\t\t\t\t\t\t\taddError(SadlErrorMessages.QUERY_ISNT_VARIABLE.get(var.toString()), expr);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tnames.add(((VariableNode)var));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tquery.setVariables(names);\n\t\t\t}\n\t\t\tif (((SelectExpression)expr).getOrderby() != null) {\n\t\t\t\tEList ol = ((SelectExpression)expr).getOrderList();\n\t\t\t\tList orderingPairs = new ArrayList();\n\t\t\t\tfor (int i = 0; i < ol.size(); i++) {\n\t\t\t\t\tOrderElement oele = ol.get(i);\n\t\t\t\t\tSadlResource ord = oele.getOrderBy();\n\t\t\t\t\torderingPairs.add(query.new OrderingPair(getDeclarationExtensions().getConcreteName(ord), \n\t\t\t\t\t\t\t(oele.isDesc() ? Order.DESC : Order.ASC)));\n\t\t\t\t}\n\t\t\t\tquery.setOrderBy(orderingPairs);\n\t\t\t}\n\t\t}\n\t\telse if (expr instanceof ConstructExpression) {\n\t\t\twhexpr = ((ConstructExpression) expr).getWhereExpression();\n\t\t\tquery.setKeyword(\"construct\");\n\t\t\tList names = new ArrayList();\n\t\t\ttry {\n\t\t\t\tObject result = processExpression(((ConstructExpression)expr).getSubj());\n\t\t\t\tif (result instanceof VariableNode) {\n\t\t\t\t\tnames.add(((VariableNode) result));\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tnames.add(createVariable(result.toString()));\n\t\t\t\t}\n\t\t\t\tresult = processExpression(((ConstructExpression)expr).getPred());\n\t\t\t\tif (result instanceof VariableNode) {\n\t\t\t\t\tnames.add((VariableNode) result);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tnames.add(createVariable(result.toString()));\n\t\t\t\t}\n\t\t\t\tresult = processExpression(((ConstructExpression)expr).getObj());\n\t\t\t\tif (result instanceof VariableNode) {\n\t\t\t\t\tnames.add(((VariableNode) result));\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tnames.add(createVariable(result.toString()));\n\t\t\t\t}\n\t\t\t\tif (names.size() != 3) {\n\t\t\t\t\taddWarning(\"A 'construct' statement should have 3 variables so as to be able to generate a graph.\", expr);\n\t\t\t\t}\n\t\t\t\tquery.setVariables(names);\n\t\t\t} catch (InvalidNameException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (InvalidTypeException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (TranslationException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (IOException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (PrefixNotFoundException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (ConfigurationException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\telse if (expr instanceof AskExpression) {\n\t\t\twhexpr = ((AskExpression) expr).getWhereExpression();\n\t\t\tquery.setKeyword(\"ask\");\n\t\t}\n\n\t\t// Translate the query to the resulting intermediate form.\n\t\tif (modelValidator != null) {\n\t\t\ttry {\n\t\t\t\tTypeCheckInfo tct = modelValidator.getType(whexpr);\n\t\t\t\tif (tct != null && tct.getImplicitProperties() != null) {\n\t\t\t\t\tList ips = tct.getImplicitProperties();\n\t\t\t\t\tint i = 0;\n\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} catch (IOException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (ConfigurationException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (DontTypeCheckException e) {\n\t\t\t\t// OK to not be able to type check\n\t\t\t} catch (CircularDefinitionException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (CircularDependencyException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (PropertyWithoutRangeException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (InvalidNameException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (TranslationException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (InvalidTypeException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\tObject pattern = null;\n\t\ttry {\n\t\t\tpattern = processExpression(whexpr);\n\t\t} catch (InvalidNameException e1) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te1.printStackTrace();\n\t\t} catch (InvalidTypeException e1) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te1.printStackTrace();\n\t\t} catch (TranslationException e1) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te1.printStackTrace();\n\t\t}\n\t\t\n\t\tObject expandedPattern = null;\n\t\ttry {\n\t\t\texpandedPattern = getIfTranslator().expandProxyNodes(pattern, false, true);\n\t\t} catch (InvalidNameException e) {\n\t\t\taddError(SadlErrorMessages.INVALID_NAME.get(\"query\", pattern.toString()), expr);\n\t\t\te.printStackTrace();\n\t\t} catch (InvalidTypeException e) {\n\t\t\taddError(SadlErrorMessages.INVALID_TYPE.get(\"query\", pattern.toString()), expr);\n\t\t\te.printStackTrace();\n\t\t} catch (TranslationException e) {\n\t\t\taddError(SadlErrorMessages. TRANSLATION_ERROR.get(\"query\", pattern.toString()), expr);\n\t\t\te.printStackTrace();\n\t\t}\n\t\tif (expandedPattern != null && expandedPattern instanceof List && ((List)expandedPattern).size() > 0) {\n\t\t\tpattern = expandedPattern;\n\t\t}\n\t\t\n\t\tif (pattern instanceof List) {\n\t\t\tif (query.getVariables() == null) {\n\t\t\t\tSet nodes = getIfTranslator().getSelectVariables((List)pattern);\n\t\t\t\tif (nodes != null && nodes.size() > 0) {\n\t\t\t\t\tList names = new ArrayList(1);\n\t\t\t\t\tfor (VariableNode node : nodes) {\n\t\t\t\t\t\tnames.add(node);\n\t\t\t\t\t}\n\t\t\t\t\tquery.setVariables(names);\n\t\t\t\t\tif (query.getKeyword() == null) {\n\t\t\t\t\t\tquery.setKeyword(\"select\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// no variables, assume an ask\n\t\t\t\t\tif (query.getKeyword() == null) {\n\t\t\t\t\t\tquery.setKeyword(\"ask\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tquery.setPatterns((List) pattern);\n\t\t}\n\t\telse if (pattern instanceof Literal) {\n\t\t\t// this must be a SPARQL query\n\t\t\tquery.setSparqlQueryString(((Literal)pattern).getValue().toString());\n\t\t}\n\t\tlogger.debug(\"Ask translation: {}\", query);\n\t\treturn query;\n\t}\n\n\tprivate Query processQuery(Object qobj) throws JenaProcessorException {\n\t\tString qstr = null;\n\t\tQuery q = new Query();\n\t\tsetTarget(q);\n\t\tif (qobj instanceof com.ge.research.sadl.model.gp.Literal) {\n\t\t\tqstr = ((com.ge.research.sadl.model.gp.Literal)qobj).getValue().toString();\n\t\t\tq.setSparqlQueryString(qstr);\n\t\t}\n\t\telse if (qobj instanceof String) {\n\t\t\tqstr = qobj.toString();\n\t\t\tq.setSparqlQueryString(qstr);\n\t\t}\n\t\telse if (qobj instanceof NamedNode) {\n\t\t\tif (isProperty(((NamedNode)qobj).getNodeType())) {\n\t\t\t\tVariableNode sn = new VariableNode(getIfTranslator().getNewVar());\n\t\t\t\tTripleElement tr = new TripleElement(sn, (Node) qobj, null);\n\t\t\t\tq.addPattern(tr);\n\t\t\t\tList vars = q.getVariables();\n\t\t\t\tif (vars == null) {\n\t\t\t\t\tvars = new ArrayList();\n\t\t\t\t\tq.setVariables(vars);\n\t\t\t\t}\n\t\t\t\tq.getVariables().add(sn);\n\t\t\t}\n\t\t}\n\t\telse if (qobj instanceof TripleElement) {\n\t\t\tSet vars = getIfTranslator().getSelectVariables((GraphPatternElement) qobj);\n\t\t\tList errs = getIfTranslator().getErrors();\n\t\t\tif (errs == null || errs.size() == 0) {\n\t\t\t\tif (vars != null && vars.size() > 0) {\n\t\t\t\t\tList varNames = new ArrayList();\n\t\t\t\t\tIterator vitr = vars.iterator();\n\t\t\t\t\twhile (vitr.hasNext()) {\n\t\t\t\t\t\tvarNames.add(vitr.next());\n\t\t\t\t\t}\n\t\t\t\t\tq.setVariables(varNames);\n\t\t\t\t}\n\t\t\t\tq.addPattern((GraphPatternElement) qobj);\n\t\t\t}\n\t\t}\n\t\telse if (qobj instanceof BuiltinElement) {\n\t\t\tString fn = ((BuiltinElement)qobj).getFuncName();\n\t\t\tList args = ((BuiltinElement)qobj).getArguments();\n\t\t\tint i = 0;\n\t\t}\n\t\telse if (qobj instanceof Junction) {\n\t\t\tq.addPattern((Junction)qobj);\n\t\t}\n\t\telse {\n\t\t\tthrow new JenaProcessorException(\"Unexpected query type: \" + qobj.getClass().getCanonicalName());\n\t\t}\n\t\tsetTarget(null);\n\t\treturn q;\n\t}\n\t\n\tpublic void processStatement(EquationStatement element) throws JenaProcessorException, InvalidNameException, InvalidTypeException, TranslationException {\n\t\tSadlResource nm = element.getName();\n\t\tEList params = element.getParameter();\n\t\tSadlTypeReference rtype = element.getReturnType();\n\t\tExpression bdy = element.getBody();\n\t\tEquation eq = createEquation(nm, rtype, params, bdy);\n\t\taddEquation(element.eResource(), eq, nm);\n\t\tIndividual eqinst = getTheJenaModel().createIndividual(getDeclarationExtensions().getConceptUri(nm), \n\t\t\t\tgetTheJenaModel().getOntClass(SadlConstants.SADL_BASE_MODEL_EQUATION_URI));\n\t\tDatatypeProperty dtp = getTheJenaModel().getDatatypeProperty(SadlConstants.SADL_BASE_MODEL_EQ_EXPRESSION_URI);\n\t\tLiteral literal = getTheJenaModel().createTypedLiteral(eq.toString());\n\t\tif (eqinst != null && dtp != null) {\n\t\t\t// these can be null during clean/build with resource open in editor\n\t\t\teqinst.addProperty(dtp, literal);\n\t\t}\n\t}\n\t\n\tprotected Equation createEquation(SadlResource nm, SadlTypeReference rtype, EList params,\n\t\t\tExpression bdy)\n\t\t\tthrows JenaProcessorException, TranslationException, InvalidNameException, InvalidTypeException {\n\t\tEquation eq = new Equation(getDeclarationExtensions().getConcreteName(nm));\n\t\teq.setNamespace(getDeclarationExtensions().getConceptNamespace(nm));\n\t\tNode rtnode = sadlTypeReferenceToNode(rtype);\n\t\teq.setReturnType(rtnode);\n\t\tif (params != null && params.size() > 0) {\n\t\t\tList args = new ArrayList();\n\t\t\tList argtypes = new ArrayList();\n\t\t\tfor (int i = 0; i < params.size(); i++) {\n\t\t\t\tSadlParameterDeclaration param = params.get(i);\n\t\t\t\tSadlResource pr = param.getName();\n\t\t\t\tObject pn = processExpression(pr);\n\t\t\t\targs.add((Node) pn);\n\t\t\t\tSadlTypeReference prtype = param.getType();\n\t\t\t\tNode prtnode = sadlTypeReferenceToNode(prtype); \n\t\t\t\targtypes.add(prtnode);\n\t\t\t}\n\t\t\teq.setArguments(args);\n\t\t\teq.setArgumentTypes(argtypes);\n\t\t}\n\t\t// put equation in context for sub-processing\n\t\tsetCurrentEquation(eq);\n\t\tObject bdyobj = processExpression(bdy);\n\t\tif (bdyobj instanceof List) {\n\t\t\teq.setBody((List) bdyobj);\n\t\t}\n\t\telse if (bdyobj instanceof GraphPatternElement) {\n\t\t\teq.addBodyElement((GraphPatternElement)bdyobj);\n\t\t}\n\t\tif (getModelValidator() != null) {\n\t\t\t// check return type against body expression\n\t\t\tStringBuilder errorMessageBuilder = new StringBuilder();\n\t\t\tif (!getModelValidator().validate(rtype, bdy, \"function return\", errorMessageBuilder)) {\n\t\t\t\taddIssueToAcceptor(errorMessageBuilder.toString(), bdy);\n\t\t\t}\n\t\t}\n\t\tsetCurrentEquation(null);\t// clear\n\t\tlogger.debug(\"Equation: \" + eq.toFullyQualifiedString());\n\t\treturn eq;\n\t}\n\t\n\tpublic void addIssueToAcceptor(String message, EObject expr) {\n\t\tif (isTypeCheckingWarningsOnly()) {\n\t\t\tissueAcceptor.addWarning(message, expr);\n\t\t}\n\t\telse {\n\t\t\tissueAcceptor.addError(message, expr);\n\t\t}\n\t}\n\t\n\tprotected void processStatement(ExternalEquationStatement element) throws JenaProcessorException, InvalidNameException, InvalidTypeException, TranslationException {\n\t\tString uri = element.getUri();\n//\t\tif(uri.equals(SadlConstants.SADL_BUILTIN_FUNCTIONS_URI)){\n//\t\t\treturn;\n//\t\t}\n\t\tSadlResource nm = element.getName();\n\t\tEList params = element.getParameter();\n\t\tSadlTypeReference rtype = element.getReturnType();\n\t\tString location = element.getLocation();\n\t\tEquation eq = createExternalEquation(nm, uri, rtype, params, location);\n\t\taddEquation(element.eResource(), eq, nm);\n\t\tIndividual eqinst = getTheJenaModel().createIndividual(getDeclarationExtensions().getConceptUri(nm), \n\t\t\t\tgetTheJenaModel().getOntClass(SadlConstants.SADL_BASE_MODEL_EXTERNAL_URI));\n\t\tDatatypeProperty dtp = getTheJenaModel().getDatatypeProperty(SadlConstants.SADL_BASE_MODEL_EXTERNALURI_URI);\n\t\tLiteral literal = uri != null ? getTheJenaModel().createTypedLiteral(uri) : null;\n\t\tif (eqinst != null && dtp != null && literal != null) {\n\t\t\t// these can be null if a resource is open in the editor and a clean/build is performed\n\t\t\teqinst.addProperty(dtp,literal);\n\t\t\tif (location != null && location.length() > 0) {\n\t\t\t\tDatatypeProperty dtp2 = getTheJenaModel().getDatatypeProperty(SadlConstants.SADL_BASE_MODEL_EXTERNALURI_LOCATIOIN);\n\t\t\t\tLiteral literal2 = getTheJenaModel().createTypedLiteral(location);\n\t\t\t\teqinst.addProperty(dtp2, literal2);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprotected Equation createExternalEquation(SadlResource nm, String uri, SadlTypeReference rtype,\n\t\t\tEList params, String location)\n\t\t\tthrows JenaProcessorException, TranslationException, InvalidNameException {\n\t\tEquation eq = new Equation(getDeclarationExtensions().getConcreteName(nm));\n\t\teq.setNamespace(getDeclarationExtensions().getConceptNamespace(nm));\n\t\teq.setExternal(true);\n\t\teq.setUri(uri);\n\t\tif (location != null) {\n\t\t\teq.setLocation(location);\n\t\t}\n\t\tif (rtype != null) {\n\t\t\tNode rtnode = sadlTypeReferenceToNode(rtype);\n\t\t\teq.setReturnType(rtnode);\n\t\t}\n\t\tif (params != null && params.size() > 0) {\n\t\t\tif (params.get(0).getUnknown() == null) {\n\t\t\t\tList args = new ArrayList();\n\t\t\t\tList argtypes = new ArrayList();\n\t\t\t\tfor (int i = 0; i < params.size(); i++) {\n\t\t\t\t\tSadlParameterDeclaration param = params.get(i);\n\t\t\t\t\tSadlResource pr = param.getName();\n\t\t\t\t\tif (pr != null) {\n\t\t\t\t\t\tObject pn = processExpression(pr);\n\t\t\t\t\t\targs.add((Node) pn);\n\t\t\t\t\t\tSadlTypeReference prtype = param.getType();\n\t\t\t\t\t\tNode prtnode = sadlTypeReferenceToNode(prtype); \n\t\t\t\t\t\targtypes.add(prtnode);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\teq.setArguments(args);\n\t\t\t\teq.setArgumentTypes(argtypes);\n\t\t\t}\n\t\t}\n\t\t\n\t\tlogger.debug(\"External Equation: \" + eq.toFullyQualifiedString());\n\t\treturn eq;\n\t}\n\t\n\tprivate NamedNode sadlTypeReferenceToNode(SadlTypeReference rtype) throws JenaProcessorException, InvalidNameException, TranslationException {\n\t\tConceptName cn = sadlSimpleTypeReferenceToConceptName(rtype);\n\t\tif (cn == null) {\n\t\t\treturn null;\n\t\t}\n\t\treturn conceptNameToNamedNode(cn);\n//\t\tcom.hp.hpl.jena.rdf.model.Resource rtobj = sadlTypeReferenceToResource(rtype);\n//\t\tif (rtobj == null) {\n////\t\t\tthrow new JenaProcessorException(\"SadlTypeReference was not resolved to a model resource.\");\n//\t\t\treturn null;\n//\t\t}\n//\t\tif (rtobj.isURIResource()) {\n//\t\t\tNamedNode rtnn = new NamedNode(((com.hp.hpl.jena.rdf.model.Resource)rtobj).getLocalName());\n//\t\t\trtnn.setNamespace(((com.hp.hpl.jena.rdf.model.Resource)rtobj).getNameSpace());\n//\t\t\treturn rtnn;\n//\t\t}\n\t}\n\t\n\tpublic NamedNode conceptNameToNamedNode(ConceptName cn) throws TranslationException, InvalidNameException {\n\t\tNamedNode rtnn = new NamedNode(cn.getUri());\n\t\trtnn.setNodeType(conceptTypeToNodeType(cn.getType()));\n\t\treturn rtnn;\n\t}\n\t\n\tprotected void addEquation(Resource resource, Equation eq, EObject nm) {\n\t\tif (getEquations() == null) {\n\t\t\tsetEquations(new ArrayList());\n\t\t\tOntModelProvider.addOtherContent(resource, getEquations());\n\t\t}\n\t\tString newEqName = eq.getName();\n\t\tList eqlist = getEquations();\n\t\tfor (int i = 0; i < eqlist.size(); i++) {\n\t\t\tif (eqlist.get(i).getName().equals(newEqName)) {\n\t\t\t\tif(!namespaceIsImported(eq.getNamespace(), resource)) {\n\t\t\t\t\tgetIssueAcceptor().addError(\"Name '\" + newEqName + \"' is already used. Please provide a unique name.\", nm);\n\t\t\t\t}else {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tgetEquations().add(eq);\n\t}\n\t\n\tprivate boolean namespaceIsImported(String namespace, Resource resource) {\n\t\tString currentNamespace = namespace.replace(\"#\", \"\");\n\t\tif(currentNamespace.equals(SadlConstants.SADL_BUILTIN_FUNCTIONS_URI) || \n\t\t\t\tcurrentNamespace.equals(SadlConstants.SADL_IMPLICIT_MODEL_URI)) {\n\t\t\treturn true;\n\t\t}\n\t\t\n\t\tTreeIterator it = resource.getAllContents();\t\n\t\twhile(it.hasNext()) {\n\t\t\tEObject eObj = it.next();\n\t\t\tif(eObj instanceof SadlImport) {\n\t\t\t\tSadlModel sadlModel = ((SadlImport)eObj).getImportedResource();\n\t\t\t\tif(sadlModel.getBaseUri().equals(currentNamespace)){\n\t\t\t\t\treturn true;\n\t\t\t\t}else if(namespaceIsImported(namespace, sadlModel.eResource())) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\t\n\tprivate boolean namespaceIsImported(String namespace, OntModel currentModel) {\n\t\tOntModel importedModel = currentModel.getImportedModel(namespace.replace(\"#\", \"\"));\n\t\tif(importedModel != null) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tpublic List getEquations(Resource resource) {\n\t\tList other = OntModelProvider.getOtherContent(resource);\n\t\treturn equations;\n\t}\n\t\n\tprivate void processStatement(RuleStatement element) throws InvalidNameException, InvalidTypeException, TranslationException {\n\t\tclearCruleVariables();\n\t\tString ruleName = getDeclarationExtensions().getConcreteName(element.getName());\n\t\tRule rule = new Rule(ruleName);\n\t\tsetTarget(rule);\n\t\tEList ifs = element.getIfs();\n\t\tEList thens = element.getThens();\n\t\tsetRulePart(RulePart.PREMISE);\n\t\tfor (int i = 0; ifs != null && i < ifs.size(); i++) {\n\t\t\tExpression expr = ifs.get(i);\n\t\t\tObject result = processExpression(expr);\n\t\t\tif (result instanceof GraphPatternElement) {\n\t\t\t\trule.addIf((GraphPatternElement) result);\n\t\t\t}\n\t\t\telse {\n\t\t\t\taddError(SadlErrorMessages.IS_NOT_A.get(\"If Expression (\" + result + \")\", \"GraphPatternElement\"), expr);\n\t\t\t}\n\t\t}\n\t\tsetRulePart(RulePart.CONCLUSION);\n\t\tfor (int i = 0; thens != null && i < thens.size(); i++) {\n\t\t\tExpression expr = thens.get(i);\n\t\t\tObject result = processExpression(expr);\n\t\t\tif (result instanceof GraphPatternElement) {\n\t\t\t\trule.addThen((GraphPatternElement) result);\n\t\t\t}\n\t\t\telse {\n\t\t\t\taddError(SadlErrorMessages.IS_NOT_A.get(\"Then Expression (\" + result + \")\", \"GraphPatternElement\"), expr);\n\t\t\t}\n\t\t}\n\t\tgetIfTranslator().setTarget(rule);\n\t\trule = getIfTranslator().postProcessRule(rule, element);\n\t\tif (rules == null) {\n\t\t\trules = new ArrayList();\n\t\t}\n\t\trules.add(rule);\n\t\tString uri = declarationExtensions.getConceptUri(element.getName());\n\t\tOntClass rcls = getTheJenaModel().getOntClass(SadlConstants.SADL_IMPLICIT_MODEL_RULE_CLASS_URI);\n\t\tif (rcls != null) {\n\t\t\tIndividual rl = getTheJenaModel().createIndividual(uri, rcls);\n\t\t\t// Add annotations, if any\n\t\t\tEList annotations = element.getAnnotations();\n\t\t\tif (annotations != null && annotations.size() > 0) {\n\t\t\t\taddNamedStructureAnnotations(rl, annotations);\n\t\t\t}\n\t\t}\n\t\tsetTarget(null);\n\t}\n\t\n\tprotected void addSadlCommand(SadlCommand sadlCommand) {\n\t\tif (getSadlCommands() == null) {\n\t\t\tsetSadlCommands(new ArrayList());\n\t\t}\n\t\tgetSadlCommands().add(sadlCommand);\n\t}\n\t\n\t/**\n\t * Get the SadlCommands generated by the processor. Used for testing purposes.\n\t * @return\n\t */\n\tpublic List getSadlCommands() {\n\t\treturn sadlCommands;\n\t}\n\n\t/* (non-Javadoc)\n\t * @see com.ge.research.sadl.jena.IJenaBasedModelProcessor#getIntermediateFormResults(boolean, boolean)\n\t */\n\t@Override\n\tpublic List getIntermediateFormResults(boolean bRaw, boolean treatAsConclusion) throws InvalidNameException, InvalidTypeException, TranslationException, IOException, PrefixNotFoundException, ConfigurationException {\n\t\tif (bRaw) {\n\t\t\treturn intermediateFormResults;\n\t\t}\n\t\telse if (intermediateFormResults != null){\n\t\t\tList cooked = new ArrayList();\n\t\t\tfor (Object im:intermediateFormResults) {\n\t\t\t\t\tgetIfTranslator().resetIFTranslator();\n\t\t\t\tRule rule = null;\n\t\t\t\tif (treatAsConclusion) {\n\t\t\t\t\trule = new Rule(\"dummy\");\n\t\t\t\t\tgetIfTranslator().setTarget(rule);\n\t\t\t\t}\n\t\t\t\tObject expansion = getIfTranslator().expandProxyNodes(im, treatAsConclusion, true);\n\t\t\t\tif (treatAsConclusion) {\n\t\t\t\t\tif (expansion instanceof List) {\n\t\t\t\t\t\tList ifs = rule.getIfs();\n\t\t\t\t\t\tif (ifs != null) {\n\t\t\t\t\t\t\tifs.addAll((Collection) expansion);\n\t\t\t\t\t\t\texpansion = getIfTranslator().listToAnd(ifs);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcooked.add(expansion);\n\t\t\t}\n\t\t\treturn cooked;\n\t\t}\n\t\treturn null;\n\t}\n\t\n\t/* (non-Javadoc)\n\t * @see com.ge.research.sadl.jena.IJenaBasedModelProcessor#expandNodesInIntermediateForm(java.lang.Object, boolean)\n\t */\n\t@Override\n\tpublic GraphPatternElement expandNodesInIntermediateForm(Object rawIntermediateForm, boolean treatAsConclusion) throws InvalidNameException, InvalidTypeException, TranslationException {\n\t\tgetIfTranslator().resetIFTranslator();\n\t\tRule rule = null;\n\t\tif (treatAsConclusion) {\n\t\t\trule = new Rule(\"dummy\");\n\t\t\tgetIfTranslator().setTarget(rule);\n\t\t}\n\t\tObject expansion = getIfTranslator().expandProxyNodes(rawIntermediateForm, treatAsConclusion, true);\n\t\tif (treatAsConclusion) {\n\t\t\tif (expansion instanceof List) {\n\t\t\t\tList ifs = rule.getIfs();\n\t\t\t\tif (ifs != null) {\n\t\t\t\t\tifs.addAll((Collection) expansion);\n\t\t\t\t\texpansion = getIfTranslator().listToAnd(ifs);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (expansion instanceof GraphPatternElement) {\n\t\t\treturn (GraphPatternElement) expansion;\n\t\t}\n\t\telse throw new TranslationException(\"Expansion failed to return a GraphPatternElement (returned '\" + expansion.toString() + \"')\");\t\n\t}\n\t\n\tprotected void addIntermediateFormResult(Object result) {\n\t\tif (intermediateFormResults == null) {\n\t\t\tintermediateFormResults = new ArrayList();\n\t\t}\n\t\tintermediateFormResults.add(result);\n\t}\n\n\tpublic IntermediateFormTranslator getIfTranslator() {\n\t\tif (intermediateFormTranslator == null) {\n\t\t\tintermediateFormTranslator = new IntermediateFormTranslator(this, getTheJenaModel());\n\t\t}\n\t\treturn intermediateFormTranslator;\n\t}\n\t\n//\t@Override\n//\tpublic Object processExpression(Expression expr) throws InvalidNameException, InvalidTypeException, TranslationException {\n//\t\treturn processExpression(expr);\n//\t}\n//\t\n\tpublic Object processExpression(final Expression expr) throws InvalidNameException, InvalidTypeException, TranslationException {\n\t\tif (expr instanceof BinaryOperation) {\n\t\t\treturn processExpression((BinaryOperation)expr);\n\t\t}\n\t\telse if (expr instanceof BooleanLiteral) {\n\t\t\treturn processExpression((BooleanLiteral)expr);\n\t\t}\n\t\telse if (expr instanceof Constant) {\n\t\t\treturn processExpression((Constant)expr);\n\t\t}\n\t\telse if (expr instanceof Declaration) {\n\t\t\treturn processExpression((Declaration)expr);\n\t\t}\n\t\telse if (expr instanceof Name) {\n\t\t\treturn processExpression((Name)expr);\n\t\t}\n\t\telse if (expr instanceof NumberLiteral) {\n\t\t\treturn processExpression((NumberLiteral)expr);\n\t\t}\n\t\telse if (expr instanceof PropOfSubject) {\n\t\t\treturn processExpression((PropOfSubject)expr);\n\t\t}\n\t\telse if (expr instanceof StringLiteral) {\n\t\t\treturn processExpression((StringLiteral)expr);\n\t\t}\n\t\telse if (expr instanceof SubjHasProp) {\n\t\t\tif (SadlASTUtils.isUnitExpression(expr)) {\n\t\t\t\treturn processSubjHasPropUnitExpression((SubjHasProp)expr);\n\t\t\t}\n\t\t\treturn processExpression((SubjHasProp)expr);\n\t\t}\n\t\telse if (expr instanceof SadlResource) {\n\t\t\treturn processExpression((SadlResource)expr);\n\t\t}\n\t\telse if (expr instanceof UnaryExpression) {\n\t\t\treturn processExpression((UnaryExpression)expr);\n\t\t}\n\t\telse if (expr instanceof Sublist) {\n\t\t\treturn processExpression((Sublist)expr);\n\t\t}\n\t\telse if (expr instanceof ValueTable) {\n\t\t\treturn processExpression((ValueTable)expr);\n\t\t}\n\t\telse if (expr instanceof SelectExpression) {\n\t\t\treturn processExpression((SelectExpression)expr);\n\t\t}\n\t\telse if (expr instanceof AskExpression) {\n//\t\t\taddError(SadlErrorMessages.UNHANDLED.get(\"AskExpression\", \" \"), expr);\n\t\t\treturn processExpression((AskExpression)expr);\n\t\t}\n\t\telse if (expr instanceof ConstructExpression) {\n\t\t\treturn processExpression((ConstructExpression)expr);\n\t\t}\n\t\telse if (expr instanceof UnitExpression) {\n\t\t\treturn processExpression((UnitExpression) expr);\n\t\t}\n\t\telse if (expr instanceof ElementInList) {\n\t\t\treturn processExpression((ElementInList) expr);\n\t\t}\n\t\telse if (expr != null){\n\t\t\tthrow new TranslationException(\"Unhandled rule expression type: \" + expr.getClass().getCanonicalName());\n\t\t}\n\t\treturn expr;\n\t}\n\t\n\tpublic Object processExpression(ValueTable expr) {\n\t\tValueRow row = ((ValueTable)expr).getRow();\n\t\tif (row == null) {\n\t\t\tEList rows = ((ValueTable)expr).getRows();\n\t\t\tif (rows == null || rows.size() == 0) {\n\t\t\t\tValueTable vtbl = ((ValueTable)expr).getValueTable();\n\t\t\t\treturn processExpression(vtbl);\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tpublic Object processExpression(BinaryOperation expr) throws InvalidNameException, InvalidTypeException, TranslationException {\n\t\t// is this a variable definition?\n\t\tboolean isLeftVariableDefinition = false;\n\t\tName leftVariableName = null;\n\t\tExpression leftVariableDefn = null;\n\t\t\n\t\t// math operations can be a variable on each side of operand\n\t\tboolean isRightVariableDefinition = false;\n\t\tName rightVariableName = null;\n\t\tExpression rightVariableDefn = null;\n\t\ttry {\n\t\t\tif (expr.getLeft() instanceof Name && isVariableDefinition((Name) expr.getLeft())) {\n\t\t\t\t// left is variable name, right is variable definition\n\t\t\t\tisLeftVariableDefinition = true;\n\t\t\t\tleftVariableName = (Name) expr.getLeft();\n\t\t\t\tleftVariableDefn = expr.getRight();\n\t\t\t}\n\t\t\tif (expr.getRight() instanceof Name && isVariableDefinition((Name)expr.getRight())) {\n\t\t\t\t// right is variable name, left is variable definition\n\t\t\t\tisRightVariableDefinition = true;\n\t\t\t\trightVariableName = (Name) expr.getRight();\n\t\t\t\trightVariableDefn = expr.getLeft();\n\t\t\t}\n\t\t} catch (CircularDefinitionException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t\t\n\t\tif (isLeftVariableDefinition) {\n\t\t\tObject leftTranslatedDefn = processExpression(leftVariableDefn);\n\t\t\tNamedNode leftDefnType = null;\n\t\t\ttry {\n\t\t\t\tVariableNode leftVar = createVariable(getDeclarationExtensions().getConceptUri(leftVariableName.getName()));\n\t\t\t\tif (leftVar == null) {\t// this can happen on clean/build when file is open in editor\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\tif (leftTranslatedDefn instanceof NamedNode) {\n\t\t\t\t\tleftDefnType = (NamedNode) leftTranslatedDefn;\n\t\t\t\t\tif (leftVar.getType() == null) {\n\t\t\t\t\t\tleftVar.setType((NamedNode) leftDefnType);\n\t\t\t\t\t}\n\t\t\t\t\tif (isRightVariableDefinition) {\n\t\t\t\t\t\tObject rightTranslatedDefn = processExpression(rightVariableDefn);\n\t\t\t\t\t\tNamedNode rightDefnType = null;\n\t\t\t\t\t\tVariableNode rightVar = createVariable(getDeclarationExtensions().getConceptUri(rightVariableName.getName()));\n\t\t\t\t\t\tif (rightVar == null) {\n\t\t\t\t\t\t\treturn null;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (rightTranslatedDefn instanceof NamedNode) {\n\t\t\t\t\t\t\trightDefnType = (NamedNode) rightTranslatedDefn;\n\t\t\t\t\t\t\tif (rightVar.getType() == null) {\n\t\t\t\t\t\t\t\trightVar.setType(rightDefnType);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn createBinaryBuiltin(expr.getOp(), leftVar, rightVar);\n\t\t\t\t\t}\n\t\t\t\t\tTripleElement trel = new TripleElement(leftVar, new RDFTypeNode(), leftDefnType);\n\t\t\t\t\ttrel.setSourceType(TripleSourceType.SPV);\n\t\t\t\t\treturn trel;\n\t\t\t\t}\n\t\t\t\telse if (expr.getRight().equals(leftVariableName) && expr.getLeft() instanceof PropOfSubject && leftTranslatedDefn instanceof TripleElement && ((TripleElement)leftTranslatedDefn).getObject() == null) {\n\t\t\t\t\t// this is just like a SubjHasProp only the order is reversed\n\t\t\t\t\t((TripleElement)leftTranslatedDefn).setObject(leftVar);\n\t\t\t\t\treturn leftTranslatedDefn;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tTypeCheckInfo varType = getModelValidator().getType(leftVariableDefn);\n\t\t\t\t\tif (varType != null) {\n\t\t\t\t\t\tif (leftVar.getType() == null) {\n\t\t\t\t\t\t\tif (varType.getCompoundTypes() != null) {\n\t\t\t\t\t\t\t\tObject jct = compoundTypeCheckTypeToNode(varType, leftVariableDefn);\n\t\t\t\t\t\t\t\tif (jct != null && jct instanceof Junction) {\n\t\t\t\t\t\t\t\t\tleftVar.setType(nodeCheck(jct));\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\taddError(\"Compound type check did not process into expected result for variable type\", leftVariableDefn);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (varType.getTypeCheckType() != null && varType.getTypeCheckType() instanceof ConceptName) {\n\t\t\t\t\t\t\t\tleftDefnType = conceptNameToNamedNode((ConceptName) varType.getTypeCheckType());\n\t\t\t\t\t\t\t\tleftVar.setType((NamedNode) leftDefnType);\n\t\t\t\t\t\t\t\tif (varType.getRangeValueType().equals(RangeValueType.LIST)) {\n\t\t\t\t\t\t\t\t\tConceptName cn = new ConceptName(((NamedNode)leftDefnType).toFullyQualifiedString());\n//\t\t\t\t\t\t\t\t\tcn.setRangeValueType(RangeValueType.LIST);\n\t\t\t\t\t\t\t\t\tcn.setType(nodeTypeToConceptType(((NamedNode)leftDefnType).getNodeType()));\n\t\t\t\t\t\t\t\t\tleftVar.setListType(cn);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (leftTranslatedDefn instanceof GraphPatternElement) {\n\t\t\t\t\t\tif (leftVar.getDefinition() != null) {\n\t\t\t\t\t\t\tleftVar.getDefinition().add((GraphPatternElement) leftTranslatedDefn);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tList defnLst = new ArrayList(1);\n\t\t\t\t\t\t\tdefnLst.add((GraphPatternElement) leftTranslatedDefn);\n\t\t\t\t\t\t\tleftVar.setDefinition(defnLst);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (leftTranslatedDefn instanceof List) {\n\t\t\t\t\t\tleftVar.setDefinition((List) leftTranslatedDefn);\n\t\t\t\t\t}\n\t\t\t\t\tif (leftTranslatedDefn instanceof TripleElement && ((TripleElement)leftTranslatedDefn).getObject() == null) {\n\t\t\t\t\t\t// this is a variable definition and the definition is a triple and the triple has no object\n\t\t\t\t\t\t((TripleElement)leftTranslatedDefn).setObject(leftVar);\n\t\t\t\t\t\treturn leftTranslatedDefn;\n\t\t\t\t\t}\n//\t\t\t\t\telse if (leftTranslatedDefn instanceof BuiltinElement) {\n//\t\t\t\t\t\t((BuiltinElement)leftTranslatedDefn).addArgument(leftVar);\n//\t\t\t\t\t\treturn leftTranslatedDefn;\n//\t\t\t\t\t}\n\t\t\t\t\tNode defn = nodeCheck(leftTranslatedDefn);\n\t\t\t\t\tGraphPatternElement bi = createBinaryBuiltin(expr.getOp(), leftVar, defn);\n\t\t\t\t\treturn bi;\n\t\t\t\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} catch (IOException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (ConfigurationException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (DontTypeCheckException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (CircularDefinitionException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (CircularDependencyException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (PropertyWithoutRangeException e) {\n\t\t\t\taddError(\"Property does not have a range\", leftVariableDefn);\n\t\t\t} catch (PrefixNotFoundException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\telse if (isRightVariableDefinition) {\t\t// only, left is not variable definition\n\t\t\tObject rightTranslatedDefn = processExpression(rightVariableDefn);\n\t\t\tNamedNode rightDefnType = null;\n\t\t\tVariableNode rightVar;\n\t\t\ttry {\n\t\t\t\trightVar = createVariable(getDeclarationExtensions().getConceptUri(rightVariableName.getName()));\n\t\t\t\tif (rightVar == null) {\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\tif (rightTranslatedDefn instanceof NamedNode) {\n\t\t\t\t\trightDefnType = (NamedNode) rightTranslatedDefn;\n\t\t\t\t\tif (rightVar.getType() == null) {\n\t\t\t\t\t\trightVar.setType(rightDefnType);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tTypeCheckInfo varType = getModelValidator().getType(rightVariableDefn);\n\t\t\t\t\tif (varType != null) {\n\t\t\t\t\t\tif (rightVar.getType() == null) {\n\t\t\t\t\t\t\tif (varType.getCompoundTypes() != null) {\n\t\t\t\t\t\t\t\tObject jct = compoundTypeCheckTypeToNode(varType, rightVariableDefn);\n\t\t\t\t\t\t\t\tif (jct != null && jct instanceof Junction) {\n\t\t\t\t\t\t\t\t\trightVar.setType(nodeCheck(jct));\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\taddError(\"Compound type check did not process into expected result for variable type\", leftVariableDefn);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (varType.getTypeCheckType() != null && varType.getTypeCheckType() instanceof ConceptName) {\n\t\t\t\t\t\t\t\trightDefnType = conceptNameToNamedNode((ConceptName) varType.getTypeCheckType());\n\t\t\t\t\t\t\t\trightVar.setType((NamedNode) rightDefnType);\n\t\t\t\t\t\t\t\tif (varType.getRangeValueType().equals(RangeValueType.LIST)) {\n\t\t\t\t\t\t\t\t\tConceptName cn = new ConceptName(((NamedNode)rightDefnType).toFullyQualifiedString());\n\t//\t\t\t\t\t\t\t\tcn.setRangeValueType(RangeValueType.LIST);\n\t\t\t\t\t\t\t\t\tcn.setType(nodeTypeToConceptType(((NamedNode)rightDefnType).getNodeType()));\n\t\t\t\t\t\t\t\t\trightVar.setListType(cn);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (rightTranslatedDefn instanceof GraphPatternElement) {\n\t\t\t\t\t\tif (rightVar.getDefinition() != null) {\n\t\t\t\t\t\t\trightVar.getDefinition().add((GraphPatternElement) rightTranslatedDefn);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tList defnLst = new ArrayList(1);\n\t\t\t\t\t\t\tdefnLst.add((GraphPatternElement) rightTranslatedDefn);\n\t\t\t\t\t\t\trightVar.setDefinition(defnLst);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (rightTranslatedDefn instanceof List) {\n\t\t\t\t\t\trightVar.setDefinition((List) rightTranslatedDefn);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tObject lobj = processExpression(expr.getLeft());\n\t\t\t\tif (lobj instanceof TripleElement && ((TripleElement)lobj).getObject() == null) {\n\t\t\t\t\t((TripleElement)lobj).setObject(rightVar);\n\t\t\t\t\treturn lobj;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\treturn createBinaryBuiltin(expr.getOp(), rightVar, lobj);\n\t\t\t\t}\n\t\t\t} catch (IOException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (PrefixNotFoundException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (ConfigurationException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\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} catch (DontTypeCheckException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (CircularDefinitionException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (CircularDependencyException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (PropertyWithoutRangeException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\t//Validate BinaryOperation expression\n\t\tStringBuilder errorMessage = new StringBuilder();\n\t\tif(!isLeftVariableDefinition && getModelValidator() != null) {\t\t// don't type check a variable definition\n\t\t\tif (!getModelValidator().validate(expr, errorMessage)) {\n\t\t\t\taddIssueToAcceptor(errorMessage.toString(), expr);\n\t\t\t\tif (isSyntheticUri(null, getCurrentResource())) {\n\t\t\t\t\tif (getMetricsProcessor() != null) {\n\t\t\t\t\t\tgetMetricsProcessor().addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.TYPE_CHECK_FAILURE_URI);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tMap ip = getModelValidator().getImpliedPropertiesUsed();\n\t\t\t\tif (ip != null) {\n\t\t\t\t\tIterator ipitr = ip.keySet().iterator();\n\t\t\t\t\twhile (ipitr.hasNext()) {\n\t\t\t\t\t\tEObject eobj = ipitr.next();\n\t\t\t\t\t\tOntModelProvider.addImpliedProperty(expr.eResource(), eobj, ip.get(eobj));\n\t\t\t\t\t}\n\t\t\t\t\t// TODO must add implied properties to rules, tests, etc.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tString op = expr.getOp();\n\t\t\n\t\tExpression lexpr = expr.getLeft();\n\t\tExpression rexpr = expr.getRight();\n\n\t\treturn processBinaryExpressionByParts(expr, op, lexpr, rexpr);\n\t}\n\t\n\tprotected boolean isVariableDefinition(Name expr) throws CircularDefinitionException {\n\t\tif (expr instanceof Name && getDeclarationExtensions().getOntConceptType(((Name)expr).getName()).equals(OntConceptType.VARIABLE)) {\n\t\t\tif (getDeclarationExtensions().getDeclaration(((Name)expr).getName()).equals((Name)expr)) {\n//\t\t\t\taddInfo(\"This is a variable definition of '\" + getDeclarationExtensions().getConceptUri(((Name)expr).getName()) + \"'\", expr);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprivate boolean isVariableDefinition(Declaration decl) {\n\t\tif (!isDefiniteArticle(decl.getArticle()) && (isDeclInThereExists(decl) || (decl.getType() instanceof SadlSimpleTypeReference))) { \n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprivate boolean isDeclInThereExists(Declaration decl) {\n\t\tif (decl.eContainer() != null && decl.eContainer() instanceof UnaryExpression && \n\t\t\t\t((UnaryExpression)decl.eContainer()).getOp().equals(\"there exists\")) {\n\t\t\treturn true;\n\t\t}\n\t\telse if (decl.eContainer() != null && decl.eContainer() instanceof SubjHasProp && \n\t\t\t\tdecl.eContainer().eContainer() != null && decl.eContainer().eContainer() instanceof UnaryExpression && \n\t\t\t\t((UnaryExpression)decl.eContainer().eContainer()).getOp().equals(\"there exists\")) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tprotected Object processBinaryExpressionByParts(EObject container, String op, Expression lexpr,\n\t\t\tExpression rexpr) throws InvalidNameException, InvalidTypeException, TranslationException {\n\t\tStringBuilder errorMessage = new StringBuilder();\n\t\tif (lexpr != null && rexpr != null) {\n\t\t\tif(!getModelValidator().validateBinaryOperationByParts(lexpr.eContainer(), lexpr, rexpr, op, errorMessage)){\n\t\t\t\taddError(errorMessage.toString(), lexpr.eContainer());\n\t\t\t}\n\t\t\telse {\n\t\t\t\tMap ip = getModelValidator().getImpliedPropertiesUsed();\n\t\t\t\tif (ip != null) {\n\t\t\t\t\tIterator ipitr = ip.keySet().iterator();\n\t\t\t\t\twhile (ipitr.hasNext()) {\n\t\t\t\t\t\tEObject eobj = ipitr.next();\n\t\t\t\t\t\tOntModelProvider.addImpliedProperty(lexpr.eResource(), eobj, ip.get(eobj));\n\t\t\t\t\t}\n\t\t\t\t\t// TODO must add implied properties to rules, tests, etc.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tBuiltinType optype = BuiltinType.getType(op);\n\t\tObject lobj;\n\t\tif (lexpr != null) {\n\t\t\tlobj = processExpression(lexpr);\t\t\t\n\t\t}\n\t\telse {\n\t\t\taddError(\"Left side of '\" + op + \"' is null\", lexpr); //TODO Add new error\n\t\t\treturn null;\n\t\t}\n\t\tObject robj = null;\n\t\tif (rexpr != null) {\n\t\t\trobj = processExpression(rexpr);\n\t\t}\n\t\telse {\n\t\t\taddError(\"Right side of '\" + op + \"' is null\", rexpr); //TODO Add new error\n\t\t\treturn null;\n\t\t}\n\t\t\t\t\n\t\tif (optype == BuiltinType.Equal || optype == BuiltinType.NotEqual) {\n\t\t\t// If we're doing an assignment, we can simplify the pattern.\n\t\t\tNode assignedNode = null;\n\t\t\tObject pattern = null;\n\t\t\tif (rexpr instanceof Declaration && !(robj instanceof VariableNode)) {\n\t\t\t\tif (lobj instanceof Node && robj instanceof Node) {\n\t\t\t\t\tTripleElement trel = new TripleElement((Node)lobj, new RDFTypeNode(), (Node)robj);\n\t\t\t\t\ttrel.setSourceType(TripleSourceType.ITC);\n\t\t\t\t\treturn trel;\n\t\t\t\t}\n\t\t\t\telse {\n//\t\t\t\t\tthrow new TranslationException(\"Unhandled binary operation condition: left and right are not both nodes.\");\n\t\t\t\t\taddError(SadlErrorMessages.UNHANDLED.get(\"binary operation condition. \", \"Left and right are not both nodes.\"), container);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (lobj instanceof NamedNode && !(lobj instanceof VariableNode) && hasCommonVariableSubject(robj)) {\n\t\t\t\tTripleElement trel = (TripleElement)robj;\n\t\t\t\twhile (trel != null) {\n\t\t\t\t\ttrel.setSubject((Node) lobj);\n\t\t\t\t\ttrel = (TripleElement) trel.getNext();\n\t\t\t\t}\n\t\t\t\treturn robj;\n\t\t\t}\n\t\t\tif ((lobj instanceof TripleElement || (lobj instanceof com.ge.research.sadl.model.gp.Literal && isSparqlQuery(((com.ge.research.sadl.model.gp.Literal)lobj).toString())))\n\t\t\t\t\t&& !(robj instanceof KnownNode)) {\n\t\t\t\tif (getRulePart().equals(RulePart.CONCLUSION) || getRulePart().equals(RulePart.PREMISE)) {\t\t// added PREMISE--side effects? awc 10/9/17\n\t\t\t\t\tif (robj instanceof com.ge.research.sadl.model.gp.Literal) {\n\t\t\t\t\t\tif (lobj instanceof TripleElement) {\n\t\t\t\t\t\t\tif (((TripleElement)lobj).getObject() == null) {\n\t\t\t\t\t\t\t\t((TripleElement)lobj).setObject((com.ge.research.sadl.model.gp.Literal)robj);\n\t\t\t\t\t\t\t\tlobj = checkForNegation((TripleElement)lobj, rexpr);\n\t\t\t\t\t\t\t\treturn lobj;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\taddError(SadlErrorMessages.UNHANDLED.get(\"rule conclusion construct \", \" \"), container);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\taddError(SadlErrorMessages.UNHANDLED.get(\"rule conclusion construct \", \"\"), container);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (robj instanceof VariableNode) {\n\t\t\t\t\t\tif (((TripleElement)lobj).getObject() == null) {\n\t\t\t\t\t\t\t((TripleElement)lobj).setObject((VariableNode) robj);\n\t\t\t\t\t\t\tlobj = checkForNegation((TripleElement)lobj, rexpr);\n\t\t\t\t\t\t\treturn lobj;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (robj instanceof NamedNode) {\n\t\t\t\t\t\tif (((TripleElement)lobj).getObject() == null) {\n\t\t\t\t\t\t\t((TripleElement)lobj).setObject((NamedNode) robj);\n\t\t\t\t\t\t\tlobj = checkForNegation((TripleElement)lobj, rexpr);\n\t\t\t\t\t\t\treturn lobj;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (robj instanceof BuiltinElement) {\n\t\t\t\t\t\tif (isModifiedTriple(((BuiltinElement)robj).getFuncType())) {\n\t\t\t\t\t\t\tassignedNode = ((BuiltinElement)robj).getArguments().get(0);\n\t\t\t\t\t\t\toptype = ((BuiltinElement)robj).getFuncType();\n\t\t\t\t\t\t\tpattern = lobj;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (isComparisonBuiltin(((BuiltinElement)robj).getFuncName())) {\n\t\t\t\t\t\t\tif ( ((BuiltinElement)robj).getArguments().get(0) instanceof com.ge.research.sadl.model.gp.Literal) {\n\t\t\t\t\t\t\t\t((TripleElement)lobj).setObject(nodeCheck(robj));\n\t\t\t\t\t\t\t\treturn lobj;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\treturn createBinaryBuiltin(((BuiltinElement)robj).getFuncName(), lobj, ((BuiltinElement)robj).getArguments().get(0));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (robj instanceof TripleElement) {\n\t\t\t\t\t\t// do nothing\n\t\t\t\t\t}\n\t\t\t\t\telse if (robj instanceof ConstantNode) {\n\t\t\t\t\t\tString cnst = ((ConstantNode)robj).getName();\n\t\t\t\t\t\tif (cnst.equals(\"None\")) {\n\t\t\t\t\t\t\t((TripleElement)lobj).setType(TripleModifierType.None);\n\t\t\t\t\t\t\treturn lobj;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\taddError(SadlErrorMessages.UNHANDLED.get(\"assignment construct in rule conclusion\", \" \"), container);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (robj instanceof BuiltinElement) {\n\t\t\t\t\tif (isModifiedTriple(((BuiltinElement)robj).getFuncType())) {\n\t\t\t\t\t\tif (((BuiltinElement)robj).getArguments() != null && ((BuiltinElement)robj).getArguments().size() > 0) {\n\t\t\t\t\t\t\tassignedNode = ((BuiltinElement)robj).getArguments().get(0);\n\t\t\t\t\t\t}\n\t\t\t\t\t\toptype = ((BuiltinElement)robj).getFuncType();\n\t\t\t\t\t\tpattern = lobj;\n\t\t\t\t\t}\n\t\t\t\t\telse if (isComparisonBuiltin(((BuiltinElement)robj).getFuncName())) {\n\t\t\t\t\t\tif ( ((BuiltinElement)robj).getArguments().get(0) instanceof Literal) {\n\t\t\t\t\t\t\t((TripleElement)lobj).setObject(nodeCheck(robj));\n\t\t\t\t\t\t\treturn lobj;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\treturn createBinaryBuiltin(((BuiltinElement)robj).getFuncName(), lobj, ((BuiltinElement)robj).getArguments().get(0));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (lobj instanceof Node && robj instanceof TripleElement) {\n\t\t\t\tassignedNode = validateNode((Node) lobj);\n\t\t\t\tpattern = (TripleElement) robj;\n\t\t\t}\n\t\t\telse if (robj instanceof Node && lobj instanceof TripleElement) {\n\t\t\t\tassignedNode = validateNode((Node) robj);\n\t\t\t\tpattern = (TripleElement) lobj;\n\t\t\t}\n\t\t\tif (assignedNode != null && pattern != null) {\n\t\t\t\t// We're expressing the type of a named thing.\n\t\t\t\tif (pattern instanceof TripleElement && ((TripleElement)pattern).getSubject() == null) {\n\t\t\t\t\tif (isModifiedTripleViaBuitin(robj)) {\n\t\t\t\t\t\toptype = ((BuiltinElement)((TripleElement)pattern).getNext()).getFuncType();\t\n\t\t\t\t\t\t((TripleElement)pattern).setNext(null);\n\t\t\t\t\t}\n\t\t\t\t\t((TripleElement)pattern).setSubject(assignedNode);\n\t\t\t\t\tif (optype != BuiltinType.Equal) {\n\t\t\t\t\t\t((TripleElement)pattern).setType(getTripleModifierType(optype));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (pattern instanceof TripleElement && ((TripleElement)pattern).getObject() == null && \n\t\t\t\t\t\t(((TripleElement)pattern).getSourceType().equals(TripleSourceType.PSnewV) \n\t\t\t\t\t\t\t\t|| ((TripleElement)pattern).getSourceType().equals(TripleSourceType.PSV))) {\n\t\t\t\t\tif (isModifiedTripleViaBuitin(robj)) {\n\t\t\t\t\t\toptype = ((BuiltinElement)((TripleElement)pattern).getNext()).getFuncType();\t\n\t\t\t\t\t\t((TripleElement)pattern).setNext(null);\n\t\t\t\t\t}\n\t\t\t\t\t((TripleElement)pattern).setObject(assignedNode);\n\t\t\t\t\tif (optype != BuiltinType.Equal) {\n\t\t\t\t\t\t((TripleElement)pattern).setType(getTripleModifierType(optype));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (pattern instanceof TripleElement && ((TripleElement)pattern).getSourceType().equals(TripleSourceType.SPV)\n\t\t\t\t\t\t&& assignedNode instanceof NamedNode && getProxyWithNullSubject(((TripleElement)pattern)) != null) {\n\t\t\t\t\tTripleElement proxyFor = getProxyWithNullSubject(((TripleElement)pattern));\n\t\t\t\t\tassignNullSubjectInProxies(((TripleElement)pattern), proxyFor, assignedNode);\n\t\t\t\t\tif (optype != BuiltinType.Equal) {\n\t\t\t\t\t\tproxyFor.setType(getTripleModifierType(optype));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (isModifiedTriple(optype) || \n\t\t\t\t\t\t(optype.equals(BuiltinType.Equal) && pattern instanceof TripleElement && \n\t\t\t\t\t\t\t\t(((TripleElement)pattern).getObject() == null || \n\t\t\t\t\t\t\t\t\t\t((TripleElement)pattern).getObject() instanceof NamedNode ||\n\t\t\t\t\t\t\t\t\t\t((TripleElement)pattern).getObject() instanceof com.ge.research.sadl.model.gp.Literal))){\n\t\t\t\t\tif (pattern instanceof TripleElement && isModifiedTripleViaBuitin(robj)) {\n\t\t\t\t\t\toptype = ((BuiltinElement)((TripleElement)pattern).getNext()).getFuncType();\n\t\t\t\t\t\t((TripleElement)pattern).setObject(assignedNode);\n\t\t\t\t\t\t((TripleElement)pattern).setNext(null);\n\t\t\t\t\t\t((TripleElement)pattern).setType(getTripleModifierType(optype));\n\t\t\t\t\t}\n\t\t\t\t\telse if (isComparisonViaBuiltin(robj, lobj)) {\n\t\t\t\t\t\tBuiltinElement be = (BuiltinElement)((TripleElement)robj).getNext();\n\t\t\t\t\t\tbe.addMissingArgument((Node) lobj);\n\t\t\t\t\t\treturn pattern;\n\t\t\t\t\t}\n\t\t\t\t\telse if (pattern instanceof TripleElement){\n\t\t\t\t\t\tTripleElement lastPattern = (TripleElement)pattern;\n\t\t\t\t\t\t// this while may need additional conditions to narrow application to nested triples?\n\t\t\t\t\t\twhile (lastPattern.getNext() != null && lastPattern instanceof TripleElement) {\n\t\t\t\t\t\t\tlastPattern = (TripleElement) lastPattern.getNext();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (getEncapsulatingTarget() instanceof Test) {\n\t\t\t\t\t\t\t((Test)getEncapsulatingTarget()).setRhs(assignedNode);\n\t\t\t\t\t\t\t((Test)getEncapsulatingTarget()).setCompName(optype);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (getEncapsulatingTarget() instanceof Query && getTarget() instanceof Test) {\n\t\t\t\t\t\t\t((Test)getTarget()).setRhs(getEncapsulatingTarget());\n\t\t\t\t\t\t\t((Test)getTarget()).setLhs(assignedNode);\n\t\t\t\t\t\t\t((Test)getTarget()).setCompName(optype);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (getTarget() instanceof Test && assignedNode != null) {\n\t\t\t\t\t\t\t((Test)getTarget()).setLhs(pattern);\n\t\t\t\t\t\t\t((Test)getTarget()).setRhs(assignedNode);\n\t\t\t\t\t\t\t((Test)getTarget()).setCompName(optype);\n\t\t\t\t\t\t\t((TripleElement) pattern).setType(TripleModifierType.None);\n\t\t\t\t\t\t\toptype = BuiltinType.Equal;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tlastPattern.setObject(assignedNode);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!optype.equals(BuiltinType.Equal)) {\n\t\t\t\t\t\t\t((TripleElement)pattern).setType(getTripleModifierType(optype));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tif (getTarget() instanceof Test) {\n\t\t\t\t\t\t\t((Test)getTarget()).setLhs(lobj);\n\t\t\t\t\t\t\t((Test)getTarget()).setRhs(assignedNode);\n\t\t\t\t\t\t\t((Test)getTarget()).setCompName(optype);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (getEncapsulatingTarget() instanceof Test) {\n\t\t\t\t\t((Test)getEncapsulatingTarget()).setRhs(assignedNode);\n\t\t\t\t\t((Test)getEncapsulatingTarget()).setCompName(optype);\n\t\t\t\t}\n\t\t\t\telse if (getTarget() instanceof Rule && pattern instanceof TripleElement && ((TripleElement)pattern).getSourceType().equals(TripleSourceType.ITC) && \n\t\t\t\t\t\t((TripleElement)pattern).getSubject() instanceof VariableNode && assignedNode instanceof VariableNode) {\n\t\t\t\t\t// in a rule of this type we just want to replace the pivot node variable\n\t\t\t\t\tdoVariableSubstitution(((TripleElement)pattern), (VariableNode)((TripleElement)pattern).getSubject(), (VariableNode)assignedNode);\n\t\t\t\t}\n\t\t\t\treturn pattern;\n\t\t\t}\n\t\t\tBuiltinElement bin = null;\n\t\t\tboolean binOnRight = false;\n\t\t\tObject retObj = null;\n\t\t\tif (lobj instanceof Node && robj instanceof BuiltinElement) {\n\t\t\t\tassignedNode = validateNode((Node)lobj);\n\t\t\t\tbin = (BuiltinElement)robj;\n\t\t\t\tretObj = robj;\n\t\t\t\tbinOnRight = true;\n\t\t\t}\n\t\t\telse if (robj instanceof Node && lobj instanceof BuiltinElement) {\n\t\t\t\tassignedNode = validateNode((Node)robj);\n\t\t\t\tbin = (BuiltinElement)lobj;\n\t\t\t\tretObj = lobj;\n\t\t\t\tbinOnRight = false;\n\t\t\t}\n\t\t\tif (bin != null && assignedNode != null) {\n\t\t\t\tif ((assignedNode instanceof VariableNode ||\n\t\t\t\t\t(assignedNode instanceof NamedNode && ((NamedNode)assignedNode).getNodeType().equals(NodeType.VariableNode)))) {\n\t\t\t\t\tif (getTarget() instanceof Rule && containsDeclaration(robj)) {\n\t\t\t\t\t\treturn replaceDeclarationWithVariableAndAddUseDeclarationAsDefinition(lexpr, lobj, rexpr, robj);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\twhile (bin.getNext() instanceof BuiltinElement) {\n\t\t\t\t\t\t\tbin = (BuiltinElement) bin.getNext();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (bin.isCreatedFromInterval()) {\n\t\t\t\t\t\t\tbin.addArgument(0, assignedNode);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tbin.addArgument(assignedNode);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn retObj;\n\t\t\t\t}\n\t\t\t\telse if (assignedNode instanceof Node && isComparisonBuiltin(bin.getFuncName())) {\n\t\t\t\t\t// this is a comparison with an extra \"is\"\n\t\t\t\t\tif (bin.getArguments().size() == 1) {\n\t\t\t\t\t\tif (bin.isCreatedFromInterval() || binOnRight) {\n\t\t\t\t\t\t\tbin.addArgument(0, assignedNode);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tbin.addArgument(assignedNode);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn bin;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// We're describing a thing with a graph pattern.\n\t\t\tSet vars = pattern instanceof TripleElement ? getSelectVariables(((TripleElement)pattern)) : null; \n\t\t\tif (vars != null && vars.size() == 1) {\n\t\t\t\t// Find where the unbound variable occurred in the pattern\n\t\t\t\t// and replace each place with the assigned node.\n\t\t\t\tVariableNode var = vars.iterator().next();\n\t\t\t\tGraphPatternElement gpe = ((TripleElement)pattern);\n\t\t\t\twhile (gpe instanceof TripleElement) {\n\t\t\t\t\tTripleElement triple = (TripleElement) gpe;\n\t\t\t\t\tif (var.equals(triple.getSubject())) {\n\t\t\t\t\t\ttriple.setSubject(assignedNode);\n\t\t\t\t\t}\n\t\t\t\t\tif (var.equals(triple.getObject())) {\n\t\t\t\t\t\ttriple.setObject(assignedNode);\n\t\t\t\t\t}\n\t\t\t\t\tgpe = gpe.getNext();\n\t\t\t\t}\n\t\t\t\treturn pattern;\n\t\t\t}\n\t\t}\n\t\t// if we get to here we want to actually create a BuiltinElement for the BinaryOpExpression\n\t\t// However, if the type is equal (\"is\", \"equal\") and the left side is a VariableNode and the right side is a literal\n\t\t//\tand the VariableNode hasn't already been bound, change from type equal to type assign.\n\t\tif (optype == BuiltinType.Equal && getTarget() instanceof Rule && lobj instanceof VariableNode && robj instanceof com.ge.research.sadl.model.gp.Literal && \n\t\t\t\t!variableIsBound((Rule)getTarget(), null, (VariableNode)lobj)) {\n\t\t\treturn createBinaryBuiltin(\"assign\", robj, lobj);\n\t\t}\n\t\tif (op.equals(\"and\") || op.equals(\"or\")) {\n\t\t\tJunction jct = new Junction();\n\t\t\tjct.setJunctionName(op);\n\t\t\tjct.setLhs(lobj);\n\t\t\tjct.setRhs(robj);\n\t\t\treturn jct;\n\t\t}\n\t\telse {\n\t\t\treturn createBinaryBuiltin(op, lobj, robj);\n\t\t}\n\t}\n\t\n\tprivate TripleElement checkForNegation(TripleElement lobj, Expression rexpr) throws InvalidTypeException {\n\t\tif (isOperationPulingUp(rexpr) && isNegation(rexpr)) {\n\t\t\tlobj.setType(TripleModifierType.Not);\n\t\t\tgetOperationPullingUp();\n\t\t}\n\t\treturn lobj;\n\t}\n\n\tprivate boolean isNegation(Expression expr) {\n\t\tif (expr instanceof UnaryExpression && ((UnaryExpression)expr).getOp().equals(\"not\")) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprivate Object replaceDeclarationWithVariableAndAddUseDeclarationAsDefinition(Expression lexpr, Object lobj, Expression rexpr, Object robj) throws TranslationException, InvalidTypeException {\n\t\tif (lobj instanceof VariableNode) {\n\t\t\tObject[] declAndTrans = getDeclarationAndTranslation(rexpr);\n\t\t\tif (declAndTrans != null) {\n\t\t\t\tObject rtrans = declAndTrans[1];\n\t\t\t\tif (rtrans instanceof NamedNode) {\n\t\t\t\t\tif (((NamedNode)rtrans).getNodeType().equals(NodeType.ClassNode)) {\n\t\t\t\t\t\tif (replaceDeclarationInRightWithVariableInLeft((Node)lobj, robj, rtrans)) {\n\t\t\t\t\t\t\tTripleElement newTriple = new TripleElement((Node)lobj, new NamedNode(RDF.type.getURI(), NodeType.ObjectProperty), (Node)rtrans);\n\t\t\t\t\t\t\tJunction jct = createJunction(rexpr, \"and\", newTriple, robj);\n\t\t\t\t\t\t\treturn jct;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprivate boolean replaceDeclarationInRightWithVariableInLeft(Node lobj, Object robj, Object rtrans) {\n\t\tif (robj instanceof BuiltinElement) {\n\t\t\tIterator argitr = ((BuiltinElement)robj).getArguments().iterator();\n\t\t\twhile (argitr.hasNext()) {\n\t\t\t\tNode arg = argitr.next();\n\t\t\t\tif (replaceDeclarationInRightWithVariableInLeft(lobj, arg, rtrans)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if (robj instanceof ProxyNode) {\n\t\t\tif (replaceDeclarationInRightWithVariableInLeft(lobj, ((ProxyNode)robj).getProxyFor(), rtrans)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\telse if (robj instanceof TripleElement) {\n\t\t\tNode subj = ((TripleElement)robj).getSubject();\n\t\t\tif (subj.equals(rtrans)) {\n\t\t\t\t((TripleElement)robj).setSubject(lobj);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\telse if (replaceDeclarationInRightWithVariableInLeft(lobj, subj, rtrans)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprivate Object[] getDeclarationAndTranslation(Expression expr) throws TranslationException {\n\t\tDeclaration decl = getDeclaration(expr);\n\t\tif (decl != null) {\n\t\t\tObject declprocessed = processExpression(decl);\n\t\t\tif (declprocessed != null) {\n\t\t\t\tObject[] result = new Object[2];\n\t\t\t\tresult[0] = decl;\n\t\t\t\tresult[1] = declprocessed;\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprivate Declaration getDeclaration(Expression rexpr) throws TranslationException {\n\t\tif (rexpr instanceof SubjHasProp) {\n\t\t\treturn getDeclarationFromSubjHasProp((SubjHasProp) rexpr);\n\t\t}\n\t\telse if (rexpr instanceof BinaryOperation) {\n\t\t\tDeclaration decl = getDeclaration(((BinaryOperation)rexpr).getLeft());\n\t\t\tif (decl != null) {\n\t\t\t\treturn decl;\n\t\t\t}\n\t\t\tdecl = getDeclaration(((BinaryOperation)rexpr).getRight());\n\t\t\tif (decl != null) {\n\t\t\t\treturn decl;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprivate boolean containsDeclaration(Object obj) {\n\t\tif (obj instanceof BuiltinElement) {\n\t\t\tIterator argitr = ((BuiltinElement)obj).getArguments().iterator();\n\t\t\twhile (argitr.hasNext()) {\n\t\t\t\tNode n = argitr.next();\n\t\t\t\tif (n instanceof ProxyNode) {\n\t\t\t\t\tif (containsDeclaration(((ProxyNode)n).getProxyFor())) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if (obj instanceof TripleElement) {\n\t\t\tNode s = ((TripleElement)obj).getSubject();\n\t\t\tif (s instanceof NamedNode && ((NamedNode)s).getNodeType().equals(NodeType.ClassNode)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (containsDeclaration(((TripleElement)obj).getSubject())) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\telse if (obj instanceof ProxyNode) {\n\t\t\tif (containsDeclaration(((ProxyNode)obj).getProxyFor())) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprivate Object processFunction(Name expr) throws InvalidNameException, InvalidTypeException, TranslationException {\n\t\tEList arglist = expr.getArglist();\n\t\tNode fnnode = processExpression(expr.getName());\n\t\tString funcname = null;\n\t\tif (fnnode instanceof VariableNode) {\n\t\t\tfuncname = ((VariableNode) fnnode).getName();\n\t\t}\n\t\telse if (fnnode == null) {\n\t\t\taddError(\"Function not found\", expr);\n\t\t\treturn null;\n\t\t}\n\t\telse {\n\t\t\tfuncname = fnnode.toString();\n\t\t}\n\t\tBuiltinElement builtin = new BuiltinElement();\n\t\tbuiltin.setFuncName(funcname);\n\t\tif (fnnode instanceof NamedNode && ((NamedNode)fnnode).getNamespace()!= null) {\n\t\t\tbuiltin.setFuncUri(fnnode.toFullyQualifiedString());\n\t\t}\n\t\tif (arglist != null && arglist.size() > 0) {\n\t\t\tList args = new ArrayList();\n\t\t\tfor (int i = 0; i < arglist.size(); i++) {\n\t\t\t\targs.add(processExpression(arglist.get(i)));\n\t\t\t}\n\t\t\tif (args != null) {\n\t\t\t\tfor (Object arg : args) {\n\t\t\t\t\tbuiltin.addArgument(nodeCheck(arg));\n\t\t\t\t\tif (arg instanceof GraphPatternElement) {\n\t\t\t\t\t\t((GraphPatternElement)arg).setEmbedded(true);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn builtin;\n\t}\n\t\n\tprivate boolean hasCommonVariableSubject(Object robj) {\n\t\tif (robj instanceof TripleElement && \n\t\t\t\t(((TripleElement)robj).getSubject() instanceof VariableNode && \n\t\t\t\t\t\t(((TripleElement)robj).getSourceType().equals(TripleSourceType.SPV)) ||\n\t\t\t\t\t\t((TripleElement)robj).getSourceType().equals(TripleSourceType.ITC))) {\n\t\t\tVariableNode subjvar = (VariableNode) ((TripleElement)robj).getSubject();\n\t\t\tObject trel = robj;\n\t\t\twhile (trel != null && trel instanceof TripleElement) {\n\t\t\t\tif (!(trel instanceof TripleElement) || \n\t\t\t\t\t\t(((TripleElement)trel).getSubject() != null &&!(((TripleElement)trel).getSubject().equals(subjvar)))) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\ttrel = ((TripleElement)trel).getNext();\n\t\t\t}\n\t\t\tif (trel == null) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns the bottom triple whose subject was replaced.\n\t * @param pattern\n\t * @param proxyFor\n\t * @param assignedNode\n\t * @return\n\t */\n\tprivate TripleElement assignNullSubjectInProxies(TripleElement pattern,\n\t\t\tTripleElement proxyFor, Node assignedNode) {\n\t\tif (pattern.getSubject() instanceof ProxyNode) {\n\t\t\tObject proxy = ((ProxyNode)pattern.getSubject()).getProxyFor();\n\t\t\tif (proxy instanceof TripleElement) {\n//\t\t\t\t((ProxyNode)pattern.getSubject()).setReplacementNode(assignedNode);\n\t\t\t\tif (((TripleElement)proxy).getSubject() == null) {\n\t\t\t\t\t// this is the bottom of the recursion\n\t\t\t\t\t((TripleElement)proxy).setSubject(assignedNode);\n\t\t\t\t\treturn (TripleElement) proxy;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// recurse down\n\t\t\t\t\tTripleElement bottom = assignNullSubjectInProxies(((TripleElement)proxy), proxyFor, assignedNode);\n\t\t\t\t\t// make the proxy next and reassign this subject as assignedNode\n\t\t\t\t\t((ProxyNode)((TripleElement)proxy).getSubject()).setReplacementNode(assignedNode);\n\t\t\t\t\t((TripleElement)proxy).setSubject(assignedNode);\n\t\t\t\t\tif (bottom.getNext() == null) {\n\t\t\t\t\t\tbottom.setNext(pattern);\n\t\t\t\t\t}\n\t\t\t\t\treturn bottom;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tprivate TripleElement getProxyWithNullSubject(TripleElement pattern) {\n\t\tif (pattern.getSubject() instanceof ProxyNode) {\n\t\t\tObject proxy = ((ProxyNode)pattern.getSubject()).getProxyFor();\n\t\t\tif (proxy instanceof TripleElement) {\n\t\t\t\tif (((TripleElement)proxy).getSubject() == null) {\n\t\t\t\t\treturn (TripleElement)proxy;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\treturn getProxyWithNullSubject(((TripleElement)proxy));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tprivate boolean isComparisonViaBuiltin(Object robj, Object lobj) {\n\t\tif (robj instanceof TripleElement && lobj instanceof Node &&\n\t\t\t\t((TripleElement)robj).getNext() instanceof BuiltinElement) {\n\t\t\tBuiltinElement be = (BuiltinElement) ((TripleElement)robj).getNext();\n\t\t\tif (isComparisonBuiltin(be.getFuncName()) && be.getArguments().size() == 1) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate boolean isModifiedTripleViaBuitin(Object robj) {\n\t\tif (robj instanceof TripleElement && ((TripleElement)robj).getNext() instanceof BuiltinElement) {\n\t\t\tBuiltinElement be = (BuiltinElement) ((TripleElement)robj).getNext();\n\t\t\tif (((TripleElement)robj).getPredicate() instanceof RDFTypeNode) {\n\t\t\t\tif (isModifiedTriple(be.getFuncType())) {\n\t\t\t\t\tNode subj = ((TripleElement)robj).getSubject();\n\t\t\t\t\tNode arg = (be.getArguments() != null && be.getArguments().size() > 0) ? be.getArguments().get(0) : null;\n\t\t\t\t\tif (subj == null && arg == null) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\tif (subj != null && arg != null && subj.equals(arg)) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (isModifiedTriple(be.getFuncType()) && ((TripleElement)robj).getObject().equals(be.getArguments().get(0))) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate boolean doVariableSubstitution(GraphPatternElement gpe, VariableNode v1, VariableNode v2) {\n\t\tboolean retval = false;\n\t\tdo {\n\t\t\tif (gpe instanceof TripleElement) {\n\t\t\t\tif (((TripleElement)gpe).getSubject().equals(v1)) {\n\t\t\t\t\t((TripleElement)gpe).setSubject(v2);\n\t\t\t\t\tretval = true;\n\t\t\t\t}\n\t\t\t\telse if (((TripleElement)gpe).getObject().equals(v1)) {\n\t\t\t\t\t((TripleElement)gpe).setObject(v2);\n\t\t\t\t\tretval = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (gpe instanceof BuiltinElement) {\n\t\t\t\tList args = ((BuiltinElement)gpe).getArguments();\n\t\t\t\tfor (int j = 0; j < args.size(); j++) {\n\t\t\t\t\tif (args.get(j).equals(v1)) {\n\t\t\t\t\t\targs.set(j, v2);\n\t\t\t\t\t\tretval = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (gpe instanceof Junction) {\n\t\t\t\tlogger.error(\"Not yet handled\");\n\t\t\t}\n\t\t\tgpe = gpe.getNext();\n\t\t} while (gpe != null);\n\t\treturn retval;\n\t}\n\n\t/**\n\t * This method returns true if the argument node is bound in some other element of the rule\n\t * \n\t * @param rule\n\t * @param gpe\n\t * @param v\n\t * @return\n\t */\n\tpublic static boolean variableIsBound(Rule rule, GraphPatternElement gpe,\n\t\t\tNode v) {\n\t\tif (v instanceof NamedNode) {\n\t\t\tif (((NamedNode)v).getNodeType() != null && !(((NamedNode)v).getNodeType().equals(NodeType.VariableNode))) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\t// Variable is bound if it appears in a triple or as the return argument of a built-in\n\t\tList givens = rule.getGivens();\n\t\tif (variableIsBoundInOtherElement(givens, 0, gpe, true, false, v)) {\n\t\t\treturn true;\n\t\t}\n\t\tList ifs = rule.getIfs();\n\t\tif (variableIsBoundInOtherElement(ifs, 0, gpe, true, false, v)) {\n\t\t\treturn true;\n\t\t}\n\t\tList thens = rule.getThens();\n\t\tif (variableIsBoundInOtherElement(thens, 0, gpe, false, true, v)) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate GraphPatternElement createBinaryBuiltin(String name, Object lobj, Object robj) throws InvalidNameException, InvalidTypeException, TranslationException {\n\t\tif (name.equals(JunctionType.AND_ALPHA) || name.equals(JunctionType.AND_SYMBOL) || name.equals(JunctionType.OR_ALPHA) || name.equals(JunctionType.OR_SYMBOL)) {\n\t\t\tJunction jct = new Junction();\n\t\t\tjct.setJunctionName(name);\n\t\t\tjct.setLhs(lobj);\n\t\t\tjct.setRhs(robj);\n\t\t\treturn jct;\n\t\t}\n\t\telse {\n\t\t\tBuiltinElement builtin = new BuiltinElement();\n\t\t\tbuiltin.setFuncName(name);\n\t\t\tif (lobj != null) {\n\t\t\t\tbuiltin.addArgument(nodeCheck(lobj));\n\t\t\t}\n\t\t\tif (robj != null) {\n\t\t\t\tbuiltin.addArgument(nodeCheck(robj));\n\t\t\t}\n\t\t\treturn builtin;\n\t\t}\n\t}\n\t\n\tprotected Junction createJunction(Expression expr, String name, Object lobj, Object robj) {\n\t\tJunction junction = new Junction();\n\t\tjunction.setJunctionName(name);\n\t\tjunction.setLhs(lobj);\n\t\tjunction.setRhs(robj);\n\t\treturn junction;\n\t}\n\n\tprivate Object createUnaryBuiltin(String name, Object sobj) throws InvalidNameException, InvalidTypeException, TranslationException {\n\t\tif (sobj instanceof com.ge.research.sadl.model.gp.Literal && BuiltinType.getType(name).equals(BuiltinType.Minus)) {\n\t\t\tObject theVal = ((com.ge.research.sadl.model.gp.Literal)sobj).getValue();\n\t\t\tif (theVal instanceof Integer) {\n\t\t\t\ttheVal = ((Integer)theVal) * -1;\n\t\t\t}\n\t\t\telse if (theVal instanceof Long) {\n\t\t\t\ttheVal = ((Long)theVal) * -1;\n\t\t\t}\n\t\t\telse if (theVal instanceof Float) {\n\t\t\t\ttheVal = ((Float)theVal) * -1;\n\t\t\t}\n\t\t\telse if (theVal instanceof Double) {\n\t\t\t\ttheVal = ((Double)theVal) * -1;\n\t\t\t}\n\t\t\t((com.ge.research.sadl.model.gp.Literal)sobj).setValue(theVal);\n\t\t\t((com.ge.research.sadl.model.gp.Literal)sobj).setOriginalText(\"-\" + ((com.ge.research.sadl.model.gp.Literal)sobj).getOriginalText());\n\t\t\treturn sobj;\n\t\t}\n\t\tif (sobj instanceof Junction) {\n\t\t\t// If the junction has two literal values, apply the op to both of them.\n\t\t\tJunction junc = (Junction) sobj;\n\t\t\tObject lhs = junc.getLhs();\n\t\t\tObject rhs = junc.getRhs();\n\t\t\tif (lhs instanceof com.ge.research.sadl.model.gp.Literal && rhs instanceof com.ge.research.sadl.model.gp.Literal) {\n\t\t\t\tlhs = createUnaryBuiltin(name, lhs);\n\t\t\t\trhs = createUnaryBuiltin(name, rhs);\n\t\t\t\tjunc.setLhs(lhs);\n\t\t\t\tjunc.setRhs(rhs);\n\t\t\t}\n\t\t\treturn junc;\n\t\t}\n\t\tif (BuiltinType.getType(name).equals(BuiltinType.Equal)) {\n\t\t\tif (sobj instanceof BuiltinElement) {\n\t\t\t\tif (isComparisonBuiltin(((BuiltinElement)sobj).getFuncName())) {\n\t\t\t\t\t// this is a \"is \"--translates to (ignore is)\n\t\t\t\t\treturn sobj;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (sobj instanceof com.ge.research.sadl.model.gp.Literal || sobj instanceof NamedNode) {\n\t\t\t\t// an \"=\" interval value of a value is just the value\n\t\t\t\treturn sobj;\n\t\t\t}\n\t\t}\n\t\tBuiltinElement builtin = new BuiltinElement();\n\t\tbuiltin.setFuncName(name);\n\t\tif (isModifiedTriple(builtin.getFuncType())) {\n\t\t\tif (sobj instanceof TripleElement) {\n\t\t\t\t((TripleElement)sobj).setType(getTripleModifierType(builtin.getFuncType()));\n\t\t\t\treturn sobj;\n\t\t\t}\n\t\t}\n\t\tif (sobj != null) {\n\t\t\tbuiltin.addArgument(nodeCheck(sobj));\n\t\t}\n\t\treturn builtin;\n\t}\n\n\tprivate TripleModifierType getTripleModifierType(BuiltinType btype) {\n\t\tif (btype.equals(BuiltinType.Not) || btype.equals(BuiltinType.NotEqual)) {\n\t\t\treturn TripleModifierType.Not;\n\t\t}\n\t\telse if (btype.equals(BuiltinType.Only)) {\n\t\t\treturn TripleModifierType.Only;\n\t\t}\n\t\telse if (btype.equals(BuiltinType.NotOnly)) {\n\t\t\treturn TripleModifierType.NotOnly;\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic Object processExpression(BooleanLiteral expr) {\n\t\tObject lit = super.processExpression(expr);\n\t\treturn lit;\n\t}\n\t\n\tpublic Node processExpression(Constant expr) throws InvalidNameException {\n//\t\tSystem.out.println(\"processing \" + expr.getClass().getCanonicalName() + \": \" + expr.getConstant());\n\t\tif (expr.getConstant().equals(\"known\")) {\n\t\t\treturn new KnownNode();\n\t\t}\n\t\treturn new ConstantNode(expr.getConstant());\n\t}\n\t\n\tpublic Object processExpression(Declaration expr) throws TranslationException {\n//\t\tString nn = expr.getNewName();\n\t\tSadlTypeReference type = expr.getType();\n\t\tString article = expr.getArticle();\n\t\tString ordinal = expr.getOrdinal();\n\t\tObject typenode = processExpression(type);\n\t\tif (article != null && isInstance(typenode)) {\n\t\t\taddError(\"An article (e.g., '\" + article + \"') should not be used in front of the name of an instance of a class.\", expr);\n\t\t}\n\t\telse if (article != null && isVariable(typenode)) {\n\t\t\taddError(\"An article (e.g., '\" + article + \"') should not be used in front of the name of a variable.\", expr);\n\t\t}\n\t\telse if (article != null && !isProperty(typenode) && !isDefinitionOfExplicitVariable(expr)) {\n\t\t\t// article should never be null, otherwise it wouldn't be a declaration\n\t\t\tint ordNum = 1;\n\t\t\tif (ordinal != null) {\n\t\t\t\tordNum = getOrdinalNumber(ordinal);\n\t\t\t}\n\t\t\telse if (article.equals(\"another\")) {\n\t\t\t\tordNum = 2;\n\t\t\t}\n\n\t\t\tif (isUseArticlesInValidation() && !isDefiniteArticle(article) && \n\t\t\t\t\ttypenode instanceof NamedNode && \n\t\t\t\t\t(((NamedNode)typenode).getNodeType().equals(NodeType.ClassNode) || ((NamedNode)typenode).getNodeType().equals(NodeType.ClassListNode))) {\n\t\t\t\tif (!isCruleVariableDefinitionPossible(expr)) {\n\t\t\t\t\tif (ordinal != null) {\n\t\t\t\t\t\taddError(\"Did not expect an indefinite article reference with ordinality in rule conclusion\", expr);\n\t\t\t\t\t}\n\t\t\t\t\treturn typenode;\n\t\t\t\t}\n\n\t\t\t\t// create a CRule variable\n\t\t\t\tString nvar = getNewVar(expr);\n\t\t\t\tVariableNode var = addCruleVariable((NamedNode)typenode, ordNum, nvar, expr, getHostEObject());\n//\t\t\t\tSystem.out.println(\"Added crule variable: \" + typenode.toString() + \", \" + ordNum + \", \" + var.toString());\n\t\t\t\treturn var;\n\t\t\t}\n\t\t\telse if (typenode != null && typenode instanceof NamedNode) {\n\t\t\t\tVariableNode var = null;\n\t\t\t\tif (isUseArticlesInValidation()) {\n\t\t\t\t\tvar = getCruleVariable((NamedNode)typenode, ordNum);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tString nvar = getNewVar(expr);\n\t\t\t\t\t\tvar = createVariable(nvar);\n\t\t\t\t\t\tvar.setType((NamedNode)typenode);\n\t\t\t\t\t} catch (IOException e) {\n\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t} catch (PrefixNotFoundException e) {\n\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t} catch (InvalidNameException e) {\n\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t} catch (InvalidTypeException e) {\n\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t} catch (ConfigurationException e) {\n\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (var == null) {\n\t\t\t\t\taddError(\"Did not find crule variable for type '\" + ((NamedNode)typenode).toString() + \"', definite article, ordinal \" + ordNum, expr);\n\t\t\t\t}\n\t\t\t\telse {\n//\t\t\t\t\tSystem.out.println(\"Retrieved crule variable: \" + typenode.toString() + \", \" + ordNum + \", \" + var.toString());\n\t\t\t\t\treturn var;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\taddError(\"No type identified\", expr);\n\t\t\t}\n\t\t}\n\t\telse if (isUseArticlesInValidation() && article == null) {\n\t\t\tif (isClass(typenode)) {\n\t\t\t\taddError(\"A class name should be preceded by either an indefinite (e.g., 'a' or 'an') or a definite (e.g., 'the') article.\", expr);\n\t\t\t}\n\t\t}\n\t\treturn typenode;\n\t}\n\t\n\tprotected EObject getHostEObject() {\n\t\treturn hostEObject ;\n\t}\n\t\n\tprotected void setHostEObject(EObject host) {\n\t\tif (hostEObject != null) {\n\t\t\tclearCruleVariablesForHostObject(hostEObject);\n\t\t}\n\t\thostEObject = host;\n\t}\n\t\n\tpublic Object processExpression(ElementInList expr) throws InvalidNameException, InvalidTypeException, TranslationException {\n\t\t// create a builtin for this\n\t\tif (expr.getElement() != null) {\n\t\t\tif (expr.getElement() instanceof PropOfSubject) {\n\t\t\t\tExpression predicate = ((PropOfSubject)expr.getElement()).getLeft();\n\t\t\t\tExpression subject = ((PropOfSubject)expr.getElement()).getRight();\n\t\t\t\tObject lst = processExpression(subject);\n\t\t\t\tObject element = processExpression(predicate);\n\t\t\t\tBuiltinElement bi = new BuiltinElement();\n\t\t\t\tbi.setFuncName(\"elementInList\");\n\t\t\t\tbi.addArgument(nodeCheck(lst));\n\t\t\t\tbi.addArgument(nodeCheck(element));\n\t\t\t\treturn bi;\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn processExpression(expr.getElement());\n//\t\t\t\tthrow new TranslationException(\"Unhandled ElementInList expression\");\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprivate boolean isVariable(Object node) {\n\t\tif (node instanceof NamedNode) {\n\t\t\tif (((NamedNode)node).getNodeType() != null && ((NamedNode)node).getNodeType().equals(NodeType.VariableNode)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprivate boolean isClass(Object node) {\n\t\tif (node instanceof NamedNode) {\n\t\t\tif (((NamedNode)node).getNodeType() != null && ((NamedNode)node).getNodeType().equals(NodeType.ClassNode)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprivate boolean isInstance(Object node) {\n\t\tif (node instanceof NamedNode) {\n\t\t\tif (((NamedNode)node).getNodeType() != null && ((NamedNode)node).getNodeType().equals(NodeType.InstanceNode)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprivate boolean isProperty(Object node) {\n\t\tif (node instanceof NamedNode) {\n\t\t\treturn isProperty(((NamedNode) node).getNodeType());\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprivate boolean isCruleVariableDefinitionPossible(Declaration expr) {\n\t\tif (getRulePart().equals(RulePart.CONCLUSION) && !isDeclInThereExists(expr)) {\n\t\t\t// this can't be a crule variable unless there is no rule body\n\t\t\tif (getTarget() != null && getTarget() instanceof Rule && \n\t\t\t\t\t(((Rule)getTarget()).getIfs() != null || ((Rule)getTarget()).getGivens() != null)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\tif (expr.eContainer() != null && expr.eContainer() instanceof BinaryOperation && isEqualOperator(((BinaryOperation)expr.eContainer()).getOp()) &&\n\t\t\t\t!((BinaryOperation)expr.eContainer()).getLeft().equals(expr) && ((BinaryOperation)expr.eContainer()).getLeft() instanceof Declaration) {\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\t\t\n\tprivate boolean isDefinitionOfExplicitVariable(Declaration expr) {\n\t\tEObject cont = expr.eContainer();\n\t\ttry {\n\t\t\tif (cont instanceof BinaryOperation && ((BinaryOperation)cont).getLeft() instanceof SadlResource && \n\t\t\t\t\tgetDeclarationExtensions().getOntConceptType((SadlResource)((BinaryOperation)cont).getLeft()).equals(OntConceptType.VARIABLE)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t} catch (CircularDefinitionException e) {\n\t\t\taddError(e.getMessage(), expr);\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprivate int getOrdinalNumber(String ordinal) throws TranslationException {\n\t\tif (ordinal == null) {\n\t\t\tthrow new TranslationException(\"Unexpected null ordinal on call to getOrdinalNumber\");\n\t\t}\n\t\tif (ordinal.equals(\"first\")) return 1;\n\t\tif (ordinal.equals(\"second\") || ordinal.equals(\"other\")) return 2;\n\t\tif (ordinal.equals(\"third\")) return 3;\n\t\tif (ordinal.equals(\"fourth\")) return 4;\n\t\tif (ordinal.equals(\"fifth\")) return 5;\n\t\tif (ordinal.equals(\"sixth\")) return 6;\n\t\tif (ordinal.equals(\"seventh\")) return 7;\n\t\tif (ordinal.equals(\"eighth\")) return 8;\n\t\tif (ordinal.equals(\"ninth\")) return 9;\n\t\tif (ordinal.equals(\"tenth\")) return 10;\n\t\tthrow new TranslationException(\"Unexpected ordinal '\" + ordinal + \"'; can't handle.\");\n\t}\n\t\n\tprivate String nextOrdinal(int ordinalNumber) throws TranslationException {\n\t\tif (ordinalNumber == 0) return \"first\";\n\t\tif (ordinalNumber == 1) return\"second\";\n\t\tif (ordinalNumber == 2) return\"third\";\n\t\tif (ordinalNumber == 3) return\"fourth\";\n\t\tif (ordinalNumber == 4) return\"fifth\";\n\t\tif (ordinalNumber == 5) return\"sixth\";\n\t\tif (ordinalNumber == 6) return\"seventh\";\n\t\tif (ordinalNumber == 7) return\"eighth\";\n\t\tif (ordinalNumber == 8) return\"ninth\";\n\t\tif (ordinalNumber == 9) return\"tenth\";\n\t\tthrow new TranslationException(\"Unexpected ordinal number '\" + ordinalNumber + \"'is larger than is handled at this time.\");\n\t}\n\t\n\tprivate boolean isDefiniteArticle(String article) {\n\t\tif (article != null && article.equalsIgnoreCase(\"the\")) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprivate Object processExpression(SadlTypeReference type) throws TranslationException {\n\t\tif (type instanceof SadlSimpleTypeReference) {\n\t\t\treturn processExpression(((SadlSimpleTypeReference)type).getType());\n\t\t}\n\t\telse if (type instanceof SadlPrimitiveDataType) {\n\t\t\tSadlDataType pt = ((SadlPrimitiveDataType)type).getPrimitiveType();\n\t\t\treturn sadlDataTypeToNamedNode(pt); \n\t\t}\n\t\telse if (type instanceof SadlUnionType) {\n\t\t\ttry {\n\t\t\t\tObject unionObj = sadlTypeReferenceToObject(type);\n\t\t\t\tif (unionObj instanceof Node) {\n\t\t\t\t\treturn unionObj;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\taddWarning(\"Unions not yet handled in this context\", type);\n\t\t\t\t}\n\t\t\t} catch (JenaProcessorException e) {\n\t\t\t\tthrow new TranslationException(\"Error processing union\", e);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tthrow new TranslationException(\"Unhandled type of SadlTypeReference: \" + type.getClass().getCanonicalName());\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprivate Object sadlDataTypeToNamedNode(SadlDataType pt) {\n\t\t/*\n\t\t string | boolean | decimal | int | long | float | double | duration | dateTime | time | date |\n gYearMonth | gYear | gMonthDay | gDay | gMonth | hexBinary | base64Binary | anyURI | \n integer | negativeInteger | nonNegativeInteger | positiveInteger | nonPositiveInteger | \n byte | unsignedByte | unsignedInt | anySimpleType;\n\t\t */\n\t\tString typeStr = pt.getLiteral();\n\t\tif (typeStr.equals(\"string\")) {\n\t\t\treturn new NamedNode(XSD.xstring.getURI(), NodeType.DataTypeNode);\n\t\t}\n\t\tif (typeStr.equals(\"boolean\")) {\n\t\t\treturn new NamedNode(XSD.xboolean.getURI(), NodeType.DataTypeNode);\n\t\t}\n\t\tif (typeStr.equals(\"byte\")) {\n\t\t\treturn new NamedNode(XSD.xbyte.getURI(), NodeType.DataTypeNode);\n\t\t}\n\t\tif (typeStr.equals(\"int\")) {\n\t\t\treturn new NamedNode(XSD.xint.getURI(), NodeType.DataTypeNode);\n\t\t}\n\t\tif (typeStr.equals(\"long\")) {\n\t\t\treturn new NamedNode(XSD.xlong.getURI(), NodeType.DataTypeNode);\n\t\t}\n\t\tif (typeStr.equals(\"float\")) {\n\t\t\treturn new NamedNode(XSD.xfloat.getURI(), NodeType.DataTypeNode);\n\t\t}\n\t\tif (typeStr.equals(\"double\")) {\n\t\t\treturn new NamedNode(XSD.xdouble.getURI(), NodeType.DataTypeNode);\n\t\t}\n\t\tif (typeStr.equals(\"short\")) {\n\t\t\treturn new NamedNode(XSD.xshort.getURI(), NodeType.DataTypeNode);\n\t\t}\n\t\treturn new NamedNode(XSD.getURI() + \"#\" + typeStr, NodeType.DataTypeNode);\n\t}\n\t\n\tpublic Object processExpression(Name expr) throws TranslationException, InvalidNameException, InvalidTypeException {\n\t\tif (expr.isFunction()) {\n\t\t\treturn processFunction(expr);\n\t\t}\n\t\tSadlResource qnm =expr.getName();\n\t\tString nm = getDeclarationExtensions().getConcreteName(qnm);\n\t\tif (nm == null) {\n\t\t\tSadlResource srnm = qnm.getName();\n\t\t\tif (srnm != null) {\n\t\t\t\treturn processExpression(srnm);\n\t\t\t}\n\t\t\taddError(SadlErrorMessages.TRANSLATE_NAME_SADLRESOURCE.toString(), expr);\n//\t\t\tthrow new InvalidNameException(\"Unable to resolve SadlResource to a name\");\n\t\t}\n\t\telse if (qnm.equals(expr) && expr.eContainer() instanceof BinaryOperation && \n\t\t\t\t((BinaryOperation)expr.eContainer()).getRight() != null && ((BinaryOperation)expr.eContainer()).getRight().equals(qnm)) {\n\t\t\taddError(\"It appears that '\" + nm + \"' is not defined.\", expr);\n\t\t}\n\t\telse {\n\t\t\treturn processExpression(qnm);\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprivate String getPrefix(String qn) {\n\t\tif (qn.contains(\":\")) {\n\t\t\treturn qn.substring(0,qn.indexOf(\":\"));\n\t\t}\n\t\treturn qn;\n\t}\n\tpublic Object \tprocessExpression(NumberLiteral expr) {\n\t\tObject lit = super.processExpression(expr);\n\t\treturn lit;\n\t}\n\t\n\tpublic Object processExpression(StringLiteral expr) {\n\t\treturn super.processExpression(expr);\n\t}\n\t\n\tpublic Object processExpression(PropOfSubject expr) throws InvalidNameException, InvalidTypeException, TranslationException {\n\t\tExpression predicate = expr.getLeft();\n\t\tif (predicate == null) {\n\t\t\taddError(\"Predicate in expression is null. Are parentheses needed?\", expr);\n\t\t\treturn null;\n\t\t}\n\t\tExpression subject = expr.getRight();\n\t\tObject trSubj = null;\n\t\tObject trPred = null;\n\t\tNode subjNode = null;\n\t\tNode predNode = null;\n\t\tString constantBuiltinName = null;\n\t\tint numBuiltinArgs = 0;\n\t\tif (predicate instanceof Constant) {\n\t\t\t// this is a pseudo PropOfSubject; the predicate is a constant\n\t\t\tString cnstval = ((Constant)predicate).getConstant();\n\t\t\tif (cnstval.equals(\"length\") || cnstval.equals(\"the length\")) {\n\t\t\t\tconstantBuiltinName = \"length\";\n\t\t\t\tnumBuiltinArgs = 1;\n\t\t\t\tif (subject instanceof PropOfSubject) {\n\t\t\t\t\tpredicate = ((PropOfSubject)subject).getLeft();\n\t\t\t\t\tsubject = ((PropOfSubject)subject).getRight();\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (cnstval.equals(\"count\")) {\n\t\t\t\tconstantBuiltinName = cnstval;\n\t\t\t\tnumBuiltinArgs = 2;\n\t\t\t\tif (subject instanceof PropOfSubject) {\n\t\t\t\t\tpredicate = ((PropOfSubject)subject).getLeft();\n\t\t\t\t\tsubject = ((PropOfSubject)subject).getRight();\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (cnstval.endsWith(\"index\")) {\n\t\t\t\tconstantBuiltinName = cnstval;\n\t\t\t\tnumBuiltinArgs = 2;\n\t\t\t\tif (subject instanceof PropOfSubject) {\n\t\t\t\t\tpredicate = ((PropOfSubject)subject).getLeft();\n\t\t\t\t\tsubject = ((PropOfSubject)subject).getRight();\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (cnstval.equals(\"first element\")) {\n\t\t\t\tconstantBuiltinName = \"firstElement\";\n\t\t\t\tnumBuiltinArgs = 1;\n\t\t\t\tif (subject instanceof PropOfSubject) {\n\t\t\t\t\tpredicate = ((PropOfSubject)subject).getLeft();\n\t\t\t\t\tsubject = ((PropOfSubject)subject).getRight();\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (cnstval.equals(\"last element\")) {\n\t\t\t\tconstantBuiltinName = \"lastElement\";\n\t\t\t\tnumBuiltinArgs = 1;\n\t\t\t\tif (subject instanceof PropOfSubject) {\n\t\t\t\t\tpredicate = ((PropOfSubject)subject).getLeft();\n\t\t\t\t\tsubject = ((PropOfSubject)subject).getRight();\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (cnstval.endsWith(\"element\")) {\n\t\t\t\tconstantBuiltinName = cnstval;\n\t\t\t\tnumBuiltinArgs = 2;\n\t\t\t\tif (subject instanceof PropOfSubject) {\n\t\t\t\t\tpredicate = ((PropOfSubject)subject).getLeft();\n\t\t\t\t\tsubject = ((PropOfSubject)subject).getRight();\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tSystem.err.println(\"Unhandled constant property in translate PropOfSubj: \" + cnstval);\n\t\t\t}\n\t\t}\n\t\telse if (predicate instanceof ElementInList) {\n\t\t\ttrSubj = processExpression(subject);\n\t\t\ttrPred = processExpression(predicate);\n\t\t\tBuiltinElement bi = new BuiltinElement();\n\t\t\tbi.setFuncName(\"elementInList\");\n\t\t\tbi.addArgument(nodeCheck(trSubj));\n\t\t\tbi.addArgument(nodeCheck(trPred));\n\t\t\treturn bi;\n\t\t\t\n\t\t}\n\t\tif (subject != null) {\n\t\t\ttrSubj = processExpression(subject);\n\t\t\tif (isUseArticlesInValidation() && subject instanceof Name && trSubj instanceof NamedNode && ((NamedNode)trSubj).getNodeType().equals(NodeType.ClassNode)) {\n\t\t\t\t// we have a class in a PropOfSubject that does not have an article (otherwise it would have been a Declaration)\n\t\t\t\taddError(\"A class name in this context should be preceded by an article, e.g., 'a', 'an', or 'the'.\", subject);\n\t\t\t}\n\t\t}\n\t\tboolean isPreviousPredicate = false;\n\t\tif (predicate != null) {\n\t\t\ttrPred = processExpression(predicate);\n\t\t}\n\t\tif (constantBuiltinName == null || numBuiltinArgs == 1) {\n\t\t\tTripleElement returnTriple = null;\n\t\t\tif (trPred instanceof Node) {\n\t\t\t\tpredNode = (Node) trPred;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tpredNode = new ProxyNode(trPred);\n\t\t\t}\n\t\t\tif (trSubj instanceof Node) {\n\t\t\t\tsubjNode = (Node) trSubj;\n\t\t\t}\n\t\t\telse if (trSubj != null) {\n\t\t\t\tsubjNode = new ProxyNode(trSubj);\n\t\t\t}\n\t\t\tif (predNode != null && predNode instanceof Node) {\n\t\t\t\treturnTriple = new TripleElement(subjNode, predNode, null);\n\t\t\t\treturnTriple.setSourceType(TripleSourceType.PSV);\n\t\t\t\tif (constantBuiltinName == null) {\n\t\t\t\t\treturn returnTriple;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (numBuiltinArgs == 1) {\n\t\t\t\tObject bi = createUnaryBuiltin(expr, constantBuiltinName, new ProxyNode(returnTriple) );\n\t\t\t\treturn bi;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tpredNode = new RDFTypeNode();\t\t\t\n\t\t\t\tNode variable = getVariableNode(expr, null, predNode, subjNode);\n\t\t\t\treturnTriple = new TripleElement();\n\t\t\t\treturnTriple.setSubject(variable);\n\t\t\t\treturnTriple.setPredicate(predNode);\n\t\t\t\treturnTriple.setObject(subjNode);\n\t\t\t\tif (subjNode instanceof NamedNode && !((NamedNode)subjNode).getNodeType().equals(NodeType.ClassNode)) {\n\t\t\t\t\taddError(SadlErrorMessages.IS_NOT_A.get(subjNode.toString(), \"class\"), subject);\n\t\t\t\t}\n\t\t\t\treturnTriple.setSourceType(TripleSourceType.ITC);\n\t\t\t\treturn returnTriple;\n\t\t\t}\n\t\t}\n\t\telse {\t// none of these create more than 2 arguments\n\t\t\tObject bi = createBinaryBuiltin(constantBuiltinName, trPred, nodeCheck(trSubj));\n\t\t\treturn bi;\n\t\t}\n\t}\n\t\n\tpublic Node processExpression(SadlResource expr) throws TranslationException {\n\t\tString nm = getDeclarationExtensions().getConcreteName(expr);\n\t\tString ns = getDeclarationExtensions().getConceptNamespace(expr);\n\t\tString prfx = getDeclarationExtensions().getConceptPrefix(expr);\n\t\tOntConceptType type;\n\t\ttry {\n\t\t\ttype = getDeclarationExtensions().getOntConceptType(expr);\n\t\t} catch (CircularDefinitionException e) {\n\t\t\ttype = e.getDefinitionType();\n\t\t\taddError(e.getMessage(), expr);\n\t\t}\n\t\tif (type.equals(OntConceptType.VARIABLE) && nm != null) {\n\t\t\tVariableNode vn = null;\n\t\t\ttry {\n\t\t\t\tvn = createVariable(expr);\n\t\t\t} catch (IOException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (PrefixNotFoundException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (InvalidNameException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (InvalidTypeException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (ConfigurationException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t\treturn vn;\n\t\t}\n\t\telse if (nm != null) {\n\t\t\tNamedNode n = new NamedNode(nm, ontConceptTypeToNodeType(type));\n\t\t\tn.setNamespace(ns);\n\t\t\tn.setPrefix(prfx);\n\t\t\treturn n;\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprotected Object processSubjHasPropUnitExpression(SubjHasProp expr) throws InvalidNameException, InvalidTypeException, TranslationException {\n\t\tExpression valexpr = expr.getLeft();\n\t\tObject valarg = processExpression(valexpr);\n\t\tif (ignoreUnittedQuantities) {\n\t\t\treturn valarg;\n\t\t}\n\t\tString unit = SadlASTUtils.getUnitAsString(expr);\n\t\tif (valarg instanceof com.ge.research.sadl.model.gp.Literal) {\n\t\t\t((com.ge.research.sadl.model.gp.Literal)valarg).setUnits(unit);\n\t\t\treturn valarg;\n\t\t}\n\t\tcom.ge.research.sadl.model.gp.Literal unitLiteral = new com.ge.research.sadl.model.gp.Literal();\n\t\tunitLiteral.setValue(unit);\n\t\treturn createBinaryBuiltin(\"unittedQuantity\", valarg, unitLiteral);\n\t}\n\n\t\n\tpublic Object processExpression(SubjHasProp expr) throws InvalidNameException, InvalidTypeException, TranslationException {\n//\t\tSystem.out.println(\"processing \" + expr.getClass().getCanonicalName() + \": \" + expr.getProp().toString());\n\t\tExpression subj = expr.getLeft();\n\t\tSadlResource pred = expr.getProp();\n\t\tExpression obj = expr.getRight();\n\t\treturn processSubjHasProp(subj, pred, obj);\n\t}\n\t\n\tprivate TripleElement processSubjHasProp(Expression subj, SadlResource pred, Expression obj)\n\t\t\tthrows InvalidNameException, InvalidTypeException, TranslationException {\n\t\tboolean isSubjVariableDefinition = false;\n\t\tboolean isObjVariableDefinition = false;\n\t\tName subjVariableName = null;\n\t\tName objVariableName = null;\n\t\tboolean subjectIsVariable = false;\n\t\tboolean objectIsVariable = false;\n\t\ttry {\n\t\t\tif (subj instanceof Name && isVariableDefinition((Name)subj)) {\n\t\t\t\t// variable is defined by domain of property pred\n\t\t\t\tisSubjVariableDefinition = true;\n\t\t\t\tsubjVariableName = (Name)subj;\n\t\t\t\tsubjectIsVariable = true;\n\t\t\t}\n\t\t\telse if (subj instanceof Declaration && isVariableDefinition((Declaration)subj)) {\n\t\t\t\t// variable is defined by a CRule declaration\n\t\t\t\tisSubjVariableDefinition = true;\n\t\t\t\tsubjectIsVariable = true;\t\t\t}\n\t\t\tif (obj instanceof Name && isVariableDefinition((Name)obj)) {\n\t\t\t\t// variable is defined by range of property pred\n\t\t\t\tisObjVariableDefinition = true;\n\t\t\t\tobjVariableName = (Name)obj;\n\t\t\t\tobjectIsVariable = true;\n\t\t\t}\n\t\t\telse if (obj instanceof Declaration && isVariableDefinition((Declaration)obj)) {\n\t\t\t\t// variable is defined by a CRule declaration\n\t\t\t\tisObjVariableDefinition = true;\n\t\t\t\tobjectIsVariable = true;\n\t\t\t}\n\t\t} catch (CircularDefinitionException e1) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te1.printStackTrace();\n\t\t}\n\t\t\n\t\tif (!isSubjVariableDefinition && !isObjVariableDefinition && getModelValidator() != null) {\n\t\t\tgetModelValidator().checkPropertyDomain(getTheJenaModel(), subj, pred, pred, false);\n\t\t\tif (obj != null) {\t// rules can have SubjHasProp expressions with null object\n\t\t\t\ttry {\n\t\t\t\t\tgetModelValidator().checkPropertyValueInRange(getTheJenaModel(), subj, pred, obj, new StringBuilder());\n\t\t\t\t} catch (DontTypeCheckException e) {\n\t\t\t\t\t// don't do anything\n\t\t\t\t} catch (PropertyWithoutRangeException e) {\n\t\t\t\t\taddError(\"Property does not have a range\", pred);\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\tthrow new TranslationException(\"Error checking value in range\", e);\n\t\t\t\t} \n\t\t\t}\n\t\t}\n\t\tObject sobj = null;\n\t\tObject pobj = null;\n\t\tObject oobj = null;\n\n\t\tif (pred != null) {\n\t\t\ttry {\n\t\t\t\tpobj = processExpression(pred);\n\t\t\t\tProperty prop = getTheJenaModel().getProperty(((NamedNode)pobj).toFullyQualifiedString());\n\t\t\t\tOntConceptType predOntConceptType = getDeclarationExtensions().getOntConceptType(pred);\n\t\t\t\tConceptName propcn = new ConceptName(((NamedNode)pobj).toFullyQualifiedString());\n\t\t\t\tpropcn.setType(nodeTypeToConceptType(ontConceptTypeToNodeType(predOntConceptType)));\n\t\t\t\tif (isSubjVariableDefinition && pobj instanceof NamedNode) {\n\t\t\t\t\tVariableNode var = null;\n\t\t\t\t\tif (subjVariableName != null) {\n//\t\t\t\t\t\tSystem.out.println(\"Variable '\" + getDeclarationExtensions().getConcreteName(subjVariableName.getName()) + \"' is defined by domain of property '\" + \n//\t\t\t\t\t\t\t\tgetDeclarationExtensions().getConceptUri(pred) + \"'\");\n\t\t\t\t\t\tvar = createVariable(subjVariableName.getName()); //getDeclarationExtensions().getConceptUri(subjVariableName.getName()));\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tsobj = processExpression(subj);\n\t\t\t\t\t}\n\t\t\t\t\tif (var != null && var.getType() == null) {\t\t// it's a variable and we don't know the type so try to get the type\n\t\t\t\t\t\tTypeCheckInfo dtci = getModelValidator().getTypeInfoFromDomain(propcn, prop, pred);\n\t\t\t\t\t\tif (dtci != null) {\n\t\t\t\t\t\t\tif (dtci.getCompoundTypes() != null) {\n\t\t\t\t\t\t\t\tObject jct = compoundTypeCheckTypeToNode(dtci, pred);\n\t\t\t\t\t\t\t\tif (jct != null && jct instanceof Junction) {\n\t\t\t\t\t\t\t\t\tif (var.getType() == null) {\n\t\t\t\t\t\t\t\t\t\tvar.setType(nodeCheck(jct));\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\taddError(\"Compound type check did not process into expected result for variable type\", pred);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if(dtci.getTypeCheckType() != null) {\n\t\t\t\t\t\t\t\tConceptIdentifier tcitype = dtci.getTypeCheckType();\n\t\t\t\t\t\t\t\tif (tcitype instanceof ConceptName) {\n\t\t\t\t\t\t\t\t\tNamedNode defn = conceptNameToNamedNode((ConceptName)tcitype);\n\t\t\t\t\t\t\t\t\tif (var.getType() == null) {\n\t\t\t\t\t\t\t\t\t\tvar.setType((NamedNode) defn);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\taddError(\"Domain type did not return a ConceptName for variable type\", pred);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\taddError(\"Domain type check info doesn't have information to set variable type\", pred);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsobj = var;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (isObjVariableDefinition && pobj instanceof NamedNode) {\n\t\t\t\t\tVariableNode var = null;\n\t\t\t\t\tif (objVariableName != null) {\n//\t\t\t\t\t\tSystem.out.println(\"Variable '\" + getDeclarationExtensions().getConcreteName(objVariableName.getName()) + \"' is defined by range of property '\" + \n//\t\t\t\t\t\t\t\tgetDeclarationExtensions().getConceptUri(pred) + \"'\");\n\t\t\t\t\t\tvar = createVariable(getDeclarationExtensions().getConceptUri(objVariableName.getName()));\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\toobj = processExpression(obj);\n\t\t\t\t\t}\n\t\t\t\t\tif (var != null) {\n\t\t\t\t\t\tTypeCheckInfo dtci = getModelValidator().getTypeInfoFromRange(propcn, prop, pred);\n\t\t\t\t\t\tif (dtci != null && dtci.getTypeCheckType() != null) {\n\t\t\t\t\t\t\tConceptIdentifier tcitype = dtci.getTypeCheckType();\n\t\t\t\t\t\t\tif (tcitype instanceof ConceptName) {\n\t\t\t\t\t\t\t\tNamedNode defn = conceptNameToNamedNode((ConceptName)tcitype);\n\t\t\t\t\t\t\t\tif (var.getType() == null) {\n\t\t\t\t\t\t\t\t\tvar.setType((NamedNode) defn);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\taddError(\"Range type did not return a ConceptName\", pred);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\toobj = var;\n\t\t\t\t\t}\n\t\t\t\t}\n// TODO should also check for restrictions on the class and local restrictions?\n\t\t\t} catch (IOException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (PrefixNotFoundException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (ConfigurationException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (DontTypeCheckException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (CircularDefinitionException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t}\t\t\t\n\t\t}\n\t\tboolean negateTriple = false;\n\t\tif (sobj == null && subj != null) {\n\t\t\tif (subj instanceof UnaryExpression && ((UnaryExpression)subj).getOp().equals(\"not\") && pobj != null) {\n\t\t\t\t// treat this negation as applying to the whole triple\n\t\t\t\tExpression subjexpr = ((UnaryExpression)subj).getExpr();\n\t\t\t\tObject subjtr = processExpression(subjexpr);\n\t\t\t\tnegateTriple = true;\n\t\t\t\tsobj = subjtr;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tsobj = processExpression(subj);\n\t\t\t}\n\t\t}\n\t\tif (oobj == null && obj != null) {\n\t\t\toobj = processExpression(obj);\n\t\t}\n\t\tTripleElement returnTriple = null;\n\t\tif (pobj != null) {\n\t\t\treturnTriple = new TripleElement(null, nodeCheck(pobj), null);\n\t\t\treturnTriple.setSourceType(TripleSourceType.SPV);\n\t\t\tif (negateTriple) {\n\t\t\t\treturnTriple.setType(TripleModifierType.Not);\n\t\t\t}\n\t\t}\n\t\tif (sobj != null) {\n\t\t\treturnTriple.setSubject(nodeCheck(sobj));\n\t\t}\n\t\tif (oobj != null) {\n\t\t\treturnTriple.setObject(nodeCheck(oobj));\n\t\t}\n\t\treturn returnTriple;\n\t}\n\t\n\tprivate Junction compoundTypeCheckTypeToNode(TypeCheckInfo dtci, EObject expr) throws InvalidNameException, InvalidTypeException, TranslationException {\n\t\tIterator ctitr = dtci.getCompoundTypes().iterator();\n\t\tJunction last = null;\n\t\tJunction jct = null;\n\t\twhile (ctitr.hasNext()) {\n\t\t\tObject current = null;\n\t\t\tTypeCheckInfo tci = ctitr.next();\n\t\t\tif (tci.getCompoundTypes() != null) {\n\t\t\t\tcurrent = compoundTypeCheckTypeToNode(tci, expr);\n\t\t\t}\n\t\t\telse if (tci.getTypeCheckType() != null) {\n\t\t\t\tif (tci.getTypeCheckType() instanceof ConceptName) {\n\t\t\t\t\tcurrent = conceptNameToNamedNode((ConceptName) tci.getTypeCheckType());\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\taddError(\"Type check info doesn't have expected ConceptName type\", expr);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\taddError(\"Type check info doesn't have valid type\", expr);\n\t\t\t}\n\t\t\tif (current != null) {\n\t\t\t\tif (jct == null) {\n\t\t\t\t\tif (ctitr.hasNext()) {\n\t\t\t\t\t\t// there is more so new junction\n\t\t\t\t\t\tjct = new Junction();\n\t\t\t\t\t\tjct.setJunctionName(\"or\");\n\t\t\t\t\t\tif (last != null) {\n\t\t\t\t\t\t\t// this is a nested junction\n\t\t\t\t\t\t\tjct.setLhs(last);\n\t\t\t\t\t\t\tjct.setRhs(current);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t// this is not a nested junction so just set the LHS to current, RHS will be set on next iteration\n\t\t\t\t\t\t\tjct.setLhs(current);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (current instanceof Junction){\n\t\t\t\t\t\tlast = (Junction) current;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\t// this shouldn't happen\n\t\t\t\t\t\taddError(\"Unexpected non-Junction result of compound type check to Junction\", expr);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// this finishes off the RHS of the first junction\n\t\t\t\t\tjct.setRhs(current);\n\t\t\t\t\tlast = jct;\n\t\t\t\t\tjct = null;\t\t// there should always be a final RHS that will set last, which is returned\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn last;\n\t}\n\t\n\tpublic Object processExpression(Sublist expr) throws InvalidNameException, InvalidTypeException, TranslationException {\n\t\tExpression list = expr.getList();\n\t\tExpression where = expr.getWhere();\n\t\tObject lobj = processExpression(list);\n\t\tObject wobj = processExpression(where);\n\t\t\n\t\taddError(\"Processing of sublist construct not yet implemented: \" + lobj.toString() + \", \" + wobj.toString(), expr);\n\t\t\n\t\tBuiltinElement builtin = new BuiltinElement();\n\t\tbuiltin.setFuncName(\"sublist\");\n\t\tbuiltin.addArgument(nodeCheck(lobj));\n\t\tif (lobj instanceof GraphPatternElement) {\n\t\t\t((GraphPatternElement)lobj).setEmbedded(true);\n\t\t}\n\t\tbuiltin.addArgument(nodeCheck(wobj));\n\t\tif (wobj instanceof GraphPatternElement) {\n\t\t\t((GraphPatternElement)wobj).setEmbedded(true);\n\t\t}\n\t\treturn builtin;\n\t}\n\t\n\tpublic Object processExpression(UnaryExpression expr) throws InvalidNameException, InvalidTypeException, TranslationException {\n\t\tObject eobj = processExpression(expr.getExpr());\n\t\tif (eobj instanceof VariableNode && ((VariableNode)eobj).isCRulesVariable() && ((VariableNode)eobj).getType() != null) {\n\t\t\tTripleElement trel = new TripleElement((VariableNode)eobj, new RDFTypeNode(), ((VariableNode)eobj).getType());\n\t\t\ttrel.setSourceType(TripleSourceType.SPV);\n\t\t\teobj = trel;\n\t\t}\n\t\tString op = expr.getOp();\n\t\tif (eobj instanceof com.ge.research.sadl.model.gp.Literal) {\n\t\t\tObject val = ((com.ge.research.sadl.model.gp.Literal)eobj).getValue();\n\t\t\tif (op.equals(\"-\") && val instanceof Number) {\n\t\t\t\tif (val instanceof BigDecimal) {\n\t\t\t\t\tval = ((BigDecimal)val).negate();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tval = -1.0 * ((Number)val).doubleValue();\n\t\t\t\t}\n\t\t\t\t((com.ge.research.sadl.model.gp.Literal)eobj).setValue(val);\n\t\t\t\t((com.ge.research.sadl.model.gp.Literal)eobj).setOriginalText(op + ((com.ge.research.sadl.model.gp.Literal)eobj).getOriginalText());\n\t\t\t\treturn eobj;\n\t\t\t}\n\t\t\telse if (op.equals(\"not\")) {\n\t\t\t\tif (val instanceof Boolean) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tboolean bval = ((Boolean)val).booleanValue();\n\t\t\t\t\t\tif (bval) {\n\t\t\t\t\t\t\t((com.ge.research.sadl.model.gp.Literal)eobj).setValue(false);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t((com.ge.research.sadl.model.gp.Literal)eobj).setValue(true);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t((com.ge.research.sadl.model.gp.Literal)eobj).setOriginalText(op + \" \" + ((com.ge.research.sadl.model.gp.Literal)eobj).getOriginalText());\n\t\t\t\t\t\treturn eobj;\n\t\t\t\t\t}\n\t\t\t\t\tcatch (Exception e) {\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// this is a not before a non-boolean value so we want to pull the negation up\n\t\t\t\t\tpullOperationUp(expr);\n\t\t\t\t\treturn eobj;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\taddError(\"Unhandled unary operator '\" + op + \"' not processed\", expr);\n\t\t\t}\n\t\t}\n\t\tBuiltinElement bi = new BuiltinElement();\n\t\tbi.setFuncName(op);\n\t\tif (eobj instanceof Node) {\n\t\t\tbi.addArgument((Node) eobj);\n\t\t}\n\t\telse if (eobj instanceof GraphPatternElement) {\n\t\t\tbi.addArgument(new ProxyNode(eobj));\n\t\t}\n\t\telse if (eobj == null) {\n\t\t\taddError(\"Unary operator '\" + op + \"' has no argument. Perhaps parentheses are needed.\", expr);\n\t\t}\n\t\telse {\n\t\t\tthrow new TranslationException(\"Expected node, got '\" + eobj.getClass().getCanonicalName() + \"'\");\n\t\t}\n\t\treturn bi;\n\t}\n\t\n\tprivate void pullOperationUp(UnaryExpression expr) {\n\t\tif (expr != null) {\n\t\t\tif (operationsPullingUp == null) {\n\t\t\t\toperationsPullingUp = new ArrayList();\n\t\t\t}\n\t\t\toperationsPullingUp.add(expr);\n\t\t}\n\t}\n\t\n\tprivate EObject getOperationPullingUp() {\n\t\tif (operationsPullingUp != null && operationsPullingUp.size() > 0) {\n\t\t\tEObject removed = operationsPullingUp.remove(operationsPullingUp.size() - 1);\n\t\t\treturn removed;\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprivate boolean isOperationPulingUp(EObject expr) {\n\t\tif (operationsPullingUp != null && operationsPullingUp.size() > 0) {\n\t\t\tif (operationsPullingUp.get(operationsPullingUp.size() - 1).equals(expr)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tpublic Object processExpression(UnitExpression expr) throws InvalidNameException, InvalidTypeException, TranslationException {\n\t\tString unit = expr.getUnit();\n\t\tExpression value = expr.getLeft();\n\t\tObject valobj = null;\n\t\tvalobj = processExpression(value);\n\t\tif (ignoreUnittedQuantities) {\n\t\t\treturn valobj;\n\t\t}\n\t\tif (valobj instanceof com.ge.research.sadl.model.gp.Literal) {\n\t\t\t((com.ge.research.sadl.model.gp.Literal)valobj).setUnits(unit);\n\t\t\treturn valobj;\n\t\t}\n\t\tcom.ge.research.sadl.model.gp.Literal unitLiteral = new com.ge.research.sadl.model.gp.Literal();\n\t\tunitLiteral.setValue(unit);\n\t\treturn createBinaryBuiltin(\"unittedQuantity\", valobj, unitLiteral);\n\t}\n\t\n//\tpublic Object processExpression(SubjHasProp expr) {\n//\t\tString unit = expr.getUnit();\n//\t\tExpression value = expr.getValue();\n//\t\tObject valobj;\n//\t\ttry {\n//\t\t\tvalobj = processExpression(value);\n//\t\t\tif (valobj instanceof com.ge.research.sadl.model.gp.Literal) {\n//\t\t\t\t((com.ge.research.sadl.model.gp.Literal)valobj).setUnits(unit);\n//\t\t\t}\n//\t\t\treturn valobj;\n//\t\t} catch (TranslationException e) {\n//\t\t\taddError(e.getMessage(), expr);\n//\t\t} catch (InvalidNameException e) {\n//\t\t\taddError(e.getMessage(), expr);\n//\t\t} catch (InvalidTypeException e) {\n//\t\t\taddError(e.getMessage(), expr);\n//\t\t}\n//\t\treturn null;\n//\t}\n\t\n\tprivate void processSadlSameAs(SadlSameAs element) throws JenaProcessorException {\n\t\tSadlResource sr = element.getNameOrRef();\n\t\tString uri = getDeclarationExtensions().getConceptUri(sr);\n\t\tOntResource rsrc = getTheJenaModel().getOntResource(uri);\n\t\tSadlTypeReference smas = element.getSameAs();\n\t\tOntConceptType sameAsType;\n\t\tif (rsrc == null) {\n\t\t\t// concept does not exist--try to get the type from the sameAs\n\t\t\tsameAsType = getSadlTypeReferenceType(smas);\n\t\t\t\n\t\t}\n\t\telse {\n\t\t\ttry {\n\t\t\t\tsameAsType = getDeclarationExtensions().getOntConceptType(sr);\n\t\t\t} catch (CircularDefinitionException e) {\n\t\t\t\tsameAsType = e.getDefinitionType();\n\t\t\t\taddError(e.getMessage(), element);\n\t\t\t}\n\t\t}\n\t\tif (sameAsType.equals(OntConceptType.CLASS)) {\n\t\t\tOntClass smasCls = sadlTypeReferenceToOntResource(smas).asClass();\n\t\t\t// this is a class axiom\n\t\t\tOntClass cls = getTheJenaModel().getOntClass(uri);\n\t\t\tif (cls == null) {\n\t\t\t\t// this is OK--create class\n\t\t\t\tcls = createOntClass(getDeclarationExtensions().getConcreteName(sr), (String)null, null);\n\t\t\t}\n\t\t\tif (element.isComplement()) {\n\t\t\t\tComplementClass cc = getTheJenaModel().createComplementClass(cls.getURI(), smasCls);\n\t\t\t\tlogger.debug(\"New complement class '\" + cls.getURI() + \"' created\");\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcls.addEquivalentClass(smasCls);\n\t\t\t\tlogger.debug(\"Class '\" + cls.toString() + \"' given equivalent class '\" + smasCls.toString() + \"'\");\n\t\t\t}\n\t\t}\n\t\telse if (sameAsType.equals(OntConceptType.INSTANCE)) {\n\t\t\tOntResource smasInst = sadlTypeReferenceToOntResource(smas);\n\t\t\trsrc.addSameAs(smasInst);\n\t\t\tlogger.debug(\"Instance '\" + rsrc.toString() + \"' declared same as '\" + smas.toString() + \"'\");\n\t\t}\n\t\telse {\n\t\t\tthrow new JenaProcessorException(\"Unexpected concept type for same as statement: \" + sameAsType.toString());\n\t\t}\n\t}\n\n\tprivate List processSadlClassOrPropertyDeclaration(SadlClassOrPropertyDeclaration element) throws JenaProcessorException, TranslationException {\n\t\tif (isEObjectPreprocessed(element)) {\n\t\t\treturn null;\n\t\t}\n\t\t// Get the names of the declared concepts and store in a list\n\t\tList newNames = new ArrayList();\n\t\tMap> nmanns = null;\n\t\tEList clses = element.getClassOrProperty();\n\t\tif (clses != null) {\n\t\t\tIterator citer = clses.iterator();\n\t\t\twhile (citer.hasNext()) {\n\t\t\t\tSadlResource sr = citer.next();\n\t\t\t\tString nm = getDeclarationExtensions().getConceptUri(sr);\n\t\t\t\tSadlResource decl = getDeclarationExtensions().getDeclaration(sr);\n\t\t\t\tif (!(decl.equals(sr))) {\n\t\t\t\t\t// defined already\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (getDeclarationExtensions().getOntConceptType(decl).equals(OntConceptType.STRUCTURE_NAME)) {\n\t\t\t\t\t\t\taddError(\"This is already a Named Structure\", sr);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (CircularDefinitionException e) {\n\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tnewNames.add(nm);\n\t\t\t\tEList anns = sr.getAnnotations();\n\t\t\t\tif (anns != null && anns.size() > 0) {\n\t\t\t\t\tif (nmanns == null) {\n\t\t\t\t\t\tnmanns = new HashMap>();\n\t\t\t\t\t}\n\t\t\t\t\tnmanns.put(nm, anns);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (newNames.size() < 1) {\n\t\t\tthrow new JenaProcessorException(\"No names passed to processSadlClassOrPropertyDeclaration\");\n\t\t}\n\t\tList rsrcList = new ArrayList();\n\t\t// The declared concept(s) will be of type class, property, or datatype. \n\t\t//\tDetermining which will depend on the structure, including the superElement....\n\t\t// \tGet the superElement\n\t\tSadlTypeReference superElement = element.getSuperElement();\n\t\tboolean isList = typeRefIsList(superElement);\n\t\t//\t\t1) if superElement is null then it is a top-level class declaration\n\t\tif (superElement == null) {\n\t\t\tOntClass cls = createOntClass(newNames.get(0), (OntClass)null);\n\t\t\tif (nmanns != null && nmanns.get(newNames.get(0)) != null) {\n\t\t\t\taddAnnotationsToResource(cls, nmanns.get(newNames.get(0)));\n\t\t\t}\n\t\t\trsrcList.add(cls);\n\t\t}\n\t\t// \t2) if superElement is not null then the type of the new concept is the same as the type of the superElement\n\t\t// \t\t\tthe superElement can be:\n\t\t// \t\t\t\ta) a SadlSimpleTypeReference\n\t\telse if (superElement instanceof SadlSimpleTypeReference) {\n\t\t\tSadlResource superSR = ((SadlSimpleTypeReference)superElement).getType();\n\t\t\tString superSRUri = getDeclarationExtensions().getConceptUri(superSR);\t\n\t\t\tOntConceptType superElementType;\n\t\t\ttry {\n\t\t\t\tsuperElementType = getDeclarationExtensions().getOntConceptType(superSR);\n\t\t\t\tif (isList) {\n\t\t\t\t\tsuperElementType = OntConceptType.CLASS_LIST;\n\t\t\t\t}\n\t\t\t} catch (CircularDefinitionException e) {\n\t\t\t\tsuperElementType = e.getDefinitionType();\n\t\t\t\taddError(SadlErrorMessages.CIRCULAR_IMPORT.get(superSRUri), superElement);\n\t\t\t}\n\t\t\tif (superElementType.equals(OntConceptType.CLASS)) {\n\t\t\t\tfor (int i = 0; i < newNames.size(); i++) {\n\t\t\t\t\tOntClass cls = createOntClass(newNames.get(i), superSRUri, superSR);\n\t\t\t\t\tif (nmanns != null && nmanns.get(newNames.get(i)) != null) {\n\t\t\t\t\t\taddAnnotationsToResource(cls, nmanns.get(newNames.get(i)));\n\t\t\t\t\t}\n\t\t\t\t\trsrcList.add(cls);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (superElementType.equals(OntConceptType.CLASS_LIST) || superElementType.equals(OntConceptType.DATATYPE_LIST)) {\n\t\t\t\tfor (int i = 0; i < newNames.size(); i++) {\n\t\t\t\t\trsrcList.add(getOrCreateListSubclass(newNames.get(i), superSRUri, superSR.eResource()));\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (superElementType.equals(OntConceptType.CLASS_PROPERTY)) {\n\t\t\t\tfor (int i = 0; i < newNames.size(); i++) {\n\t\t\t\t\tOntProperty prop = createObjectProperty(newNames.get(i), superSRUri);\n\t\t\t\t\tif (nmanns != null && nmanns.get(newNames.get(i)) != null) {\n\t\t\t\t\t\taddAnnotationsToResource(prop, nmanns.get(newNames.get(i)));\n\t\t\t\t\t}\n\t\t\t\t\trsrcList.add(prop);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (superElementType.equals(OntConceptType.DATATYPE_PROPERTY)) {\n\t\t\t\tfor (int i = 0; i < newNames.size(); i++) {\n\t\t\t\t\tDatatypeProperty prop = createDatatypeProperty(newNames.get(i), superSRUri);\n\t\t\t\t\tif (nmanns != null && nmanns.get(newNames.get(i)) != null) {\n\t\t\t\t\t\taddAnnotationsToResource(prop, nmanns.get(newNames.get(i)));\n\t\t\t\t\t}\n\t\t\t\t\trsrcList.add(prop);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (superElementType.equals(OntConceptType.ANNOTATION_PROPERTY)) {\n\t\t\t\tfor (int i = 0; i < newNames.size(); i++) {\n\t\t\t\t\tAnnotationProperty prop = createAnnotationProperty(newNames.get(i), superSRUri);\n\t\t\t\t\tif (nmanns != null && nmanns.get(newNames.get(i)) != null) {\n\t\t\t\t\t\taddAnnotationsToResource(prop, nmanns.get(newNames.get(i)));\n\t\t\t\t\t}\n\t\t\t\t\trsrcList.add(prop);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (superElementType.equals(OntConceptType.RDF_PROPERTY)) {\n\t\t\t\tfor (int i = 0; i < newNames.size(); i++) {\n\t\t\t\t\tOntProperty prop = createRdfProperty(newNames.get(i), superSRUri);\n\t\t\t\t\tif (nmanns != null && nmanns.get(newNames.get(i)) != null) {\n\t\t\t\t\t\taddAnnotationsToResource(prop, nmanns.get(newNames.get(i)));\n\t\t\t\t\t}\n\t\t\t\t\trsrcList.add(prop);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t//\t\t\t\tb) a SadlPrimitiveDataType\n\t\telse if (superElement instanceof SadlPrimitiveDataType) {\n\t\t\tif (isList) {\n\t\t\t\tcom.hp.hpl.jena.rdf.model.Resource spdt = getSadlPrimitiveDataTypeResource((SadlPrimitiveDataType) superElement);\n\t\t\t\trsrcList.add(getOrCreateListSubclass(newNames.get(0), spdt.getURI(), superElement.eResource()));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcom.hp.hpl.jena.rdf.model.Resource spdt = processSadlPrimitiveDataType(element, (SadlPrimitiveDataType) superElement, newNames.get(0));\n\t\t\t\tif (spdt instanceof OntClass) {\n\t\t\t\t\trsrcList.add((OntClass)spdt);\n\t\t\t\t}\n\t\t\t\telse if (spdt.canAs(OntResource.class)){\n\t\t\t\t\trsrcList.add(spdt.as(OntResource.class));\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrow new JenaProcessorException(\"Expected OntResource to be returned\"); // .add(spdt);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t//\t\t\t\tc) a SadlPropertyCondition\n\t\telse if (superElement instanceof SadlPropertyCondition) {\n\t\t\tOntClass propCond = processSadlPropertyCondition((SadlPropertyCondition) superElement);\n\t\t\trsrcList.add(propCond);\n\t\t}\n\t\t//\t\t\t\td) a SadlTypeReference\n\t\telse if (superElement instanceof SadlTypeReference) {\n\t\t\t// this can only be a class; can't create a property as a SadlTypeReference\n\t\t\tObject superClsObj = sadlTypeReferenceToObject(superElement);\n\t\t\tif (superClsObj instanceof List) {\n\t\t\t\t// must be a union of xsd datatypes; create RDFDatatype\n\t\t\t\tOntClass unionCls = createRdfsDatatype(newNames.get(0), (List)superClsObj, null, null);\n\t\t\t\trsrcList.add(unionCls);\n\t\t\t}\n\t\t\telse if (superClsObj instanceof OntResource) {\n\t\t\t\tOntResource superCls = (OntResource)superClsObj;\n\t\t\t\tif (superCls != null) {\n\t\t\t\t\tif (superCls instanceof UnionClass) {\n\t\t\t\t\t\tExtendedIterator itr = ((UnionClass)superCls).listOperands();\n\t\t\t\t\t\twhile (itr.hasNext()) {\n\t\t\t\t\t\t\tcom.hp.hpl.jena.rdf.model.Resource cls = itr.next();\n//\t\t\t\t\t\t\tSystem.out.println(\"Union member: \" + cls.toString());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (superCls instanceof IntersectionClass) {\n\t\t\t\t\t\tExtendedIterator itr = ((IntersectionClass)superCls).listOperands();\n\t\t\t\t\t\twhile (itr.hasNext()) {\n\t\t\t\t\t\t\tcom.hp.hpl.jena.rdf.model.Resource cls = itr.next();\n//\t\t\t\t\t\t\tSystem.out.println(\"Intersection member: \" + cls.toString());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\trsrcList.add(createOntClass(newNames.get(0), superCls.as(OntClass.class)));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tEList restrictions = element.getRestrictions();\n\t\tif (restrictions != null) {\n\t\t\tIterator ritr = restrictions.iterator();\n\t\t\twhile (ritr.hasNext()) {\n\t\t\t\tSadlPropertyRestriction rest = ritr.next();\n\t\t\t\tif (rest instanceof SadlMustBeOneOf) {\n\t\t\t\t\t//\n\t\t\t\t\tEList instances = ((SadlMustBeOneOf)rest).getValues();\n\t\t\t\t\tif (instances != null) {\n\t\t\t\t\t\tIterator iitr = instances.iterator();\n\t\t\t\t\t\tList individuals = new ArrayList();\n\t\t\t\t\t\twhile (iitr.hasNext()) {\n\t\t\t\t\t\t\tSadlExplicitValue inst = iitr.next();\n\t\t\t\t\t\t\tif (inst instanceof SadlResource) {\n\t\t\t\t\t\t\t\tfor (int i = 0; i < rsrcList.size(); i++) {\n\t\t\t\t\t\t\t\t\tindividuals.add(createIndividual((SadlResource)inst, rsrcList.get(i).asClass()));\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tthrow new JenaProcessorException(\"Unhandled type of SadlExplicitValue: \" + inst.getClass().getCanonicalName());\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// create equivalent class\n\t\t\t\t\t\tRDFList collection = getTheJenaModel().createList();\n\t\t\t\t\t\tIterator iter = individuals.iterator();\n\t\t\t\t\t\twhile (iter.hasNext()) {\n\t\t\t\t\t\t\tRDFNode dt = iter.next();\n\t\t\t\t\t\t\tcollection = collection.with(dt);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tEnumeratedClass enumcls = getTheJenaModel().createEnumeratedClass(null, collection);\n\t\t\t\t\t\tOntResource cls = rsrcList.get(0);\n\t\t\t\t\t\tif (cls.canAs(OntClass.class)){\n\t\t\t\t\t\t\tcls.as(OntClass.class).addEquivalentClass(enumcls);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (rest instanceof SadlCanOnlyBeOneOf) {\n\t\t\t\t\tEList instances = ((SadlCanOnlyBeOneOf)rest).getValues();\n\t\t\t\t\tif (instances != null) {\n\t\t\t\t\t\tIterator iitr = instances.iterator();\n\t\t\t\t\t\tList individuals = new ArrayList();\n\t\t\t\t\t\twhile (iitr.hasNext()) {\n\t\t\t\t\t\t\tSadlExplicitValue inst = iitr.next();\n\t\t\t\t\t\t\tif (inst instanceof SadlResource) {\n\t\t\t\t\t\t\t\tfor (int i = 0; i < rsrcList.size(); i++) {\n\t\t\t\t\t\t\t\t\tindividuals.add(createIndividual((SadlResource)inst, rsrcList.get(i).asClass()));\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tthrow new JenaProcessorException(\"Unhandled type of SadlExplicitValue: \" + inst.getClass().getCanonicalName());\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// create equivalent class\n\t\t\t\t\t\tRDFList collection = getTheJenaModel().createList();\n\t\t\t\t\t\tIterator iter = individuals.iterator();\n\t\t\t\t\t\twhile (iter.hasNext()) {\n\t\t\t\t\t\t\tRDFNode dt = iter.next();\n\t\t\t\t\t\t\tcollection = collection.with(dt);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tEnumeratedClass enumcls = getTheJenaModel().createEnumeratedClass(null, collection);\n\t\t\t\t\t\tOntResource cls = rsrcList.get(0);\n\t\t\t\t\t\tif (cls.canAs(OntClass.class)){\n\t\t\t\t\t\t\tcls.as(OntClass.class).addEquivalentClass(enumcls);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (int i = 0; i < rsrcList.size(); i++) {\n\t\t\tIterator dbiter = element.getDescribedBy().iterator();\n\t\t\twhile (dbiter.hasNext()) {\n\t\t\t\tSadlProperty sp = dbiter.next();\n\t\t\t\t// if this is an assignment of a range to a property the property will be returned (prop) for domain assignment,\n\t\t\t\t// but if it is a condition to be added as property restriction null will be returned\n\t\t\t\tProperty prop = processSadlProperty(rsrcList.get(i), sp);\n\t\t\t\tif (prop != null) {\n\t\t\t\t\taddPropertyDomain(prop, rsrcList.get(i), sp); //.eContainer());\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t\tif (isList) {\n\t\t\taddLengthRestrictionsToList(rsrcList.get(0), element.getFacet());\n\n\t\t}\n\t\treturn rsrcList;\n\t}\n\n\tprivate Property processSadlProperty(OntResource subject, SadlProperty element) throws JenaProcessorException {\n\t\tProperty retProp = null;\n\t\t// this has multiple forms:\n\t\t//\t1) is a property...\n\t\t//\t2) relationship of to is \n\t\t// 3) describes with \t(1st spr is a SadlTypeAssociation, the domain; 2nd spr is a SadlRangeRestriction, the range)\n\t\t// 4) of \t(1st spr is a SadlTypeAssociation, the class being restricted; 2nd spr is a SadlCondition\n\t\t// 5) of can only be one of { or } (1st spr is SadlTypeAssociation, 2nd spr is a SadlCanOnlyBeOneOf)\n\t\t// 6) of must be one of { or } (1st spr is SadlTypeAssociation, 2nd spr is a SadlCanOnlyBeOneOf)\n\t\tSadlResource sr = sadlResourceFromSadlProperty(element);\n\t\tString propUri = getDeclarationExtensions().getConceptUri(sr);\n\t\tOntConceptType propType;\n\t\ttry {\n\t\t\tpropType = getDeclarationExtensions().getOntConceptType(sr);\n\t\t\tif (!isProperty(propType)) {\n\t\t\t\taddError(SadlErrorMessages.INVALID_USE_OF_CLASS_AS_PROPERTY.get(getDeclarationExtensions().getConcreteName(sr)),element);\n\t\t\t}\n\t\t} catch (CircularDefinitionException e) {\n\t\t\tpropType = e.getDefinitionType();\n\t\t\taddError(e.getMessage(), element);\n\t\t}\n\t\t\n\t\t\n\t\tIterator spitr = element.getRestrictions().iterator();\n\t\tif (spitr.hasNext()) {\n\t\t\tSadlPropertyRestriction spr1 = spitr.next();\n\t\t\tif (spr1 instanceof SadlIsAnnotation) {\n\t\t\t\tretProp = getTheJenaModel().createAnnotationProperty(propUri);\n\t\t\t}\n\t\t\telse if (spr1 instanceof SadlIsTransitive) {\n\t\t\t\tOntProperty pr;\n\t\t\t\tif (propType.equals(OntConceptType.CLASS_PROPERTY)) {\n\t\t\t\t\tpr = getOrCreateObjectProperty(propUri);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrow new JenaProcessorException(\"Only object properties can be transitive\");\n\t\t\t\t}\n\t\t\t\tif (pr == null) {\n\t\t\t\t\tthrow new JenaProcessorException(\"Property '\" + propUri + \"' not found in ontology.\");\n\t\t\t\t}\n\t\t\t\tpr.convertToTransitiveProperty();\n\t\t\t\tretProp = getTheJenaModel().createTransitiveProperty(pr.getURI());\n\t\t\t}\n\t\t\telse if (spr1 instanceof SadlIsInverseOf) {\n\t\t\t\tOntProperty pr;\n\t\t\t\tif (propType.equals(OntConceptType.CLASS_PROPERTY)) {\n\t\t\t\t\tpr = getOrCreateObjectProperty(propUri);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrow new JenaProcessorException(\"Only object properties can have inverses\");\n\t\t\t\t}\n\t\t\t\tif (pr == null) {\n\t\t\t\t\tthrow new JenaProcessorException(\"Property '\" + propUri + \"' not found in ontology.\");\n\t\t\t\t}\n\t\t\t\tSadlResource otherProp = ((SadlIsInverseOf)spr1).getOtherProperty();\n\t\t\t\tString otherPropUri = getDeclarationExtensions().getConceptUri(otherProp);\n\t\t\t\tOntConceptType optype;\n\t\t\t\ttry {\n\t\t\t\t\toptype = getDeclarationExtensions().getOntConceptType(otherProp);\n\t\t\t\t} catch (CircularDefinitionException e) {\n\t\t\t\t\toptype = e.getDefinitionType();\n\t\t\t\t\taddError(e.getMessage(), element);\n\t\t\t\t}\n\t\t\t\tif (!optype.equals(OntConceptType.CLASS_PROPERTY)) {\n\t\t\t\t\tthrow new JenaProcessorException(\"Only object properties can have inverses\");\n\t\t\t\t}\n\t\t\t\tOntProperty opr = getOrCreateObjectProperty(otherPropUri);\n\t\t\t\tif (opr == null) {\n\t\t\t\t\tthrow new JenaProcessorException(\"Property '\" + otherPropUri + \"' not found in ontology.\");\n\t\t\t\t}\n\t\t\t\tpr.addInverseOf(opr);\n\t\t\t}\n\t\t\telse if (spr1 instanceof SadlRangeRestriction) {\n\t\t\t\tSadlTypeReference rng = ((SadlRangeRestriction)spr1).getRange();\n\t\t\t\tif (rng != null) {\n\t\t\t\t\tRangeValueType rngValueType = RangeValueType.CLASS_OR_DT;\t// default\n\t\t\t\t\tboolean isList = typeRefIsList(rng);\n\t\t\t\t\tif (isList) {\n\t\t\t\t\t\trngValueType = RangeValueType.LIST;\n\t\t\t\t\t}\n\t\t\t\t\tOntProperty prop;\n\t\t\t\t\tString rngName;\n\t\t\t\t\tif (!isList && rng instanceof SadlPrimitiveDataType) {\n\t\t\t\t\t\trngName = ((SadlPrimitiveDataType)rng).getPrimitiveType().getName();\n\t\t\t\t\t\tRDFNode rngNode = primitiveDatatypeToRDFNode(rngName);\n\t\t\t\t\t\tif (!checkForExistingCompatibleDatatypeProperty(propUri, rngNode)) {\n\t\t\t\t\t\t\tprop = createDatatypeProperty(propUri, null);\n\t\t\t\t\t\t\taddPropertyRange(propType, prop, rngNode, rngValueType, rng);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tprop = getTheJenaModel().getDatatypeProperty(propUri);\n\t\t\t\t\t\t\taddPropertyRange(propType, prop, rngNode, rngValueType, rng);\n\t\t\t\t\t\t}\n\t\t\t\t\t\taddPropertyRange(propType, prop, rngNode, rngValueType, rng);\n\t\t\t\t\t\tretProp = prop;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\trngName = sadlSimpleTypeReferenceToConceptName(rng).toFQString();\n\t\t\t\t\t\tOntResource rngRsrc;\n\t\t\t\t\t\tif (isList) {\n\t\t\t\t\t\t\trngRsrc = getOrCreateListSubclass(null, rngName, element.eResource());\n\t\t\t\t\t\t\taddLengthRestrictionsToList(rngRsrc, ((SadlRangeRestriction)spr1).getFacet());\n\t\t\t\t\t\t\tpropType = OntConceptType.CLASS_PROPERTY;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\trngRsrc = sadlTypeReferenceToOntResource(rng);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tretProp = assignRangeToProperty(propUri, propType, rngRsrc, rngValueType, rng);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (((SadlRangeRestriction)spr1).isSingleValued()) {\n\t\t\t\t\t// add cardinality restriction\n\t\t\t\t\taddCardinalityRestriction(subject, retProp, 1);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (spr1 instanceof SadlCondition) {\n\t\t\t\tOntProperty prop = getTheJenaModel().getOntProperty(propUri);\n\t\t\t\tif (prop == null) {\n\t\t\t\t\tprop = getOrCreateRdfProperty(propUri);\n\t\t\t\t}\n\t\t\t\tOntClass condCls = sadlConditionToOntClass((SadlCondition) spr1, prop, propType);\n\t\t\t\tOntClass cls = null;\n\t\t\t\tif (subject != null) {\n\t\t\t\t\tif (subject.canAs(OntClass.class)){\n\t\t\t\t\t\tcls = subject.as(OntClass.class);\n\t\t\t\t\t\tcls.addSuperClass(condCls);\n\t\t\t\t\t\tretProp = null;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tthrow new JenaProcessorException(\"Unable to convert concept being restricted (\" + subject.toString() + \") to an OntClass.\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// I think this is OK... AWC 3/13/2017\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (spitr.hasNext()) {\n\t\t\t\tSadlPropertyRestriction spr2 = spitr.next();\n\t\t\t\tif (spitr.hasNext()) {\n\t\t\t\t\tStringBuilder sb = new StringBuilder();\n\t\t\t\t\tint cntr = 0;\n\t\t\t\t\twhile (spitr.hasNext()) {\n\t\t\t\t\t\tif (cntr++ > 0) sb.append(\", \");\n\t\t\t\t\t\tsb.append(spitr.next().getClass().getCanonicalName());\n\t\t\t\t\t}\n\t\t\t\t\tthrow new JenaProcessorException(\"Unexpected SadlProperty has more than 2 restrictions: \" + sb.toString());\n\t\t\t\t}\n\t\t\t\tif (spr1 instanceof SadlTypeAssociation && spr2 instanceof SadlRangeRestriction) {\n\t\t\t\t\t// this is case 3\n\t\t\t\t\tSadlTypeReference domain = ((SadlTypeAssociation)spr1).getDomain();\n\t\t\t\t\tOntConceptType domaintype;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tdomaintype = sadlTypeReferenceOntConceptType(domain);\n\t\t\t\t\t\tif (domaintype != null && domaintype.equals(OntConceptType.DATATYPE)) {\n\t\t\t\t\t\t\taddWarning(SadlErrorMessages.DATATYPE_AS_DOMAIN.get() , domain);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (CircularDefinitionException e) {\n\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t\tOntResource domainrsrc = sadlTypeReferenceToOntResource(domain);\n\n\t\t\t\t\t// before creating the property, determine if the range is a sadllistmodel:List as if it is the property type is actually an owl:ObjectProperty\n\t\t\t\t\tRangeValueType rngValueType = RangeValueType.CLASS_OR_DT;\t// default\n\t\t\t\t\tSadlTypeReference rng = ((SadlRangeRestriction)spr2).getRange();\n\t\t\t\t\tif (rng instanceof SadlPrimitiveDataType) {\n\t\t\t\t\t\tif (((SadlPrimitiveDataType)rng).isList()) {\n\t\t\t\t\t\t\trngValueType = RangeValueType.LIST;\n\t\t\t\t\t\t\tpropType = OntConceptType.DATATYPE_LIST;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (rng instanceof SadlSimpleTypeReference) {\n\t\t\t\t\t\tif (((SadlSimpleTypeReference)rng).isList()) {\n\t\t\t\t\t\t\trngValueType = RangeValueType.LIST;\n\t\t\t\t\t\t\tpropType = OntConceptType.CLASS_LIST;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tOntProperty prop;\n\t\t\t\t\tif (propType.equals(OntConceptType.CLASS_PROPERTY) || rngValueType.equals(RangeValueType.LIST)) {\n\t\t\t\t\t\tprop = getOrCreateObjectProperty(propUri);\n\t\t\t\t\t}\n\t\t\t\t\telse if (propType.equals(OntConceptType.DATATYPE_PROPERTY)){\n\t\t\t\t\t\tprop = getOrCreateDatatypeProperty(propUri);\n\t\t\t\t\t}\n\t\t\t\t\telse if (propType.equals(OntConceptType.RDF_PROPERTY)) {\n\t\t\t\t\t\tprop = getOrCreateRdfProperty(propUri);\n\t\t\t\t\t}\n\t\t\t\t\telse if (propType.equals(OntConceptType.ANNOTATION_PROPERTY)) {\n\t\t\t\t\t\taddError(\"Can't specify domain of an annotation property. Did you want to use a property restriction?\", sr);\n\t\t\t\t\t\tthrow new JenaProcessorException(\"Invalid property type (\" + propType.toString() + \") for '\" + propUri + \"'\");\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tthrow new JenaProcessorException(\"Invalid property type (\" + propType.toString() + \") for '\" + propUri + \"'\");\n\t\t\t\t\t}\n\t\t\t\t\taddPropertyDomain(prop, domainrsrc, domain);\n\t\t\t\t\tSadlTypeReference from = element.getFrom();\n\t\t\t\t\tif (from != null) {\n\t\t\t\t\t\tOntResource fromrsrc = sadlTypeReferenceToOntResource(from);\n\t\t\t\t\t\tthrow new JenaProcessorException(\"What is 'from'?\");\n\t\t\t\t\t}\n\t\t\t\t\tSadlTypeReference to = element.getTo();\n\t\t\t\t\tif (to != null) {\n\t\t\t\t\t\tOntResource torsrc = sadlTypeReferenceToOntResource(to);\n\t\t\t\t\t\tthrow new JenaProcessorException(\"What is 'to'?\");\n\t\t\t\t\t}\n\t\t\t\t\t\n//\t\t\t\t\tRangeValueType rngValueType = RangeValueType.CLASS_OR_DT;\t// default\n//\t\t\t\t\tSadlTypeReference rng = ((SadlRangeRestriction)spr2).getRange();\n\t\t\t\t\tif (rng instanceof SadlPrimitiveDataType && !rngValueType.equals(RangeValueType.LIST)) {\n\t\t\t\t\t\tString rngName = ((SadlPrimitiveDataType)rng).getPrimitiveType().getName();\n\t\t\t\t\t\tRDFNode rngNode = primitiveDatatypeToRDFNode(rngName);\n\t\t\t\t\t\tDatatypeProperty prop2 = null;\n\t\t\t\t\t\tif (!checkForExistingCompatibleDatatypeProperty(propUri, rngNode)) {\n\t\t\t\t\t\t\t//TODO should this ever happen? spr1 should have created the property?\n\t\t\t\t\t\t\tprop2 = createDatatypeProperty(propUri, null);\n\t\t\t\t\t\t\taddPropertyRange(propType, prop, rngNode, rngValueType, rng);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tprop2 = getTheJenaModel().getDatatypeProperty(propUri);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tretProp = prop2;\n\t\t\t\t\t}\n\t\t\t\t\telse if (((SadlRangeRestriction)spr2).getTypeonly() == null) {\t\t\t\t\n\t\t\t\t\t\tOntResource rngRsrc = sadlTypeReferenceToOntResource(rng);\n\t\t\t\t\t\tif ((rng instanceof SadlSimpleTypeReference && ((SadlSimpleTypeReference)rng).isList()) || \n\t\t\t\t\t\t\t\t(rng instanceof SadlPrimitiveDataType && ((SadlPrimitiveDataType)rng).isList())) {\n\t\t\t\t\t\t\taddLengthRestrictionsToList(rngRsrc, ((SadlRangeRestriction)spr2).getFacet());\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (rngRsrc == null) {\n\t\t\t\t\t\t\taddError(SadlErrorMessages.RANGE_RESOLVE.toString(), rng);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tretProp = assignRangeToProperty(propUri, propType, rngRsrc, rngValueType, rng);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tretProp = prop;\n\t\t\t\t\t}\n\t\t\t\t\tif (((SadlRangeRestriction)spr2).isSingleValued()) {\n\t\t\t\t\t\taddCardinalityRestriction(domainrsrc, retProp, 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (spr1 instanceof SadlTypeAssociation && spr2 instanceof SadlCondition) {\n\t\t\t\t\t// this is case 4\n\t\t\t\t\tSadlTypeReference domain = ((SadlTypeAssociation)spr1).getDomain();\n\t\t\t\t\tOntResource domainrsrc = sadlTypeReferenceToOntResource(domain);\n\t\t\t\t\tif (domainrsrc == null) {\n\t\t\t\t\t\taddError(SadlErrorMessages.UNABLE_TO_FIND.get(\"domain\"), domain);\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t}\n\t\t\t\t\telse if (domainrsrc.canAs(OntClass.class)){ \n\t\t\t\t\t\tOntClass cls = domainrsrc.as(OntClass.class);\n\t\t\t\t\t\tProperty prop = getTheJenaModel().getProperty(propUri);\n\t\t\t\t\t\tif (prop != null) {\n\t\t\t\t\t\t\tOntClass condCls = sadlConditionToOntClass((SadlCondition) spr2, prop, propType);\n\t\t\t\t\t\t\tif (condCls != null) {\n\t\t\t\t\t\t\t\tcls.addSuperClass(condCls);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\taddError(SadlErrorMessages.UNABLE_TO_ADD.get(\"restriction\",\"unable to create condition class\"), domain);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tretProp = prop;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tthrow new JenaProcessorException(\"Unable to convert property '\" + propUri + \"' to OntProperty.\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tthrow new JenaProcessorException(\"Unable to convert concept being restricted (\" + domainrsrc.toString() + \") to an OntClass.\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (spr1 instanceof SadlTypeAssociation && spr2 instanceof SadlCanOnlyBeOneOf) {\n\t\t\t\t\tSadlTypeReference domain = ((SadlTypeAssociation)spr1).getDomain();\n\t\t\t\t\tOntResource domainrsrc = sadlTypeReferenceToOntResource(domain);\n\t\t\t\t\tif (domainrsrc == null) {\n\t\t\t\t\t\taddError(SadlErrorMessages.UNABLE_TO_FIND.get(\"domain\"), domain);\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t}\n\t\t\t\t\telse if (domainrsrc.canAs(OntClass.class)){ \n\t\t\t\t\t\tOntClass cls = domainrsrc.as(OntClass.class);\n\t\t\t\t\t\tProperty prop = getTheJenaModel().getProperty(propUri);\n\t\t\t\t\t\tif (prop != null) {\n\t\t\t\t\t\t\tEList values = ((SadlCanOnlyBeOneOf)spr2).getValues();\n\t\t\t\t\t\t\tif (values != null) {\n\t\t\t\t\t\t\t\tEnumeratedClass enumCls = sadlExplicitValuesToEnumeratedClass(values);\n\t\t\t\t\t\t\t\tAllValuesFromRestriction avf = getTheJenaModel()\n\t\t\t\t\t\t\t\t\t\t.createAllValuesFromRestriction(null,\n\t\t\t\t\t\t\t\t\t\t\t\tprop, enumCls);\n\t\t\t\t\t\t\t\tif (avf != null) {\n\t\t\t\t\t\t\t\t\tcls.addSuperClass(avf);\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\taddError(SadlErrorMessages.UNABLE_TO_CREATE.get(\"AllValuesFromRestriction\", \"Unknown reason\"), spr2);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\taddError(SadlErrorMessages.UNABLE_TO_ADD.get(\"all values from restriction\", \"unable to create oneOf class\"), domain);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tretProp = prop;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tthrow new JenaProcessorException(\"Unable to convert property '\" + propUri + \"' to OntProperty.\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (spr1 instanceof SadlTypeAssociation && spr2 instanceof SadlMustBeOneOf) {\n\t\t\t\t\tSadlTypeReference domain = ((SadlTypeAssociation)spr1).getDomain();\n\t\t\t\t\tOntResource domainrsrc = sadlTypeReferenceToOntResource(domain);\n\t\t\t\t\tif (domainrsrc == null) {\n\t\t\t\t\t\taddError(SadlErrorMessages.UNABLE_TO_FIND.get(\"domain\"), domain);\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t}\n\t\t\t\t\telse if (domainrsrc.canAs(OntClass.class)){ \n\t\t\t\t\t\tOntClass cls = domainrsrc.as(OntClass.class);\n\t\t\t\t\t\tProperty prop = getTheJenaModel().getProperty(propUri);\n\t\t\t\t\t\tif (prop != null) {\n\t\t\t\t\t\t\tEList values = ((SadlMustBeOneOf)spr2).getValues();\n\t\t\t\t\t\t\tif (values != null) {\n\t\t\t\t\t\t\t\tEnumeratedClass enumCls = sadlExplicitValuesToEnumeratedClass(values);\n\t\t\t\t\t\t\t\tSomeValuesFromRestriction svf = getTheJenaModel()\n\t\t\t\t\t\t\t\t\t\t.createSomeValuesFromRestriction(null,\n\t\t\t\t\t\t\t\t\t\t\t\tprop, enumCls);\n\t\t\t\t\t\t\t\tif (svf != null) {\n\t\t\t\t\t\t\t\t\tcls.addSuperClass(svf);\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\taddError(SadlErrorMessages.UNABLE_TO_CREATE.get(\"SomeValuesFromRestriction\", \"Unknown reason\"), spr2);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\taddError(SadlErrorMessages.UNABLE_TO_ADD.get(\"some values from restriction\", \"unable to create oneOf class\"), domain);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tretProp = prop;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tthrow new JenaProcessorException(\"Unable to convert property '\" + propUri + \"' to OntProperty.\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\telse if (spr1 instanceof SadlTypeAssociation && spr2 instanceof SadlDefaultValue) {\n\t\t\t\t\tSadlExplicitValue dv = ((SadlDefaultValue)spr2).getDefValue();\n\t\t\t\t\tint lvl = ((SadlDefaultValue)spr2).getLevel();\n\t\t\t\t\tSadlTypeReference domain = ((SadlTypeAssociation)spr1).getDomain();\n\t\t\t\t\tOntResource domainrsrc = sadlTypeReferenceToOntResource(domain);\n\t\t\t\t\tif (domainrsrc == null) {\n\t\t\t\t\t\taddError(SadlErrorMessages.UNABLE_TO_FIND.get(\"domain\"), domain);\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t}\n\t\t\t\t\telse if (domainrsrc.canAs(OntClass.class)){ \n\t\t\t\t\t\tOntClass cls = domainrsrc.as(OntClass.class);\n\t\t\t\t\t\tProperty prop = getTheJenaModel().getProperty(propUri);\n\t\t\t\t\t\tif (prop != null) {\n\t\t\t\t\t\t\tif (sadlDefaultsModel == null) {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\timportSadlDefaultsModel(element.eResource());\n\t\t\t\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t\t\t\t\tthrow new JenaProcessorException(\"Failed to load SADL Defaults model\", e);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tRDFNode defVal = sadlExplicitValueToRdfNode(dv, prop, true);\n\t\t\t\t\t\t\tIndividual seeAlsoDefault = null;\n\t\t\t\t\t\t\tif (propType.equals(OntConceptType.CLASS_PROPERTY) || (propType.equals(OntConceptType.RDF_PROPERTY) && defVal.isResource())) {\n\t\t\t\t\t\t\t\tif (!(defVal.isURIResource()) || !defVal.canAs(Individual.class)) {\n\t\t\t\t\t\t\t\t\taddError(\"Error creating default for property '\" + propUri + \"' for class '\" + cls.getURI() + \"' with value '\" + defVal.toString()\n\t\t\t\t\t\t\t\t\t\t\t+ \"': the value is not a named concept.\", spr2);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\tIndividual defInst = defVal.as(Individual.class);\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\tseeAlsoDefault = createDefault(cls, prop, defInst, lvl, element);\n\t\t\t\t\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\t\t\t\t\taddError(\"Error creating default for property '\" + propUri + \"' for class '\" + cls.getURI() + \"' with value '\" + defVal.toString()\n\t\t\t\t\t\t\t\t\t\t\t\t+ \"': \" + e.getMessage(), spr2);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tif (propType.equals(OntConceptType.DATATYPE_PROPERTY) && !defVal.isLiteral()) {\n\t\t\t\t\t\t\t\t\taddError(\"Error creating default for property '\" + propUri + \"' for class '\" + cls.getURI() + \"' with value '\" + defVal.toString()\n\t\t\t\t\t\t\t\t\t\t\t+ \"': the value is a named concept but should be a data value.\", spr2);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\tseeAlsoDefault = createDefault(cls, prop, defVal.asLiteral(), lvl, spr2);\n\t\t\t\t\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\t\t\t\t\taddError(\"Error creating default for property '\" + propUri + \"' for class '\" + cls.getURI() + \"' with value '\" + defVal.toString()\n\t\t\t\t\t\t\t\t\t\t\t\t+ \"': \" + e.getMessage(), spr2);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (seeAlsoDefault != null) {\n\t\t\t\t\t\t\t\tcls.addSeeAlso(seeAlsoDefault);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\taddError(\"Unable to create default for '\" + cls.getURI() + \"', '\"\n\t\t\t\t\t\t\t\t\t\t+ propUri + \"', '\" + defVal + \"'\", element);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrow new JenaProcessorException(\"Unhandled restriction: spr1 is '\" + spr1.getClass().getName() + \"', spr2 is '\" + spr2.getClass().getName() + \"'\");\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (spr1 instanceof SadlTypeAssociation) {\n\t\t\t\t// this is case 3 but with range not present\n\t\t\t\tSadlTypeReference domain = ((SadlTypeAssociation)spr1).getDomain();\n\t\t\t\tOntResource domainrsrc = sadlTypeReferenceToOntResource(domain);\n\t\t\t\tObjectProperty prop = getOrCreateObjectProperty(propUri);\n\t\t\t\tif (domainrsrc != null) {\n\t\t\t\t\taddPropertyDomain(prop, domainrsrc, domain);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (spr1 instanceof SadlIsSymmetrical) {\n\t\t\t\tObjectProperty prop = getOrCreateObjectProperty(propUri);\n\t\t\t\tif (prop != null) {\n\t\t\t\t\tif (!prop.isObjectProperty()) {\n\t\t\t\t\t\taddError(SadlErrorMessages.OBJECT_PROP_SYMMETRY.toString(), spr1);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tgetTheJenaModel().add(prop,RDF.type,OWL.SymmetricProperty);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthrow new JenaProcessorException(\"Unhandled SadlProperty expression\");\n\t\t\t}\n\t\t\t\n\t\t\twhile (spitr.hasNext()) {\n\t\t\t\tSadlPropertyRestriction spr = spitr.next();\n\t\t\t\tif (spr instanceof SadlRangeRestriction) {\n\t\t\t\t\tRangeValueType rngValueType = RangeValueType.CLASS_OR_DT;\t// default\n\t\t\t\t\tSadlTypeReference rng = ((SadlRangeRestriction)spr).getRange();\n\t\t\t\t\tif (rng instanceof SadlPrimitiveDataType) {\n\t\t\t\t\t\tString rngName = ((SadlPrimitiveDataType)rng).getPrimitiveType().getName();\n\t\t\t\t\t\tRDFNode rngNode = primitiveDatatypeToRDFNode(rngName);\n\t\t\t\t\t\tDatatypeProperty prop = null;\n\t\t\t\t\t\tif (!checkForExistingCompatibleDatatypeProperty(propUri, rngNode)) {\n\t\t\t\t\t\t\tprop = createDatatypeProperty(propUri, null);\n\t\t\t\t\t\t\taddPropertyRange(propType, prop, rngNode, rngValueType, rng);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tprop = getTheJenaModel().getDatatypeProperty(propUri);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tretProp = prop;\n\t\t\t\t\t}\n\t\t\t\t\telse {\t\t\t\t\n\t\t\t\t\t\tOntResource rngRsrc = sadlTypeReferenceToOntResource(rng);\n\t\t\t\t\t\tif (rngRsrc == null) {\n\t\t\t\t\t\t\tthrow new JenaProcessorException(\"Range failed to resolve to a class or datatype\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tretProp = assignRangeToProperty(propUri, propType, rngRsrc, rngValueType, rng);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (spr instanceof SadlCondition) {\n\t\t\t\t\tif (propType.equals(OntConceptType.CLASS_PROPERTY)) {\n\t\t\t\t\t\tObjectProperty prop = getOrCreateObjectProperty(propUri);\n\t\t\t\t\t\tOntClass condCls = sadlConditionToOntClass((SadlCondition) spr, prop, propType);\n\t\t\t\t\t\taddPropertyRange(propType, prop, condCls, RangeValueType.CLASS_OR_DT, spr);\t\t// use default?\n\t\t\t\t\t\t//TODO don't we need to add this class as superclass??\n\t\t\t\t\t\tretProp = prop;\n\t\t\t\t\t}\n\t\t\t\t\telse if (propType.equals(OntConceptType.DATATYPE_PROPERTY)) {\n\t\t\t\t\t\tObjectProperty prop = getOrCreateObjectProperty(propUri);\n\t\t\t\t\t\tOntClass condCls = sadlConditionToOntClass((SadlCondition) spr, prop, propType);\n\t\t\t\t\t\t//TODO don't we need to add this class as superclass??\n\t\t\t\t\t\tretProp = prop;\n\t//\t\t\t\t\tthrow new JenaProcessorException(\"SadlCondition on data type property not handled\");\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tthrow new JenaProcessorException(\"Invalid property type: \" + propType.toString());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (spr instanceof SadlTypeAssociation) {\n\t\t\t\t\tSadlTypeReference domain = ((SadlTypeAssociation)spr).getDomain();\n\t\t\t\t\tOntResource domainrsrc = sadlTypeReferenceToOntResource(domain);\n\t\t\t\t\tObjectProperty prop = getOrCreateObjectProperty(propUri);\n\t\t\t\t\tif (domainrsrc != null) {\n\t\t\t\t\t\taddPropertyDomain(prop, domainrsrc, domain);\n\t\t\t\t\t}\n\t\t\t\t\tSadlTypeReference from = element.getFrom();\n\t\t\t\t\tif (from != null) {\n\t\t\t\t\t\tOntResource fromrsrc = sadlTypeReferenceToOntResource(from);\n\t\t\t\t\t\tthrow new JenaProcessorException(\"What is 'from'?\");\n\t\t\t\t\t}\n\t\t\t\t\tSadlTypeReference to = element.getTo();\n\t\t\t\t\tif (to != null) {\n\t\t\t\t\t\tOntResource torsrc = sadlTypeReferenceToOntResource(to);\n\t\t\t\t\t\tthrow new JenaProcessorException(\"What is 'to'?\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (spr instanceof SadlIsAnnotation) {\n\t\t\t\t\tretProp = getTheJenaModel().createAnnotationProperty(propUri);\n\t\t\t\t}\n\t\t\t\telse if (spr instanceof SadlIsTransitive) {\n\t\t\t\t\tOntProperty pr = getOrCreateObjectProperty(propUri);\n\t\t\t\t\tpr.convertToTransitiveProperty();\n\t\t\t\t\tretProp = getTheJenaModel().createTransitiveProperty(pr.getURI());\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrow new JenaProcessorException(\"Unhandled SadlPropertyRestriction type: \" + spr.getClass().getCanonicalName());\n\t\t\t\t}\n\t\t\t} // end while\n\t\t}\n\t\telse if (element.getFrom() != null && element.getTo() != null) {\n\t\t\tSadlTypeReference fromTypeRef = element.getFrom();\n\t\t\tObject frm;\n\t\t\ttry {\n\t\t\t\tfrm = processExpression(fromTypeRef);\n\t\t\t\tSadlTypeReference toTypeRef = element.getTo();\n\t\t\t\tObject t = processExpression(toTypeRef);\n\t\t\t\tif (frm != null && t != null) {\n\t\t\t\t\tOntClass dmn;\n\t\t\t\t\tOntClass rng;\n\t\t\t\t\tif (frm instanceof OntClass) {\n\t\t\t\t\t\tdmn = (OntClass)frm;\n\t\t\t\t\t}\n\t\t\t\t\telse if (frm instanceof NamedNode) {\n\t\t\t\t\t\tdmn = getOrCreateOntClass(((NamedNode)frm).toFullyQualifiedString());\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tthrow new JenaTransactionException(\"Valid domain not identified: \" + frm.toString());\n\t\t\t\t\t}\n\t\t\t\t\tif (t instanceof OntClass) {\n\t\t\t\t\t\trng = (OntClass)t;\n\t\t\t\t\t} else if (t instanceof NamedNode) {\n\t\t\t\t\t\trng = getOrCreateOntClass(((NamedNode)t).toFullyQualifiedString());\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tthrow new JenaTransactionException(\"Valid range not identified: \" + t.toString());\n\t\t\t\t\t}\n\t\t\t\t\tOntProperty pr = createObjectProperty(propUri, null);\n\t\t\t\t\taddPropertyDomain(pr, dmn, toTypeRef);\n\t\t\t\t\taddPropertyRange(OntConceptType.CLASS_PROPERTY, pr, rng, RangeValueType.CLASS_OR_DT, element);\n\t\t\t\t\tretProp = pr;\n\t\t\t\t}\n\t\t\t\telse if (frm == null){\n\t\t\t\t\tthrow new JenaTransactionException(\"Valid domian not identified\");\n\t\t\t\t}\n\t\t\t\telse if (t == null) {\n\t\t\t\t\tthrow new JenaTransactionException(\"Valid range not identified\");\n\t\t\t\t}\n\t\t\t} catch (TranslationException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t// No restrictions--this will become an rdf:Property\n\t\t\tretProp = createRdfProperty(propUri, null);\n\t\t}\n\t\tif (sr != null && retProp != null && sr.getAnnotations() != null && retProp.canAs(OntResource.class)) {\n\t\t\taddAnnotationsToResource(retProp.as(OntResource.class), sr.getAnnotations());\n\t\t}\n\t\treturn retProp;\n\t}\n\t\n\tprivate void addLengthRestrictionsToList(OntResource rngRsrc, SadlDataTypeFacet facet) {\n\t\t// check for list length restrictions\n\t\tif (facet != null && rngRsrc.canAs(OntClass.class)) {\n\t\t\tif (facet.getLen() != null) {\n\t\t\t\tint len = Integer.parseInt(facet.getLen());\n\t\t\t\tHasValueRestriction hvr = getTheJenaModel().createHasValueRestriction(null,\n\t\t\t\t\t\tgetTheJenaModel().getProperty(SadlConstants.SADL_LIST_MODEL_LENGTH_RESTRICTION_URI),\n\t\t\t\t\t\tgetTheJenaModel().createTypedLiteral(len));\n\t\t\t\trngRsrc.as(OntClass.class).addSuperClass(hvr);\n\t\t\t}\n\t\t\tif (facet.getMinlen() != null) {\n\t\t\t\tint minlen = Integer.parseInt(facet.getMinlen());\n\t\t\t\tHasValueRestriction hvr = getTheJenaModel().createHasValueRestriction(null,\n\t\t\t\t\t\tgetTheJenaModel().getProperty(SadlConstants.SADL_LIST_MODEL_MINLENGTH_RESTRICTION_URI),\n\t\t\t\t\t\tgetTheJenaModel().createTypedLiteral(minlen));\n\t\t\t\trngRsrc.as(OntClass.class).addSuperClass(hvr);\n\t\t\t}\n\t\t\tif (facet.getMaxlen() != null && !facet.getMaxlen().equals(\"*\")) {\n\t\t\t\tint maxlen = Integer.parseInt(facet.getMaxlen());\n\t\t\t\tHasValueRestriction hvr = getTheJenaModel().createHasValueRestriction(null,\n\t\t\t\t\t\tgetTheJenaModel().getProperty(SadlConstants.SADL_LIST_MODEL_MAXLENGTH_RESTRICTION_URI),\n\t\t\t\t\t\tgetTheJenaModel().createTypedLiteral(maxlen));\n\t\t\t\trngRsrc.as(OntClass.class).addSuperClass(hvr);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprivate void addCardinalityRestriction(OntResource cls, Property retProp, int cardinality) {\n\t\tif (cls != null && cls.canAs(OntClass.class)) {\n\t\t\tCardinalityRestriction cr = getTheJenaModel().createCardinalityRestriction(null, retProp, cardinality);\n\t\t\tcls.as(OntClass.class).addSuperClass(cr);\n\t\t}\n\t}\n\t\n\tprivate String createUniqueDefaultValName(OntClass restricted,\n\t\t\tProperty prop) throws PrefixNotFoundException {\n\t\tString nmBase = restricted.getLocalName() + \"_\" + prop.getLocalName()\n\t\t\t\t+ \"_default\";\n\t\tString nm = getModelNamespace() + nmBase;\n\t\tint cntr = 0;\n\t\twhile (getTheJenaModel().getIndividual(nm) != null) {\n\t\t\tnm = nmBase + ++cntr;\n\t\t}\n\t\treturn nm;\n\t}\n\n\tprivate Individual createDefault(OntClass restricted, Property prop,\n\t\t\tRDFNode defValue, int level, EObject ref) throws Exception {\n\t\tif (defValue instanceof Individual) {\n\t\t\tOntClass instDefCls = getTheJenaModel().getOntClass(\n\t\t\t\t\tResourceManager.ACUITY_DEFAULTS_NS + \"ObjectDefault\");\n\t\t\tif (instDefCls == null) {\n\t\t\t\taddError(\"Unable to find ObjectDefault in Defaults model\", ref);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tIndividual def = getTheJenaModel().createIndividual(createUniqueDefaultValName(restricted, prop), instDefCls);\n\t\t\tdef.addProperty(\n\t\t\t\t\tgetTheJenaModel().getOntProperty(\n\t\t\t\t\t\t\tResourceManager.ACUITY_DEFAULTS_NS +\n\t\t\t\t\t\t\t\t\t\"appliesToProperty\"), prop);\n\t\t\tdef.addProperty(\n\t\t\t\t\tgetTheJenaModel().getOntProperty(ResourceManager.ACUITY_DEFAULTS_NS + \n\t\t\t\t\t\t\t\t\t\"hasObjectDefault\"), defValue);\n\t\t\tif (level > 0) {\n\t\t\t\tString hlpuri = ResourceManager.ACUITY_DEFAULTS_NS +\n\t\t\t\t\t\t\"hasLevel\";\n\t\t\t\tOntProperty hlp = getTheJenaModel().getOntProperty(hlpuri);\n\t\t\t\tif (hlp == null) {\n\t\t\t\t\taddError(\"Unable to find hasLevel property in Defaults model\", ref);\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\tLiteral defLvl = getTheJenaModel().createTypedLiteral(level);\n\t\t\t\tdef.addProperty(hlp, defLvl);\n\t\t\t}\n\t\t\treturn def;\n\t\t} else if (defValue instanceof Literal) {\n\t\t\tOntClass litDefCls = getTheJenaModel().getOntClass(\n\t\t\t\t\tResourceManager.ACUITY_DEFAULTS_NS + \"DataDefault\");\n\t\t\tif (litDefCls == null) {\n\t\t\t\taddError(\"Unable to find DataDefault in Defaults model\",ref);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tIndividual def = getTheJenaModel().createIndividual(\n\t\t\t\t\tmodelNamespace +\n\t\t\t\t\t\t\tcreateUniqueDefaultValName(restricted, prop),\n\t\t\t\t\tlitDefCls);\n\t\t\tdef.addProperty(\n\t\t\t\t\tgetTheJenaModel().getOntProperty(\n\t\t\t\t\t\t\tResourceManager.ACUITY_DEFAULTS_NS +\n\t\t\t\t\t\t\t\t\t\"appliesToProperty\"), prop);\n\t\t\tdef.addProperty(\n\t\t\t\t\tgetTheJenaModel().getOntProperty(\n\t\t\t\t\t\t\tResourceManager.ACUITY_DEFAULTS_NS +\n\t\t\t\t\t\t\t\t\t\"hasDataDefault\"), defValue);\n\t\t\tif (level > 0) {\n\t\t\t\tString hlpuri = ResourceManager.ACUITY_DEFAULTS_NS +\n\t\t\t\t\t\t\"hasLevel\";\n\t\t\t\tOntProperty hlp = getTheJenaModel().getOntProperty(hlpuri);\n\t\t\t\tif (hlp == null) {\n\t\t\t\t\taddError(\"Unable to find hasLevel in Defaults model\",ref);\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\tLiteral defLvl = getTheJenaModel().createTypedLiteral(level);\n\t\t\t\tdef.addProperty(hlp, defLvl);\n\t\t\t}\n\t\t\treturn def;\n\t\t}\n\t\treturn null;\n\t}\n\n\tprivate EnumeratedClass sadlExplicitValuesToEnumeratedClass(EList values)\n\t\t\tthrows JenaProcessorException {\n\t\tList nodevals = new ArrayList();\n\t\tfor (int i = 0; i < values.size(); i++) {\n\t\t\tSadlExplicitValue value = values.get(i);\n\t\t\tRDFNode nodeval = sadlExplicitValueToRdfNode(value, null, true);\n\t\t\tif (nodeval.canAs(Individual.class)){\n\t\t\t\tnodevals.add(nodeval.as(Individual.class));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tnodevals.add(nodeval);\n\t\t\t}\n\t\t}\n\t\tRDFNode[] enumedArray = nodevals\n\t\t\t\t.toArray(new RDFNode[nodevals.size()]);\n\t\tRDFList rdfl = getTheJenaModel().createList(enumedArray);\n\t\tEnumeratedClass enumCls = getTheJenaModel().createEnumeratedClass(null, rdfl);\n\t\treturn enumCls;\n\t}\n\t\n\tprivate RDFNode sadlExplicitValueToRdfNode(SadlExplicitValue value, Property prop, boolean literalsAllowed) throws JenaProcessorException {\n\t\tif (value instanceof SadlResource) {\n\t\t\tString uri = getDeclarationExtensions().getConceptUri((SadlResource) value);\n\t\t\tcom.hp.hpl.jena.rdf.model.Resource rsrc = getTheJenaModel().getResource(uri);\n\t\t\treturn rsrc;\n\t\t}\n\t\telse {\n\t\t\tLiteral litval = sadlExplicitValueToLiteral(value, prop);\n\t\t\treturn litval;\n\t\t}\n\t}\n\t\n\tprivate Property assignRangeToProperty(String propUri, OntConceptType propType, OntResource rngRsrc,\n\t\t\tRangeValueType rngValueType, SadlTypeReference rng) throws JenaProcessorException {\n\t\tProperty retProp;\n\t\tif (propType.equals(OntConceptType.CLASS_PROPERTY) || propType.equals(OntConceptType.CLASS_LIST) || propType.equals(OntConceptType.DATATYPE_LIST)) {\n\t\t\tOntClass rngCls = rngRsrc.asClass();\n\t\t\tObjectProperty prop = getOrCreateObjectProperty(propUri);\n\t\t\taddPropertyRange(propType, prop, rngCls, rngValueType, rng);\n\t\t\tretProp = prop;\n\t\t}\n\t\telse if (propType.equals(OntConceptType.DATATYPE_PROPERTY)) {\n\t\t\tDatatypeProperty prop = getOrCreateDatatypeProperty(propUri);\n\t\t\taddPropertyRange(propType, prop, rngRsrc, rngValueType, rng);\n\t\t\tretProp = prop;\n\t\t}\n\t\telse if (propType.equals(OntConceptType.RDF_PROPERTY)) {\n\t\t\tOntProperty prop = getOrCreateRdfProperty(propUri);\n\t\t\taddPropertyRange(propType, prop, rngRsrc, rngValueType, rng);\n//\t\t\tgetTheJenaModel().add(prop, RDFS.range, rngRsrc);\n\t\t\tretProp = prop;\n\t\t}\n\t\telse {\n\t\t\tthrow new JenaProcessorException(\"Property '\" + propUri + \"' of unexpected type '\" + rngRsrc.toString() + \"'\");\n\t\t}\n\t\treturn retProp;\n\t}\n\n\tprivate SadlResource sadlResourceFromSadlProperty(SadlProperty element) {\n\t\tSadlResource sr = element.getNameOrRef();\n\t\tif (sr == null) {\n\t\t\tsr = element.getProperty();\n\t\t}\n\t\tif (sr == null) {\n\t\t\tsr = element.getNameDeclarations().iterator().next();\n\t\t}\n\t\treturn sr;\n\t}\n\n\tprivate void addPropertyRange(OntConceptType propType, OntProperty prop, RDFNode rngNode, RangeValueType rngValueType, EObject context) throws JenaProcessorException {\n\t\tOntResource rngResource = null;\n\t\tif (rngNode instanceof OntClass){\n\t\t\trngResource = rngNode.as(OntClass.class);\n\t\t\tif (prop.isDatatypeProperty()) {\n\t\t\t\t// this happens when the range is a union of Lists of primitive types\n\t\t\t\tgetTheJenaModel().remove(prop,RDF.type, OWL.DatatypeProperty);\n\t\t\t\tgetTheJenaModel().add(prop, RDF.type, OWL.ObjectProperty);\n\t\t\t}\n\t\t}\n\t\t// If ignoring UnittedQuantity, change any UnittedQuantity range to the range of value and make the property an owl:DatatypeProperty\n\t\t// TODO this should probably work for any declared subclass of UnittedQuantity and associated value restriction?\n\t\tif (ignoreUnittedQuantities && rngResource != null && rngResource.isURIResource() && rngResource.canAs(OntClass.class) && \n\t\t\t\trngResource.getURI().equals(SadlConstants.SADL_IMPLICIT_MODEL_UNITTEDQUANTITY_URI)) {\n\t\t\tcom.hp.hpl.jena.rdf.model.Resource effectiveRng = getUnittedQuantityValueRange();\n\t\t\trngNode = effectiveRng;\n\t\t\trngResource = null;\n\t\t\tgetTheJenaModel().remove(prop,RDF.type, OWL.ObjectProperty);\n\t\t\tgetTheJenaModel().add(prop, RDF.type, OWL.DatatypeProperty);\n\t\t}\n\t\t\n\t\tRDFNode propOwlType = null;\n\t\tboolean rangeExists = false;\n\t\tboolean addNewRange = false;\n\t\tStmtIterator existingRngItr = getTheJenaModel().listStatements(prop, RDFS.range, (RDFNode)null);\n\t\tif (existingRngItr.hasNext()) {\n\t\t\tRDFNode existingRngNode = existingRngItr.next().getObject();\n\t\t\trangeExists = true;\n\t\t\t// property already has a range know to this model\n\t\t\tif (rngNode.equals(existingRngNode) || (rngResource != null && rngResource.equals(existingRngNode))) {\n\t\t\t\t// do nothing-- rngNode is already in range\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (prop.isDatatypeProperty()) {\n\t\t\t\tString existingRange = stmtIteratorToObjectString(getTheJenaModel().listStatements(prop, RDFS.range, (RDFNode)null));\n\t\t\t\taddError(SadlErrorMessages.CANNOT_ASSIGN_EXISTING.get(\"range\", nodeToString(prop), existingRange), context);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!rngNode.isResource()) {\n\t\t\t\taddError(\"Proposed range node '\" + rngNode.toString() + \"' is not a Resource so cannot be added to create a union class as range\", context);\n\t\t\t\treturn;\n\t\t\t}\t\t\n\t\t\tif (existingRngNode.canAs(OntClass.class)){\n\t\t\t\t// is the new range a subclass of the existing range, or vice versa?\n\t\t\t\tif ((rngResource != null && rngResource.canAs(OntClass.class) && checkForSubclassing(rngResource.as(OntClass.class), existingRngNode.as(OntClass.class), context)) || \n\t\t\t\t\t\trngNode.canAs(OntClass.class) && checkForSubclassing(rngNode.as(OntClass.class), existingRngNode.as(OntClass.class), context)) {\n\t\t\t\t\tStringBuilder sb = new StringBuilder(\"This range is a subclass of the range which is already defined\");\n\t\t\t\t\tString existingRange = nodeToString(existingRngNode);\n\t\t\t\t\tif (existingRange != null) {\n\t\t\t\t\t\tsb.append(\" (\");\n\t\t\t\t\t\tsb.append(existingRange);\n\t\t\t\t\t\tsb.append(\") \");\n\t\t\t\t\t}\n\t\t\t\t\tsb.append(\"; perhaps you meant to restrict values of this property on this class with an 'only has values of type' restriction?\");\n\t\t\t\t\taddWarning(sb.toString(), context);\t\t\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tboolean rangeInThisModel = false;\n\t\t\tStmtIterator inModelStmtItr = getTheJenaModel().getBaseModel().listStatements(prop, RDFS.range, (RDFNode)null);\n\t\t\tif (inModelStmtItr.hasNext()) {\n\t\t\t\trangeInThisModel = true;\n\t\t\t}\n\t\t\tif (domainAndRangeAsUnionClasses) {\n\t\t\t\t// in this case we want to create a union class if necessary\n\t\t\t\tif (rangeInThisModel) {\n\t\t\t\t\t// this model (as opposed to imports) already has a range specified\n\t\t\t\t\taddNewRange = false;\n\t\t\t\t\tUnionClass newUnionClass = null;\n\t\t\t\t\twhile (inModelStmtItr.hasNext()) {\n\t\t\t\t\t\tRDFNode rngThisModel = inModelStmtItr.nextStatement().getObject();\n\t\t\t\t\t\tif (rngThisModel.isResource()) {\n\t\t\t\t\t\t\tif (rngThisModel.canAs(OntResource.class)){\n\t\t\t\t\t\t\t\tif (existingRngNode.toString().equals(rngThisModel.toString())) {\n\t\t\t\t\t\t\t\t\trngThisModel = existingRngNode;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tnewUnionClass = createUnionClass(rngThisModel.as(OntResource.class), rngResource != null ? rngResource : rngNode.asResource());\n\t\t\t\t\t\t\t\tlogger.debug(\"Range '\" + rngNode.toString() + \"' added to property '\" + prop.getURI() + \"'\");\n\t\t\t\t\t\t\t\tif (!newUnionClass.equals(rngThisModel)) {\n\t\t\t\t\t\t\t\t\taddNewRange = true;\n\t\t\t\t\t\t\t\t\trngResource = newUnionClass;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\trngNode = null;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tthrow new JenaProcessorException(\"Encountered non-OntResource in range of '\" + prop.getURI() + \"'\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tthrow new JenaProcessorException(\"Encountered non-Resource in range of '\" + prop.getURI() + \"'\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (addNewRange) {\n\t\t\t\t\t\tgetTheJenaModel().remove(getTheJenaModel().getBaseModel().listStatements(prop, RDFS.range, (RDFNode)null));\n\t\t\t\t\t\trngNode = newUnionClass;\n\t\t\t\t\t}\n\t\t\t\t}\t// end if existing range in this model\n\t\t\t\telse {\n\t\t\t\t\tinModelStmtItr.close();\n\t\t\t\t\t// check to see if this is something new\n\t\t\t\t\tdo {\n\t\t\t\t\t\tif (existingRngNode.equals(rngNode)) {\n\t\t\t\t\t\t\texistingRngItr.close();\n\t\t\t\t\t\t\treturn;\t// already in domain, nothing to add\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (existingRngItr.hasNext()) {\n\t\t\t\t\t\t\texistingRngNode = existingRngItr.next().getObject();\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\texistingRngNode = null;\n\t\t\t\t\t\t}\n\t\t\t\t\t} while (existingRngNode != null);\n\t\t\t\t}\n\t\t\t}\t// end if domainAndRangeAsUnionClasses\n\t\t\telse {\n\t\t\t\tinModelStmtItr.close();\n\t\t\t}\n\t\t\tif (rangeExists && !rangeInThisModel) {\n\t\t\t\taddWarning(SadlErrorMessages.IMPORTED_RANGE_CHANGE.get(nodeToString(prop)), context);\n\t\t\t}\n\t\t}\t// end if existing range in any model, this or imports\n\t\tif (rngNode != null) {\t\n\t\t\tif (rngResource != null) {\n\t\t\t\tif (!domainAndRangeAsUnionClasses && rngResource instanceof UnionClass) {\n\t\t\t\t\tList uclsmembers = getUnionClassMemebers((UnionClass)rngResource);\n\t\t\t\t\tfor (int i = 0; i < uclsmembers.size(); i++) {\n\t\t\t\t\t\tgetTheJenaModel().add(prop, RDFS.range, uclsmembers.get(i));\n\t\t\t\t\t\tlogger.debug(\"Range '\" + uclsmembers.get(i).toString() + \"' added to property '\" + prop.getURI() + \"'\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tgetTheJenaModel().add(prop, RDFS.range, rngResource);\n\t\t\t\t\tlogger.debug(\"Range '\" + rngResource.toString() + \"' added to property '\" + prop.getURI() + \"'\");\n\t\t\t\t}\n\t\t\t\tpropOwlType = OWL.ObjectProperty;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcom.hp.hpl.jena.rdf.model.Resource rngrsrc = rngNode.asResource();\n\t\t\t\tif (rngrsrc.hasProperty(RDF.type, RDFS.Datatype)) {\n\t\t\t\t\tpropOwlType = OWL.DatatypeProperty;\n\t\t\t\t}\n\t\t\t\telse if (rngrsrc.canAs(OntClass.class)){\n\t\t\t\t\tpropOwlType = OWL.ObjectProperty;\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tpropOwlType = OWL.DatatypeProperty;\n\t\t\t\t}\n\t\t\t\tgetTheJenaModel().add(prop, RDFS.range, rngNode);\n\t\t\t}\n\t\t}\n\t\tif (propType.equals(OntConceptType.RDF_PROPERTY) && propOwlType != null) {\n\t\t\tgetTheJenaModel().add(prop, RDF.type, propOwlType);\n\t\t}\n\t}\n\n\tprivate String stmtIteratorToObjectString(StmtIterator stmtitr) {\n\t\tStringBuilder sb = new StringBuilder();\n\t\twhile (stmtitr.hasNext()) {\n\t\t\tRDFNode obj = stmtitr.next().getObject();\n\t\t\tif (sb.length() > 0) {\n\t\t\t\tsb.append(\", \");\n\t\t\t}\n\t\t\tsb.append(nodeToString(obj));\n\t\t}\n\t\treturn sb.toString();\n\t}\n\t\n\tprivate String nodeToString(RDFNode obj) {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tif (obj.isURIResource()) {\n\t\t\tsb.append(uriStringToString(obj.toString()));\n\t\t}\n\t\telse if (obj.canAs(UnionClass.class)){\n\t\t\tUnionClass ucls = obj.as(UnionClass.class);\n\t\t\tExtendedIterator uitr = ucls.getOperands().iterator();\n\t\t\tsb.append(\"(\");\n\t\t\twhile (uitr.hasNext()) {\n\t\t\t\tif (sb.length() > 1) {\n\t\t\t\t\tsb.append(\" or \");\n\t\t\t\t}\n\t\t\t\tsb.append(nodeToString(uitr.next()));\n\t\t\t}\n\t\t\tsb.append(\")\");\n\t\t}\n\t\telse if (obj.canAs(IntersectionClass.class)){\n\t\t\tIntersectionClass icls = obj.as(IntersectionClass.class);\n\t\t\tExtendedIterator iitr = icls.getOperands().iterator();\n\t\t\tsb.append(\"(\");\n\t\t\twhile (iitr.hasNext()) {\n\t\t\t\tif (sb.length() > 1) {\n\t\t\t\t\tsb.append(\" and \");\n\t\t\t\t}\n\t\t\t\tsb.append(nodeToString(iitr.next()));\n\t\t\t}\n\t\t\tsb.append(\")\");\n\t\t}\n\t\telse if (obj.isResource() && \n\t\t\t\tgetTheJenaModel().contains(obj.asResource(), RDFS.subClassOf, getTheJenaModel().getOntClass(SadlConstants.SADL_LIST_MODEL_LIST_URI))) {\n\t\t\tConceptName cn = getTypedListType(obj);\n\t\t\tsb.append(cn.getName());\n\t\t\tsb.append(\" List\");\n\t\t}\n\t\telse {\n\t\t\tsb.append(\"\");\n\t\t}\n\t\treturn sb.toString();\n\t}\n\t\n\tpublic String uriStringToString(String uri) {\n\t\tint sep = uri.lastIndexOf('#');\n\t\tif (sep > 0) {\n\t\t\tString ns = uri.substring(0, sep);\n\t\t\tString ln = uri.substring(sep + 1);\n\t\t\t// if the concept is in the current model just return the localname\n\t\t\tif (ns.equals(getModelName())) {\n\t\t\t\treturn ln;\n\t\t\t}\n\t\t\t// get the prefix and if there is one generate qname\n\t\t\tString prefix = getConfigMgr().getGlobalPrefix(ns);\n\t\t\tif (prefix != null && prefix.length() > 0) {\n\t\t\t\treturn prefix + \":\" + ln;\n\t\t\t}\n\t\t\treturn ln;\n\t\t}\n\t\treturn uri;\n\t}\n\n\n\t\n\tprivate boolean checkForSubclassing(OntClass rangeCls, OntResource existingRange, EObject context) throws JenaProcessorException {\n\t\t// this is changing the range of a property defined in a different model\n\t\ttry {\n\t\t\tif (SadlUtils.classIsSubclassOf((OntClass) rangeCls, existingRange, true, null)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t} catch (CircularDependencyException e) {\n\t\t\tthrow new JenaProcessorException(e.getMessage(), e);\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprivate boolean updateObjectPropertyRange(OntProperty prop, OntResource rangeCls, ExtendedIterator ritr, RangeValueType rngValueType, EObject context) throws JenaProcessorException {\n\t\tboolean retval = false;\n\t\tif (rangeCls != null) {\n\t\t\tOntResource newRange = createUnionOfClasses(rangeCls, ritr);\n\t\t\tif (newRange != null) {\n\t\t\t\tif (newRange.equals(rangeCls)) {\n\t\t\t\t\treturn retval;\t// do nothing--the rangeCls is already in the range\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (prop.getRange() != null) {\n\t\t\t\t// remove existing range in this model\n\t\t\t\tprop.removeRange(prop.getRange());\n\t\t\t}\n\t\t\tprop.addRange(newRange); \n\t\t\tretval = true;\n\t\t} else {\n\t\t\taddError(SadlErrorMessages.INVALID_NULL.get(\"range\"), context);\n\t\t}\n\t\treturn retval;\n\t}\n\n\tpublic void addError(String msg, EObject context) {\n\t\tif (getIssueAcceptor() != null) {\n\t\t\tgetIssueAcceptor().addError(msg, context);\n\t\t\tif (isSyntheticUri(null, getCurrentResource())) {\n\t\t\t\tif (getMetricsProcessor() != null) {\n\t\t\t\t\tgetMetricsProcessor().addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.UNCLASSIFIED_FAILURE_URI);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if (!generationInProgress){\n\t\t\tSystem.err.println(msg);\n\t\t}\n\t}\n\n\tpublic void addWarning(String msg, EObject context) {\n\t\tif (getIssueAcceptor() != null) {\n\t\t\tgetIssueAcceptor().addWarning(msg, context);\n\t\t\tif (isSyntheticUri(null, getCurrentResource())) {\n\t\t\t\tif (getMetricsProcessor() != null) {\n\t\t\t\t\tgetMetricsProcessor().addMarker(null, MetricsProcessor.WARNING_MARKER_URI, MetricsProcessor.WARNING_MARKER_URI);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if (!generationInProgress) {\n\t\t\tSystem.out.println(msg);\t\t\t\n\t\t}\n\t}\n\n\tpublic void addInfo(String msg, EObject context) {\n\t\tif (getIssueAcceptor() != null) {\n\t\t\tgetIssueAcceptor().addInfo(msg, context);\n\t\t\tif (isSyntheticUri(null, getCurrentResource())) {\n\t\t\t\tif (getMetricsProcessor() != null) {\n\t\t\t\t\tgetMetricsProcessor().addMarker(null, MetricsProcessor.INFO_MARKER_URI, MetricsProcessor.INFO_MARKER_URI);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if (!generationInProgress) {\n\t\t\tSystem.out.println(msg);\t\t\t\n\t\t}\n\t}\n\n\t//\tprivate OntResource addClassToUnionClass(OntResource existingCls,\n//\t\t\tOntResource cls) throws JenaProcessorException {\n//\t\tif (existingCls != null && !existingCls.equals(cls)) {\n//\t\t\ttry {\n//\t\t\t\tif (existingCls.canAs(OntClass.class) && SadlUtils.classIsSubclassOf(existingCls.as(OntClass.class), cls, true, null)) {\n//\t\t\t\t\treturn cls;\n//\t\t\t\t}\n//\t\t\t\telse if (cls.canAs(OntClass.class) && SadlUtils.classIsSubclassOf(cls.as(OntClass.class), existingCls, true, null)) {\n//\t\t\t\t\treturn existingCls;\n//\t\t\t\t}\n//\t\t\t\telse {\n//\t\t\t\t\tRDFList classes = null;\n//\t\t\t\t\tif (existingCls.canAs(UnionClass.class)) {\n//\t\t\t\t\t\ttry {\n//\t\t\t\t\t\t\t UnionClass ucls = existingCls.as(UnionClass.class);\n//\t\t\t\t\t\t\t ucls.addOperand(cls);\n//\t\t\t\t\t\t\t return ucls;\n//\t\t\t\t\t\t} catch (Exception e) {\n//\t\t\t\t\t\t\t// don't know why this is happening\n//\t\t\t\t\t\t\tlogger.error(\"Union class error that hasn't been resolved or understood.\");\n//\t\t\t\t\t\t\treturn cls;\n//\t\t\t\t\t\t}\n//\t\t\t\t\t} else {\n//\t\t\t\t\t\tif (cls.equals(existingCls)) {\n//\t\t\t\t\t\t\treturn existingCls;\n//\t\t\t\t\t\t}\n//\t\t\t\t\t\tclasses = getTheJenaModel().createList();\n//\t\t\t\t\t\tOntResource inCurrentModel = null;\n//\t\t\t\t\t\tif (existingCls.isURIResource()) {\n//\t\t\t\t\t\t\tinCurrentModel = getTheJenaModel().getOntResource(existingCls.getURI());\n//\t\t\t\t\t\t}\n//\t\t\t\t\t\tif (inCurrentModel != null) {\n//\t\t\t\t\t\t\tclasses = classes.with(inCurrentModel);\n//\t\t\t\t\t\t}\n//\t\t\t\t\t\telse {\n//\t\t\t\t\t\t\tclasses = classes.with(existingCls);\n//\t\t\t\t\t\t}\n//\t\t\t\t\t\tclasses = classes.with(cls);\n//\t\t\t\t\t}\n//\t\t\t\t\tOntResource unionClass = getTheJenaModel().createUnionClass(null,\n//\t\t\t\t\t\t\tclasses);\n//\t\t\t\t\treturn unionClass;\n//\t\t\t\t}\n//\t\t\t} catch (CircularDependencyException e) {\n//\t\t\t\tthrow new JenaProcessorException(e.getMessage(), e);\n//\t\t\t}\n//\t\t} else {\n//\t\t\treturn cls;\n//\t\t}\n//\t}\n\n\tprivate void processSadlNecessaryAndSufficient(SadlNecessaryAndSufficient element) throws JenaProcessorException {\n\t\tOntResource rsrc = sadlTypeReferenceToOntResource(element.getSubject());\n\t\tOntClass supercls = null;\n\t\tif (rsrc != null) {\n\t\t\tsupercls = rsrc.asClass();\n\t\t}\n\t\tOntClass rolecls = getOrCreateOntClass(getDeclarationExtensions().getConceptUri(element.getObject()));\n\t\tIterator itr = element.getPropConditions().iterator();\n\t\tList conditionClasses = new ArrayList();\n\t\twhile (itr.hasNext()) {\n\t\t\tSadlPropertyCondition nxt = itr.next();\n\t\t\tconditionClasses.add(processSadlPropertyCondition(nxt));\n\t\t}\n\t\t// we have all the parts--create the equivalence class\n\t\tif (conditionClasses.size() == 1) {\n\t\t\tif (supercls != null && conditionClasses.get(0) != null) {\n\t\t\t\tIntersectionClass eqcls = createIntersectionClass(supercls, conditionClasses.get(0));\n\t\t\t\trolecls.setEquivalentClass(eqcls);\n\t\t\t\tlogger.debug(\"New intersection class created as equivalent of '\" + rolecls.getURI() + \"'\");\n\t\t\t} else if (conditionClasses.get(0) != null) {\n\t\t\t\trolecls.setEquivalentClass(conditionClasses.get(0));\n\t\t\t\tlogger.debug(\"Equivalent class set for '\" + rolecls.getURI() + \"'\");\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthrow new JenaProcessorException(\"Necessary and sufficient conditions appears to have invalid input.\");\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tint base = supercls != null ? 1 : 0;\n\t\t\tRDFNode[] memberList = new RDFNode[base + conditionClasses.size()];\n\t\t\tif (base > 0) {\n\t\t\t\tmemberList[0] = supercls;\n\t\t\t}\n\t\t\tfor (int i = 0; i < conditionClasses.size(); i++) {\n\t\t\t\tmemberList[base + i] = conditionClasses.get(i);\n\t\t\t}\n\t\t\tIntersectionClass eqcls = createIntersectionClass(memberList);\n\t\t\trolecls.setEquivalentClass(eqcls);\n\t\t\tlogger.debug(\"New intersection class created as equivalent of '\" + rolecls.getURI() + \"'\");\n\t\t}\n\t}\n\n\tprivate void processSadlDifferentFrom(SadlDifferentFrom element) throws JenaProcessorException {\n\t\tList differentFrom = new ArrayList();\n\t\tIterator dcitr = element.getTypes().iterator();\n\t\twhile(dcitr.hasNext()) {\n\t\t\tSadlClassOrPropertyDeclaration decl = dcitr.next();\n\t\t\tIterator djitr = decl.getClassOrProperty().iterator();\n\t\t\twhile (djitr.hasNext()) {\n\t\t\t\tSadlResource sr = djitr.next();\n\t\t\t\tString declUri = getDeclarationExtensions().getConceptUri(sr);\n\t\t\t\tif (declUri == null) {\n\t\t\t\t\tthrow new JenaProcessorException(\"Failed to get concept URI for SadlResource in processSadlDifferentFrom\");\n\t\t\t\t}\n\t\t\t\tIndividual inst = getTheJenaModel().getIndividual(declUri);\n\t\t\t\tdifferentFrom.add(inst);\n\t\t\t}\n\t\t}\n\t\tSadlTypeReference nsas = element.getNotTheSameAs();\n\t\tif (nsas != null) {\n\t\t\tOntResource nsasrsrc = sadlTypeReferenceToOntResource(nsas);\n\t\t\tdifferentFrom.add(nsasrsrc.asIndividual());\n\t\t\tSadlResource sr = element.getNameOrRef();\n\t\t\tIndividual otherInst = getTheJenaModel().getIndividual(getDeclarationExtensions().getConceptUri(sr));\n\t\t\tdifferentFrom.add(otherInst);\n\t\t}\n\t\tRDFNode[] nodeArray = null;\n\t\tif (differentFrom.size() > 0) {\n\t\t\tnodeArray = differentFrom.toArray(new Individual[differentFrom.size()]);\n\t\t}\n\t\telse {\n\t\t\tthrow new JenaProcessorException(\"Unexpect empty array in processSadlDifferentFrom\");\n\t\t}\n\t\tRDFList differentMembers = getTheJenaModel().createList(nodeArray);\n\t\tgetTheJenaModel().createAllDifferent(differentMembers);\n\t\tlogger.debug(\"New all different from created\");\n\t}\n\n\tprivate Individual processSadlInstance(SadlInstance element) throws JenaProcessorException, CircularDefinitionException {\n\t\t// this has two forms:\n\t\t//\t1) is a ...\n\t\t//\t2) a ....\n\t\tSadlTypeReference type = element.getType();\n\t\tboolean isList = typeRefIsList(type);\n\t\tSadlResource sr = sadlResourceFromSadlInstance(element);\n\t\tIndividual inst = null;\n\t\tString instUri = null;\n\t\tOntConceptType subjType = null;\n\t\tboolean isActuallyClass = false;\n\t\tif (sr != null) {\n\t\t\tinstUri = getDeclarationExtensions().getConceptUri(sr);\n\t\t\tif (instUri == null) {\n\t\t\t\tthrow new JenaProcessorException(\"Failed to get concept URI of SadlResource in processSadlInstance\");\n\t\t\t}\n\t\t\tsubjType = getDeclarationExtensions().getOntConceptType(sr);\n\t\t\tif (subjType.equals(OntConceptType.CLASS)) {\n\t\t\t\t// This is really a class so don't treat as an instance\n\t\t\t\tOntClass actualClass = getOrCreateOntClass(instUri);\n\t\t\t\tisActuallyClass = true;\n\t\t\t\tinst = actualClass.asIndividual();\n\t\t\t}\n\t\t}\n\t\tOntClass cls = null;\n\t\tif (!isActuallyClass) {\n\t\t\tif (type != null) {\n\t\t\t\tif (type instanceof SadlPrimitiveDataType) {\n\t\t\t\t\tcom.hp.hpl.jena.rdf.model.Resource rsrc = sadlTypeReferenceToResource(type);\n\t\t\t\t\tif (isList) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tcls = getOrCreateListSubclass(null, rsrc.getURI(), type.eResource());\n\t\t\t\t\t\t} catch (JenaProcessorException e) {\n\t\t\t\t\t\t\taddError(e.getMessage(), type);\n\t\t\t\t\t\t}\n\t\t\t\t\t}else{\n\t\t\t\t\t\t//AATIM-2306 If not list, generate error when creating instances of primitive data types.\n\t\t\t\t\t\taddError(\"Invalid to create an instance of a primitive datatype ( \\'\" + ((SadlPrimitiveDataType) type).getPrimitiveType().toString() + \"\\' in this case). Instances of primitive datatypes exist implicitly.\", type );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tOntResource or = sadlTypeReferenceToOntResource(type);\n\t\t\t\t\tif (or != null && or.canAs(OntClass.class)){\n\t\t\t\t\t\tcls = or.asClass();\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\telse if (or instanceof Individual) {\n\t\t\t\t\t\tinst = (Individual) or;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} \n\t\t\tif (inst == null) {\n\t\t\t\tif (cls != null) {\n\t\t\t\t\tinst = createIndividual(instUri, cls);\n\t\t\t\t}\n\t\t\t\telse if (instUri != null) {\n\t\t\t\t\tinst = createIndividual(instUri, (OntClass)null);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrow new JenaProcessorException(\"Can't create an unnamed instance with no class given\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tIterator itr = element.getPropertyInitializers().iterator();\n\t\twhile (itr.hasNext()) {\n\t\t\tSadlPropertyInitializer propinit = itr.next();\n\t\t\tSadlResource prop = propinit.getProperty();\n\t\t\tOntConceptType propType = getDeclarationExtensions().getOntConceptType(prop);\n\t\t\tif (subjType != null && subjType.equals(OntConceptType.CLASS) && \n\t\t\t\t\t!(propType.equals(OntConceptType.ANNOTATION_PROPERTY)) && \t// only a problem if not an annotation property\n\t\t\t\t\t!getOwlFlavor().equals(SadlConstants.OWL_FLAVOR.OWL_FULL)) {\n\t\t\t\taddWarning(SadlErrorMessages.CLASS_PROPERTY_VALUE_OWL_FULL.get(), element);\n\t\t\t}\n\t\t\tEObject val = propinit.getValue();\n\t\t\tif (val != null) {\n\t\t\t\ttry {\n\t\t\t\t\tif (getModelValidator() != null) {\n\t\t\t\t\t\tStringBuilder error = new StringBuilder();\n\t\t\t\t\t\tif (!getModelValidator().checkPropertyValueInRange(getTheJenaModel(), sr, prop, val, error)) {\n\t\t\t\t\t\t\tissueAcceptor.addError(error.toString(), propinit);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} catch (DontTypeCheckException e) {\n\t\t\t\t\t// do nothing\n\t\t\t\t} catch(PropertyWithoutRangeException e){\n\t\t\t\t\tString propUri = getDeclarationExtensions().getConceptUri(prop);\n\t\t\t\t\tif (!propUri.equals(SadlConstants.SADL_IMPLICIT_MODEL_IMPLIED_PROPERTY_URI)) {\n\t\t\t\t\t\tissueAcceptor.addWarning(SadlErrorMessages.PROPERTY_WITHOUT_RANGE.get(getDeclarationExtensions().getConcreteName(prop)), propinit);\n\t\t\t\t\t}\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\tthrow new JenaProcessorException(\"Unexpected error checking value in range\", e);\n\t\t\t\t}\n\t\t\t\tassignInstancePropertyValue(inst, cls, prop, val);\n\t\t\t} else {\n\t\t\t\taddError(\"no value found\", propinit);\n\t\t\t}\n\t\t}\n\t\tSadlValueList listInitializer = element.getListInitializer();\n\t\tif (listInitializer != null) {\n\t\t\tif(listInitializer.getExplicitValues().isEmpty()){\n\t\t\t\taddError(SadlErrorMessages.EMPTY_LIST_DEFINITION.get(), element);\n\t\t\t}else{\n\t\t\t\tif (cls == null) {\n\t\t\t\t\tConceptName cn = getTypedListType(inst);\n\t\t\t\t\tif (cn != null) {\n\t\t\t\t\t\tcls = getTheJenaModel().getOntClass(cn.toFQString());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (cls != null) {\n\t\t\t\t\taddListValues(inst, cls, listInitializer);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrow new JenaProcessorException(\"Unable to find type of list '\" + inst.toString() + \"'\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn inst;\n\t}\n\n\tprivate OWL_FLAVOR getOwlFlavor() {\n\t\treturn owlFlavor;\n\t}\n\t\n\tpublic ConceptName getTypedListType(RDFNode node) {\n\t\tif (node.isResource()) {\n\t\t\tStmtIterator sitr = theJenaModel.listStatements(node.asResource(), RDFS.subClassOf, (RDFNode)null);\n\t\t\twhile (sitr.hasNext()) {\n\t\t\t\tRDFNode supercls = sitr.nextStatement().getObject();\n\t\t\t\tif (supercls.isResource()) {\n\t\t\t\t\tif (supercls.asResource().hasProperty(OWL.onProperty, theJenaModel.getResource(SadlConstants.SADL_LIST_MODEL_FIRST_URI))) {\n\t\t\t\t\t\tStatement avfstmt = supercls.asResource().getProperty(OWL.allValuesFrom);\n\t\t\t\t\t\tif (avfstmt != null) {\n\t\t\t\t\t\t\tRDFNode type = avfstmt.getObject();\n\t\t\t\t\t\t\tif (type.isURIResource()) {\n\t\t\t\t\t\t\t\tConceptName cn = createTypedConceptName(type.asResource().getURI(), OntConceptType.CLASS);\n\t\t\t\t\t\t\t\tcn.setRangeValueType(RangeValueType.LIST);\n\t\t\t\t\t\t\t\tsitr.close();\n\t\t\t\t\t\t\t\treturn cn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// maybe it's an instance\n\t\t\tif (node.asResource().canAs(Individual.class)) {\n\t\t\t\tExtendedIterator itr = node.asResource().as(Individual.class).listRDFTypes(true);\n\t\t\t\twhile (itr.hasNext()) {\n\t\t\t\t\tcom.hp.hpl.jena.rdf.model.Resource r = itr.next();\n\t\t\t\t\tsitr = theJenaModel.listStatements(r, RDFS.subClassOf, (RDFNode)null);\n\t\t\t\t\twhile (sitr.hasNext()) {\n\t\t\t\t\t\tRDFNode supercls = sitr.nextStatement().getObject();\n\t\t\t\t\t\tif (supercls.isResource()) {\n\t\t\t\t\t\t\tif (supercls.asResource().hasProperty(OWL.onProperty, theJenaModel.getResource(SadlConstants.SADL_LIST_MODEL_FIRST_URI))) {\n\t\t\t\t\t\t\t\tStatement avfstmt = supercls.asResource().getProperty(OWL.allValuesFrom);\n\t\t\t\t\t\t\t\tif (avfstmt != null) {\n\t\t\t\t\t\t\t\t\tRDFNode type = avfstmt.getObject();\n\t\t\t\t\t\t\t\t\tif (type.isURIResource()) {\n\t\t\t\t\t\t\t\t\t\tConceptName cn = createTypedConceptName(type.asResource().getURI(), OntConceptType.CLASS);\n\t\t\t\t\t\t\t\t\t\tsitr.close();\n\t\t\t\t\t\t\t\t\t\treturn cn;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic ConceptName createTypedConceptName(String conceptUri, OntConceptType conceptType) {\n\t\tConceptName cn = new ConceptName(conceptUri);\n\t\tif (conceptType.equals(OntConceptType.CLASS)) {\n\t\t\tcn.setType(ConceptType.ONTCLASS);\n\t\t}\n\t\telse if (conceptType.equals(OntConceptType.ANNOTATION_PROPERTY)) {\n\t\t\tcn.setType(ConceptType.ANNOTATIONPROPERTY);\n\t\t}\n\t\telse if (conceptType.equals(OntConceptType.DATATYPE_PROPERTY)) {\n\t\t\tcn.setType(ConceptType.DATATYPEPROPERTY);\n\t\t}\n\t\telse if (conceptType.equals(OntConceptType.INSTANCE)) {\n\t\t\tcn.setType(ConceptType.INDIVIDUAL);\n\t\t}\n\t\telse if (conceptType.equals(OntConceptType.CLASS_PROPERTY)) {\n\t\t\tcn.setType(ConceptType.OBJECTPROPERTY);\n\t\t}\n\t\telse if (conceptType.equals(OntConceptType.DATATYPE)) {\n\t\t\tcn.setType(ConceptType.RDFDATATYPE);\n\t\t}\n\t\telse if (conceptType.equals(OntConceptType.RDF_PROPERTY)) {\n\t\t\tcn.setType(ConceptType.RDFPROPERTY);\n\t\t}\n\t\telse if (conceptType.equals(OntConceptType.VARIABLE)) {\n\t\t\tcn.setType(ConceptType.VARIABLE);\n\t\t}\n\t\telse if (conceptType.equals(OntConceptType.FUNCTION_DEFN)) {\n\t\t\tcn.setType(ConceptType.FUNCTION_DEFN);\n\t\t}\n\t\treturn cn;\n\t}\n\n\t\n\tprivate boolean typeRefIsList(SadlTypeReference type) throws JenaProcessorException {\n\t\tboolean isList = false;\n\t\tif (type instanceof SadlSimpleTypeReference) {\n\t\t\tisList = ((SadlSimpleTypeReference)type).isList();\n\t\t}\n\t\telse if (type instanceof SadlPrimitiveDataType) {\n\t\t\tisList = ((SadlPrimitiveDataType)type).isList();\n\t\t}\n\t\tif (isList) {\n\t\t\ttry {\n\t\t\t\timportSadlListModel(type.eResource());\n\t\t\t} catch (ConfigurationException e) {\n\t\t\t\tthrow new JenaProcessorException(\"Unable to load List model\", e);\n\t\t\t}\t\t\t\n\t\t}\n\t\treturn isList;\n\t}\n\t\n\tprivate void addListValues(Individual inst, OntClass cls, SadlValueList listInitializer) {\n\t\tcom.hp.hpl.jena.rdf.model.Resource to = null;\n\t\tExtendedIterator scitr = cls.listSuperClasses(true);\n\t\twhile (scitr.hasNext()) {\n\t\t\tOntClass sc = scitr.next(); \n\t\t\tif (sc.isRestriction() && ((sc.as(Restriction.class)).isAllValuesFromRestriction() && \n\t\t\t\t\tsc.as(AllValuesFromRestriction.class).onProperty(getTheJenaModel().getProperty(SadlConstants.SADL_LIST_MODEL_FIRST_URI)))) {\n\t\t\t\tto = sc.as(AllValuesFromRestriction.class).getAllValuesFrom();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (to == null) {\n//\t\t\taddError(\"No 'to' resource found in restriction of List subclass\", listInitializer);\n\t\t}\n\t\tIterator values = listInitializer.getExplicitValues().iterator();\n\t\taddValueToList(null, inst, cls, to, values);\n\t}\n\t\n\tprivate Individual addValueToList(Individual lastInst, Individual inst, OntClass cls, com.hp.hpl.jena.rdf.model.Resource type, \n\t\t\tIterator valueIterator) {\n\t\tif (inst == null) {\n\t\t\tinst = getTheJenaModel().createIndividual(cls);\n\t\t}\n\t\tSadlExplicitValue val = valueIterator.next();\n\t\tif (val instanceof SadlResource) {\n\t\t\tIndividual listInst;\n\t\t\ttry {\n\t\t\t\tif (type.canAs(OntClass.class)) { \n\t\t\t\t\tlistInst = createIndividual((SadlResource)val, type.as(OntClass.class));\n\t\t\t\t\tExtendedIterator itr = listInst.listRDFTypes(false);\n\t\t\t\t\tboolean match = false;\n\t\t\t\t\twhile (itr.hasNext()) {\n\t\t\t\t\t\tcom.hp.hpl.jena.rdf.model.Resource typ = itr.next();\n\t\t\t\t\t\tif (typ.equals(type)) {\n\t\t\t\t\t\t\tmatch = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!match) {\n\t\t\t\t\t\taddError(\"The Instance '\" + listInst.toString() + \"' doesn't match the List type.\", val);\n\t\t\t\t\t}\n\t\t\t\t\tgetTheJenaModel().add(inst, getTheJenaModel().getProperty(SadlConstants.SADL_LIST_MODEL_FIRST_URI), listInst);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\taddError(\"The type of the list could not be converted to a class.\", val);\n\t\t\t\t}\n\t\t\t} catch (JenaProcessorException e) {\n\t\t\t\taddError(e.getMessage(), val);\n\t\t\t} catch (TranslationException e) {\n\t\t\t\taddError(e.getMessage(), val);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tLiteral lval;\n\t\t\ttry {\n\t\t\t\tlval = sadlExplicitValueToLiteral((SadlExplicitValue)val, type);\n\t\t\t\tgetTheJenaModel().add(inst, getTheJenaModel().getProperty(SadlConstants.SADL_LIST_MODEL_FIRST_URI), lval);\n\t\t\t} catch (JenaProcessorException e) {\n\t\t\t\taddError(e.getMessage(), val);\n\t\t\t}\n\t\t}\n\t\tif (valueIterator.hasNext()) {\n\t\t\tIndividual rest = addValueToList(inst, null, cls, type, valueIterator);\n\t\t\tgetTheJenaModel().add(inst, getTheJenaModel().getProperty(SadlConstants.SADL_LIST_MODEL_REST_URI), rest);\n\t\t}\n\t\treturn inst;\n\t}\n\t\n\tprivate void assignInstancePropertyValue(Individual inst, OntClass cls, SadlResource prop, EObject val) throws JenaProcessorException, CircularDefinitionException {\n\t\tOntConceptType type;\n\t\ttry {\n\t\t\ttype = getDeclarationExtensions().getOntConceptType(prop);\n\t\t} catch (CircularDefinitionException e) {\n\t\t\ttype = e.getDefinitionType();\n\t\t\taddError(e.getMessage(), prop);\n\t\t}\n\t\tString propuri = getDeclarationExtensions().getConceptUri(prop);\n\t\tif (type.equals(OntConceptType.CLASS_PROPERTY)) {\n\t\t\tOntProperty oprop = getTheJenaModel().getOntProperty(propuri);\n\t\t\tif (oprop == null) {\n\t\t\t\taddError(SadlErrorMessages.PROPERTY_NOT_EXIST.get(propuri), prop);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (val instanceof SadlInstance) {\n\t\t\t\t\tIndividual instval = processSadlInstance((SadlInstance) val);\n\t\t\t\t\tOntClass uQCls = getTheJenaModel().getOntClass(SadlConstants.SADL_IMPLICIT_MODEL_UNITTEDQUANTITY_URI);\n\t\t\t\t\tif (uQCls != null && instval.hasRDFType(uQCls) && ignoreUnittedQuantities) {\n\t\t\t\t\t\tif (val instanceof SadlNestedInstance) {\n\t\t\t\t\t\t\tIterator propinititr = ((SadlNestedInstance)val).getPropertyInitializers().iterator();\n\t\t\t\t\t\t\twhile (propinititr.hasNext()) {\n\t\t\t\t\t\t\t\tEObject pval = propinititr.next().getValue();\n\t\t\t\t\t\t\t\tif (pval instanceof SadlNumberLiteral) {\n\t\t\t\t\t\t\t\t\tcom.hp.hpl.jena.rdf.model.Resource effectiveRng = getUnittedQuantityValueRange();\n\t\t\t\t\t\t\t\t\tLiteral lval = sadlExplicitValueToLiteral((SadlNumberLiteral)pval, effectiveRng);\n\t\t\t\t\t\t\t\t\tif (lval != null) {\n\t\t\t\t\t\t\t\t\t\taddInstancePropertyValue(inst, oprop, lval, val);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\taddInstancePropertyValue(inst, oprop, instval, val);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (val instanceof SadlResource) {\n\t\t\t\t\tString uri = getDeclarationExtensions().getConceptUri((SadlResource) val);\n\t\t\t\t\tcom.hp.hpl.jena.rdf.model.Resource rsrc = getTheJenaModel().getResource(uri);\n\t\t\t\t\tif (rsrc.canAs(Individual.class)){\n\t\t\t\t\t\taddInstancePropertyValue(inst, oprop, rsrc.as(Individual.class), val);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tthrow new JenaProcessorException(\"unhandled value type SadlResource that isn't an instance (URI is '\" + uri + \"')\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (val instanceof SadlExplicitValue) {\n\t\t\t\t\tOntResource rng = oprop.getRange();\n\t\t\t\t\tif (val instanceof SadlNumberLiteral && ((SadlNumberLiteral)val).getUnit() != null) {\n\t\t\t\t\t\tif (!ignoreUnittedQuantities) {\n\t\t\t\t\t\t\tString unit = ((SadlNumberLiteral)val).getUnit();\n\t\t\t\t\t\t\tif (rng != null) {\n\t\t\t\t\t\t\t\tif (rng.canAs(OntClass.class) \n\t\t\t\t\t\t\t\t\t\t&& checkForSubclassing(rng.as(OntClass.class), \n\t\t\t\t\t\t\t\t\t\t\t\tgetTheJenaModel().getOntClass(SadlConstants.SADL_IMPLICIT_MODEL_UNITTEDQUANTITY_URI), val)) {\n\t\t\t\t\t\t\t\t\taddUnittedQuantityAsInstancePropertyValue(inst, oprop, rng, ((SadlNumberLiteral)val).getLiteralNumber(), unit);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\taddError(SadlErrorMessages.UNITTED_QUANTITY_ERROR.toString(), val);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\taddUnittedQuantityAsInstancePropertyValue(inst, oprop, rng, ((SadlNumberLiteral)val).getLiteralNumber(), unit);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tcom.hp.hpl.jena.rdf.model.Resource effectiveRng = getUnittedQuantityValueRange();\n\t\t\t\t\t\t\tLiteral lval = sadlExplicitValueToLiteral((SadlExplicitValue)val, effectiveRng);\n\t\t\t\t\t\t\tif (lval != null) {\n\t\t\t\t\t\t\t\taddInstancePropertyValue(inst, oprop, lval, val);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tif (rng == null) {\n\t\t\t\t\t\t\t// this isn't really an ObjectProperty--should probably be an rdf:Property\n\t\t\t\t\t\t\tLiteral lval = sadlExplicitValueToLiteral((SadlExplicitValue)val, null);\n\t\t\t\t\t\t\taddInstancePropertyValue(inst, oprop, lval, val);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\taddError(\"A SadlExplicitValue is given to an an ObjectProperty\", val);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (val instanceof SadlValueList) {\n//\t\t\t\t\tEList vals = ((SadlValueList)val).getExplicitValues();\n\t\t\t\t\taddListValues(inst, cls, (SadlValueList) val);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrow new JenaProcessorException(\"unhandled value type for object property\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if (type.equals(OntConceptType.DATATYPE_PROPERTY)) {\n\t\t\tDatatypeProperty dprop = getTheJenaModel().getDatatypeProperty(propuri);\n\t\t\tif (dprop == null) {\n//\t\t\t\tdumpModel(getTheJenaModel());\n\t\t\t\taddError(SadlErrorMessages.PROPERTY_NOT_EXIST.get(propuri), prop);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (val instanceof SadlValueList) {\n//\t\t\t\t\tEList vals = ((SadlValueList)val).getExplicitValues();\n\t\t\t\t\taddListValues(inst, cls, (SadlValueList) val);\n\t\t\t\t}\n\t\t\t\telse if (val instanceof SadlExplicitValue) {\n\t\t\t\t\tLiteral lval = sadlExplicitValueToLiteral((SadlExplicitValue)val, dprop.getRange());\n\t\t\t\t\tif (lval != null) {\n\t\t\t\t\t\taddInstancePropertyValue(inst, dprop, lval, val);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrow new JenaProcessorException(\"unhandled value type for data property\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if (type.equals(OntConceptType.ANNOTATION_PROPERTY)) {\n\t\t\tAnnotationProperty annprop = getTheJenaModel().getAnnotationProperty(propuri);\n\t\t\tif (annprop == null) {\n\t\t\t\taddError(SadlErrorMessages.PROPERTY_NOT_EXIST.get(propuri), prop);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tRDFNode rsrcval;\n\t\t\t\tif (val instanceof SadlResource) {\n\t\t\t\t\tString uri = getDeclarationExtensions().getConceptUri((SadlResource) val);\n\t\t\t\t\t rsrcval = getTheJenaModel().getResource(uri);\n\t\t\t\t}\n\t\t\t\telse if (val instanceof SadlInstance) {\n\t\t\t\t\trsrcval = processSadlInstance((SadlInstance) val);\n\t\t\t\t}\n\t\t\t\telse if (val instanceof SadlExplicitValue) {\n\t\t\t\t\trsrcval = sadlExplicitValueToLiteral((SadlExplicitValue)val, null);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrow new JenaProcessorException(SadlErrorMessages.UNHANDLED.get(val.getClass().getCanonicalName(), \"unable to handle annotation value\"));\n\t\t\t\t}\n\t\t\t\taddInstancePropertyValue(inst, annprop, rsrcval, val);\n\t\t\t}\n\t\t}\n\t\telse if (type.equals(OntConceptType.RDF_PROPERTY)) {\n\t\t\tProperty rdfprop = getTheJenaModel().getProperty(propuri);\n\t\t\tif (rdfprop == null) {\n\t\t\t\taddError(SadlErrorMessages.PROPERTY_NOT_EXIST.get(propuri), prop);\n\t\t\t}\n\t\t\tRDFNode rsrcval;\n\t\t\tif (val instanceof SadlResource) {\n\t\t\t\tString uri = getDeclarationExtensions().getConceptUri((SadlResource) val);\n\t\t\t\t rsrcval = getTheJenaModel().getResource(uri);\n\t\t\t}\n\t\t\telse if (val instanceof SadlInstance) {\n\t\t\t\trsrcval = processSadlInstance((SadlInstance) val);\n\t\t\t}\n\t\t\telse if (val instanceof SadlExplicitValue) {\n\t\t\t\trsrcval = sadlExplicitValueToLiteral((SadlExplicitValue)val, null);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthrow new JenaProcessorException(\"unable to handle rdf property value of type '\" + val.getClass().getCanonicalName() + \"')\");\n\t\t\t}\n\t\t\taddInstancePropertyValue(inst, rdfprop, rsrcval, val);\n\t\t}\n\t\telse if (type.equals(OntConceptType.VARIABLE)) {\n\t\t\t// a variable for a property type is only valid in a rule or query.\n\t\t\tif (getTarget() == null || getTarget() instanceof Test) {\n\t\t\t\taddError(\"Variable can be used for property only in queries and rules\", val);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tthrow new JenaProcessorException(\"unhandled property type\");\n\t\t}\n\t}\n\tprivate com.hp.hpl.jena.rdf.model.Resource getUnittedQuantityValueRange() {\n\t\tcom.hp.hpl.jena.rdf.model.Resource effectiveRng = getTheJenaModel().getOntProperty(SadlConstants.SADL_IMPLICIT_MODEL_VALUE_URI).getRange();\n\t\tif (effectiveRng == null) {\n\t\t\teffectiveRng = XSD.decimal;\n\t\t}\n\t\treturn effectiveRng;\n\t}\n\t\n\tprivate void addInstancePropertyValue(Individual inst, Property prop, RDFNode value, EObject ctx) {\n\t\tif (prop.getURI().equals(SadlConstants.SADL_IMPLICIT_MODEL_IMPLIED_PROPERTY_URI)) {\n\t\t\t// check for ambiguity through duplication of property range\n\t\t\tif (value.canAs(OntProperty.class)){ \n\t\t\t\tNodeIterator ipvs = inst.listPropertyValues(prop);\n\t\t\t\tif (ipvs.hasNext()) {\n\t\t\t\t\tList valueRngLst = new ArrayList();\n\t\t\t\t\tExtendedIterator vitr = value.as(OntProperty.class).listRange();\n\t\t\t\t\twhile (vitr.hasNext()) {\n\t\t\t\t\t\tvalueRngLst.add(vitr.next());\n\t\t\t\t\t}\n\t\t\t\t\tvitr.close();\n\t\t\t\t\tboolean overlap = false;\n\t\t\t\t\twhile (ipvs.hasNext()) {\n\t\t\t\t\t\tRDFNode ipv = ipvs.next();\n\t\t\t\t\t\tif (ipv.canAs(OntProperty.class)){\n\t\t\t\t\t\t\tExtendedIterator ipvitr = ipv.as(OntProperty.class).listRange();\n\t\t\t\t\t\t\twhile (ipvitr.hasNext()) {\n\t\t\t\t\t\t\t\tOntResource ipvr = ipvitr.next();\n\t\t\t\t\t\t\t\tif (valueRngLst.contains(ipvr)) {\n\t\t\t\t\t\t\t\t\taddError(\"Ambiguous condition--multiple implied properties (\" + \n\t\t\t\t\t\t\t\t\t\t\tvalue.as(OntProperty.class).getLocalName() + \",\" + ipv.as(OntProperty.class).getLocalName() + \n\t\t\t\t\t\t\t\t\t\t\t\") have the same range (\" + ipvr.getLocalName() + \")\", ctx);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\taddImpliedPropertyClass(inst);\n\t\t}\n\t\tinst.addProperty(prop, value);\n\t\tlogger.debug(\"added value '\" + value.toString() + \"' to property '\" + prop.toString() + \"' for instance '\" + inst.toString() + \"'\");\n\t}\n\n\tprivate void addUnittedQuantityAsInstancePropertyValue(Individual inst, OntProperty oprop, OntResource rng, BigDecimal number, String unit) {\n\t\taddUnittedQuantityAsInstancePropertyValue(inst, oprop, rng, number.toPlainString(), unit);\n\t}\n\n\tprivate void addImpliedPropertyClass(Individual inst) {\n\t\tif(!allImpliedPropertyClasses.contains(inst)) {\n\t\t\tallImpliedPropertyClasses.add(inst);\n\t\t}\n\t}\n\t\n\tprivate void addUnittedQuantityAsInstancePropertyValue(Individual inst, OntProperty oprop, OntResource rng, String literalNumber, String unit) {\n\t\tIndividual unittedVal;\n\t\tif (rng != null && rng.canAs(OntClass.class)) {\n\t\t\tunittedVal = getTheJenaModel().createIndividual(rng.as(OntClass.class));\n\t\t}\n\t\telse {\n\t\t\tunittedVal = getTheJenaModel().createIndividual(getTheJenaModel().getOntClass(SadlConstants.SADL_IMPLICIT_MODEL_UNITTEDQUANTITY_URI));\n\t\t}\n\t\t// TODO this may need to check for property restrictions on a subclass of UnittedQuantity\n\t\tunittedVal.addProperty(getTheJenaModel().getProperty(SadlConstants.SADL_IMPLICIT_MODEL_VALUE_URI), getTheJenaModel().createTypedLiteral(literalNumber));\n\t\tunittedVal.addProperty(getTheJenaModel().getProperty(SadlConstants.SADL_IMPLICIT_MODEL_UNIT_URI), getTheJenaModel().createTypedLiteral(unit));\n\t\tinst.addProperty(oprop, unittedVal);\n\t}\n\t\n\tprivate void dumpModel(OntModel m) {\n\t\tSystem.out.println(\"Dumping OntModel\");\n\t\tPrintStream strm = System.out;\n\t\tm.write(strm);\n\t\tExtendedIterator itr = m.listSubModels();\n\t\twhile (itr.hasNext()) {\n\t\t\tdumpModel(itr.next());\n\t\t}\n\t}\n\t\n\tprivate SadlResource sadlResourceFromSadlInstance(SadlInstance element) throws JenaProcessorException {\n\t\tSadlResource sr = element.getNameOrRef();\n\t\tif (sr == null) {\n\t\t\tsr = element.getInstance();\n\t\t}\n\t\treturn sr;\n\t}\n\n\tprivate void processSadlDisjointClasses(SadlDisjointClasses element) throws JenaProcessorException {\n\t\tList disjointClses = new ArrayList();\n\t\tif (element.getClasses() != null) {\n\t\t\tIterator dcitr = element.getClasses().iterator();\n\t\t\twhile (dcitr.hasNext()) {\n\t\t\t\tSadlResource sr = dcitr.next();\n\t\t\t\tString declUri = getDeclarationExtensions().getConceptUri(sr);\n\t\t\t\tif (declUri == null) {\n\t\t\t\t\tthrow new JenaProcessorException(\"Failed to get concept URI of SadlResource in processSadlDisjointClasses\");\n\t\t\t\t}\n\t\t\t\tOntClass cls = getTheJenaModel().getOntClass(declUri);\n\t\t\t\tif (cls == null) {\n\t\t\t\t\tthrow new JenaProcessorException(\"Failed to get class '\" + declUri + \"' from Jena model.\");\n\t\t\t\t}\n\t\t\t\tdisjointClses.add(cls.asClass());\n\t\t\t}\n\t\t}\n\t\tIterator dcitr = element.getTypes().iterator();\n\t\twhile(dcitr.hasNext()) {\n\t\t\tSadlClassOrPropertyDeclaration decl = dcitr.next();\n\t\t\tIterator djitr = decl.getClassOrProperty().iterator();\n\t\t\twhile (djitr.hasNext()) {\n\t\t\t\tSadlResource sr = djitr.next();\n\t\t\t\tString declUri = getDeclarationExtensions().getConceptUri(sr);\n\t\t\t\tif (declUri == null) {\n\t\t\t\t\tthrow new JenaProcessorException(\"Failed to get concept URI of SadlResource in processSadlDisjointClasses\");\n\t\t\t\t}\n\t\t\t\tOntClass cls = getTheJenaModel().getOntClass(declUri);\n\t\t\t\tdisjointClses.add(cls.asClass());\n\t\t\t}\n\t\t}\n\t\t// must set them disjoint pairwise\n\t\tfor (int i = 0; i < disjointClses.size(); i++) {\n\t\t\tfor (int j = i + 1; j < disjointClses.size(); j++) {\n\t\t\t\tdisjointClses.get(i).addDisjointWith(disjointClses.get(j));\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate ObjectProperty getOrCreateObjectProperty(String propName) {\n\t\tObjectProperty prop = getTheJenaModel().getObjectProperty(propName);\n\t\tif (prop == null) {\n\t\t\tprop = getTheJenaModel().createObjectProperty(propName);\n\t\t\tlogger.debug(\"New object property '\" + prop.getURI() + \"' created\");\n\t\t}\n\t\treturn prop;\n\t}\n\n\tprivate DatatypeProperty getOrCreateDatatypeProperty(String propUri) throws JenaProcessorException {\n\t\tDatatypeProperty prop = getTheJenaModel().getDatatypeProperty(propUri);\n\t\tif (prop == null) {\n\t\t\tprop = createDatatypeProperty(propUri, null);\n\t\t}\n\t\treturn prop;\n\t}\n\t\n\tprivate OntProperty getOrCreateRdfProperty(String propUri) {\n\t\tProperty op = getTheJenaModel().getProperty(propUri);\n\t\tif (op != null && op.canAs(OntProperty.class)) {\n\t\t\treturn op.as(OntProperty.class);\n\t\t}\n\t\treturn createRdfProperty(propUri, null);\n\t}\n\n\tprivate boolean checkForExistingCompatibleDatatypeProperty(\n\t\t\tString propUri, RDFNode rngNode) {\n\t\tDatatypeProperty prop = getTheJenaModel().getDatatypeProperty(propUri);\n\t\tif (prop != null) {\n\t\t\tOntResource rng = prop.getRange();\n\t\t\tif (rng != null && rng.equals(rngNode)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate void addPropertyDomain(Property prop, OntResource cls, EObject context) throws JenaProcessorException {\n\t\tboolean addNewDomain = true;\n\t\tStmtIterator sitr = getTheJenaModel().listStatements(prop, RDFS.domain, (RDFNode)null);\n\t\tboolean domainExists = false;\n\t\tif (sitr.hasNext()) {\n\t\t\tRDFNode existingDomain = sitr.next().getObject();\n\t\t\tdomainExists = true;\n\t\t\t// property already has a domain known to this model\n\t\t\tif (cls.equals(existingDomain)) {\n\t\t\t\t// do nothing--cls is already in domain\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\tif (existingDomain.canAs(OntClass.class)) {\n\t\t\t\t// is the new domain a subclass of the existing domain?\n\t\t\t\tif (cls.canAs(OntClass.class) && checkForSubclassing(cls.as(OntClass.class), existingDomain.as(OntClass.class), context) ) {\n\t\t\t\t\tStringBuilder sb = new StringBuilder(\"This specified domain of '\");\n\t\t\t\t\tsb.append(nodeToString(prop));\n\t\t\t\t\tsb.append(\"' is a subclass of the domain which is already defined\");\n\t\t\t\t\tString dmnstr = nodeToString(existingDomain);\n\t\t\t\t\tif (dmnstr != null) {\n\t\t\t\t\t\tsb.append(\" (\");\n\t\t\t\t\t\tsb.append(dmnstr);\n\t\t\t\t\t\tsb.append(\") \");\n\t\t\t\t\t}\n\t\t\t\t\taddWarning(sb.toString(), context);\t\t\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tboolean domainInThisModel = false;\n\t\t\tStmtIterator inModelStmtItr = getTheJenaModel().getBaseModel().listStatements(prop, RDFS.domain, (RDFNode)null);\n\t\t\tif (inModelStmtItr.hasNext()) {\n\t\t\t\tdomainInThisModel = true;\n\t\t\t}\n\t\t\tif (domainAndRangeAsUnionClasses) {\n\t\t\t\t// in this case we want to create a union class if necessary\n\t\t\t\tif (domainInThisModel) {\n\t\t\t\t\t// this model (as opposed to imports) already has a domain specified\n\t\t\t\t\taddNewDomain = false;\n\t\t\t\t\tUnionClass newUnionClass = null;\n\t\t\t\t\twhile (inModelStmtItr.hasNext()) {\n\t\t\t\t\t\tRDFNode dmn = inModelStmtItr.nextStatement().getObject();\n\t\t\t\t\t\tif (dmn.isResource()) {\t// should always be a Resource\n\t\t\t\t\t\t\tif (dmn.canAs(OntResource.class)){\n\t\t\t\t\t\t\t\tif (existingDomain.toString().equals(dmn.toString())) {\n\t\t\t\t\t\t\t\t\tdmn = existingDomain;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tnewUnionClass = createUnionClass(dmn.as(OntResource.class), cls);\n\t\t\t\t\t\t\t\tlogger.debug(\"Domain '\" + cls.toString() + \"' added to property '\" + prop.getURI() + \"'\");\n\t\t\t\t\t\t\t\tif (!newUnionClass.equals(dmn)) {\n\t\t\t\t\t\t\t\t\taddNewDomain = true;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tthrow new JenaProcessorException(\"Encountered non-OntResource in domain of '\" + prop.getURI() + \"'\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tthrow new JenaProcessorException(\"Encountered non-Resource in domain of '\" + prop.getURI() + \"'\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (addNewDomain) {\n\t\t\t\t\t\tgetTheJenaModel().remove(getTheJenaModel().getBaseModel().listStatements(prop, RDFS.domain, (RDFNode)null));\n\t\t\t\t\t\tcls = newUnionClass;\n\t\t\t\t\t}\n\t\t\t\t}\t// end if existing domain in this model\n\t\t\t\telse {\n\t\t\t\t\tinModelStmtItr.close();\n\t\t\t\t\t// check to see if this is something new\n\t\t\t\t\tdo {\n\t\t\t\t\t\tif (existingDomain.equals(cls)) {\n\t\t\t\t\t\t\tsitr.close();\n\t\t\t\t\t\t\treturn;\t// already in domain, nothing to add\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (sitr.hasNext()) {\n\t\t\t\t\t\t\texistingDomain = sitr.next().getObject();\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\texistingDomain = null;\n\t\t\t\t\t\t}\n\t\t\t\t\t} while (existingDomain != null);\n\t\t\t\t}\n\t\t\t}\t// end if domainAndRangeAsUnionClasses\n\t\t\telse {\n\t\t\t\tinModelStmtItr.close();\n\t\t\t}\n\t\t\tif (domainExists && !domainInThisModel) {\n\t\t\t\taddWarning(SadlErrorMessages.IMPORTED_DOMAIN_CHANGE.get(nodeToString(prop)), context);\n\t\t\t}\n\t\t}\t// end if existing domain in any model, this or imports\n\t\tif(cls != null){\n\t\t\tif (!domainAndRangeAsUnionClasses && cls instanceof UnionClass) {\n\t\t\t\tList uclsmembers = getUnionClassMemebers((UnionClass)cls);\n\t\t\t\tfor (int i = 0; i < uclsmembers.size(); i++) {\n\t\t\t\t\tgetTheJenaModel().add(prop, RDFS.domain, uclsmembers.get(i));\n\t\t\t\t\tlogger.debug(\"Domain '\" + uclsmembers.get(i).toString() + \"' added to property '\" + prop.getURI() + \"'\");\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (addNewDomain) {\n\t\t\t\tgetTheJenaModel().add(prop, RDFS.domain, cls);\t\n\t\t\t\tlogger.debug(\"Domain '\" + cls.toString() + \"' added to property '\" + prop.getURI() + \"'\");\n\t\t\t\tlogger.debug(\"Domain of '\" + prop.toString() + \"' is now: \" + nodeToString(cls));\n\t\t\t}\n\t\t}else{\n\t\t\tlogger.debug(\"Domain is not defined for property '\" + prop.toString() + \"'\");\n\t\t}\n\t}\n\n\tprivate List getUnionClassMemebers(UnionClass cls) {\n\t\tList members = null;\n\t\tExtendedIterator itr = ((UnionClass)cls).listOperands();\n\t\twhile (itr.hasNext()) {\n\t\t\tcom.hp.hpl.jena.rdf.model.Resource ucls = itr.next();\n\t\t\tif (ucls instanceof UnionClass || ucls.canAs(UnionClass.class)) {\n\t\t\t\tList nested = getUnionClassMemebers(ucls.as(UnionClass.class));\n\t\t\t\tif (members == null) {\n\t\t\t\t\tmembers = nested;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tmembers.addAll(nested);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (members == null) members = new ArrayList();\n\t\t\t\tmembers.add(ucls);\n\t\t\t}\n\t\t}\n\t\tif (cls.isAnon()) {\n\t\t\tfor (int i = 0; i < members.size(); i++) {\n\t\t\t\t((UnionClass)cls).removeOperand(members.get(i));\n\t\t\t}\n\t\t\tgetTheJenaModel().removeAll(cls, null, null);\n\t\t\tgetTheJenaModel().removeAll(null, null, cls);\n\t\t\tcls.remove();\n\t\t}\n\t\treturn members;\n\t}\n\t\n\tprivate OntResource createUnionOfClasses(OntResource cls, List existingClasses) throws JenaProcessorException {\n\t\tOntResource unionClass = null;\n\t\tRDFList classes = null;\n\t\tIterator ecitr = existingClasses.iterator();\n\t\tboolean allEqual = true;\n\t\twhile (ecitr.hasNext()) {\n\t\t\tOntResource existingCls = ecitr.next();\n\t\t\tif (!existingCls.canAs(OntResource.class)){\n\t\t\t\tthrow new JenaProcessorException(\"Unable to convert '\" + existingCls.toString() + \"' to OntResource to put into union of classes\");\n\t\t\t}\n\t\t\tif (existingCls.equals(cls)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tallEqual = false;\n\t\t\t}\n\t\t\tif (existingCls.as(OntResource.class).canAs(UnionClass.class)) {\n\t\t\t\tList uclist = getOntResourcesInUnionClass(getTheJenaModel(), existingCls.as(UnionClass.class));\n\t\t\t\tif (classes == null) {\n\t\t\t\t\tclasses = getTheJenaModel().createList();\n\t\t\t\t\tclasses = classes.with(cls);\n\t\t\t\t}\n\t\t\t\tfor (int i = 0; i < uclist.size(); i++) {\n\t\t\t\t\tclasses = classes.with(uclist.get(i));\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (classes == null) {\n\t\t\t\t\tclasses = getTheJenaModel().createList();\n\t\t\t\t\tclasses = classes.with(cls);\n\t\t\t\t}\n\t\t\t\tclasses = classes.with(existingCls.as(OntResource.class));\n\t\t\t}\n\t\t}\n\t\tif (allEqual) {\n\t\t\treturn cls;\n\t\t}\n\t\tif (classes != null) {\n\t\t\tunionClass = getTheJenaModel().createUnionClass(null, classes);\n\t\t}\n\t\treturn unionClass;\n\t}\n\t\n\tprivate OntResource createUnionOfClasses(OntResource cls, ExtendedIterator ditr) throws JenaProcessorException {\n\t\tOntResource unionClass = null;\n\t\tRDFList classes = null;\n\t\tboolean allEqual = true;\n\t\twhile (ditr.hasNext()) {\n\t\t\tOntResource existingCls = ditr.next();\n\t\t\tif (!existingCls.canAs(OntResource.class)){\n\t\t\t\tthrow new JenaProcessorException(\"Unable to '\" + existingCls.toString() + \"' to OntResource to put into union of classes\");\n\t\t\t}\n\t\t\tif (existingCls.equals(cls)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tallEqual = false;\n\t\t\t}\n\t\t\tif (existingCls.as(OntResource.class).canAs(UnionClass.class)) {\n\t\t\t\tif (classes != null) {\n\t\t\t\t\tclasses.append(existingCls.as(UnionClass.class).getOperands());\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\ttry {\n\t\t\t\t\t\texistingCls.as(UnionClass.class).addOperand(cls);\n\t\t\t\t\t\tunionClass = existingCls.as(UnionClass.class);\n\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\t// don't know why this is happening\n\t\t\t\t\t\tlogger.error(\"Union class error that hasn't been resolved or understood.\");\t\t\t\t\t\n\t\t\t\t\t\treturn cls;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (classes == null) {\n\t\t\t\t\tclasses = getTheJenaModel().createList();\n\t\t\t\t}\n\t\t\t\tclasses = classes.with(existingCls.as(OntResource.class));\n\t\t\t\tclasses = classes.with(cls);\n\t\t\t}\n\t\t}\n\t\tif (allEqual) {\n\t\t\treturn cls;\n\t\t}\n\t\tif (classes != null) {\n\t\t\tunionClass = getTheJenaModel().createUnionClass(null, classes);\n\t\t}\n\t\treturn unionClass;\n\t}\n\t\n\tprivate RDFNode primitiveDatatypeToRDFNode(String name) {\n\t\treturn getTheJenaModel().getResource(XSD.getURI() + name);\n\t}\n\n\tprivate OntClass getOrCreateOntClass(String name) {\n\t\tOntClass cls = getTheJenaModel().getOntClass(name);\n\t\tif (cls == null) {\n\t\t\tcls = createOntClass(name, (OntClass)null);\n\t\t}\n\t\treturn cls;\n\t}\n\t\n\tprivate OntClass createOntClass(String newName, String superSRUri, EObject superSR) {\n\t\tif (superSRUri != null) {\n\t\t\tOntClass superCls = getTheJenaModel().getOntClass(superSRUri);\n\t\t\tif (superCls == null) {\n\t\t\t\tsuperCls = getTheJenaModel().createClass(superSRUri);\n\t\t\t}\n\t\t\treturn createOntClass(newName, superCls);\n\t\t}\n\t\treturn createOntClass(newName, (OntClass)null);\n\t}\n\t\n\tprivate OntClass createOntClass(String newName, OntClass superCls) {\n\t\tOntClass newCls = getTheJenaModel().createClass(newName);\n\t\tlogger.debug(\"New class '\" + newCls.getURI() + \"' created\");\n\t\tif (superCls != null) {\n\t\t\tnewCls.addSuperClass(superCls);\n\t\t\tlogger.debug(\" Class '\" + newCls.getURI() + \"' given super class '\" + superCls.toString() + \"'\");\n\t\t}\n\t\treturn newCls;\n\t}\n\t\n\tprivate OntClass getOrCreateListSubclass(String newName, String typeUri, Resource resource) throws JenaProcessorException {\n\t\tif (sadlListModel == null) {\n\t\t\ttry {\n\t\t\t\timportSadlListModel(resource);\n\t\t\t} catch (Exception e) {\n\t\t\t\te.printStackTrace();\n\t\t\t\tthrow new JenaProcessorException(\"Failed to load SADL List model\", e);\n\t\t\t}\n\t\t}\n\t\tOntClass lstcls = getTheJenaModel().getOntClass(SadlConstants.SADL_LIST_MODEL_LIST_URI);\n\t\tExtendedIterator lscitr = lstcls.listSubClasses();\n\t\twhile (lscitr.hasNext()) {\n\t\t\tOntClass scls = lscitr.next();\n\t\t\tif (newName != null && scls.isURIResource() && newName.equals(scls.getURI())) {\n\t\t\t\t// same class\n\t\t\t\treturn scls;\n\t\t\t}\n\t\t\tif (newName == null && scls.isAnon()) {\n\t\t\t\t// both are unnamed, check type (and length restrictions in future)\n\t\t\t\tExtendedIterator spcitr = scls.listSuperClasses(true);\n\t\t\t\twhile (spcitr.hasNext()) {\n\t\t\t\t\tOntClass spcls = spcitr.next();\n\t\t\t\t\tif (spcls.isRestriction() && spcls.asRestriction().isAllValuesFromRestriction()) {\n\t\t\t\t\t\tOntProperty onprop = spcls.asRestriction().getOnProperty();\n\t\t\t\t\t\tif (onprop.isURIResource() && onprop.getURI().equals(SadlConstants.SADL_LIST_MODEL_FIRST_URI)) {\n\t\t\t\t\t\t\tcom.hp.hpl.jena.rdf.model.Resource avf = spcls.asRestriction().asAllValuesFromRestriction().getAllValuesFrom();\n\t\t\t\t\t\t\tif (avf.isURIResource() && avf.getURI().equals(typeUri)) {\n\t\t\t\t\t\t\t\tspcitr.close();\n\t\t\t\t\t\t\t\tlscitr.close();\n\t\t\t\t\t\t\t\treturn scls;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tOntClass newcls = createOntClass(newName, lstcls);\n\t\tcom.hp.hpl.jena.rdf.model.Resource typeResource = getTheJenaModel().getResource(typeUri);\n\t\tProperty pfirst = getTheJenaModel().getProperty(SadlConstants.SADL_LIST_MODEL_FIRST_URI);\n\t\tAllValuesFromRestriction avf = getTheJenaModel().createAllValuesFromRestriction(null, pfirst, typeResource);\n\t\tnewcls.addSuperClass(avf);\n\t\tProperty prest = getTheJenaModel().getProperty(SadlConstants.SADL_LIST_MODEL_REST_URI);\n\t\tAllValuesFromRestriction avf2 = getTheJenaModel().createAllValuesFromRestriction(null, prest, newcls);\n\t\tnewcls.addSuperClass(avf2);\n\t\treturn newcls;\n\t}\n\t\n\tprivate OntProperty createObjectProperty(String newName, String superSRUri) throws JenaProcessorException {\n\t\tOntProperty newProp = getTheJenaModel().createObjectProperty(newName);\n\t\tlogger.debug(\"New object property '\" + newProp.getURI() + \"' created\");\n\t\tif (superSRUri != null) {\n\t\t\tOntProperty superProp = getTheJenaModel().getOntProperty(superSRUri);\n\t\t\tif (superProp == null) {\n//\t\t\t\tthrow new JenaProcessorException(\"Unable to find super property '\" + superSRUri + \"'\");\n\t\t\t\tgetTheJenaModel().createObjectProperty(superSRUri);\n\t\t\t}\n\t\t\tnewProp.addSuperProperty(superProp);\n\t\t\tlogger.debug(\" Object property '\" + newProp.getURI() + \"' given super property '\" + superSRUri + \"'\");\n\t\t}\n\t\treturn newProp;\n\t}\n\t\n\tprivate AnnotationProperty createAnnotationProperty(String newName, String superSRUri) {\n\t\tAnnotationProperty annProp = getTheJenaModel().createAnnotationProperty(newName);\n\t\tlogger.debug(\"New annotation property '\" + annProp.getURI() + \"' created\");\n\t\tif (superSRUri != null) {\n\t\t\tProperty superProp = getTheJenaModel().getProperty(superSRUri);\n\t\t\tif (superProp == null) {\n\t\t\t\tsuperProp = getTheJenaModel().createOntProperty(superSRUri);\n\t\t\t}\n\t\t\tgetTheJenaModel().add(annProp, RDFS.subPropertyOf, superProp);\n\t\t\tlogger.debug(\" Property '\" + annProp.getURI() + \"' given super property '\" + superSRUri + \"'\");\n\t\t}\n\t\treturn annProp;\n\t}\n\t\n\tprivate OntProperty createRdfProperty(String newName, String superSRUri) {\n\t\tOntProperty newProp = getTheJenaModel().createOntProperty(newName);\n\t\tlogger.debug(\"New object property '\" + newProp.getURI() + \"' created\");\n\t\tif (superSRUri != null) {\n\t\t\tProperty superProp = getTheJenaModel().getProperty(superSRUri);\n\t\t\tif (superProp == null) {\n\t\t\t\tsuperProp = getTheJenaModel().createOntProperty(superSRUri);\n\t\t\t}\n\t\t\tgetTheJenaModel().add(newProp, RDFS.subPropertyOf, superProp);\n\t\t\tlogger.debug(\" Property '\" + newProp.getURI() + \"' given super property '\" + superSRUri + \"'\");\n\t\t}\n\t\treturn newProp;\n\t}\n\t\n\tprivate DatatypeProperty createDatatypeProperty(String newName, String superSRUri) throws JenaProcessorException {\n\t\tDatatypeProperty newProp = getTheJenaModel().createDatatypeProperty(newName);\n\t\tlogger.debug(\"New datatype property '\" + newProp.getURI() + \"' created\");\n\t\tif (superSRUri != null) {\n\t\t\tOntProperty superProp = getTheJenaModel().getOntProperty(superSRUri);\n\t\t\tif (superProp == null) {\n//\t\t\t\tthrow new JenaProcessorException(\"Unable to find super property '\" + superSRUri + \"'\");\n\t\t\t\tif (superProp == null) {\n\t\t\t\t\tgetTheJenaModel().createDatatypeProperty(superSRUri);\n\t\t\t\t}\n\t\t\t}\n\t\t\tnewProp.addSuperProperty(superProp);\n\t\t\tlogger.debug(\" Datatype property '\" + newProp.getURI() + \"' given super property '\" + superSRUri + \"'\");\n\t\t}\n\t\treturn newProp;\n\t}\n\t\n\tprivate Individual createIndividual(SadlResource srsrc, OntClass type) throws JenaProcessorException, TranslationException {\n\t\tNode n = processExpression(srsrc);\n\t\tif (n == null) {\n\t\t\tthrow new JenaProcessorException(\"SadlResource failed to convert to Node\");\n\t\t}\n\t\tIndividual inst = createIndividual(n.toFullyQualifiedString(), type);\n\t\tEList anns = srsrc.getAnnotations();\n\t\tif (anns != null) {\n\t\t\taddAnnotationsToResource(inst, anns);\n\t\t}\n\t\treturn inst;\n\t}\n\t\n\tprivate Individual createIndividual(String newName, OntClass supercls) {\n\t\tIndividual inst = getTheJenaModel().createIndividual(newName, supercls);\n\t\tlogger.debug(\"New instance '\" + (newName != null ? newName : \"(bnode)\") + \"' created\");\n\t\treturn inst;\n\t}\n\t\n\tprivate OntResource sadlTypeReferenceToOntResource(SadlTypeReference sadlTypeRef) throws JenaProcessorException {\n\t\tcom.hp.hpl.jena.rdf.model.Resource obj = sadlTypeReferenceToResource(sadlTypeRef);\n\t\tif (obj == null) {\n\t\t\treturn null;\t// this happens when sadlTypeRef is a variable (even if unintended)\n\t\t}\n\t\tif (obj instanceof OntResource) {\n\t\t\treturn (OntResource)obj;\n\t\t}\n\t\telse if (obj instanceof RDFNode) {\n\t\t\tif (((RDFNode)obj).canAs(OntResource.class)) {\n\t\t\t\treturn ((RDFNode)obj).as(OntResource.class);\n\t\t\t}\n\t\t}\n\t\tthrow new JenaProcessorException(\"Unable to convert SadlTypeReference '\" + sadlTypeRef + \"' to OntResource\");\n\t}\n\t\n\tprivate com.hp.hpl.jena.rdf.model.Resource sadlTypeReferenceToResource(SadlTypeReference sadlTypeRef) throws JenaProcessorException {\n\t\tObject obj = sadlTypeReferenceToObject(sadlTypeRef);\n\t\tif (obj == null) {\n\t\t\treturn null;\t// this happens when sadlTypeRef is a variable (even if unintended)\n\t\t}\n\t\tif (obj instanceof com.hp.hpl.jena.rdf.model.Resource) {\n\t\t\treturn (com.hp.hpl.jena.rdf.model.Resource) obj;\n\t\t}\n\t\telse if (obj instanceof RDFNode) {\n\t\t\tif (((RDFNode)obj).canAs(com.hp.hpl.jena.rdf.model.Resource.class)) {\n\t\t\t\treturn ((RDFNode)obj).as(com.hp.hpl.jena.rdf.model.Resource.class);\n\t\t\t}\n\t\t}\n\t\tthrow new JenaProcessorException(\"Unable to convert SadlTypeReference '\" + sadlTypeRef + \"' to OntResource\");\n\t}\n\t\n\tprivate ConceptName sadlSimpleTypeReferenceToConceptName(SadlTypeReference sadlTypeRef) throws JenaProcessorException {\n\t\tif (sadlTypeRef instanceof SadlSimpleTypeReference) {\n\t\t\tSadlResource strSR = ((SadlSimpleTypeReference)sadlTypeRef).getType();\n\t\t\tOntConceptType ctype;\n\t\t\ttry {\n\t\t\t\tctype = getDeclarationExtensions().getOntConceptType(strSR);\n\t\t\t} catch (CircularDefinitionException e) {\n\t\t\t\tctype = e.getDefinitionType();\n\t\t\t\taddError(e.getMessage(), sadlTypeRef);\n\t\t\t}\n\t\t\tString strSRUri = getDeclarationExtensions().getConceptUri(strSR);\t\n\t\t\tif (strSRUri == null) {\n\t\t\t\tif (ctype.equals(OntConceptType.VARIABLE)) {\n\t\t\t\t\t//throw new JenaProcessorException(\"Failed to get variable URI of SadlResource in sadlSimpleTypeReferenceToConceptName\");\n\t\t\t\t\t// be silent? during clean these URIs won't be found\n\t\t\t\t}\n//\t\t\t\tthrow new JenaProcessorException(\"Failed to get concept URI of SadlResource in sadlSimpleTypeReferenceToConceptName\");\n\t\t\t\t// be silent? during clean these URIs won't be found\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (ctype.equals(OntConceptType.CLASS)) {\n\t\t\t\tConceptName cn = new ConceptName(strSRUri);\n\t\t\t\tcn.setType(ConceptType.ONTCLASS);\n\t\t\t\treturn cn;\n\t\t\t}\n\t\t\telse if (ctype.equals(OntConceptType.CLASS_LIST)) {\n\t\t\t\tConceptName cn = new ConceptName(strSRUri);\n\t\t\t\tcn.setType(ConceptType.ONTCLASS);\n\t\t\t\tcn.setRangeValueType(RangeValueType.LIST);\n\t\t\t\treturn cn;\n\t\t\t}\n\t\t\telse if (ctype.equals(OntConceptType.DATATYPE_LIST)) {\n\t\t\t\tConceptName cn = new ConceptName(strSRUri);\n\t\t\t\tcn.setType(ConceptType.RDFDATATYPE);\n\t\t\t\tcn.setRangeValueType(RangeValueType.LIST);\n\t\t\t\treturn cn;\n\t\t\t}\n\t\t\telse if (ctype.equals(OntConceptType.INSTANCE)) {\n\t\t\t\tConceptName cn = new ConceptName(strSRUri);\n\t\t\t\tcn.setType(ConceptType.INDIVIDUAL);\n\t\t\t\treturn cn;\n\t\t\t}\n\t\t\telse if (ctype.equals(OntConceptType.DATATYPE)) {\t\t\t\t\n\t\t\t\tConceptName cn = new ConceptName(strSRUri);\n\t\t\t\tcn.setType(ConceptType.RDFDATATYPE);\n\t\t\t\treturn cn;\n\t\t\t}\n\t\t\telse if (ctype.equals(OntConceptType.CLASS_PROPERTY)) {\n\t\t\t\tConceptName cn = new ConceptName(strSRUri);\n\t\t\t\tcn.setType(ConceptType.OBJECTPROPERTY);\n\t\t\t\treturn cn;\n\t\t\t}\n\t\t\telse if (ctype.equals(OntConceptType.DATATYPE_PROPERTY)) {\n\t\t\t\tConceptName cn = new ConceptName(strSRUri);\n\t\t\t\tcn.setType(ConceptType.DATATYPEPROPERTY);\n\t\t\t\treturn cn;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthrow new JenaProcessorException(\"SadlSimpleTypeReference '\" + strSRUri + \"' was of a type not yet handled: \" + ctype.toString());\n\t\t\t}\n\t\t}\n\t\telse if (sadlTypeRef instanceof SadlPrimitiveDataType) {\n\t\t\tcom.hp.hpl.jena.rdf.model.Resource trr = getSadlPrimitiveDataTypeResource((SadlPrimitiveDataType) sadlTypeRef);\n\t\t\tConceptName cn = new ConceptName(trr.getURI());\n\t\t\tcn.setType(ConceptType.RDFDATATYPE);\n\t\t\treturn cn;\n\t\t}\n\t\telse {\n\t\t\tthrow new JenaProcessorException(\"SadlTypeReference is not a URI resource\");\n\t\t}\n\t}\n\t\n\tprivate OntConceptType sadlTypeReferenceOntConceptType(SadlTypeReference sadlTypeRef) throws CircularDefinitionException {\n\t\tif (sadlTypeRef instanceof SadlSimpleTypeReference) {\n\t\t\tSadlResource strSR = ((SadlSimpleTypeReference)sadlTypeRef).getType();\n\t\t\treturn getDeclarationExtensions().getOntConceptType(strSR);\n\t\t}\n\t\telse if (sadlTypeRef instanceof SadlPrimitiveDataType) {\n\t\t\treturn OntConceptType.DATATYPE;\n\t\t}\n\t\telse if (sadlTypeRef instanceof SadlPropertyCondition) {\n\t\t\tSadlResource sr = ((SadlPropertyCondition)sadlTypeRef).getProperty();\n\t\t\treturn getDeclarationExtensions().getOntConceptType(sr);\t\t\n\t\t}\n\t\telse if (sadlTypeRef instanceof SadlUnionType || sadlTypeRef instanceof SadlIntersectionType) {\n\t\t\treturn OntConceptType.CLASS;\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprotected Object sadlTypeReferenceToObject(SadlTypeReference sadlTypeRef) throws JenaProcessorException {\n\t\tOntResource rsrc = null;\n\t\t// TODO How do we tell if this is a union versus an intersection?\t\t\t\t\t\t\n\t\tif (sadlTypeRef instanceof SadlSimpleTypeReference) {\n\t\t\tSadlResource strSR = ((SadlSimpleTypeReference)sadlTypeRef).getType();\n\t\t\t//TODO check for proxy, i.e. unresolved references\n\t\t\tOntConceptType ctype;\n\t\t\ttry {\n\t\t\t\tctype = getDeclarationExtensions().getOntConceptType(strSR);\n\t\t\t} catch (CircularDefinitionException e) {\n\t\t\t\tctype = e.getDefinitionType();\n\t\t\t\taddError(e.getMessage(), sadlTypeRef);\n\t\t\t}\n\t\t\tString strSRUri = getDeclarationExtensions().getConceptUri(strSR);\t\n\t\t\tif (strSRUri == null) {\n\t\t\t\tif (ctype.equals(OntConceptType.VARIABLE)) {\n\t\t\t\t\taddError(\"Range should not be a variable.\", sadlTypeRef);\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\tthrow new JenaProcessorException(\"Failed to get concept URI of SadlResource in sadlTypeReferenceToObject\");\n\t\t\t}\n\t\t\tif (ctype.equals(OntConceptType.CLASS)) {\n\t\t\t\tif (((SadlSimpleTypeReference) sadlTypeRef).isList()) {\n\t\t\t\t\trsrc = getOrCreateListSubclass(null, strSRUri, sadlTypeRef.eResource());\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\trsrc = getTheJenaModel().getOntClass(strSRUri);\n\t\t\t\t\tif (rsrc == null) {\n\t\t\t\t\t\treturn createOntClass(strSRUri, (OntClass)null);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (ctype.equals(OntConceptType.CLASS_LIST)) {\n\t\t\t\trsrc = getTheJenaModel().getOntClass(strSRUri);\n\t\t\t\tif (rsrc == null) {\n\t\t\t\t\treturn getOrCreateListSubclass(strSRUri, strSRUri, strSR.eResource());\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (ctype.equals(OntConceptType.DATATYPE_LIST)) {\n\t\t\t\trsrc = getTheJenaModel().getOntClass(strSRUri);\n\t\t\t\tif (rsrc == null) {\n\t\t\t\t\treturn getOrCreateListSubclass(strSRUri, strSRUri, strSR.eResource());\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (ctype.equals(OntConceptType.INSTANCE)) {\n\t\t\t\trsrc = getTheJenaModel().getIndividual(strSRUri);\n\t\t\t\tif (rsrc == null) {\n\t\t\t\t\t// is it OK to create Individual without knowing class??\n\t\t\t\t\treturn createIndividual(strSRUri, (OntClass)null);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (ctype.equals(OntConceptType.DATATYPE)) {\t\t\t\t\n\t\t\t\tOntResource dt = getTheJenaModel().getOntResource(strSRUri);\n\t\t\t\tif (dt == null) {\n\t\t\t\t\tthrow new JenaProcessorException(\"SadlSimpleTypeReference '\" + strSRUri + \"' not found; it should exist as there isn't enough information to create it.\");\n\t\t\t\t}\n\t\t\t\treturn dt;\n\t\t\t}\n\t\t\telse if (ctype.equals(OntConceptType.CLASS_PROPERTY)) {\n\t\t\t\tOntProperty otp = getTheJenaModel().getOntProperty(strSRUri);\n\t\t\t\tif (otp == null) {\n\t\t\t\t\tthrow new JenaProcessorException(\"SadlSimpleTypeReference '\" + strSRUri + \"' not found; should have found an ObjectProperty\");\n\t\t\t\t}\n\t\t\t\treturn otp;\n\t\t\t}\n\t\t\telse if (ctype.equals(OntConceptType.DATATYPE_PROPERTY)) {\n\t\t\t\tOntProperty dtp = getTheJenaModel().getOntProperty(strSRUri);\n\t\t\t\tif (dtp == null) {\n\t\t\t\t\tthrow new JenaProcessorException(\"SadlSimpleTypeReference '\" + strSRUri + \"' not found; should have found an DatatypeProperty\");\n\t\t\t\t}\n\t\t\t\treturn dtp;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthrow new JenaProcessorException(\"SadlSimpleTypeReference '\" + strSRUri + \"' was of a type not yet handled: \" + ctype.toString());\n\t\t\t}\n\t\t}\n\t\telse if (sadlTypeRef instanceof SadlPrimitiveDataType) {\n\t\t\treturn processSadlPrimitiveDataType(null, (SadlPrimitiveDataType) sadlTypeRef, null);\n\t\t}\n\t\telse if (sadlTypeRef instanceof SadlPropertyCondition) {\n\t\t\treturn processSadlPropertyCondition((SadlPropertyCondition) sadlTypeRef);\t\t\n\t\t}\n\t\telse if (sadlTypeRef instanceof SadlUnionType) {\n\t\t\tRDFNode lftNode = null; RDFNode rhtNode = null;\n\t\t\tSadlTypeReference lft = ((SadlUnionType)sadlTypeRef).getLeft();\n\t\t\tObject lftObj = sadlTypeReferenceToObject(lft);\n\t\t\tif (lftObj == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (lftObj instanceof OntResource) {\n\t\t\t\tlftNode = ((OntResource)lftObj).asClass();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (lftObj instanceof RDFNode) {\n\t\t\t\t\tlftNode = (RDFNode) lftObj;\n\t\t\t\t}\n\t\t\t\telse if (lftObj instanceof List) {\n\t\t\t\t\t// carry on: RDFNode list from nested union\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrow new JenaProcessorException(\"Union member of unsupported type: \" + lftObj.getClass().getCanonicalName());\n\t\t\t\t}\n\t\t\t}\n\t\t\tSadlTypeReference rht = ((SadlUnionType)sadlTypeRef).getRight();\n\t\t\tObject rhtObj = sadlTypeReferenceToObject(rht);\n\t\t\tif (rhtObj == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (rhtObj instanceof OntResource && ((OntResource) rhtObj).canAs(OntClass.class)) {\n\t\t\t\trhtNode = ((OntResource)rhtObj).asClass();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (rhtObj instanceof RDFNode) {\n\t\t\t\t\trhtNode = (RDFNode) rhtObj;\n\t\t\t\t}\n\t\t\t\telse if (rhtObj instanceof List) {\n\t\t\t\t\t// carry on: RDFNode list from nested union\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrow new JenaProcessorException(\"Union member of unsupported type: \" + rhtObj != null ? rhtObj.getClass().getCanonicalName() : \"null\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (lftNode instanceof OntResource && rhtNode instanceof OntResource) {\n\t\t\t\tOntClass unionCls = createUnionClass(lftNode, rhtNode);\n\t\t\t\treturn unionCls;\n\t\t\t}\n\t\t\telse if (lftObj instanceof List && rhtNode instanceof RDFNode) {\n\t\t\t\t((List)lftObj).add(rhtNode);\n\t\t\t\treturn lftObj;\n\t\t\t}\n\t\t\telse if (lftObj instanceof RDFNode && rhtNode instanceof List) {\n\t\t\t\t((List)rhtNode).add(lftNode);\n\t\t\t\treturn rhtNode;\n\t\t\t}\n\t\t\telse if (lftNode instanceof RDFNode && rhtNode instanceof RDFNode){\n\t\t\t\tList rdfdatatypelist = new ArrayList();\n\t\t\t\trdfdatatypelist.add((RDFNode) lftNode);\n\t\t\t\trdfdatatypelist.add((RDFNode) rhtNode);\n\t\t\t\treturn rdfdatatypelist;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthrow new JenaProcessorException(\"Left and right sides of union are of incompatible types: \" + lftNode.toString() + \" and \" + rhtNode.toString());\n\t\t\t}\n\t\t}\n\t\telse if (sadlTypeRef instanceof SadlIntersectionType) {\n\t\t\tRDFNode lftNode = null; RDFNode rhtNode = null;\n\t\t\tSadlTypeReference lft = ((SadlIntersectionType)sadlTypeRef).getLeft();\n\t\t\tObject lftObj = sadlTypeReferenceToObject(lft);\n\t\t\tif (lftObj == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (lftObj instanceof OntResource) {\n\t\t\t\tlftNode = ((OntResource)lftObj).asClass();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (lftObj instanceof RDFNode) {\n\t\t\t\t\tlftNode = (RDFNode) lftObj;\n\t\t\t\t}\n\t\t\t\telse if (lftObj == null) {\n\t\t\t\t\taddError(\"SadlIntersectionType did not resolve to an ontology object (null)\", sadlTypeRef);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrow new JenaProcessorException(\"Intersection member of unsupported type: \" + lftObj.getClass().getCanonicalName());\n\t\t\t\t}\n\t\t\t}\n\t\t\tSadlTypeReference rht = ((SadlIntersectionType)sadlTypeRef).getRight();\n\t\t\tif (rht == null) {\n\t\t\t\tthrow new JenaProcessorException(\"No right-hand side to intersection\");\n\t\t\t}\n\t\t\tObject rhtObj = sadlTypeReferenceToObject(rht);\n\t\t\tif (rhtObj == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (rhtObj instanceof OntResource) {\n\t\t\t\trhtNode = ((OntResource)rhtObj).asClass();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (rhtObj instanceof RDFNode) {\n\t\t\t\t\trhtNode = (RDFNode) rhtObj;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrow new JenaProcessorException(\"Intersection member of unsupported type: \" + rhtObj.getClass().getCanonicalName());\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (lftNode instanceof OntResource && rhtNode instanceof OntResource) {\n\t\t\t\tOntClass intersectCls = createIntersectionClass(lftNode, rhtNode);\n\t\t\t\treturn intersectCls;\n\t\t\t}\n\t\t\telse if (lftNode instanceof RDFNode && rhtNode instanceof RDFNode){\n\t\t\t\tList rdfdatatypelist = new ArrayList();\n\t\t\t\trdfdatatypelist.add((RDFNode) lftNode);\n\t\t\t\trdfdatatypelist.add((RDFNode) rhtNode);\n\t\t\t\treturn rdfdatatypelist;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthrow new JenaProcessorException(\"Left and right sides of union are of incompatible types: \" + lftNode.toString() + \" and \" + rhtNode.toString());\n\t\t\t}\n\t\t}\n\t\treturn rsrc;\n\t}\n\n\tprivate com.hp.hpl.jena.rdf.model.Resource processSadlPrimitiveDataType(SadlClassOrPropertyDeclaration element, SadlPrimitiveDataType sadlTypeRef, String newDatatypeUri) throws JenaProcessorException {\n\t\tcom.hp.hpl.jena.rdf.model.Resource onDatatype = getSadlPrimitiveDataTypeResource(sadlTypeRef);\n\t\tif (sadlTypeRef.isList()) {\n\t\t\tonDatatype = getOrCreateListSubclass(null, onDatatype.toString(), sadlTypeRef.eResource());\n\t\t}\n\t\tif (newDatatypeUri == null) {\n\t\t\treturn onDatatype;\n\t\t}\n\t\tSadlDataTypeFacet facet = element.getFacet();\n\t\tOntClass datatype = createRdfsDatatype(newDatatypeUri, null, onDatatype, facet);\n\t\treturn datatype;\n\t}\n\t\n\tprivate com.hp.hpl.jena.rdf.model.Resource getSadlPrimitiveDataTypeResource(SadlPrimitiveDataType sadlTypeRef)\n\t\t\tthrows JenaProcessorException {\n\t\tSadlDataType pt = sadlTypeRef.getPrimitiveType();\n\t\tString typeStr = pt.getLiteral();\n\t\tcom.hp.hpl.jena.rdf.model.Resource onDatatype;\n\t\tif (typeStr.equals(XSD.xstring.getLocalName())) onDatatype = XSD.xstring;\n\t\telse if (typeStr.equals(XSD.anyURI.getLocalName())) onDatatype = XSD.anyURI;\n\t\telse if (typeStr.equals(XSD.base64Binary.getLocalName())) onDatatype = XSD.base64Binary;\n\t\telse if (typeStr.equals(XSD.xbyte.getLocalName())) onDatatype = XSD.xbyte;\n\t\telse if (typeStr.equals(XSD.date.getLocalName())) onDatatype = XSD.date;\n\t\telse if (typeStr.equals(XSD.dateTime.getLocalName())) onDatatype = XSD.dateTime;\n\t\telse if (typeStr.equals(XSD.decimal.getLocalName())) onDatatype = XSD.decimal;\n\t\telse if (typeStr.equals(XSD.duration.getLocalName())) onDatatype = XSD.duration;\n\t\telse if (typeStr.equals(XSD.gDay.getLocalName())) onDatatype = XSD.gDay;\n\t\telse if (typeStr.equals(XSD.gMonth.getLocalName())) onDatatype = XSD.gMonth;\n\t\telse if (typeStr.equals(XSD.gMonthDay.getLocalName())) onDatatype = XSD.gMonthDay;\n\t\telse if (typeStr.equals(XSD.gYear.getLocalName())) onDatatype = XSD.gYear;\n\t\telse if (typeStr.equals(XSD.gYearMonth.getLocalName())) onDatatype = XSD.gYearMonth;\n\t\telse if (typeStr.equals(XSD.hexBinary.getLocalName())) onDatatype = XSD.hexBinary;\n\t\telse if (typeStr.equals(XSD.integer.getLocalName())) onDatatype = XSD.integer;\n\t\telse if (typeStr.equals(XSD.time.getLocalName())) onDatatype = XSD.time;\n\t\telse if (typeStr.equals(XSD.xboolean.getLocalName())) onDatatype = XSD.xboolean;\n\t\telse if (typeStr.equals(XSD.xdouble.getLocalName())) onDatatype = XSD.xdouble;\n\t\telse if (typeStr.equals(XSD.xfloat.getLocalName())) onDatatype = XSD.xfloat;\n\t\telse if (typeStr.equals(XSD.xint.getLocalName())) onDatatype = XSD.xint;\n\t\telse if (typeStr.equals(XSD.xlong.getLocalName())) onDatatype = XSD.xlong;\n\t\telse if (typeStr.equals(XSD.anyURI.getLocalName())) onDatatype = XSD.anyURI;\n\t\telse if (typeStr.equals(XSD.anyURI.getLocalName())) onDatatype = XSD.anyURI;\n\t\telse {\n\t\t\tthrow new JenaProcessorException(\"Unexpected primitive data type: \" + typeStr);\n\t\t}\n\t\treturn onDatatype;\n\t}\n\tprivate OntClass createRdfsDatatype(String newDatatypeUri, List unionOfTypes, com.hp.hpl.jena.rdf.model.Resource onDatatype,\n\t\t\tSadlDataTypeFacet facet) throws JenaProcessorException {\n\t\tOntClass datatype = getTheJenaModel().createOntResource(OntClass.class, RDFS.Datatype, newDatatypeUri);\n\t\tOntClass equivClass = getTheJenaModel().createOntResource(OntClass.class, RDFS.Datatype, null);\n\t\tif (onDatatype != null) {\n\t\t\tequivClass.addProperty(OWL2.onDatatype, onDatatype);\n\t\t\tif (facet != null) {\n\t\t\t\tcom.hp.hpl.jena.rdf.model.Resource restrictions = facetsToRestrictionNode(newDatatypeUri, facet);\n\t\t\t\t// Create a list containing the restrictions\n\t\t\t\tRDFList list = getTheJenaModel().createList(new RDFNode[] {restrictions});\n\t\t\t\tequivClass.addProperty(OWL2.withRestrictions, list);\n\t\t\t}\n\t\t}\n\t\telse if (unionOfTypes != null) {\n\t\t\tIterator iter = unionOfTypes.iterator();\n\t\t\tRDFList collection = getTheJenaModel().createList();\n\t\t\twhile (iter.hasNext()) {\n\t\t\t\tRDFNode dt = iter.next();\n\t\t\t\tcollection = collection.with(dt);\n\t\t\t}\n\t\t\tequivClass.addProperty(OWL.unionOf, collection);\n\t\t}\n\t\telse {\n\t\t\tthrow new JenaProcessorException(\"Invalid arguments to createRdfsDatatype\");\n\t\t}\n\t\tdatatype.addEquivalentClass(equivClass);\n\t\treturn datatype;\n\t}\n\n\tprivate com.hp.hpl.jena.rdf.model.Resource facetsToRestrictionNode(String newName, SadlDataTypeFacet facet) {\n\t\tcom.hp.hpl.jena.rdf.model.Resource anon = getTheJenaModel().createResource();\n\t\t\n\t\tanon.addProperty(xsdProperty(facet.isMinInclusive()?\"minInclusive\":\"minExclusive\"), \"\" + facet.getMin());\n\t\tanon.addProperty(xsdProperty(facet.isMaxInclusive()?\"maxInclusive\":\"maxExclusive\"), \"\" + facet.getMax());\n\t\t\n\t\tif (facet.getLen() != null) {\n\t\t\tanon.addProperty(xsdProperty(\"length\"), \"\" + facet.getLen());\n\t\t}\n\t\tif (facet.getMinlen() != null) {\n\t\t\tanon.addProperty(xsdProperty(\"minLength\"), \"\" + facet.getMinlen());\n\t\t}\n\t\tif (facet.getMaxlen() != null && !facet.getMaxlen().equals(\"*\")) {\n\t\t\tanon.addProperty(xsdProperty(\"maxLength\"), \"\" + facet.getMaxlen());\n\t\t}\n\t\tif (facet.getRegex() != null) {\n\t\t\tanon.addProperty(xsdProperty(\"pattern\"), \"\" + facet.getRegex());\n\t\t}\n\t\tif (facet.getValues() != null) {\n\t\t\tIterator iter = facet.getValues().iterator();\n\t\t\twhile (iter.hasNext()) {\n\t\t\t\tanon.addProperty(xsdProperty(\"enumeration\"), iter.next());\n\t\t\t}\n\t\t}\n\t\treturn anon;\n\t}\n\n\tprotected OntClass processSadlPropertyCondition(SadlPropertyCondition sadlPropCond) throws JenaProcessorException {\n\t\tOntClass retval = null;\n\t\tSadlResource sr = ((SadlPropertyCondition)sadlPropCond).getProperty();\n\t\tString propUri = getDeclarationExtensions().getConceptUri(sr);\n\t\tif (propUri == null) {\n\t\t\tthrow new JenaProcessorException(\"Failed to get concept URI of SadlResource in processSadlPropertyCondition\");\n\t\t}\n\t\tOntConceptType propType;\n\t\ttry {\n\t\t\tpropType = getDeclarationExtensions().getOntConceptType(sr);\n\t\t} catch (CircularDefinitionException e) {\n\t\t\tpropType = e.getDefinitionType();\n\t\t\taddError(e.getMessage(), sadlPropCond);\n\t\t}\n\t\tOntProperty prop = getTheJenaModel().getOntProperty(propUri);\n\t\tif (prop == null) {\n\t\t\tif (propType.equals(OntConceptType.CLASS_PROPERTY)) {\n\t\t\t\tprop = getTheJenaModel().createObjectProperty(propUri);\n\t\t\t}\n\t\t\telse if (propType.equals(OntConceptType.DATATYPE_PROPERTY)) {\n\t\t\t\tprop = getTheJenaModel().createDatatypeProperty(propUri);\n\t\t\t}\n\t\t\telse if (propType.equals(OntConceptType.ANNOTATION_PROPERTY)) {\n\t\t\t\tprop = getTheJenaModel().createAnnotationProperty(propUri);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tprop = getTheJenaModel().createOntProperty(propUri);\n\t\t\t}\n\t\t}\n\t\tIterator conditer = ((SadlPropertyCondition)sadlPropCond).getCond().iterator();\n\t\twhile (conditer.hasNext()) {\n\t\t\tSadlCondition cond = conditer.next();\n\t\t\tretval = sadlConditionToOntClass(cond, prop, propType);\n\t\t\tif (conditer.hasNext()) {\n\t\t\t\tthrow new JenaProcessorException(\"Multiple property conditions not currently handled\");\n\t\t\t}\n\t\t}\n\t\treturn retval;\n\t}\n\n\tprotected OntClass sadlConditionToOntClass(SadlCondition cond, Property prop, OntConceptType propType) throws JenaProcessorException {\n\t\tOntClass retval = null;\n\t\tif (prop == null) {\n\t\t\taddError(SadlErrorMessages.CANNOT_CREATE.get(\"restriction\", \"unresolvable property\"), cond);\n\t\t}\n\t\telse if (cond instanceof SadlAllValuesCondition) {\n\t\t\tSadlTypeReference type = ((SadlAllValuesCondition)cond).getType();\n\t\t\tif (type instanceof SadlPrimitiveDataType) {\n\t\t\t\tSadlDataType pt = ((SadlPrimitiveDataType)type).getPrimitiveType();\n\t\t\t\tString typeStr = pt.getLiteral();\n\t\t\t\ttypeStr = XSD.getURI() + typeStr;\n\t\t\t}\n\t\t\tcom.hp.hpl.jena.rdf.model.Resource typersrc = sadlTypeReferenceToResource(type);\n\t\t\tif (typersrc == null) {\n\t\t\t\taddError(SadlErrorMessages.CANNOT_CREATE.get(\"all values from restriction\",\n\t\t\t\t\t\t\"restriction on unresolvable property value restriction\"), type);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tAllValuesFromRestriction avf = getTheJenaModel().createAllValuesFromRestriction(null, prop, typersrc);\n\t\t\t\tlogger.debug(\"New all values from restriction on '\" + prop.getURI() + \"' to values of type '\" + typersrc.toString() + \"'\");\n\t\t\t\tretval = avf;\n\t\t\t}\n\t\t}\n\t\telse if (cond instanceof SadlHasValueCondition) {\n//\t\t\tSadlExplicitValue value = ((SadlHasValueCondition)cond).getRestriction();\n\t\t\tRDFNode val = null;\n\t\t\tEObject restObj = ((SadlHasValueCondition)cond).getRestriction();\n\t\t\tif (restObj instanceof SadlExplicitValue) {\n\t\t\t\tSadlExplicitValue value = (SadlExplicitValue) restObj;\n\t\t\t\tif (value instanceof SadlResource) {\n\t\t\t\t\tOntConceptType srType;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tsrType = getDeclarationExtensions().getOntConceptType((SadlResource)value);\n\t\t\t\t\t} catch (CircularDefinitionException e) {\n\t\t\t\t\t\tsrType = e.getDefinitionType();\n\t\t\t\t\t\taddError(e.getMessage(), cond);\n\t\t\t\t\t}\n\t\t\t\t\tSadlResource srValue = (SadlResource) value;\n\t\t\t\t\tif (srType == null) {\n\t\t\t\t\t\tsrValue = ((SadlResource)value).getName();\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tsrType = getDeclarationExtensions().getOntConceptType(srValue);\n\t\t\t\t\t\t} catch (CircularDefinitionException e) {\n\t\t\t\t\t\t\tsrType = e.getDefinitionType();\n\t\t\t\t\t\t\taddError(e.getMessage(), cond);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (srType == null) {\n\t\t\t\t\t\tthrow new JenaProcessorException(\"Unable to resolve SadlResource value\");\n\t\t\t\t\t}\n\t\t\t\t\tif (srType.equals(OntConceptType.INSTANCE)) {\n\t\t\t\t\t\tString valUri = getDeclarationExtensions().getConceptUri(srValue);\n\t\t\t\t\t\tif (valUri == null) {\n\t\t\t\t\t\t\tthrow new JenaProcessorException(\"Failed to find SadlResource in Xtext model\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tval = getTheJenaModel().getIndividual(valUri);\n\t\t\t\t\t\tif (val == null) {\n\t\t\t\t\t\t\tSadlResource decl = getDeclarationExtensions().getDeclaration(srValue);\n\t\t\t\t\t\t\tif (decl != null && !decl.equals(srValue)) {\n\t\t\t\t\t\t\t\tEObject cont = decl.eContainer();\n\t\t\t\t\t\t\t\tif (cont instanceof SadlInstance) {\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\tval = processSadlInstance((SadlInstance)cont);\n\t\t\t\t\t\t\t\t\t} catch (CircularDefinitionException e) {\n\t\t\t\t\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse if (cont instanceof SadlMustBeOneOf) {\n\t\t\t\t\t\t\t\t\tcont = ((SadlMustBeOneOf)cont).eContainer();\n\t\t\t\t\t\t\t\t\tif (cont instanceof SadlClassOrPropertyDeclaration) {\n\t\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\t\tprocessSadlClassOrPropertyDeclaration((SadlClassOrPropertyDeclaration) cont);\n\t\t\t\t\t\t\t\t\t\t\teobjectPreprocessed(cont);\n\t\t\t\t\t\t\t\t\t\t} catch (TranslationException e) {\n\t\t\t\t\t\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tval = getTheJenaModel().getIndividual(valUri);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse if (cont instanceof SadlCanOnlyBeOneOf) {\n\t\t\t\t\t\t\t\t\tcont = ((SadlCanOnlyBeOneOf)cont).eContainer();\n\t\t\t\t\t\t\t\t\tif (cont instanceof SadlClassOrPropertyDeclaration) {\n\t\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\t\tprocessSadlClassOrPropertyDeclaration((SadlClassOrPropertyDeclaration) cont);\n\t\t\t\t\t\t\t\t\t\t\teobjectPreprocessed(cont);\n\t\t\t\t\t\t\t\t\t\t} catch (TranslationException e) {\n\t\t\t\t\t\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tval = getTheJenaModel().getIndividual(valUri);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (val == null) {\n\t\t\t\t\t\t\t\tthrow new JenaProcessorException(\"Failed to retrieve instance '\" + valUri + \"' from Jena model\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tthrow new JenaProcessorException(\"A has value restriction is to a SADL resource that did not resolve to an instance in the model\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (prop.canAs(OntProperty.class)) {\n\t\t\t\t\t\tval = sadlExplicitValueToLiteral(value, prop.as(OntProperty.class).getRange());\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tval = sadlExplicitValueToLiteral(value, null);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (restObj instanceof SadlNestedInstance) {\n\t\t\t\ttry {\n\t\t\t\t\tval = processSadlInstance((SadlNestedInstance)restObj);\n\t\t\t\t} catch (CircularDefinitionException e) {\n\t\t\t\t\tthrow new JenaProcessorException(e.getMessage());\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (propType.equals(OntConceptType.CLASS_PROPERTY)) {\n\t\t\t\tIndividual valInst = val.as(Individual.class);\n\t\t\t\tif (prop.canAs(OntProperty.class) && valueInObjectTypePropertyRange(prop.as(OntProperty.class), valInst, cond)) {\n\t\t\t\t\tHasValueRestriction hvr = getTheJenaModel().createHasValueRestriction(null, prop, valInst);\n\t\t\t\t\tlogger.debug(\"New has value restriction on '\" + prop.getURI() + \"' to value '\" + valInst.toString() + \"'\");\n\t\t\t\t\tretval = hvr;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrow new JenaProcessorException(SadlErrorMessages.NOT_IN_RANGE.get(valInst.getURI(), prop.getURI()));\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (propType.equals(OntConceptType.DATATYPE_PROPERTY)) {\n\t\t\t\tif (prop.canAs(OntProperty.class) && val.isLiteral() && valueInDatatypePropertyRange(prop.as(OntProperty.class), val.asLiteral(), cond)) {\n\t\t\t\t\tHasValueRestriction hvr = getTheJenaModel().createHasValueRestriction(null, prop, val);\n\t\t\t\t\tlogger.debug(\"New has value restriction on '\" + prop.getURI() + \"' to value '\" + val.toString() + \"'\");\n\t\t\t\t\tretval = hvr;\n\t\t\t\t}\t\n\t\t\t\telse {\n\t\t\t\t\tthrow new JenaProcessorException(SadlErrorMessages.NOT_IN_RANGE.get(val.toString(), prop.getURI()));\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (propType.equals(OntConceptType.RDF_PROPERTY)) {\n\t\t\t\tHasValueRestriction hvr = getTheJenaModel().createHasValueRestriction(null, prop, val);\n\t\t\t\tlogger.debug(\"New has value restriction on '\" + prop.getURI() + \"' to value '\" + val.toString() + \"'\");\n\t\t\t\tretval = hvr;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthrow new JenaProcessorException(\"Has value restriction on unexpected property type: \" + propType.toString());\n\t\t\t}\n\t\t}\n\t\telse if (cond instanceof SadlCardinalityCondition) {\n\t\t\t// Note: SomeValuesFrom is embedded in cardinality in the SADL grammar--an \"at least\" cardinality with \"one\" instead of # \n\t\t\tString cardinality = ((SadlCardinalityCondition)cond).getCardinality();\n\t\t\tSadlTypeReference type = ((SadlCardinalityCondition)cond).getType();\n\t\t\tOntResource typersrc = null;\n\t\t\tif (type != null) {\n\t\t\t\ttypersrc = sadlTypeReferenceToOntResource(type);\t\t\t\t\t\n\t\t\t}\n\t\t\tif (cardinality.equals(\"one\")) {\n\t\t\t\t// this is interpreted as a someValuesFrom restriction\n\t\t\t\tif (type == null) {\n\t\t\t\t\tthrow new JenaProcessorException(\"'one' means some value from class so a type must be given\");\n\t\t\t\t}\n\t\t\t\tSomeValuesFromRestriction svf = getTheJenaModel().createSomeValuesFromRestriction(null, prop, typersrc);\n\t\t\t\tlogger.debug(\"New some values from restriction on '\" + prop.getURI() + \"' to values of type '\" + typersrc.toString() + \"'\");\n\t\t\t\tretval = svf;\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// cardinality restrictioin\n\t\t\t\tint cardNum = Integer.parseInt(cardinality);\n\t\t\t\tString op = ((SadlCardinalityCondition)cond).getOperator();\n\t\t\t\tif (op == null) {\n\t\t\t\t\tCardinalityRestriction cr = getTheJenaModel().createCardinalityRestriction(null, prop, cardNum);\t\n\t\t\t\t\tlogger.debug(\"New cardinality restriction \" + cardNum + \" on '\" + prop.getURI() + \"' created\");\n\t\t\t\t\tif (type != null) {\n\t\t\t\t\t\tcr.removeAll(OWL.cardinality);\n\t\t\t\t\t\tcr.addLiteral(OWL2.qualifiedCardinality, cardNum);\n\t\t\t\t\t\tcr.addProperty(OWL2.onClass, typersrc);\n\t\t\t\t\t}\n\t\t\t\t\tretval = cr;\n\t\t\t\t}\n\t\t\t\telse if (op.equals(\"least\")) {\n\t\t\t\t\tMinCardinalityRestriction cr = getTheJenaModel().createMinCardinalityRestriction(null, prop, cardNum);\t\t\t\t\t\t\t\n\t\t\t\t\tlogger.debug(\"New min cardinality restriction \" + cardNum + \" on '\" + prop.getURI() + \"' created\");\n\t\t\t\t\tif (type != null) {\n\t\t\t\t\t\tcr.removeAll(OWL.minCardinality);\n\t\t\t\t\t\tcr.addLiteral(OWL2.minQualifiedCardinality, cardNum);\n\t\t\t\t\t\tcr.addProperty(OWL2.onClass, typersrc);\n\t\t\t\t\t}\n\t\t\t\t\tretval = cr;\n\t\t\t\t}\n\t\t\t\telse if (op.equals(\"most\")) {\n\t\t\t\t\tlogger.debug(\"New max cardinality restriction \" + cardNum + \" on '\" + prop.getURI() + \"' created\");\n\t\t\t\t\tMaxCardinalityRestriction cr = getTheJenaModel().createMaxCardinalityRestriction(null, prop, cardNum);\t\t\t\t\t\t\t\n\t\t\t\t\tif (type != null) {\n\t\t\t\t\t\tcr.removeAll(OWL.maxCardinality);\n\t\t\t\t\t\tcr.addLiteral(OWL2.maxQualifiedCardinality, cardNum);\n\t\t\t\t\t\tcr.addProperty(OWL2.onClass, typersrc);\n\t\t\t\t\t}\n\t\t\t\t\tretval = cr;\n\t\t\t\t}\n\t\t\t\tif (logger.isDebugEnabled()) {\n\t\t\t\t\tif (type != null) {\n\t\t\t\t\t\tlogger.debug(\" cardinality is qualified; values must be of type '\" + typersrc + \"'\");\n\t\t\t\t\t}\t\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tthrow new JenaProcessorException(\"Unhandled SadlCondition type: \" + cond.getClass().getCanonicalName());\n\t\t}\n\t\treturn retval;\n\t}\n\n\tprivate boolean valueInDatatypePropertyRange(OntProperty prop, Literal val, EObject cond) {\n\t\ttry {\n\t\t\tif (getModelValidator() != null) {\n\t\t\t\treturn getModelValidator().checkDataPropertyValueInRange(getTheJenaModel(), null, prop, val);\n\t\t\t}\n\t\t} catch (TranslationException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn true;\n\t}\n\n\tprotected Literal sadlExplicitValueToLiteral(SadlExplicitValue value, com.hp.hpl.jena.rdf.model.Resource rng) throws JenaProcessorException {\n\t\ttry {\n\t\t\tboolean isNegated = false;\n\t\t\tif (value instanceof SadlUnaryExpression) {\n\t\t\t\tString op = ((SadlUnaryExpression)value).getOperator();\n\t\t\t\tif (op.equals(\"-\")) {\n\t\t\t\t\tvalue = ((SadlUnaryExpression)value).getValue();\n\t\t\t\t\tisNegated = true;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrow new JenaProcessorException(\"Unhandled case of unary operator on SadlExplicitValue: \" + op);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (value instanceof SadlNumberLiteral) {\n\t\t\t\tString val = ((SadlNumberLiteral)value).getLiteralNumber().toPlainString();\n\t\t\t\tif (isNegated) {\n\t\t\t\t\tval = \"-\" + val;\n\t\t\t\t}\n\t\t\t\tif (rng != null && rng.getURI() != null) {\n\t\t\t\t\treturn SadlUtils.getLiteralMatchingDataPropertyRange(getTheJenaModel(), rng.getURI(), val);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (val.contains(\".\")) {\n\t\t\t\t\t\treturn getTheJenaModel().createTypedLiteral(Double.parseDouble(val));\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\treturn getTheJenaModel().createTypedLiteral(Integer.parseInt(val));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (value instanceof SadlStringLiteral) {\n\t\t\t\tString val = ((SadlStringLiteral)value).getLiteralString();\n\t\t\t\tif (isNegated) {\n\t\t\t\t\tval = \"-\" + val;\n\t\t\t\t}\n\t\t\t\tif (rng != null) {\n\t\t\t\t\treturn SadlUtils.getLiteralMatchingDataPropertyRange(getTheJenaModel(), rng.getURI(), val);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\treturn getTheJenaModel().createTypedLiteral(val);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (value instanceof SadlBooleanLiteral) {\n\t\t\t\tSadlBooleanLiteral val = ((SadlBooleanLiteral)value);\n\t\t\t\tif (rng != null) {\n\t\t\t\t\treturn SadlUtils.getLiteralMatchingDataPropertyRange(getTheJenaModel(), rng.getURI(), val.isTruethy());\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\treturn getTheJenaModel().createTypedLiteral(val.isTruethy());\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (value instanceof SadlValueList) {\n\t\t\t\tthrow new JenaProcessorException(\"A SADL value list cannot be converted to a Literal\");\n\t\t\t}\n\t\t\telse if (value instanceof SadlConstantLiteral) {\n\t\t\t\tString val = ((SadlConstantLiteral)value).getTerm();\n\t\t\t\tif (val.equals(\"PI\")) {\n\t\t\t\t\tdouble cv = Math.PI;\n\t\t\t\t\tif (isNegated) {\n\t\t\t\t\t\tcv = cv*-1.0;\n\t\t\t\t\t}\n\t\t\t\t\treturn SadlUtils.getLiteralMatchingDataPropertyRange(getTheJenaModel(), rng.getURI(), cv);\n\t\t\t\t}\n\t\t\t\telse if (val.equals(\"e\")) {\n\t\t\t\t\tdouble cv = Math.E;\n\t\t\t\t\tif (isNegated) {\n\t\t\t\t\t\tcv = cv*-1.0;\n\t\t\t\t\t}\n\t\t\t\t\treturn SadlUtils.getLiteralMatchingDataPropertyRange(getTheJenaModel(), rng.getURI(), cv);\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\telse if (rng != null) {\n\t\t\t\t\tif (isNegated) {\n\t\t\t\t\t\tval = \"-\" + val;\n\t\t\t\t\t}\n\t\t\t\t\treturn SadlUtils.getLiteralMatchingDataPropertyRange(getTheJenaModel(), rng.getURI(), val);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (isNegated) {\n\t\t\t\t\t\tval = \"-\" + val;\n\t\t\t\t\t}\n\t\t\t\t\ttry {\n\t\t\t\t\t\tint ival = Integer.parseInt(val);\n\t\t\t\t\t\treturn getTheJenaModel().createTypedLiteral(ival);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (Exception e) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tdouble dval = Double.parseDouble(val);\n\t\t\t\t\t\t\treturn getTheJenaModel().createTypedLiteral(dval);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcatch (Exception e2) {\n\t\t\t\t\t\t\treturn getTheJenaModel().createTypedLiteral(val);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (value instanceof SadlResource) {\n\t\t\t\tNode nval = processExpression((SadlResource)value);\n\t\t\t\tthrow new JenaProcessorException(\"Unable to convert concept '\" + nval.toFullyQualifiedString() + \"to a literal\");\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthrow new JenaProcessorException(\"Unhandled sadl explicit vaue type: \" + value.getClass().getCanonicalName());\n\t\t\t}\n\t\t}\n\t\tcatch (Throwable t) {\n\t\t\taddError(t.getMessage(), value);\n\t\t}\n\t\treturn null;\n\t}\n\n\tprivate boolean valueInObjectTypePropertyRange(OntProperty prop, Individual valInst, EObject cond) throws JenaProcessorException {\n\t\tExtendedIterator itr = prop.listRange();\n\t\twhile (itr.hasNext()) {\n\t\t\tOntResource nxt = itr.next();\n\t\t\tif (nxt.isClass()) {\n\t\t\t\tif (instanceBelongsToClass(getTheJenaModel(), valInst, nxt)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprivate IntersectionClass createIntersectionClass(RDFNode... members) throws JenaProcessorException {\n\t\tRDFList classes = getTheJenaModel().createList(members);\n\t\tif (!classes.isEmpty()) {\n\t\t\tIntersectionClass intersectCls = getTheJenaModel().createIntersectionClass(null, classes);\n\t\t\tlogger.debug(\"New intersection class created\");\n\t\t\treturn intersectCls;\n\t\t}\n\t\tthrow new JenaProcessorException(\"createIntersectionClass called with empty list of classes\");\n\t}\n\n\tprivate UnionClass createUnionClass(RDFNode... members) throws JenaProcessorException {\n\t\tUnionClass existingBnodeUnion = null;\n\t\tfor (int i = 0; i < members.length; i++) {\n\t\t\tRDFNode mmbr = members[i];\n\t\t\tif ((mmbr instanceof UnionClass || mmbr.canAs(UnionClass.class) && mmbr.isAnon())) {\n\t\t\t\texistingBnodeUnion = mmbr.as(UnionClass.class);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (existingBnodeUnion != null) {\n\t\t\tfor (int i = 0; i < members.length; i++) {\n\t\t\t\tRDFNode mmbr = members[i];\n\t\t\t\tif (!mmbr.equals(existingBnodeUnion)) {\n\t\t\t\t\texistingBnodeUnion.addOperand(mmbr.asResource());\n\t\t\t\t\tlogger.debug(\"Added member '\" + mmbr.toString() + \"' to existing union class\");\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn existingBnodeUnion;\n\t\t}\n\t\telse {\n\t\t\tRDFList classes = getTheJenaModel().createList(members);\n\t\t\tif (!classes.isEmpty()) {\n\t\t\t\tUnionClass unionCls = getTheJenaModel().createUnionClass(null, classes);\n\t\t\t\tlogger.debug(\"New union class created\");\n\t\t\t\treturn unionCls;\n\t\t\t}\n\t\t}\n\t\tthrow new JenaProcessorException(\"createUnionClass called with empty list of classes\");\n\t}\n\n\tprivate OntConceptType getSadlTypeReferenceType(SadlTypeReference sadlTypeRef) throws JenaProcessorException {\n\t\tif (sadlTypeRef instanceof SadlSimpleTypeReference) {\n\t\t\tSadlResource sr = ((SadlSimpleTypeReference)sadlTypeRef).getType();\n\t\t\ttry {\n\t\t\t\treturn getDeclarationExtensions().getOntConceptType(sr);\n\t\t\t} catch (CircularDefinitionException e) {\n\t\t\t\taddError(e.getMessage(), sadlTypeRef);\n\t\t\t\treturn e.getDefinitionType();\n\t\t\t}\n\t\t}\n\t\telse if (sadlTypeRef instanceof SadlPrimitiveDataType) {\n\t\t\treturn OntConceptType.DATATYPE;\n\t\t}\n\t\telse if (sadlTypeRef instanceof SadlPropertyCondition) {\n\t\t\t// property conditions => OntClass\n\t\t\treturn OntConceptType.CLASS;\n\t\t}\n\t\telse if (sadlTypeRef instanceof SadlUnionType) {\n\t\t\tSadlTypeReference lft = ((SadlUnionType)sadlTypeRef).getLeft();\n\t\t\tOntConceptType lfttype = getSadlTypeReferenceType(lft);\n\t\t\treturn lfttype;\n//\t\t\tSadlTypeReference rght = ((SadlUnionType)sadlTypeRef).getRight();\n\t\t}\n\t\telse if (sadlTypeRef instanceof SadlIntersectionType) {\n\t\t\tSadlTypeReference lft = ((SadlIntersectionType)sadlTypeRef).getLeft();\n\t\t\tOntConceptType lfttype = getSadlTypeReferenceType(lft);\n\t\t\treturn lfttype;\n//\t\t\tSadlTypeReference rght = ((SadlIntersectionType)sadlTypeRef).getRight();\n\t\t}\n\t\tthrow new JenaProcessorException(\"Unexpected SadlTypeReference subtype: \" + sadlTypeRef.getClass().getCanonicalName());\n\t}\n\n\tprotected String assureNamespaceEndsWithHash(String name) {\n\t\tname = name.trim();\n\t\tif (!name.endsWith(\"#\")) {\n\t\t\treturn name + \"#\";\n\t\t}\n\t\treturn name;\n\t}\n\n\tpublic String getModelNamespace() {\n\t\treturn modelNamespace;\n\t}\n\n\tprotected void setModelNamespace(String modelNamespace) {\n\t\tthis.modelNamespace = modelNamespace;\n\t}\n\n\tpublic OntDocumentManager getJenaDocumentMgr(OntModelSpec ontModelSpec) {\n\t\tif (jenaDocumentMgr == null) {\n\t\t\tif (getMappingModel() != null) {\n\t\t\t\tsetJenaDocumentMgr(new OntDocumentManager(getMappingModel()));\n\t\t\t\tif (ontModelSpec != null) {\n\t\t\t\t\tontModelSpec.setDocumentManager(jenaDocumentMgr);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tsetJenaDocumentMgr(OntDocumentManager.getInstance());\n\t\t\t}\n\t\t}\n\t\treturn jenaDocumentMgr;\n\t}\n\n\tprivate void setJenaDocumentMgr(OntDocumentManager ontDocumentManager) {\n\t\tjenaDocumentMgr = ontDocumentManager;\n\t}\n\n\tprivate Model getMappingModel() {\n\t\t// TODO Auto-generated method stub\n\t\treturn null;\n\t}\n\t\n\t/**\n\t * return true if the instance belongs to the class else return false\n\t * \n\t * @param inst\n\t * @param cls\n\t * @return\n\t * @throws JenaProcessorException \n\t */\n\tpublic boolean instanceBelongsToClass(OntModel m, OntResource inst, OntResource cls) throws JenaProcessorException {\n\t\t// The following cases must be considered:\n\t\t// 1) The class is a union of other classes. Check to see if the instance is a member of any of\n\t\t//\t\tthe union classes and if so return true.\n\t\t// 2) The class is an intersection of other classes. Check to see if the instance is \n\t\t//\t\ta member of each class in the intersection and if so return true.\n\t\t// 3) The class is neither a union nor an intersection. If the instance belongs to the class return true. Otherwise\n\t\t//\t\tcheck to see if the instance belongs to a subclass of the class else\n\t\t//\t\treturn false. (Superclasses do not need to be considered because even if the instance belongs to a super\n\t\t//\t\tclass that does not tell us that it belongs to the class.)\n\t\t\n\t\t/*\n\t\t * e.g., \tInternet is a Network.\n\t\t * \t\t\tNetwork is a type of Subsystem.\n\t\t * \t\t\tSubsystem is type of System.\n\t\t */\n\t\tif (cls.isURIResource()) {\n\t\t\tcls = m.getOntClass(cls.getURI());\n\t\t}\n\t\tif (cls == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (cls.canAs(UnionClass.class)) {\n\t\t\tList uclses = getOntResourcesInUnionClass(m, cls.as(UnionClass.class));\t\n\t\t\tfor (int i = 0; i < uclses.size(); i++) {\n\t\t\t\tOntResource ucls = uclses.get(i);\n\t\t\t\tif (instanceBelongsToClass(m, inst, ucls)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if (cls.canAs(IntersectionClass.class)) {\n\t\t\tList uclses = getOntResourcesInIntersectionClass(m, cls.as(IntersectionClass.class));\t\n\t\t\tfor (int i = 0; i < uclses.size(); i++) {\n\t\t\t\tOntResource ucls = uclses.get(i);\n\t\t\t\tif (!instanceBelongsToClass(m, inst, ucls)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\telse if (cls.canAs(Restriction.class)) {\n\t\t\tRestriction rest = cls.as(Restriction.class);\n\t\t\tOntProperty ontp = rest.getOnProperty();\t\t\t\t\n\t\t\tif (rest.isAllValuesFromRestriction()) {\n\t\t\t\tStmtIterator siter = inst.listProperties(ontp);\n\t\t\t\twhile (siter.hasNext()) {\n\t\t\t\t\tStatement stmt = siter.nextStatement();\n\t\t\t\t\tRDFNode obj = stmt.getObject();\n\t\t\t\t\tif (obj.canAs(Individual.class)) {\n\t\t\t\t\t\tcom.hp.hpl.jena.rdf.model.Resource avfc = rest.asAllValuesFromRestriction().getAllValuesFrom();\n\t\t\t\t\t\tif (!instanceBelongsToClass(m, (Individual)obj.as(Individual.class), (OntResource)avfc.as(OntResource.class))) {\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (rest.isSomeValuesFromRestriction()) {\n\t\t\t\tif (inst.hasProperty(ontp)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (rest.isHasValueRestriction()) {\n\t\t\t\tRDFNode hval = rest.as(HasValueRestriction.class).getHasValue();\n\t\t\t\tif (inst.hasProperty(ontp, hval)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (rest.isCardinalityRestriction()) {\n\t\t\t\tthrow new JenaProcessorException(\"Unhandled cardinality restriction\");\n\t\t\t}\n\t\t\telse if (rest.isMaxCardinalityRestriction()) {\n\t\t\t\tthrow new JenaProcessorException(\"Unhandled max cardinality restriction\");\n\t\t\t}\n\t\t\telse if (rest.isMinCardinalityRestriction()) {\n\t\t\t\tthrow new JenaProcessorException(\"Unhandled min cardinality restriction\");\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (inst.canAs(Individual.class)) {\n\t\t\t\tExtendedIterator eitr = inst.asIndividual().listRDFTypes(false);\n\t\t\t\twhile (eitr.hasNext()) {\n\t\t\t\t\tcom.hp.hpl.jena.rdf.model.Resource r = eitr.next();\t\t\t\t\n\t\t\t\t\tOntResource or = m.getOntResource(r);\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (or.isURIResource()) {\n\t\t\t\t\t\t\tOntClass oc = m.getOntClass(or.getURI());\n\t\t\t\t\t\t\tif (SadlUtils.classIsSubclassOf(oc, cls, true, null)) {\n\t\t\t\t\t\t\t\teitr.close();\n\t\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (or.canAs(OntClass.class)) {\n\t\t\t\t\t\t\tif (SadlUtils.classIsSubclassOf(or.as(OntClass.class), cls, true, null)) {\n\t\t\t\t\t\t\t\teitr.close();\n\t\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (CircularDependencyException e) {\n\t\t\t\t\t\tthrow new JenaProcessorException(e.getMessage(), e);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\tpublic List getOntResourcesInUnionClass(OntModel m, UnionClass ucls) {\n\t\tList results = new ArrayList();\n\t\tList clses = ucls.getOperands().asJavaList();\n\t\tfor (int i = 0; i < clses.size(); i++) {\n\t\t\tRDFNode mcls = clses.get(i);\n\t\t\tif (mcls.canAs(OntResource.class)) {\n\t\t\t\tif (mcls.canAs(UnionClass.class)){\n\t\t\t\t\tList innerList = getOntResourcesInUnionClass(m, mcls.as(UnionClass.class));\n\t\t\t\t\tfor (int j = 0; j < innerList.size(); j++) {\n\t\t\t\t\t\tOntResource innerRsrc = innerList.get(j);\n\t\t\t\t\t\tif (!results.contains(innerRsrc)) {\n\t\t\t\t\t\t\tresults.add(innerRsrc);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tresults.add(mcls.as(OntResource.class));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn results;\n\t}\n\t\n\tpublic List getOntResourcesInIntersectionClass(OntModel m, IntersectionClass icls) {\n\t\tList results = new ArrayList();\n\t\tList clses = icls.getOperands().asJavaList();\n\t\tfor (int i = 0; i < clses.size(); i++) {\n\t\t\tRDFNode mcls = clses.get(i);\n\t\t\tif (mcls.canAs(OntResource.class)) {\n\t\t\t\tresults.add(mcls.as(OntResource.class));\n\t\t\t}\n\t\t}\n\t\treturn results;\n\t}\n\n\tpublic ValidationAcceptor getIssueAcceptor() {\n\t\treturn issueAcceptor;\n\t}\n\n\tprotected void setIssueAcceptor(ValidationAcceptor issueAcceptor) {\n\t\tthis.issueAcceptor = issueAcceptor;\n\t}\n\n\tprivate CancelIndicator getCancelIndicator() {\n\t\treturn cancelIndicator;\n\t}\n\n\tprotected void setCancelIndicator(CancelIndicator cancelIndicator) {\n\t\tthis.cancelIndicator = cancelIndicator;\n\t}\n\n\tprotected String getModelName() {\n\t\treturn modelName;\n\t}\n\n\tprotected void setModelName(String modelName) {\n\t\tthis.modelName = modelName;\n\t}\n\n\t@Override\n\tpublic void processExternalModels(String mappingFileFolder, List fileNames) throws IOException {\n\t\tFile mff = new File(mappingFileFolder);\n\t\tif (!mff.exists()) {\n\t\t\tmff.mkdirs();\n\t\t}\n\t\tif (!mff.isDirectory()) {\n\t\t\tthrow new IOException(\"Mapping file location '\" + mappingFileFolder + \"' exists but is not a directory.\");\n\t\t}\n\t\tSystem.out.println(\"Ready to save mappings in folder: \" + mff.getCanonicalPath());\n\t\tfor (int i = 0; i < fileNames.size(); i++) {\n\t\t\tSystem.out.println(\" URL: \" + fileNames.get(i));\n\t\t}\n\t}\n\t\n\tpublic String getModelAlias() {\n\t\treturn modelAlias;\n\t}\n\t\n\tprotected void setModelAlias(String modelAlias) {\n\t\tthis.modelAlias = modelAlias;\n\t}\n\t\n\tprivate OntModelSpec getSpec() {\n\t\treturn spec;\n\t}\n\t\n\tprivate void setSpec(OntModelSpec spec) {\n\t\tthis.spec = spec;\n\t}\n\t\n\t/**\n\t * This method looks in the clauses of a Rule to see if there is already a triple matching the given pattern. If there is\n\t * a new variable of the same name is created (to make sure the count is right) and returned. If not a rule or no match\n\t * a new variable (new name) is created and returned.\n\t * @param expr \n\t * @param subject\n\t * @param predicate\n\t * @param object\n\t * @return\n\t */\n\tprotected VariableNode getVariableNode(Expression expr, Node subject, Node predicate, Node object) {\n\t\tif (getTarget() != null) {\n\t\t\t// Note: when we find a match we still create a new VariableNode with the same name in order to have the right reference counts for the new VariableNode\n\t\t\tif (getTarget() instanceof Rule) {\n\t\t\t\tVariableNode var = findVariableInTripleForReuse(((Rule)getTarget()).getGivens(), subject, predicate, object);\n\t\t\t\tif (var != null) {\n\t\t\t\t\treturn new VariableNode(var.getName());\n\t\t\t\t}\n\t\t\t\tvar = findVariableInTripleForReuse(((Rule)getTarget()).getIfs(), subject, predicate, object);\n\t\t\t\tif (var != null) {\n\t\t\t\t\treturn new VariableNode(var.getName());\n\t\t\t\t}\n\t\t\t\tvar = findVariableInTripleForReuse(((Rule)getTarget()).getThens(), subject, predicate, object);\n\t\t\t\tif (var != null) {\n\t\t\t\t\treturn new VariableNode(var.getName());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn new VariableNode(getNewVar(expr));\n\t}\n\t\n\tprotected String getNewVar(Expression expr) {\n\t\tIScopeProvider scopeProvider = ((XtextResource)expr.eResource()).getResourceServiceProvider().get(IScopeProvider.class);\n\t\tIScope scope = scopeProvider.getScope(expr, SADLPackage.Literals.SADL_RESOURCE__NAME);\n\t\tString proposedName = \"v\" + vNum;\n\t\twhile (userDefinedVariables.contains(proposedName)\n\t\t\t\t|| \tscope.getSingleElement(QualifiedName.create(proposedName)) != null) {\n\t\t\tvNum++;\n\t\t\tproposedName = \"v\" + vNum;\n\t\t}\n\t\tvNum++;\n\t\treturn proposedName;\n\t}\n\t\n\t/**\n\t * Supporting method for the method above (getVariableNode(Node, Node, Node))\n\t * @param gpes\n\t * @param subject\n\t * @param predicate\n\t * @param object\n\t * @return\n\t */\n\tprotected VariableNode findVariableInTripleForReuse(List gpes, Node subject, Node predicate, Node object) {\n\t\tif (gpes != null) {\n\t\t\tIterator itr = gpes.iterator();\n\t\t\twhile (itr.hasNext()) {\n\t\t\t\tGraphPatternElement gpe = itr.next();\n\t\t\t\twhile (gpe != null) {\n\t\t\t\t\tif (gpe instanceof TripleElement) {\n\t\t\t\t\t\tTripleElement tr = (TripleElement)gpe;\n\t\t\t\t\t\tNode tsn = tr.getSubject();\n\t\t\t\t\t\tNode tpn = tr.getPredicate();\n\t\t\t\t\t\tNode ton = tr.getObject();\n\t\t\t\t\t\tif (subject == null && tsn instanceof VariableNode) {\n\t\t\t\t\t\t\tif (predicate != null && predicate.equals(tpn) && object != null && object.equals(ton)) {\n\t\t\t\t\t\t\t\treturn (VariableNode) tsn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (predicate == null && tpn instanceof VariableNode) {\n\t\t\t\t\t\t\tif (subject != null && subject.equals(tsn) && object != null && object.equals(ton)) {\n\t\t\t\t\t\t\t\treturn (VariableNode) tpn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (object == null && ton instanceof VariableNode) {\n\t\t\t\t\t\t\tif (subject != null && subject.equals(tsn) && predicate != null && predicate.equals(tpn)) {\n\t\t\t\t\t\t\t\treturn (VariableNode) ton;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tgpe = gpe.getNext();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tpublic List getRules() {\n\t\treturn rules;\n\t}\n\t\t\n\tprivate java.nio.file.Path checkImplicitSadlModelExistence(Resource resource, ProcessorContext context) throws IOException, ConfigurationException, URISyntaxException, JenaProcessorException {\n\t\tUtilsForJena ufj = new UtilsForJena();\n\t\tString policyFileUrl = ufj.getPolicyFilename(resource);\n\t\tString policyFilename = policyFileUrl != null ? ufj.fileUrlToFileName(policyFileUrl) : null;\n\t\tif (policyFilename != null) {\n\t\t\tFile projectFolder = new File(policyFilename).getParentFile().getParentFile();\n\t\t\tString relPath = SadlConstants.SADL_IMPLICIT_MODEL_FOLDER + \"/\" + SadlConstants.SADL_IMPLICIT_MODEL_FILENAME;\n\t\t\tString platformPath = projectFolder.getName() + \"/\" + relPath;\n\t\t\tString implicitSadlModelFN = projectFolder + \"/\" + relPath;\n\t\t\tFile implicitModelFile = new File(implicitSadlModelFN);\n\t\t\tif (!implicitModelFile.exists()) {\n\t\t\t\tcreateSadlImplicitModel(implicitModelFile);\n\t\t\t\ttry {\n\t\t\t\t\tResource newRsrc = resource.getResourceSet().createResource(URI.createPlatformResourceURI(platformPath, false)); // createFileURI(implicitSadlModelFN));\n//\t\t\t\t\tnewRsrc.load(new StringInputStream(implicitModel), resource.getResourceSet().getLoadOptions());\n\t\t\t\t\tnewRsrc.load(resource.getResourceSet().getLoadOptions());\n\t\t\t\t\trefreshResource(newRsrc);\n\t\t\t\t}\n\t\t\t\tcatch (Throwable t) {}\n\t\t\t}\n\t\t\treturn implicitModelFile.getAbsoluteFile().toPath();\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tstatic public File createBuiltinFunctionImplicitModel(String projectRootPath) throws IOException, ConfigurationException{\n\t\t//First, obtain proper translator for project\n\t\tSadlUtils su = new SadlUtils();\n\t\tif(projectRootPath.startsWith(\"file\")){\n\t\t\tprojectRootPath = su.fileUrlToFileName(projectRootPath);\n\t\t}\n\t\tfinal File mfFolder = new File(projectRootPath + \"/\" + ResourceManager.OWLDIR);\n\t\tfinal String format = ConfigurationManager.RDF_XML_ABBREV_FORMAT;\n\t\tString fixedModelFolderName = mfFolder.getCanonicalPath().replace(\"\\\\\", \"/\");\n\t\tIConfigurationManagerForIDE configMgr = ConfigurationManagerForIdeFactory.getConfigurationManagerForIDE(fixedModelFolderName, format);\n\t\tITranslator translator = configMgr.getTranslator();\n\t\t//Second, obtain built-in function implicit model contents\n\t\tString builtinFunctionModel = translator.getBuiltinFunctionModel();\n\t\t//Third, create built-in function implicit model file\n\t\tFile builtinFunctionFile = new File(projectRootPath + \"/\" +\n\t\t\t\t\t\t\t\t\t\t\tSadlConstants.SADL_IMPLICIT_MODEL_FOLDER + \"/\" +\n\t\t\t\t\t\t\t\t\t\t\tSadlConstants.SADL_BUILTIN_FUNCTIONS_FILENAME);\t\n\t\tsu.stringToFile(builtinFunctionFile, builtinFunctionModel, true);\n\t\t\n\t\treturn builtinFunctionFile;\n\t}\n\t\n\tstatic public String getSadlBaseModel() {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tsb.append(\"\\n\");\n\t\tsb.append(\"\t \\n\");\n\t\tsb.append(\"\t Base model for SADL. These concepts can be used without importing.\\n\");\n\t\tsb.append(\"\t \\n\");\n\t\tsb.append(\"\t \\n\");\n\t\tsb.append(\"\t \\n\");\n\t\tsb.append(\"\t \\n\");\n\t\tsb.append(\"\t \\n\");\n\t\tsb.append(\"\t \\n\");\n\t\tsb.append(\"\t \\n\");\n\t\tsb.append(\"\t \\n\");\n\t\tsb.append(\"\t \\n\");\n\t\tsb.append(\"\t \\n\");\n\t\tsb.append(\"\t \\n\");\n\t\tsb.append(\"\t \\n\");\n\t\tsb.append(\"\t \\n\");\n\t\tsb.append(\"\t \\n\");\n\t\tsb.append(\"\t \\n\");\n\t\tsb.append(\"\\n\");\n\t\treturn sb.toString();\n\t}\n\t\n\tstatic public String getSadlListModel() {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" Typed List model for SADL.\\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\"\\n\");\n\t\treturn sb.toString();\n\t}\n\t\n\tstatic public String getSadlDefaultsModel() {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tsb.append(\"\\n\");\n\t\tsb.append(\"\\n\");\n\t\tsb.append(\"\t\\n\");\n\t\tsb.append(\"\t Copyright 2007, 2008, 2009 - General Electric Company, All Rights Reserved\\n\");\n\t\tsb.append(\"\t $Id: defaults.owl,v 1.1 2014/01/23 21:52:26 crapo Exp $\\n\");\n\t\tsb.append(\"\t\\n\");\n\t\tsb.append(\"\t\\n\");\n\t\tsb.append(\"\t\tThis type of default has a value which is a Literal\\n\");\n\t\tsb.append(\"\t\t\\n\");\n\t\tsb.append(\"\t\t\t\\n\");\n\t\tsb.append(\"\t\t\\n\");\n\t\tsb.append(\"\t\\n\");\n\t\tsb.append(\"\t\\n\");\n\t\tsb.append(\"\t\tThis type of default has a value which is an Individual\\n\");\n\t\tsb.append(\"\t\t\\n\");\n\t\tsb.append(\"\t\t\t\\n\");\n\t\tsb.append(\"\t\t\\n\");\n\t\tsb.append(\"\t\\n\");\n\t\tsb.append(\"\t\\n\");\n\t\tsb.append(\"\t\t\\n\");\n\t\tsb.append(\"\t\t\\n\");\n\t\tsb.append(\"\t\t\\n\");\n\t\tsb.append(\"\t\\n\");\n\t\tsb.append(\"\t\\n\");\n\t\tsb.append(\"\t\t\\n\");\n\t\tsb.append(\"\t\t\\n\");\n\t\tsb.append(\"\t\\n\");\n\t\tsb.append(\"\t\\n\");\n\t\tsb.append(\"\t\t\\n\");\n\t\tsb.append(\"\t\t\\n\");\n\t\tsb.append(\"\t\\n\");\n\t\tsb.append(\"\t\\n\");\n\t\tsb.append(\"\t\tThe value of this Property is the Property to which the default value applies.\\n\");\n\t\tsb.append(\"\t\t\\n\");\n\t\tsb.append(\"\t\t\\n\");\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsb.append(\"\t\t\");\n\t\tsb.append(\"\t\\n\");\n\t\tsb.append(\"\\n\");\n\t\treturn sb.toString();\n\t}\n\t\n\tprivate boolean importSadlListModel(Resource resource) throws JenaProcessorException, ConfigurationException {\n\t\tif (sadlListModel == null) {\n\t\t\ttry {\n\t\t\t\tsadlListModel = getOntModelFromString(resource, getSadlListModel());\n\t\t\t\tOntModelProvider.setSadlListModel(sadlListModel);\n\t\t\t} catch (Exception e) {\n\t\t\t\tthrow new JenaProcessorException(e.getMessage(), e);\n\t\t\t}\n\t\t\taddImportToJenaModel(getModelName(), SadlConstants.SADL_LIST_MODEL_URI, SadlConstants.SADL_LIST_MODEL_PREFIX, sadlListModel);\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tpublic OntModel getOntModelFromString(Resource resource, String serializedModel)\n\t\t\tthrows IOException, ConfigurationException, URISyntaxException, JenaProcessorException {\n\t\tOntModel listModel = prepareEmptyOntModel(resource);\n\t\tInputStream stream = new ByteArrayInputStream(serializedModel.getBytes());\n\t\tlistModel.read(stream, null);\n\t\treturn listModel;\n\t}\n\t\n\tprivate boolean importSadlDefaultsModel(Resource resource) throws JenaProcessorException, ConfigurationException {\n\t\tif (sadlDefaultsModel == null) {\n\t\t\ttry {\n\t\t\t\tsadlDefaultsModel = getOntModelFromString(resource, getSadlDefaultsModel());\n\t\t\t\tOntModelProvider.setSadlDefaultsModel(sadlDefaultsModel);\n\t\t\t} catch (Exception e) {\n\t\t\t\tthrow new JenaProcessorException(e.getMessage(), e);\n\t\t\t}\n\t\t\taddImportToJenaModel(getModelName(), SadlConstants.SADL_DEFAULTS_MODEL_URI, SadlConstants.SADL_DEFAULTS_MODEL_PREFIX, sadlDefaultsModel);\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprotected IConfigurationManagerForIDE getConfigMgr(Resource resource, String format) throws ConfigurationException {\n\t\tif (configMgr == null) {\n\t\t\tString modelFolderPathname = getModelFolderPath(resource);\n\t\t\tif (format == null) {\n\t\t\t\tformat = ConfigurationManager.RDF_XML_ABBREV_FORMAT; // default\n\t\t\t}\n\t\t\tif (isSyntheticUri(modelFolderPathname, resource)) {\n\t\t\t\tmodelFolderPathname = null;\n\t\t\t\tconfigMgr = ConfigurationManagerForIdeFactory.getConfigurationManagerForIDE(modelFolderPathname, format, true);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconfigMgr = ConfigurationManagerForIdeFactory.getConfigurationManagerForIDE(modelFolderPathname , format);\n\t\t\t}\n\t\t}\n\t\treturn configMgr;\n\t}\n\t\n\tprotected boolean isSyntheticUri(String modelFolderPathname, Resource resource) {\n\t\tif ((modelFolderPathname == null && \n\t\t\t\tresource.getURI().toString().startsWith(\"synthetic\")) ||\n\t\t\t\t\t\tresource.getURI().toString().startsWith(SYNTHETIC_FROM_TEST)) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprotected IConfigurationManagerForIDE getConfigMgr() {\n\t\treturn configMgr;\n\t}\n\t\n\tprotected boolean isBooleanOperator(String op) {\n\t\tOPERATORS_RETURNING_BOOLEAN[] ops = OPERATORS_RETURNING_BOOLEAN.values();\n\t\tfor (int i = 0; i < ops.length; i++) {\n\t\t\tif (op.equals(ops[i].toString())) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprotected boolean isConjunction(String op) {\n\t\tif (op.equals(\"and\")) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprotected void resetProcessorState(SadlModelElement element) throws InvalidTypeException {\n\t\ttry {\n\t\t\tif (getModelValidator() != null) {\n\t\t\t\tgetModelValidator().resetValidatorState(element);\n\t\t\t}\n\t\t} catch (TranslationException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\tpublic List getEquations() {\n\t\treturn equations;\n\t}\n\t\n\tpublic void setEquations(List equations) {\n\t\tthis.equations = equations;\n\t}\n\t\n\tprotected boolean isClass(OntConceptType oct){\n\t\tif(oct.equals(OntConceptType.CLASS)){\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprotected boolean isProperty(NodeType oct) {\n\t\tif (oct.equals(NodeType.ObjectProperty) || \n\t\t\t\toct.equals(NodeType.DataTypeProperty) || \n\t\t\t\toct.equals(NodeType.PropertyNode)){\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprotected boolean isProperty(OntConceptType oct) {\n\t\tif (oct.equals(OntConceptType.DATATYPE_PROPERTY) || \n\t\t\t\toct.equals(OntConceptType.CLASS_PROPERTY) || \n\t\t\t\toct.equals(OntConceptType.RDF_PROPERTY) || \n\t\t\t\toct.equals(OntConceptType.ANNOTATION_PROPERTY)){\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic SadlCommand getTargetCommand() {\n\t\treturn targetCommand;\n\t}\n\t\n\tpublic ITranslator getTranslator() throws ConfigurationException {\n\t\tIConfigurationManagerForIDE cm = getConfigMgr(getCurrentResource(), getOwlModelFormat(getProcessorContext()));\n\t\tif (cm.getTranslatorClassName() == null) {\n\t\t\tcm.setTranslatorClassName(translatorClassName );\n\t\t\tcm.setReasonerClassName(reasonerClassName);\n\t\t}\n\t\treturn cm.getTranslator();\n\t}\n\t\n\t/**\n\t * Method to obtain the sadlimplicitmodel:impliedProperty annotation property values for the given class\n\t * @param cls -- the Jena Resource (nominally a class) for which the values are desired\n\t * @return -- a List of the ConceptNames of the values \n\t */\n\tpublic List getImpliedProperties(com.hp.hpl.jena.rdf.model.Resource cls) {\n\t\tList retlst = null;\n\t\tif (cls == null) return null;\n\t\tif (!cls.isURIResource()) return null;\t// impliedProperties can only be given to a named class\n\t\tif (!cls.canAs(OntClass.class)) {\n\t\t\taddError(\"Can't get implied properties of a non-class entity.\", null);\n\t\t\treturn null; \n\t\t}\n\t\tList allImplPropClasses = getAllImpliedPropertyClasses();\n\t\tif (allImplPropClasses != null) {\n\t\t\tfor (OntResource ipcls : allImplPropClasses) {\n\t\t\t\ttry {\n\t\t\t\t\tif (SadlUtils.classIsSubclassOf(cls.as(OntClass.class), ipcls, true, null)) {\n\t\t\t\t\t\tStmtIterator sitr = getTheJenaModel().listStatements(ipcls, getTheJenaModel().getProperty(SadlConstants.SADL_IMPLICIT_MODEL_IMPLIED_PROPERTY_URI), (RDFNode)null);\n\t\t\t\t\t\tif (sitr.hasNext()) {\n\t\t\t\t\t\t\tif (retlst == null) {\n\t\t\t\t\t\t\t\tretlst = new ArrayList();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\twhile (sitr.hasNext()) {\n\t\t\t\t\t\t\t\tRDFNode obj = sitr.nextStatement().getObject();\n\t\t\t\t\t\t\t\tif (obj.isURIResource()) {\n\t\t\t\t\t\t\t\t\tConceptName cn = new ConceptName(obj.asResource().getURI());\n\t\t\t\t\t\t\t\t\tif (!retlst.contains(cn)) {\n\t\t\t\t\t\t\t\t\t\tretlst.add(cn);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} catch (CircularDependencyException e) {\n\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\t\n\t\t\t}\n\t\t}\n//\t\t// check superclasses\n//\t\tif (cls.canAs(OntClass.class)) {\n//\t\t\tOntClass ontcls = cls.as(OntClass.class);\n//\t\t\tExtendedIterator eitr = ontcls.listSuperClasses();\n//\t\t\twhile (eitr.hasNext()) {\n//\t\t\t\tOntClass supercls = eitr.next();\n//\t\t\t\tList scips = getImpliedProperties(supercls);\n//\t\t\t\tif (scips != null) {\n//\t\t\t\t\tif (retlst == null) {\n//\t\t\t\t\t\tretlst = scips;\n//\t\t\t\t\t}\n//\t\t\t\t\telse {\n//\t\t\t\t\t\tfor (int i = 0; i < scips.size(); i++) {\n//\t\t\t\t\t\t\tConceptName cn = scips.get(i);\n//\t\t\t\t\t\t\tif (!scips.contains(cn)) {\n//\t\t\t\t\t\t\t\tretlst.add(scips.get(i));\n//\t\t\t\t\t\t\t}\n//\t\t\t\t\t\t}\n//\t\t\t\t\t}\n//\t\t\t\t}\n//\t\t\t}\n//\t\t}\n//\t\tStmtIterator sitr = getTheJenaModel().listStatements(cls, getTheJenaModel().getProperty(SadlConstants.SADL_IMPLICIT_MODEL_IMPLIED_PROPERTY_URI), (RDFNode)null);\n//\t\tif (sitr.hasNext()) {\n//\t\t\tif (retlst == null) {\n//\t\t\t\tretlst = new ArrayList();\n//\t\t\t}\n//\t\t\twhile (sitr.hasNext()) {\n//\t\t\t\tRDFNode obj = sitr.nextStatement().getObject();\n//\t\t\t\tif (obj.isURIResource()) {\n//\t\t\t\t\tConceptName cn = new ConceptName(obj.asResource().getURI());\n//\t\t\t\t\tif (!retlst.contains(cn)) {\n//\t\t\t\t\t\tretlst.add(cn);\n//\t\t\t\t\t}\n//\t\t\t\t}\n//\t\t\t}\n//\t\t\treturn retlst;\n//\t\t}\n////\t\tif (retlst == null && cls.isURIResource() && cls.getURI().endsWith(\"#DATA\")) {\n//////\t\t\tdumpModel(getTheJenaModel());\n//////\t\t\tStmtIterator stmtitr = cls.listProperties();\n////\t\t\tStmtIterator stmtitr = getTheJenaModel().listStatements(cls, null, (RDFNode)null);\n////\t\t\twhile (stmtitr.hasNext()) {\n////\t\t\t\tSystem.out.println(stmtitr.next().toString());\n////\t\t\t}\n////\t\t}\n\t\treturn retlst;\n\t}\n\t\n\tprivate List getAllImpliedPropertyClasses() {\n\t\treturn allImpliedPropertyClasses;\n\t}\n\t\n\tprotected int initializeAllImpliedPropertyClasses () {\n\t\tint cntr = 0;\n\t\tallImpliedPropertyClasses = new ArrayList();\n\t\tStmtIterator sitr = getTheJenaModel().listStatements(null, getTheJenaModel().getProperty(SadlConstants.SADL_IMPLICIT_MODEL_IMPLIED_PROPERTY_URI), (RDFNode)null);\n\t\tif (sitr.hasNext()) {\n\t\t\twhile (sitr.hasNext()) {\n\t\t\t\tcom.hp.hpl.jena.rdf.model.Resource subj = sitr.nextStatement().getSubject();\n\t\t\t\tif (subj.canAs(OntResource.class)) {\n\t\t\t\t\tOntResource or = subj.as(OntResource.class);\n\t\t\t\t\tif (!allImpliedPropertyClasses.contains(or)) {\n\t\t\t\t\t\tallImpliedPropertyClasses.add(or);\n\t\t\t\t\t\tcntr++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn cntr;\n\t}\n\t\n\t/**\n\t * Method to obtain the sadlimplicitmodel:expandedProperty annotation property values for the given class\n\t * @param cls -- the Jena Resource (nominally a class) for which the values are desired\n\t * @return -- a List of the URI strings of the values \n\t */\n\tpublic List getExpandedProperties(com.hp.hpl.jena.rdf.model.Resource cls) {\n\t\tList retlst = null;\n\t\tif (cls == null) return null;\n\t\t// check superclasses\n\t\tif (cls.canAs(OntClass.class)) {\n\t\t\tOntClass ontcls = cls.as(OntClass.class);\n\t\t\tExtendedIterator eitr = ontcls.listSuperClasses();\n\t\t\twhile (eitr.hasNext()) {\n\t\t\t\tOntClass supercls = eitr.next();\n\t\t\t\tList scips = getExpandedProperties(supercls);\n\t\t\t\tif (scips != null) {\n\t\t\t\t\tif (retlst == null) {\n\t\t\t\t\t\tretlst = scips;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tfor (int i = 0; i < scips.size(); i++) {\n\t\t\t\t\t\t\tString cn = scips.get(i);\n\t\t\t\t\t\t\tif (!scips.contains(cn)) {\n\t\t\t\t\t\t\t\tretlst.add(scips.get(i));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tStmtIterator sitr = getTheJenaModel().listStatements(cls, getTheJenaModel().getProperty(SadlConstants.SADL_IMPLICIT_MODEL_EXPANDED_PROPERTY_URI), (RDFNode)null);\n\t\tif (sitr.hasNext()) {\n\t\t\tif (retlst == null) {\n\t\t\t\tretlst = new ArrayList();\n\t\t\t}\n\t\t\twhile (sitr.hasNext()) {\n\t\t\t\tRDFNode obj = sitr.nextStatement().getObject();\n\t\t\t\tif (obj.isURIResource()) {\n\t\t\t\t\tString cn = obj.asResource().getURI();\n\t\t\t\t\tif (!retlst.contains(cn)) {\n\t\t\t\t\t\tretlst.add(cn);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn retlst;\n\t\t}\n\t\treturn retlst;\n\t}\n\t\n\tprotected boolean isLookingForFirstProperty() {\n\t\treturn lookingForFirstProperty;\n\t}\n\n\tprotected void setLookingForFirstProperty(boolean lookingForFirstProperty) {\n\t\tthis.lookingForFirstProperty = lookingForFirstProperty;\n\t}\n\t\n\tpublic Equation getCurrentEquation() {\n\t\treturn currentEquation;\n\t}\n\t\n\tprotected void setCurrentEquation(Equation currentEquation) {\n\t\tthis.currentEquation = currentEquation;\n\t}\n\t\n\tpublic JenaBasedSadlModelValidator getModelValidator() throws TranslationException {\n\t\treturn modelValidator;\n\t}\n\t\n\tprotected void setModelValidator(JenaBasedSadlModelValidator modelValidator) {\n\t\tthis.modelValidator = modelValidator;\n\t}\n\n\tprotected void initializeModelValidator(){\n\t\tsetModelValidator(new JenaBasedSadlModelValidator(issueAcceptor, getTheJenaModel(), getDeclarationExtensions(), this, getMetricsProcessor()));\n\t}\n\t\n\tprotected IMetricsProcessor getMetricsProcessor() {\n\t\treturn metricsProcessor;\n\t}\n\t\n\tprotected void setMetricsProcessor(IMetricsProcessor metricsProcessor) {\n\t\tthis.metricsProcessor = metricsProcessor;\n\t}\n\n\tprotected String rdfNodeToString(RDFNode node) {\n\t\tif (node.isLiteral()) {\n\t\t\treturn node.asLiteral().getValue().toString();\n\t\t}\n\t\telse if (node.isURIResource() && getConfigMgr() != null) {\n\t\t\tString prefix = getConfigMgr().getGlobalPrefix(node.asResource().getNameSpace());\n\t\t\tif (prefix != null) {\n\t\t\t\treturn prefix + \":\" + node.asResource().getLocalName();\n\t\t\t}\n\t\t}\n\t\treturn node.toString();\n\t}\n\n\tprotected String conceptIdentifierToString(ConceptIdentifier ci) {\n\t\tif (ci instanceof ConceptName) {\n\t\t\tif (getConfigMgr() != null && ((ConceptName)ci).getPrefix() == null && ((ConceptName)ci).getNamespace() != null) {\n\t\t\t\tString ns = ((ConceptName)ci).getNamespace();\n\t\t\t\tif (ns.endsWith(\"#\")) {\n\t\t\t\t\tns = ns.substring(0, ns.length() - 1);\n\t\t\t\t}\n\t\t\t\tString prefix = getConfigMgr().getGlobalPrefix(ns);\n\t\t\t\tif (prefix == null) {\n\t\t\t\t\treturn ((ConceptName)ci).getName();\n\t\t\t\t}\n\t\t\t\t((ConceptName)ci).setPrefix(prefix);\n\t\t\t}\n\t\t\treturn ((ConceptName)ci).toString();\n\t\t}\n\t\treturn ci.toString();\n\t}\n\t\n\tpublic boolean isNumericComparisonOperator(String operation) {\n\t\tif (numericComparisonOperators.contains(operation)) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tpublic boolean isEqualityInequalityComparisonOperator(String operation) {\n\t\tif (equalityInequalityComparisonOperators.contains(operation)) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tpublic boolean isComparisonOperator(String operation) {\n\t\tif (comparisonOperators.contains(operation)) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic boolean isBooleanComparison(List operations) {\n\t\tif(comparisonOperators.containsAll(operations)){\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic boolean canBeNumericOperator(String op) {\n\t\tif (canBeNumericOperators.contains(op)) return true;\n\t\treturn false;\n\t}\n\n\tpublic boolean isNumericOperator(String op) {\n\t\tif (numericOperators.contains(op)) return true;\n\t\treturn false;\n\t}\n\n\tpublic boolean isNumericOperator(List operations) {\n\t\tIterator itr = operations.iterator();\n\t\twhile (itr.hasNext()) {\n\t\t\tif (isNumericOperator(itr.next())) return true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic boolean canBeNumericOperator(List operations) {\n\t\tIterator itr = operations.iterator();\n\t\twhile (itr.hasNext()) {\n\t\t\tif (canBeNumericOperator(itr.next())) return true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tpublic boolean isNumericType(ConceptName conceptName) {\n\t\ttry {\n\t\t\tif (conceptName.getName().equals(\"known\") && conceptName.getNamespace() == null) {\n\t\t\t\t// known matches everything\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tString uri = conceptName.getUri();\n\t\t\treturn isNumericType(uri);\n\t\t} catch (InvalidNameException e) {\n\t\t\t// OK, some constants don't have namespace and so aren't numeric\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic boolean isNumericType(String uri) {\n\t\tif (uri.equals(XSD.decimal.getURI()) ||\n\t\t\t\turi.equals(XSD.integer.getURI()) ||\n\t\t\t\turi.equals(XSD.xdouble.getURI()) ||\n\t\t\t\turi.equals(XSD.xfloat.getURI()) ||\n\t\t\t\turi.equals(XSD.xint.getURI()) ||\n\t\t\t\turi.equals(XSD.xlong.getURI())) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic boolean isBooleanType(String uri) {\n\t\tif (uri.equals(XSD.xboolean.getURI())) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\tprotected void setOwlFlavor(OWL_FLAVOR owlFlavor) {\n\t\tthis.owlFlavor = owlFlavor;\n\t}\n\tprotected boolean isTypeCheckingWarningsOnly() {\n\t\treturn typeCheckingWarningsOnly;\n\t}\n\tprotected void setTypeCheckingWarningsOnly(boolean typeCheckingWarningsOnly) {\n\t\tthis.typeCheckingWarningsOnly = typeCheckingWarningsOnly;\n\t}\n\n\tprotected boolean isBinaryListOperator(String op) {\n\t\tif (op.equals(\"contain\") || op.equals(\"contains\") || op.equals(\"unique\")) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\tprotected boolean sharedDisjunctiveContainer(Expression expr1, Expression expr2) {\n\t\tif (expr1 != null) {\n\t\t\tEObject cont1 = expr1.eContainer();\n\t\t\tdo {\n\t\t\t\tif (cont1 instanceof BinaryOperation && ((BinaryOperation)cont1).getOp().equals(\"or\")) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcont1 = cont1.eContainer();\n\t\t\t} while (cont1 != null && cont1.eContainer() != null);\n\t\n\t\t\tif (expr2 != null) {\n\t\t\t\tEObject cont2 = expr2;\n\t\t\t\tdo {\n\t\t\t\t\tif (cont2 instanceof BinaryOperation && ((BinaryOperation)cont2).getOp().equals(\"or\")) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcont2 = cont2.eContainer();\n\t\t\t\t} while (cont2 != null && cont2.eContainer() != null);\n\t\t\t\tif (cont1 != null && cont2 != null && cont1.equals(cont2)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tpublic boolean isTypedListSubclass(RDFNode node) {\n\t\tif (node != null && node.isResource()) {\n\t\t\tif (node.asResource().hasProperty(RDFS.subClassOf, theJenaModel.getResource(SadlConstants.SADL_LIST_MODEL_LIST_URI))) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprotected boolean isEqualOperator(String op) {\n\t\tBuiltinType optype = BuiltinType.getType(op);\n\t\tif (optype.equals(BuiltinType.Equal)) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tpublic DeclarationExtensions getDeclarationExtensions() {\n\t\treturn declarationExtensions;\n\t}\n\t\n\tpublic void setDeclarationExtensions(DeclarationExtensions declarationExtensions) {\n\t\tthis.declarationExtensions = declarationExtensions;\n\t}\n\tprotected void addNamedStructureAnnotations(Individual namedStructure, EList annotations) throws TranslationException {\n\t\tIterator annitr = annotations.iterator();\n\t\tif (annitr.hasNext()) {\n\t\t\twhile (annitr.hasNext()) {\n\t\t\t\tNamedStructureAnnotation ra = annitr.next();\n\t\t\t\tString annuri = getDeclarationExtensions().getConceptUri(ra.getType());\n\t\t\t\tProperty annProp = getTheJenaModel().getProperty(annuri);\n\t\t\t\ttry {\n\t\t\t\t\tif (annProp == null || !isProperty(getDeclarationExtensions().getOntConceptType(ra.getType()))) {\n\t\t\t\t\t\tissueAcceptor.addError(\"Annotation property '\" + annuri + \"' not found in model\", ra);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t} catch (CircularDefinitionException e1) {\n\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\te1.printStackTrace();\n\t\t\t\t}\n\t\t\t\tIterator cntntitr = ra.getContents().iterator();\n\t\t\t\tStringBuilder sb = new StringBuilder();\n\t\t\t\tint cntr = 0;\n\t\t\t\twhile (cntntitr.hasNext()) {\n\t\t\t\t\tSadlExplicitValue annvalue = cntntitr.next();\n\t\t\t\t\tif (annvalue instanceof SadlResource) {\n\t\t\t\t\t\tNode n = processExpression((SadlResource)annvalue);\n\t\t\t\t\t\tOntResource nor = getTheJenaModel().getOntResource(n.toFullyQualifiedString());\n\t\t\t\t\t\tif (nor != null) {\t\t// can be null during entry of statement in editor\n\t\t\t\t\t\t\tgetTheJenaModel().add(namedStructure, annProp, nor);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tcom.hp.hpl.jena.ontology.OntResource range = annProp.canAs(OntProperty.class) ? annProp.as(OntProperty.class).getRange() : null;\n\t\t\t\t\t\t\tcom.hp.hpl.jena.rdf.model.Literal annLiteral = sadlExplicitValueToLiteral(annvalue, range);\n\t\t\t\t\t\t\tgetTheJenaModel().add(namedStructure, annProp, annLiteral);\n\t\t\t\t\t\t\tif (cntr > 0) sb.append(\", \");\n\t\t\t\t\t\t\tsb.append(\"\\\"\");\n\t\t\t\t\t\t\tsb.append(annvalue);\n\t\t\t\t\t\t\tsb.append(\"\\\"\");\n\t\t\t\t\t\t\tcntr++;\n\t\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t\t} //getTheJenaModel().createTypedLiteral(annvalue);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlogger.debug(\"Named structure annotation: \" + getDeclarationExtensions().getConceptUri(ra.getType()) + \" = \" + sb.toString());\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprotected Declaration getDeclarationFromSubjHasProp(SubjHasProp subject) {\n\t\tExpression left = subject.getLeft();\n\t\tif (left instanceof Declaration) {\n\t\t\treturn (Declaration)left;\n\t\t}\n\t\telse if (left instanceof SubjHasProp) {\n\t\t\treturn getDeclarationFromSubjHasProp((SubjHasProp)left);\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprotected VariableNode getCruleVariable(NamedNode type, int ordNum) {\n\t\tList existingList = cruleVariables != null ? cruleVariables.get(type) : null;\n\t\tif (existingList != null && ordNum >= 0 && ordNum <= existingList.size()) {\n\t\t\treturn existingList.get(ordNum -1);\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprotected VariableNode addCruleVariable(NamedNode type, int ordinalNumber, String name, EObject expr, EObject host) throws TranslationException {\n\t\tif (cruleVariables == null) {\n\t\t\tcruleVariables = new HashMap>();\n\t\t}\n\t\tif (!cruleVariables.containsKey(type)) {\n\t\t\tList newList = new ArrayList();\n\t\t\tVariableNode var = new VariableNode(name);\n\t\t\tvar.setCRulesVariable(true);\n\t\t\tvar.setType(type);\n\t\t\tvar.setHostObject(getHostEObject());\n\t\t\tnewList.add(var);\n\t\t\tcruleVariables.put(type, newList);\n\t\t\treturn var;\n\t\t}\n\t\telse {\n\t\t\tList existingList = cruleVariables.get(type);\n\t\t\tIterator nodeitr = existingList.iterator();\n\t\t\twhile (nodeitr.hasNext()) {\n\t\t\t\tif (nodeitr.next().getName().equals(name)) {\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t}\n\t\t\tint idx = existingList.size();\n\t\t\tif (idx == ordinalNumber - 1) {\n\t\t\t\tVariableNode var = new VariableNode(name);\n\t\t\t\tvar.setCRulesVariable(true);\n\t\t\t\tvar.setType(type);\n\t\t\t\tvar.setHostObject(getHostEObject());\n\t\t\t\texistingList.add(var);\n\t\t\t\treturn var;\n\t\t\t}\n\t\t\telse {\n\t\t\t\taddError(\"There is already an implicit variable with ordinality \" + ordinalNumber + \". Please use 'a \" + nextOrdinal(ordinalNumber) + \n\t\t\t\t\t\t\"' to create another implicit variable or 'the \" + nextOrdinal(ordinalNumber - 1) + \"' to refer to the existing implicit variable.\", expr);\n\t\t\t\treturn existingList.get(existingList.size() - 1);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprotected void clearCruleVariables() {\n\t\tif (cruleVariables != null) {\n\t\t\tcruleVariables.clear();\n\t\t}\n\t\tvNum = 0;\t// reset system-generated variable name counter\n\t}\n\t\n\tprotected void clearCruleVariablesForHostObject(EObject host) {\n\t\tif (cruleVariables != null) {\n\t\t\tIterator crvitr = cruleVariables.keySet().iterator();\n\t\t\twhile (crvitr.hasNext()) {\n\t\t\t\tList varsOfType = cruleVariables.get(crvitr.next());\n\t\t\t\tfor (int i = varsOfType.size() - 1; i >= 0; i--) {\n\t\t\t\t\tif (varsOfType.get(i).getHostObject() != null && varsOfType.get(i).getHostObject().equals(host)) {\n\t\t\t\t\t\tvarsOfType.remove(i);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprotected void processModelImports(Ontology modelOntology, URI importingResourceUri, SadlModel model) throws OperationCanceledError {\n\t\tEList implist = model.getImports();\n\t\tIterator impitr = implist.iterator();\n\t\twhile (impitr.hasNext()) {\n\t\t\tSadlImport simport = impitr.next();\n\t\t\tSadlModel importedResource = simport.getImportedResource();\n\t\t\tif (importedResource != null) {\n\t\t\t\t//\t\t\t\t\tURI importingResourceUri = resource.getURI();\n\t\t\t\tString importUri = importedResource.getBaseUri();\n\t\t\t\tString importPrefix = simport.getAlias();\n\t\t\t\tResource eResource = importedResource.eResource();\n\t\t\t\tif (eResource instanceof XtextResource) {\n\t\t\t\t\tXtextResource xtrsrc = (XtextResource) eResource;\n\t\t\t\t\tURI importedResourceUri = xtrsrc.getURI();\n\t\t\t\t\tOntModel importedOntModel = OntModelProvider.find(xtrsrc);\n\t\t\t\t\tif (importedOntModel == null) {\n\t\t\t\t\t\tlogger.debug(\"JenaBasedSadlModelProcessor failed to resolve null OntModel for Resource '\" + importedResourceUri + \"' while processing Resource '\" + importingResourceUri + \"'\");\n\t\t\t\t\t} else {\n\t\t\t\t\t\taddImportToJenaModel(modelName, importUri, importPrefix, importedOntModel);\t\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t} else if (eResource instanceof ExternalEmfResource) {\n\t\t\t\t\tExternalEmfResource emfResource = (ExternalEmfResource) eResource;\n\t\t\t\t\taddImportToJenaModel(modelName, importUri, importPrefix, emfResource.getJenaModel());\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t}\n\n\t//\tprotected Literal sadlExplicitValueToLiteral(SadlExplicitValue value, OntProperty prop) throws JenaProcessorException, TranslationException {\n\tprotected boolean isEObjectPreprocessed(EObject eobj) {\n\t\tif (preprocessedEObjects != null && preprocessedEObjects.contains(eobj)) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprotected boolean eobjectPreprocessed(EObject eobj) {\n\t\tif (preprocessedEObjects == null) {\n\t\t\tpreprocessedEObjects = new ArrayList();\n\t\t\tpreprocessedEObjects.add(eobj);\n\t\t\treturn true;\n\t\t}\n\t\tif (preprocessedEObjects.contains(eobj)) {\n\t\t\treturn false;\n\t\t}\n\t\tpreprocessedEObjects.add(eobj);\n\t\treturn true;\n\t}\n\t\n//\tprotected Literal sadlExplicitValueToLiteral(SadlExplicitValue value, OntProperty prop) throws JenaProcessorException, TranslationException {\n//\t\tif (value instanceof SadlNumberLiteral) {\n//\t\t\tString strval = ((SadlNumberLiteral)value).getLiteralNumber();\n//\t\t\treturn SadlUtils.getLiteralMatchingDataPropertyRange(getTheJenaModel(), prop, strval);\n//\t\t}\n//\t\telse if (value instanceof SadlStringLiteral) {\n//\t\t\tString val = ((SadlStringLiteral)value).getLiteralString();\n//\t\t\treturn SadlUtils.getLiteralMatchingDataPropertyRange(getTheJenaModel(), prop, val);\n//\t\t}\n//\t\telse if (value instanceof SadlBooleanLiteral) {\n//\t\t\tSadlBooleanLiteral val = ((SadlBooleanLiteral)value);\n//\t\t\treturn SadlUtils.getLiteralMatchingDataPropertyRange(getTheJenaModel(), prop, val.toString());\n//\t\t}\n//\t\telse if (value instanceof SadlValueList) {\n//\t\t\tthrow new JenaProcessorException(\"A SADL value list cannot be converted to a Literal\");\n//\t\t}\n//\t\telse if (value instanceof SadlConstantLiteral) {\n//\t\t\tString val = ((SadlConstantLiteral)value).getTerm();\n//\t\t\treturn SadlUtils.getLiteralMatchingDataPropertyRange(getTheJenaModel(), prop, val);\n//\t\t}\n//\t\telse {\n//\t\t\tthrow new JenaProcessorException(\"Unhandled sadl explicit vaue type: \" + value.getClass().getCanonicalName());\n//\t\t}\n//\t}\n\n\tprotected void checkShallForControlledProperty(Expression expr) {\n\t\tOntConceptType exprType = null;\n\t\tSadlResource sr = null;\n\t\tif (expr instanceof Name) {\n\t\t\tsr = ((Name)expr).getName();\n\t\t}\n\t\telse if (expr instanceof SadlResource) {\n\t\t\tsr = (SadlResource) expr;\n\t\t}\n\t\tif (sr != null) {\n\t\t\ttry {\n\t\t\t\texprType = getDeclarationExtensions().getOntConceptType(sr);\n\t\t\t\tif (!isProperty(exprType)) {\n\t\t\t\t\taddError(\"Expected a property as controlled variable in a Requirement shall statement\", expr);\n\t\t\t\t}\n\t\t\t} catch (CircularDefinitionException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected List getControlledPropertiesForTable(Expression expr) {\n\t\tList results = new ArrayList();\n\t\tif (expr instanceof Name) {\n\t\t\tresults.add(((Name)expr).getName());\n\t\t}\n\t\telse if (expr instanceof SadlResource) {\n\t\t\tresults.add((SadlResource) expr);\n\t\t}\n\t\telse if (expr instanceof BinaryOperation && ((BinaryOperation)expr).getOp().equals(\"and\")) {\n\t\t\tList leftList = getControlledPropertiesForTable(((BinaryOperation)expr).getLeft());\n\t\t\tif (leftList != null) {\n\t\t\t\tresults.addAll(leftList);\n\t\t\t}\n\t\t\tList rightList = getControlledPropertiesForTable(((BinaryOperation)expr).getRight());\n\t\t\tif (rightList != null) {\n\t\t\t\tresults.addAll(rightList);\n\t\t\t}\n\t\t}\n\t\telse if (expr instanceof PropOfSubject) {\n\t\t\tList propList = getControlledPropertiesForTable(((PropOfSubject)expr).getLeft());\n\t\t\tif (propList != null) {\n\t\t\t\tresults.addAll(propList);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\taddError(\"Tabular requirement appears to have an invalid set statement\", expr);\n\t\t}\n\t\treturn results;\n\t}\n\t\n\tpublic VariableNode getVariable(String name) {\n\t\tObject trgt = getTarget();\n\t\tif (trgt instanceof Rule) {\n\t\t\treturn ((Rule)trgt).getVariable(name);\n\t\t}\n\t\telse if (trgt instanceof Query) {\n\t\t\treturn ((Query)trgt).getVariable(name);\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprivate void setSadlCommands(List sadlCommands) {\n\t\tthis.sadlCommands = sadlCommands;\n\t}\n\t\n\t/* (non-Javadoc)\n\t * @see com.ge.research.sadl.jena.IJenaBasedModelProcessor#compareTranslations(java.lang.String, java.lang.String)\n\t */\n\t@Override\n\tpublic boolean compareTranslations(String result, String evalTo) {\n\t\tevalTo = removeNewLines(evalTo);\n\t\tevalTo = removeLocation(evalTo);\n\t\tresult = removeNewLines(result);\n\t\tresult = removeLocation(result);\n\t\tboolean stat = result.equals(evalTo);\n\t\tif (!stat) {\n\t\t\tSystem.err.println(\"Comparison failed:\");\n\t\t\tSystem.err.println(\" \" + result);\n\t\t\tSystem.err.println(\" \" + evalTo);\n\t\t}\n\t\treturn stat;\n\t}\n\t\n\tprotected String removeNewLines(String evalTo) {\n\t String cleanString = evalTo.replaceAll(\"\\r\", \"\").replaceAll(\"\\n\", \"\").replaceAll(\" \", \"\");\n\t\treturn cleanString;\n\t}\n\t\n\tprotected String removeLocation(String str) {\n\t\tint locloc = str.indexOf(\"location(\");\n\t\twhile (locloc > 0) {\n\t\t\tint afterloc = str.indexOf(\"sreq(name(\", locloc);\n\t\t\tString before = str.substring(0, locloc);\n\t\t\tint realStart = before.lastIndexOf(\"sreq(name(\");\n\t\t\tif (realStart > 0) {\n\t\t\t\tbefore = str.substring(0, realStart);\n\t\t\t}\n\t\t\tif (afterloc > 0) {\n\t\t\t\tString after = str.substring(afterloc);\n\t\t\t\tstr = before + after;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tstr = before;\n\t\t\t}\n\t\t\tlocloc = str.indexOf(\"location(\");\n\t\t}\n\t\treturn str;\n\t}\n\tpublic boolean isUseArticlesInValidation() {\n\t\treturn useArticlesInValidation;\n\t}\n\tpublic void setUseArticlesInValidation(boolean useArticlesInValidation) {\n\t\tthis.useArticlesInValidation = useArticlesInValidation;\n\t}\n\n}\n"},"new_file":{"kind":"string","value":"sadl3/com.ge.research.sadl.parent/com.ge.research.sadl.jena/src/com/ge/research/sadl/jena/JenaBasedSadlModelProcessor.java"},"old_contents":{"kind":"string","value":"/************************************************************************\n * Copyright © 2007-2016 - General Electric Company, All Rights Reserved\n *\n * Project: SADL\n *\n * Description: The Semantic Application Design Language (SADL) is a\n * language for building semantic models and expressing rules that\n * capture additional domain knowledge. The SADL-IDE (integrated\n * development environment) is a set of Eclipse plug-ins that\n * support the editing and testing of semantic models using the\n * SADL language.\n *\n * This software is distributed \"AS-IS\" without ANY WARRANTIES\n * and licensed under the Eclipse Public License - v 1.0\n * which is available at http://www.eclipse.org/org/documents/epl-v10.php\n *\n ***********************************************************************/\npackage com.ge.research.sadl.jena;\n\nimport static com.ge.research.sadl.processing.ISadlOntologyHelper.ContextBuilder.MISSING_SUBJECT;\nimport static com.ge.research.sadl.processing.ISadlOntologyHelper.GrammarContextIds.PROPOFSUBJECT_PROP;\nimport static com.ge.research.sadl.processing.ISadlOntologyHelper.GrammarContextIds.PROPOFSUBJECT_RIGHT;\nimport static com.ge.research.sadl.processing.ISadlOntologyHelper.GrammarContextIds.SADLPROPERTYINITIALIZER_PROPERTY;\nimport static com.ge.research.sadl.processing.ISadlOntologyHelper.GrammarContextIds.SADLPROPERTYINITIALIZER_VALUE;\nimport static com.ge.research.sadl.processing.ISadlOntologyHelper.GrammarContextIds.SADLSTATEMENT_SUPERELEMENT;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.ByteArrayOutputStream;\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.PrintStream;\nimport java.math.BigDecimal;\nimport java.net.MalformedURLException;\nimport java.net.URISyntaxException;\nimport java.nio.charset.Charset;\nimport java.nio.file.Paths;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.swing.text.html.HTMLDocument.HTMLReader.IsindexAction;\n\nimport org.eclipse.core.resources.IFile;\nimport org.eclipse.core.resources.IResource;\nimport org.eclipse.core.resources.IWorkspaceRoot;\nimport org.eclipse.core.resources.ResourcesPlugin;\nimport org.eclipse.core.runtime.OperationCanceledException;\nimport org.eclipse.core.runtime.Path;\nimport org.eclipse.emf.common.EMFPlugin;\nimport org.eclipse.emf.common.util.EList;\nimport org.eclipse.emf.common.util.TreeIterator;\nimport org.eclipse.emf.common.util.URI;\nimport org.eclipse.emf.ecore.EObject;\nimport org.eclipse.emf.ecore.resource.Resource;\nimport org.eclipse.xtext.diagnostics.Severity;\nimport org.eclipse.xtext.generator.IFileSystemAccess2;\nimport org.eclipse.xtext.naming.QualifiedName;\nimport org.eclipse.xtext.nodemodel.ICompositeNode;\nimport org.eclipse.xtext.nodemodel.util.NodeModelUtils;\nimport org.eclipse.xtext.resource.XtextResource;\nimport org.eclipse.xtext.scoping.IScope;\nimport org.eclipse.xtext.scoping.IScopeProvider;\nimport org.eclipse.xtext.service.OperationCanceledError;\nimport org.eclipse.xtext.util.CancelIndicator;\nimport org.eclipse.xtext.validation.CheckMode;\nimport org.eclipse.xtext.validation.CheckType;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.ge.research.sadl.builder.ConfigurationManagerForIdeFactory;\nimport com.ge.research.sadl.builder.IConfigurationManagerForIDE;\nimport com.ge.research.sadl.errorgenerator.generator.SadlErrorMessages;\nimport com.ge.research.sadl.external.ExternalEmfResource;\nimport com.ge.research.sadl.jena.JenaBasedSadlModelValidator.TypeCheckInfo;\nimport com.ge.research.sadl.jena.inference.SadlJenaModelGetterPutter;\nimport com.ge.research.sadl.model.CircularDefinitionException;\nimport com.ge.research.sadl.model.ConceptIdentifier;\nimport com.ge.research.sadl.model.ConceptName;\nimport com.ge.research.sadl.model.ConceptName.ConceptType;\nimport com.ge.research.sadl.model.ConceptName.RangeValueType;\nimport com.ge.research.sadl.model.DeclarationExtensions;\nimport com.ge.research.sadl.model.ModelError;\nimport com.ge.research.sadl.model.OntConceptType;\nimport com.ge.research.sadl.model.PrefixNotFoundException;\nimport com.ge.research.sadl.model.gp.BuiltinElement;\nimport com.ge.research.sadl.model.gp.BuiltinElement.BuiltinType;\nimport com.ge.research.sadl.model.gp.ConstantNode;\nimport com.ge.research.sadl.model.gp.EndWrite;\nimport com.ge.research.sadl.model.gp.Equation;\nimport com.ge.research.sadl.model.gp.Explain;\nimport com.ge.research.sadl.model.gp.GraphPatternElement;\nimport com.ge.research.sadl.model.gp.Junction;\nimport com.ge.research.sadl.model.gp.Junction.JunctionType;\nimport com.ge.research.sadl.model.gp.KnownNode;\n//import com.ge.research.sadl.model.gp.Literal;\nimport com.ge.research.sadl.model.gp.NamedNode;\nimport com.ge.research.sadl.model.gp.NamedNode.NodeType;\nimport com.ge.research.sadl.model.gp.Node;\nimport com.ge.research.sadl.model.gp.Print;\nimport com.ge.research.sadl.model.gp.ProxyNode;\nimport com.ge.research.sadl.model.gp.Query;\nimport com.ge.research.sadl.model.gp.Query.Order;\nimport com.ge.research.sadl.model.gp.Query.OrderingPair;\nimport com.ge.research.sadl.model.gp.RDFTypeNode;\nimport com.ge.research.sadl.model.gp.Read;\nimport com.ge.research.sadl.model.gp.Rule;\nimport com.ge.research.sadl.model.gp.SadlCommand;\nimport com.ge.research.sadl.model.gp.StartWrite;\nimport com.ge.research.sadl.model.gp.Test;\nimport com.ge.research.sadl.model.gp.TripleElement;\nimport com.ge.research.sadl.model.gp.TripleElement.TripleModifierType;\nimport com.ge.research.sadl.model.gp.TripleElement.TripleSourceType;\nimport com.ge.research.sadl.model.gp.VariableNode;\nimport com.ge.research.sadl.preferences.SadlPreferences;\nimport com.ge.research.sadl.processing.ISadlOntologyHelper.Context;\nimport com.ge.research.sadl.processing.OntModelProvider;\nimport com.ge.research.sadl.processing.SadlConstants;\nimport com.ge.research.sadl.processing.SadlConstants.OWL_FLAVOR;\nimport com.ge.research.sadl.processing.SadlModelProcessor;\nimport com.ge.research.sadl.processing.ValidationAcceptor;\nimport com.ge.research.sadl.processing.ValidationAcceptorExt;\nimport com.ge.research.sadl.reasoner.CircularDependencyException;\nimport com.ge.research.sadl.reasoner.ConfigurationException;\nimport com.ge.research.sadl.reasoner.ConfigurationManager;\nimport com.ge.research.sadl.reasoner.IReasoner;\nimport com.ge.research.sadl.reasoner.ITranslator;\nimport com.ge.research.sadl.reasoner.InvalidNameException;\nimport com.ge.research.sadl.reasoner.InvalidTypeException;\nimport com.ge.research.sadl.reasoner.SadlJenaModelGetter;\nimport com.ge.research.sadl.reasoner.TranslationException;\nimport com.ge.research.sadl.reasoner.utils.SadlUtils;\nimport com.ge.research.sadl.sADL.AskExpression;\nimport com.ge.research.sadl.sADL.BinaryOperation;\nimport com.ge.research.sadl.sADL.BooleanLiteral;\nimport com.ge.research.sadl.sADL.Constant;\nimport com.ge.research.sadl.sADL.ConstructExpression;\nimport com.ge.research.sadl.sADL.Declaration;\nimport com.ge.research.sadl.sADL.ElementInList;\nimport com.ge.research.sadl.sADL.EndWriteStatement;\nimport com.ge.research.sadl.sADL.EquationStatement;\nimport com.ge.research.sadl.sADL.ExplainStatement;\nimport com.ge.research.sadl.sADL.Expression;\nimport com.ge.research.sadl.sADL.ExpressionStatement;\nimport com.ge.research.sadl.sADL.ExternalEquationStatement;\nimport com.ge.research.sadl.sADL.Name;\nimport com.ge.research.sadl.sADL.NamedStructureAnnotation;\nimport com.ge.research.sadl.sADL.NumberLiteral;\nimport com.ge.research.sadl.sADL.OrderElement;\nimport com.ge.research.sadl.sADL.PrintStatement;\nimport com.ge.research.sadl.sADL.PropOfSubject;\nimport com.ge.research.sadl.sADL.QueryStatement;\nimport com.ge.research.sadl.sADL.ReadStatement;\nimport com.ge.research.sadl.sADL.RuleStatement;\nimport com.ge.research.sadl.sADL.SADLPackage;\nimport com.ge.research.sadl.sADL.SadlAllValuesCondition;\nimport com.ge.research.sadl.sADL.SadlAnnotation;\nimport com.ge.research.sadl.sADL.SadlBooleanLiteral;\nimport com.ge.research.sadl.sADL.SadlCanOnlyBeOneOf;\nimport com.ge.research.sadl.sADL.SadlCardinalityCondition;\nimport com.ge.research.sadl.sADL.SadlClassOrPropertyDeclaration;\nimport com.ge.research.sadl.sADL.SadlCondition;\nimport com.ge.research.sadl.sADL.SadlConstantLiteral;\nimport com.ge.research.sadl.sADL.SadlDataType;\nimport com.ge.research.sadl.sADL.SadlDataTypeFacet;\nimport com.ge.research.sadl.sADL.SadlDefaultValue;\nimport com.ge.research.sadl.sADL.SadlDifferentFrom;\nimport com.ge.research.sadl.sADL.SadlDisjointClasses;\nimport com.ge.research.sadl.sADL.SadlExplicitValue;\nimport com.ge.research.sadl.sADL.SadlHasValueCondition;\nimport com.ge.research.sadl.sADL.SadlImport;\nimport com.ge.research.sadl.sADL.SadlInstance;\nimport com.ge.research.sadl.sADL.SadlIntersectionType;\nimport com.ge.research.sadl.sADL.SadlIsAnnotation;\nimport com.ge.research.sadl.sADL.SadlIsInverseOf;\nimport com.ge.research.sadl.sADL.SadlIsSymmetrical;\nimport com.ge.research.sadl.sADL.SadlIsTransitive;\nimport com.ge.research.sadl.sADL.SadlModel;\nimport com.ge.research.sadl.sADL.SadlModelElement;\nimport com.ge.research.sadl.sADL.SadlMustBeOneOf;\nimport com.ge.research.sadl.sADL.SadlNecessaryAndSufficient;\nimport com.ge.research.sadl.sADL.SadlNestedInstance;\nimport com.ge.research.sadl.sADL.SadlNumberLiteral;\nimport com.ge.research.sadl.sADL.SadlParameterDeclaration;\nimport com.ge.research.sadl.sADL.SadlPrimitiveDataType;\nimport com.ge.research.sadl.sADL.SadlProperty;\nimport com.ge.research.sadl.sADL.SadlPropertyCondition;\nimport com.ge.research.sadl.sADL.SadlPropertyInitializer;\nimport com.ge.research.sadl.sADL.SadlPropertyRestriction;\nimport com.ge.research.sadl.sADL.SadlRangeRestriction;\nimport com.ge.research.sadl.sADL.SadlResource;\nimport com.ge.research.sadl.sADL.SadlSameAs;\nimport com.ge.research.sadl.sADL.SadlSimpleTypeReference;\nimport com.ge.research.sadl.sADL.SadlStringLiteral;\nimport com.ge.research.sadl.sADL.SadlTypeAssociation;\nimport com.ge.research.sadl.sADL.SadlTypeReference;\nimport com.ge.research.sadl.sADL.SadlUnaryExpression;\nimport com.ge.research.sadl.sADL.SadlUnionType;\nimport com.ge.research.sadl.sADL.SadlValueList;\nimport com.ge.research.sadl.sADL.SelectExpression;\nimport com.ge.research.sadl.sADL.StartWriteStatement;\nimport com.ge.research.sadl.sADL.StringLiteral;\nimport com.ge.research.sadl.sADL.SubjHasProp;\nimport com.ge.research.sadl.sADL.Sublist;\nimport com.ge.research.sadl.sADL.TestStatement;\nimport com.ge.research.sadl.sADL.UnaryExpression;\nimport com.ge.research.sadl.sADL.UnitExpression;\nimport com.ge.research.sadl.sADL.ValueRow;\nimport com.ge.research.sadl.sADL.ValueTable;\nimport com.ge.research.sadl.utils.PathToFileUriConverter;\n//import com.ge.research.sadl.server.ISadlServer;\n//import com.ge.research.sadl.server.SessionNotFoundException;\n//import com.ge.research.sadl.server.server.SadlServerImpl;\nimport com.ge.research.sadl.utils.ResourceManager;\nimport com.ge.research.sadl.utils.SadlASTUtils;\nimport com.google.common.base.Preconditions;\nimport com.google.common.collect.Iterables;\nimport com.hp.hpl.jena.ontology.AllValuesFromRestriction;\nimport com.hp.hpl.jena.ontology.AnnotationProperty;\nimport com.hp.hpl.jena.ontology.CardinalityRestriction;\nimport com.hp.hpl.jena.ontology.ComplementClass;\nimport com.hp.hpl.jena.ontology.DatatypeProperty;\nimport com.hp.hpl.jena.ontology.EnumeratedClass;\nimport com.hp.hpl.jena.ontology.HasValueRestriction;\nimport com.hp.hpl.jena.ontology.Individual;\nimport com.hp.hpl.jena.ontology.IntersectionClass;\nimport com.hp.hpl.jena.ontology.MaxCardinalityRestriction;\nimport com.hp.hpl.jena.ontology.MinCardinalityRestriction;\nimport com.hp.hpl.jena.ontology.ObjectProperty;\nimport com.hp.hpl.jena.ontology.OntClass;\nimport com.hp.hpl.jena.ontology.OntDocumentManager;\nimport com.hp.hpl.jena.ontology.OntModel;\nimport com.hp.hpl.jena.ontology.OntModelSpec;\nimport com.hp.hpl.jena.ontology.OntProperty;\nimport com.hp.hpl.jena.ontology.OntResource;\nimport com.hp.hpl.jena.ontology.Ontology;\nimport com.hp.hpl.jena.ontology.Restriction;\nimport com.hp.hpl.jena.ontology.SomeValuesFromRestriction;\nimport com.hp.hpl.jena.ontology.UnionClass;\nimport com.hp.hpl.jena.rdf.model.Literal;\nimport com.hp.hpl.jena.rdf.model.Model;\nimport com.hp.hpl.jena.rdf.model.ModelFactory;\nimport com.hp.hpl.jena.rdf.model.NodeIterator;\nimport com.hp.hpl.jena.rdf.model.Property;\nimport com.hp.hpl.jena.rdf.model.RDFList;\nimport com.hp.hpl.jena.rdf.model.RDFNode;\nimport com.hp.hpl.jena.rdf.model.RDFWriter;\nimport com.hp.hpl.jena.rdf.model.ResourceFactory;\nimport com.hp.hpl.jena.rdf.model.Statement;\nimport com.hp.hpl.jena.rdf.model.StmtIterator;\nimport com.hp.hpl.jena.reasoner.TriplePattern;\nimport com.hp.hpl.jena.sparql.JenaTransactionException;\nimport com.hp.hpl.jena.util.iterator.ExtendedIterator;\nimport com.hp.hpl.jena.vocabulary.OWL;\nimport com.hp.hpl.jena.vocabulary.OWL2;\nimport com.hp.hpl.jena.vocabulary.RDF;\nimport com.hp.hpl.jena.vocabulary.RDFS;\nimport com.hp.hpl.jena.vocabulary.XSD;\n\npublic class JenaBasedSadlModelProcessor extends SadlModelProcessor implements IJenaBasedModelProcessor {\n\tprivate static final Logger logger = LoggerFactory.getLogger(JenaBasedSadlModelProcessor.class);\n\n public final static String XSDNS = XSD.getURI();\n\n public final static Property xsdProperty( String local )\n { return ResourceFactory.createProperty( XSDNS + local ); }\n\n\tprivate Resource currentResource;\n\tprotected OntModel theJenaModel;\n\tprotected OntModelSpec spec;\n\tprivate OWL_FLAVOR owlFlavor = OWL_FLAVOR.OWL_DL;\n//\tprotected ISadlServer kServer = null;\n\t\n\tpublic enum AnnType {ALIAS, NOTE}\t\n\n\tprivate List comparisonOperators = Arrays.asList(\">=\",\">\",\"<=\",\"<\",\"==\",\"!=\",\"is\",\"=\",\"not\",\"unique\",\"in\",\"contains\",\"does\",/*\"not\",*/\"contain\");\n\tprivate List numericOperators = Arrays.asList(\"*\",\"+\",\"/\",\"-\",\"%\",\"^\");\n\tprivate List numericComparisonOperators = Arrays.asList(\">=\", \">\", \"<=\", \"<\");\n\tprivate List equalityInequalityComparisonOperators = Arrays.asList(\"==\", \"!=\", \"is\", \"=\");\n\tprivate List canBeNumericOperators = Arrays.asList(\">=\",\">\",\"<=\",\"<\",\"==\",\"!=\",\"is\",\"=\");\n\tpublic enum OPERATORS_RETURNING_BOOLEAN {contains, unique, is, gt, ge, lt, le, and, or, not, was, hasBeen}\n\t\n\tpublic enum BOOLEAN_LITERAL_TEST {BOOLEAN_TRUE, BOOLEAN_FALSE, NOT_BOOLEAN, NOT_BOOLEAN_NEGATED}\n\n\tprivate int vNum = 0;\t// used to create unique variables\n\tprivate List userDefinedVariables = new ArrayList();\n\t\n\t// A \"crule\" variable has a type, a number indicating its ordinal, and a name\n\t//\tThey are stored by type as key to a list of names, the index in the list is its ordinal number\n\tprivate Map> cruleVariables = null;\n\tprivate List preprocessedEObjects = null;\t\n\t\n\tprotected String modelName;\n\tprotected String modelAlias;\n\tprotected String modelNamespace;\n\tprivate OntDocumentManager jenaDocumentMgr;\n\tprotected IConfigurationManagerForIDE configMgr;\n\t\n\tprivate OntModel sadlBaseModel = null;\n\n\tprivate boolean importSadlListModel = false;\n\tprivate OntModel sadlListModel = null;\n\tprivate boolean importSadlDefaultsModel = false;\n\tprivate OntModel sadlDefaultsModel = null;\n\t\n\t\n\tprivate OntModel sadlImplicitModel = null;\n\tprivate OntModel sadlBuiltinFunctionModel = null;\n\n\tprotected JenaBasedSadlModelValidator modelValidator = null;\n\tprotected ValidationAcceptor issueAcceptor = null;\n\tprotected CancelIndicator cancelIndicator = null;\n\n\tprivate boolean lookingForFirstProperty = false;\t// in rules and other constructs, the first property may be significant (the binding, for example)\n\n\tprotected List importsInOrderOfAppearance = null;\t// an ordered set of import URIs, ordered by appearance in file.\n\tprivate List rules = null;\n\tprivate List equations = null;\n\tprivate Equation currentEquation = null;\n\tprivate List sadlCommands = null;\n\tprivate SadlCommand targetCommand = null;\n\t\n\tprivate List operationsPullingUp = null;\n\t\n\tint modelErrorCount = 0;\n\tint modelWarningCount = 0;\n\tint modelInfoCount = 0;\n\n\tprivate IntermediateFormTranslator intermediateFormTranslator = null;\n\n\tprotected boolean generationInProgress = false;\n\n\tpublic static String[] reservedFolderNames = {\"Graphs\", \"OwlModels\", \"Temp\", SadlConstants.SADL_IMPLICIT_MODEL_FOLDER};\n\tpublic static String[] reservedFileNames = {\"Project.sadl\",\"SadlBaseModel.sadl\", \"SadlListModel.sadl\", \n\t\t\t\"RulePatterns.sadl\", \"RulePatternsData.sadl\", \"SadlServicesConfigurationConcepts.sadl\", \n\t\t\t\"ServicesConfig.sadl\", \"defaults.sadl\", \"SadlImplicitModel.sadl\", \"SadlBuiltinFunctions.sadl\"};\n\tpublic static String[] reservedModelURIs = {SadlConstants.SADL_BASE_MODEL_URI,SadlConstants.SADL_LIST_MODEL_URI,\n\t\t\tSadlConstants.SADL_RULE_PATTERN_URI, SadlConstants.SADL_RULE_PATTERN_DATA_URI,\n\t\t\tSadlConstants.SADL_SERIVCES_CONFIGURATION_CONCEPTS_URI, SadlConstants.SADL_SERIVCES_CONFIGURATION_URI,\n\t\t\tSadlConstants.SADL_DEFAULTS_MODEL_URI};\n\tpublic static String[] reservedPrefixes = {SadlConstants.SADL_BASE_MODEL_PREFIX,SadlConstants.SADL_LIST_MODEL_PREFIX,\n\t\t\tSadlConstants.SADL_DEFAULTS_MODEL_PREFIX};\n\n\tprotected boolean includeImpliedPropertiesInTranslation = false;\t// should implied properties be included in translator output? default false\n\n\tprivate DeclarationExtensions declarationExtensions;\n\t\n\tpublic JenaBasedSadlModelProcessor() {\n\t\tlogger.debug(\"New \" + this.getClass().getCanonicalName() + \"' created\");\n\t\tsetDeclarationExtensions(new DeclarationExtensions());\n\t}\n\t/**\n\t * For TESTING\n\t * @return\n\t */\n\tpublic OntModel getTheJenaModel() {\n\t\treturn theJenaModel;\n\t}\n\t\n\tprotected void setCurrentResource(Resource currentResource) {\n\t\tthis.currentResource = currentResource;\n\t}\n\t\n\tpublic Resource getCurrentResource() {\n\t\treturn currentResource;\n\t}\n\n\t/* (non-Javadoc)\n\t * @see com.ge.research.sadl.jena.IJenaBasedModelProcessor#onGenerate(org.eclipse.emf.ecore.resource.Resource, org.eclipse.xtext.generator.IFileSystemAccess2, com.ge.research.sadl.processing.IModelProcessor.ProcessorContext)\n\t */\n\t@Override\n\tpublic void onGenerate(Resource resource, IFileSystemAccess2 fsa, ProcessorContext context) {\n\t\tgenerationInProgress = true;\n\t\tsetProcessorContext(context);\n\t\tList newMappings = new ArrayList();\n \tlogger.debug(\"onGenerate called for Resource '\" + resource.getURI() + \"'\");\n// \tSystem.out.println(\"onGenerate called for Resource '\" + resource.getURI() + \"'\");\n\t\t// save the model\n\t\tif (getTheJenaModel() == null) {\n\t\t\tOntModel m = OntModelProvider.find(resource);\n\t\t\ttheJenaModel = m;\n\t\t\tsetModelName(OntModelProvider.getModelName(resource));\n\t\t\tsetModelAlias(OntModelProvider.getModelPrefix(resource));\n\t\t}\n\t\tif (fsa !=null) {\n\t\t\tString format = getOwlModelFormat(context);\n\t\t\ttry {\n\t\t\t\tITranslator translator = null;\n\t\t\t\tList cmds = getSadlCommands();\n\t\t\t\tif (cmds != null) {\n\t\t\t\t\tIterator cmditr = cmds.iterator();\n\t\t\t\t\tList namedQueryList = null;\n\t\t\t\t\twhile (cmditr.hasNext()) {\n\t\t\t\t\t\tSadlCommand cmd = cmditr.next();\n\t\t\t\t\t\tif (cmd instanceof Query && ((Query)cmd).getName() != null) {\n\t\t\t\t\t\t\tif (translator == null) {\n\t\t\t\t\t\t\t\ttranslator = getConfigMgr(resource, format).getTranslator();\n\t\t\t\t\t\t\t\tnamedQueryList = new ArrayList();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tIndividual queryInst = getTheJenaModel().getIndividual(((Query)cmd).getFqName());\n\t\t\t\t\t\t\tif (queryInst != null && !namedQueryList.contains(queryInst.getURI())) {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tString translatedQuery = null;\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\ttranslatedQuery = translator.translateQuery(getTheJenaModel(), (Query)cmd);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcatch (UnsupportedOperationException e) {\n\t\t\t\t\t\t\t\t\t\tIReasoner defaultReasoner = getConfigMgr(resource, format).getOtherReasoner(ConfigurationManager.DEFAULT_REASONER);\n\t\t\t\t\t\t\t\t\t\ttranslator = getConfigMgr(resource, format).getTranslatorForReasoner(defaultReasoner);\n\t\t\t\t\t\t\t\t\t\ttranslatedQuery = translator.translateQuery(getTheJenaModel(), (Query)cmd);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tLiteral queryLit = getTheJenaModel().createTypedLiteral(translatedQuery);\n\t\t\t\t\t\t\t\t\tqueryInst.addProperty(RDFS.isDefinedBy, queryLit);\n\t\t\t\t\t\t\t\t\tnamedQueryList.add(queryInst.getURI());\n\t\t\t\t\t\t\t\t} catch (TranslationException e) {\n\t\t\t\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t\t\t\t} catch (InvalidNameException e) {\n\t\t\t\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (ConfigurationException e1) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te1.printStackTrace();\n\t\t\t}\n\n\n//\t\t\t// Output the OWL file for the ontology model\n\t\t\tURI lastSeg = fsa.getURI(resource.getURI().lastSegment());\n\t\t\tString owlFN = lastSeg.trimFileExtension().appendFileExtension(ResourceManager.getOwlFileExtension(format)).lastSegment().toString();\n\t\t\tRDFWriter w = getTheJenaModel().getWriter(format);\n\t\t\tw.setProperty(\"xmlbase\",getModelName());\n\t\t\tByteArrayOutputStream out = new ByteArrayOutputStream();\n\t\t\tw.write(getTheJenaModel().getBaseModel(), out, getModelName());\n\t\t\tCharset charset = Charset.forName(\"UTF-8\"); \n\t\t\tCharSequence seq = new String(out.toByteArray(), charset);\n\t\t\tfsa.generateFile(owlFN, seq);\n\t\t\t\n//\t\t\t// if there are equations, output them to a Prolog file\n//\t\t\tList eqs = getEquations();\n//\t\t\tif (eqs != null) {\n//\t\t\t\tStringBuilder sb = new StringBuilder();\n//\t\t\t\tfor (int i = 0; i < eqs.size(); i++) {\n//\t\t\t\t\tsb.append(eqs.get(i).toFullyQualifiedString());\n//\t\t\t\t\tsb.append(\"\\n\");\n//\t\t\t\t}\n//\t\t\t\tfsa.generateFile(lastSeg.appendFileExtension(\"pl\").lastSegment().toString(), sb.toString());\n//\t\t\t}\n\t\t\t\n\t\t\ttry {\n\t\t\t\tString modelFolder = getModelFolderPath(resource);\n\t\t\t\tSadlUtils su = new SadlUtils();\n\t\t\t\tString fn = SadlConstants.SADL_BASE_MODEL_FILENAME + \".\" + ResourceManager.getOwlFileExtension(format);\n\t\t\t\tif (!fileExists(fsa, fn)) {\n\t\t\t\t\tsadlBaseModel = OntModelProvider.getSadlBaseModel();\n\t\t\t\t\tif(sadlBaseModel != null) {\n\t\t\t\t\t\tRDFWriter w2 = sadlBaseModel.getWriter(format);\n\t\t\t\t\t\tw.setProperty(\"xmlbase\",SadlConstants.SADL_BASE_MODEL_URI);\n\t\t\t\t\t\tByteArrayOutputStream out2 = new ByteArrayOutputStream();\n\t\t\t\t\t\tw2.write(sadlBaseModel.getBaseModel(), out2, SadlConstants.SADL_BASE_MODEL_URI);\n\t\t\t\t\t\tCharSequence seq2 = new String(out2.toByteArray(), charset);\n\t\t\t\t\t\tfsa.generateFile(fn, seq2);\n\t\t\t\t\t\tString[] mapping = new String[3];\n\t\t\t\t\t\tmapping[0] = su.fileNameToFileUrl(modelFolder + \"/\" + fn);\n\t\t\t\t\t\tmapping[1] = SadlConstants.SADL_BASE_MODEL_URI;\n\t\t\t\t\t\tmapping[2] = SadlConstants.SADL_BASE_MODEL_PREFIX;\n\t\t\t\t\t\tnewMappings.add(mapping);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfn = SadlConstants.SADL_LIST_MODEL_FILENAME + \".\" + ResourceManager.getOwlFileExtension(format);\n\t\t\t\tif (!fileExists(fsa, fn)) {\n\t\t\t\t\tsadlListModel = OntModelProvider.getSadlListModel();\n\t\t\t\t\tif(sadlListModel != null) {\n\t\t\t\t\t\tRDFWriter w2 = sadlListModel.getWriter(format);\n\t\t\t\t\t\tw.setProperty(\"xmlbase\",SadlConstants.SADL_LIST_MODEL_URI);\n\t\t\t\t\t\tByteArrayOutputStream out2 = new ByteArrayOutputStream();\n\t\t\t\t\t\tw2.write(sadlListModel.getBaseModel(), out2, SadlConstants.SADL_LIST_MODEL_URI);\n\t\t\t\t\t\tCharSequence seq2 = new String(out2.toByteArray(), charset);\n\t\t\t\t\t\tfsa.generateFile(fn, seq2);\n\t\t\t\t\t\tString[] mapping = new String[3];\n\t\t\t\t\t\tmapping[0] = su.fileNameToFileUrl(modelFolder + \"/\" + fn);\n\t\t\t\t\t\tmapping[1] = SadlConstants.SADL_LIST_MODEL_URI;\n\t\t\t\t\t\tmapping[2] = SadlConstants.SADL_LIST_MODEL_PREFIX;\n\t\t\t\t\t\tnewMappings.add(mapping);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfn = SadlConstants.SADL_DEFAULTS_MODEL_FILENAME + \".\" + ResourceManager.getOwlFileExtension(format);\n\t\t\t\tif (!fileExists(fsa, fn)) {\n\t\t\t\t\tsadlDefaultsModel = OntModelProvider.getSadlDefaultsModel();\n\t\t\t\t\tif(sadlDefaultsModel != null) {\n\t\t\t\t\t\tRDFWriter w2 = sadlDefaultsModel.getWriter(format);\n\t\t\t\t\t\tw.setProperty(\"xmlbase\",SadlConstants.SADL_DEFAULTS_MODEL_URI);\n\t\t\t\t\t\tByteArrayOutputStream out2 = new ByteArrayOutputStream();\n\t\t\t\t\t\tw2.write(sadlDefaultsModel.getBaseModel(), out2, SadlConstants.SADL_DEFAULTS_MODEL_URI);\n\t\t\t\t\t\tCharSequence seq2 = new String(out2.toByteArray(), charset);\n\t\t\t\t\t\tfsa.generateFile(fn, seq2);\n\t\t\t\t\t\tString[] mapping = new String[3];\n\t\t\t\t\t\tmapping[0] = su.fileNameToFileUrl(modelFolder + \"/\" + fn);\n\t\t\t\t\t\tmapping[1] = SadlConstants.SADL_DEFAULTS_MODEL_URI;\n\t\t\t\t\t\tmapping[2] = SadlConstants.SADL_DEFAULTS_MODEL_PREFIX;\n\t\t\t\t\t\tnewMappings.add(mapping);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t//\t\t\t// Output the ont-policy.rdf mapping file: the mapping will have been updated already via onValidate\n\t//\t\t\tif (!fsa.isFile(UtilsForJena.ONT_POLICY_FILENAME)) {\n\t//\t\t\t\tfsa.generateFile(UtilsForJena.ONT_POLICY_FILENAME, getDefaultPolicyFileContent());\n\t//\t\t\t}\n\n\t\t\t\tString[] mapping = new String[3];\n\t\t\t\tmapping[0] = su.fileNameToFileUrl(modelFolder + \"/\" + owlFN);\n\t\t\t\tmapping[1] = getModelName();\n\t\t\t\tmapping[2] = getModelAlias();\n\n\t\t\t\tnewMappings.add(mapping);\n\t\t\t\t\n\t\t\t\t// Output the Rules and any other knowledge structures via the specified translator\n\t\t\t\tList otherContent = OntModelProvider.getOtherContent(resource);\n\t\t\t\tif (otherContent != null) {\n\t\t\t\t\tfor (int i = 0; i < otherContent.size(); i++) {\n\t\t\t\t\t\tObject oc = otherContent.get(i);\n\t\t\t\t\t\tif (oc instanceof List) {\n\t\t\t\t\t\t\tif (((List)oc).get(0) instanceof Equation) {\n\t\t\t\t\t\t\t\tsetEquations((List) oc); \n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (((List)oc).get(0) instanceof Rule) {\n\t\t\t\t\t\t\t\trules = (List) oc;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tList results = translateAndSaveModel(resource, owlFN, format, newMappings);\n\t\t\t\tif (results != null) {\n\t\t\t\t\tgenerationInProgress = false;\t// we need these errors to show up\n\t\t\t\t\tmodelErrorsToOutput(resource, results);\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch (Exception e) {\n\t\t\t\t\n\t\t\t}\n\t\t}\n\t\tgenerationInProgress = false;\n\t \tlogger.debug(\"onGenerate completed for Resource '\" + resource.getURI() + \"'\");\n\t}\n\t\n\t// akitta: get rid of this hack once https://github.com/eclipse/xtext-core/issues/180 is fixed\n\tprivate boolean fileExists(IFileSystemAccess2 fsa, String fileName) {\n\t\ttry {\n\t\t\treturn fsa.isFile(fileName);\n\t\t} catch (Exception e) {\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tprivate List translateAndSaveModel(Resource resource, String owlFN, String _repoType, List newMappings) {\n\t\tString modelFolderPathname = getModelFolderPath(resource);\n\t\ttry {\n//\t\t\tIConfigurationManagerForIDE configMgr = new ConfigurationManagerForIDE(modelFolderPathname , _repoType);\n\t\t\tif (newMappings != null) {\n\t\t\t\tgetConfigMgr(resource, _repoType).addMappings(newMappings, false, \"SADL\");\n\t\t\t}\n\t\t\tITranslator translator = getConfigMgr(resource, _repoType).getTranslator();\n\t\t\tList results = translator\n\t\t\t\t\t.translateAndSaveModel(getTheJenaModel(), getRules(),\n\t\t\t\t\t\t\tmodelFolderPathname, getModelName(), getImportsInOrderOfAppearance(), \n\t\t\t\t\t\t\towlFN);\n\t\t\tif (results != null) {\n\t\t\t\tmodelErrorsToOutput(resource, results);\n\t\t\t}\n\t\t\telse if (getOtherKnowledgeStructure(resource) != null) {\n\t\t\t\tresults = translator.translateAndSaveModelWithOtherStructure(getTheJenaModel(), getOtherKnowledgeStructure(resource), \n\t\t\t\t\t\tmodelFolderPathname, getModelName(), getImportsInOrderOfAppearance(), owlFN);\n\t\t\t\treturn results;\n\t\t\t}\n\t\t} catch (MalformedURLException e1) {\n\t\t\te1.printStackTrace();\n\t\t} catch (com.ge.research.sadl.reasoner.ConfigurationException e) {\n\t\t\te.printStackTrace();\n\t\t} catch (TranslationException e) {\n\t\t\te.printStackTrace();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t} catch (URISyntaxException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\t\n\t\t\n\t\treturn null;\n\t}\n\t\n\tprivate String getModelFolderPath(Resource resource) {\n\t\tfinal URI resourceUri = resource.getURI();\n\t\tfinal URI modelFolderUri = resourceUri\n\t\t\t\t.trimSegments(resourceUri.isFile() ? 1 : resourceUri.segmentCount() - 2)\n\t\t\t\t.appendSegment(UtilsForJena.OWL_MODELS_FOLDER_NAME);\n\t\t\n\t\tif (resourceUri.isPlatformResource()) {\n\t\t\t final IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(modelFolderUri.toPlatformString(true)));\n\t\t\t return file.getRawLocation().toPortableString();\n\t\t} else {\n\t\t\tfinal String modelFolderPathname = findModelFolderPath(resource.getURI());\n\t\t\treturn modelFolderPathname == null ? modelFolderUri.toFileString() : modelFolderPathname;\n\t\t}\n\t}\n\t\n\tstatic String findProjectPath(URI uri) {\n\t\tString modelFolder = findModelFolderPath(uri);\n\t\tif (modelFolder != null) {\n\t\t\treturn new File(modelFolder).getParent();\n\t\t}\n\t\treturn null;\n }\n\t\n public static String findModelFolderPath(URI uri){\n \tFile file = new File(uri.path());\n \tif(file != null){\n \t\tif(file.isDirectory()){\n \t\t\tif(file.getAbsolutePath().endsWith(UtilsForJena.OWL_MODELS_FOLDER_NAME)){\n \t\t\t\treturn file.getAbsolutePath();\n \t\t\t}\n \t\t\t\n \t\t\tfor(File child : file.listFiles()){\n \t\t\t\tif(child.getAbsolutePath().endsWith(UtilsForJena.OWL_MODELS_FOLDER_NAME)){\n \t\t\t\t\treturn child.getAbsolutePath();\n \t\t\t\t}\n \t\t\t}\n \t\t\t//Didn't find a project file in this directory, check parent\n \t\t\tif(file.getParentFile() != null){\n \t\t\t\treturn findModelFolderPath(uri.trimSegments(1));\n \t\t\t}\n \t\t}\n \t\tif(file.isFile() && file.getParentFile() != null){\n \t\t\treturn findModelFolderPath(uri.trimSegments(1));\n \t\t}\n \t}\n \t\n \treturn null;\n }\n\t\n\tprivate Object getOtherKnowledgeStructure(Resource resource) {\n\t\tif (getEquations(resource) != null) {\n\t\t\treturn getEquations(resource);\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprivate void modelErrorsToOutput(Resource resource, List errors) {\n\t\tfor (int i = 0; errors != null && i < errors.size(); i++) {\n\t\t\tModelError err = errors.get(i);\n\t\t\taddError(err.getErrorMsg(), resource.getContents().get(0));\n\t\t}\n\t}\n\t\n\t/**\n\t * Method to retrieve a list of the model's imports ordered according to appearance\n\t * @return\n\t */\n\tpublic List getImportsInOrderOfAppearance() {\n\t\treturn importsInOrderOfAppearance;\n\t}\n\n\tprivate void addOrderedImport(String importUri) {\n\t\tif (importsInOrderOfAppearance == null) {\n\t\t\timportsInOrderOfAppearance = new ArrayList();\n\t\t}\n\t\tif (!importsInOrderOfAppearance.contains(importUri)) {\n\t\t\timportsInOrderOfAppearance.add(importUri);\n\t\t}\n\t\t\n\t}\n\t\n\tprotected IMetricsProcessor metricsProcessor;\n\t\n\tpublic String getDefaultMakerSubjectUri() {\n\t\treturn null;\n\t}\n\n\tprivate ProcessorContext processorContext;\n\n\tprivate String reasonerClassName = null;\n\tprivate String translatorClassName = null;\n\n\tprotected boolean ignoreUnittedQuantities;\n\t\n\tprivate boolean useArticlesInValidation;\n\n\tprotected boolean domainAndRangeAsUnionClasses = true;\n\n\tprivate boolean typeCheckingWarningsOnly;\n\n\tprivate List allImpliedPropertyClasses = null;\n\n\tprivate ArrayList intermediateFormResults = null;\n\n\tprivate EObject hostEObject = null;\n\n public static void refreshResource(Resource newRsrc) {\n \ttry {\n \t\tURI uri = newRsrc.getURI();\n \t\turi = newRsrc.getResourceSet().getURIConverter().normalize(uri);\n \t\tString scheme = uri.scheme();\n \t\tif (\"platform\".equals(scheme) && uri.segmentCount() > 1 &&\n \t\t\t\t\"resource\".equals(uri.segment(0)))\n \t\t{\n \t\t\tStringBuffer platformResourcePath = new StringBuffer();\n \t\t\tfor (int j = 1, size = uri.segmentCount() - 1; j < size; ++j)\n \t\t\t{\n \t\t\t\tplatformResourcePath.append('/');\n \t\t\t\tplatformResourcePath.append(uri.segment(j));\n \t\t\t}\n \t\t\tIResource r = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(platformResourcePath.toString()));\n \t\t\tr.refreshLocal(IResource.DEPTH_INFINITE, null);\n \t\t}\n \t}\n \tcatch (Throwable t) {\n \t\t// this will happen if in test environment\n \t}\n\t}\n\n @Override\n public void validate(Context context, SadlResource candidate) {\n \tValidationAcceptor savedIssueAccpetor = this.issueAcceptor;\n \tsetIssueAcceptor(context.getAcceptor());\n \t\n \tString contextId = context.getGrammarContextId().orNull();\n \tOntModel ontModel = context.getOntModel();\n \tSadlResource subject = context.getSubject();\n \tSystem.out.println(\"Subject: \" + getDeclarationExtensions().getConceptUri(subject));\n \tSystem.out.println(\"Candidate: \" + getDeclarationExtensions().getConceptUri(candidate));\n \t\n\t\ttry {\n\t \tif (subject == MISSING_SUBJECT) {\n\t \t\treturn;\n\t \t}\n\t\t\tswitch (contextId) {\n\t\t\t\tcase SADLPROPERTYINITIALIZER_PROPERTY: {\n\t\t\t\t\tOntConceptType candtype = getDeclarationExtensions().getOntConceptType(candidate);\n\t\t\t\t\tif (!isProperty(candtype)) {\n\t\t\t\t\t\tcontext.getAcceptor().add(\"No\", candidate, Severity.ERROR);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tmodelValidator.checkPropertyDomain(ontModel, subject, candidate, candidate, true);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tcase SADLPROPERTYINITIALIZER_VALUE: {\n\t\t\t\t\tSadlResource prop = context.getRestrictions().iterator().next();\n\t\t\t\t\tOntConceptType proptype = getDeclarationExtensions().getOntConceptType(prop);\n\t\t\t\t\tif (proptype.equals(OntConceptType.DATATYPE_PROPERTY)) {\n\t\t\t\t\t\tcontext.getAcceptor().add(\"No\", candidate, Severity.ERROR);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (proptype.equals(OntConceptType.CLASS_PROPERTY)) {\n\t\t\t\t\t\tOntConceptType candtype = getDeclarationExtensions().getOntConceptType(candidate);\n\t\t\t\t\t\tif (!candtype.equals(OntConceptType.INSTANCE)) {\n\t\t\t\t\t\t\tcontext.getAcceptor().add(\"No\", candidate, Severity.ERROR);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tIterator ritr = context.getRestrictions().iterator();\n\t\t\t\t\twhile (ritr.hasNext()) {\n\t\t\t\t\t\tSystem.out.println(\"Restriction: \" + getDeclarationExtensions().getConceptUri(ritr.next()));\n\t\t\t\t\t}\n\t\t\t\t\tmodelValidator.checkPropertyDomain(ontModel, subject, prop, subject, true);\n\t\t\t\t\tStringBuilder errorMessageBuilder = new StringBuilder();\n\t\t\t\t\tif (!modelValidator.validateBinaryOperationByParts(candidate, prop, candidate, \"is\", errorMessageBuilder)) {\n\t\t\t\t\t\tcontext.getAcceptor().add(errorMessageBuilder.toString(), candidate, Severity.ERROR);\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tcase SADLSTATEMENT_SUPERELEMENT: {\n\t\t\t\t\tOntConceptType candtype = getDeclarationExtensions().getOntConceptType(candidate);\n\t\t\t\t\tif (candtype.equals(OntConceptType.CLASS) ||\n\t\t\t\t\t\t\tcandtype.equals(OntConceptType.CLASS_LIST) ||\n\t\t\t\t\t\t\tcandtype.equals(OntConceptType.CLASS_PROPERTY) ||\n\t\t\t\t\t\t\tcandtype.equals(OntConceptType.DATATYPE) ||\n\t\t\t\t\t\t\tcandtype.equals(OntConceptType.DATATYPE_LIST) ||\n\t\t\t\t\t\t\tcandtype.equals(OntConceptType.DATATYPE_PROPERTY) ||\n\t\t\t\t\t\t\tcandtype.equals(OntConceptType.RDF_PROPERTY)) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tcontext.getAcceptor().add(\"No\", candidate, Severity.ERROR);\n\t\t\t\t}\n\t\t\t\tcase PROPOFSUBJECT_RIGHT: {\n\t\t\t\t\tOntConceptType subjtype = getDeclarationExtensions().getOntConceptType(subject);\n\t\t\t\t\tOntConceptType candtype = getDeclarationExtensions().getOntConceptType(candidate);\n\t\t\t\t\tif ((candtype.equals(OntConceptType.CLASS) || candtype.equals(OntConceptType.INSTANCE)) && isProperty(subjtype)) {\n\t\t\t\t\t\tmodelValidator.checkPropertyDomain(ontModel, candidate, subject, candidate, true);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tcontext.getAcceptor().add(\"No\", candidate, Severity.ERROR);\n\t\t\t\t\treturn;\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\tcase PROPOFSUBJECT_PROP: {\n\t\t\t\t\tOntConceptType subjtype = getDeclarationExtensions().getOntConceptType(subject);\n\t\t\t\t\tOntConceptType candtype = getDeclarationExtensions().getOntConceptType(candidate);\n\t\t\t\t\tif ((candtype.equals(OntConceptType.CLASS) || candtype.equals(OntConceptType.INSTANCE)) && isProperty(subjtype)) {\n\t\t\t\t\t\tmodelValidator.checkPropertyDomain(ontModel, candidate, subject, candidate, true);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tcontext.getAcceptor().add(\"No\", candidate, Severity.ERROR);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tdefault: {\n\t\t\t\t\t// Ignored\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (InvalidTypeException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t} catch (CircularDefinitionException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t\tfinally {\n\t\t\tif (savedIssueAccpetor != null) {\n\t\t\t\tsetIssueAcceptor(savedIssueAccpetor);\n\t\t\t}\n\t\t}\n }\n \n\t@Override\n\tpublic boolean isSupported(String fileExtension) {\n\t\treturn \"sadl\".equals(fileExtension);\n\t}\n\n /* (non-Javadoc)\n\t * @see com.ge.research.sadl.jena.IJenaBasedModelProcessor#onValidate(org.eclipse.emf.ecore.resource.Resource, com.ge.research.sadl.processing.ValidationAcceptor, org.eclipse.xtext.validation.CheckMode, com.ge.research.sadl.processing.IModelProcessor.ProcessorContext)\n\t */\n @Override\n\tpublic void onValidate(Resource resource, ValidationAcceptor issueAcceptor, CheckMode mode, ProcessorContext context) {\n \t\tlogger.debug(\"onValidate called for Resource '\" + resource.getURI() + \"'\");\n\t\tif (mode.shouldCheck(CheckType.EXPENSIVE)) {\n\t\t\t// do expensive validation, i.e. those that should only be done when 'validate' action was invoked. \n\t\t}\n\t\tsetIssueAcceptor(issueAcceptor);\n\t\tsetProcessorContext(context);\n\t\tsetCancelIndicator(cancelIndicator);\n\t\tif (resource.getContents().size() < 1) {\n\t\t\treturn;\n\t\t}\n\t\tsetCurrentResource(resource);\n\t\tSadlModel model = (SadlModel) resource.getContents().get(0);\n\t\tString modelActualUrl =resource.getURI().lastSegment();\n\t\tvalidateResourcePathAndName(resource, model, modelActualUrl);\n\t\tString modelName = model.getBaseUri();\n\t\tsetModelName(modelName);\n\t\tsetModelNamespace(assureNamespaceEndsWithHash(modelName));\n\t\tsetModelAlias(model.getAlias());\n\t\tif (getModelAlias() == null) {\n\t\t\tsetModelAlias(\"\");\n\t\t}\n\t\t\n\t\ttry {\n\t\t\ttheJenaModel = prepareEmptyOntModel(resource);\n\t\t} catch (ConfigurationException e1) {\n\t\t\te1.printStackTrace();\n\t\t\taddError(SadlErrorMessages.CONFIGURATION_ERROR.get(e1.getMessage()), model);\n\t\t\taddError(e1.getMessage(), model);\n\t\t\treturn; // this is a fatal error\n\t\t}\n\t\tgetTheJenaModel().setNsPrefix(getModelAlias(), getModelNamespace());\n\t\tOntology modelOntology = getTheJenaModel().createOntology(modelName);\n\t\tlogger.debug(\"Ontology '\" + modelName + \"' created\");\n\t\tmodelOntology.addComment(\"This ontology was created from a SADL file '\"\n\t\t\t\t+ modelActualUrl + \"' and should not be directly edited.\", \"en\");\n\t\t\n\t\tString modelVersion = model.getVersion();\n\t\tif (modelVersion != null) {\n\t\t\tmodelOntology.addVersionInfo(modelVersion);\n\t\t}\n\n\t\tEList anns = model.getAnnotations();\n\t\taddAnnotationsToResource(modelOntology, anns);\n\t\t\n\t\tOntModelProvider.registerResource(resource);\n\n\t\ttry {\n\t\t\t//Add SadlBaseModel to everything except the SadlImplicitModel\n\t\t\tif(!resource.getURI().lastSegment().equals(SadlConstants.SADL_IMPLICIT_MODEL_FILENAME)){\n\t\t\t\taddSadlBaseModelImportToJenaModel(resource);\n\t\t\t}\n\t\t\t// Add the SadlImplicitModel to everything except itself and the SadlBuilinFunctions\n\t\t\tif (!resource.getURI().lastSegment().equals(SadlConstants.SADL_IMPLICIT_MODEL_FILENAME) &&\n\t\t\t\t\t!resource.getURI().lastSegment().equals(SadlConstants.SADL_BUILTIN_FUNCTIONS_FILENAME)) {\n\t\t\t\taddImplicitSadlModelImportToJenaModel(resource, context);\n\t\t\t\taddImplicitBuiltinFunctionModelImportToJenaModel(resource, context);\n\n\t\t\t}\n\t\t} catch (IOException e1) {\n\t\t\te1.printStackTrace();\n\t\t} catch (ConfigurationException e1) {\n\t\t\te1.printStackTrace();\n\t\t} catch (URISyntaxException e1) {\n\t\t\te1.printStackTrace();\n\t\t} catch (JenaProcessorException e1) {\n\t\t\te1.printStackTrace();\n\t\t}\n\t\t\n\t\tprocessModelImports(modelOntology, resource.getURI(), model);\n\n\t\tboolean enableMetricsCollection = true;\t// no longer a preference\n\t\ttry {\n\t\t\tif (enableMetricsCollection) {\n\t\t\t\tif (!isSyntheticUri(null, resource)) {\n\t\t\t\t\tsetMetricsProcessor(new MetricsProcessor(modelName, resource, getConfigMgr(resource, getOwlModelFormat(context)), this));\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (JenaProcessorException e1) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te1.printStackTrace();\n\t\t} catch (ConfigurationException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\n\t\tString impPropDW = context.getPreferenceValues().getPreference(SadlPreferences.USE_IMPLIED_PROPERTIES_IN_TRANSLATION);\n\t\tif (impPropDW != null) {\n\t\t\tincludeImpliedPropertiesInTranslation = Boolean.parseBoolean(impPropDW);\n\t\t}\n\n\t\tsetTypeCheckingWarningsOnly(true);\n\t\tString typechecking = context.getPreferenceValues().getPreference(SadlPreferences.TYPE_CHECKING_WARNING_ONLY);\n\t\tif (typechecking != null) {\n\t\t\tsetTypeCheckingWarningsOnly(Boolean.parseBoolean(typechecking));\n\t\t}\n\t\tignoreUnittedQuantities = true;\n\t\tString ignoreUnits = context.getPreferenceValues().getPreference(SadlPreferences.IGNORE_UNITTEDQUANTITIES);\n\t\tif (ignoreUnits != null) {\n\t\t\tignoreUnittedQuantities = Boolean.parseBoolean(ignoreUnits);\n\t\t}\n\t\t\n\t\tsetUseArticlesInValidation(false);\n\t\tString useArticles = context.getPreferenceValues().getPreference(SadlPreferences.P_USE_ARTICLES_IN_VALIDATION);\n\t\tif (useArticles != null) {\n\t\t\tsetUseArticlesInValidation(Boolean.parseBoolean(useArticles));\n\t\t}\n\t\t\n\t\tdomainAndRangeAsUnionClasses = true;\n\t\tString domainAndRangeAsUnionClassesStr = context.getPreferenceValues().getPreference(SadlPreferences.CREATE_DOMAIN_AND_RANGE_AS_UNION_CLASSES);\n\t\tif (domainAndRangeAsUnionClassesStr != null) {\n\t\t\tdomainAndRangeAsUnionClasses = Boolean.parseBoolean(domainAndRangeAsUnionClassesStr);\n\t\t}\n\n\t\t// create validator for expressions\n\t\tinitializeModelValidator();\n\t\tinitializeAllImpliedPropertyClasses();\n\t\t\n\t\t// process rest of parse tree\n\t\tList elements = model.getElements();\n\t\tif (elements != null) {\n\t\t\tIterator elitr = elements.iterator();\n\t\t\twhile (elitr.hasNext()) {\n\t\t\t\t// check for cancelation from time to time\n\t\t\t\tif (context.getCancelIndicator().isCanceled()) {\n\t\t\t\t\tthrow new OperationCanceledException();\n\t\t\t\t}\n\t\t\t\tSadlModelElement element = elitr.next();\n\t\t\t\tprocessModelElement(element);\n\t\t\t}\n\t\t}\n \tlogger.debug(\"onValidate completed for Resource '\" + resource.getURI() + \"'\");\n \tif (getSadlCommands() != null && getSadlCommands().size() > 0) {\n \t\tOntModelProvider.attach(model.eResource(), getTheJenaModel(), getModelName(), getModelAlias(), getSadlCommands());\n \t}\n \telse {\n \t\tOntModelProvider.attach(model.eResource(), getTheJenaModel(), getModelName(), getModelAlias());\n \t}\n \tif (rules != null && rules.size() > 0) {\n \t\tList other = OntModelProvider.getOtherContent(model.eResource());\n \t\tif (other != null) {\n \t\t\tother.add(rules);\n \t\t}\n \t\telse {\n \t\t\tOntModelProvider.addOtherContent(model.eResource(), rules);\n \t\t}\n \t}\n\t\tif (issueAcceptor instanceof ValidationAcceptorExt) {\n\t\t\tfinal ValidationAcceptorExt acceptor = (ValidationAcceptorExt) issueAcceptor;\n\t\t\ttry {\n\t\t\t\tif (!resource.getURI().lastSegment().equals(\"SadlImplicitModel.sadl\") &&\n\t\t\t\t\t!resource.getURI().lastSegment().equals(SadlConstants.SADL_BUILTIN_FUNCTIONS_FILENAME)) {\n//\t\t\t\t\tSystem.out.println(\"Metrics for '\" + resource.getURI().lastSegment() + \"':\");\n\t\t\t\t\tif (acceptor.getErrorCount() > 0) {\n\t\t\t\t\t\tString msg = \" Model totals: \" + countPlusLabel(acceptor.getErrorCount(), \"error\") + \", \" + \n\t\t\t\t\t\t\t\tcountPlusLabel(acceptor.getWarningCount(), \"warning\") + \", \" + \n\t\t\t\t\t\t\t\tcountPlusLabel(acceptor.getInfoCount(), \"info\");\n//\t\t\t\t\t\tSystem.out.flush();\n\t\t\t\t\t\tSystem.err.println(\"No OWL model output generated for '\" + resource.getURI() + \"'.\");\n\t\t\t\t\t\tSystem.err.println(msg);\n\t\t\t\t\t\tSystem.err.flush();\n\t\t\t\t\t}\n//\t\t\t\t\telse {\n//\t\t\t\t\t\tSystem.out.println(msg);\n//\t\t\t\t\t}\n\t\t\t\t\tif (!isSyntheticUri(null, resource)) {\n\t\t\t\t\t\t// don't do metrics on JUnit tests\n\t\t\t\t\t\tif (getMetricsProcessor() != null) {\n\t\t\t\t\t\t\tgetMetricsProcessor().saveMetrics(ConfigurationManager.RDF_XML_ABBREV_FORMAT);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (IOException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (IllegalStateException e) {\n\t\t\t\t// this is OK--will happen during standalone testing\n\t\t\t} catch (ConfigurationException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (URISyntaxException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t}\n\tprotected void processModelElement(SadlModelElement element) {\n\t\ttry {\n\t\t\tif (element instanceof SadlClassOrPropertyDeclaration) {\n\t\t\t\tprocessSadlClassOrPropertyDeclaration((SadlClassOrPropertyDeclaration) element);\t\n\t\t\t}\n\t\t\telse if (element instanceof SadlProperty) {\n\t\t\t\tprocessSadlProperty(null, (SadlProperty) element);\n\t\t\t}\n\t\t\telse if (element instanceof SadlNecessaryAndSufficient) {\n\t\t\t\tprocessSadlNecessaryAndSufficient((SadlNecessaryAndSufficient)element);\n\t\t\t}\n\t\t\telse if (element instanceof SadlDifferentFrom) {\n\t\t\t\tprocessSadlDifferentFrom((SadlDifferentFrom)element);\n\t\t\t}\n\t\t\telse if (element instanceof SadlInstance) {\n\t\t\t\tprocessSadlInstance((SadlInstance) element);\n\t\t\t}\n\t\t\telse if (element instanceof SadlDisjointClasses) {\n\t\t\t\tprocessSadlDisjointClasses((SadlDisjointClasses)element);\n\t\t\t}\n\t\t\telse if (element instanceof SadlSameAs) {\n\t\t\t\tprocessSadlSameAs((SadlSameAs)element);\n\t\t\t}\n\t\t\telse if (element instanceof RuleStatement) {\n\t\t\t\tprocessStatement((RuleStatement)element);\n\t\t\t}\n\t\t\telse if (element instanceof EquationStatement) {\n\t\t\t\tprocessStatement((EquationStatement)element);\n\t\t\t}\n\t\t\telse if (element instanceof PrintStatement) {\n\t\t\t\tprocessStatement((PrintStatement)element);\n\t\t\t}\n\t\t\telse if (element instanceof ReadStatement) {\n\t\t\t\tprocessStatement((ReadStatement)element);\n\t\t\t}\n\t\t\telse if (element instanceof StartWriteStatement) {\n\t\t\t\tprocessStatement((StartWriteStatement)element);\n\t\t\t}\n\t\t\telse if (element instanceof EndWriteStatement) {\n\t\t\t\tprocessStatement((EndWriteStatement)element);\n\t\t\t}\n\t\t\telse if (element instanceof ExplainStatement) {\n\t\t\t\tprocessStatement((ExplainStatement)element);\n\t\t\t}\n\t\t\telse if (element instanceof QueryStatement) {\n\t\t\t\tprocessStatement((QueryStatement)element);\n\t\t\t}\n\t\t\telse if (element instanceof SadlResource) {\n\t\t\t\tif (!SadlASTUtils.isUnit(element)) {\n\t\t\t\t\tprocessStatement((SadlResource)element);\t\t\t\t\t\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (element instanceof TestStatement) {\n\t\t\t\tprocessStatement((TestStatement)element);\n\t\t\t}\n\t\t\telse if (element instanceof ExternalEquationStatement) {\n\t\t\t\tprocessStatement((ExternalEquationStatement)element);\n\t\t\t}\n\t\t\telse if (element instanceof ExpressionStatement) {\n\t\t\t\tObject rawResult = processExpression(((ExpressionStatement)element).getExpr());\n\t\t\t\tif (isSyntheticUri(null, element.eResource())) {\n\t\t\t\t\t// for tests, do not expand; expansion, if desired, will be done upon retrieval\n\t\t\t\t\taddIntermediateFormResult(rawResult);\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// for IDE, expand and also add as info marker\n\t\t\t\t\tObject intForm = getIfTranslator().expandProxyNodes(rawResult, false, true);\n\t\t\t\t\taddIntermediateFormResult(intForm);\t\t\t\t\t\n\t\t\t\t\taddInfo(intForm.toString(), element);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthrow new JenaProcessorException(\"onValidate for element of type '\" + element.getClass().getCanonicalName() + \"' not implemented\");\n\t\t\t}\n\t\t}\n\t\tcatch (JenaProcessorException e) {\n\t\t\taddError(e.getMessage(), element);\n\t\t} catch (InvalidNameException e) {\n\t\t\te.printStackTrace();\n\t\t} catch (InvalidTypeException e) {\n\t\t\te.printStackTrace();\n\t\t} catch (TranslationException e) {\n\t\t\te.printStackTrace();\n\t\t} catch (CircularDefinitionException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t\tcatch (Throwable t) {\n\t\t\tt.printStackTrace();\n\t\t}\n\t}\n\t\n\tprivate PathToFileUriConverter getUriConverter(Resource resource) {\n\t\treturn ((XtextResource) resource).getResourceServiceProvider().get(PathToFileUriConverter.class);\n\t}\n \n\tprotected void validateResourcePathAndName(Resource resource, SadlModel model, String modelActualUrl) {\n\t\tif (!isReservedFolder(resource, model)) {\n\t\t\tif (isReservedName(resource)) {\n\t\t\t\tif (!isSyntheticUri(null, resource)) {\n\t\t\t\t\taddError(SadlErrorMessages.RESERVED_NAME.get(modelActualUrl), model);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n \n\tprivate void addImplicitBuiltinFunctionModelImportToJenaModel(Resource resource, ProcessorContext context) throws ConfigurationException, IOException, URISyntaxException, JenaProcessorException {\n\t\tif (isSyntheticUri(null, resource)) {\n\t\t\t// test case: get SadlImplicitModel OWL model from the OntModelProvider\n\t\t\tURI simTestUri = URI.createURI(SadlConstants.SADL_BUILTIN_FUNCTIONS_SYNTHETIC_URI);\n\t\t\ttry {\n\t\t\t\tsadlBuiltinFunctionModel = OntModelProvider.find(resource.getResourceSet().getResource(simTestUri, true));\n\t\t\t}\n\t\t\tcatch (Exception e) {\n\t\t\t\t// this happens if the test case doesn't cause the implicit model to be loaded--here now for backward compatibility but test cases should be fixed?\n\t\t\t\tsadlBuiltinFunctionModel = null;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tjava.nio.file.Path implfn = checkImplicitBuiltinFunctionModelExistence(resource, context);\n\t\t\tif (implfn != null) {\n\t\t\t\tfinal URI uri = getUri(resource, implfn);\n\t\t\t\tResource imrsrc = resource.getResourceSet().getResource(uri, true);\n\t\t\t\tif (sadlBuiltinFunctionModel == null) {\n\t\t\t\t\tif (imrsrc instanceof XtextResource) {\n\t\t\t\t\t\tsadlBuiltinFunctionModel = OntModelProvider.find((XtextResource)imrsrc);\n\t\t\t\t\t}\n\t\t\t\t\telse if (imrsrc instanceof ExternalEmfResource) {\n\t\t\t\t\t\tsadlBuiltinFunctionModel = ((ExternalEmfResource) imrsrc).getJenaModel();\n\t\t\t\t\t}\n\t\t\t\t\tif (sadlBuiltinFunctionModel == null) {\n\t\t\t\t\t\tif (imrsrc instanceof XtextResource) {\n\t\t\t\t\t\t\t((XtextResource) imrsrc).getResourceServiceProvider().getResourceValidator().validate(imrsrc, CheckMode.FAST_ONLY, cancelIndicator);\n\t\t\t\t\t\t\tsadlBuiltinFunctionModel = OntModelProvider.find(imrsrc);\n\t\t\t\t\t\t\tOntModelProvider.attach(imrsrc, sadlBuiltinFunctionModel, SadlConstants.SADL_BUILTIN_FUNCTIONS_URI, SadlConstants.SADL_BUILTIN_FUNCTIONS_ALIAS);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tIConfigurationManagerForIDE cm = getConfigMgr(resource, getOwlModelFormat(context));\n\t\t\t\t\t\t\tif (cm.getModelGetter() == null) {\n\t\t\t\t\t\t\t\tcm.setModelGetter(new SadlJenaModelGetter(cm, null));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcm.getModelGetter().getOntModel(SadlConstants.SADL_BUILTIN_FUNCTIONS_URI,\n\t\t\t\t\t\t\t\t\tResourceManager.getProjectUri(resource).appendSegment(ResourceManager.OWLDIR)\n\t\t\t\t\t\t\t\t\t\t\t.appendFragment(SadlConstants.OWL_BUILTIN_FUNCTIONS_FILENAME)\n\t\t\t\t\t\t\t\t\t\t\t.toFileString(),\n\t\t\t\t\t\t\t\t\tgetOwlModelFormat(context));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (sadlBuiltinFunctionModel != null) {\n\t\t\taddImportToJenaModel(getModelName(), SadlConstants.SADL_BUILTIN_FUNCTIONS_URI, SadlConstants.SADL_BUILTIN_FUNCTIONS_ALIAS, sadlBuiltinFunctionModel);\n\t\t}\n\t}\n\t\n\t/**\n\t * \n\t * @param anyResource any resource is just to \n\t * @param resourcePath the Java NIO path of the resource to load as a `platform:/resource/` if the Eclipse platform is running, otherwise\n\t * \tloads it as a file resource. \n\t */\n\tprivate URI getUri(Resource anyResource, java.nio.file.Path resourcePath) {\n\t\tPreconditions.checkArgument(anyResource instanceof XtextResource, \"Expected an Xtext resource. Got: \" + anyResource);\n\t\tif (EMFPlugin.IS_ECLIPSE_RUNNING) {\n\t\t\tIWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();\n\t\t\tjava.nio.file.Path workspaceRootPath = Paths.get(workspaceRoot.getLocationURI());\n\t\t\tjava.nio.file.Path relativePath = workspaceRootPath.relativize(resourcePath);\n\t\t\tPath relativeResourcePath = new Path(relativePath.toString());\n\t\t\treturn URI.createPlatformResourceURI(relativeResourcePath.toOSString(), true);\n\t\t} else {\n\t\t\tfinal PathToFileUriConverter uriConverter = getUriConverter(anyResource);\n\t\t\treturn uriConverter.createFileUri(resourcePath);\n\t\t}\n\t\t\n\t}\n\t\n\tprivate java.nio.file.Path checkImplicitBuiltinFunctionModelExistence(Resource resource, ProcessorContext context) throws IOException, ConfigurationException {\n\t\tUtilsForJena ufj = new UtilsForJena();\n\t\tString policyFileUrl = ufj.getPolicyFilename(resource);\n\t\tString policyFilename = policyFileUrl != null ? ufj.fileUrlToFileName(policyFileUrl) : null;\n\t\tif (policyFilename != null) {\n\t\t\tFile projectFolder = new File(policyFilename).getParentFile().getParentFile();\n\t\t\tif(projectFolder == null){\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tString relPath = SadlConstants.SADL_IMPLICIT_MODEL_FOLDER + \"/\" + SadlConstants.SADL_BUILTIN_FUNCTIONS_FILENAME;\n\t\t\tString platformPath = projectFolder.getName() + \"/\" + relPath;\n\t\t\tString implicitSadlModelFN = projectFolder + \"/\" + relPath;\n\t\t\tFile implicitModelFile = new File(implicitSadlModelFN);\n\t\t\tif (!implicitModelFile.exists()) {\n\t\t\t\tcreateBuiltinFunctionImplicitModel(projectFolder.getAbsolutePath());\n\t\t\t\ttry {\n\t\t\t\t\tResource newRsrc = resource.getResourceSet().createResource(URI.createPlatformResourceURI(platformPath, false)); \n\t\t\t\t\tnewRsrc.load(resource.getResourceSet().getLoadOptions());\n\t\t\t\t\trefreshResource(newRsrc);\n\t\t\t\t}\n\t\t\t\tcatch (Throwable t) {}\n\t\t\t}\n\t\t\treturn implicitModelFile.getAbsoluteFile().toPath();\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprivate void addImplicitSadlModelImportToJenaModel(Resource resource, ProcessorContext context) throws IOException, ConfigurationException, URISyntaxException, JenaProcessorException {\n\t\tif (isSyntheticUri(null, resource)) {\n\t\t\t// test case: get SadlImplicitModel OWL model from the OntModelProvider\n\t\t\tURI simTestUri = URI.createURI(SadlConstants.SADL_IMPLICIT_MODEL_SYNTHETIC_URI);\n\t\t\ttry {\n\t\t\t\tsadlImplicitModel = OntModelProvider.find(resource.getResourceSet().getResource(simTestUri, true));\n\t\t\t}\n\t\t\tcatch (Exception e) {\n\t\t\t\t// this happens if the test case doesn't cause the implicit model to be loaded--here now for backward compatibility but test cases should be fixed?\n\t\t\t\tsadlImplicitModel = null;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tjava.nio.file.Path implfn = checkImplicitSadlModelExistence(resource, context);\n\t\t\tif (implfn != null) {\n\t\t\t\tfinal URI uri = getUri(resource, implfn);\n\t\t\t\tResource imrsrc = resource.getResourceSet().getResource(uri, true);\n\t\t\t\tif (sadlImplicitModel == null) {\n\t\t\t\t\tif (imrsrc instanceof XtextResource) {\n\t\t\t\t\t\tsadlImplicitModel = OntModelProvider.find((XtextResource)imrsrc);\n\t\t\t\t\t}\n\t\t\t\t\telse if (imrsrc instanceof ExternalEmfResource) {\n\t\t\t\t\t\tsadlImplicitModel = ((ExternalEmfResource) imrsrc).getJenaModel();\n\t\t\t\t\t}\n\t\t\t\t\tif (sadlImplicitModel == null) {\n\t\t\t\t\t\tif (imrsrc instanceof XtextResource) {\n\t\t\t\t\t\t\t((XtextResource) imrsrc).getResourceServiceProvider().getResourceValidator().validate(imrsrc, CheckMode.FAST_ONLY, cancelIndicator);\n\t\t\t\t\t\t\tsadlImplicitModel = OntModelProvider.find(imrsrc);\n\t\t\t\t\t\t\tOntModelProvider.attach(imrsrc, sadlImplicitModel, SadlConstants.SADL_IMPLICIT_MODEL_URI, SadlConstants.SADL_IMPLICIT_MODEL_PREFIX);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tIConfigurationManagerForIDE cm = getConfigMgr(resource, getOwlModelFormat(context));\n\t\t\t\t\t\t\tif (cm.getModelGetter() == null) {\n\t\t\t\t\t\t\t\tcm.setModelGetter(new SadlJenaModelGetter(cm, null));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcm.getModelGetter().getOntModel(SadlConstants.SADL_IMPLICIT_MODEL_URI,\n\t\t\t\t\t\t\t\t\tResourceManager.getProjectUri(resource).appendSegment(ResourceManager.OWLDIR)\n\t\t\t\t\t\t\t\t\t\t\t.appendFragment(SadlConstants.OWL_IMPLICIT_MODEL_FILENAME)\n\t\t\t\t\t\t\t\t\t\t\t.toFileString(),\n\t\t\t\t\t\t\t\t\tgetOwlModelFormat(context));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (sadlImplicitModel != null) {\n\t\t\taddImportToJenaModel(getModelName(), SadlConstants.SADL_IMPLICIT_MODEL_URI, SadlConstants.SADL_IMPLICIT_MODEL_PREFIX, sadlImplicitModel);\n\t\t}\n\t}\n\t\n\tprivate void addSadlBaseModelImportToJenaModel(Resource resource) throws IOException, ConfigurationException, URISyntaxException, JenaProcessorException {\n\t\tif (sadlBaseModel == null) {\n\t\t\tsadlBaseModel = OntModelProvider.getSadlBaseModel();\n\t\t\tif (sadlBaseModel == null) {\n\t\t\t\tsadlBaseModel = getOntModelFromString(resource, getSadlBaseModel());\n\t\t\t\tOntModelProvider.setSadlBaseModel(sadlBaseModel);\n\t\t\t}\n\t\t}\n\t\taddImportToJenaModel(getModelName(), SadlConstants.SADL_BASE_MODEL_URI, SadlConstants.SADL_BASE_MODEL_PREFIX, sadlBaseModel);\n\t}\n\t\n\tprotected void addAnnotationsToResource(OntResource modelOntology, EList anns) {\n\t\tIterator iter = anns.iterator();\n\t\twhile (iter.hasNext()) {\n\t\t\tSadlAnnotation ann = iter.next();\n\t\t\tString anntype = ann.getType();\n\t\t\tEList annContents = ann.getContents();\n\t\t\tIterator anniter = annContents.iterator();\n\t\t\twhile (anniter.hasNext()) {\n\t\t\t\tString annContent = anniter.next();\n\t\t\t\tif (anntype.equalsIgnoreCase(AnnType.ALIAS.toString())) {\n\t\t\t\t\tmodelOntology.addLabel(annContent, \"en\");\n\t\t\t\t}\n\t\t\t\telse if (anntype.equalsIgnoreCase(AnnType.NOTE.toString())) {\n\t\t\t\t\tmodelOntology.addComment(annContent, \"en\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic OntModel prepareEmptyOntModel(Resource resource) throws ConfigurationException {\n\t\ttry {\n\t\t\tIConfigurationManagerForIDE cm = getConfigMgr(resource, getOwlModelFormat(getProcessorContext()));\n\t\t\tOntDocumentManager owlDocMgr = cm.getJenaDocumentMgr();\n\t\t\tOntModelSpec spec = new OntModelSpec(OntModelSpec.OWL_MEM);\n\t\t\tsetSpec(spec);\n\t\t\tString modelFolderPathname = getModelFolderPath(resource);\n\t\t\tif (modelFolderPathname != null && !modelFolderPathname.startsWith(SYNTHETIC_FROM_TEST)) {\n\t\t\t\tFile mff = new File(modelFolderPathname);\n\t\t\t\tmff.mkdirs();\n\t\t\t\tspec.setImportModelGetter(new SadlJenaModelGetterPutter(spec, modelFolderPathname));\n\t\t\t}\n\t\t\tif (owlDocMgr != null) {\n\t\t\t\tspec.setDocumentManager(owlDocMgr);\n\t\t\t\towlDocMgr.setProcessImports(true);\n\t\t\t}\n\t\t\treturn ModelFactory.createOntologyModel(spec);\n\t\t}\n\t\tcatch (ConfigurationException e) {\n\t\t\te.printStackTrace();\n\t\t\tthrow e;\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t\tthrow new ConfigurationException(e.getMessage(), e);\n\t\t}\n\t}\n\t\n\tprivate void setProcessorContext(ProcessorContext ctx) {\n\t\tprocessorContext = ctx;\n\t}\n\t\n\tprivate ProcessorContext getProcessorContext() {\n\t\treturn processorContext;\n\t}\n\t\n\tprotected String countPlusLabel(int count, String label) {\n\t\tif (count == 0 || count > 1) {\n\t\t\tlabel = label + \"s\";\n\t\t}\n\t\treturn \"\" + count + \" \" + label;\n\t}\n\n\tprivate void addImportToJenaModel(String modelName, String importUri, String importPrefix, Model importedOntModel) {\n\t\tgetTheJenaModel().getDocumentManager().addModel(importUri, importedOntModel, true);\n\t\tOntology modelOntology = getTheJenaModel().createOntology(modelName);\n\t\tif (importPrefix == null) {\n\t\t\ttry {\n\t\t\t\timportPrefix = getConfigMgr(getCurrentResource(), getOwlModelFormat(getProcessorContext())).getGlobalPrefix(importUri);\n\t\t\t} catch (ConfigurationException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\tif (importPrefix != null) {\n\t\t\tgetTheJenaModel().setNsPrefix(importPrefix, importUri);\n\t\t}\n\t\tcom.hp.hpl.jena.rdf.model.Resource importedOntology = getTheJenaModel().createResource(importUri);\n\t\tmodelOntology.addImport(importedOntology);\n\t\tgetTheJenaModel().addSubModel(importedOntModel);\n\t\tgetTheJenaModel().addLoadedImport(importUri);\n//\t\tgetTheJenaModel().loadImports();\n//\t\tIConfigurationManagerForIDE cm;\n//\t\ttry {\n//\t\t\tcm = getConfigMgr(getCurrentResource(), getOwlModelFormat(getProcessorContext()));\n//\t\t\tcm.loadImportedModel(modelOntology, getTheJenaModel(), importUri, cm.getAltUrlFromPublicUri(importUri));\n//\t\t} catch (ConfigurationException e) {\n//\t\t\tthrow new JenaTransactionException(\"Unable to load imported model '\" + importUri + \"'\", e);\n//\t\t}\n\t\taddOrderedImport(importUri);\n\t}\n\n//\t/**\n//\t * Method to determine the OWL model URI and actual URL for each import and add that, along with the prefix,\n//\t * to the Jena OntDocumentManager so that it will be loaded when we do a Jena loadImports\n//\t * @param sadlImports -- the list of imports to \n//\t * @return \n//\t */\n//\tprivate List getIndirectImportResources(SadlModel model) {\n//\t\tEList implist = model.getImports();\n//\t\tIterator impitr = implist.iterator();\n//\t\tif (impitr.hasNext()) {\n//\t\t\tList importedResources = new ArrayList();\n//\t\t\twhile (impitr.hasNext()) {\n//\t\t\t\tSadlImport simport = impitr.next();\n//\t\t\t\tSadlModel importedModel = simport.getImportedResource();\n//\t\t\t\tif (importedModel != null) {\n//\t\t\t\t\tString importUri = importedModel.getBaseUri();\n//\t\t\t\t\tString importPrefix = simport.getAlias();\n//\t\t \t\tif (importPrefix != null) {\n//\t\t \t\t\tgetTheJenaModel().setNsPrefix(importPrefix, assureNamespaceEndsWithHash(importUri));\n//\t\t \t\t}\n//\t\t\t \timportedResources.add(importedModel.eResource());\n//\t\t\t\t}\n//\t\t\t\telse {\n//\t\t\t\t\taddError(\"Unable to obtain import URI\", simport);\n//\t\t\t\t}\n//\t\t\t\tList moreImports = getIndirectImportResources(importedModel);\n//\t\t\t\tif (moreImports != null) {\n//\t\t\t\t\timportedResources.addAll(moreImports);\n//\t\t\t\t}\n//\t\t\t}\n//\t\t\treturn importedResources;\n//\t\t}\n//\t\treturn null;\n//\t}\n\t\n\t/**\n\t * Method to check for erroneous use of a reserved folder name\n\t * @param resource\n\t * @param model\n\t * @return\n\t */\n\tprivate boolean isReservedFolder(Resource resource, SadlModel model) {\n\t\tURI prjuri = ResourceManager.getProjectUri(resource);\n\t\tif (prjuri == null) {\n\t\t\treturn false;\t// this is the path that JUnit tests will follow\n\t\t}\n\t\tURI rsrcuri = resource.getURI();\n\t\tString[] rsrcsegs = rsrcuri.segments();\n\t\tString[] prjsegs = prjuri.segments();\n\t\tif (rsrcsegs.length > prjsegs.length) {\n\t\t\tString topPrjFolder = rsrcsegs[prjsegs.length];\n\t\t\tfor (String fnm:reservedFolderNames) {\n\t\t\t\tif (topPrjFolder.equals(fnm)) {\n\t\t\t\t\tif (fnm.equals(SadlConstants.SADL_IMPLICIT_MODEL_FOLDER)) {\n\t\t\t\t\t\tif (!isReservedName(resource)) {\n\t\t\t\t\t\t\t// only reserved names allowed here\n\t\t\t\t\t\t\taddError(SadlErrorMessages.RESERVED_FOLDER.get(fnm), model);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\taddError(SadlErrorMessages.RESERVED_FOLDER.get(fnm), model);\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate boolean isReservedName(Resource resource) {\n\t\tString nm = resource.getURI().lastSegment();\n\t\tfor (String rnm:reservedFileNames) {\n\t\t\tif (rnm.equals(nm)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprivate void processStatement(SadlResource element) throws TranslationException {\n\t\tObject srobj = processExpression(element);\n\t\tint i = 0;\n\t}\n\t\n\tpublic Test[] processStatement(TestStatement element) throws JenaProcessorException {\n\t\tTest[] generatedTests = null;\n\t\tTest sadlTest = null;\n\t\tboolean done = false;\n\t\ttry {\n\t\t\tEList tests = element.getTests();\n\t\t\tfor (int tidx = 0; tidx < tests.size(); tidx++) {\n\t\t\t\tExpression expr = tests.get(tidx);\n\t\t\t\t// we know it's a Test so create one and set as translation target\n\t\t\t\tTest test = new Test();\n\t\t\t\tfinal ICompositeNode node = NodeModelUtils.findActualNodeFor(element);\n\t\t\t\tif (node != null) {\n\t\t\t\t\ttest.setOffset(node.getOffset() - 1);\n\t\t\t\t\ttest.setLength(node.getLength());\n\t\t\t\t}\n\t\t\t\tsetTarget(test);\n\t\n\t\t\t\t// now translate the test expression\n\t\t\t\tObject testtrans = processExpression(expr);\n\t\t\t\t\n\t\t\t\t// Examine testtrans, the results of the translation.\n\t\t\t\t// The recognition of various Test patterns, so that the LHS, RHS, Comparison of the Test can be\n\t\t\t\t// properly set is best done on the translation before the ProxyNodes are expanded--their expansion\n\t\t\t\t// destroys needed information and introduces ambiguity\n\t\t\t\n\t\t\t\tif (testtrans instanceof BuiltinElement \n\t\t\t\t\t\t&& IntermediateFormTranslator.isComparisonBuiltin(((BuiltinElement)testtrans).getFuncName())) {\n\t\t\t\t\tList args = ((BuiltinElement)testtrans).getArguments();\n\t\t\t\t\tif (args != null && args.size() == 2) {\n\t\t\t\t\t\ttest.setCompName(((BuiltinElement)testtrans).getFuncType());\n\t\t\t\t\t\tObject lhsObj = getIfTranslator().expandProxyNodes(args.get(0), false, true);\n\t\t\t\t\t\tObject rhsObj = getIfTranslator().expandProxyNodes(args.get(1), false, true);\n\t\t\t\t\t\ttest.setLhs((lhsObj != null && lhsObj instanceof List && ((List)lhsObj).size() > 0) ? lhsObj : args.get(0));\n\t\t\t\t\t\ttest.setRhs((rhsObj != null && rhsObj instanceof List && ((List)rhsObj).size() > 0) ? rhsObj : args.get(1));\n\t\t\t\t\t\tgeneratedTests = new Test[1];\n\t\t\t\t\t\tgeneratedTests[0] = test;\n\t\t\t\t\t\tdone = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (testtrans instanceof TripleElement) {\n\t\t\t\t\tif (((TripleElement)testtrans).getModifierType() != null &&\n\t\t\t\t\t\t\t!((TripleElement)testtrans).getModifierType().equals(TripleModifierType.None)) {\n\t\t\t\t\t\t// Filtered query with modification\n\t\t\t\t\t\tTripleModifierType ttype = ((TripleElement)testtrans).getModifierType();\n\t\t\t\t\t\tObject trans = getIfTranslator().expandProxyNodes(testtrans, false, true);\n\t\t\t\t\t\tif ((trans != null && trans instanceof List && ((List)trans).size() > 0)) {\n\t\t\t\t\t\t\tif (ttype.equals(TripleModifierType.Not)) {\n\t\t\t\t\t\t\t\tif (changeFilterDirection(trans)) {\n\t\t\t\t\t\t\t\t\t((TripleElement)testtrans).setType(TripleModifierType.None);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ttest.setLhs(trans);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tif (ttype.equals(TripleModifierType.Not)) {\n\t\t\t\t\t\t\t\tchangeFilterDirection(testtrans);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ttest.setLhs(testtrans);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tgeneratedTests = new Test[1];\n\t\t\t\t\t\tgeneratedTests[0] = test;\n\t\t\t\t\t\tdone = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (!done) {\n\t\t\t\t\t// expand ProxyNodes and see what we can do with the expanded form\n\t\t\t\t\tList expanded = new ArrayList();\n\t\t\t\t\tObject testExpanded = getIfTranslator().expandProxyNodes(testtrans, false, true);\n\t\t\t\t\tboolean treatAsMultipleTests = false; {\n\t\t\t\t\t\tif (testExpanded instanceof List) {\n\t\t\t\t\t\t\ttreatAsMultipleTests = containsMultipleTests((List) testExpanded);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (treatAsMultipleTests && testExpanded instanceof List) {\n\t\t\t\t\t\tfor (int i = 0; i < ((List)testExpanded).size(); i++) {\n\t\t\t\t\t\t\texpanded.add(((List)testExpanded).get(i));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\texpanded.add(testExpanded);\n\t\t\t\t\t}\n\t\n\t\t\t\t\tif (expanded.size() == 0) {\n\t\t\t\t\t\tgeneratedTests = new Test[1];\n\t\t\t\t\t\tgeneratedTests[0] = test;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tgeneratedTests = new Test[expanded.size()];\n\t\t\n\t\t\t\t\t\tfor (int i = 0; expanded != null && i < expanded.size(); i++) {\n\t\t\t\t\t\t\tObject testgpe = expanded.get(i);\n\t\t\t\t\t\t\tif (i > 0) {\n\t\t\t\t\t\t\t\t// not the first element; need a new Test\n\t\t\t\t\t\t\t\ttest = new Test();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tgeneratedTests[i] = test;\n\t\t\n\t\t\t\t\t\t\t// Case 3: the test translates into a TripleElement\n\t\t\t\t\t\t\tif (testgpe instanceof TripleElement) {\n\t\t\t\t\t\t\t\ttest.setLhs(testgpe); \n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (!done && testgpe instanceof List) {\n\t\t\t\t\t\t\t\ttest.setLhs(testgpe);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tfor (int i = 0; generatedTests != null && i < generatedTests.length; i++) {\n\t\t\t\tsadlTest = generatedTests[i];\n\t\t\t\tapplyImpliedProperties(sadlTest, tests.get(0));\n\t\t\t\tgetIfTranslator().postProcessTest(sadlTest, element);\n//\t\t\t\tICompositeNode node = NodeModelUtils.findActualNodeFor(element);\n//\t\t\t\tif (node != null) {\n//\t\t\t\t\t\ttest.setLineNo(node.getStartLine());\n//\t\t\t\t\t\ttest.setLength(node.getLength());\n//\t\t\t\t\t\ttest.setOffset(node.getOffset());\n//\t\t\t\t}\n\t\t\n\t\t\t\tlogger.debug(\"Test translation: {}\", sadlTest);\n\t\t\t\tList transErrors = getIfTranslator().getErrors();\n\t\t\t\tfor (int j = 0; transErrors != null && j < transErrors.size(); j++) {\n\t\t\t\t\tIFTranslationError err = transErrors.get(j);\n\t\t\t\t\ttry {\n\t\t\t\t\t\taddError(err.getLocalizedMessage(), element);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (Exception e) {\n\t\t\t\t\t\t// this will happen for standalone testing where there is no Eclipse Workspace\n\t\t\t\t\t\tlogger.error(\"Test: \" + sadlTest.toString());\n\t\t\t\t\t\tlogger.error(\" Translation error: \" + err.getLocalizedMessage() + \n\t\t\t\t\t\t\t\t(err.getCause() != null ? (\" (\" + err.getCause().getLocalizedMessage() + \")\") : \"\"));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tvalidateTest(element, sadlTest);\n\t\t\t\taddSadlCommand(sadlTest);\n\t\t\t}\n\t\t\treturn generatedTests;\n\t\t} catch (InvalidNameException e) {\n\t\t\taddError(SadlErrorMessages.INVALID_NAME.get(\"test\", e.getMessage()), element);\n\t\t\te.printStackTrace();\n\t\t} catch (InvalidTypeException e) {\n\t\t\taddError(SadlErrorMessages.INVALID_PROP_TYPE.get(e.getMessage()), element);\n\t\t\te.printStackTrace();\n\t\t} catch (TranslationException e) {\n\t\t\taddError(SadlErrorMessages.TEST_TRANSLATION_EXCEPTION.get(e.getMessage()), element);\n//\t\t\te.printStackTrace();\n\t\t}\n\t\treturn generatedTests;\n\t}\n\t\n\tprivate void applyImpliedProperties(Test sadlTest, Expression element) throws TranslationException {\n\t\tsadlTest.setLhs(applyImpliedPropertiesToSide(sadlTest.getLhs(), element));\n\t\tsadlTest.setRhs(applyImpliedPropertiesToSide(sadlTest.getRhs(), element));\n\t}\n\t\n\tprivate Object applyImpliedPropertiesToSide(Object side, Expression element) throws TranslationException {\n\t\tMap> impprops = OntModelProvider.getAllImpliedProperties(getCurrentResource());\n\t\tif (impprops != null) {\n\t\t\tIterator imppropitr = impprops.keySet().iterator();\n\t\t\twhile (imppropitr.hasNext()) {\n\t\t\t\tEObject eobj = imppropitr.next();\n\t\t\t\tString uri = null;\n\t\t\t\tif (eobj instanceof SadlResource) {\n\t\t\t\t\turi = getDeclarationExtensions().getConceptUri((SadlResource)eobj);\n\t\t\t\t}\n\t\t\t\telse if (eobj instanceof Name) {\n\t\t\t\t\turi = getDeclarationExtensions().getConceptUri(((Name)eobj).getName());\n\t\t\t\t}\n\t\t\t\tif (uri != null) {\n\t\t\t\t\tif (side instanceof NamedNode) {\n\t\t\t\t\t\tif (((NamedNode)side).toFullyQualifiedString().equals(uri)) {\n\t\t\t\t\t\t\tList props = impprops.get(eobj);\n\t\t\t\t\t\t\tif (props != null && props.size() > 0) {\n\t\t\t\t\t\t\t\tif (props.size() > 1) {\n\t\t\t\t\t\t\t\t\tthrow new TranslationException(\"More than 1 implied property found!\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t// apply impliedProperties\n\t\t\t\t\t\t\t\tNamedNode pred = new NamedNode(props.get(0).getURI());\n\t\t\t\t\t\t\t\tif (props.get(0) instanceof DatatypeProperty) {\n\t\t\t\t\t\t\t\t\tpred.setNodeType(NodeType.DataTypeProperty);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse if (props.get(0) instanceof ObjectProperty) {\n\t\t\t\t\t\t\t\t\tpred.setNodeType(NodeType.ObjectProperty);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\tpred.setNodeType(NodeType.PropertyNode);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn new TripleElement((NamedNode)side, pred, new VariableNode(getNewVar(element)));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn side;\t\t\n\t}\n\t\n\tpublic VariableNode createVariable(SadlResource sr) throws IOException, PrefixNotFoundException, InvalidNameException, InvalidTypeException, TranslationException, ConfigurationException {\n\t\tVariableNode var = createVariable(getDeclarationExtensions().getConceptUri(sr));\n\t\tif (var.getType() != null) {\n\t\t\treturn var;\t// all done\n\t\t}\n\t\tSadlResource decl = getDeclarationExtensions().getDeclaration(sr);\n\t\tEObject defnContainer = decl.eContainer();\n\t\ttry {\n\t\t\tTypeCheckInfo tci = null;\n\t\t\tif (defnContainer instanceof BinaryOperation) {\n\t\t\t\tif (((BinaryOperation)defnContainer).getLeft().equals(decl)) {\n\t\t\t\t\tExpression defn = ((BinaryOperation)defnContainer).getRight();\n\t\t\t\t\ttci = getModelValidator().getType(defn);\n\t\t\t\t}\n\t\t\t\telse if (((BinaryOperation)defnContainer).getLeft() instanceof PropOfSubject) {\n\t\t\t\t\ttci = getModelValidator().getType(((BinaryOperation)defnContainer).getLeft());\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (defnContainer instanceof SadlParameterDeclaration) {\n\t\t\t\tSadlTypeReference type = ((SadlParameterDeclaration)defnContainer).getType();\n\t\t\t\ttci = getModelValidator().getType(type);\n\t\t\t}\n\t\t\telse if (defnContainer instanceof SubjHasProp) {\n\t\t\t\tif (((SubjHasProp)defnContainer).getLeft().equals(decl)) {\n\t\t\t\t\t// need domain of property\n\t\t\t\t\tExpression pexpr = ((SubjHasProp)defnContainer).getProp();\n\t\t\t\t\tif (pexpr instanceof SadlResource) {\n\t\t\t\t\t\tString puri = getDeclarationExtensions().getConceptUri((SadlResource)pexpr);\n\t\t\t\t\t\tOntConceptType ptype = getDeclarationExtensions().getOntConceptType((SadlResource)pexpr);\n\t\t\t\t\t\tif (isProperty(ptype)) {\n\t\t\t\t\t\t\tProperty prop = getTheJenaModel().getProperty(puri);\n\t\t\t\t\t\t\ttci = getModelValidator().getTypeInfoFromDomain(new ConceptName(puri), prop, defnContainer);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\taddError(\"Right of SubjHasProp not handled (\" + ptype.toString() + \")\", defnContainer);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\taddError(\"Right of SubjHasProp not a Name (\" + pexpr.getClass().toString() + \")\", defnContainer);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (((SubjHasProp)defnContainer).getRight().equals(decl)) {\n\t\t\t\t\t// need range of property\n\t\t\t\t\ttci = getModelValidator().getType(((SubjHasProp)defnContainer).getProp());\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (!isContainedBy(sr, QueryStatement.class)) {\n\t\t\t\taddError(\"Unhandled variable definition\", sr);\n\t\t\t}\n\t\t\tif (tci != null && tci.getTypeCheckType() instanceof ConceptName) {\n\t\t\t\tif (var.getType() == null) {\n\t\t\t\t\tvar.setType(conceptNameToNamedNode((ConceptName)tci.getTypeCheckType()));\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (!var.getType().toFullyQualifiedString().equals(tci.getTypeCheckType().toString())) {\n\t\t\t\t\t\taddError(\"Changing type of variable '\" + var.getName() + \"' from '\" + var.getType().toFullyQualifiedString() + \"' to '\" + tci.getTypeCheckType().toString() + \"' not allowed.\", sr);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (URISyntaxException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t} catch (DontTypeCheckException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t} catch (CircularDefinitionException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t} catch (CircularDependencyException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t} catch (PropertyWithoutRangeException e) {\n\t\t\taddError(\"Property does not have a range\", defnContainer);\n\t\t}\n\t\treturn var;\n\t}\n\n\tprivate boolean isContainedBy(EObject eobj, Class cls) {\n\t\tif (eobj.eContainer() != null) {\n// TODO fix this to be generic\n\t\t\tif (eobj.eContainer() instanceof QueryStatement) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn isContainedBy(eobj.eContainer(), cls);\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprotected VariableNode createVariable(String name) throws IOException, PrefixNotFoundException, InvalidNameException, InvalidTypeException, TranslationException, ConfigurationException {\n\t\tObject trgt = getTarget();\n\t\tif (trgt instanceof Rule) {\n\t\t\tif (((Rule)trgt).getVariable(name) != null) {\n\t\t\t\treturn ((Rule)trgt).getVariable(name);\n\t\t\t}\n\t\t}\n\t\telse if (trgt instanceof Query) {\n\t\t\tif (((Query)trgt).getVariable(name) != null) {\n\t\t\t\treturn ((Query)trgt).getVariable(name);\n\t\t\t}\n\t\t}\n\t\telse if (trgt instanceof Test) {\n\t\t\t// TODO\n\t\t}\n\t\tVariableNode newVar = new VariableNode(name);\n\t\tif (trgt instanceof Rule) {\n\t\t\t((Rule)trgt).addRuleVariable(newVar);\n\t\t}\n\t\telse if (trgt instanceof Query) {\n\t\t\t((Query)trgt).addVariable(newVar);\n\t\t}\n\t\telse if (trgt instanceof Test) {\n\t\t\t// TODO\n\t\t}\n\t\treturn newVar;\n\t}\n\t\n\tprivate boolean containsMultipleTests(List testtrans) {\n\t\tif (testtrans.size() == 1) {\n\t\t\treturn false;\n\t\t}\n\t\tList vars = new ArrayList();\n\t\tfor (int i = 0; i < testtrans.size(); i++) {\n\t\t\tGraphPatternElement gpe = testtrans.get(i);\n\t\t\tif (gpe instanceof TripleElement) {\n\t\t\t\tNode anode = ((TripleElement)gpe).getSubject();\n\t\t\t\tif (vars.contains(anode)) {\n\t\t\t\t\treturn false; // there are vars between patterns\n\t\t\t\t}\n\t\t\t\telse if (anode instanceof VariableNode) {\n\t\t\t\t\tvars.add((VariableNode) anode);\n\t\t\t\t}\n\t\t\t\tanode = ((TripleElement)gpe).getObject();\n\t\t\t\tif (vars.contains(anode)) {\n\t\t\t\t\treturn false; // there are vars between patterns\n\t\t\t\t}\n\t\t\t\telse if (anode instanceof VariableNode){\n\t\t\t\t\tvars.add((VariableNode) anode);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (gpe instanceof BuiltinElement) {\n\t\t\t\tList args = ((BuiltinElement)gpe).getArguments();\n\t\t\t\tfor (int j = 0; args != null && j < args.size(); j++) {\n\t\t\t\t\tNode anode = args.get(j);\n\t\t\t\t\tif (anode instanceof VariableNode && vars.contains(anode)) {\n\t\t\t\t\t\treturn false; // there are vars between patterns\n\t\t\t\t\t}\n\t\t\t\t\telse if (anode instanceof VariableNode) {\n\t\t\t\t\t\tvars.add((VariableNode) anode);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n private boolean changeFilterDirection(Object patterns) {\n\t\tif (patterns instanceof List) {\n\t\t\tfor (int i = 0; i < ((List)patterns).size(); i++) {\n\t\t\t\tObject litem = ((List)patterns).get(i);\n\t\t\t\tif (litem instanceof BuiltinElement) {\n\t\t\t\t\tIntermediateFormTranslator.builtinComparisonComplement((BuiltinElement)litem);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate int validateTest(EObject object, Test test) {\n\t\tint numErrors = 0;\n\t\tObject lhs = test.getLhs();\n\t\tif (lhs instanceof GraphPatternElement) {\n\t\t\tnumErrors += validateGraphPatternElement(object, (GraphPatternElement)lhs);\n\t\t}\n\t\telse if (lhs instanceof List) {\n\t\t\tfor (int i = 0; i < ((List)lhs).size(); i++) {\n\t\t\t\tObject lhsinst = ((List)lhs).get(i);\n\t\t\t\tif (lhsinst instanceof GraphPatternElement) {\n\t\t\t\t\tnumErrors += validateGraphPatternElement(object, (GraphPatternElement)lhsinst);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tObject rhs = test.getLhs();\n\t\tif (rhs instanceof GraphPatternElement) {\n\t\t\tnumErrors += validateGraphPatternElement(object, (GraphPatternElement)rhs);\n\t\t}\n\t\telse if (rhs instanceof List) {\n\t\t\tfor (int i = 0; i < ((List)rhs).size(); i++) {\n\t\t\t\tObject rhsinst = ((List)rhs).get(i);\n\t\t\t\tif (rhsinst instanceof GraphPatternElement) {\n\t\t\t\t\tnumErrors += validateGraphPatternElement(object, (GraphPatternElement)rhsinst);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn numErrors;\n\t}\n\t\n /**\n * This method checks a GraphPatternElement for errors and warnings and generates the same if found.\n * \n * @param gpe\n * @return\n */\n private int validateGraphPatternElement(EObject object, GraphPatternElement gpe) {\n \tint numErrors = 0;\n\t\tif (gpe instanceof TripleElement) {\n\t\t\tif (((TripleElement) gpe).getSubject() instanceof NamedNode &&\n\t\t\t\t\t((NamedNode)((TripleElement)gpe).getSubject()).getNodeType().equals(NodeType.PropertyNode)) {\n\t\t\t\taddError(SadlErrorMessages.UNEXPECTED_TRIPLE.get(((NamedNode)((TripleElement)gpe).getSubject()).getName()), object);\n\t\t\t\tnumErrors++;\n\t\t\t}\n\t\t\tif (((TripleElement) gpe).getObject() instanceof NamedNode &&\n\t\t\t\t\t((NamedNode)((TripleElement)gpe).getObject()).getNodeType().equals(NodeType.PropertyNode)) {\n\t\t\t\tif (!(((TripleElement)gpe).getPredicate() instanceof NamedNode) || \n\t\t\t\t\t\t!((NamedNode)((TripleElement)gpe).getPredicate()).getNamespace().equals(OWL.NAMESPACE.getNameSpace())) {\n\t\t\t\t\taddError(SadlErrorMessages.UNEXPECTED_TRIPLE.get(((NamedNode)((TripleElement)gpe).getSubject()).getName()), object);\n\t\t\t\t\tnumErrors++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (((TripleElement) gpe).getPredicate() instanceof NamedNode &&\n\t\t\t\t\t!(((NamedNode)((TripleElement)gpe).getPredicate()).getNodeType().equals(NodeType.PropertyNode)) &&\n\t\t\t\t\t!(((NamedNode)((TripleElement)gpe).getPredicate()).getNodeType().equals(NodeType.ObjectProperty)) &&\n\t\t\t\t\t!(((NamedNode)((TripleElement)gpe).getPredicate()).getNodeType().equals(NodeType.DataTypeProperty))) {\n\t\t\t\tif (((NamedNode)((TripleElement)gpe).getPredicate()).getNodeType().equals(NodeType.VariableNode)) {\n\t\t\t\t\taddWarning(SadlErrorMessages.VARIABLE_INSTEAD_OF_PROP.get(((NamedNode)((TripleElement)gpe).getPredicate()).getName()), object);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\taddError(SadlErrorMessages.EXPECTED_A.get(\"property as triple pattern predicate rather than \" + \n\t\t\t\t\t\t\t((NamedNode)((TripleElement)gpe).getPredicate()).getNodeType().toString() + \" \" + \n\t\t\t\t\t\t\t((NamedNode)((TripleElement)gpe).getPredicate()).getName()), object);\n\t\t\t\t\tnumErrors++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if (gpe instanceof BuiltinElement) {\n\t\t\tif (((BuiltinElement)gpe).getFuncType().equals(BuiltinType.Not)) {\n\t\t\t\tList args = ((BuiltinElement)gpe).getArguments();\n\t\t\t\tif (args != null && args.size() == 1 && args.get(0) instanceof KnownNode) {\n\t\t\t\t\taddError(SadlErrorMessages.PHRASE_NOT_KNOWN.toString(), object);\n\t\t\t\t\taddError(\"Phrase 'not known' is not a valid graph pattern; did you mean 'is not known'?\", object);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (gpe.getNext() != null) {\n\t\t\tnumErrors += validateGraphPatternElement(object, gpe.getNext());\n\t\t}\n\t\treturn numErrors;\n\t}\n \n\tprivate void processStatement(ExplainStatement element) throws JenaProcessorException, InvalidNameException, InvalidTypeException, TranslationException {\n\t\tString ruleName = element.getRulename() != null ? declarationExtensions.getConcreteName(element.getRulename()) : null;\n\t\tif (ruleName != null) {\n\t\t\tExplain cmd = new Explain(ruleName);\n\t\t\taddSadlCommand(cmd);\n\t\t}\n\t\telse {\n\t\t\tObject result = processExpression(element.getExpr());\n\t\t\tif (result instanceof GraphPatternElement) {\n\t\t\t\tExplain cmd = new Explain((GraphPatternElement)result);\n\t\t\t\taddSadlCommand(cmd);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthrow new TranslationException(\"Unhandled ExplainStatement: \" + result.toString());\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprivate void processStatement(StartWriteStatement element) throws JenaProcessorException {\n\t\tString dataOnly = element.getDataOnly();\n\t\tStartWrite cmd = new StartWrite(dataOnly != null);\n\t\taddSadlCommand(cmd);\n\t}\n\t\n\tprivate void processStatement(EndWriteStatement element) throws JenaProcessorException {\n\t\tString outputFN = element.getFilename();\n\t\tEndWrite cmd = new EndWrite(outputFN);\n\t\taddSadlCommand(cmd);\n\t}\n\t\n\tprivate void processStatement(ReadStatement element) throws JenaProcessorException {\n\t\tString filename = element.getFilename();\n\t\tString templateFilename = element.getTemplateFilename();\n\t\tRead readCmd = new Read(filename, templateFilename);\n\t\taddSadlCommand(readCmd);\n\t}\n\t\n\tprivate void processStatement(PrintStatement element) throws JenaProcessorException {\n\t\tString dispStr = ((PrintStatement)element).getDisplayString();\n\t\tPrint print = new Print(dispStr);\n\t\tString mdl = ((PrintStatement)element).getModel();\n\t\tif (mdl != null) {\n\t\t\tprint.setModel(mdl);\n\t\t}\n\t\taddSadlCommand(print);\n\t}\n\t\n\tpublic Query processStatement(QueryStatement element) throws JenaProcessorException, InvalidNameException, InvalidTypeException, TranslationException, CircularDefinitionException {\n\t\tExpression qexpr = element.getExpr();\n\t\tif (qexpr != null) {\n\t\t\tif (qexpr instanceof Name) {\n\t\t\t\tOntConceptType qntype = getDeclarationExtensions().getOntConceptType(((Name)qexpr).getName());\n\t\t\t\tif (qntype.equals(OntConceptType.STRUCTURE_NAME)) {\n\t\t\t\t\t// this is just a named query declared elsewhere\n\t\t\t\t\tSadlResource qdecl = getDeclarationExtensions().getDeclaration(((Name)qexpr).getName());\n\t\t\t\t\tEObject qdeclcont = qdecl.eContainer();\n\t\t\t\t\tif (qdeclcont instanceof QueryStatement) {\n\t\t\t\t\t\tqexpr = ((QueryStatement)qdeclcont).getExpr();\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\taddError(\"Unexpected named structure name whose definition is not a query statement\", qexpr);\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tObject qobj = processExpression(qexpr);\n\t\t\tQuery query = null;\n\t\t\tif (qobj instanceof Query) {\n\t\t\t\tquery = (Query) qobj;\n\t\t\t}\n\t\t\telse if (qobj == null) {\n\t\t\t\t// maybe this is a query by name?\n\t\t\t\tif (qexpr instanceof Name) {\n\t\t\t\t\t SadlResource qnm = ((Name)qexpr).getName();\n\t\t\t\t\t String qnmuri = getDeclarationExtensions().getConceptUri(qnm);\n\t\t\t\t\t if (qnmuri != null) {\n\t\t\t\t\t\t Individual qinst = getTheJenaModel().getIndividual(qnmuri);\n\t\t\t\t\t\t if (qinst != null) {\n\t\t\t\t\t\t\t StmtIterator stmtitr = qinst.listProperties();\n\t\t\t\t\t\t\t while (stmtitr.hasNext()) {\n\t\t\t\t\t\t\t\t System.out.println(stmtitr.nextStatement().toString());\n\t\t\t\t\t\t\t }\n\t\t\t\t\t\t }\n\t\t\t\t\t }\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tquery = processQuery(qobj);\n\t\t\t}\n\t\t\tif (query != null) {\n\t\t\t\tif (element.getName() != null) {\n\t\t\t\t\tString uri = declarationExtensions.getConceptUri(element.getName());\n\t\t\t\t\tquery.setFqName(uri);\n\t\t\t\t\tOntClass nqcls = getTheJenaModel().getOntClass(SadlConstants.SADL_IMPLICIT_MODEL_NAMEDQUERY_CLASS_URI);\n\t\t\t\t\tif (nqcls != null) {\n\t\t\t\t\t\tIndividual nqry = getTheJenaModel().createIndividual(uri, nqcls);\n\t\t\t\t\t\t// Add annotations, if any\n\t\t\t\t\t\tEList annotations = element.getAnnotations();\n\t\t\t\t\t\tif (annotations != null && annotations.size() > 0) {\n\t\t\t\t\t\t\taddNamedStructureAnnotations(nqry, annotations);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\t\t\t\t\n\t\t\t\t}\n\t\t\t\tif (element.getStart().equals(\"Graph\")) {\n\t\t\t\t\tquery.setGraph(true);\n\t\t\t\t}\n\t\t\t\tfinal ICompositeNode node = NodeModelUtils.findActualNodeFor(element);\n\t\t\t\tif (node != null) {\n\t\t\t\t\tquery.setOffset(node.getOffset() - 1);\n\t\t\t\t\tquery.setLength(node.getLength());\n\t\t\t\t}\n\t\t\t\tquery = addExpandedPropertiesToQuery(query, qexpr);\n\t\t\t\taddSadlCommand(query);\n\t\t\t\treturn query;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t// this is a reference to a named query defined elsewhere\n\t\t\tSadlResource sr = element.getName();\n\t\t\tSadlResource sr2 = declarationExtensions.getDeclaration(sr);\n\t\t\tif (sr2 != null) {\n\t\t\tEObject cont = sr2.eContainer();\n\t\t\t\tif (cont instanceof QueryStatement && ((QueryStatement)cont).getExpr() != null) {\n\t\t\t\t\treturn processStatement((QueryStatement)cont);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\tprivate Query addExpandedPropertiesToQuery(Query query, Expression expr) {\n\t\tList vars = query.getVariables();\n\t\tList elements = query.getPatterns();\n\t\tif (elements != null) {\n\t\t\tList triplesToAdd = null;\n\t\t\tfor (GraphPatternElement e: elements) {\n\t\t\t\tif (e instanceof TripleElement) {\n\t\t\t\t\tNode subj = ((TripleElement)e).getSubject();\n\t\t\t\t\tNode obj = ((TripleElement)e).getObject();\n\t\t\t\t\tboolean implicitObject = false;\n\t\t\t\t\tif (obj == null) {\n\t\t\t\t\t\tobj = new VariableNode(getIfTranslator().getNewVar());\n\t\t\t\t\t\t((TripleElement) e).setObject(obj);\n\t\t\t\t\t\timplicitObject = true;\n\t\t\t\t\t}\n\t\t\t\t\tif (implicitObject || obj instanceof VariableNode) {\n\t\t\t\t\t\tVariableNode vn = (VariableNode) ((TripleElement)e).getObject();\n\t\t\t\t\t\t//\t\t\t\t\tif (vars != null && vars.contains(vn.getName())) {\n\t\t\t\t\t\tNode pred = ((TripleElement)e).getPredicate();\n\t\t\t\t\t\tConceptName predcn = new ConceptName(pred.toFullyQualifiedString());\n\t\t\t\t\t\tProperty predProp = getTheJenaModel().getProperty(pred.toFullyQualifiedString());\n\t\t\t\t\t\tsetPropertyConceptNameType(predcn, predProp);\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tTypeCheckInfo tci = getModelValidator().getTypeInfoFromRange(predcn, predProp, null);\n\t\t\t\t\t\t\tif (tci != null) {\n\t\t\t\t\t\t\t\tConceptIdentifier tct = tci.getTypeCheckType();\n\t\t\t\t\t\t\t\tif (tct instanceof ConceptName) {\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\tOntClass rngcls = getTheJenaModel().getOntClass(((ConceptName)tct).getUri());\n\t\t\t\t\t\t\t\t\t\tif (rngcls != null) {\n\t\t\t\t\t\t\t\t\t\t\tList expandedProps = getExpandedProperties(rngcls);\n\t\t\t\t\t\t\t\t\t\t\tif (expandedProps != null) {\n\t\t\t\t\t\t\t\t\t\t\t\tfor (int i = 0; i < expandedProps.size(); i++) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tString epstr = expandedProps.get(i);\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (!subjPredMatch(elements, vn, epstr)) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tNamedNode propnode = new NamedNode(epstr, NodeType.ObjectProperty);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tString vnameprefix = (subj instanceof NamedNode) ? ((NamedNode)subj).getName() : \"x\";\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (pred instanceof NamedNode) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tvnameprefix += \"_\" + ((NamedNode)pred).getName();\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tVariableNode newvar = new VariableNode(vnameprefix + \"_\" + propnode.getName()); //getIfTranslator().getNewVar());\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tTripleElement newtriple = new TripleElement(vn, propnode, newvar);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (vars == null) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tvars = new ArrayList();\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tquery.setVariables(vars);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tvars.add(newvar);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (triplesToAdd == null) triplesToAdd = new ArrayList();\n\t\t\t\t\t\t\t\t\t\t\t\t\t\ttriplesToAdd.add(newtriple);\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t} catch (InvalidNameException e1) {\n\t\t\t\t\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\t\t\t\t\te1.printStackTrace();\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (DontTypeCheckException e1) {\n\t\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\t\te1.printStackTrace();\n\t\t\t\t\t\t} catch (InvalidTypeException e1) {\n\t\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\t\te1.printStackTrace();\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//\t\t\t\t\t}\n\t\t\t\t\t\tcatch (TranslationException e2) {\n\t\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\t\te2.printStackTrace();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (triplesToAdd == null && implicitObject) {\n\t\t\t\t\t\tquery.getVariables().add(((VariableNode)obj));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (triplesToAdd != null) {\n\t\t\t\tfor (int i = 0; i < triplesToAdd.size(); i++) {\n\t\t\t\t\tquery.addPattern(triplesToAdd.get(i));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn query;\n\t}\n\t\n\tpublic void setPropertyConceptNameType(ConceptName predcn, Property predProp) {\n\t\tif (predProp instanceof ObjectProperty) {\n\t\t\tpredcn.setType(ConceptType.OBJECTPROPERTY);\n\t\t}\n\t\telse if (predProp instanceof DatatypeProperty) {\n\t\t\tpredcn.setType(ConceptType.DATATYPEPROPERTY);\n\t\t}\n\t\telse if (predProp instanceof AnnotationProperty) {\n\t\t\tpredcn.setType(ConceptType.ANNOTATIONPROPERTY);\n\t\t}\n\t\telse {\n\t\t\tpredcn.setType(ConceptType.RDFPROPERTY);\n\t\t}\n\t}\n\t\n\tprivate boolean subjPredMatch(List elements, VariableNode vn, String epstr) {\n\t\tfor (int i = 0; elements != null && i < elements.size(); i++) {\n\t\t\tGraphPatternElement gp = elements.get(i);\n\t\t\tif (gp instanceof TripleElement) {\n\t\t\t\tTripleElement tr = (TripleElement)gp;\n\t\t\t\tif (tr.getSubject().equals(vn) && tr.getPredicate().toFullyQualifiedString().equals(epstr)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tpublic Query processExpression(SelectExpression expr) throws InvalidNameException, InvalidTypeException, TranslationException {\n\t\treturn processAsk(expr);\n\t}\n\t\n\tpublic Query processExpression(ConstructExpression expr) throws InvalidNameException, InvalidTypeException, TranslationException {\n\t\treturn processAsk(expr);\n\t}\n\t\n\tpublic Query processExpression(AskExpression expr) throws InvalidNameException, InvalidTypeException, TranslationException {\n\t\treturn processAsk(expr);\n\t}\n\t\n\tprivate Query processAsk(Expression expr) {\n\t\tQuery query = new Query();\n\t\tquery.setContext(expr);\n\t\tsetTarget(query);\n//\t\tif (parent != null) {\n//\t\t\tgetIfTranslator().setEncapsulatingTarget(parent);\n//\t\t}\n\t\t\n\t\t// get variables and other information from the SelectExpression\n\t\tEList varList = null;\n\t\tExpression whexpr = null;\n\t\tif (expr instanceof SelectExpression) {\n\t\t\twhexpr = ((SelectExpression) expr).getWhereExpression();\n\t\t\tquery.setKeyword(\"select\");\n\t\t\tif (((SelectExpression)expr).isDistinct()) {\n\t\t\t\tquery.setDistinct(true);\n\t\t\t}\n\t\t\tvarList = ((SelectExpression)expr).getSelectFrom();\n\t\t\tif (varList != null) {\n\t\t\t\tList names = new ArrayList();\n\t\t\t\tfor (int i = 0; i < varList.size(); i++) {\n\t\t\t\t\tObject var = null;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tvar = processExpression(varList.get(i));\n\t\t\t\t\t} catch (TranslationException e2) {\n\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\te2.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t\tTypeCheckInfo tci = null;\n\t\t\t\t\ttry {\n\t\t\t\t\t\ttci = modelValidator.getType(varList.get(i));\n\t\t\t\t\t} catch (DontTypeCheckException e1) {\n\t\t\t\t\t\t// OK to not type check\n\t\t\t\t\t} catch (CircularDefinitionException e1) {\n\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\te1.printStackTrace();\n\t\t\t\t\t} catch (URISyntaxException e1) {\n\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\te1.printStackTrace();\n\t\t\t\t\t} catch (IOException e1) {\n\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\te1.printStackTrace();\n\t\t\t\t\t} catch (ConfigurationException e1) {\n\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\te1.printStackTrace();\n\t\t\t\t\t} catch (CircularDependencyException e) {\n\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t} catch (PropertyWithoutRangeException e) {\n\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t} catch (InvalidNameException e) {\n\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t} catch (TranslationException e) {\n\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t} catch (InvalidTypeException e) {\n\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t\tif (!(var instanceof VariableNode)) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tOntConceptType vtype = getDeclarationExtensions().getOntConceptType(varList.get(i));\n\t\t\t\t\t\t\tif (vtype.equals(OntConceptType.VARIABLE)) {\n\t\t\t\t\t\t\t\tint k = 0;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (CircularDefinitionException e) {\n\t\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t\t}\n//\t\t\t\t\t\tthrow new InvalidNameException(\"'\" + var.toString() + \"' isn't a variable as expected in query select names.\");\n\t\t\t\t\t\tif (var != null) {\n\t\t\t\t\t\t\taddError(SadlErrorMessages.QUERY_ISNT_VARIABLE.get(var.toString()), expr);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tnames.add(((VariableNode)var));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tquery.setVariables(names);\n\t\t\t}\n\t\t\tif (((SelectExpression)expr).getOrderby() != null) {\n\t\t\t\tEList ol = ((SelectExpression)expr).getOrderList();\n\t\t\t\tList orderingPairs = new ArrayList();\n\t\t\t\tfor (int i = 0; i < ol.size(); i++) {\n\t\t\t\t\tOrderElement oele = ol.get(i);\n\t\t\t\t\tSadlResource ord = oele.getOrderBy();\n\t\t\t\t\torderingPairs.add(query.new OrderingPair(getDeclarationExtensions().getConcreteName(ord), \n\t\t\t\t\t\t\t(oele.isDesc() ? Order.DESC : Order.ASC)));\n\t\t\t\t}\n\t\t\t\tquery.setOrderBy(orderingPairs);\n\t\t\t}\n\t\t}\n\t\telse if (expr instanceof ConstructExpression) {\n\t\t\twhexpr = ((ConstructExpression) expr).getWhereExpression();\n\t\t\tquery.setKeyword(\"construct\");\n\t\t\tList names = new ArrayList();\n\t\t\ttry {\n\t\t\t\tObject result = processExpression(((ConstructExpression)expr).getSubj());\n\t\t\t\tif (result instanceof VariableNode) {\n\t\t\t\t\tnames.add(((VariableNode) result));\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tnames.add(createVariable(result.toString()));\n\t\t\t\t}\n\t\t\t\tresult = processExpression(((ConstructExpression)expr).getPred());\n\t\t\t\tif (result instanceof VariableNode) {\n\t\t\t\t\tnames.add((VariableNode) result);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tnames.add(createVariable(result.toString()));\n\t\t\t\t}\n\t\t\t\tresult = processExpression(((ConstructExpression)expr).getObj());\n\t\t\t\tif (result instanceof VariableNode) {\n\t\t\t\t\tnames.add(((VariableNode) result));\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tnames.add(createVariable(result.toString()));\n\t\t\t\t}\n\t\t\t\tif (names.size() != 3) {\n\t\t\t\t\taddWarning(\"A 'construct' statement should have 3 variables so as to be able to generate a graph.\", expr);\n\t\t\t\t}\n\t\t\t\tquery.setVariables(names);\n\t\t\t} catch (InvalidNameException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (InvalidTypeException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (TranslationException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (IOException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (PrefixNotFoundException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (ConfigurationException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\telse if (expr instanceof AskExpression) {\n\t\t\twhexpr = ((AskExpression) expr).getWhereExpression();\n\t\t\tquery.setKeyword(\"ask\");\n\t\t}\n\n\t\t// Translate the query to the resulting intermediate form.\n\t\tif (modelValidator != null) {\n\t\t\ttry {\n\t\t\t\tTypeCheckInfo tct = modelValidator.getType(whexpr);\n\t\t\t\tif (tct != null && tct.getImplicitProperties() != null) {\n\t\t\t\t\tList ips = tct.getImplicitProperties();\n\t\t\t\t\tint i = 0;\n\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} catch (IOException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (ConfigurationException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (DontTypeCheckException e) {\n\t\t\t\t// OK to not be able to type check\n\t\t\t} catch (CircularDefinitionException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (CircularDependencyException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (PropertyWithoutRangeException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (InvalidNameException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (TranslationException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (InvalidTypeException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\tObject pattern = null;\n\t\ttry {\n\t\t\tpattern = processExpression(whexpr);\n\t\t} catch (InvalidNameException e1) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te1.printStackTrace();\n\t\t} catch (InvalidTypeException e1) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te1.printStackTrace();\n\t\t} catch (TranslationException e1) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te1.printStackTrace();\n\t\t}\n\t\t\n\t\tObject expandedPattern = null;\n\t\ttry {\n\t\t\texpandedPattern = getIfTranslator().expandProxyNodes(pattern, false, true);\n\t\t} catch (InvalidNameException e) {\n\t\t\taddError(SadlErrorMessages.INVALID_NAME.get(\"query\", pattern.toString()), expr);\n\t\t\te.printStackTrace();\n\t\t} catch (InvalidTypeException e) {\n\t\t\taddError(SadlErrorMessages.INVALID_TYPE.get(\"query\", pattern.toString()), expr);\n\t\t\te.printStackTrace();\n\t\t} catch (TranslationException e) {\n\t\t\taddError(SadlErrorMessages. TRANSLATION_ERROR.get(\"query\", pattern.toString()), expr);\n\t\t\te.printStackTrace();\n\t\t}\n\t\tif (expandedPattern != null && expandedPattern instanceof List && ((List)expandedPattern).size() > 0) {\n\t\t\tpattern = expandedPattern;\n\t\t}\n\t\t\n\t\tif (pattern instanceof List) {\n\t\t\tif (query.getVariables() == null) {\n\t\t\t\tSet nodes = getIfTranslator().getSelectVariables((List)pattern);\n\t\t\t\tif (nodes != null && nodes.size() > 0) {\n\t\t\t\t\tList names = new ArrayList(1);\n\t\t\t\t\tfor (VariableNode node : nodes) {\n\t\t\t\t\t\tnames.add(node);\n\t\t\t\t\t}\n\t\t\t\t\tquery.setVariables(names);\n\t\t\t\t\tif (query.getKeyword() == null) {\n\t\t\t\t\t\tquery.setKeyword(\"select\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// no variables, assume an ask\n\t\t\t\t\tif (query.getKeyword() == null) {\n\t\t\t\t\t\tquery.setKeyword(\"ask\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tquery.setPatterns((List) pattern);\n\t\t}\n\t\telse if (pattern instanceof Literal) {\n\t\t\t// this must be a SPARQL query\n\t\t\tquery.setSparqlQueryString(((Literal)pattern).getValue().toString());\n\t\t}\n\t\tlogger.debug(\"Ask translation: {}\", query);\n\t\treturn query;\n\t}\n\n\tprivate Query processQuery(Object qobj) throws JenaProcessorException {\n\t\tString qstr = null;\n\t\tQuery q = new Query();\n\t\tsetTarget(q);\n\t\tif (qobj instanceof com.ge.research.sadl.model.gp.Literal) {\n\t\t\tqstr = ((com.ge.research.sadl.model.gp.Literal)qobj).getValue().toString();\n\t\t\tq.setSparqlQueryString(qstr);\n\t\t}\n\t\telse if (qobj instanceof String) {\n\t\t\tqstr = qobj.toString();\n\t\t\tq.setSparqlQueryString(qstr);\n\t\t}\n\t\telse if (qobj instanceof NamedNode) {\n\t\t\tif (isProperty(((NamedNode)qobj).getNodeType())) {\n\t\t\t\tVariableNode sn = new VariableNode(getIfTranslator().getNewVar());\n\t\t\t\tTripleElement tr = new TripleElement(sn, (Node) qobj, null);\n\t\t\t\tq.addPattern(tr);\n\t\t\t\tList vars = q.getVariables();\n\t\t\t\tif (vars == null) {\n\t\t\t\t\tvars = new ArrayList();\n\t\t\t\t\tq.setVariables(vars);\n\t\t\t\t}\n\t\t\t\tq.getVariables().add(sn);\n\t\t\t}\n\t\t}\n\t\telse if (qobj instanceof TripleElement) {\n\t\t\tSet vars = getIfTranslator().getSelectVariables((GraphPatternElement) qobj);\n\t\t\tList errs = getIfTranslator().getErrors();\n\t\t\tif (errs == null || errs.size() == 0) {\n\t\t\t\tif (vars != null && vars.size() > 0) {\n\t\t\t\t\tList varNames = new ArrayList();\n\t\t\t\t\tIterator vitr = vars.iterator();\n\t\t\t\t\twhile (vitr.hasNext()) {\n\t\t\t\t\t\tvarNames.add(vitr.next());\n\t\t\t\t\t}\n\t\t\t\t\tq.setVariables(varNames);\n\t\t\t\t}\n\t\t\t\tq.addPattern((GraphPatternElement) qobj);\n\t\t\t}\n\t\t}\n\t\telse if (qobj instanceof BuiltinElement) {\n\t\t\tString fn = ((BuiltinElement)qobj).getFuncName();\n\t\t\tList args = ((BuiltinElement)qobj).getArguments();\n\t\t\tint i = 0;\n\t\t}\n\t\telse if (qobj instanceof Junction) {\n\t\t\tq.addPattern((Junction)qobj);\n\t\t}\n\t\telse {\n\t\t\tthrow new JenaProcessorException(\"Unexpected query type: \" + qobj.getClass().getCanonicalName());\n\t\t}\n\t\tsetTarget(null);\n\t\treturn q;\n\t}\n\t\n\tpublic void processStatement(EquationStatement element) throws JenaProcessorException, InvalidNameException, InvalidTypeException, TranslationException {\n\t\tSadlResource nm = element.getName();\n\t\tEList params = element.getParameter();\n\t\tSadlTypeReference rtype = element.getReturnType();\n\t\tExpression bdy = element.getBody();\n\t\tEquation eq = createEquation(nm, rtype, params, bdy);\n\t\taddEquation(element.eResource(), eq, nm);\n\t\tIndividual eqinst = getTheJenaModel().createIndividual(getDeclarationExtensions().getConceptUri(nm), \n\t\t\t\tgetTheJenaModel().getOntClass(SadlConstants.SADL_BASE_MODEL_EQUATION_URI));\n\t\tDatatypeProperty dtp = getTheJenaModel().getDatatypeProperty(SadlConstants.SADL_BASE_MODEL_EQ_EXPRESSION_URI);\n\t\tLiteral literal = getTheJenaModel().createTypedLiteral(eq.toString());\n\t\tif (eqinst != null && dtp != null) {\n\t\t\t// these can be null during clean/build with resource open in editor\n\t\t\teqinst.addProperty(dtp, literal);\n\t\t}\n\t}\n\t\n\tprotected Equation createEquation(SadlResource nm, SadlTypeReference rtype, EList params,\n\t\t\tExpression bdy)\n\t\t\tthrows JenaProcessorException, TranslationException, InvalidNameException, InvalidTypeException {\n\t\tEquation eq = new Equation(getDeclarationExtensions().getConcreteName(nm));\n\t\teq.setNamespace(getDeclarationExtensions().getConceptNamespace(nm));\n\t\tNode rtnode = sadlTypeReferenceToNode(rtype);\n\t\teq.setReturnType(rtnode);\n\t\tif (params != null && params.size() > 0) {\n\t\t\tList args = new ArrayList();\n\t\t\tList argtypes = new ArrayList();\n\t\t\tfor (int i = 0; i < params.size(); i++) {\n\t\t\t\tSadlParameterDeclaration param = params.get(i);\n\t\t\t\tSadlResource pr = param.getName();\n\t\t\t\tObject pn = processExpression(pr);\n\t\t\t\targs.add((Node) pn);\n\t\t\t\tSadlTypeReference prtype = param.getType();\n\t\t\t\tNode prtnode = sadlTypeReferenceToNode(prtype); \n\t\t\t\targtypes.add(prtnode);\n\t\t\t}\n\t\t\teq.setArguments(args);\n\t\t\teq.setArgumentTypes(argtypes);\n\t\t}\n\t\t// put equation in context for sub-processing\n\t\tsetCurrentEquation(eq);\n\t\tObject bdyobj = processExpression(bdy);\n\t\tif (bdyobj instanceof List) {\n\t\t\teq.setBody((List) bdyobj);\n\t\t}\n\t\telse if (bdyobj instanceof GraphPatternElement) {\n\t\t\teq.addBodyElement((GraphPatternElement)bdyobj);\n\t\t}\n\t\tif (getModelValidator() != null) {\n\t\t\t// check return type against body expression\n\t\t\tStringBuilder errorMessageBuilder = new StringBuilder();\n\t\t\tif (!getModelValidator().validate(rtype, bdy, \"function return\", errorMessageBuilder)) {\n\t\t\t\taddIssueToAcceptor(errorMessageBuilder.toString(), bdy);\n\t\t\t}\n\t\t}\n\t\tsetCurrentEquation(null);\t// clear\n\t\tlogger.debug(\"Equation: \" + eq.toFullyQualifiedString());\n\t\treturn eq;\n\t}\n\t\n\tpublic void addIssueToAcceptor(String message, EObject expr) {\n\t\tif (isTypeCheckingWarningsOnly()) {\n\t\t\tissueAcceptor.addWarning(message, expr);\n\t\t}\n\t\telse {\n\t\t\tissueAcceptor.addError(message, expr);\n\t\t}\n\t}\n\t\n\tprotected void processStatement(ExternalEquationStatement element) throws JenaProcessorException, InvalidNameException, InvalidTypeException, TranslationException {\n\t\tString uri = element.getUri();\n//\t\tif(uri.equals(SadlConstants.SADL_BUILTIN_FUNCTIONS_URI)){\n//\t\t\treturn;\n//\t\t}\n\t\tSadlResource nm = element.getName();\n\t\tEList params = element.getParameter();\n\t\tSadlTypeReference rtype = element.getReturnType();\n\t\tString location = element.getLocation();\n\t\tEquation eq = createExternalEquation(nm, uri, rtype, params, location);\n\t\taddEquation(element.eResource(), eq, nm);\n\t\tIndividual eqinst = getTheJenaModel().createIndividual(getDeclarationExtensions().getConceptUri(nm), \n\t\t\t\tgetTheJenaModel().getOntClass(SadlConstants.SADL_BASE_MODEL_EXTERNAL_URI));\n\t\tDatatypeProperty dtp = getTheJenaModel().getDatatypeProperty(SadlConstants.SADL_BASE_MODEL_EXTERNALURI_URI);\n\t\tLiteral literal = uri != null ? getTheJenaModel().createTypedLiteral(uri) : null;\n\t\tif (eqinst != null && dtp != null && literal != null) {\n\t\t\t// these can be null if a resource is open in the editor and a clean/build is performed\n\t\t\teqinst.addProperty(dtp,literal);\n\t\t\tif (location != null && location.length() > 0) {\n\t\t\t\tDatatypeProperty dtp2 = getTheJenaModel().getDatatypeProperty(SadlConstants.SADL_BASE_MODEL_EXTERNALURI_LOCATIOIN);\n\t\t\t\tLiteral literal2 = getTheJenaModel().createTypedLiteral(location);\n\t\t\t\teqinst.addProperty(dtp2, literal2);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprotected Equation createExternalEquation(SadlResource nm, String uri, SadlTypeReference rtype,\n\t\t\tEList params, String location)\n\t\t\tthrows JenaProcessorException, TranslationException, InvalidNameException {\n\t\tEquation eq = new Equation(getDeclarationExtensions().getConcreteName(nm));\n\t\teq.setNamespace(getDeclarationExtensions().getConceptNamespace(nm));\n\t\teq.setExternal(true);\n\t\teq.setUri(uri);\n\t\tif (location != null) {\n\t\t\teq.setLocation(location);\n\t\t}\n\t\tif (rtype != null) {\n\t\t\tNode rtnode = sadlTypeReferenceToNode(rtype);\n\t\t\teq.setReturnType(rtnode);\n\t\t}\n\t\tif (params != null && params.size() > 0) {\n\t\t\tif (params.get(0).getUnknown() == null) {\n\t\t\t\tList args = new ArrayList();\n\t\t\t\tList argtypes = new ArrayList();\n\t\t\t\tfor (int i = 0; i < params.size(); i++) {\n\t\t\t\t\tSadlParameterDeclaration param = params.get(i);\n\t\t\t\t\tSadlResource pr = param.getName();\n\t\t\t\t\tif (pr != null) {\n\t\t\t\t\t\tObject pn = processExpression(pr);\n\t\t\t\t\t\targs.add((Node) pn);\n\t\t\t\t\t\tSadlTypeReference prtype = param.getType();\n\t\t\t\t\t\tNode prtnode = sadlTypeReferenceToNode(prtype); \n\t\t\t\t\t\targtypes.add(prtnode);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\teq.setArguments(args);\n\t\t\t\teq.setArgumentTypes(argtypes);\n\t\t\t}\n\t\t}\n\t\t\n\t\tlogger.debug(\"External Equation: \" + eq.toFullyQualifiedString());\n\t\treturn eq;\n\t}\n\t\n\tprivate NamedNode sadlTypeReferenceToNode(SadlTypeReference rtype) throws JenaProcessorException, InvalidNameException, TranslationException {\n\t\tConceptName cn = sadlSimpleTypeReferenceToConceptName(rtype);\n\t\tif (cn == null) {\n\t\t\treturn null;\n\t\t}\n\t\treturn conceptNameToNamedNode(cn);\n//\t\tcom.hp.hpl.jena.rdf.model.Resource rtobj = sadlTypeReferenceToResource(rtype);\n//\t\tif (rtobj == null) {\n////\t\t\tthrow new JenaProcessorException(\"SadlTypeReference was not resolved to a model resource.\");\n//\t\t\treturn null;\n//\t\t}\n//\t\tif (rtobj.isURIResource()) {\n//\t\t\tNamedNode rtnn = new NamedNode(((com.hp.hpl.jena.rdf.model.Resource)rtobj).getLocalName());\n//\t\t\trtnn.setNamespace(((com.hp.hpl.jena.rdf.model.Resource)rtobj).getNameSpace());\n//\t\t\treturn rtnn;\n//\t\t}\n\t}\n\t\n\tpublic NamedNode conceptNameToNamedNode(ConceptName cn) throws TranslationException, InvalidNameException {\n\t\tNamedNode rtnn = new NamedNode(cn.getUri());\n\t\trtnn.setNodeType(conceptTypeToNodeType(cn.getType()));\n\t\treturn rtnn;\n\t}\n\t\n\tprotected void addEquation(Resource resource, Equation eq, EObject nm) {\n\t\tif (getEquations() == null) {\n\t\t\tsetEquations(new ArrayList());\n\t\t\tOntModelProvider.addOtherContent(resource, getEquations());\n\t\t}\n\t\tString newEqName = eq.getName();\n\t\tList eqlist = getEquations();\n\t\tfor (int i = 0; i < eqlist.size(); i++) {\n\t\t\tif (eqlist.get(i).getName().equals(newEqName)) {\n\t\t\t\tif(!namespaceIsImported(eq.getNamespace(), resource)) {\n\t\t\t\t\tgetIssueAcceptor().addError(\"Name '\" + newEqName + \"' is already used. Please provide a unique name.\", nm);\n\t\t\t\t}else {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tgetEquations().add(eq);\n\t}\n\t\n\tprivate boolean namespaceIsImported(String namespace, Resource resource) {\n\t\tString currentNamespace = namespace.replace(\"#\", \"\");\n\t\tif(currentNamespace.equals(SadlConstants.SADL_BUILTIN_FUNCTIONS_URI) || \n\t\t\t\tcurrentNamespace.equals(SadlConstants.SADL_IMPLICIT_MODEL_URI)) {\n\t\t\treturn true;\n\t\t}\n\t\t\n\t\tTreeIterator it = resource.getAllContents();\t\n\t\twhile(it.hasNext()) {\n\t\t\tEObject eObj = it.next();\n\t\t\tif(eObj instanceof SadlImport) {\n\t\t\t\tSadlModel sadlModel = ((SadlImport)eObj).getImportedResource();\n\t\t\t\tif(sadlModel.getBaseUri().equals(currentNamespace)){\n\t\t\t\t\treturn true;\n\t\t\t\t}else if(namespaceIsImported(namespace, sadlModel.eResource())) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\t\n\tprivate boolean namespaceIsImported(String namespace, OntModel currentModel) {\n\t\tOntModel importedModel = currentModel.getImportedModel(namespace.replace(\"#\", \"\"));\n\t\tif(importedModel != null) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tpublic List getEquations(Resource resource) {\n\t\tList other = OntModelProvider.getOtherContent(resource);\n\t\treturn equations;\n\t}\n\t\n\tprivate void processStatement(RuleStatement element) throws InvalidNameException, InvalidTypeException, TranslationException {\n\t\tclearCruleVariables();\n\t\tString ruleName = getDeclarationExtensions().getConcreteName(element.getName());\n\t\tRule rule = new Rule(ruleName);\n\t\tsetTarget(rule);\n\t\tEList ifs = element.getIfs();\n\t\tEList thens = element.getThens();\n\t\tsetRulePart(RulePart.PREMISE);\n\t\tfor (int i = 0; ifs != null && i < ifs.size(); i++) {\n\t\t\tExpression expr = ifs.get(i);\n\t\t\tObject result = processExpression(expr);\n\t\t\tif (result instanceof GraphPatternElement) {\n\t\t\t\trule.addIf((GraphPatternElement) result);\n\t\t\t}\n\t\t\telse {\n\t\t\t\taddError(SadlErrorMessages.IS_NOT_A.get(\"If Expression (\" + result + \")\", \"GraphPatternElement\"), expr);\n\t\t\t}\n\t\t}\n\t\tsetRulePart(RulePart.CONCLUSION);\n\t\tfor (int i = 0; thens != null && i < thens.size(); i++) {\n\t\t\tExpression expr = thens.get(i);\n\t\t\tObject result = processExpression(expr);\n\t\t\tif (result instanceof GraphPatternElement) {\n\t\t\t\trule.addThen((GraphPatternElement) result);\n\t\t\t}\n\t\t\telse {\n\t\t\t\taddError(SadlErrorMessages.IS_NOT_A.get(\"Then Expression (\" + result + \")\", \"GraphPatternElement\"), expr);\n\t\t\t}\n\t\t}\n\t\tgetIfTranslator().setTarget(rule);\n\t\trule = getIfTranslator().postProcessRule(rule, element);\n\t\tif (rules == null) {\n\t\t\trules = new ArrayList();\n\t\t}\n\t\trules.add(rule);\n\t\tString uri = declarationExtensions.getConceptUri(element.getName());\n\t\tOntClass rcls = getTheJenaModel().getOntClass(SadlConstants.SADL_IMPLICIT_MODEL_RULE_CLASS_URI);\n\t\tif (rcls != null) {\n\t\t\tIndividual rl = getTheJenaModel().createIndividual(uri, rcls);\n\t\t\t// Add annotations, if any\n\t\t\tEList annotations = element.getAnnotations();\n\t\t\tif (annotations != null && annotations.size() > 0) {\n\t\t\t\taddNamedStructureAnnotations(rl, annotations);\n\t\t\t}\n\t\t}\n\t\tsetTarget(null);\n\t}\n\t\n\tprotected void addSadlCommand(SadlCommand sadlCommand) {\n\t\tif (getSadlCommands() == null) {\n\t\t\tsetSadlCommands(new ArrayList());\n\t\t}\n\t\tgetSadlCommands().add(sadlCommand);\n\t}\n\t\n\t/**\n\t * Get the SadlCommands generated by the processor. Used for testing purposes.\n\t * @return\n\t */\n\tpublic List getSadlCommands() {\n\t\treturn sadlCommands;\n\t}\n\n\t/* (non-Javadoc)\n\t * @see com.ge.research.sadl.jena.IJenaBasedModelProcessor#getIntermediateFormResults(boolean, boolean)\n\t */\n\t@Override\n\tpublic List getIntermediateFormResults(boolean bRaw, boolean treatAsConclusion) throws InvalidNameException, InvalidTypeException, TranslationException, IOException, PrefixNotFoundException, ConfigurationException {\n\t\tif (bRaw) {\n\t\t\treturn intermediateFormResults;\n\t\t}\n\t\telse if (intermediateFormResults != null){\n\t\t\tList cooked = new ArrayList();\n\t\t\tfor (Object im:intermediateFormResults) {\n\t\t\t\t\tgetIfTranslator().resetIFTranslator();\n\t\t\t\tRule rule = null;\n\t\t\t\tif (treatAsConclusion) {\n\t\t\t\t\trule = new Rule(\"dummy\");\n\t\t\t\t\tgetIfTranslator().setTarget(rule);\n\t\t\t\t}\n\t\t\t\tObject expansion = getIfTranslator().expandProxyNodes(im, treatAsConclusion, true);\n\t\t\t\tif (treatAsConclusion) {\n\t\t\t\t\tif (expansion instanceof List) {\n\t\t\t\t\t\tList ifs = rule.getIfs();\n\t\t\t\t\t\tif (ifs != null) {\n\t\t\t\t\t\t\tifs.addAll((Collection) expansion);\n\t\t\t\t\t\t\texpansion = getIfTranslator().listToAnd(ifs);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcooked.add(expansion);\n\t\t\t}\n\t\t\treturn cooked;\n\t\t}\n\t\treturn null;\n\t}\n\t\n\t/* (non-Javadoc)\n\t * @see com.ge.research.sadl.jena.IJenaBasedModelProcessor#expandNodesInIntermediateForm(java.lang.Object, boolean)\n\t */\n\t@Override\n\tpublic GraphPatternElement expandNodesInIntermediateForm(Object rawIntermediateForm, boolean treatAsConclusion) throws InvalidNameException, InvalidTypeException, TranslationException {\n\t\tgetIfTranslator().resetIFTranslator();\n\t\tRule rule = null;\n\t\tif (treatAsConclusion) {\n\t\t\trule = new Rule(\"dummy\");\n\t\t\tgetIfTranslator().setTarget(rule);\n\t\t}\n\t\tObject expansion = getIfTranslator().expandProxyNodes(rawIntermediateForm, treatAsConclusion, true);\n\t\tif (treatAsConclusion) {\n\t\t\tif (expansion instanceof List) {\n\t\t\t\tList ifs = rule.getIfs();\n\t\t\t\tif (ifs != null) {\n\t\t\t\t\tifs.addAll((Collection) expansion);\n\t\t\t\t\texpansion = getIfTranslator().listToAnd(ifs);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (expansion instanceof GraphPatternElement) {\n\t\t\treturn (GraphPatternElement) expansion;\n\t\t}\n\t\telse throw new TranslationException(\"Expansion failed to return a GraphPatternElement (returned '\" + expansion.toString() + \"')\");\t\n\t}\n\t\n\tprotected void addIntermediateFormResult(Object result) {\n\t\tif (intermediateFormResults == null) {\n\t\t\tintermediateFormResults = new ArrayList();\n\t\t}\n\t\tintermediateFormResults.add(result);\n\t}\n\n\tpublic IntermediateFormTranslator getIfTranslator() {\n\t\tif (intermediateFormTranslator == null) {\n\t\t\tintermediateFormTranslator = new IntermediateFormTranslator(this, getTheJenaModel());\n\t\t}\n\t\treturn intermediateFormTranslator;\n\t}\n\t\n//\t@Override\n//\tpublic Object processExpression(Expression expr) throws InvalidNameException, InvalidTypeException, TranslationException {\n//\t\treturn processExpression(expr);\n//\t}\n//\t\n\tpublic Object processExpression(final Expression expr) throws InvalidNameException, InvalidTypeException, TranslationException {\n\t\tif (expr instanceof BinaryOperation) {\n\t\t\treturn processExpression((BinaryOperation)expr);\n\t\t}\n\t\telse if (expr instanceof BooleanLiteral) {\n\t\t\treturn processExpression((BooleanLiteral)expr);\n\t\t}\n\t\telse if (expr instanceof Constant) {\n\t\t\treturn processExpression((Constant)expr);\n\t\t}\n\t\telse if (expr instanceof Declaration) {\n\t\t\treturn processExpression((Declaration)expr);\n\t\t}\n\t\telse if (expr instanceof Name) {\n\t\t\treturn processExpression((Name)expr);\n\t\t}\n\t\telse if (expr instanceof NumberLiteral) {\n\t\t\treturn processExpression((NumberLiteral)expr);\n\t\t}\n\t\telse if (expr instanceof PropOfSubject) {\n\t\t\treturn processExpression((PropOfSubject)expr);\n\t\t}\n\t\telse if (expr instanceof StringLiteral) {\n\t\t\treturn processExpression((StringLiteral)expr);\n\t\t}\n\t\telse if (expr instanceof SubjHasProp) {\n\t\t\tif (SadlASTUtils.isUnitExpression(expr)) {\n\t\t\t\treturn processSubjHasPropUnitExpression((SubjHasProp)expr);\n\t\t\t}\n\t\t\treturn processExpression((SubjHasProp)expr);\n\t\t}\n\t\telse if (expr instanceof SadlResource) {\n\t\t\treturn processExpression((SadlResource)expr);\n\t\t}\n\t\telse if (expr instanceof UnaryExpression) {\n\t\t\treturn processExpression((UnaryExpression)expr);\n\t\t}\n\t\telse if (expr instanceof Sublist) {\n\t\t\treturn processExpression((Sublist)expr);\n\t\t}\n\t\telse if (expr instanceof ValueTable) {\n\t\t\treturn processExpression((ValueTable)expr);\n\t\t}\n\t\telse if (expr instanceof SelectExpression) {\n\t\t\treturn processExpression((SelectExpression)expr);\n\t\t}\n\t\telse if (expr instanceof AskExpression) {\n//\t\t\taddError(SadlErrorMessages.UNHANDLED.get(\"AskExpression\", \" \"), expr);\n\t\t\treturn processExpression((AskExpression)expr);\n\t\t}\n\t\telse if (expr instanceof ConstructExpression) {\n\t\t\treturn processExpression((ConstructExpression)expr);\n\t\t}\n\t\telse if (expr instanceof UnitExpression) {\n\t\t\treturn processExpression((UnitExpression) expr);\n\t\t}\n\t\telse if (expr instanceof ElementInList) {\n\t\t\treturn processExpression((ElementInList) expr);\n\t\t}\n\t\telse if (expr != null){\n\t\t\tthrow new TranslationException(\"Unhandled rule expression type: \" + expr.getClass().getCanonicalName());\n\t\t}\n\t\treturn expr;\n\t}\n\t\n\tpublic Object processExpression(ValueTable expr) {\n\t\tValueRow row = ((ValueTable)expr).getRow();\n\t\tif (row == null) {\n\t\t\tEList rows = ((ValueTable)expr).getRows();\n\t\t\tif (rows == null || rows.size() == 0) {\n\t\t\t\tValueTable vtbl = ((ValueTable)expr).getValueTable();\n\t\t\t\treturn processExpression(vtbl);\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tpublic Object processExpression(BinaryOperation expr) throws InvalidNameException, InvalidTypeException, TranslationException {\n\t\t// is this a variable definition?\n\t\tboolean isLeftVariableDefinition = false;\n\t\tName leftVariableName = null;\n\t\tExpression leftVariableDefn = null;\n\t\t\n\t\t// math operations can be a variable on each side of operand\n\t\tboolean isRightVariableDefinition = false;\n\t\tName rightVariableName = null;\n\t\tExpression rightVariableDefn = null;\n\t\ttry {\n\t\t\tif (expr.getLeft() instanceof Name && isVariableDefinition((Name) expr.getLeft())) {\n\t\t\t\t// left is variable name, right is variable definition\n\t\t\t\tisLeftVariableDefinition = true;\n\t\t\t\tleftVariableName = (Name) expr.getLeft();\n\t\t\t\tleftVariableDefn = expr.getRight();\n\t\t\t}\n\t\t\tif (expr.getRight() instanceof Name && isVariableDefinition((Name)expr.getRight())) {\n\t\t\t\t// right is variable name, left is variable definition\n\t\t\t\tisRightVariableDefinition = true;\n\t\t\t\trightVariableName = (Name) expr.getRight();\n\t\t\t\trightVariableDefn = expr.getLeft();\n\t\t\t}\n\t\t} catch (CircularDefinitionException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t\t\n\t\tif (isLeftVariableDefinition) {\n\t\t\tObject leftTranslatedDefn = processExpression(leftVariableDefn);\n\t\t\tNamedNode leftDefnType = null;\n\t\t\ttry {\n\t\t\t\tVariableNode leftVar = createVariable(getDeclarationExtensions().getConceptUri(leftVariableName.getName()));\n\t\t\t\tif (leftVar == null) {\t// this can happen on clean/build when file is open in editor\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\tif (leftTranslatedDefn instanceof NamedNode) {\n\t\t\t\t\tleftDefnType = (NamedNode) leftTranslatedDefn;\n\t\t\t\t\tif (leftVar.getType() == null) {\n\t\t\t\t\t\tleftVar.setType((NamedNode) leftDefnType);\n\t\t\t\t\t}\n\t\t\t\t\tif (isRightVariableDefinition) {\n\t\t\t\t\t\tObject rightTranslatedDefn = processExpression(rightVariableDefn);\n\t\t\t\t\t\tNamedNode rightDefnType = null;\n\t\t\t\t\t\tVariableNode rightVar = createVariable(getDeclarationExtensions().getConceptUri(rightVariableName.getName()));\n\t\t\t\t\t\tif (rightVar == null) {\n\t\t\t\t\t\t\treturn null;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (rightTranslatedDefn instanceof NamedNode) {\n\t\t\t\t\t\t\trightDefnType = (NamedNode) rightTranslatedDefn;\n\t\t\t\t\t\t\tif (rightVar.getType() == null) {\n\t\t\t\t\t\t\t\trightVar.setType(rightDefnType);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn createBinaryBuiltin(expr.getOp(), leftVar, rightVar);\n\t\t\t\t\t}\n\t\t\t\t\tTripleElement trel = new TripleElement(leftVar, new RDFTypeNode(), leftDefnType);\n\t\t\t\t\ttrel.setSourceType(TripleSourceType.SPV);\n\t\t\t\t\treturn trel;\n\t\t\t\t}\n\t\t\t\telse if (expr.getRight().equals(leftVariableName) && expr.getLeft() instanceof PropOfSubject && leftTranslatedDefn instanceof TripleElement && ((TripleElement)leftTranslatedDefn).getObject() == null) {\n\t\t\t\t\t// this is just like a SubjHasProp only the order is reversed\n\t\t\t\t\t((TripleElement)leftTranslatedDefn).setObject(leftVar);\n\t\t\t\t\treturn leftTranslatedDefn;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tTypeCheckInfo varType = getModelValidator().getType(leftVariableDefn);\n\t\t\t\t\tif (varType != null) {\n\t\t\t\t\t\tif (leftVar.getType() == null) {\n\t\t\t\t\t\t\tif (varType.getCompoundTypes() != null) {\n\t\t\t\t\t\t\t\tObject jct = compoundTypeCheckTypeToNode(varType, leftVariableDefn);\n\t\t\t\t\t\t\t\tif (jct != null && jct instanceof Junction) {\n\t\t\t\t\t\t\t\t\tleftVar.setType(nodeCheck(jct));\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\taddError(\"Compound type check did not process into expected result for variable type\", leftVariableDefn);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (varType.getTypeCheckType() != null && varType.getTypeCheckType() instanceof ConceptName) {\n\t\t\t\t\t\t\t\tleftDefnType = conceptNameToNamedNode((ConceptName) varType.getTypeCheckType());\n\t\t\t\t\t\t\t\tleftVar.setType((NamedNode) leftDefnType);\n\t\t\t\t\t\t\t\tif (varType.getRangeValueType().equals(RangeValueType.LIST)) {\n\t\t\t\t\t\t\t\t\tConceptName cn = new ConceptName(((NamedNode)leftDefnType).toFullyQualifiedString());\n//\t\t\t\t\t\t\t\t\tcn.setRangeValueType(RangeValueType.LIST);\n\t\t\t\t\t\t\t\t\tcn.setType(nodeTypeToConceptType(((NamedNode)leftDefnType).getNodeType()));\n\t\t\t\t\t\t\t\t\tleftVar.setListType(cn);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (leftTranslatedDefn instanceof GraphPatternElement) {\n\t\t\t\t\t\tif (leftVar.getDefinition() != null) {\n\t\t\t\t\t\t\tleftVar.getDefinition().add((GraphPatternElement) leftTranslatedDefn);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tList defnLst = new ArrayList(1);\n\t\t\t\t\t\t\tdefnLst.add((GraphPatternElement) leftTranslatedDefn);\n\t\t\t\t\t\t\tleftVar.setDefinition(defnLst);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (leftTranslatedDefn instanceof List) {\n\t\t\t\t\t\tleftVar.setDefinition((List) leftTranslatedDefn);\n\t\t\t\t\t}\n\t\t\t\t\tif (leftTranslatedDefn instanceof TripleElement && ((TripleElement)leftTranslatedDefn).getObject() == null) {\n\t\t\t\t\t\t// this is a variable definition and the definition is a triple and the triple has no object\n\t\t\t\t\t\t((TripleElement)leftTranslatedDefn).setObject(leftVar);\n\t\t\t\t\t\treturn leftTranslatedDefn;\n\t\t\t\t\t}\n//\t\t\t\t\telse if (leftTranslatedDefn instanceof BuiltinElement) {\n//\t\t\t\t\t\t((BuiltinElement)leftTranslatedDefn).addArgument(leftVar);\n//\t\t\t\t\t\treturn leftTranslatedDefn;\n//\t\t\t\t\t}\n\t\t\t\t\tNode defn = nodeCheck(leftTranslatedDefn);\n\t\t\t\t\tGraphPatternElement bi = createBinaryBuiltin(expr.getOp(), leftVar, defn);\n\t\t\t\t\treturn bi;\n\t\t\t\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} catch (IOException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (ConfigurationException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (DontTypeCheckException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (CircularDefinitionException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (CircularDependencyException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (PropertyWithoutRangeException e) {\n\t\t\t\taddError(\"Property does not have a range\", leftVariableDefn);\n\t\t\t} catch (PrefixNotFoundException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\telse if (isRightVariableDefinition) {\t\t// only, left is not variable definition\n\t\t\tObject rightTranslatedDefn = processExpression(rightVariableDefn);\n\t\t\tNamedNode rightDefnType = null;\n\t\t\tVariableNode rightVar;\n\t\t\ttry {\n\t\t\t\trightVar = createVariable(getDeclarationExtensions().getConceptUri(rightVariableName.getName()));\n\t\t\t\tif (rightVar == null) {\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\tif (rightTranslatedDefn instanceof NamedNode) {\n\t\t\t\t\trightDefnType = (NamedNode) rightTranslatedDefn;\n\t\t\t\t\tif (rightVar.getType() == null) {\n\t\t\t\t\t\trightVar.setType(rightDefnType);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tTypeCheckInfo varType = getModelValidator().getType(rightVariableDefn);\n\t\t\t\t\tif (varType != null) {\n\t\t\t\t\t\tif (rightVar.getType() == null) {\n\t\t\t\t\t\t\tif (varType.getCompoundTypes() != null) {\n\t\t\t\t\t\t\t\tObject jct = compoundTypeCheckTypeToNode(varType, rightVariableDefn);\n\t\t\t\t\t\t\t\tif (jct != null && jct instanceof Junction) {\n\t\t\t\t\t\t\t\t\trightVar.setType(nodeCheck(jct));\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\taddError(\"Compound type check did not process into expected result for variable type\", leftVariableDefn);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (varType.getTypeCheckType() != null && varType.getTypeCheckType() instanceof ConceptName) {\n\t\t\t\t\t\t\t\trightDefnType = conceptNameToNamedNode((ConceptName) varType.getTypeCheckType());\n\t\t\t\t\t\t\t\trightVar.setType((NamedNode) rightDefnType);\n\t\t\t\t\t\t\t\tif (varType.getRangeValueType().equals(RangeValueType.LIST)) {\n\t\t\t\t\t\t\t\t\tConceptName cn = new ConceptName(((NamedNode)rightDefnType).toFullyQualifiedString());\n\t//\t\t\t\t\t\t\t\tcn.setRangeValueType(RangeValueType.LIST);\n\t\t\t\t\t\t\t\t\tcn.setType(nodeTypeToConceptType(((NamedNode)rightDefnType).getNodeType()));\n\t\t\t\t\t\t\t\t\trightVar.setListType(cn);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (rightTranslatedDefn instanceof GraphPatternElement) {\n\t\t\t\t\t\tif (rightVar.getDefinition() != null) {\n\t\t\t\t\t\t\trightVar.getDefinition().add((GraphPatternElement) rightTranslatedDefn);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tList defnLst = new ArrayList(1);\n\t\t\t\t\t\t\tdefnLst.add((GraphPatternElement) rightTranslatedDefn);\n\t\t\t\t\t\t\trightVar.setDefinition(defnLst);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (rightTranslatedDefn instanceof List) {\n\t\t\t\t\t\trightVar.setDefinition((List) rightTranslatedDefn);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tObject lobj = processExpression(expr.getLeft());\n\t\t\t\tif (lobj instanceof TripleElement && ((TripleElement)lobj).getObject() == null) {\n\t\t\t\t\t((TripleElement)lobj).setObject(rightVar);\n\t\t\t\t\treturn lobj;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\treturn createBinaryBuiltin(expr.getOp(), rightVar, lobj);\n\t\t\t\t}\n\t\t\t} catch (IOException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (PrefixNotFoundException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (ConfigurationException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\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} catch (DontTypeCheckException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (CircularDefinitionException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (CircularDependencyException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (PropertyWithoutRangeException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\t//Validate BinaryOperation expression\n\t\tStringBuilder errorMessage = new StringBuilder();\n\t\tif(!isLeftVariableDefinition && getModelValidator() != null) {\t\t// don't type check a variable definition\n\t\t\tif (!getModelValidator().validate(expr, errorMessage)) {\n\t\t\t\taddIssueToAcceptor(errorMessage.toString(), expr);\n\t\t\t\tif (isSyntheticUri(null, getCurrentResource())) {\n\t\t\t\t\tif (getMetricsProcessor() != null) {\n\t\t\t\t\t\tgetMetricsProcessor().addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.TYPE_CHECK_FAILURE_URI);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tMap ip = getModelValidator().getImpliedPropertiesUsed();\n\t\t\t\tif (ip != null) {\n\t\t\t\t\tIterator ipitr = ip.keySet().iterator();\n\t\t\t\t\twhile (ipitr.hasNext()) {\n\t\t\t\t\t\tEObject eobj = ipitr.next();\n\t\t\t\t\t\tOntModelProvider.addImpliedProperty(expr.eResource(), eobj, ip.get(eobj));\n\t\t\t\t\t}\n\t\t\t\t\t// TODO must add implied properties to rules, tests, etc.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tString op = expr.getOp();\n\t\t\n\t\tExpression lexpr = expr.getLeft();\n\t\tExpression rexpr = expr.getRight();\n\n\t\treturn processBinaryExpressionByParts(expr, op, lexpr, rexpr);\n\t}\n\t\n\tprotected boolean isVariableDefinition(Name expr) throws CircularDefinitionException {\n\t\tif (expr instanceof Name && getDeclarationExtensions().getOntConceptType(((Name)expr).getName()).equals(OntConceptType.VARIABLE)) {\n\t\t\tif (getDeclarationExtensions().getDeclaration(((Name)expr).getName()).equals((Name)expr)) {\n//\t\t\t\taddInfo(\"This is a variable definition of '\" + getDeclarationExtensions().getConceptUri(((Name)expr).getName()) + \"'\", expr);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprivate boolean isVariableDefinition(Declaration decl) {\n\t\tif (!isDefiniteArticle(decl.getArticle()) && (isDeclInThereExists(decl) || (decl.getType() instanceof SadlSimpleTypeReference))) { \n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprivate boolean isDeclInThereExists(Declaration decl) {\n\t\tif (decl.eContainer() != null && decl.eContainer() instanceof UnaryExpression && \n\t\t\t\t((UnaryExpression)decl.eContainer()).getOp().equals(\"there exists\")) {\n\t\t\treturn true;\n\t\t}\n\t\telse if (decl.eContainer() != null && decl.eContainer() instanceof SubjHasProp && \n\t\t\t\tdecl.eContainer().eContainer() != null && decl.eContainer().eContainer() instanceof UnaryExpression && \n\t\t\t\t((UnaryExpression)decl.eContainer().eContainer()).getOp().equals(\"there exists\")) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tprotected Object processBinaryExpressionByParts(EObject container, String op, Expression lexpr,\n\t\t\tExpression rexpr) throws InvalidNameException, InvalidTypeException, TranslationException {\n\t\tStringBuilder errorMessage = new StringBuilder();\n\t\tif (lexpr != null && rexpr != null) {\n\t\t\tif(!getModelValidator().validateBinaryOperationByParts(lexpr.eContainer(), lexpr, rexpr, op, errorMessage)){\n\t\t\t\taddError(errorMessage.toString(), lexpr.eContainer());\n\t\t\t}\n\t\t\telse {\n\t\t\t\tMap ip = getModelValidator().getImpliedPropertiesUsed();\n\t\t\t\tif (ip != null) {\n\t\t\t\t\tIterator ipitr = ip.keySet().iterator();\n\t\t\t\t\twhile (ipitr.hasNext()) {\n\t\t\t\t\t\tEObject eobj = ipitr.next();\n\t\t\t\t\t\tOntModelProvider.addImpliedProperty(lexpr.eResource(), eobj, ip.get(eobj));\n\t\t\t\t\t}\n\t\t\t\t\t// TODO must add implied properties to rules, tests, etc.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tBuiltinType optype = BuiltinType.getType(op);\n\t\tObject lobj;\n\t\tif (lexpr != null) {\n\t\t\tlobj = processExpression(lexpr);\t\t\t\n\t\t}\n\t\telse {\n\t\t\taddError(\"Left side of '\" + op + \"' is null\", lexpr); //TODO Add new error\n\t\t\treturn null;\n\t\t}\n\t\tObject robj = null;\n\t\tif (rexpr != null) {\n\t\t\trobj = processExpression(rexpr);\n\t\t}\n\t\telse {\n\t\t\taddError(\"Right side of '\" + op + \"' is null\", rexpr); //TODO Add new error\n\t\t\treturn null;\n\t\t}\n\t\t\t\t\n\t\tif (optype == BuiltinType.Equal || optype == BuiltinType.NotEqual) {\n\t\t\t// If we're doing an assignment, we can simplify the pattern.\n\t\t\tNode assignedNode = null;\n\t\t\tObject pattern = null;\n\t\t\tif (rexpr instanceof Declaration && !(robj instanceof VariableNode)) {\n\t\t\t\tif (lobj instanceof Node && robj instanceof Node) {\n\t\t\t\t\tTripleElement trel = new TripleElement((Node)lobj, new RDFTypeNode(), (Node)robj);\n\t\t\t\t\ttrel.setSourceType(TripleSourceType.ITC);\n\t\t\t\t\treturn trel;\n\t\t\t\t}\n\t\t\t\telse {\n//\t\t\t\t\tthrow new TranslationException(\"Unhandled binary operation condition: left and right are not both nodes.\");\n\t\t\t\t\taddError(SadlErrorMessages.UNHANDLED.get(\"binary operation condition. \", \"Left and right are not both nodes.\"), container);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (lobj instanceof NamedNode && !(lobj instanceof VariableNode) && hasCommonVariableSubject(robj)) {\n\t\t\t\tTripleElement trel = (TripleElement)robj;\n\t\t\t\twhile (trel != null) {\n\t\t\t\t\ttrel.setSubject((Node) lobj);\n\t\t\t\t\ttrel = (TripleElement) trel.getNext();\n\t\t\t\t}\n\t\t\t\treturn robj;\n\t\t\t}\n\t\t\tif ((lobj instanceof TripleElement || (lobj instanceof com.ge.research.sadl.model.gp.Literal && isSparqlQuery(((com.ge.research.sadl.model.gp.Literal)lobj).toString())))\n\t\t\t\t\t&& !(robj instanceof KnownNode)) {\n\t\t\t\tif (getRulePart().equals(RulePart.CONCLUSION) || getRulePart().equals(RulePart.PREMISE)) {\t\t// added PREMISE--side effects? awc 10/9/17\n\t\t\t\t\tif (robj instanceof com.ge.research.sadl.model.gp.Literal) {\n\t\t\t\t\t\tif (lobj instanceof TripleElement) {\n\t\t\t\t\t\t\tif (((TripleElement)lobj).getObject() == null) {\n\t\t\t\t\t\t\t\t((TripleElement)lobj).setObject((com.ge.research.sadl.model.gp.Literal)robj);\n\t\t\t\t\t\t\t\tlobj = checkForNegation((TripleElement)lobj, rexpr);\n\t\t\t\t\t\t\t\treturn lobj;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\taddError(SadlErrorMessages.UNHANDLED.get(\"rule conclusion construct \", \" \"), container);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\taddError(SadlErrorMessages.UNHANDLED.get(\"rule conclusion construct \", \"\"), container);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (robj instanceof VariableNode) {\n\t\t\t\t\t\tif (((TripleElement)lobj).getObject() == null) {\n\t\t\t\t\t\t\t((TripleElement)lobj).setObject((VariableNode) robj);\n\t\t\t\t\t\t\tlobj = checkForNegation((TripleElement)lobj, rexpr);\n\t\t\t\t\t\t\treturn lobj;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (robj instanceof NamedNode) {\n\t\t\t\t\t\tif (((TripleElement)lobj).getObject() == null) {\n\t\t\t\t\t\t\t((TripleElement)lobj).setObject((NamedNode) robj);\n\t\t\t\t\t\t\tlobj = checkForNegation((TripleElement)lobj, rexpr);\n\t\t\t\t\t\t\treturn lobj;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (robj instanceof BuiltinElement) {\n\t\t\t\t\t\tif (isModifiedTriple(((BuiltinElement)robj).getFuncType())) {\n\t\t\t\t\t\t\tassignedNode = ((BuiltinElement)robj).getArguments().get(0);\n\t\t\t\t\t\t\toptype = ((BuiltinElement)robj).getFuncType();\n\t\t\t\t\t\t\tpattern = lobj;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (isComparisonBuiltin(((BuiltinElement)robj).getFuncName())) {\n\t\t\t\t\t\t\tif ( ((BuiltinElement)robj).getArguments().get(0) instanceof com.ge.research.sadl.model.gp.Literal) {\n\t\t\t\t\t\t\t\t((TripleElement)lobj).setObject(nodeCheck(robj));\n\t\t\t\t\t\t\t\treturn lobj;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\treturn createBinaryBuiltin(((BuiltinElement)robj).getFuncName(), lobj, ((BuiltinElement)robj).getArguments().get(0));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (robj instanceof TripleElement) {\n\t\t\t\t\t\t// do nothing\n\t\t\t\t\t}\n\t\t\t\t\telse if (robj instanceof ConstantNode) {\n\t\t\t\t\t\tString cnst = ((ConstantNode)robj).getName();\n\t\t\t\t\t\tif (cnst.equals(\"None\")) {\n\t\t\t\t\t\t\t((TripleElement)lobj).setType(TripleModifierType.None);\n\t\t\t\t\t\t\treturn lobj;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\taddError(SadlErrorMessages.UNHANDLED.get(\"assignment construct in rule conclusion\", \" \"), container);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (robj instanceof BuiltinElement) {\n\t\t\t\t\tif (isModifiedTriple(((BuiltinElement)robj).getFuncType())) {\n\t\t\t\t\t\tif (((BuiltinElement)robj).getArguments() != null && ((BuiltinElement)robj).getArguments().size() > 0) {\n\t\t\t\t\t\t\tassignedNode = ((BuiltinElement)robj).getArguments().get(0);\n\t\t\t\t\t\t}\n\t\t\t\t\t\toptype = ((BuiltinElement)robj).getFuncType();\n\t\t\t\t\t\tpattern = lobj;\n\t\t\t\t\t}\n\t\t\t\t\telse if (isComparisonBuiltin(((BuiltinElement)robj).getFuncName())) {\n\t\t\t\t\t\tif ( ((BuiltinElement)robj).getArguments().get(0) instanceof Literal) {\n\t\t\t\t\t\t\t((TripleElement)lobj).setObject(nodeCheck(robj));\n\t\t\t\t\t\t\treturn lobj;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\treturn createBinaryBuiltin(((BuiltinElement)robj).getFuncName(), lobj, ((BuiltinElement)robj).getArguments().get(0));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (lobj instanceof Node && robj instanceof TripleElement) {\n\t\t\t\tassignedNode = validateNode((Node) lobj);\n\t\t\t\tpattern = (TripleElement) robj;\n\t\t\t}\n\t\t\telse if (robj instanceof Node && lobj instanceof TripleElement) {\n\t\t\t\tassignedNode = validateNode((Node) robj);\n\t\t\t\tpattern = (TripleElement) lobj;\n\t\t\t}\n\t\t\tif (assignedNode != null && pattern != null) {\n\t\t\t\t// We're expressing the type of a named thing.\n\t\t\t\tif (pattern instanceof TripleElement && ((TripleElement)pattern).getSubject() == null) {\n\t\t\t\t\tif (isModifiedTripleViaBuitin(robj)) {\n\t\t\t\t\t\toptype = ((BuiltinElement)((TripleElement)pattern).getNext()).getFuncType();\t\n\t\t\t\t\t\t((TripleElement)pattern).setNext(null);\n\t\t\t\t\t}\n\t\t\t\t\t((TripleElement)pattern).setSubject(assignedNode);\n\t\t\t\t\tif (optype != BuiltinType.Equal) {\n\t\t\t\t\t\t((TripleElement)pattern).setType(getTripleModifierType(optype));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (pattern instanceof TripleElement && ((TripleElement)pattern).getObject() == null && \n\t\t\t\t\t\t(((TripleElement)pattern).getSourceType().equals(TripleSourceType.PSnewV) \n\t\t\t\t\t\t\t\t|| ((TripleElement)pattern).getSourceType().equals(TripleSourceType.PSV))) {\n\t\t\t\t\tif (isModifiedTripleViaBuitin(robj)) {\n\t\t\t\t\t\toptype = ((BuiltinElement)((TripleElement)pattern).getNext()).getFuncType();\t\n\t\t\t\t\t\t((TripleElement)pattern).setNext(null);\n\t\t\t\t\t}\n\t\t\t\t\t((TripleElement)pattern).setObject(assignedNode);\n\t\t\t\t\tif (optype != BuiltinType.Equal) {\n\t\t\t\t\t\t((TripleElement)pattern).setType(getTripleModifierType(optype));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (pattern instanceof TripleElement && ((TripleElement)pattern).getSourceType().equals(TripleSourceType.SPV)\n\t\t\t\t\t\t&& assignedNode instanceof NamedNode && getProxyWithNullSubject(((TripleElement)pattern)) != null) {\n\t\t\t\t\tTripleElement proxyFor = getProxyWithNullSubject(((TripleElement)pattern));\n\t\t\t\t\tassignNullSubjectInProxies(((TripleElement)pattern), proxyFor, assignedNode);\n\t\t\t\t\tif (optype != BuiltinType.Equal) {\n\t\t\t\t\t\tproxyFor.setType(getTripleModifierType(optype));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (isModifiedTriple(optype) || \n\t\t\t\t\t\t(optype.equals(BuiltinType.Equal) && pattern instanceof TripleElement && \n\t\t\t\t\t\t\t\t(((TripleElement)pattern).getObject() == null || \n\t\t\t\t\t\t\t\t\t\t((TripleElement)pattern).getObject() instanceof NamedNode ||\n\t\t\t\t\t\t\t\t\t\t((TripleElement)pattern).getObject() instanceof com.ge.research.sadl.model.gp.Literal))){\n\t\t\t\t\tif (pattern instanceof TripleElement && isModifiedTripleViaBuitin(robj)) {\n\t\t\t\t\t\toptype = ((BuiltinElement)((TripleElement)pattern).getNext()).getFuncType();\n\t\t\t\t\t\t((TripleElement)pattern).setObject(assignedNode);\n\t\t\t\t\t\t((TripleElement)pattern).setNext(null);\n\t\t\t\t\t\t((TripleElement)pattern).setType(getTripleModifierType(optype));\n\t\t\t\t\t}\n\t\t\t\t\telse if (isComparisonViaBuiltin(robj, lobj)) {\n\t\t\t\t\t\tBuiltinElement be = (BuiltinElement)((TripleElement)robj).getNext();\n\t\t\t\t\t\tbe.addMissingArgument((Node) lobj);\n\t\t\t\t\t\treturn pattern;\n\t\t\t\t\t}\n\t\t\t\t\telse if (pattern instanceof TripleElement){\n\t\t\t\t\t\tTripleElement lastPattern = (TripleElement)pattern;\n\t\t\t\t\t\t// this while may need additional conditions to narrow application to nested triples?\n\t\t\t\t\t\twhile (lastPattern.getNext() != null && lastPattern instanceof TripleElement) {\n\t\t\t\t\t\t\tlastPattern = (TripleElement) lastPattern.getNext();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (getEncapsulatingTarget() instanceof Test) {\n\t\t\t\t\t\t\t((Test)getEncapsulatingTarget()).setRhs(assignedNode);\n\t\t\t\t\t\t\t((Test)getEncapsulatingTarget()).setCompName(optype);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (getEncapsulatingTarget() instanceof Query && getTarget() instanceof Test) {\n\t\t\t\t\t\t\t((Test)getTarget()).setRhs(getEncapsulatingTarget());\n\t\t\t\t\t\t\t((Test)getTarget()).setLhs(assignedNode);\n\t\t\t\t\t\t\t((Test)getTarget()).setCompName(optype);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (getTarget() instanceof Test && assignedNode != null) {\n\t\t\t\t\t\t\t((Test)getTarget()).setLhs(pattern);\n\t\t\t\t\t\t\t((Test)getTarget()).setRhs(assignedNode);\n\t\t\t\t\t\t\t((Test)getTarget()).setCompName(optype);\n\t\t\t\t\t\t\t((TripleElement) pattern).setType(TripleModifierType.None);\n\t\t\t\t\t\t\toptype = BuiltinType.Equal;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tlastPattern.setObject(assignedNode);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!optype.equals(BuiltinType.Equal)) {\n\t\t\t\t\t\t\t((TripleElement)pattern).setType(getTripleModifierType(optype));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tif (getTarget() instanceof Test) {\n\t\t\t\t\t\t\t((Test)getTarget()).setLhs(lobj);\n\t\t\t\t\t\t\t((Test)getTarget()).setRhs(assignedNode);\n\t\t\t\t\t\t\t((Test)getTarget()).setCompName(optype);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (getEncapsulatingTarget() instanceof Test) {\n\t\t\t\t\t((Test)getEncapsulatingTarget()).setRhs(assignedNode);\n\t\t\t\t\t((Test)getEncapsulatingTarget()).setCompName(optype);\n\t\t\t\t}\n\t\t\t\telse if (getTarget() instanceof Rule && pattern instanceof TripleElement && ((TripleElement)pattern).getSourceType().equals(TripleSourceType.ITC) && \n\t\t\t\t\t\t((TripleElement)pattern).getSubject() instanceof VariableNode && assignedNode instanceof VariableNode) {\n\t\t\t\t\t// in a rule of this type we just want to replace the pivot node variable\n\t\t\t\t\tdoVariableSubstitution(((TripleElement)pattern), (VariableNode)((TripleElement)pattern).getSubject(), (VariableNode)assignedNode);\n\t\t\t\t}\n\t\t\t\treturn pattern;\n\t\t\t}\n\t\t\tBuiltinElement bin = null;\n\t\t\tboolean binOnRight = false;\n\t\t\tObject retObj = null;\n\t\t\tif (lobj instanceof Node && robj instanceof BuiltinElement) {\n\t\t\t\tassignedNode = validateNode((Node)lobj);\n\t\t\t\tbin = (BuiltinElement)robj;\n\t\t\t\tretObj = robj;\n\t\t\t\tbinOnRight = true;\n\t\t\t}\n\t\t\telse if (robj instanceof Node && lobj instanceof BuiltinElement) {\n\t\t\t\tassignedNode = validateNode((Node)robj);\n\t\t\t\tbin = (BuiltinElement)lobj;\n\t\t\t\tretObj = lobj;\n\t\t\t\tbinOnRight = false;\n\t\t\t}\n\t\t\tif (bin != null && assignedNode != null) {\n\t\t\t\tif ((assignedNode instanceof VariableNode ||\n\t\t\t\t\t(assignedNode instanceof NamedNode && ((NamedNode)assignedNode).getNodeType().equals(NodeType.VariableNode)))) {\n\t\t\t\t\tif (getTarget() instanceof Rule && containsDeclaration(robj)) {\n\t\t\t\t\t\treturn replaceDeclarationWithVariableAndAddUseDeclarationAsDefinition(lexpr, lobj, rexpr, robj);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\twhile (bin.getNext() instanceof BuiltinElement) {\n\t\t\t\t\t\t\tbin = (BuiltinElement) bin.getNext();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (bin.isCreatedFromInterval()) {\n\t\t\t\t\t\t\tbin.addArgument(0, assignedNode);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tbin.addArgument(assignedNode);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn retObj;\n\t\t\t\t}\n\t\t\t\telse if (assignedNode instanceof Node && isComparisonBuiltin(bin.getFuncName())) {\n\t\t\t\t\t// this is a comparison with an extra \"is\"\n\t\t\t\t\tif (bin.getArguments().size() == 1) {\n\t\t\t\t\t\tif (bin.isCreatedFromInterval() || binOnRight) {\n\t\t\t\t\t\t\tbin.addArgument(0, assignedNode);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tbin.addArgument(assignedNode);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn bin;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// We're describing a thing with a graph pattern.\n\t\t\tSet vars = pattern instanceof TripleElement ? getSelectVariables(((TripleElement)pattern)) : null; \n\t\t\tif (vars != null && vars.size() == 1) {\n\t\t\t\t// Find where the unbound variable occurred in the pattern\n\t\t\t\t// and replace each place with the assigned node.\n\t\t\t\tVariableNode var = vars.iterator().next();\n\t\t\t\tGraphPatternElement gpe = ((TripleElement)pattern);\n\t\t\t\twhile (gpe instanceof TripleElement) {\n\t\t\t\t\tTripleElement triple = (TripleElement) gpe;\n\t\t\t\t\tif (var.equals(triple.getSubject())) {\n\t\t\t\t\t\ttriple.setSubject(assignedNode);\n\t\t\t\t\t}\n\t\t\t\t\tif (var.equals(triple.getObject())) {\n\t\t\t\t\t\ttriple.setObject(assignedNode);\n\t\t\t\t\t}\n\t\t\t\t\tgpe = gpe.getNext();\n\t\t\t\t}\n\t\t\t\treturn pattern;\n\t\t\t}\n\t\t}\n\t\t// if we get to here we want to actually create a BuiltinElement for the BinaryOpExpression\n\t\t// However, if the type is equal (\"is\", \"equal\") and the left side is a VariableNode and the right side is a literal\n\t\t//\tand the VariableNode hasn't already been bound, change from type equal to type assign.\n\t\tif (optype == BuiltinType.Equal && getTarget() instanceof Rule && lobj instanceof VariableNode && robj instanceof com.ge.research.sadl.model.gp.Literal && \n\t\t\t\t!variableIsBound((Rule)getTarget(), null, (VariableNode)lobj)) {\n\t\t\treturn createBinaryBuiltin(\"assign\", robj, lobj);\n\t\t}\n\t\tif (op.equals(\"and\") || op.equals(\"or\")) {\n\t\t\tJunction jct = new Junction();\n\t\t\tjct.setJunctionName(op);\n\t\t\tjct.setLhs(lobj);\n\t\t\tjct.setRhs(robj);\n\t\t\treturn jct;\n\t\t}\n\t\telse {\n\t\t\treturn createBinaryBuiltin(op, lobj, robj);\n\t\t}\n\t}\n\t\n\tprivate TripleElement checkForNegation(TripleElement lobj, Expression rexpr) throws InvalidTypeException {\n\t\tif (isOperationPulingUp(rexpr) && isNegation(rexpr)) {\n\t\t\tlobj.setType(TripleModifierType.Not);\n\t\t\tgetOperationPullingUp();\n\t\t}\n\t\treturn lobj;\n\t}\n\n\tprivate boolean isNegation(Expression expr) {\n\t\tif (expr instanceof UnaryExpression && ((UnaryExpression)expr).getOp().equals(\"not\")) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprivate Object replaceDeclarationWithVariableAndAddUseDeclarationAsDefinition(Expression lexpr, Object lobj, Expression rexpr, Object robj) throws TranslationException, InvalidTypeException {\n\t\tif (lobj instanceof VariableNode) {\n\t\t\tObject[] declAndTrans = getDeclarationAndTranslation(rexpr);\n\t\t\tif (declAndTrans != null) {\n\t\t\t\tObject rtrans = declAndTrans[1];\n\t\t\t\tif (rtrans instanceof NamedNode) {\n\t\t\t\t\tif (((NamedNode)rtrans).getNodeType().equals(NodeType.ClassNode)) {\n\t\t\t\t\t\tif (replaceDeclarationInRightWithVariableInLeft((Node)lobj, robj, rtrans)) {\n\t\t\t\t\t\t\tTripleElement newTriple = new TripleElement((Node)lobj, new NamedNode(RDF.type.getURI(), NodeType.ObjectProperty), (Node)rtrans);\n\t\t\t\t\t\t\tJunction jct = createJunction(rexpr, \"and\", newTriple, robj);\n\t\t\t\t\t\t\treturn jct;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprivate boolean replaceDeclarationInRightWithVariableInLeft(Node lobj, Object robj, Object rtrans) {\n\t\tif (robj instanceof BuiltinElement) {\n\t\t\tIterator argitr = ((BuiltinElement)robj).getArguments().iterator();\n\t\t\twhile (argitr.hasNext()) {\n\t\t\t\tNode arg = argitr.next();\n\t\t\t\tif (replaceDeclarationInRightWithVariableInLeft(lobj, arg, rtrans)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if (robj instanceof ProxyNode) {\n\t\t\tif (replaceDeclarationInRightWithVariableInLeft(lobj, ((ProxyNode)robj).getProxyFor(), rtrans)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\telse if (robj instanceof TripleElement) {\n\t\t\tNode subj = ((TripleElement)robj).getSubject();\n\t\t\tif (subj.equals(rtrans)) {\n\t\t\t\t((TripleElement)robj).setSubject(lobj);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\telse if (replaceDeclarationInRightWithVariableInLeft(lobj, subj, rtrans)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprivate Object[] getDeclarationAndTranslation(Expression expr) throws TranslationException {\n\t\tDeclaration decl = getDeclaration(expr);\n\t\tif (decl != null) {\n\t\t\tObject declprocessed = processExpression(decl);\n\t\t\tif (declprocessed != null) {\n\t\t\t\tObject[] result = new Object[2];\n\t\t\t\tresult[0] = decl;\n\t\t\t\tresult[1] = declprocessed;\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprivate Declaration getDeclaration(Expression rexpr) throws TranslationException {\n\t\tif (rexpr instanceof SubjHasProp) {\n\t\t\treturn getDeclarationFromSubjHasProp((SubjHasProp) rexpr);\n\t\t}\n\t\telse if (rexpr instanceof BinaryOperation) {\n\t\t\tDeclaration decl = getDeclaration(((BinaryOperation)rexpr).getLeft());\n\t\t\tif (decl != null) {\n\t\t\t\treturn decl;\n\t\t\t}\n\t\t\tdecl = getDeclaration(((BinaryOperation)rexpr).getRight());\n\t\t\tif (decl != null) {\n\t\t\t\treturn decl;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprivate boolean containsDeclaration(Object obj) {\n\t\tif (obj instanceof BuiltinElement) {\n\t\t\tIterator argitr = ((BuiltinElement)obj).getArguments().iterator();\n\t\t\twhile (argitr.hasNext()) {\n\t\t\t\tNode n = argitr.next();\n\t\t\t\tif (n instanceof ProxyNode) {\n\t\t\t\t\tif (containsDeclaration(((ProxyNode)n).getProxyFor())) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if (obj instanceof TripleElement) {\n\t\t\tNode s = ((TripleElement)obj).getSubject();\n\t\t\tif (s instanceof NamedNode && ((NamedNode)s).getNodeType().equals(NodeType.ClassNode)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (containsDeclaration(((TripleElement)obj).getSubject())) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\telse if (obj instanceof ProxyNode) {\n\t\t\tif (containsDeclaration(((ProxyNode)obj).getProxyFor())) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprivate Object processFunction(Name expr) throws InvalidNameException, InvalidTypeException, TranslationException {\n\t\tEList arglist = expr.getArglist();\n\t\tNode fnnode = processExpression(expr.getName());\n\t\tString funcname = null;\n\t\tif (fnnode instanceof VariableNode) {\n\t\t\tfuncname = ((VariableNode) fnnode).getName();\n\t\t}\n\t\telse if (fnnode == null) {\n\t\t\taddError(\"Function not found\", expr);\n\t\t\treturn null;\n\t\t}\n\t\telse {\n\t\t\tfuncname = fnnode.toString();\n\t\t}\n\t\tBuiltinElement builtin = new BuiltinElement();\n\t\tbuiltin.setFuncName(funcname);\n\t\tif (fnnode instanceof NamedNode && ((NamedNode)fnnode).getNamespace()!= null) {\n\t\t\tbuiltin.setFuncUri(fnnode.toFullyQualifiedString());\n\t\t}\n\t\tif (arglist != null && arglist.size() > 0) {\n\t\t\tList args = new ArrayList();\n\t\t\tfor (int i = 0; i < arglist.size(); i++) {\n\t\t\t\targs.add(processExpression(arglist.get(i)));\n\t\t\t}\n\t\t\tif (args != null) {\n\t\t\t\tfor (Object arg : args) {\n\t\t\t\t\tbuiltin.addArgument(nodeCheck(arg));\n\t\t\t\t\tif (arg instanceof GraphPatternElement) {\n\t\t\t\t\t\t((GraphPatternElement)arg).setEmbedded(true);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn builtin;\n\t}\n\t\n\tprivate boolean hasCommonVariableSubject(Object robj) {\n\t\tif (robj instanceof TripleElement && \n\t\t\t\t(((TripleElement)robj).getSubject() instanceof VariableNode && \n\t\t\t\t\t\t(((TripleElement)robj).getSourceType().equals(TripleSourceType.SPV)) ||\n\t\t\t\t\t\t((TripleElement)robj).getSourceType().equals(TripleSourceType.ITC))) {\n\t\t\tVariableNode subjvar = (VariableNode) ((TripleElement)robj).getSubject();\n\t\t\tObject trel = robj;\n\t\t\twhile (trel != null && trel instanceof TripleElement) {\n\t\t\t\tif (!(trel instanceof TripleElement) || \n\t\t\t\t\t\t(((TripleElement)trel).getSubject() != null &&!(((TripleElement)trel).getSubject().equals(subjvar)))) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\ttrel = ((TripleElement)trel).getNext();\n\t\t\t}\n\t\t\tif (trel == null) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns the bottom triple whose subject was replaced.\n\t * @param pattern\n\t * @param proxyFor\n\t * @param assignedNode\n\t * @return\n\t */\n\tprivate TripleElement assignNullSubjectInProxies(TripleElement pattern,\n\t\t\tTripleElement proxyFor, Node assignedNode) {\n\t\tif (pattern.getSubject() instanceof ProxyNode) {\n\t\t\tObject proxy = ((ProxyNode)pattern.getSubject()).getProxyFor();\n\t\t\tif (proxy instanceof TripleElement) {\n//\t\t\t\t((ProxyNode)pattern.getSubject()).setReplacementNode(assignedNode);\n\t\t\t\tif (((TripleElement)proxy).getSubject() == null) {\n\t\t\t\t\t// this is the bottom of the recursion\n\t\t\t\t\t((TripleElement)proxy).setSubject(assignedNode);\n\t\t\t\t\treturn (TripleElement) proxy;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// recurse down\n\t\t\t\t\tTripleElement bottom = assignNullSubjectInProxies(((TripleElement)proxy), proxyFor, assignedNode);\n\t\t\t\t\t// make the proxy next and reassign this subject as assignedNode\n\t\t\t\t\t((ProxyNode)((TripleElement)proxy).getSubject()).setReplacementNode(assignedNode);\n\t\t\t\t\t((TripleElement)proxy).setSubject(assignedNode);\n\t\t\t\t\tif (bottom.getNext() == null) {\n\t\t\t\t\t\tbottom.setNext(pattern);\n\t\t\t\t\t}\n\t\t\t\t\treturn bottom;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tprivate TripleElement getProxyWithNullSubject(TripleElement pattern) {\n\t\tif (pattern.getSubject() instanceof ProxyNode) {\n\t\t\tObject proxy = ((ProxyNode)pattern.getSubject()).getProxyFor();\n\t\t\tif (proxy instanceof TripleElement) {\n\t\t\t\tif (((TripleElement)proxy).getSubject() == null) {\n\t\t\t\t\treturn (TripleElement)proxy;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\treturn getProxyWithNullSubject(((TripleElement)proxy));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tprivate boolean isComparisonViaBuiltin(Object robj, Object lobj) {\n\t\tif (robj instanceof TripleElement && lobj instanceof Node &&\n\t\t\t\t((TripleElement)robj).getNext() instanceof BuiltinElement) {\n\t\t\tBuiltinElement be = (BuiltinElement) ((TripleElement)robj).getNext();\n\t\t\tif (isComparisonBuiltin(be.getFuncName()) && be.getArguments().size() == 1) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate boolean isModifiedTripleViaBuitin(Object robj) {\n\t\tif (robj instanceof TripleElement && ((TripleElement)robj).getNext() instanceof BuiltinElement) {\n\t\t\tBuiltinElement be = (BuiltinElement) ((TripleElement)robj).getNext();\n\t\t\tif (((TripleElement)robj).getPredicate() instanceof RDFTypeNode) {\n\t\t\t\tif (isModifiedTriple(be.getFuncType())) {\n\t\t\t\t\tNode subj = ((TripleElement)robj).getSubject();\n\t\t\t\t\tNode arg = (be.getArguments() != null && be.getArguments().size() > 0) ? be.getArguments().get(0) : null;\n\t\t\t\t\tif (subj == null && arg == null) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\tif (subj != null && arg != null && subj.equals(arg)) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (isModifiedTriple(be.getFuncType()) && ((TripleElement)robj).getObject().equals(be.getArguments().get(0))) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate boolean doVariableSubstitution(GraphPatternElement gpe, VariableNode v1, VariableNode v2) {\n\t\tboolean retval = false;\n\t\tdo {\n\t\t\tif (gpe instanceof TripleElement) {\n\t\t\t\tif (((TripleElement)gpe).getSubject().equals(v1)) {\n\t\t\t\t\t((TripleElement)gpe).setSubject(v2);\n\t\t\t\t\tretval = true;\n\t\t\t\t}\n\t\t\t\telse if (((TripleElement)gpe).getObject().equals(v1)) {\n\t\t\t\t\t((TripleElement)gpe).setObject(v2);\n\t\t\t\t\tretval = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (gpe instanceof BuiltinElement) {\n\t\t\t\tList args = ((BuiltinElement)gpe).getArguments();\n\t\t\t\tfor (int j = 0; j < args.size(); j++) {\n\t\t\t\t\tif (args.get(j).equals(v1)) {\n\t\t\t\t\t\targs.set(j, v2);\n\t\t\t\t\t\tretval = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (gpe instanceof Junction) {\n\t\t\t\tlogger.error(\"Not yet handled\");\n\t\t\t}\n\t\t\tgpe = gpe.getNext();\n\t\t} while (gpe != null);\n\t\treturn retval;\n\t}\n\n\t/**\n\t * This method returns true if the argument node is bound in some other element of the rule\n\t * \n\t * @param rule\n\t * @param gpe\n\t * @param v\n\t * @return\n\t */\n\tpublic static boolean variableIsBound(Rule rule, GraphPatternElement gpe,\n\t\t\tNode v) {\n\t\tif (v instanceof NamedNode) {\n\t\t\tif (((NamedNode)v).getNodeType() != null && !(((NamedNode)v).getNodeType().equals(NodeType.VariableNode))) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\t// Variable is bound if it appears in a triple or as the return argument of a built-in\n\t\tList givens = rule.getGivens();\n\t\tif (variableIsBoundInOtherElement(givens, 0, gpe, true, false, v)) {\n\t\t\treturn true;\n\t\t}\n\t\tList ifs = rule.getIfs();\n\t\tif (variableIsBoundInOtherElement(ifs, 0, gpe, true, false, v)) {\n\t\t\treturn true;\n\t\t}\n\t\tList thens = rule.getThens();\n\t\tif (variableIsBoundInOtherElement(thens, 0, gpe, false, true, v)) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate GraphPatternElement createBinaryBuiltin(String name, Object lobj, Object robj) throws InvalidNameException, InvalidTypeException, TranslationException {\n\t\tif (name.equals(JunctionType.AND_ALPHA) || name.equals(JunctionType.AND_SYMBOL) || name.equals(JunctionType.OR_ALPHA) || name.equals(JunctionType.OR_SYMBOL)) {\n\t\t\tJunction jct = new Junction();\n\t\t\tjct.setJunctionName(name);\n\t\t\tjct.setLhs(lobj);\n\t\t\tjct.setRhs(robj);\n\t\t\treturn jct;\n\t\t}\n\t\telse {\n\t\t\tBuiltinElement builtin = new BuiltinElement();\n\t\t\tbuiltin.setFuncName(name);\n\t\t\tif (lobj != null) {\n\t\t\t\tbuiltin.addArgument(nodeCheck(lobj));\n\t\t\t}\n\t\t\tif (robj != null) {\n\t\t\t\tbuiltin.addArgument(nodeCheck(robj));\n\t\t\t}\n\t\t\treturn builtin;\n\t\t}\n\t}\n\t\n\tprotected Junction createJunction(Expression expr, String name, Object lobj, Object robj) {\n\t\tJunction junction = new Junction();\n\t\tjunction.setJunctionName(name);\n\t\tjunction.setLhs(lobj);\n\t\tjunction.setRhs(robj);\n\t\treturn junction;\n\t}\n\n\tprivate Object createUnaryBuiltin(String name, Object sobj) throws InvalidNameException, InvalidTypeException, TranslationException {\n\t\tif (sobj instanceof com.ge.research.sadl.model.gp.Literal && BuiltinType.getType(name).equals(BuiltinType.Minus)) {\n\t\t\tObject theVal = ((com.ge.research.sadl.model.gp.Literal)sobj).getValue();\n\t\t\tif (theVal instanceof Integer) {\n\t\t\t\ttheVal = ((Integer)theVal) * -1;\n\t\t\t}\n\t\t\telse if (theVal instanceof Long) {\n\t\t\t\ttheVal = ((Long)theVal) * -1;\n\t\t\t}\n\t\t\telse if (theVal instanceof Float) {\n\t\t\t\ttheVal = ((Float)theVal) * -1;\n\t\t\t}\n\t\t\telse if (theVal instanceof Double) {\n\t\t\t\ttheVal = ((Double)theVal) * -1;\n\t\t\t}\n\t\t\t((com.ge.research.sadl.model.gp.Literal)sobj).setValue(theVal);\n\t\t\t((com.ge.research.sadl.model.gp.Literal)sobj).setOriginalText(\"-\" + ((com.ge.research.sadl.model.gp.Literal)sobj).getOriginalText());\n\t\t\treturn sobj;\n\t\t}\n\t\tif (sobj instanceof Junction) {\n\t\t\t// If the junction has two literal values, apply the op to both of them.\n\t\t\tJunction junc = (Junction) sobj;\n\t\t\tObject lhs = junc.getLhs();\n\t\t\tObject rhs = junc.getRhs();\n\t\t\tif (lhs instanceof com.ge.research.sadl.model.gp.Literal && rhs instanceof com.ge.research.sadl.model.gp.Literal) {\n\t\t\t\tlhs = createUnaryBuiltin(name, lhs);\n\t\t\t\trhs = createUnaryBuiltin(name, rhs);\n\t\t\t\tjunc.setLhs(lhs);\n\t\t\t\tjunc.setRhs(rhs);\n\t\t\t}\n\t\t\treturn junc;\n\t\t}\n\t\tif (BuiltinType.getType(name).equals(BuiltinType.Equal)) {\n\t\t\tif (sobj instanceof BuiltinElement) {\n\t\t\t\tif (isComparisonBuiltin(((BuiltinElement)sobj).getFuncName())) {\n\t\t\t\t\t// this is a \"is \"--translates to (ignore is)\n\t\t\t\t\treturn sobj;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (sobj instanceof com.ge.research.sadl.model.gp.Literal || sobj instanceof NamedNode) {\n\t\t\t\t// an \"=\" interval value of a value is just the value\n\t\t\t\treturn sobj;\n\t\t\t}\n\t\t}\n\t\tBuiltinElement builtin = new BuiltinElement();\n\t\tbuiltin.setFuncName(name);\n\t\tif (isModifiedTriple(builtin.getFuncType())) {\n\t\t\tif (sobj instanceof TripleElement) {\n\t\t\t\t((TripleElement)sobj).setType(getTripleModifierType(builtin.getFuncType()));\n\t\t\t\treturn sobj;\n\t\t\t}\n\t\t}\n\t\tif (sobj != null) {\n\t\t\tbuiltin.addArgument(nodeCheck(sobj));\n\t\t}\n\t\treturn builtin;\n\t}\n\n\tprivate TripleModifierType getTripleModifierType(BuiltinType btype) {\n\t\tif (btype.equals(BuiltinType.Not) || btype.equals(BuiltinType.NotEqual)) {\n\t\t\treturn TripleModifierType.Not;\n\t\t}\n\t\telse if (btype.equals(BuiltinType.Only)) {\n\t\t\treturn TripleModifierType.Only;\n\t\t}\n\t\telse if (btype.equals(BuiltinType.NotOnly)) {\n\t\t\treturn TripleModifierType.NotOnly;\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic Object processExpression(BooleanLiteral expr) {\n\t\tObject lit = super.processExpression(expr);\n\t\treturn lit;\n\t}\n\t\n\tpublic Node processExpression(Constant expr) throws InvalidNameException {\n//\t\tSystem.out.println(\"processing \" + expr.getClass().getCanonicalName() + \": \" + expr.getConstant());\n\t\tif (expr.getConstant().equals(\"known\")) {\n\t\t\treturn new KnownNode();\n\t\t}\n\t\treturn new ConstantNode(expr.getConstant());\n\t}\n\t\n\tpublic Object processExpression(Declaration expr) throws TranslationException {\n//\t\tString nn = expr.getNewName();\n\t\tSadlTypeReference type = expr.getType();\n\t\tString article = expr.getArticle();\n\t\tString ordinal = expr.getOrdinal();\n\t\tObject typenode = processExpression(type);\n\t\tif (article != null && isInstance(typenode)) {\n\t\t\taddError(\"An article (e.g., '\" + article + \"') should not be used in front of the name of an instance of a class.\", expr);\n\t\t}\n\t\telse if (article != null && isVariable(typenode)) {\n\t\t\taddError(\"An article (e.g., '\" + article + \"') should not be used in front of the name of a variable.\", expr);\n\t\t}\n\t\telse if (article != null && !isProperty(typenode) && !isDefinitionOfExplicitVariable(expr)) {\n\t\t\t// article should never be null, otherwise it wouldn't be a declaration\n\t\t\tint ordNum = 1;\n\t\t\tif (ordinal != null) {\n\t\t\t\tordNum = getOrdinalNumber(ordinal);\n\t\t\t}\n\t\t\telse if (article.equals(\"another\")) {\n\t\t\t\tordNum = 2;\n\t\t\t}\n\n\t\t\tif (isUseArticlesInValidation() && !isDefiniteArticle(article) && \n\t\t\t\t\ttypenode instanceof NamedNode && \n\t\t\t\t\t(((NamedNode)typenode).getNodeType().equals(NodeType.ClassNode) || ((NamedNode)typenode).getNodeType().equals(NodeType.ClassListNode))) {\n\t\t\t\tif (!isCruleVariableDefinitionPossible(expr)) {\n\t\t\t\t\tif (ordinal != null) {\n\t\t\t\t\t\taddError(\"Did not expect an indefinite article reference with ordinality in rule conclusion\", expr);\n\t\t\t\t\t}\n\t\t\t\t\treturn typenode;\n\t\t\t\t}\n\n\t\t\t\t// create a CRule variable\n\t\t\t\tString nvar = getNewVar(expr);\n\t\t\t\tVariableNode var = addCruleVariable((NamedNode)typenode, ordNum, nvar, expr, getHostEObject());\n//\t\t\t\tSystem.out.println(\"Added crule variable: \" + typenode.toString() + \", \" + ordNum + \", \" + var.toString());\n\t\t\t\treturn var;\n\t\t\t}\n\t\t\telse if (typenode != null && typenode instanceof NamedNode) {\n\t\t\t\tVariableNode var = null;\n\t\t\t\tif (isUseArticlesInValidation()) {\n\t\t\t\t\tvar = getCruleVariable((NamedNode)typenode, ordNum);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tString nvar = getNewVar(expr);\n\t\t\t\t\t\tvar = createVariable(nvar);\n\t\t\t\t\t\tvar.setType((NamedNode)typenode);\n\t\t\t\t\t} catch (IOException e) {\n\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t} catch (PrefixNotFoundException e) {\n\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t} catch (InvalidNameException e) {\n\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t} catch (InvalidTypeException e) {\n\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t} catch (ConfigurationException e) {\n\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (var == null) {\n\t\t\t\t\taddError(\"Did not find crule variable for type '\" + ((NamedNode)typenode).toString() + \"', definite article, ordinal \" + ordNum, expr);\n\t\t\t\t}\n\t\t\t\telse {\n//\t\t\t\t\tSystem.out.println(\"Retrieved crule variable: \" + typenode.toString() + \", \" + ordNum + \", \" + var.toString());\n\t\t\t\t\treturn var;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\taddError(\"No type identified\", expr);\n\t\t\t}\n\t\t}\n\t\telse if (isUseArticlesInValidation() && article == null) {\n\t\t\tif (isClass(typenode)) {\n\t\t\t\taddError(\"A class name should be preceded by either an indefinite (e.g., 'a' or 'an') or a definite (e.g., 'the') article.\", expr);\n\t\t\t}\n\t\t}\n\t\treturn typenode;\n\t}\n\t\n\tprotected EObject getHostEObject() {\n\t\treturn hostEObject ;\n\t}\n\t\n\tprotected void setHostEObject(EObject host) {\n\t\tif (hostEObject != null) {\n\t\t\tclearCruleVariablesForHostObject(hostEObject);\n\t\t}\n\t\thostEObject = host;\n\t}\n\t\n\tpublic Object processExpression(ElementInList expr) throws InvalidNameException, InvalidTypeException, TranslationException {\n\t\t// create a builtin for this\n\t\tif (expr.getElement() != null) {\n\t\t\tif (expr.getElement() instanceof PropOfSubject) {\n\t\t\t\tExpression predicate = ((PropOfSubject)expr.getElement()).getLeft();\n\t\t\t\tExpression subject = ((PropOfSubject)expr.getElement()).getRight();\n\t\t\t\tObject lst = processExpression(subject);\n\t\t\t\tObject element = processExpression(predicate);\n\t\t\t\tBuiltinElement bi = new BuiltinElement();\n\t\t\t\tbi.setFuncName(\"elementInList\");\n\t\t\t\tbi.addArgument(nodeCheck(lst));\n\t\t\t\tbi.addArgument(nodeCheck(element));\n\t\t\t\treturn bi;\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn processExpression(expr.getElement());\n//\t\t\t\tthrow new TranslationException(\"Unhandled ElementInList expression\");\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprivate boolean isVariable(Object node) {\n\t\tif (node instanceof NamedNode) {\n\t\t\tif (((NamedNode)node).getNodeType() != null && ((NamedNode)node).getNodeType().equals(NodeType.VariableNode)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprivate boolean isClass(Object node) {\n\t\tif (node instanceof NamedNode) {\n\t\t\tif (((NamedNode)node).getNodeType() != null && ((NamedNode)node).getNodeType().equals(NodeType.ClassNode)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprivate boolean isInstance(Object node) {\n\t\tif (node instanceof NamedNode) {\n\t\t\tif (((NamedNode)node).getNodeType() != null && ((NamedNode)node).getNodeType().equals(NodeType.InstanceNode)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprivate boolean isProperty(Object node) {\n\t\tif (node instanceof NamedNode) {\n\t\t\treturn isProperty(((NamedNode) node).getNodeType());\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprivate boolean isCruleVariableDefinitionPossible(Declaration expr) {\n\t\tif (getRulePart().equals(RulePart.CONCLUSION) && !isDeclInThereExists(expr)) {\n\t\t\t// this can't be a crule variable unless there is no rule body\n\t\t\tif (getTarget() != null && getTarget() instanceof Rule && \n\t\t\t\t\t(((Rule)getTarget()).getIfs() != null || ((Rule)getTarget()).getGivens() != null)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\tif (expr.eContainer() != null && expr.eContainer() instanceof BinaryOperation && isEqualOperator(((BinaryOperation)expr.eContainer()).getOp()) &&\n\t\t\t\t!((BinaryOperation)expr.eContainer()).getLeft().equals(expr) && ((BinaryOperation)expr.eContainer()).getLeft() instanceof Declaration) {\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\t\t\n\tprivate boolean isDefinitionOfExplicitVariable(Declaration expr) {\n\t\tEObject cont = expr.eContainer();\n\t\ttry {\n\t\t\tif (cont instanceof BinaryOperation && ((BinaryOperation)cont).getLeft() instanceof SadlResource && \n\t\t\t\t\tgetDeclarationExtensions().getOntConceptType((SadlResource)((BinaryOperation)cont).getLeft()).equals(OntConceptType.VARIABLE)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t} catch (CircularDefinitionException e) {\n\t\t\taddError(e.getMessage(), expr);\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprivate int getOrdinalNumber(String ordinal) throws TranslationException {\n\t\tif (ordinal == null) {\n\t\t\tthrow new TranslationException(\"Unexpected null ordinal on call to getOrdinalNumber\");\n\t\t}\n\t\tif (ordinal.equals(\"first\")) return 1;\n\t\tif (ordinal.equals(\"second\") || ordinal.equals(\"other\")) return 2;\n\t\tif (ordinal.equals(\"third\")) return 3;\n\t\tif (ordinal.equals(\"fourth\")) return 4;\n\t\tif (ordinal.equals(\"fifth\")) return 5;\n\t\tif (ordinal.equals(\"sixth\")) return 6;\n\t\tif (ordinal.equals(\"seventh\")) return 7;\n\t\tif (ordinal.equals(\"eighth\")) return 8;\n\t\tif (ordinal.equals(\"ninth\")) return 9;\n\t\tif (ordinal.equals(\"tenth\")) return 10;\n\t\tthrow new TranslationException(\"Unexpected ordinal '\" + ordinal + \"'; can't handle.\");\n\t}\n\t\n\tprivate String nextOrdinal(int ordinalNumber) throws TranslationException {\n\t\tif (ordinalNumber == 0) return \"first\";\n\t\tif (ordinalNumber == 1) return\"second\";\n\t\tif (ordinalNumber == 2) return\"third\";\n\t\tif (ordinalNumber == 3) return\"fourth\";\n\t\tif (ordinalNumber == 4) return\"fifth\";\n\t\tif (ordinalNumber == 5) return\"sixth\";\n\t\tif (ordinalNumber == 6) return\"seventh\";\n\t\tif (ordinalNumber == 7) return\"eighth\";\n\t\tif (ordinalNumber == 8) return\"ninth\";\n\t\tif (ordinalNumber == 9) return\"tenth\";\n\t\tthrow new TranslationException(\"Unexpected ordinal number '\" + ordinalNumber + \"'is larger than is handled at this time.\");\n\t}\n\t\n\tprivate boolean isDefiniteArticle(String article) {\n\t\tif (article != null && article.equalsIgnoreCase(\"the\")) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprivate Object processExpression(SadlTypeReference type) throws TranslationException {\n\t\tif (type instanceof SadlSimpleTypeReference) {\n\t\t\treturn processExpression(((SadlSimpleTypeReference)type).getType());\n\t\t}\n\t\telse if (type instanceof SadlPrimitiveDataType) {\n\t\t\tSadlDataType pt = ((SadlPrimitiveDataType)type).getPrimitiveType();\n\t\t\treturn sadlDataTypeToNamedNode(pt); \n\t\t}\n\t\telse if (type instanceof SadlUnionType) {\n\t\t\ttry {\n\t\t\t\tObject unionObj = sadlTypeReferenceToObject(type);\n\t\t\t\tif (unionObj instanceof Node) {\n\t\t\t\t\treturn unionObj;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\taddWarning(\"Unions not yet handled in this context\", type);\n\t\t\t\t}\n\t\t\t} catch (JenaProcessorException e) {\n\t\t\t\tthrow new TranslationException(\"Error processing union\", e);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tthrow new TranslationException(\"Unhandled type of SadlTypeReference: \" + type.getClass().getCanonicalName());\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprivate Object sadlDataTypeToNamedNode(SadlDataType pt) {\n\t\t/*\n\t\t string | boolean | decimal | int | long | float | double | duration | dateTime | time | date |\n gYearMonth | gYear | gMonthDay | gDay | gMonth | hexBinary | base64Binary | anyURI | \n integer | negativeInteger | nonNegativeInteger | positiveInteger | nonPositiveInteger | \n byte | unsignedByte | unsignedInt | anySimpleType;\n\t\t */\n\t\tString typeStr = pt.getLiteral();\n\t\tif (typeStr.equals(\"string\")) {\n\t\t\treturn new NamedNode(XSD.xstring.getURI(), NodeType.DataTypeNode);\n\t\t}\n\t\tif (typeStr.equals(\"boolean\")) {\n\t\t\treturn new NamedNode(XSD.xboolean.getURI(), NodeType.DataTypeNode);\n\t\t}\n\t\tif (typeStr.equals(\"byte\")) {\n\t\t\treturn new NamedNode(XSD.xbyte.getURI(), NodeType.DataTypeNode);\n\t\t}\n\t\tif (typeStr.equals(\"int\")) {\n\t\t\treturn new NamedNode(XSD.xint.getURI(), NodeType.DataTypeNode);\n\t\t}\n\t\tif (typeStr.equals(\"long\")) {\n\t\t\treturn new NamedNode(XSD.xlong.getURI(), NodeType.DataTypeNode);\n\t\t}\n\t\tif (typeStr.equals(\"float\")) {\n\t\t\treturn new NamedNode(XSD.xfloat.getURI(), NodeType.DataTypeNode);\n\t\t}\n\t\tif (typeStr.equals(\"double\")) {\n\t\t\treturn new NamedNode(XSD.xdouble.getURI(), NodeType.DataTypeNode);\n\t\t}\n\t\tif (typeStr.equals(\"short\")) {\n\t\t\treturn new NamedNode(XSD.xshort.getURI(), NodeType.DataTypeNode);\n\t\t}\n\t\treturn new NamedNode(XSD.getURI() + \"#\" + typeStr, NodeType.DataTypeNode);\n\t}\n\t\n\tpublic Object processExpression(Name expr) throws TranslationException, InvalidNameException, InvalidTypeException {\n\t\tif (expr.isFunction()) {\n\t\t\treturn processFunction(expr);\n\t\t}\n\t\tSadlResource qnm =expr.getName();\n\t\tString nm = getDeclarationExtensions().getConcreteName(qnm);\n\t\tif (nm == null) {\n\t\t\tSadlResource srnm = qnm.getName();\n\t\t\tif (srnm != null) {\n\t\t\t\treturn processExpression(srnm);\n\t\t\t}\n\t\t\taddError(SadlErrorMessages.TRANSLATE_NAME_SADLRESOURCE.toString(), expr);\n//\t\t\tthrow new InvalidNameException(\"Unable to resolve SadlResource to a name\");\n\t\t}\n\t\telse if (qnm.equals(expr) && expr.eContainer() instanceof BinaryOperation && \n\t\t\t\t((BinaryOperation)expr.eContainer()).getRight() != null && ((BinaryOperation)expr.eContainer()).getRight().equals(qnm)) {\n\t\t\taddError(\"It appears that '\" + nm + \"' is not defined.\", expr);\n\t\t}\n\t\telse {\n\t\t\treturn processExpression(qnm);\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprivate String getPrefix(String qn) {\n\t\tif (qn.contains(\":\")) {\n\t\t\treturn qn.substring(0,qn.indexOf(\":\"));\n\t\t}\n\t\treturn qn;\n\t}\n\tpublic Object \tprocessExpression(NumberLiteral expr) {\n\t\tObject lit = super.processExpression(expr);\n\t\treturn lit;\n\t}\n\t\n\tpublic Object processExpression(StringLiteral expr) {\n\t\treturn super.processExpression(expr);\n\t}\n\t\n\tpublic Object processExpression(PropOfSubject expr) throws InvalidNameException, InvalidTypeException, TranslationException {\n\t\tExpression predicate = expr.getLeft();\n\t\tif (predicate == null) {\n\t\t\taddError(\"Predicate in expression is null. Are parentheses needed?\", expr);\n\t\t\treturn null;\n\t\t}\n\t\tExpression subject = expr.getRight();\n\t\tObject trSubj = null;\n\t\tObject trPred = null;\n\t\tNode subjNode = null;\n\t\tNode predNode = null;\n\t\tString constantBuiltinName = null;\n\t\tint numBuiltinArgs = 0;\n\t\tif (predicate instanceof Constant) {\n\t\t\t// this is a pseudo PropOfSubject; the predicate is a constant\n\t\t\tString cnstval = ((Constant)predicate).getConstant();\n\t\t\tif (cnstval.equals(\"length\") || cnstval.equals(\"the length\")) {\n\t\t\t\tconstantBuiltinName = \"length\";\n\t\t\t\tnumBuiltinArgs = 1;\n\t\t\t\tif (subject instanceof PropOfSubject) {\n\t\t\t\t\tpredicate = ((PropOfSubject)subject).getLeft();\n\t\t\t\t\tsubject = ((PropOfSubject)subject).getRight();\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (cnstval.equals(\"count\")) {\n\t\t\t\tconstantBuiltinName = cnstval;\n\t\t\t\tnumBuiltinArgs = 2;\n\t\t\t\tif (subject instanceof PropOfSubject) {\n\t\t\t\t\tpredicate = ((PropOfSubject)subject).getLeft();\n\t\t\t\t\tsubject = ((PropOfSubject)subject).getRight();\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (cnstval.endsWith(\"index\")) {\n\t\t\t\tconstantBuiltinName = cnstval;\n\t\t\t\tnumBuiltinArgs = 2;\n\t\t\t\tif (subject instanceof PropOfSubject) {\n\t\t\t\t\tpredicate = ((PropOfSubject)subject).getLeft();\n\t\t\t\t\tsubject = ((PropOfSubject)subject).getRight();\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (cnstval.equals(\"first element\")) {\n\t\t\t\tconstantBuiltinName = \"firstElement\";\n\t\t\t\tnumBuiltinArgs = 1;\n\t\t\t\tif (subject instanceof PropOfSubject) {\n\t\t\t\t\tpredicate = ((PropOfSubject)subject).getLeft();\n\t\t\t\t\tsubject = ((PropOfSubject)subject).getRight();\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (cnstval.equals(\"last element\")) {\n\t\t\t\tconstantBuiltinName = \"lastElement\";\n\t\t\t\tnumBuiltinArgs = 1;\n\t\t\t\tif (subject instanceof PropOfSubject) {\n\t\t\t\t\tpredicate = ((PropOfSubject)subject).getLeft();\n\t\t\t\t\tsubject = ((PropOfSubject)subject).getRight();\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (cnstval.endsWith(\"element\")) {\n\t\t\t\tconstantBuiltinName = cnstval;\n\t\t\t\tnumBuiltinArgs = 2;\n\t\t\t\tif (subject instanceof PropOfSubject) {\n\t\t\t\t\tpredicate = ((PropOfSubject)subject).getLeft();\n\t\t\t\t\tsubject = ((PropOfSubject)subject).getRight();\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tSystem.err.println(\"Unhandled constant property in translate PropOfSubj: \" + cnstval);\n\t\t\t}\n\t\t}\n\t\telse if (predicate instanceof ElementInList) {\n\t\t\ttrSubj = processExpression(subject);\n\t\t\ttrPred = processExpression(predicate);\n\t\t\tBuiltinElement bi = new BuiltinElement();\n\t\t\tbi.setFuncName(\"elementInList\");\n\t\t\tbi.addArgument(nodeCheck(trSubj));\n\t\t\tbi.addArgument(nodeCheck(trPred));\n\t\t\treturn bi;\n\t\t\t\n\t\t}\n\t\tif (subject != null) {\n\t\t\ttrSubj = processExpression(subject);\n\t\t\tif (isUseArticlesInValidation() && subject instanceof Name && trSubj instanceof NamedNode && ((NamedNode)trSubj).getNodeType().equals(NodeType.ClassNode)) {\n\t\t\t\t// we have a class in a PropOfSubject that does not have an article (otherwise it would have been a Declaration)\n\t\t\t\taddError(\"A class name in this context should be preceded by an article, e.g., 'a', 'an', or 'the'.\", subject);\n\t\t\t}\n\t\t}\n\t\tboolean isPreviousPredicate = false;\n\t\tif (predicate != null) {\n\t\t\ttrPred = processExpression(predicate);\n\t\t}\n\t\tif (constantBuiltinName == null || numBuiltinArgs == 1) {\n\t\t\tTripleElement returnTriple = null;\n\t\t\tif (trPred instanceof Node) {\n\t\t\t\tpredNode = (Node) trPred;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tpredNode = new ProxyNode(trPred);\n\t\t\t}\n\t\t\tif (trSubj instanceof Node) {\n\t\t\t\tsubjNode = (Node) trSubj;\n\t\t\t}\n\t\t\telse if (trSubj != null) {\n\t\t\t\tsubjNode = new ProxyNode(trSubj);\n\t\t\t}\n\t\t\tif (predNode != null && predNode instanceof Node) {\n\t\t\t\treturnTriple = new TripleElement(subjNode, predNode, null);\n\t\t\t\treturnTriple.setSourceType(TripleSourceType.PSV);\n\t\t\t\tif (constantBuiltinName == null) {\n\t\t\t\t\treturn returnTriple;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (numBuiltinArgs == 1) {\n\t\t\t\tObject bi = createUnaryBuiltin(expr, constantBuiltinName, new ProxyNode(returnTriple) );\n\t\t\t\treturn bi;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tpredNode = new RDFTypeNode();\t\t\t\n\t\t\t\tNode variable = getVariableNode(expr, null, predNode, subjNode);\n\t\t\t\treturnTriple = new TripleElement();\n\t\t\t\treturnTriple.setSubject(variable);\n\t\t\t\treturnTriple.setPredicate(predNode);\n\t\t\t\treturnTriple.setObject(subjNode);\n\t\t\t\tif (subjNode instanceof NamedNode && !((NamedNode)subjNode).getNodeType().equals(NodeType.ClassNode)) {\n\t\t\t\t\taddError(SadlErrorMessages.IS_NOT_A.get(subjNode.toString(), \"class\"), subject);\n\t\t\t\t}\n\t\t\t\treturnTriple.setSourceType(TripleSourceType.ITC);\n\t\t\t\treturn returnTriple;\n\t\t\t}\n\t\t}\n\t\telse {\t// none of these create more than 2 arguments\n\t\t\tObject bi = createBinaryBuiltin(constantBuiltinName, trPred, nodeCheck(trSubj));\n\t\t\treturn bi;\n\t\t}\n\t}\n\t\n\tpublic Node processExpression(SadlResource expr) throws TranslationException {\n\t\tString nm = getDeclarationExtensions().getConcreteName(expr);\n\t\tString ns = getDeclarationExtensions().getConceptNamespace(expr);\n\t\tString prfx = getDeclarationExtensions().getConceptPrefix(expr);\n\t\tOntConceptType type;\n\t\ttry {\n\t\t\ttype = getDeclarationExtensions().getOntConceptType(expr);\n\t\t} catch (CircularDefinitionException e) {\n\t\t\ttype = e.getDefinitionType();\n\t\t\taddError(e.getMessage(), expr);\n\t\t}\n\t\tif (type.equals(OntConceptType.VARIABLE) && nm != null) {\n\t\t\tVariableNode vn = null;\n\t\t\ttry {\n\t\t\t\tvn = createVariable(expr);\n\t\t\t} catch (IOException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (PrefixNotFoundException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (InvalidNameException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (InvalidTypeException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (ConfigurationException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t\treturn vn;\n\t\t}\n\t\telse if (nm != null) {\n\t\t\tNamedNode n = new NamedNode(nm, ontConceptTypeToNodeType(type));\n\t\t\tn.setNamespace(ns);\n\t\t\tn.setPrefix(prfx);\n\t\t\treturn n;\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprotected Object processSubjHasPropUnitExpression(SubjHasProp expr) throws InvalidNameException, InvalidTypeException, TranslationException {\n\t\tExpression valexpr = expr.getLeft();\n\t\tObject valarg = processExpression(valexpr);\n\t\tif (ignoreUnittedQuantities) {\n\t\t\treturn valarg;\n\t\t}\n\t\tString unit = SadlASTUtils.getUnitAsString(expr);\n\t\tif (valarg instanceof com.ge.research.sadl.model.gp.Literal) {\n\t\t\t((com.ge.research.sadl.model.gp.Literal)valarg).setUnits(unit);\n\t\t\treturn valarg;\n\t\t}\n\t\tcom.ge.research.sadl.model.gp.Literal unitLiteral = new com.ge.research.sadl.model.gp.Literal();\n\t\tunitLiteral.setValue(unit);\n\t\treturn createBinaryBuiltin(\"unittedQuantity\", valarg, unitLiteral);\n\t}\n\n\t\n\tpublic Object processExpression(SubjHasProp expr) throws InvalidNameException, InvalidTypeException, TranslationException {\n//\t\tSystem.out.println(\"processing \" + expr.getClass().getCanonicalName() + \": \" + expr.getProp().toString());\n\t\tExpression subj = expr.getLeft();\n\t\tSadlResource pred = expr.getProp();\n\t\tExpression obj = expr.getRight();\n\t\treturn processSubjHasProp(subj, pred, obj);\n\t}\n\t\n\tprivate TripleElement processSubjHasProp(Expression subj, SadlResource pred, Expression obj)\n\t\t\tthrows InvalidNameException, InvalidTypeException, TranslationException {\n\t\tboolean isSubjVariableDefinition = false;\n\t\tboolean isObjVariableDefinition = false;\n\t\tName subjVariableName = null;\n\t\tName objVariableName = null;\n\t\tboolean subjectIsVariable = false;\n\t\tboolean objectIsVariable = false;\n\t\ttry {\n\t\t\tif (subj instanceof Name && isVariableDefinition((Name)subj)) {\n\t\t\t\t// variable is defined by domain of property pred\n\t\t\t\tisSubjVariableDefinition = true;\n\t\t\t\tsubjVariableName = (Name)subj;\n\t\t\t\tsubjectIsVariable = true;\n\t\t\t}\n\t\t\telse if (subj instanceof Declaration && isVariableDefinition((Declaration)subj)) {\n\t\t\t\t// variable is defined by a CRule declaration\n\t\t\t\tisSubjVariableDefinition = true;\n\t\t\t\tsubjectIsVariable = true;\t\t\t}\n\t\t\tif (obj instanceof Name && isVariableDefinition((Name)obj)) {\n\t\t\t\t// variable is defined by range of property pred\n\t\t\t\tisObjVariableDefinition = true;\n\t\t\t\tobjVariableName = (Name)obj;\n\t\t\t\tobjectIsVariable = true;\n\t\t\t}\n\t\t\telse if (obj instanceof Declaration && isVariableDefinition((Declaration)obj)) {\n\t\t\t\t// variable is defined by a CRule declaration\n\t\t\t\tisObjVariableDefinition = true;\n\t\t\t\tobjectIsVariable = true;\n\t\t\t}\n\t\t} catch (CircularDefinitionException e1) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te1.printStackTrace();\n\t\t}\n\t\t\n\t\tif (!isSubjVariableDefinition && !isObjVariableDefinition && getModelValidator() != null) {\n\t\t\tgetModelValidator().checkPropertyDomain(getTheJenaModel(), subj, pred, pred, false);\n\t\t\tif (obj != null) {\t// rules can have SubjHasProp expressions with null object\n\t\t\t\ttry {\n\t\t\t\t\tgetModelValidator().checkPropertyValueInRange(getTheJenaModel(), subj, pred, obj, new StringBuilder());\n\t\t\t\t} catch (DontTypeCheckException e) {\n\t\t\t\t\t// don't do anything\n\t\t\t\t} catch (PropertyWithoutRangeException e) {\n\t\t\t\t\taddError(\"Property does not have a range\", pred);\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\tthrow new TranslationException(\"Error checking value in range\", e);\n\t\t\t\t} \n\t\t\t}\n\t\t}\n\t\tObject sobj = null;\n\t\tObject pobj = null;\n\t\tObject oobj = null;\n\n\t\tif (pred != null) {\n\t\t\ttry {\n\t\t\t\tpobj = processExpression(pred);\n\t\t\t\tProperty prop = getTheJenaModel().getProperty(((NamedNode)pobj).toFullyQualifiedString());\n\t\t\t\tOntConceptType predOntConceptType = getDeclarationExtensions().getOntConceptType(pred);\n\t\t\t\tConceptName propcn = new ConceptName(((NamedNode)pobj).toFullyQualifiedString());\n\t\t\t\tpropcn.setType(nodeTypeToConceptType(ontConceptTypeToNodeType(predOntConceptType)));\n\t\t\t\tif (isSubjVariableDefinition && pobj instanceof NamedNode) {\n\t\t\t\t\tVariableNode var = null;\n\t\t\t\t\tif (subjVariableName != null) {\n//\t\t\t\t\t\tSystem.out.println(\"Variable '\" + getDeclarationExtensions().getConcreteName(subjVariableName.getName()) + \"' is defined by domain of property '\" + \n//\t\t\t\t\t\t\t\tgetDeclarationExtensions().getConceptUri(pred) + \"'\");\n\t\t\t\t\t\tvar = createVariable(subjVariableName.getName()); //getDeclarationExtensions().getConceptUri(subjVariableName.getName()));\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tsobj = processExpression(subj);\n\t\t\t\t\t}\n\t\t\t\t\tif (var != null && var.getType() == null) {\t\t// it's a variable and we don't know the type so try to get the type\n\t\t\t\t\t\tTypeCheckInfo dtci = getModelValidator().getTypeInfoFromDomain(propcn, prop, pred);\n\t\t\t\t\t\tif (dtci != null) {\n\t\t\t\t\t\t\tif (dtci.getCompoundTypes() != null) {\n\t\t\t\t\t\t\t\tObject jct = compoundTypeCheckTypeToNode(dtci, pred);\n\t\t\t\t\t\t\t\tif (jct != null && jct instanceof Junction) {\n\t\t\t\t\t\t\t\t\tif (var.getType() == null) {\n\t\t\t\t\t\t\t\t\t\tvar.setType(nodeCheck(jct));\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\taddError(\"Compound type check did not process into expected result for variable type\", pred);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if(dtci.getTypeCheckType() != null) {\n\t\t\t\t\t\t\t\tConceptIdentifier tcitype = dtci.getTypeCheckType();\n\t\t\t\t\t\t\t\tif (tcitype instanceof ConceptName) {\n\t\t\t\t\t\t\t\t\tNamedNode defn = conceptNameToNamedNode((ConceptName)tcitype);\n\t\t\t\t\t\t\t\t\tif (var.getType() == null) {\n\t\t\t\t\t\t\t\t\t\tvar.setType((NamedNode) defn);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\taddError(\"Domain type did not return a ConceptName for variable type\", pred);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\taddError(\"Domain type check info doesn't have information to set variable type\", pred);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsobj = var;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (isObjVariableDefinition && pobj instanceof NamedNode) {\n\t\t\t\t\tVariableNode var = null;\n\t\t\t\t\tif (objVariableName != null) {\n//\t\t\t\t\t\tSystem.out.println(\"Variable '\" + getDeclarationExtensions().getConcreteName(objVariableName.getName()) + \"' is defined by range of property '\" + \n//\t\t\t\t\t\t\t\tgetDeclarationExtensions().getConceptUri(pred) + \"'\");\n\t\t\t\t\t\tvar = createVariable(getDeclarationExtensions().getConceptUri(objVariableName.getName()));\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\toobj = processExpression(obj);\n\t\t\t\t\t}\n\t\t\t\t\tif (var != null) {\n\t\t\t\t\t\tTypeCheckInfo dtci = getModelValidator().getTypeInfoFromRange(propcn, prop, pred);\n\t\t\t\t\t\tif (dtci != null && dtci.getTypeCheckType() != null) {\n\t\t\t\t\t\t\tConceptIdentifier tcitype = dtci.getTypeCheckType();\n\t\t\t\t\t\t\tif (tcitype instanceof ConceptName) {\n\t\t\t\t\t\t\t\tNamedNode defn = conceptNameToNamedNode((ConceptName)tcitype);\n\t\t\t\t\t\t\t\tif (var.getType() == null) {\n\t\t\t\t\t\t\t\t\tvar.setType((NamedNode) defn);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\taddError(\"Range type did not return a ConceptName\", pred);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\toobj = var;\n\t\t\t\t\t}\n\t\t\t\t}\n// TODO should also check for restrictions on the class and local restrictions?\n\t\t\t} catch (IOException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (PrefixNotFoundException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (ConfigurationException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (DontTypeCheckException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (CircularDefinitionException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t}\t\t\t\n\t\t}\n\t\tboolean negateTriple = false;\n\t\tif (sobj == null && subj != null) {\n\t\t\tif (subj instanceof UnaryExpression && ((UnaryExpression)subj).getOp().equals(\"not\") && pobj != null) {\n\t\t\t\t// treat this negation as applying to the whole triple\n\t\t\t\tExpression subjexpr = ((UnaryExpression)subj).getExpr();\n\t\t\t\tObject subjtr = processExpression(subjexpr);\n\t\t\t\tnegateTriple = true;\n\t\t\t\tsobj = subjtr;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tsobj = processExpression(subj);\n\t\t\t}\n\t\t}\n\t\tif (oobj == null && obj != null) {\n\t\t\toobj = processExpression(obj);\n\t\t}\n\t\tTripleElement returnTriple = null;\n\t\tif (pobj != null) {\n\t\t\treturnTriple = new TripleElement(null, nodeCheck(pobj), null);\n\t\t\treturnTriple.setSourceType(TripleSourceType.SPV);\n\t\t\tif (negateTriple) {\n\t\t\t\treturnTriple.setType(TripleModifierType.Not);\n\t\t\t}\n\t\t}\n\t\tif (sobj != null) {\n\t\t\treturnTriple.setSubject(nodeCheck(sobj));\n\t\t}\n\t\tif (oobj != null) {\n\t\t\treturnTriple.setObject(nodeCheck(oobj));\n\t\t}\n\t\treturn returnTriple;\n\t}\n\t\n\tprivate Junction compoundTypeCheckTypeToNode(TypeCheckInfo dtci, EObject expr) throws InvalidNameException, InvalidTypeException, TranslationException {\n\t\tIterator ctitr = dtci.getCompoundTypes().iterator();\n\t\tJunction last = null;\n\t\tJunction jct = null;\n\t\twhile (ctitr.hasNext()) {\n\t\t\tObject current = null;\n\t\t\tTypeCheckInfo tci = ctitr.next();\n\t\t\tif (tci.getCompoundTypes() != null) {\n\t\t\t\tcurrent = compoundTypeCheckTypeToNode(tci, expr);\n\t\t\t}\n\t\t\telse if (tci.getTypeCheckType() != null) {\n\t\t\t\tif (tci.getTypeCheckType() instanceof ConceptName) {\n\t\t\t\t\tcurrent = conceptNameToNamedNode((ConceptName) tci.getTypeCheckType());\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\taddError(\"Type check info doesn't have expected ConceptName type\", expr);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\taddError(\"Type check info doesn't have valid type\", expr);\n\t\t\t}\n\t\t\tif (current != null) {\n\t\t\t\tif (jct == null) {\n\t\t\t\t\tif (ctitr.hasNext()) {\n\t\t\t\t\t\t// there is more so new junction\n\t\t\t\t\t\tjct = new Junction();\n\t\t\t\t\t\tjct.setJunctionName(\"or\");\n\t\t\t\t\t\tif (last != null) {\n\t\t\t\t\t\t\t// this is a nested junction\n\t\t\t\t\t\t\tjct.setLhs(last);\n\t\t\t\t\t\t\tjct.setRhs(current);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t// this is not a nested junction so just set the LHS to current, RHS will be set on next iteration\n\t\t\t\t\t\t\tjct.setLhs(current);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (current instanceof Junction){\n\t\t\t\t\t\tlast = (Junction) current;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\t// this shouldn't happen\n\t\t\t\t\t\taddError(\"Unexpected non-Junction result of compound type check to Junction\", expr);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// this finishes off the RHS of the first junction\n\t\t\t\t\tjct.setRhs(current);\n\t\t\t\t\tlast = jct;\n\t\t\t\t\tjct = null;\t\t// there should always be a final RHS that will set last, which is returned\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn last;\n\t}\n\t\n\tpublic Object processExpression(Sublist expr) throws InvalidNameException, InvalidTypeException, TranslationException {\n\t\tExpression list = expr.getList();\n\t\tExpression where = expr.getWhere();\n\t\tObject lobj = processExpression(list);\n\t\tObject wobj = processExpression(where);\n\t\t\n\t\taddError(\"Processing of sublist construct not yet implemented: \" + lobj.toString() + \", \" + wobj.toString(), expr);\n\t\t\n\t\tBuiltinElement builtin = new BuiltinElement();\n\t\tbuiltin.setFuncName(\"sublist\");\n\t\tbuiltin.addArgument(nodeCheck(lobj));\n\t\tif (lobj instanceof GraphPatternElement) {\n\t\t\t((GraphPatternElement)lobj).setEmbedded(true);\n\t\t}\n\t\tbuiltin.addArgument(nodeCheck(wobj));\n\t\tif (wobj instanceof GraphPatternElement) {\n\t\t\t((GraphPatternElement)wobj).setEmbedded(true);\n\t\t}\n\t\treturn builtin;\n\t}\n\t\n\tpublic Object processExpression(UnaryExpression expr) throws InvalidNameException, InvalidTypeException, TranslationException {\n\t\tObject eobj = processExpression(expr.getExpr());\n\t\tif (eobj instanceof VariableNode && ((VariableNode)eobj).isCRulesVariable() && ((VariableNode)eobj).getType() != null) {\n\t\t\tTripleElement trel = new TripleElement((VariableNode)eobj, new RDFTypeNode(), ((VariableNode)eobj).getType());\n\t\t\ttrel.setSourceType(TripleSourceType.SPV);\n\t\t\teobj = trel;\n\t\t}\n\t\tString op = expr.getOp();\n\t\tif (eobj instanceof com.ge.research.sadl.model.gp.Literal) {\n\t\t\tObject val = ((com.ge.research.sadl.model.gp.Literal)eobj).getValue();\n\t\t\tif (op.equals(\"-\") && val instanceof Number) {\n\t\t\t\tif (val instanceof BigDecimal) {\n\t\t\t\t\tval = ((BigDecimal)val).negate();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tval = -1.0 * ((Number)val).doubleValue();\n\t\t\t\t}\n\t\t\t\t((com.ge.research.sadl.model.gp.Literal)eobj).setValue(val);\n\t\t\t\t((com.ge.research.sadl.model.gp.Literal)eobj).setOriginalText(op + ((com.ge.research.sadl.model.gp.Literal)eobj).getOriginalText());\n\t\t\t\treturn eobj;\n\t\t\t}\n\t\t\telse if (op.equals(\"not\")) {\n\t\t\t\tif (val instanceof Boolean) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tboolean bval = ((Boolean)val).booleanValue();\n\t\t\t\t\t\tif (bval) {\n\t\t\t\t\t\t\t((com.ge.research.sadl.model.gp.Literal)eobj).setValue(false);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t((com.ge.research.sadl.model.gp.Literal)eobj).setValue(true);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t((com.ge.research.sadl.model.gp.Literal)eobj).setOriginalText(op + \" \" + ((com.ge.research.sadl.model.gp.Literal)eobj).getOriginalText());\n\t\t\t\t\t\treturn eobj;\n\t\t\t\t\t}\n\t\t\t\t\tcatch (Exception e) {\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// this is a not before a non-boolean value so we want to pull the negation up\n\t\t\t\t\tpullOperationUp(expr);\n\t\t\t\t\treturn eobj;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\taddError(\"Unhandled unary operator '\" + op + \"' not processed\", expr);\n\t\t\t}\n\t\t}\n\t\tBuiltinElement bi = new BuiltinElement();\n\t\tbi.setFuncName(op);\n\t\tif (eobj instanceof Node) {\n\t\t\tbi.addArgument((Node) eobj);\n\t\t}\n\t\telse if (eobj instanceof GraphPatternElement) {\n\t\t\tbi.addArgument(new ProxyNode(eobj));\n\t\t}\n\t\telse if (eobj == null) {\n\t\t\taddError(\"Unary operator '\" + op + \"' has no argument. Perhaps parentheses are needed.\", expr);\n\t\t}\n\t\telse {\n\t\t\tthrow new TranslationException(\"Expected node, got '\" + eobj.getClass().getCanonicalName() + \"'\");\n\t\t}\n\t\treturn bi;\n\t}\n\t\n\tprivate void pullOperationUp(UnaryExpression expr) {\n\t\tif (expr != null) {\n\t\t\tif (operationsPullingUp == null) {\n\t\t\t\toperationsPullingUp = new ArrayList();\n\t\t\t}\n\t\t\toperationsPullingUp.add(expr);\n\t\t}\n\t}\n\t\n\tprivate EObject getOperationPullingUp() {\n\t\tif (operationsPullingUp != null && operationsPullingUp.size() > 0) {\n\t\t\tEObject removed = operationsPullingUp.remove(operationsPullingUp.size() - 1);\n\t\t\treturn removed;\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprivate boolean isOperationPulingUp(EObject expr) {\n\t\tif (operationsPullingUp != null && operationsPullingUp.size() > 0) {\n\t\t\tif (operationsPullingUp.get(operationsPullingUp.size() - 1).equals(expr)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tpublic Object processExpression(UnitExpression expr) throws InvalidNameException, InvalidTypeException, TranslationException {\n\t\tString unit = expr.getUnit();\n\t\tExpression value = expr.getLeft();\n\t\tObject valobj = null;\n\t\tvalobj = processExpression(value);\n\t\tif (ignoreUnittedQuantities) {\n\t\t\treturn valobj;\n\t\t}\n\t\tif (valobj instanceof com.ge.research.sadl.model.gp.Literal) {\n\t\t\t((com.ge.research.sadl.model.gp.Literal)valobj).setUnits(unit);\n\t\t\treturn valobj;\n\t\t}\n\t\tcom.ge.research.sadl.model.gp.Literal unitLiteral = new com.ge.research.sadl.model.gp.Literal();\n\t\tunitLiteral.setValue(unit);\n\t\treturn createBinaryBuiltin(\"unittedQuantity\", valobj, unitLiteral);\n\t}\n\t\n//\tpublic Object processExpression(SubjHasProp expr) {\n//\t\tString unit = expr.getUnit();\n//\t\tExpression value = expr.getValue();\n//\t\tObject valobj;\n//\t\ttry {\n//\t\t\tvalobj = processExpression(value);\n//\t\t\tif (valobj instanceof com.ge.research.sadl.model.gp.Literal) {\n//\t\t\t\t((com.ge.research.sadl.model.gp.Literal)valobj).setUnits(unit);\n//\t\t\t}\n//\t\t\treturn valobj;\n//\t\t} catch (TranslationException e) {\n//\t\t\taddError(e.getMessage(), expr);\n//\t\t} catch (InvalidNameException e) {\n//\t\t\taddError(e.getMessage(), expr);\n//\t\t} catch (InvalidTypeException e) {\n//\t\t\taddError(e.getMessage(), expr);\n//\t\t}\n//\t\treturn null;\n//\t}\n\t\n\tprivate void processSadlSameAs(SadlSameAs element) throws JenaProcessorException {\n\t\tSadlResource sr = element.getNameOrRef();\n\t\tString uri = getDeclarationExtensions().getConceptUri(sr);\n\t\tOntResource rsrc = getTheJenaModel().getOntResource(uri);\n\t\tSadlTypeReference smas = element.getSameAs();\n\t\tOntConceptType sameAsType;\n\t\tif (rsrc == null) {\n\t\t\t// concept does not exist--try to get the type from the sameAs\n\t\t\tsameAsType = getSadlTypeReferenceType(smas);\n\t\t\t\n\t\t}\n\t\telse {\n\t\t\ttry {\n\t\t\t\tsameAsType = getDeclarationExtensions().getOntConceptType(sr);\n\t\t\t} catch (CircularDefinitionException e) {\n\t\t\t\tsameAsType = e.getDefinitionType();\n\t\t\t\taddError(e.getMessage(), element);\n\t\t\t}\n\t\t}\n\t\tif (sameAsType.equals(OntConceptType.CLASS)) {\n\t\t\tOntClass smasCls = sadlTypeReferenceToOntResource(smas).asClass();\n\t\t\t// this is a class axiom\n\t\t\tOntClass cls = getTheJenaModel().getOntClass(uri);\n\t\t\tif (cls == null) {\n\t\t\t\t// this is OK--create class\n\t\t\t\tcls = createOntClass(getDeclarationExtensions().getConcreteName(sr), (String)null, null);\n\t\t\t}\n\t\t\tif (element.isComplement()) {\n\t\t\t\tComplementClass cc = getTheJenaModel().createComplementClass(cls.getURI(), smasCls);\n\t\t\t\tlogger.debug(\"New complement class '\" + cls.getURI() + \"' created\");\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcls.addEquivalentClass(smasCls);\n\t\t\t\tlogger.debug(\"Class '\" + cls.toString() + \"' given equivalent class '\" + smasCls.toString() + \"'\");\n\t\t\t}\n\t\t}\n\t\telse if (sameAsType.equals(OntConceptType.INSTANCE)) {\n\t\t\tOntResource smasInst = sadlTypeReferenceToOntResource(smas);\n\t\t\trsrc.addSameAs(smasInst);\n\t\t\tlogger.debug(\"Instance '\" + rsrc.toString() + \"' declared same as '\" + smas.toString() + \"'\");\n\t\t}\n\t\telse {\n\t\t\tthrow new JenaProcessorException(\"Unexpected concept type for same as statement: \" + sameAsType.toString());\n\t\t}\n\t}\n\n\tprivate List processSadlClassOrPropertyDeclaration(SadlClassOrPropertyDeclaration element) throws JenaProcessorException, TranslationException {\n\t\tif (isEObjectPreprocessed(element)) {\n\t\t\treturn null;\n\t\t}\n\t\t// Get the names of the declared concepts and store in a list\n\t\tList newNames = new ArrayList();\n\t\tMap> nmanns = null;\n\t\tEList clses = element.getClassOrProperty();\n\t\tif (clses != null) {\n\t\t\tIterator citer = clses.iterator();\n\t\t\twhile (citer.hasNext()) {\n\t\t\t\tSadlResource sr = citer.next();\n\t\t\t\tString nm = getDeclarationExtensions().getConceptUri(sr);\n\t\t\t\tSadlResource decl = getDeclarationExtensions().getDeclaration(sr);\n\t\t\t\tif (!(decl.equals(sr))) {\n\t\t\t\t\t// defined already\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (getDeclarationExtensions().getOntConceptType(decl).equals(OntConceptType.STRUCTURE_NAME)) {\n\t\t\t\t\t\t\taddError(\"This is already a Named Structure\", sr);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (CircularDefinitionException e) {\n\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tnewNames.add(nm);\n\t\t\t\tEList anns = sr.getAnnotations();\n\t\t\t\tif (anns != null && anns.size() > 0) {\n\t\t\t\t\tif (nmanns == null) {\n\t\t\t\t\t\tnmanns = new HashMap>();\n\t\t\t\t\t}\n\t\t\t\t\tnmanns.put(nm, anns);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (newNames.size() < 1) {\n\t\t\tthrow new JenaProcessorException(\"No names passed to processSadlClassOrPropertyDeclaration\");\n\t\t}\n\t\tList rsrcList = new ArrayList();\n\t\t// The declared concept(s) will be of type class, property, or datatype. \n\t\t//\tDetermining which will depend on the structure, including the superElement....\n\t\t// \tGet the superElement\n\t\tSadlTypeReference superElement = element.getSuperElement();\n\t\tboolean isList = typeRefIsList(superElement);\n\t\t//\t\t1) if superElement is null then it is a top-level class declaration\n\t\tif (superElement == null) {\n\t\t\tOntClass cls = createOntClass(newNames.get(0), (OntClass)null);\n\t\t\tif (nmanns != null && nmanns.get(newNames.get(0)) != null) {\n\t\t\t\taddAnnotationsToResource(cls, nmanns.get(newNames.get(0)));\n\t\t\t}\n\t\t\trsrcList.add(cls);\n\t\t}\n\t\t// \t2) if superElement is not null then the type of the new concept is the same as the type of the superElement\n\t\t// \t\t\tthe superElement can be:\n\t\t// \t\t\t\ta) a SadlSimpleTypeReference\n\t\telse if (superElement instanceof SadlSimpleTypeReference) {\n\t\t\tSadlResource superSR = ((SadlSimpleTypeReference)superElement).getType();\n\t\t\tString superSRUri = getDeclarationExtensions().getConceptUri(superSR);\t\n\t\t\tOntConceptType superElementType;\n\t\t\ttry {\n\t\t\t\tsuperElementType = getDeclarationExtensions().getOntConceptType(superSR);\n\t\t\t\tif (isList) {\n\t\t\t\t\tsuperElementType = OntConceptType.CLASS_LIST;\n\t\t\t\t}\n\t\t\t} catch (CircularDefinitionException e) {\n\t\t\t\tsuperElementType = e.getDefinitionType();\n\t\t\t\taddError(SadlErrorMessages.CIRCULAR_IMPORT.get(superSRUri), superElement);\n\t\t\t}\n\t\t\tif (superElementType.equals(OntConceptType.CLASS)) {\n\t\t\t\tfor (int i = 0; i < newNames.size(); i++) {\n\t\t\t\t\tOntClass cls = createOntClass(newNames.get(i), superSRUri, superSR);\n\t\t\t\t\tif (nmanns != null && nmanns.get(newNames.get(i)) != null) {\n\t\t\t\t\t\taddAnnotationsToResource(cls, nmanns.get(newNames.get(i)));\n\t\t\t\t\t}\n\t\t\t\t\trsrcList.add(cls);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (superElementType.equals(OntConceptType.CLASS_LIST) || superElementType.equals(OntConceptType.DATATYPE_LIST)) {\n\t\t\t\tfor (int i = 0; i < newNames.size(); i++) {\n\t\t\t\t\trsrcList.add(getOrCreateListSubclass(newNames.get(i), superSRUri, superSR.eResource()));\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (superElementType.equals(OntConceptType.CLASS_PROPERTY)) {\n\t\t\t\tfor (int i = 0; i < newNames.size(); i++) {\n\t\t\t\t\tOntProperty prop = createObjectProperty(newNames.get(i), superSRUri);\n\t\t\t\t\tif (nmanns != null && nmanns.get(newNames.get(i)) != null) {\n\t\t\t\t\t\taddAnnotationsToResource(prop, nmanns.get(newNames.get(i)));\n\t\t\t\t\t}\n\t\t\t\t\trsrcList.add(prop);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (superElementType.equals(OntConceptType.DATATYPE_PROPERTY)) {\n\t\t\t\tfor (int i = 0; i < newNames.size(); i++) {\n\t\t\t\t\tDatatypeProperty prop = createDatatypeProperty(newNames.get(i), superSRUri);\n\t\t\t\t\tif (nmanns != null && nmanns.get(newNames.get(i)) != null) {\n\t\t\t\t\t\taddAnnotationsToResource(prop, nmanns.get(newNames.get(i)));\n\t\t\t\t\t}\n\t\t\t\t\trsrcList.add(prop);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (superElementType.equals(OntConceptType.ANNOTATION_PROPERTY)) {\n\t\t\t\tfor (int i = 0; i < newNames.size(); i++) {\n\t\t\t\t\tAnnotationProperty prop = createAnnotationProperty(newNames.get(i), superSRUri);\n\t\t\t\t\tif (nmanns != null && nmanns.get(newNames.get(i)) != null) {\n\t\t\t\t\t\taddAnnotationsToResource(prop, nmanns.get(newNames.get(i)));\n\t\t\t\t\t}\n\t\t\t\t\trsrcList.add(prop);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (superElementType.equals(OntConceptType.RDF_PROPERTY)) {\n\t\t\t\tfor (int i = 0; i < newNames.size(); i++) {\n\t\t\t\t\tOntProperty prop = createRdfProperty(newNames.get(i), superSRUri);\n\t\t\t\t\tif (nmanns != null && nmanns.get(newNames.get(i)) != null) {\n\t\t\t\t\t\taddAnnotationsToResource(prop, nmanns.get(newNames.get(i)));\n\t\t\t\t\t}\n\t\t\t\t\trsrcList.add(prop);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t//\t\t\t\tb) a SadlPrimitiveDataType\n\t\telse if (superElement instanceof SadlPrimitiveDataType) {\n\t\t\tif (isList) {\n\t\t\t\tcom.hp.hpl.jena.rdf.model.Resource spdt = getSadlPrimitiveDataTypeResource((SadlPrimitiveDataType) superElement);\n\t\t\t\trsrcList.add(getOrCreateListSubclass(newNames.get(0), spdt.getURI(), superElement.eResource()));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcom.hp.hpl.jena.rdf.model.Resource spdt = processSadlPrimitiveDataType(element, (SadlPrimitiveDataType) superElement, newNames.get(0));\n\t\t\t\tif (spdt instanceof OntClass) {\n\t\t\t\t\trsrcList.add((OntClass)spdt);\n\t\t\t\t}\n\t\t\t\telse if (spdt.canAs(OntResource.class)){\n\t\t\t\t\trsrcList.add(spdt.as(OntResource.class));\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrow new JenaProcessorException(\"Expected OntResource to be returned\"); // .add(spdt);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t//\t\t\t\tc) a SadlPropertyCondition\n\t\telse if (superElement instanceof SadlPropertyCondition) {\n\t\t\tOntClass propCond = processSadlPropertyCondition((SadlPropertyCondition) superElement);\n\t\t\trsrcList.add(propCond);\n\t\t}\n\t\t//\t\t\t\td) a SadlTypeReference\n\t\telse if (superElement instanceof SadlTypeReference) {\n\t\t\t// this can only be a class; can't create a property as a SadlTypeReference\n\t\t\tObject superClsObj = sadlTypeReferenceToObject(superElement);\n\t\t\tif (superClsObj instanceof List) {\n\t\t\t\t// must be a union of xsd datatypes; create RDFDatatype\n\t\t\t\tOntClass unionCls = createRdfsDatatype(newNames.get(0), (List)superClsObj, null, null);\n\t\t\t\trsrcList.add(unionCls);\n\t\t\t}\n\t\t\telse if (superClsObj instanceof OntResource) {\n\t\t\t\tOntResource superCls = (OntResource)superClsObj;\n\t\t\t\tif (superCls != null) {\n\t\t\t\t\tif (superCls instanceof UnionClass) {\n\t\t\t\t\t\tExtendedIterator itr = ((UnionClass)superCls).listOperands();\n\t\t\t\t\t\twhile (itr.hasNext()) {\n\t\t\t\t\t\t\tcom.hp.hpl.jena.rdf.model.Resource cls = itr.next();\n//\t\t\t\t\t\t\tSystem.out.println(\"Union member: \" + cls.toString());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (superCls instanceof IntersectionClass) {\n\t\t\t\t\t\tExtendedIterator itr = ((IntersectionClass)superCls).listOperands();\n\t\t\t\t\t\twhile (itr.hasNext()) {\n\t\t\t\t\t\t\tcom.hp.hpl.jena.rdf.model.Resource cls = itr.next();\n//\t\t\t\t\t\t\tSystem.out.println(\"Intersection member: \" + cls.toString());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\trsrcList.add(createOntClass(newNames.get(0), superCls.as(OntClass.class)));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tEList restrictions = element.getRestrictions();\n\t\tif (restrictions != null) {\n\t\t\tIterator ritr = restrictions.iterator();\n\t\t\twhile (ritr.hasNext()) {\n\t\t\t\tSadlPropertyRestriction rest = ritr.next();\n\t\t\t\tif (rest instanceof SadlMustBeOneOf) {\n\t\t\t\t\t//\n\t\t\t\t\tEList instances = ((SadlMustBeOneOf)rest).getValues();\n\t\t\t\t\tif (instances != null) {\n\t\t\t\t\t\tIterator iitr = instances.iterator();\n\t\t\t\t\t\tList individuals = new ArrayList();\n\t\t\t\t\t\twhile (iitr.hasNext()) {\n\t\t\t\t\t\t\tSadlExplicitValue inst = iitr.next();\n\t\t\t\t\t\t\tif (inst instanceof SadlResource) {\n\t\t\t\t\t\t\t\tfor (int i = 0; i < rsrcList.size(); i++) {\n\t\t\t\t\t\t\t\t\tindividuals.add(createIndividual((SadlResource)inst, rsrcList.get(i).asClass()));\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tthrow new JenaProcessorException(\"Unhandled type of SadlExplicitValue: \" + inst.getClass().getCanonicalName());\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// create equivalent class\n\t\t\t\t\t\tRDFList collection = getTheJenaModel().createList();\n\t\t\t\t\t\tIterator iter = individuals.iterator();\n\t\t\t\t\t\twhile (iter.hasNext()) {\n\t\t\t\t\t\t\tRDFNode dt = iter.next();\n\t\t\t\t\t\t\tcollection = collection.with(dt);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tEnumeratedClass enumcls = getTheJenaModel().createEnumeratedClass(null, collection);\n\t\t\t\t\t\tOntResource cls = rsrcList.get(0);\n\t\t\t\t\t\tif (cls.canAs(OntClass.class)){\n\t\t\t\t\t\t\tcls.as(OntClass.class).addEquivalentClass(enumcls);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (rest instanceof SadlCanOnlyBeOneOf) {\n\t\t\t\t\tEList instances = ((SadlCanOnlyBeOneOf)rest).getValues();\n\t\t\t\t\tif (instances != null) {\n\t\t\t\t\t\tIterator iitr = instances.iterator();\n\t\t\t\t\t\tList individuals = new ArrayList();\n\t\t\t\t\t\twhile (iitr.hasNext()) {\n\t\t\t\t\t\t\tSadlExplicitValue inst = iitr.next();\n\t\t\t\t\t\t\tif (inst instanceof SadlResource) {\n\t\t\t\t\t\t\t\tfor (int i = 0; i < rsrcList.size(); i++) {\n\t\t\t\t\t\t\t\t\tindividuals.add(createIndividual((SadlResource)inst, rsrcList.get(i).asClass()));\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tthrow new JenaProcessorException(\"Unhandled type of SadlExplicitValue: \" + inst.getClass().getCanonicalName());\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// create equivalent class\n\t\t\t\t\t\tRDFList collection = getTheJenaModel().createList();\n\t\t\t\t\t\tIterator iter = individuals.iterator();\n\t\t\t\t\t\twhile (iter.hasNext()) {\n\t\t\t\t\t\t\tRDFNode dt = iter.next();\n\t\t\t\t\t\t\tcollection = collection.with(dt);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tEnumeratedClass enumcls = getTheJenaModel().createEnumeratedClass(null, collection);\n\t\t\t\t\t\tOntResource cls = rsrcList.get(0);\n\t\t\t\t\t\tif (cls.canAs(OntClass.class)){\n\t\t\t\t\t\t\tcls.as(OntClass.class).addEquivalentClass(enumcls);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (int i = 0; i < rsrcList.size(); i++) {\n\t\t\tIterator dbiter = element.getDescribedBy().iterator();\n\t\t\twhile (dbiter.hasNext()) {\n\t\t\t\tSadlProperty sp = dbiter.next();\n\t\t\t\t// if this is an assignment of a range to a property the property will be returned (prop) for domain assignment,\n\t\t\t\t// but if it is a condition to be added as property restriction null will be returned\n\t\t\t\tProperty prop = processSadlProperty(rsrcList.get(i), sp);\n\t\t\t\tif (prop != null) {\n\t\t\t\t\taddPropertyDomain(prop, rsrcList.get(i), sp); //.eContainer());\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t\tif (isList) {\n\t\t\taddLengthRestrictionsToList(rsrcList.get(0), element.getFacet());\n\n\t\t}\n\t\treturn rsrcList;\n\t}\n\n\tprivate Property processSadlProperty(OntResource subject, SadlProperty element) throws JenaProcessorException {\n\t\tProperty retProp = null;\n\t\t// this has multiple forms:\n\t\t//\t1) is a property...\n\t\t//\t2) relationship of to is \n\t\t// 3) describes with \t(1st spr is a SadlTypeAssociation, the domain; 2nd spr is a SadlRangeRestriction, the range)\n\t\t// 4) of \t(1st spr is a SadlTypeAssociation, the class being restricted; 2nd spr is a SadlCondition\n\t\t// 5) of can only be one of { or } (1st spr is SadlTypeAssociation, 2nd spr is a SadlCanOnlyBeOneOf)\n\t\t// 6) of must be one of { or } (1st spr is SadlTypeAssociation, 2nd spr is a SadlCanOnlyBeOneOf)\n\t\tSadlResource sr = sadlResourceFromSadlProperty(element);\n\t\tString propUri = getDeclarationExtensions().getConceptUri(sr);\n\t\tOntConceptType propType;\n\t\ttry {\n\t\t\tpropType = getDeclarationExtensions().getOntConceptType(sr);\n\t\t\tif (!isProperty(propType)) {\n\t\t\t\taddError(SadlErrorMessages.INVALID_USE_OF_CLASS_AS_PROPERTY.get(getDeclarationExtensions().getConcreteName(sr)),element);\n\t\t\t}\n\t\t} catch (CircularDefinitionException e) {\n\t\t\tpropType = e.getDefinitionType();\n\t\t\taddError(e.getMessage(), element);\n\t\t}\n\t\t\n\t\t\n\t\tIterator spitr = element.getRestrictions().iterator();\n\t\tif (spitr.hasNext()) {\n\t\t\tSadlPropertyRestriction spr1 = spitr.next();\n\t\t\tif (spr1 instanceof SadlIsAnnotation) {\n\t\t\t\tretProp = getTheJenaModel().createAnnotationProperty(propUri);\n\t\t\t}\n\t\t\telse if (spr1 instanceof SadlIsTransitive) {\n\t\t\t\tOntProperty pr;\n\t\t\t\tif (propType.equals(OntConceptType.CLASS_PROPERTY)) {\n\t\t\t\t\tpr = getOrCreateObjectProperty(propUri);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrow new JenaProcessorException(\"Only object properties can be transitive\");\n\t\t\t\t}\n\t\t\t\tif (pr == null) {\n\t\t\t\t\tthrow new JenaProcessorException(\"Property '\" + propUri + \"' not found in ontology.\");\n\t\t\t\t}\n\t\t\t\tpr.convertToTransitiveProperty();\n\t\t\t\tretProp = getTheJenaModel().createTransitiveProperty(pr.getURI());\n\t\t\t}\n\t\t\telse if (spr1 instanceof SadlIsInverseOf) {\n\t\t\t\tOntProperty pr;\n\t\t\t\tif (propType.equals(OntConceptType.CLASS_PROPERTY)) {\n\t\t\t\t\tpr = getOrCreateObjectProperty(propUri);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrow new JenaProcessorException(\"Only object properties can have inverses\");\n\t\t\t\t}\n\t\t\t\tif (pr == null) {\n\t\t\t\t\tthrow new JenaProcessorException(\"Property '\" + propUri + \"' not found in ontology.\");\n\t\t\t\t}\n\t\t\t\tSadlResource otherProp = ((SadlIsInverseOf)spr1).getOtherProperty();\n\t\t\t\tString otherPropUri = getDeclarationExtensions().getConceptUri(otherProp);\n\t\t\t\tOntConceptType optype;\n\t\t\t\ttry {\n\t\t\t\t\toptype = getDeclarationExtensions().getOntConceptType(otherProp);\n\t\t\t\t} catch (CircularDefinitionException e) {\n\t\t\t\t\toptype = e.getDefinitionType();\n\t\t\t\t\taddError(e.getMessage(), element);\n\t\t\t\t}\n\t\t\t\tif (!optype.equals(OntConceptType.CLASS_PROPERTY)) {\n\t\t\t\t\tthrow new JenaProcessorException(\"Only object properties can have inverses\");\n\t\t\t\t}\n\t\t\t\tOntProperty opr = getOrCreateObjectProperty(otherPropUri);\n\t\t\t\tif (opr == null) {\n\t\t\t\t\tthrow new JenaProcessorException(\"Property '\" + otherPropUri + \"' not found in ontology.\");\n\t\t\t\t}\n\t\t\t\tpr.addInverseOf(opr);\n\t\t\t}\n\t\t\telse if (spr1 instanceof SadlRangeRestriction) {\n\t\t\t\tSadlTypeReference rng = ((SadlRangeRestriction)spr1).getRange();\n\t\t\t\tif (rng != null) {\n\t\t\t\t\tRangeValueType rngValueType = RangeValueType.CLASS_OR_DT;\t// default\n\t\t\t\t\tboolean isList = typeRefIsList(rng);\n\t\t\t\t\tif (isList) {\n\t\t\t\t\t\trngValueType = RangeValueType.LIST;\n\t\t\t\t\t}\n\t\t\t\t\tOntProperty prop;\n\t\t\t\t\tString rngName;\n\t\t\t\t\tif (!isList && rng instanceof SadlPrimitiveDataType) {\n\t\t\t\t\t\trngName = ((SadlPrimitiveDataType)rng).getPrimitiveType().getName();\n\t\t\t\t\t\tRDFNode rngNode = primitiveDatatypeToRDFNode(rngName);\n\t\t\t\t\t\tif (!checkForExistingCompatibleDatatypeProperty(propUri, rngNode)) {\n\t\t\t\t\t\t\tprop = createDatatypeProperty(propUri, null);\n\t\t\t\t\t\t\taddPropertyRange(propType, prop, rngNode, rngValueType, rng);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tprop = getTheJenaModel().getDatatypeProperty(propUri);\n\t\t\t\t\t\t\taddPropertyRange(propType, prop, rngNode, rngValueType, rng);\n\t\t\t\t\t\t}\n\t\t\t\t\t\taddPropertyRange(propType, prop, rngNode, rngValueType, rng);\n\t\t\t\t\t\tretProp = prop;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\trngName = sadlSimpleTypeReferenceToConceptName(rng).toFQString();\n\t\t\t\t\t\tOntResource rngRsrc;\n\t\t\t\t\t\tif (isList) {\n\t\t\t\t\t\t\trngRsrc = getOrCreateListSubclass(null, rngName, element.eResource());\n\t\t\t\t\t\t\taddLengthRestrictionsToList(rngRsrc, ((SadlRangeRestriction)spr1).getFacet());\n\t\t\t\t\t\t\tpropType = OntConceptType.CLASS_PROPERTY;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\trngRsrc = sadlTypeReferenceToOntResource(rng);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tretProp = assignRangeToProperty(propUri, propType, rngRsrc, rngValueType, rng);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (((SadlRangeRestriction)spr1).isSingleValued()) {\n\t\t\t\t\t// add cardinality restriction\n\t\t\t\t\taddCardinalityRestriction(subject, retProp, 1);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (spr1 instanceof SadlCondition) {\n\t\t\t\tOntProperty prop = getTheJenaModel().getOntProperty(propUri);\n\t\t\t\tif (prop == null) {\n\t\t\t\t\tprop = getOrCreateRdfProperty(propUri);\n\t\t\t\t}\n\t\t\t\tOntClass condCls = sadlConditionToOntClass((SadlCondition) spr1, prop, propType);\n\t\t\t\tOntClass cls = null;\n\t\t\t\tif (subject != null) {\n\t\t\t\t\tif (subject.canAs(OntClass.class)){\n\t\t\t\t\t\tcls = subject.as(OntClass.class);\n\t\t\t\t\t\tcls.addSuperClass(condCls);\n\t\t\t\t\t\tretProp = null;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tthrow new JenaProcessorException(\"Unable to convert concept being restricted (\" + subject.toString() + \") to an OntClass.\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// I think this is OK... AWC 3/13/2017\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (spitr.hasNext()) {\n\t\t\t\tSadlPropertyRestriction spr2 = spitr.next();\n\t\t\t\tif (spitr.hasNext()) {\n\t\t\t\t\tStringBuilder sb = new StringBuilder();\n\t\t\t\t\tint cntr = 0;\n\t\t\t\t\twhile (spitr.hasNext()) {\n\t\t\t\t\t\tif (cntr++ > 0) sb.append(\", \");\n\t\t\t\t\t\tsb.append(spitr.next().getClass().getCanonicalName());\n\t\t\t\t\t}\n\t\t\t\t\tthrow new JenaProcessorException(\"Unexpected SadlProperty has more than 2 restrictions: \" + sb.toString());\n\t\t\t\t}\n\t\t\t\tif (spr1 instanceof SadlTypeAssociation && spr2 instanceof SadlRangeRestriction) {\n\t\t\t\t\t// this is case 3\n\t\t\t\t\tSadlTypeReference domain = ((SadlTypeAssociation)spr1).getDomain();\n\t\t\t\t\tOntConceptType domaintype;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tdomaintype = sadlTypeReferenceOntConceptType(domain);\n\t\t\t\t\t\tif (domaintype != null && domaintype.equals(OntConceptType.DATATYPE)) {\n\t\t\t\t\t\t\taddWarning(SadlErrorMessages.DATATYPE_AS_DOMAIN.get() , domain);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (CircularDefinitionException e) {\n\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t\tOntResource domainrsrc = sadlTypeReferenceToOntResource(domain);\n\n\t\t\t\t\t// before creating the property, determine if the range is a sadllistmodel:List as if it is the property type is actually an owl:ObjectProperty\n\t\t\t\t\tRangeValueType rngValueType = RangeValueType.CLASS_OR_DT;\t// default\n\t\t\t\t\tSadlTypeReference rng = ((SadlRangeRestriction)spr2).getRange();\n\t\t\t\t\tif (rng instanceof SadlPrimitiveDataType) {\n\t\t\t\t\t\tif (((SadlPrimitiveDataType)rng).isList()) {\n\t\t\t\t\t\t\trngValueType = RangeValueType.LIST;\n\t\t\t\t\t\t\tpropType = OntConceptType.DATATYPE_LIST;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (rng instanceof SadlSimpleTypeReference) {\n\t\t\t\t\t\tif (((SadlSimpleTypeReference)rng).isList()) {\n\t\t\t\t\t\t\trngValueType = RangeValueType.LIST;\n\t\t\t\t\t\t\tpropType = OntConceptType.CLASS_LIST;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tOntProperty prop;\n\t\t\t\t\tif (propType.equals(OntConceptType.CLASS_PROPERTY) || rngValueType.equals(RangeValueType.LIST)) {\n\t\t\t\t\t\tprop = getOrCreateObjectProperty(propUri);\n\t\t\t\t\t}\n\t\t\t\t\telse if (propType.equals(OntConceptType.DATATYPE_PROPERTY)){\n\t\t\t\t\t\tprop = getOrCreateDatatypeProperty(propUri);\n\t\t\t\t\t}\n\t\t\t\t\telse if (propType.equals(OntConceptType.RDF_PROPERTY)) {\n\t\t\t\t\t\tprop = getOrCreateRdfProperty(propUri);\n\t\t\t\t\t}\n\t\t\t\t\telse if (propType.equals(OntConceptType.ANNOTATION_PROPERTY)) {\n\t\t\t\t\t\taddError(\"Can't specify domain of an annotation property. Did you want to use a property restriction?\", sr);\n\t\t\t\t\t\tthrow new JenaProcessorException(\"Invalid property type (\" + propType.toString() + \") for '\" + propUri + \"'\");\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tthrow new JenaProcessorException(\"Invalid property type (\" + propType.toString() + \") for '\" + propUri + \"'\");\n\t\t\t\t\t}\n\t\t\t\t\taddPropertyDomain(prop, domainrsrc, domain);\n\t\t\t\t\tSadlTypeReference from = element.getFrom();\n\t\t\t\t\tif (from != null) {\n\t\t\t\t\t\tOntResource fromrsrc = sadlTypeReferenceToOntResource(from);\n\t\t\t\t\t\tthrow new JenaProcessorException(\"What is 'from'?\");\n\t\t\t\t\t}\n\t\t\t\t\tSadlTypeReference to = element.getTo();\n\t\t\t\t\tif (to != null) {\n\t\t\t\t\t\tOntResource torsrc = sadlTypeReferenceToOntResource(to);\n\t\t\t\t\t\tthrow new JenaProcessorException(\"What is 'to'?\");\n\t\t\t\t\t}\n\t\t\t\t\t\n//\t\t\t\t\tRangeValueType rngValueType = RangeValueType.CLASS_OR_DT;\t// default\n//\t\t\t\t\tSadlTypeReference rng = ((SadlRangeRestriction)spr2).getRange();\n\t\t\t\t\tif (rng instanceof SadlPrimitiveDataType && !rngValueType.equals(RangeValueType.LIST)) {\n\t\t\t\t\t\tString rngName = ((SadlPrimitiveDataType)rng).getPrimitiveType().getName();\n\t\t\t\t\t\tRDFNode rngNode = primitiveDatatypeToRDFNode(rngName);\n\t\t\t\t\t\tDatatypeProperty prop2 = null;\n\t\t\t\t\t\tif (!checkForExistingCompatibleDatatypeProperty(propUri, rngNode)) {\n\t\t\t\t\t\t\t//TODO should this ever happen? spr1 should have created the property?\n\t\t\t\t\t\t\tprop2 = createDatatypeProperty(propUri, null);\n\t\t\t\t\t\t\taddPropertyRange(propType, prop, rngNode, rngValueType, rng);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tprop2 = getTheJenaModel().getDatatypeProperty(propUri);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tretProp = prop2;\n\t\t\t\t\t}\n\t\t\t\t\telse if (((SadlRangeRestriction)spr2).getTypeonly() == null) {\t\t\t\t\n\t\t\t\t\t\tOntResource rngRsrc = sadlTypeReferenceToOntResource(rng);\n\t\t\t\t\t\tif ((rng instanceof SadlSimpleTypeReference && ((SadlSimpleTypeReference)rng).isList()) || \n\t\t\t\t\t\t\t\t(rng instanceof SadlPrimitiveDataType && ((SadlPrimitiveDataType)rng).isList())) {\n\t\t\t\t\t\t\taddLengthRestrictionsToList(rngRsrc, ((SadlRangeRestriction)spr2).getFacet());\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (rngRsrc == null) {\n\t\t\t\t\t\t\taddError(SadlErrorMessages.RANGE_RESOLVE.toString(), rng);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tretProp = assignRangeToProperty(propUri, propType, rngRsrc, rngValueType, rng);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tretProp = prop;\n\t\t\t\t\t}\n\t\t\t\t\tif (((SadlRangeRestriction)spr2).isSingleValued()) {\n\t\t\t\t\t\taddCardinalityRestriction(domainrsrc, retProp, 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (spr1 instanceof SadlTypeAssociation && spr2 instanceof SadlCondition) {\n\t\t\t\t\t// this is case 4\n\t\t\t\t\tSadlTypeReference domain = ((SadlTypeAssociation)spr1).getDomain();\n\t\t\t\t\tOntResource domainrsrc = sadlTypeReferenceToOntResource(domain);\n\t\t\t\t\tif (domainrsrc == null) {\n\t\t\t\t\t\taddError(SadlErrorMessages.UNABLE_TO_FIND.get(\"domain\"), domain);\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t}\n\t\t\t\t\telse if (domainrsrc.canAs(OntClass.class)){ \n\t\t\t\t\t\tOntClass cls = domainrsrc.as(OntClass.class);\n\t\t\t\t\t\tProperty prop = getTheJenaModel().getProperty(propUri);\n\t\t\t\t\t\tif (prop != null) {\n\t\t\t\t\t\t\tOntClass condCls = sadlConditionToOntClass((SadlCondition) spr2, prop, propType);\n\t\t\t\t\t\t\tif (condCls != null) {\n\t\t\t\t\t\t\t\tcls.addSuperClass(condCls);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\taddError(SadlErrorMessages.UNABLE_TO_ADD.get(\"restriction\",\"unable to create condition class\"), domain);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tretProp = prop;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tthrow new JenaProcessorException(\"Unable to convert property '\" + propUri + \"' to OntProperty.\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tthrow new JenaProcessorException(\"Unable to convert concept being restricted (\" + domainrsrc.toString() + \") to an OntClass.\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (spr1 instanceof SadlTypeAssociation && spr2 instanceof SadlCanOnlyBeOneOf) {\n\t\t\t\t\tSadlTypeReference domain = ((SadlTypeAssociation)spr1).getDomain();\n\t\t\t\t\tOntResource domainrsrc = sadlTypeReferenceToOntResource(domain);\n\t\t\t\t\tif (domainrsrc == null) {\n\t\t\t\t\t\taddError(SadlErrorMessages.UNABLE_TO_FIND.get(\"domain\"), domain);\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t}\n\t\t\t\t\telse if (domainrsrc.canAs(OntClass.class)){ \n\t\t\t\t\t\tOntClass cls = domainrsrc.as(OntClass.class);\n\t\t\t\t\t\tProperty prop = getTheJenaModel().getProperty(propUri);\n\t\t\t\t\t\tif (prop != null) {\n\t\t\t\t\t\t\tEList values = ((SadlCanOnlyBeOneOf)spr2).getValues();\n\t\t\t\t\t\t\tif (values != null) {\n\t\t\t\t\t\t\t\tEnumeratedClass enumCls = sadlExplicitValuesToEnumeratedClass(values);\n\t\t\t\t\t\t\t\tAllValuesFromRestriction avf = getTheJenaModel()\n\t\t\t\t\t\t\t\t\t\t.createAllValuesFromRestriction(null,\n\t\t\t\t\t\t\t\t\t\t\t\tprop, enumCls);\n\t\t\t\t\t\t\t\tif (avf != null) {\n\t\t\t\t\t\t\t\t\tcls.addSuperClass(avf);\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\taddError(SadlErrorMessages.UNABLE_TO_CREATE.get(\"AllValuesFromRestriction\", \"Unknown reason\"), spr2);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\taddError(SadlErrorMessages.UNABLE_TO_ADD.get(\"all values from restriction\", \"unable to create oneOf class\"), domain);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tretProp = prop;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tthrow new JenaProcessorException(\"Unable to convert property '\" + propUri + \"' to OntProperty.\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (spr1 instanceof SadlTypeAssociation && spr2 instanceof SadlMustBeOneOf) {\n\t\t\t\t\tSadlTypeReference domain = ((SadlTypeAssociation)spr1).getDomain();\n\t\t\t\t\tOntResource domainrsrc = sadlTypeReferenceToOntResource(domain);\n\t\t\t\t\tif (domainrsrc == null) {\n\t\t\t\t\t\taddError(SadlErrorMessages.UNABLE_TO_FIND.get(\"domain\"), domain);\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t}\n\t\t\t\t\telse if (domainrsrc.canAs(OntClass.class)){ \n\t\t\t\t\t\tOntClass cls = domainrsrc.as(OntClass.class);\n\t\t\t\t\t\tProperty prop = getTheJenaModel().getProperty(propUri);\n\t\t\t\t\t\tif (prop != null) {\n\t\t\t\t\t\t\tEList values = ((SadlMustBeOneOf)spr2).getValues();\n\t\t\t\t\t\t\tif (values != null) {\n\t\t\t\t\t\t\t\tEnumeratedClass enumCls = sadlExplicitValuesToEnumeratedClass(values);\n\t\t\t\t\t\t\t\tSomeValuesFromRestriction svf = getTheJenaModel()\n\t\t\t\t\t\t\t\t\t\t.createSomeValuesFromRestriction(null,\n\t\t\t\t\t\t\t\t\t\t\t\tprop, enumCls);\n\t\t\t\t\t\t\t\tif (svf != null) {\n\t\t\t\t\t\t\t\t\tcls.addSuperClass(svf);\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\taddError(SadlErrorMessages.UNABLE_TO_CREATE.get(\"SomeValuesFromRestriction\", \"Unknown reason\"), spr2);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\taddError(SadlErrorMessages.UNABLE_TO_ADD.get(\"some values from restriction\", \"unable to create oneOf class\"), domain);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tretProp = prop;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tthrow new JenaProcessorException(\"Unable to convert property '\" + propUri + \"' to OntProperty.\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\telse if (spr1 instanceof SadlTypeAssociation && spr2 instanceof SadlDefaultValue) {\n\t\t\t\t\tSadlExplicitValue dv = ((SadlDefaultValue)spr2).getDefValue();\n\t\t\t\t\tint lvl = ((SadlDefaultValue)spr2).getLevel();\n\t\t\t\t\tSadlTypeReference domain = ((SadlTypeAssociation)spr1).getDomain();\n\t\t\t\t\tOntResource domainrsrc = sadlTypeReferenceToOntResource(domain);\n\t\t\t\t\tif (domainrsrc == null) {\n\t\t\t\t\t\taddError(SadlErrorMessages.UNABLE_TO_FIND.get(\"domain\"), domain);\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t}\n\t\t\t\t\telse if (domainrsrc.canAs(OntClass.class)){ \n\t\t\t\t\t\tOntClass cls = domainrsrc.as(OntClass.class);\n\t\t\t\t\t\tProperty prop = getTheJenaModel().getProperty(propUri);\n\t\t\t\t\t\tif (prop != null) {\n\t\t\t\t\t\t\tif (sadlDefaultsModel == null) {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\timportSadlDefaultsModel(element.eResource());\n\t\t\t\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t\t\t\t\tthrow new JenaProcessorException(\"Failed to load SADL Defaults model\", e);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tRDFNode defVal = sadlExplicitValueToRdfNode(dv, prop, true);\n\t\t\t\t\t\t\tIndividual seeAlsoDefault = null;\n\t\t\t\t\t\t\tif (propType.equals(OntConceptType.CLASS_PROPERTY) || (propType.equals(OntConceptType.RDF_PROPERTY) && defVal.isResource())) {\n\t\t\t\t\t\t\t\tif (!(defVal.isURIResource()) || !defVal.canAs(Individual.class)) {\n\t\t\t\t\t\t\t\t\taddError(\"Error creating default for property '\" + propUri + \"' for class '\" + cls.getURI() + \"' with value '\" + defVal.toString()\n\t\t\t\t\t\t\t\t\t\t\t+ \"': the value is not a named concept.\", spr2);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\tIndividual defInst = defVal.as(Individual.class);\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\tseeAlsoDefault = createDefault(cls, prop, defInst, lvl, element);\n\t\t\t\t\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\t\t\t\t\taddError(\"Error creating default for property '\" + propUri + \"' for class '\" + cls.getURI() + \"' with value '\" + defVal.toString()\n\t\t\t\t\t\t\t\t\t\t\t\t+ \"': \" + e.getMessage(), spr2);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tif (propType.equals(OntConceptType.DATATYPE_PROPERTY) && !defVal.isLiteral()) {\n\t\t\t\t\t\t\t\t\taddError(\"Error creating default for property '\" + propUri + \"' for class '\" + cls.getURI() + \"' with value '\" + defVal.toString()\n\t\t\t\t\t\t\t\t\t\t\t+ \"': the value is a named concept but should be a data value.\", spr2);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\tseeAlsoDefault = createDefault(cls, prop, defVal.asLiteral(), lvl, spr2);\n\t\t\t\t\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\t\t\t\t\taddError(\"Error creating default for property '\" + propUri + \"' for class '\" + cls.getURI() + \"' with value '\" + defVal.toString()\n\t\t\t\t\t\t\t\t\t\t\t\t+ \"': \" + e.getMessage(), spr2);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (seeAlsoDefault != null) {\n\t\t\t\t\t\t\t\tcls.addSeeAlso(seeAlsoDefault);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\taddError(\"Unable to create default for '\" + cls.getURI() + \"', '\"\n\t\t\t\t\t\t\t\t\t\t+ propUri + \"', '\" + defVal + \"'\", element);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrow new JenaProcessorException(\"Unhandled restriction: spr1 is '\" + spr1.getClass().getName() + \"', spr2 is '\" + spr2.getClass().getName() + \"'\");\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (spr1 instanceof SadlTypeAssociation) {\n\t\t\t\t// this is case 3 but with range not present\n\t\t\t\tSadlTypeReference domain = ((SadlTypeAssociation)spr1).getDomain();\n\t\t\t\tOntResource domainrsrc = sadlTypeReferenceToOntResource(domain);\n\t\t\t\tObjectProperty prop = getOrCreateObjectProperty(propUri);\n\t\t\t\tif (domainrsrc != null) {\n\t\t\t\t\taddPropertyDomain(prop, domainrsrc, domain);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (spr1 instanceof SadlIsSymmetrical) {\n\t\t\t\tObjectProperty prop = getOrCreateObjectProperty(propUri);\n\t\t\t\tif (prop != null) {\n\t\t\t\t\tif (!prop.isObjectProperty()) {\n\t\t\t\t\t\taddError(SadlErrorMessages.OBJECT_PROP_SYMMETRY.toString(), spr1);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tgetTheJenaModel().add(prop,RDF.type,OWL.SymmetricProperty);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthrow new JenaProcessorException(\"Unhandled SadlProperty expression\");\n\t\t\t}\n\t\t\t\n\t\t\twhile (spitr.hasNext()) {\n\t\t\t\tSadlPropertyRestriction spr = spitr.next();\n\t\t\t\tif (spr instanceof SadlRangeRestriction) {\n\t\t\t\t\tRangeValueType rngValueType = RangeValueType.CLASS_OR_DT;\t// default\n\t\t\t\t\tSadlTypeReference rng = ((SadlRangeRestriction)spr).getRange();\n\t\t\t\t\tif (rng instanceof SadlPrimitiveDataType) {\n\t\t\t\t\t\tString rngName = ((SadlPrimitiveDataType)rng).getPrimitiveType().getName();\n\t\t\t\t\t\tRDFNode rngNode = primitiveDatatypeToRDFNode(rngName);\n\t\t\t\t\t\tDatatypeProperty prop = null;\n\t\t\t\t\t\tif (!checkForExistingCompatibleDatatypeProperty(propUri, rngNode)) {\n\t\t\t\t\t\t\tprop = createDatatypeProperty(propUri, null);\n\t\t\t\t\t\t\taddPropertyRange(propType, prop, rngNode, rngValueType, rng);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tprop = getTheJenaModel().getDatatypeProperty(propUri);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tretProp = prop;\n\t\t\t\t\t}\n\t\t\t\t\telse {\t\t\t\t\n\t\t\t\t\t\tOntResource rngRsrc = sadlTypeReferenceToOntResource(rng);\n\t\t\t\t\t\tif (rngRsrc == null) {\n\t\t\t\t\t\t\tthrow new JenaProcessorException(\"Range failed to resolve to a class or datatype\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tretProp = assignRangeToProperty(propUri, propType, rngRsrc, rngValueType, rng);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (spr instanceof SadlCondition) {\n\t\t\t\t\tif (propType.equals(OntConceptType.CLASS_PROPERTY)) {\n\t\t\t\t\t\tObjectProperty prop = getOrCreateObjectProperty(propUri);\n\t\t\t\t\t\tOntClass condCls = sadlConditionToOntClass((SadlCondition) spr, prop, propType);\n\t\t\t\t\t\taddPropertyRange(propType, prop, condCls, RangeValueType.CLASS_OR_DT, spr);\t\t// use default?\n\t\t\t\t\t\t//TODO don't we need to add this class as superclass??\n\t\t\t\t\t\tretProp = prop;\n\t\t\t\t\t}\n\t\t\t\t\telse if (propType.equals(OntConceptType.DATATYPE_PROPERTY)) {\n\t\t\t\t\t\tObjectProperty prop = getOrCreateObjectProperty(propUri);\n\t\t\t\t\t\tOntClass condCls = sadlConditionToOntClass((SadlCondition) spr, prop, propType);\n\t\t\t\t\t\t//TODO don't we need to add this class as superclass??\n\t\t\t\t\t\tretProp = prop;\n\t//\t\t\t\t\tthrow new JenaProcessorException(\"SadlCondition on data type property not handled\");\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tthrow new JenaProcessorException(\"Invalid property type: \" + propType.toString());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (spr instanceof SadlTypeAssociation) {\n\t\t\t\t\tSadlTypeReference domain = ((SadlTypeAssociation)spr).getDomain();\n\t\t\t\t\tOntResource domainrsrc = sadlTypeReferenceToOntResource(domain);\n\t\t\t\t\tObjectProperty prop = getOrCreateObjectProperty(propUri);\n\t\t\t\t\tif (domainrsrc != null) {\n\t\t\t\t\t\taddPropertyDomain(prop, domainrsrc, domain);\n\t\t\t\t\t}\n\t\t\t\t\tSadlTypeReference from = element.getFrom();\n\t\t\t\t\tif (from != null) {\n\t\t\t\t\t\tOntResource fromrsrc = sadlTypeReferenceToOntResource(from);\n\t\t\t\t\t\tthrow new JenaProcessorException(\"What is 'from'?\");\n\t\t\t\t\t}\n\t\t\t\t\tSadlTypeReference to = element.getTo();\n\t\t\t\t\tif (to != null) {\n\t\t\t\t\t\tOntResource torsrc = sadlTypeReferenceToOntResource(to);\n\t\t\t\t\t\tthrow new JenaProcessorException(\"What is 'to'?\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (spr instanceof SadlIsAnnotation) {\n\t\t\t\t\tretProp = getTheJenaModel().createAnnotationProperty(propUri);\n\t\t\t\t}\n\t\t\t\telse if (spr instanceof SadlIsTransitive) {\n\t\t\t\t\tOntProperty pr = getOrCreateObjectProperty(propUri);\n\t\t\t\t\tpr.convertToTransitiveProperty();\n\t\t\t\t\tretProp = getTheJenaModel().createTransitiveProperty(pr.getURI());\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrow new JenaProcessorException(\"Unhandled SadlPropertyRestriction type: \" + spr.getClass().getCanonicalName());\n\t\t\t\t}\n\t\t\t} // end while\n\t\t}\n\t\telse if (element.getFrom() != null && element.getTo() != null) {\n\t\t\tSadlTypeReference fromTypeRef = element.getFrom();\n\t\t\tObject frm;\n\t\t\ttry {\n\t\t\t\tfrm = processExpression(fromTypeRef);\n\t\t\t\tSadlTypeReference toTypeRef = element.getTo();\n\t\t\t\tObject t = processExpression(toTypeRef);\n\t\t\t\tif (frm != null && t != null) {\n\t\t\t\t\tOntClass dmn;\n\t\t\t\t\tOntClass rng;\n\t\t\t\t\tif (frm instanceof OntClass) {\n\t\t\t\t\t\tdmn = (OntClass)frm;\n\t\t\t\t\t}\n\t\t\t\t\telse if (frm instanceof NamedNode) {\n\t\t\t\t\t\tdmn = getOrCreateOntClass(((NamedNode)frm).toFullyQualifiedString());\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tthrow new JenaTransactionException(\"Valid domain not identified: \" + frm.toString());\n\t\t\t\t\t}\n\t\t\t\t\tif (t instanceof OntClass) {\n\t\t\t\t\t\trng = (OntClass)t;\n\t\t\t\t\t} else if (t instanceof NamedNode) {\n\t\t\t\t\t\trng = getOrCreateOntClass(((NamedNode)t).toFullyQualifiedString());\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tthrow new JenaTransactionException(\"Valid range not identified: \" + t.toString());\n\t\t\t\t\t}\n\t\t\t\t\tOntProperty pr = createObjectProperty(propUri, null);\n\t\t\t\t\taddPropertyDomain(pr, dmn, toTypeRef);\n\t\t\t\t\taddPropertyRange(OntConceptType.CLASS_PROPERTY, pr, rng, RangeValueType.CLASS_OR_DT, element);\n\t\t\t\t\tretProp = pr;\n\t\t\t\t}\n\t\t\t\telse if (frm == null){\n\t\t\t\t\tthrow new JenaTransactionException(\"Valid domian not identified\");\n\t\t\t\t}\n\t\t\t\telse if (t == null) {\n\t\t\t\t\tthrow new JenaTransactionException(\"Valid range not identified\");\n\t\t\t\t}\n\t\t\t} catch (TranslationException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t// No restrictions--this will become an rdf:Property\n\t\t\tretProp = createRdfProperty(propUri, null);\n\t\t}\n\t\tif (sr != null && retProp != null && sr.getAnnotations() != null && retProp.canAs(OntResource.class)) {\n\t\t\taddAnnotationsToResource(retProp.as(OntResource.class), sr.getAnnotations());\n\t\t}\n\t\treturn retProp;\n\t}\n\t\n\tprivate void addLengthRestrictionsToList(OntResource rngRsrc, SadlDataTypeFacet facet) {\n\t\t// check for list length restrictions\n\t\tif (facet != null && rngRsrc.canAs(OntClass.class)) {\n\t\t\tif (facet.getLen() != null) {\n\t\t\t\tint len = Integer.parseInt(facet.getLen());\n\t\t\t\tHasValueRestriction hvr = getTheJenaModel().createHasValueRestriction(null,\n\t\t\t\t\t\tgetTheJenaModel().getProperty(SadlConstants.SADL_LIST_MODEL_LENGTH_RESTRICTION_URI),\n\t\t\t\t\t\tgetTheJenaModel().createTypedLiteral(len));\n\t\t\t\trngRsrc.as(OntClass.class).addSuperClass(hvr);\n\t\t\t}\n\t\t\tif (facet.getMinlen() != null) {\n\t\t\t\tint minlen = Integer.parseInt(facet.getMinlen());\n\t\t\t\tHasValueRestriction hvr = getTheJenaModel().createHasValueRestriction(null,\n\t\t\t\t\t\tgetTheJenaModel().getProperty(SadlConstants.SADL_LIST_MODEL_MINLENGTH_RESTRICTION_URI),\n\t\t\t\t\t\tgetTheJenaModel().createTypedLiteral(minlen));\n\t\t\t\trngRsrc.as(OntClass.class).addSuperClass(hvr);\n\t\t\t}\n\t\t\tif (facet.getMaxlen() != null && !facet.getMaxlen().equals(\"*\")) {\n\t\t\t\tint maxlen = Integer.parseInt(facet.getMaxlen());\n\t\t\t\tHasValueRestriction hvr = getTheJenaModel().createHasValueRestriction(null,\n\t\t\t\t\t\tgetTheJenaModel().getProperty(SadlConstants.SADL_LIST_MODEL_MAXLENGTH_RESTRICTION_URI),\n\t\t\t\t\t\tgetTheJenaModel().createTypedLiteral(maxlen));\n\t\t\t\trngRsrc.as(OntClass.class).addSuperClass(hvr);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprivate void addCardinalityRestriction(OntResource cls, Property retProp, int cardinality) {\n\t\tif (cls != null && cls.canAs(OntClass.class)) {\n\t\t\tCardinalityRestriction cr = getTheJenaModel().createCardinalityRestriction(null, retProp, cardinality);\n\t\t\tcls.as(OntClass.class).addSuperClass(cr);\n\t\t}\n\t}\n\t\n\tprivate String createUniqueDefaultValName(OntClass restricted,\n\t\t\tProperty prop) throws PrefixNotFoundException {\n\t\tString nmBase = restricted.getLocalName() + \"_\" + prop.getLocalName()\n\t\t\t\t+ \"_default\";\n\t\tString nm = getModelNamespace() + nmBase;\n\t\tint cntr = 0;\n\t\twhile (getTheJenaModel().getIndividual(nm) != null) {\n\t\t\tnm = nmBase + ++cntr;\n\t\t}\n\t\treturn nm;\n\t}\n\n\tprivate Individual createDefault(OntClass restricted, Property prop,\n\t\t\tRDFNode defValue, int level, EObject ref) throws Exception {\n\t\tif (defValue instanceof Individual) {\n\t\t\tOntClass instDefCls = getTheJenaModel().getOntClass(\n\t\t\t\t\tResourceManager.ACUITY_DEFAULTS_NS + \"ObjectDefault\");\n\t\t\tif (instDefCls == null) {\n\t\t\t\taddError(\"Unable to find ObjectDefault in Defaults model\", ref);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tIndividual def = getTheJenaModel().createIndividual(createUniqueDefaultValName(restricted, prop), instDefCls);\n\t\t\tdef.addProperty(\n\t\t\t\t\tgetTheJenaModel().getOntProperty(\n\t\t\t\t\t\t\tResourceManager.ACUITY_DEFAULTS_NS +\n\t\t\t\t\t\t\t\t\t\"appliesToProperty\"), prop);\n\t\t\tdef.addProperty(\n\t\t\t\t\tgetTheJenaModel().getOntProperty(ResourceManager.ACUITY_DEFAULTS_NS + \n\t\t\t\t\t\t\t\t\t\"hasObjectDefault\"), defValue);\n\t\t\tif (level > 0) {\n\t\t\t\tString hlpuri = ResourceManager.ACUITY_DEFAULTS_NS +\n\t\t\t\t\t\t\"hasLevel\";\n\t\t\t\tOntProperty hlp = getTheJenaModel().getOntProperty(hlpuri);\n\t\t\t\tif (hlp == null) {\n\t\t\t\t\taddError(\"Unable to find hasLevel property in Defaults model\", ref);\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\tLiteral defLvl = getTheJenaModel().createTypedLiteral(level);\n\t\t\t\tdef.addProperty(hlp, defLvl);\n\t\t\t}\n\t\t\treturn def;\n\t\t} else if (defValue instanceof Literal) {\n\t\t\tOntClass litDefCls = getTheJenaModel().getOntClass(\n\t\t\t\t\tResourceManager.ACUITY_DEFAULTS_NS + \"DataDefault\");\n\t\t\tif (litDefCls == null) {\n\t\t\t\taddError(\"Unable to find DataDefault in Defaults model\",ref);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tIndividual def = getTheJenaModel().createIndividual(\n\t\t\t\t\tmodelNamespace +\n\t\t\t\t\t\t\tcreateUniqueDefaultValName(restricted, prop),\n\t\t\t\t\tlitDefCls);\n\t\t\tdef.addProperty(\n\t\t\t\t\tgetTheJenaModel().getOntProperty(\n\t\t\t\t\t\t\tResourceManager.ACUITY_DEFAULTS_NS +\n\t\t\t\t\t\t\t\t\t\"appliesToProperty\"), prop);\n\t\t\tdef.addProperty(\n\t\t\t\t\tgetTheJenaModel().getOntProperty(\n\t\t\t\t\t\t\tResourceManager.ACUITY_DEFAULTS_NS +\n\t\t\t\t\t\t\t\t\t\"hasDataDefault\"), defValue);\n\t\t\tif (level > 0) {\n\t\t\t\tString hlpuri = ResourceManager.ACUITY_DEFAULTS_NS +\n\t\t\t\t\t\t\"hasLevel\";\n\t\t\t\tOntProperty hlp = getTheJenaModel().getOntProperty(hlpuri);\n\t\t\t\tif (hlp == null) {\n\t\t\t\t\taddError(\"Unable to find hasLevel in Defaults model\",ref);\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\tLiteral defLvl = getTheJenaModel().createTypedLiteral(level);\n\t\t\t\tdef.addProperty(hlp, defLvl);\n\t\t\t}\n\t\t\treturn def;\n\t\t}\n\t\treturn null;\n\t}\n\n\tprivate EnumeratedClass sadlExplicitValuesToEnumeratedClass(EList values)\n\t\t\tthrows JenaProcessorException {\n\t\tList nodevals = new ArrayList();\n\t\tfor (int i = 0; i < values.size(); i++) {\n\t\t\tSadlExplicitValue value = values.get(i);\n\t\t\tRDFNode nodeval = sadlExplicitValueToRdfNode(value, null, true);\n\t\t\tif (nodeval.canAs(Individual.class)){\n\t\t\t\tnodevals.add(nodeval.as(Individual.class));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tnodevals.add(nodeval);\n\t\t\t}\n\t\t}\n\t\tRDFNode[] enumedArray = nodevals\n\t\t\t\t.toArray(new RDFNode[nodevals.size()]);\n\t\tRDFList rdfl = getTheJenaModel().createList(enumedArray);\n\t\tEnumeratedClass enumCls = getTheJenaModel().createEnumeratedClass(null, rdfl);\n\t\treturn enumCls;\n\t}\n\t\n\tprivate RDFNode sadlExplicitValueToRdfNode(SadlExplicitValue value, Property prop, boolean literalsAllowed) throws JenaProcessorException {\n\t\tif (value instanceof SadlResource) {\n\t\t\tString uri = getDeclarationExtensions().getConceptUri((SadlResource) value);\n\t\t\tcom.hp.hpl.jena.rdf.model.Resource rsrc = getTheJenaModel().getResource(uri);\n\t\t\treturn rsrc;\n\t\t}\n\t\telse {\n\t\t\tLiteral litval = sadlExplicitValueToLiteral(value, prop);\n\t\t\treturn litval;\n\t\t}\n\t}\n\t\n\tprivate Property assignRangeToProperty(String propUri, OntConceptType propType, OntResource rngRsrc,\n\t\t\tRangeValueType rngValueType, SadlTypeReference rng) throws JenaProcessorException {\n\t\tProperty retProp;\n\t\tif (propType.equals(OntConceptType.CLASS_PROPERTY) || propType.equals(OntConceptType.CLASS_LIST) || propType.equals(OntConceptType.DATATYPE_LIST)) {\n\t\t\tOntClass rngCls = rngRsrc.asClass();\n\t\t\tObjectProperty prop = getOrCreateObjectProperty(propUri);\n\t\t\taddPropertyRange(propType, prop, rngCls, rngValueType, rng);\n\t\t\tretProp = prop;\n\t\t}\n\t\telse if (propType.equals(OntConceptType.DATATYPE_PROPERTY)) {\n\t\t\tDatatypeProperty prop = getOrCreateDatatypeProperty(propUri);\n\t\t\taddPropertyRange(propType, prop, rngRsrc, rngValueType, rng);\n\t\t\tretProp = prop;\n\t\t}\n\t\telse if (propType.equals(OntConceptType.RDF_PROPERTY)) {\n\t\t\tOntProperty prop = getOrCreateRdfProperty(propUri);\n\t\t\taddPropertyRange(propType, prop, rngRsrc, rngValueType, rng);\n//\t\t\tgetTheJenaModel().add(prop, RDFS.range, rngRsrc);\n\t\t\tretProp = prop;\n\t\t}\n\t\telse {\n\t\t\tthrow new JenaProcessorException(\"Property '\" + propUri + \"' of unexpected type '\" + rngRsrc.toString() + \"'\");\n\t\t}\n\t\treturn retProp;\n\t}\n\n\tprivate SadlResource sadlResourceFromSadlProperty(SadlProperty element) {\n\t\tSadlResource sr = element.getNameOrRef();\n\t\tif (sr == null) {\n\t\t\tsr = element.getProperty();\n\t\t}\n\t\tif (sr == null) {\n\t\t\tsr = element.getNameDeclarations().iterator().next();\n\t\t}\n\t\treturn sr;\n\t}\n\n\tprivate void addPropertyRange(OntConceptType propType, OntProperty prop, RDFNode rngNode, RangeValueType rngValueType, EObject context) throws JenaProcessorException {\n\t\tOntResource rngResource = null;\n\t\tif (rngNode instanceof OntClass){\n\t\t\trngResource = rngNode.as(OntClass.class);\n\t\t\tif (prop.isDatatypeProperty()) {\n\t\t\t\t// this happens when the range is a union of Lists of primitive types\n\t\t\t\tgetTheJenaModel().remove(prop,RDF.type, OWL.DatatypeProperty);\n\t\t\t\tgetTheJenaModel().add(prop, RDF.type, OWL.ObjectProperty);\n\t\t\t}\n\t\t}\n\t\t// If ignoring UnittedQuantity, change any UnittedQuantity range to the range of value and make the property an owl:DatatypeProperty\n\t\t// TODO this should probably work for any declared subclass of UnittedQuantity and associated value restriction?\n\t\tif (ignoreUnittedQuantities && rngResource != null && rngResource.isURIResource() && rngResource.canAs(OntClass.class) && \n\t\t\t\trngResource.getURI().equals(SadlConstants.SADL_IMPLICIT_MODEL_UNITTEDQUANTITY_URI)) {\n\t\t\tcom.hp.hpl.jena.rdf.model.Resource effectiveRng = getUnittedQuantityValueRange();\n\t\t\trngNode = effectiveRng;\n\t\t\trngResource = null;\n\t\t\tgetTheJenaModel().remove(prop,RDF.type, OWL.ObjectProperty);\n\t\t\tgetTheJenaModel().add(prop, RDF.type, OWL.DatatypeProperty);\n\t\t}\n\t\t\n\t\tRDFNode propOwlType = null;\n\t\tboolean rangeExists = false;\n\t\tboolean addNewRange = false;\n\t\tStmtIterator existingRngItr = getTheJenaModel().listStatements(prop, RDFS.range, (RDFNode)null);\n\t\tif (existingRngItr.hasNext()) {\n\t\t\tRDFNode existingRngNode = existingRngItr.next().getObject();\n\t\t\trangeExists = true;\n\t\t\t// property already has a range know to this model\n\t\t\tif (rngNode.equals(existingRngNode) || (rngResource != null && rngResource.equals(existingRngNode))) {\n\t\t\t\t// do nothing-- rngNode is already in range\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (prop.isDatatypeProperty()) {\n\t\t\t\tString existingRange = stmtIteratorToObjectString(getTheJenaModel().listStatements(prop, RDFS.range, (RDFNode)null));\n\t\t\t\taddError(SadlErrorMessages.CANNOT_ASSIGN_EXISTING.get(\"range\", nodeToString(prop), existingRange), context);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!rngNode.isResource()) {\n\t\t\t\taddError(\"Proposed range node '\" + rngNode.toString() + \"' is not a Resource so cannot be added to create a union class as range\", context);\n\t\t\t\treturn;\n\t\t\t}\t\t\n\t\t\tif (existingRngNode.canAs(OntClass.class)){\n\t\t\t\t// is the new range a subclass of the existing range, or vice versa?\n\t\t\t\tif ((rngResource != null && rngResource.canAs(OntClass.class) && checkForSubclassing(rngResource.as(OntClass.class), existingRngNode.as(OntClass.class), context)) || \n\t\t\t\t\t\trngNode.canAs(OntClass.class) && checkForSubclassing(rngNode.as(OntClass.class), existingRngNode.as(OntClass.class), context)) {\n\t\t\t\t\tStringBuilder sb = new StringBuilder(\"This range is a subclass of the range which is already defined\");\n\t\t\t\t\tString existingRange = nodeToString(existingRngNode);\n\t\t\t\t\tif (existingRange != null) {\n\t\t\t\t\t\tsb.append(\" (\");\n\t\t\t\t\t\tsb.append(existingRange);\n\t\t\t\t\t\tsb.append(\") \");\n\t\t\t\t\t}\n\t\t\t\t\tsb.append(\"; perhaps you meant to restrict values of this property on this class with an 'only has values of type' restriction?\");\n\t\t\t\t\taddWarning(sb.toString(), context);\t\t\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tboolean rangeInThisModel = false;\n\t\t\tStmtIterator inModelStmtItr = getTheJenaModel().getBaseModel().listStatements(prop, RDFS.range, (RDFNode)null);\n\t\t\tif (inModelStmtItr.hasNext()) {\n\t\t\t\trangeInThisModel = true;\n\t\t\t}\n\t\t\tif (domainAndRangeAsUnionClasses) {\n\t\t\t\t// in this case we want to create a union class if necessary\n\t\t\t\tif (rangeInThisModel) {\n\t\t\t\t\t// this model (as opposed to imports) already has a range specified\n\t\t\t\t\taddNewRange = false;\n\t\t\t\t\tUnionClass newUnionClass = null;\n\t\t\t\t\twhile (inModelStmtItr.hasNext()) {\n\t\t\t\t\t\tRDFNode rngThisModel = inModelStmtItr.nextStatement().getObject();\n\t\t\t\t\t\tif (rngThisModel.isResource()) {\n\t\t\t\t\t\t\tif (rngThisModel.canAs(OntResource.class)){\n\t\t\t\t\t\t\t\tif (existingRngNode.toString().equals(rngThisModel.toString())) {\n\t\t\t\t\t\t\t\t\trngThisModel = existingRngNode;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tnewUnionClass = createUnionClass(rngThisModel.as(OntResource.class), rngResource != null ? rngResource : rngNode.asResource());\n\t\t\t\t\t\t\t\tlogger.debug(\"Range '\" + rngNode.toString() + \"' added to property '\" + prop.getURI() + \"'\");\n\t\t\t\t\t\t\t\tif (!newUnionClass.equals(rngThisModel)) {\n\t\t\t\t\t\t\t\t\taddNewRange = true;\n\t\t\t\t\t\t\t\t\trngResource = newUnionClass;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\trngNode = null;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tthrow new JenaProcessorException(\"Encountered non-OntResource in range of '\" + prop.getURI() + \"'\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tthrow new JenaProcessorException(\"Encountered non-Resource in range of '\" + prop.getURI() + \"'\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (addNewRange) {\n\t\t\t\t\t\tgetTheJenaModel().remove(getTheJenaModel().getBaseModel().listStatements(prop, RDFS.range, (RDFNode)null));\n\t\t\t\t\t\trngNode = newUnionClass;\n\t\t\t\t\t}\n\t\t\t\t}\t// end if existing range in this model\n\t\t\t\telse {\n\t\t\t\t\tinModelStmtItr.close();\n\t\t\t\t\t// check to see if this is something new\n\t\t\t\t\tdo {\n\t\t\t\t\t\tif (existingRngNode.equals(rngNode)) {\n\t\t\t\t\t\t\texistingRngItr.close();\n\t\t\t\t\t\t\treturn;\t// already in domain, nothing to add\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (existingRngItr.hasNext()) {\n\t\t\t\t\t\t\texistingRngNode = existingRngItr.next().getObject();\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\texistingRngNode = null;\n\t\t\t\t\t\t}\n\t\t\t\t\t} while (existingRngNode != null);\n\t\t\t\t}\n\t\t\t}\t// end if domainAndRangeAsUnionClasses\n\t\t\telse {\n\t\t\t\tinModelStmtItr.close();\n\t\t\t}\n\t\t\tif (rangeExists && !rangeInThisModel) {\n\t\t\t\taddWarning(SadlErrorMessages.IMPORTED_RANGE_CHANGE.get(nodeToString(prop)), context);\n\t\t\t}\n\t\t}\t// end if existing range in any model, this or imports\n\t\tif (rngNode != null) {\t\n\t\t\tif (rngResource != null) {\n\t\t\t\tif (!domainAndRangeAsUnionClasses && rngResource instanceof UnionClass) {\n\t\t\t\t\tList uclsmembers = getUnionClassMemebers((UnionClass)rngResource);\n\t\t\t\t\tfor (int i = 0; i < uclsmembers.size(); i++) {\n\t\t\t\t\t\tgetTheJenaModel().add(prop, RDFS.range, uclsmembers.get(i));\n\t\t\t\t\t\tlogger.debug(\"Range '\" + uclsmembers.get(i).toString() + \"' added to property '\" + prop.getURI() + \"'\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tgetTheJenaModel().add(prop, RDFS.range, rngResource);\n\t\t\t\t\tlogger.debug(\"Range '\" + rngResource.toString() + \"' added to property '\" + prop.getURI() + \"'\");\n\t\t\t\t}\n\t\t\t\tpropOwlType = OWL.ObjectProperty;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcom.hp.hpl.jena.rdf.model.Resource rngrsrc = rngNode.asResource();\n\t\t\t\tif (rngrsrc.hasProperty(RDF.type, RDFS.Datatype)) {\n\t\t\t\t\tpropOwlType = OWL.DatatypeProperty;\n\t\t\t\t}\n\t\t\t\telse if (rngrsrc.canAs(OntClass.class)){\n\t\t\t\t\tpropOwlType = OWL.ObjectProperty;\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tpropOwlType = OWL.DatatypeProperty;\n\t\t\t\t}\n\t\t\t\tgetTheJenaModel().add(prop, RDFS.range, rngNode);\n\t\t\t}\n\t\t}\n\t\tif (propType.equals(OntConceptType.RDF_PROPERTY) && propOwlType != null) {\n\t\t\tgetTheJenaModel().add(prop, RDF.type, propOwlType);\n\t\t}\n\t}\n\n\tprivate String stmtIteratorToObjectString(StmtIterator stmtitr) {\n\t\tStringBuilder sb = new StringBuilder();\n\t\twhile (stmtitr.hasNext()) {\n\t\t\tRDFNode obj = stmtitr.next().getObject();\n\t\t\tif (sb.length() > 0) {\n\t\t\t\tsb.append(\", \");\n\t\t\t}\n\t\t\tsb.append(nodeToString(obj));\n\t\t}\n\t\treturn sb.toString();\n\t}\n\t\n\tprivate String nodeToString(RDFNode obj) {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tif (obj.isURIResource()) {\n\t\t\tsb.append(uriStringToString(obj.toString()));\n\t\t}\n\t\telse if (obj.canAs(UnionClass.class)){\n\t\t\tUnionClass ucls = obj.as(UnionClass.class);\n\t\t\tExtendedIterator uitr = ucls.getOperands().iterator();\n\t\t\tsb.append(\"(\");\n\t\t\twhile (uitr.hasNext()) {\n\t\t\t\tif (sb.length() > 1) {\n\t\t\t\t\tsb.append(\" or \");\n\t\t\t\t}\n\t\t\t\tsb.append(nodeToString(uitr.next()));\n\t\t\t}\n\t\t\tsb.append(\")\");\n\t\t}\n\t\telse if (obj.canAs(IntersectionClass.class)){\n\t\t\tIntersectionClass icls = obj.as(IntersectionClass.class);\n\t\t\tExtendedIterator iitr = icls.getOperands().iterator();\n\t\t\tsb.append(\"(\");\n\t\t\twhile (iitr.hasNext()) {\n\t\t\t\tif (sb.length() > 1) {\n\t\t\t\t\tsb.append(\" and \");\n\t\t\t\t}\n\t\t\t\tsb.append(nodeToString(iitr.next()));\n\t\t\t}\n\t\t\tsb.append(\")\");\n\t\t}\n\t\telse if (obj.isResource() && \n\t\t\t\tgetTheJenaModel().contains(obj.asResource(), RDFS.subClassOf, getTheJenaModel().getOntClass(SadlConstants.SADL_LIST_MODEL_LIST_URI))) {\n\t\t\tConceptName cn = getTypedListType(obj);\n\t\t\tsb.append(cn.getName());\n\t\t\tsb.append(\" List\");\n\t\t}\n\t\telse {\n\t\t\tsb.append(\"\");\n\t\t}\n\t\treturn sb.toString();\n\t}\n\t\n\tpublic String uriStringToString(String uri) {\n\t\tint sep = uri.lastIndexOf('#');\n\t\tif (sep > 0) {\n\t\t\tString ns = uri.substring(0, sep);\n\t\t\tString ln = uri.substring(sep + 1);\n\t\t\t// if the concept is in the current model just return the localname\n\t\t\tif (ns.equals(getModelName())) {\n\t\t\t\treturn ln;\n\t\t\t}\n\t\t\t// get the prefix and if there is one generate qname\n\t\t\tString prefix = getConfigMgr().getGlobalPrefix(ns);\n\t\t\tif (prefix != null && prefix.length() > 0) {\n\t\t\t\treturn prefix + \":\" + ln;\n\t\t\t}\n\t\t\treturn ln;\n\t\t}\n\t\treturn uri;\n\t}\n\n\n\t\n\tprivate boolean checkForSubclassing(OntClass rangeCls, OntResource existingRange, EObject context) throws JenaProcessorException {\n\t\t// this is changing the range of a property defined in a different model\n\t\ttry {\n\t\t\tif (SadlUtils.classIsSubclassOf((OntClass) rangeCls, existingRange, true, null)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t} catch (CircularDependencyException e) {\n\t\t\tthrow new JenaProcessorException(e.getMessage(), e);\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprivate boolean updateObjectPropertyRange(OntProperty prop, OntResource rangeCls, ExtendedIterator ritr, RangeValueType rngValueType, EObject context) throws JenaProcessorException {\n\t\tboolean retval = false;\n\t\tif (rangeCls != null) {\n\t\t\tOntResource newRange = createUnionOfClasses(rangeCls, ritr);\n\t\t\tif (newRange != null) {\n\t\t\t\tif (newRange.equals(rangeCls)) {\n\t\t\t\t\treturn retval;\t// do nothing--the rangeCls is already in the range\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (prop.getRange() != null) {\n\t\t\t\t// remove existing range in this model\n\t\t\t\tprop.removeRange(prop.getRange());\n\t\t\t}\n\t\t\tprop.addRange(newRange); \n\t\t\tretval = true;\n\t\t} else {\n\t\t\taddError(SadlErrorMessages.INVALID_NULL.get(\"range\"), context);\n\t\t}\n\t\treturn retval;\n\t}\n\n\tpublic void addError(String msg, EObject context) {\n\t\tif (getIssueAcceptor() != null) {\n\t\t\tgetIssueAcceptor().addError(msg, context);\n\t\t\tif (isSyntheticUri(null, getCurrentResource())) {\n\t\t\t\tif (getMetricsProcessor() != null) {\n\t\t\t\t\tgetMetricsProcessor().addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.UNCLASSIFIED_FAILURE_URI);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if (!generationInProgress){\n\t\t\tSystem.err.println(msg);\n\t\t}\n\t}\n\n\tpublic void addWarning(String msg, EObject context) {\n\t\tif (getIssueAcceptor() != null) {\n\t\t\tgetIssueAcceptor().addWarning(msg, context);\n\t\t\tif (isSyntheticUri(null, getCurrentResource())) {\n\t\t\t\tif (getMetricsProcessor() != null) {\n\t\t\t\t\tgetMetricsProcessor().addMarker(null, MetricsProcessor.WARNING_MARKER_URI, MetricsProcessor.WARNING_MARKER_URI);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if (!generationInProgress) {\n\t\t\tSystem.out.println(msg);\t\t\t\n\t\t}\n\t}\n\n\tpublic void addInfo(String msg, EObject context) {\n\t\tif (getIssueAcceptor() != null) {\n\t\t\tgetIssueAcceptor().addInfo(msg, context);\n\t\t\tif (isSyntheticUri(null, getCurrentResource())) {\n\t\t\t\tif (getMetricsProcessor() != null) {\n\t\t\t\t\tgetMetricsProcessor().addMarker(null, MetricsProcessor.INFO_MARKER_URI, MetricsProcessor.INFO_MARKER_URI);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if (!generationInProgress) {\n\t\t\tSystem.out.println(msg);\t\t\t\n\t\t}\n\t}\n\n\t//\tprivate OntResource addClassToUnionClass(OntResource existingCls,\n//\t\t\tOntResource cls) throws JenaProcessorException {\n//\t\tif (existingCls != null && !existingCls.equals(cls)) {\n//\t\t\ttry {\n//\t\t\t\tif (existingCls.canAs(OntClass.class) && SadlUtils.classIsSubclassOf(existingCls.as(OntClass.class), cls, true, null)) {\n//\t\t\t\t\treturn cls;\n//\t\t\t\t}\n//\t\t\t\telse if (cls.canAs(OntClass.class) && SadlUtils.classIsSubclassOf(cls.as(OntClass.class), existingCls, true, null)) {\n//\t\t\t\t\treturn existingCls;\n//\t\t\t\t}\n//\t\t\t\telse {\n//\t\t\t\t\tRDFList classes = null;\n//\t\t\t\t\tif (existingCls.canAs(UnionClass.class)) {\n//\t\t\t\t\t\ttry {\n//\t\t\t\t\t\t\t UnionClass ucls = existingCls.as(UnionClass.class);\n//\t\t\t\t\t\t\t ucls.addOperand(cls);\n//\t\t\t\t\t\t\t return ucls;\n//\t\t\t\t\t\t} catch (Exception e) {\n//\t\t\t\t\t\t\t// don't know why this is happening\n//\t\t\t\t\t\t\tlogger.error(\"Union class error that hasn't been resolved or understood.\");\n//\t\t\t\t\t\t\treturn cls;\n//\t\t\t\t\t\t}\n//\t\t\t\t\t} else {\n//\t\t\t\t\t\tif (cls.equals(existingCls)) {\n//\t\t\t\t\t\t\treturn existingCls;\n//\t\t\t\t\t\t}\n//\t\t\t\t\t\tclasses = getTheJenaModel().createList();\n//\t\t\t\t\t\tOntResource inCurrentModel = null;\n//\t\t\t\t\t\tif (existingCls.isURIResource()) {\n//\t\t\t\t\t\t\tinCurrentModel = getTheJenaModel().getOntResource(existingCls.getURI());\n//\t\t\t\t\t\t}\n//\t\t\t\t\t\tif (inCurrentModel != null) {\n//\t\t\t\t\t\t\tclasses = classes.with(inCurrentModel);\n//\t\t\t\t\t\t}\n//\t\t\t\t\t\telse {\n//\t\t\t\t\t\t\tclasses = classes.with(existingCls);\n//\t\t\t\t\t\t}\n//\t\t\t\t\t\tclasses = classes.with(cls);\n//\t\t\t\t\t}\n//\t\t\t\t\tOntResource unionClass = getTheJenaModel().createUnionClass(null,\n//\t\t\t\t\t\t\tclasses);\n//\t\t\t\t\treturn unionClass;\n//\t\t\t\t}\n//\t\t\t} catch (CircularDependencyException e) {\n//\t\t\t\tthrow new JenaProcessorException(e.getMessage(), e);\n//\t\t\t}\n//\t\t} else {\n//\t\t\treturn cls;\n//\t\t}\n//\t}\n\n\tprivate void processSadlNecessaryAndSufficient(SadlNecessaryAndSufficient element) throws JenaProcessorException {\n\t\tOntResource rsrc = sadlTypeReferenceToOntResource(element.getSubject());\n\t\tOntClass supercls = null;\n\t\tif (rsrc != null) {\n\t\t\tsupercls = rsrc.asClass();\n\t\t}\n\t\tOntClass rolecls = getOrCreateOntClass(getDeclarationExtensions().getConceptUri(element.getObject()));\n\t\tIterator itr = element.getPropConditions().iterator();\n\t\tList conditionClasses = new ArrayList();\n\t\twhile (itr.hasNext()) {\n\t\t\tSadlPropertyCondition nxt = itr.next();\n\t\t\tconditionClasses.add(processSadlPropertyCondition(nxt));\n\t\t}\n\t\t// we have all the parts--create the equivalence class\n\t\tif (conditionClasses.size() == 1) {\n\t\t\tif (supercls != null && conditionClasses.get(0) != null) {\n\t\t\t\tIntersectionClass eqcls = createIntersectionClass(supercls, conditionClasses.get(0));\n\t\t\t\trolecls.setEquivalentClass(eqcls);\n\t\t\t\tlogger.debug(\"New intersection class created as equivalent of '\" + rolecls.getURI() + \"'\");\n\t\t\t} else if (conditionClasses.get(0) != null) {\n\t\t\t\trolecls.setEquivalentClass(conditionClasses.get(0));\n\t\t\t\tlogger.debug(\"Equivalent class set for '\" + rolecls.getURI() + \"'\");\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthrow new JenaProcessorException(\"Necessary and sufficient conditions appears to have invalid input.\");\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tint base = supercls != null ? 1 : 0;\n\t\t\tRDFNode[] memberList = new RDFNode[base + conditionClasses.size()];\n\t\t\tif (base > 0) {\n\t\t\t\tmemberList[0] = supercls;\n\t\t\t}\n\t\t\tfor (int i = 0; i < conditionClasses.size(); i++) {\n\t\t\t\tmemberList[base + i] = conditionClasses.get(i);\n\t\t\t}\n\t\t\tIntersectionClass eqcls = createIntersectionClass(memberList);\n\t\t\trolecls.setEquivalentClass(eqcls);\n\t\t\tlogger.debug(\"New intersection class created as equivalent of '\" + rolecls.getURI() + \"'\");\n\t\t}\n\t}\n\n\tprivate void processSadlDifferentFrom(SadlDifferentFrom element) throws JenaProcessorException {\n\t\tList differentFrom = new ArrayList();\n\t\tIterator dcitr = element.getTypes().iterator();\n\t\twhile(dcitr.hasNext()) {\n\t\t\tSadlClassOrPropertyDeclaration decl = dcitr.next();\n\t\t\tIterator djitr = decl.getClassOrProperty().iterator();\n\t\t\twhile (djitr.hasNext()) {\n\t\t\t\tSadlResource sr = djitr.next();\n\t\t\t\tString declUri = getDeclarationExtensions().getConceptUri(sr);\n\t\t\t\tif (declUri == null) {\n\t\t\t\t\tthrow new JenaProcessorException(\"Failed to get concept URI for SadlResource in processSadlDifferentFrom\");\n\t\t\t\t}\n\t\t\t\tIndividual inst = getTheJenaModel().getIndividual(declUri);\n\t\t\t\tdifferentFrom.add(inst);\n\t\t\t}\n\t\t}\n\t\tSadlTypeReference nsas = element.getNotTheSameAs();\n\t\tif (nsas != null) {\n\t\t\tOntResource nsasrsrc = sadlTypeReferenceToOntResource(nsas);\n\t\t\tdifferentFrom.add(nsasrsrc.asIndividual());\n\t\t\tSadlResource sr = element.getNameOrRef();\n\t\t\tIndividual otherInst = getTheJenaModel().getIndividual(getDeclarationExtensions().getConceptUri(sr));\n\t\t\tdifferentFrom.add(otherInst);\n\t\t}\n\t\tRDFNode[] nodeArray = null;\n\t\tif (differentFrom.size() > 0) {\n\t\t\tnodeArray = differentFrom.toArray(new Individual[differentFrom.size()]);\n\t\t}\n\t\telse {\n\t\t\tthrow new JenaProcessorException(\"Unexpect empty array in processSadlDifferentFrom\");\n\t\t}\n\t\tRDFList differentMembers = getTheJenaModel().createList(nodeArray);\n\t\tgetTheJenaModel().createAllDifferent(differentMembers);\n\t\tlogger.debug(\"New all different from created\");\n\t}\n\n\tprivate Individual processSadlInstance(SadlInstance element) throws JenaProcessorException, CircularDefinitionException {\n\t\t// this has two forms:\n\t\t//\t1) is a ...\n\t\t//\t2) a ....\n\t\tSadlTypeReference type = element.getType();\n\t\tboolean isList = typeRefIsList(type);\n\t\tSadlResource sr = sadlResourceFromSadlInstance(element);\n\t\tIndividual inst = null;\n\t\tString instUri = null;\n\t\tOntConceptType subjType = null;\n\t\tboolean isActuallyClass = false;\n\t\tif (sr != null) {\n\t\t\tinstUri = getDeclarationExtensions().getConceptUri(sr);\n\t\t\tif (instUri == null) {\n\t\t\t\tthrow new JenaProcessorException(\"Failed to get concept URI of SadlResource in processSadlInstance\");\n\t\t\t}\n\t\t\tsubjType = getDeclarationExtensions().getOntConceptType(sr);\n\t\t\tif (subjType.equals(OntConceptType.CLASS)) {\n\t\t\t\t// This is really a class so don't treat as an instance\n\t\t\t\tOntClass actualClass = getOrCreateOntClass(instUri);\n\t\t\t\tisActuallyClass = true;\n\t\t\t\tinst = actualClass.asIndividual();\n\t\t\t}\n\t\t}\n\t\tOntClass cls = null;\n\t\tif (!isActuallyClass) {\n\t\t\tif (type != null) {\n\t\t\t\tif (type instanceof SadlPrimitiveDataType) {\n\t\t\t\t\tcom.hp.hpl.jena.rdf.model.Resource rsrc = sadlTypeReferenceToResource(type);\n\t\t\t\t\tif (isList) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tcls = getOrCreateListSubclass(null, rsrc.getURI(), type.eResource());\n\t\t\t\t\t\t} catch (JenaProcessorException e) {\n\t\t\t\t\t\t\taddError(e.getMessage(), type);\n\t\t\t\t\t\t}\n\t\t\t\t\t}else{\n\t\t\t\t\t\t//AATIM-2306 If not list, generate error when creating instances of primitive data types.\n\t\t\t\t\t\taddError(\"Invalid to create an instance of a primitive datatype ( \\'\" + ((SadlPrimitiveDataType) type).getPrimitiveType().toString() + \"\\' in this case). Instances of primitive datatypes exist implicitly.\", type );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tOntResource or = sadlTypeReferenceToOntResource(type);\n\t\t\t\t\tif (or != null && or.canAs(OntClass.class)){\n\t\t\t\t\t\tcls = or.asClass();\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\telse if (or instanceof Individual) {\n\t\t\t\t\t\tinst = (Individual) or;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} \n\t\t\tif (inst == null) {\n\t\t\t\tif (cls != null) {\n\t\t\t\t\tinst = createIndividual(instUri, cls);\n\t\t\t\t}\n\t\t\t\telse if (instUri != null) {\n\t\t\t\t\tinst = createIndividual(instUri, (OntClass)null);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrow new JenaProcessorException(\"Can't create an unnamed instance with no class given\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tIterator itr = element.getPropertyInitializers().iterator();\n\t\twhile (itr.hasNext()) {\n\t\t\tSadlPropertyInitializer propinit = itr.next();\n\t\t\tSadlResource prop = propinit.getProperty();\n\t\t\tOntConceptType propType = getDeclarationExtensions().getOntConceptType(prop);\n\t\t\tif (subjType != null && subjType.equals(OntConceptType.CLASS) && \n\t\t\t\t\t!(propType.equals(OntConceptType.ANNOTATION_PROPERTY)) && \t// only a problem if not an annotation property\n\t\t\t\t\t!getOwlFlavor().equals(SadlConstants.OWL_FLAVOR.OWL_FULL)) {\n\t\t\t\taddWarning(SadlErrorMessages.CLASS_PROPERTY_VALUE_OWL_FULL.get(), element);\n\t\t\t}\n\t\t\tEObject val = propinit.getValue();\n\t\t\tif (val != null) {\n\t\t\t\ttry {\n\t\t\t\t\tif (getModelValidator() != null) {\n\t\t\t\t\t\tStringBuilder error = new StringBuilder();\n\t\t\t\t\t\tif (!getModelValidator().checkPropertyValueInRange(getTheJenaModel(), sr, prop, val, error)) {\n\t\t\t\t\t\t\tissueAcceptor.addError(error.toString(), propinit);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} catch (DontTypeCheckException e) {\n\t\t\t\t\t// do nothing\n\t\t\t\t} catch(PropertyWithoutRangeException e){\n\t\t\t\t\tString propUri = getDeclarationExtensions().getConceptUri(prop);\n\t\t\t\t\tif (!propUri.equals(SadlConstants.SADL_IMPLICIT_MODEL_IMPLIED_PROPERTY_URI)) {\n\t\t\t\t\t\tissueAcceptor.addWarning(SadlErrorMessages.PROPERTY_WITHOUT_RANGE.get(getDeclarationExtensions().getConcreteName(prop)), propinit);\n\t\t\t\t\t}\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\tthrow new JenaProcessorException(\"Unexpected error checking value in range\", e);\n\t\t\t\t}\n\t\t\t\tassignInstancePropertyValue(inst, cls, prop, val);\n\t\t\t} else {\n\t\t\t\taddError(\"no value found\", propinit);\n\t\t\t}\n\t\t}\n\t\tSadlValueList listInitializer = element.getListInitializer();\n\t\tif (listInitializer != null) {\n\t\t\tif(listInitializer.getExplicitValues().isEmpty()){\n\t\t\t\taddError(SadlErrorMessages.EMPTY_LIST_DEFINITION.get(), element);\n\t\t\t}else{\n\t\t\t\tif (cls == null) {\n\t\t\t\t\tConceptName cn = getTypedListType(inst);\n\t\t\t\t\tif (cn != null) {\n\t\t\t\t\t\tcls = getTheJenaModel().getOntClass(cn.toFQString());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (cls != null) {\n\t\t\t\t\taddListValues(inst, cls, listInitializer);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrow new JenaProcessorException(\"Unable to find type of list '\" + inst.toString() + \"'\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn inst;\n\t}\n\n\tprivate OWL_FLAVOR getOwlFlavor() {\n\t\treturn owlFlavor;\n\t}\n\t\n\tpublic ConceptName getTypedListType(RDFNode node) {\n\t\tif (node.isResource()) {\n\t\t\tStmtIterator sitr = theJenaModel.listStatements(node.asResource(), RDFS.subClassOf, (RDFNode)null);\n\t\t\twhile (sitr.hasNext()) {\n\t\t\t\tRDFNode supercls = sitr.nextStatement().getObject();\n\t\t\t\tif (supercls.isResource()) {\n\t\t\t\t\tif (supercls.asResource().hasProperty(OWL.onProperty, theJenaModel.getResource(SadlConstants.SADL_LIST_MODEL_FIRST_URI))) {\n\t\t\t\t\t\tStatement avfstmt = supercls.asResource().getProperty(OWL.allValuesFrom);\n\t\t\t\t\t\tif (avfstmt != null) {\n\t\t\t\t\t\t\tRDFNode type = avfstmt.getObject();\n\t\t\t\t\t\t\tif (type.isURIResource()) {\n\t\t\t\t\t\t\t\tConceptName cn = createTypedConceptName(type.asResource().getURI(), OntConceptType.CLASS);\n\t\t\t\t\t\t\t\tcn.setRangeValueType(RangeValueType.LIST);\n\t\t\t\t\t\t\t\tsitr.close();\n\t\t\t\t\t\t\t\treturn cn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// maybe it's an instance\n\t\t\tif (node.asResource().canAs(Individual.class)) {\n\t\t\t\tExtendedIterator itr = node.asResource().as(Individual.class).listRDFTypes(true);\n\t\t\t\twhile (itr.hasNext()) {\n\t\t\t\t\tcom.hp.hpl.jena.rdf.model.Resource r = itr.next();\n\t\t\t\t\tsitr = theJenaModel.listStatements(r, RDFS.subClassOf, (RDFNode)null);\n\t\t\t\t\twhile (sitr.hasNext()) {\n\t\t\t\t\t\tRDFNode supercls = sitr.nextStatement().getObject();\n\t\t\t\t\t\tif (supercls.isResource()) {\n\t\t\t\t\t\t\tif (supercls.asResource().hasProperty(OWL.onProperty, theJenaModel.getResource(SadlConstants.SADL_LIST_MODEL_FIRST_URI))) {\n\t\t\t\t\t\t\t\tStatement avfstmt = supercls.asResource().getProperty(OWL.allValuesFrom);\n\t\t\t\t\t\t\t\tif (avfstmt != null) {\n\t\t\t\t\t\t\t\t\tRDFNode type = avfstmt.getObject();\n\t\t\t\t\t\t\t\t\tif (type.isURIResource()) {\n\t\t\t\t\t\t\t\t\t\tConceptName cn = createTypedConceptName(type.asResource().getURI(), OntConceptType.CLASS);\n\t\t\t\t\t\t\t\t\t\tsitr.close();\n\t\t\t\t\t\t\t\t\t\treturn cn;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic ConceptName createTypedConceptName(String conceptUri, OntConceptType conceptType) {\n\t\tConceptName cn = new ConceptName(conceptUri);\n\t\tif (conceptType.equals(OntConceptType.CLASS)) {\n\t\t\tcn.setType(ConceptType.ONTCLASS);\n\t\t}\n\t\telse if (conceptType.equals(OntConceptType.ANNOTATION_PROPERTY)) {\n\t\t\tcn.setType(ConceptType.ANNOTATIONPROPERTY);\n\t\t}\n\t\telse if (conceptType.equals(OntConceptType.DATATYPE_PROPERTY)) {\n\t\t\tcn.setType(ConceptType.DATATYPEPROPERTY);\n\t\t}\n\t\telse if (conceptType.equals(OntConceptType.INSTANCE)) {\n\t\t\tcn.setType(ConceptType.INDIVIDUAL);\n\t\t}\n\t\telse if (conceptType.equals(OntConceptType.CLASS_PROPERTY)) {\n\t\t\tcn.setType(ConceptType.OBJECTPROPERTY);\n\t\t}\n\t\telse if (conceptType.equals(OntConceptType.DATATYPE)) {\n\t\t\tcn.setType(ConceptType.RDFDATATYPE);\n\t\t}\n\t\telse if (conceptType.equals(OntConceptType.RDF_PROPERTY)) {\n\t\t\tcn.setType(ConceptType.RDFPROPERTY);\n\t\t}\n\t\telse if (conceptType.equals(OntConceptType.VARIABLE)) {\n\t\t\tcn.setType(ConceptType.VARIABLE);\n\t\t}\n\t\telse if (conceptType.equals(OntConceptType.FUNCTION_DEFN)) {\n\t\t\tcn.setType(ConceptType.FUNCTION_DEFN);\n\t\t}\n\t\treturn cn;\n\t}\n\n\t\n\tprivate boolean typeRefIsList(SadlTypeReference type) throws JenaProcessorException {\n\t\tboolean isList = false;\n\t\tif (type instanceof SadlSimpleTypeReference) {\n\t\t\tisList = ((SadlSimpleTypeReference)type).isList();\n\t\t}\n\t\telse if (type instanceof SadlPrimitiveDataType) {\n\t\t\tisList = ((SadlPrimitiveDataType)type).isList();\n\t\t}\n\t\tif (isList) {\n\t\t\ttry {\n\t\t\t\timportSadlListModel(type.eResource());\n\t\t\t} catch (ConfigurationException e) {\n\t\t\t\tthrow new JenaProcessorException(\"Unable to load List model\", e);\n\t\t\t}\t\t\t\n\t\t}\n\t\treturn isList;\n\t}\n\t\n\tprivate void addListValues(Individual inst, OntClass cls, SadlValueList listInitializer) {\n\t\tcom.hp.hpl.jena.rdf.model.Resource to = null;\n\t\tExtendedIterator scitr = cls.listSuperClasses(true);\n\t\twhile (scitr.hasNext()) {\n\t\t\tOntClass sc = scitr.next(); \n\t\t\tif (sc.isRestriction() && ((sc.as(Restriction.class)).isAllValuesFromRestriction() && \n\t\t\t\t\tsc.as(AllValuesFromRestriction.class).onProperty(getTheJenaModel().getProperty(SadlConstants.SADL_LIST_MODEL_FIRST_URI)))) {\n\t\t\t\tto = sc.as(AllValuesFromRestriction.class).getAllValuesFrom();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (to == null) {\n//\t\t\taddError(\"No 'to' resource found in restriction of List subclass\", listInitializer);\n\t\t}\n\t\tIterator values = listInitializer.getExplicitValues().iterator();\n\t\taddValueToList(null, inst, cls, to, values);\n\t}\n\t\n\tprivate Individual addValueToList(Individual lastInst, Individual inst, OntClass cls, com.hp.hpl.jena.rdf.model.Resource type, \n\t\t\tIterator valueIterator) {\n\t\tif (inst == null) {\n\t\t\tinst = getTheJenaModel().createIndividual(cls);\n\t\t}\n\t\tSadlExplicitValue val = valueIterator.next();\n\t\tif (val instanceof SadlResource) {\n\t\t\tIndividual listInst;\n\t\t\ttry {\n\t\t\t\tif (type.canAs(OntClass.class)) { \n\t\t\t\t\tlistInst = createIndividual((SadlResource)val, type.as(OntClass.class));\n\t\t\t\t\tExtendedIterator itr = listInst.listRDFTypes(false);\n\t\t\t\t\tboolean match = false;\n\t\t\t\t\twhile (itr.hasNext()) {\n\t\t\t\t\t\tcom.hp.hpl.jena.rdf.model.Resource typ = itr.next();\n\t\t\t\t\t\tif (typ.equals(type)) {\n\t\t\t\t\t\t\tmatch = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!match) {\n\t\t\t\t\t\taddError(\"The Instance '\" + listInst.toString() + \"' doesn't match the List type.\", val);\n\t\t\t\t\t}\n\t\t\t\t\tgetTheJenaModel().add(inst, getTheJenaModel().getProperty(SadlConstants.SADL_LIST_MODEL_FIRST_URI), listInst);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\taddError(\"The type of the list could not be converted to a class.\", val);\n\t\t\t\t}\n\t\t\t} catch (JenaProcessorException e) {\n\t\t\t\taddError(e.getMessage(), val);\n\t\t\t} catch (TranslationException e) {\n\t\t\t\taddError(e.getMessage(), val);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tLiteral lval;\n\t\t\ttry {\n\t\t\t\tlval = sadlExplicitValueToLiteral((SadlExplicitValue)val, type);\n\t\t\t\tgetTheJenaModel().add(inst, getTheJenaModel().getProperty(SadlConstants.SADL_LIST_MODEL_FIRST_URI), lval);\n\t\t\t} catch (JenaProcessorException e) {\n\t\t\t\taddError(e.getMessage(), val);\n\t\t\t}\n\t\t}\n\t\tif (valueIterator.hasNext()) {\n\t\t\tIndividual rest = addValueToList(inst, null, cls, type, valueIterator);\n\t\t\tgetTheJenaModel().add(inst, getTheJenaModel().getProperty(SadlConstants.SADL_LIST_MODEL_REST_URI), rest);\n\t\t}\n\t\treturn inst;\n\t}\n\t\n\tprivate void assignInstancePropertyValue(Individual inst, OntClass cls, SadlResource prop, EObject val) throws JenaProcessorException, CircularDefinitionException {\n\t\tOntConceptType type;\n\t\ttry {\n\t\t\ttype = getDeclarationExtensions().getOntConceptType(prop);\n\t\t} catch (CircularDefinitionException e) {\n\t\t\ttype = e.getDefinitionType();\n\t\t\taddError(e.getMessage(), prop);\n\t\t}\n\t\tString propuri = getDeclarationExtensions().getConceptUri(prop);\n\t\tif (type.equals(OntConceptType.CLASS_PROPERTY)) {\n\t\t\tOntProperty oprop = getTheJenaModel().getOntProperty(propuri);\n\t\t\tif (oprop == null) {\n\t\t\t\taddError(SadlErrorMessages.PROPERTY_NOT_EXIST.get(propuri), prop);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (val instanceof SadlInstance) {\n\t\t\t\t\tIndividual instval = processSadlInstance((SadlInstance) val);\n\t\t\t\t\tOntClass uQCls = getTheJenaModel().getOntClass(SadlConstants.SADL_IMPLICIT_MODEL_UNITTEDQUANTITY_URI);\n\t\t\t\t\tif (uQCls != null && instval.hasRDFType(uQCls) && ignoreUnittedQuantities) {\n\t\t\t\t\t\tif (val instanceof SadlNestedInstance) {\n\t\t\t\t\t\t\tIterator propinititr = ((SadlNestedInstance)val).getPropertyInitializers().iterator();\n\t\t\t\t\t\t\twhile (propinititr.hasNext()) {\n\t\t\t\t\t\t\t\tEObject pval = propinititr.next().getValue();\n\t\t\t\t\t\t\t\tif (pval instanceof SadlNumberLiteral) {\n\t\t\t\t\t\t\t\t\tcom.hp.hpl.jena.rdf.model.Resource effectiveRng = getUnittedQuantityValueRange();\n\t\t\t\t\t\t\t\t\tLiteral lval = sadlExplicitValueToLiteral((SadlNumberLiteral)pval, effectiveRng);\n\t\t\t\t\t\t\t\t\tif (lval != null) {\n\t\t\t\t\t\t\t\t\t\taddInstancePropertyValue(inst, oprop, lval, val);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\taddInstancePropertyValue(inst, oprop, instval, val);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (val instanceof SadlResource) {\n\t\t\t\t\tString uri = getDeclarationExtensions().getConceptUri((SadlResource) val);\n\t\t\t\t\tcom.hp.hpl.jena.rdf.model.Resource rsrc = getTheJenaModel().getResource(uri);\n\t\t\t\t\tif (rsrc.canAs(Individual.class)){\n\t\t\t\t\t\taddInstancePropertyValue(inst, oprop, rsrc.as(Individual.class), val);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tthrow new JenaProcessorException(\"unhandled value type SadlResource that isn't an instance (URI is '\" + uri + \"')\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (val instanceof SadlExplicitValue) {\n\t\t\t\t\tOntResource rng = oprop.getRange();\n\t\t\t\t\tif (val instanceof SadlNumberLiteral && ((SadlNumberLiteral)val).getUnit() != null) {\n\t\t\t\t\t\tif (!ignoreUnittedQuantities) {\n\t\t\t\t\t\t\tString unit = ((SadlNumberLiteral)val).getUnit();\n\t\t\t\t\t\t\tif (rng != null) {\n\t\t\t\t\t\t\t\tif (rng.canAs(OntClass.class) \n\t\t\t\t\t\t\t\t\t\t&& checkForSubclassing(rng.as(OntClass.class), \n\t\t\t\t\t\t\t\t\t\t\t\tgetTheJenaModel().getOntClass(SadlConstants.SADL_IMPLICIT_MODEL_UNITTEDQUANTITY_URI), val)) {\n\t\t\t\t\t\t\t\t\taddUnittedQuantityAsInstancePropertyValue(inst, oprop, rng, ((SadlNumberLiteral)val).getLiteralNumber(), unit);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\taddError(SadlErrorMessages.UNITTED_QUANTITY_ERROR.toString(), val);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\taddUnittedQuantityAsInstancePropertyValue(inst, oprop, rng, ((SadlNumberLiteral)val).getLiteralNumber(), unit);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tcom.hp.hpl.jena.rdf.model.Resource effectiveRng = getUnittedQuantityValueRange();\n\t\t\t\t\t\t\tLiteral lval = sadlExplicitValueToLiteral((SadlExplicitValue)val, effectiveRng);\n\t\t\t\t\t\t\tif (lval != null) {\n\t\t\t\t\t\t\t\taddInstancePropertyValue(inst, oprop, lval, val);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tif (rng == null) {\n\t\t\t\t\t\t\t// this isn't really an ObjectProperty--should probably be an rdf:Property\n\t\t\t\t\t\t\tLiteral lval = sadlExplicitValueToLiteral((SadlExplicitValue)val, null);\n\t\t\t\t\t\t\taddInstancePropertyValue(inst, oprop, lval, val);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\taddError(\"A SadlExplicitValue is given to an an ObjectProperty\", val);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (val instanceof SadlValueList) {\n//\t\t\t\t\tEList vals = ((SadlValueList)val).getExplicitValues();\n\t\t\t\t\taddListValues(inst, cls, (SadlValueList) val);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrow new JenaProcessorException(\"unhandled value type for object property\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if (type.equals(OntConceptType.DATATYPE_PROPERTY)) {\n\t\t\tDatatypeProperty dprop = getTheJenaModel().getDatatypeProperty(propuri);\n\t\t\tif (dprop == null) {\n//\t\t\t\tdumpModel(getTheJenaModel());\n\t\t\t\taddError(SadlErrorMessages.PROPERTY_NOT_EXIST.get(propuri), prop);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (val instanceof SadlValueList) {\n//\t\t\t\t\tEList vals = ((SadlValueList)val).getExplicitValues();\n\t\t\t\t\taddListValues(inst, cls, (SadlValueList) val);\n\t\t\t\t}\n\t\t\t\telse if (val instanceof SadlExplicitValue) {\n\t\t\t\t\tLiteral lval = sadlExplicitValueToLiteral((SadlExplicitValue)val, dprop.getRange());\n\t\t\t\t\tif (lval != null) {\n\t\t\t\t\t\taddInstancePropertyValue(inst, dprop, lval, val);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrow new JenaProcessorException(\"unhandled value type for data property\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if (type.equals(OntConceptType.ANNOTATION_PROPERTY)) {\n\t\t\tAnnotationProperty annprop = getTheJenaModel().getAnnotationProperty(propuri);\n\t\t\tif (annprop == null) {\n\t\t\t\taddError(SadlErrorMessages.PROPERTY_NOT_EXIST.get(propuri), prop);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tRDFNode rsrcval;\n\t\t\t\tif (val instanceof SadlResource) {\n\t\t\t\t\tString uri = getDeclarationExtensions().getConceptUri((SadlResource) val);\n\t\t\t\t\t rsrcval = getTheJenaModel().getResource(uri);\n\t\t\t\t}\n\t\t\t\telse if (val instanceof SadlInstance) {\n\t\t\t\t\trsrcval = processSadlInstance((SadlInstance) val);\n\t\t\t\t}\n\t\t\t\telse if (val instanceof SadlExplicitValue) {\n\t\t\t\t\trsrcval = sadlExplicitValueToLiteral((SadlExplicitValue)val, null);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrow new JenaProcessorException(SadlErrorMessages.UNHANDLED.get(val.getClass().getCanonicalName(), \"unable to handle annotation value\"));\n\t\t\t\t}\n\t\t\t\taddInstancePropertyValue(inst, annprop, rsrcval, val);\n\t\t\t}\n\t\t}\n\t\telse if (type.equals(OntConceptType.RDF_PROPERTY)) {\n\t\t\tProperty rdfprop = getTheJenaModel().getProperty(propuri);\n\t\t\tif (rdfprop == null) {\n\t\t\t\taddError(SadlErrorMessages.PROPERTY_NOT_EXIST.get(propuri), prop);\n\t\t\t}\n\t\t\tRDFNode rsrcval;\n\t\t\tif (val instanceof SadlResource) {\n\t\t\t\tString uri = getDeclarationExtensions().getConceptUri((SadlResource) val);\n\t\t\t\t rsrcval = getTheJenaModel().getResource(uri);\n\t\t\t}\n\t\t\telse if (val instanceof SadlInstance) {\n\t\t\t\trsrcval = processSadlInstance((SadlInstance) val);\n\t\t\t}\n\t\t\telse if (val instanceof SadlExplicitValue) {\n\t\t\t\trsrcval = sadlExplicitValueToLiteral((SadlExplicitValue)val, null);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthrow new JenaProcessorException(\"unable to handle rdf property value of type '\" + val.getClass().getCanonicalName() + \"')\");\n\t\t\t}\n\t\t\taddInstancePropertyValue(inst, rdfprop, rsrcval, val);\n\t\t}\n\t\telse if (type.equals(OntConceptType.VARIABLE)) {\n\t\t\t// a variable for a property type is only valid in a rule or query.\n\t\t\tif (getTarget() == null || getTarget() instanceof Test) {\n\t\t\t\taddError(\"Variable can be used for property only in queries and rules\", val);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tthrow new JenaProcessorException(\"unhandled property type\");\n\t\t}\n\t}\n\tprivate com.hp.hpl.jena.rdf.model.Resource getUnittedQuantityValueRange() {\n\t\tcom.hp.hpl.jena.rdf.model.Resource effectiveRng = getTheJenaModel().getOntProperty(SadlConstants.SADL_IMPLICIT_MODEL_VALUE_URI).getRange();\n\t\tif (effectiveRng == null) {\n\t\t\teffectiveRng = XSD.decimal;\n\t\t}\n\t\treturn effectiveRng;\n\t}\n\t\n\tprivate void addInstancePropertyValue(Individual inst, Property prop, RDFNode value, EObject ctx) {\n\t\tif (prop.getURI().equals(SadlConstants.SADL_IMPLICIT_MODEL_IMPLIED_PROPERTY_URI)) {\n\t\t\t// check for ambiguity through duplication of property range\n\t\t\tif (value.canAs(OntProperty.class)){ \n\t\t\t\tNodeIterator ipvs = inst.listPropertyValues(prop);\n\t\t\t\tif (ipvs.hasNext()) {\n\t\t\t\t\tList valueRngLst = new ArrayList();\n\t\t\t\t\tExtendedIterator vitr = value.as(OntProperty.class).listRange();\n\t\t\t\t\twhile (vitr.hasNext()) {\n\t\t\t\t\t\tvalueRngLst.add(vitr.next());\n\t\t\t\t\t}\n\t\t\t\t\tvitr.close();\n\t\t\t\t\tboolean overlap = false;\n\t\t\t\t\twhile (ipvs.hasNext()) {\n\t\t\t\t\t\tRDFNode ipv = ipvs.next();\n\t\t\t\t\t\tif (ipv.canAs(OntProperty.class)){\n\t\t\t\t\t\t\tExtendedIterator ipvitr = ipv.as(OntProperty.class).listRange();\n\t\t\t\t\t\t\twhile (ipvitr.hasNext()) {\n\t\t\t\t\t\t\t\tOntResource ipvr = ipvitr.next();\n\t\t\t\t\t\t\t\tif (valueRngLst.contains(ipvr)) {\n\t\t\t\t\t\t\t\t\taddError(\"Ambiguous condition--multiple implied properties (\" + \n\t\t\t\t\t\t\t\t\t\t\tvalue.as(OntProperty.class).getLocalName() + \",\" + ipv.as(OntProperty.class).getLocalName() + \n\t\t\t\t\t\t\t\t\t\t\t\") have the same range (\" + ipvr.getLocalName() + \")\", ctx);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\taddImpliedPropertyClass(inst);\n\t\t}\n\t\tinst.addProperty(prop, value);\n\t\tlogger.debug(\"added value '\" + value.toString() + \"' to property '\" + prop.toString() + \"' for instance '\" + inst.toString() + \"'\");\n\t}\n\n\tprivate void addUnittedQuantityAsInstancePropertyValue(Individual inst, OntProperty oprop, OntResource rng, BigDecimal number, String unit) {\n\t\taddUnittedQuantityAsInstancePropertyValue(inst, oprop, rng, number.toPlainString(), unit);\n\t}\n\n\tprivate void addImpliedPropertyClass(Individual inst) {\n\t\tif(!allImpliedPropertyClasses.contains(inst)) {\n\t\t\tallImpliedPropertyClasses.add(inst);\n\t\t}\n\t}\n\t\n\tprivate void addUnittedQuantityAsInstancePropertyValue(Individual inst, OntProperty oprop, OntResource rng, String literalNumber, String unit) {\n\t\tIndividual unittedVal;\n\t\tif (rng != null && rng.canAs(OntClass.class)) {\n\t\t\tunittedVal = getTheJenaModel().createIndividual(rng.as(OntClass.class));\n\t\t}\n\t\telse {\n\t\t\tunittedVal = getTheJenaModel().createIndividual(getTheJenaModel().getOntClass(SadlConstants.SADL_IMPLICIT_MODEL_UNITTEDQUANTITY_URI));\n\t\t}\n\t\t// TODO this may need to check for property restrictions on a subclass of UnittedQuantity\n\t\tunittedVal.addProperty(getTheJenaModel().getProperty(SadlConstants.SADL_IMPLICIT_MODEL_VALUE_URI), getTheJenaModel().createTypedLiteral(literalNumber));\n\t\tunittedVal.addProperty(getTheJenaModel().getProperty(SadlConstants.SADL_IMPLICIT_MODEL_UNIT_URI), getTheJenaModel().createTypedLiteral(unit));\n\t\tinst.addProperty(oprop, unittedVal);\n\t}\n\t\n\tprivate void dumpModel(OntModel m) {\n\t\tSystem.out.println(\"Dumping OntModel\");\n\t\tPrintStream strm = System.out;\n\t\tm.write(strm);\n\t\tExtendedIterator itr = m.listSubModels();\n\t\twhile (itr.hasNext()) {\n\t\t\tdumpModel(itr.next());\n\t\t}\n\t}\n\t\n\tprivate SadlResource sadlResourceFromSadlInstance(SadlInstance element) throws JenaProcessorException {\n\t\tSadlResource sr = element.getNameOrRef();\n\t\tif (sr == null) {\n\t\t\tsr = element.getInstance();\n\t\t}\n\t\treturn sr;\n\t}\n\n\tprivate void processSadlDisjointClasses(SadlDisjointClasses element) throws JenaProcessorException {\n\t\tList disjointClses = new ArrayList();\n\t\tif (element.getClasses() != null) {\n\t\t\tIterator dcitr = element.getClasses().iterator();\n\t\t\twhile (dcitr.hasNext()) {\n\t\t\t\tSadlResource sr = dcitr.next();\n\t\t\t\tString declUri = getDeclarationExtensions().getConceptUri(sr);\n\t\t\t\tif (declUri == null) {\n\t\t\t\t\tthrow new JenaProcessorException(\"Failed to get concept URI of SadlResource in processSadlDisjointClasses\");\n\t\t\t\t}\n\t\t\t\tOntClass cls = getTheJenaModel().getOntClass(declUri);\n\t\t\t\tif (cls == null) {\n\t\t\t\t\tthrow new JenaProcessorException(\"Failed to get class '\" + declUri + \"' from Jena model.\");\n\t\t\t\t}\n\t\t\t\tdisjointClses.add(cls.asClass());\n\t\t\t}\n\t\t}\n\t\tIterator dcitr = element.getTypes().iterator();\n\t\twhile(dcitr.hasNext()) {\n\t\t\tSadlClassOrPropertyDeclaration decl = dcitr.next();\n\t\t\tIterator djitr = decl.getClassOrProperty().iterator();\n\t\t\twhile (djitr.hasNext()) {\n\t\t\t\tSadlResource sr = djitr.next();\n\t\t\t\tString declUri = getDeclarationExtensions().getConceptUri(sr);\n\t\t\t\tif (declUri == null) {\n\t\t\t\t\tthrow new JenaProcessorException(\"Failed to get concept URI of SadlResource in processSadlDisjointClasses\");\n\t\t\t\t}\n\t\t\t\tOntClass cls = getTheJenaModel().getOntClass(declUri);\n\t\t\t\tdisjointClses.add(cls.asClass());\n\t\t\t}\n\t\t}\n\t\t// must set them disjoint pairwise\n\t\tfor (int i = 0; i < disjointClses.size(); i++) {\n\t\t\tfor (int j = i + 1; j < disjointClses.size(); j++) {\n\t\t\t\tdisjointClses.get(i).addDisjointWith(disjointClses.get(j));\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate ObjectProperty getOrCreateObjectProperty(String propName) {\n\t\tObjectProperty prop = getTheJenaModel().getObjectProperty(propName);\n\t\tif (prop == null) {\n\t\t\tprop = getTheJenaModel().createObjectProperty(propName);\n\t\t\tlogger.debug(\"New object property '\" + prop.getURI() + \"' created\");\n\t\t}\n\t\treturn prop;\n\t}\n\n\tprivate DatatypeProperty getOrCreateDatatypeProperty(String propUri) throws JenaProcessorException {\n\t\tDatatypeProperty prop = getTheJenaModel().getDatatypeProperty(propUri);\n\t\tif (prop == null) {\n\t\t\tprop = createDatatypeProperty(propUri, null);\n\t\t}\n\t\treturn prop;\n\t}\n\t\n\tprivate OntProperty getOrCreateRdfProperty(String propUri) {\n\t\tProperty op = getTheJenaModel().getProperty(propUri);\n\t\tif (op != null && op.canAs(OntProperty.class)) {\n\t\t\treturn op.as(OntProperty.class);\n\t\t}\n\t\treturn createRdfProperty(propUri, null);\n\t}\n\n\tprivate boolean checkForExistingCompatibleDatatypeProperty(\n\t\t\tString propUri, RDFNode rngNode) {\n\t\tDatatypeProperty prop = getTheJenaModel().getDatatypeProperty(propUri);\n\t\tif (prop != null) {\n\t\t\tOntResource rng = prop.getRange();\n\t\t\tif (rng != null && rng.equals(rngNode)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate void addPropertyDomain(Property prop, OntResource cls, EObject context) throws JenaProcessorException {\n\t\tboolean addNewDomain = true;\n\t\tStmtIterator sitr = getTheJenaModel().listStatements(prop, RDFS.domain, (RDFNode)null);\n\t\tboolean domainExists = false;\n\t\tif (sitr.hasNext()) {\n\t\t\tRDFNode existingDomain = sitr.next().getObject();\n\t\t\tdomainExists = true;\n\t\t\t// property already has a domain known to this model\n\t\t\tif (cls.equals(existingDomain)) {\n\t\t\t\t// do nothing--cls is already in domain\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\tif (existingDomain.canAs(OntClass.class)) {\n\t\t\t\t// is the new domain a subclass of the existing domain?\n\t\t\t\tif (cls.canAs(OntClass.class) && checkForSubclassing(cls.as(OntClass.class), existingDomain.as(OntClass.class), context) ) {\n\t\t\t\t\tStringBuilder sb = new StringBuilder(\"This specified domain of '\");\n\t\t\t\t\tsb.append(nodeToString(prop));\n\t\t\t\t\tsb.append(\"' is a subclass of the domain which is already defined\");\n\t\t\t\t\tString dmnstr = nodeToString(existingDomain);\n\t\t\t\t\tif (dmnstr != null) {\n\t\t\t\t\t\tsb.append(\" (\");\n\t\t\t\t\t\tsb.append(dmnstr);\n\t\t\t\t\t\tsb.append(\") \");\n\t\t\t\t\t}\n\t\t\t\t\taddWarning(sb.toString(), context);\t\t\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tboolean domainInThisModel = false;\n\t\t\tStmtIterator inModelStmtItr = getTheJenaModel().getBaseModel().listStatements(prop, RDFS.domain, (RDFNode)null);\n\t\t\tif (inModelStmtItr.hasNext()) {\n\t\t\t\tdomainInThisModel = true;\n\t\t\t}\n\t\t\tif (domainAndRangeAsUnionClasses) {\n\t\t\t\t// in this case we want to create a union class if necessary\n\t\t\t\tif (domainInThisModel) {\n\t\t\t\t\t// this model (as opposed to imports) already has a domain specified\n\t\t\t\t\taddNewDomain = false;\n\t\t\t\t\tUnionClass newUnionClass = null;\n\t\t\t\t\twhile (inModelStmtItr.hasNext()) {\n\t\t\t\t\t\tRDFNode dmn = inModelStmtItr.nextStatement().getObject();\n\t\t\t\t\t\tif (dmn.isResource()) {\t// should always be a Resource\n\t\t\t\t\t\t\tif (dmn.canAs(OntResource.class)){\n\t\t\t\t\t\t\t\tif (existingDomain.toString().equals(dmn.toString())) {\n\t\t\t\t\t\t\t\t\tdmn = existingDomain;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tnewUnionClass = createUnionClass(dmn.as(OntResource.class), cls);\n\t\t\t\t\t\t\t\tlogger.debug(\"Domain '\" + cls.toString() + \"' added to property '\" + prop.getURI() + \"'\");\n\t\t\t\t\t\t\t\tif (!newUnionClass.equals(dmn)) {\n\t\t\t\t\t\t\t\t\taddNewDomain = true;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tthrow new JenaProcessorException(\"Encountered non-OntResource in domain of '\" + prop.getURI() + \"'\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tthrow new JenaProcessorException(\"Encountered non-Resource in domain of '\" + prop.getURI() + \"'\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (addNewDomain) {\n\t\t\t\t\t\tgetTheJenaModel().remove(getTheJenaModel().getBaseModel().listStatements(prop, RDFS.domain, (RDFNode)null));\n\t\t\t\t\t\tcls = newUnionClass;\n\t\t\t\t\t}\n\t\t\t\t}\t// end if existing domain in this model\n\t\t\t\telse {\n\t\t\t\t\tinModelStmtItr.close();\n\t\t\t\t\t// check to see if this is something new\n\t\t\t\t\tdo {\n\t\t\t\t\t\tif (existingDomain.equals(cls)) {\n\t\t\t\t\t\t\tsitr.close();\n\t\t\t\t\t\t\treturn;\t// already in domain, nothing to add\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (sitr.hasNext()) {\n\t\t\t\t\t\t\texistingDomain = sitr.next().getObject();\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\texistingDomain = null;\n\t\t\t\t\t\t}\n\t\t\t\t\t} while (existingDomain != null);\n\t\t\t\t}\n\t\t\t}\t// end if domainAndRangeAsUnionClasses\n\t\t\telse {\n\t\t\t\tinModelStmtItr.close();\n\t\t\t}\n\t\t\tif (domainExists && !domainInThisModel) {\n\t\t\t\taddWarning(SadlErrorMessages.IMPORTED_DOMAIN_CHANGE.get(nodeToString(prop)), context);\n\t\t\t}\n\t\t}\t// end if existing domain in any model, this or imports\n\t\tif(cls != null){\n\t\t\tif (!domainAndRangeAsUnionClasses && cls instanceof UnionClass) {\n\t\t\t\tList uclsmembers = getUnionClassMemebers((UnionClass)cls);\n\t\t\t\tfor (int i = 0; i < uclsmembers.size(); i++) {\n\t\t\t\t\tgetTheJenaModel().add(prop, RDFS.domain, uclsmembers.get(i));\n\t\t\t\t\tlogger.debug(\"Domain '\" + uclsmembers.get(i).toString() + \"' added to property '\" + prop.getURI() + \"'\");\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (addNewDomain) {\n\t\t\t\tgetTheJenaModel().add(prop, RDFS.domain, cls);\t\n\t\t\t\tlogger.debug(\"Domain '\" + cls.toString() + \"' added to property '\" + prop.getURI() + \"'\");\n\t\t\t\tlogger.debug(\"Domain of '\" + prop.toString() + \"' is now: \" + nodeToString(cls));\n\t\t\t}\n\t\t}else{\n\t\t\tlogger.debug(\"Domain is not defined for property '\" + prop.toString() + \"'\");\n\t\t}\n\t}\n\n\tprivate List getUnionClassMemebers(UnionClass cls) {\n\t\tList members = null;\n\t\tExtendedIterator itr = ((UnionClass)cls).listOperands();\n\t\twhile (itr.hasNext()) {\n\t\t\tcom.hp.hpl.jena.rdf.model.Resource ucls = itr.next();\n\t\t\tif (ucls instanceof UnionClass || ucls.canAs(UnionClass.class)) {\n\t\t\t\tList nested = getUnionClassMemebers(ucls.as(UnionClass.class));\n\t\t\t\tif (members == null) {\n\t\t\t\t\tmembers = nested;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tmembers.addAll(nested);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (members == null) members = new ArrayList();\n\t\t\t\tmembers.add(ucls);\n\t\t\t}\n\t\t}\n\t\tif (cls.isAnon()) {\n\t\t\tfor (int i = 0; i < members.size(); i++) {\n\t\t\t\t((UnionClass)cls).removeOperand(members.get(i));\n\t\t\t}\n\t\t\tgetTheJenaModel().removeAll(cls, null, null);\n\t\t\tgetTheJenaModel().removeAll(null, null, cls);\n\t\t\tcls.remove();\n\t\t}\n\t\treturn members;\n\t}\n\t\n\tprivate OntResource createUnionOfClasses(OntResource cls, List existingClasses) throws JenaProcessorException {\n\t\tOntResource unionClass = null;\n\t\tRDFList classes = null;\n\t\tIterator ecitr = existingClasses.iterator();\n\t\tboolean allEqual = true;\n\t\twhile (ecitr.hasNext()) {\n\t\t\tOntResource existingCls = ecitr.next();\n\t\t\tif (!existingCls.canAs(OntResource.class)){\n\t\t\t\tthrow new JenaProcessorException(\"Unable to convert '\" + existingCls.toString() + \"' to OntResource to put into union of classes\");\n\t\t\t}\n\t\t\tif (existingCls.equals(cls)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tallEqual = false;\n\t\t\t}\n\t\t\tif (existingCls.as(OntResource.class).canAs(UnionClass.class)) {\n\t\t\t\tList uclist = getOntResourcesInUnionClass(getTheJenaModel(), existingCls.as(UnionClass.class));\n\t\t\t\tif (classes == null) {\n\t\t\t\t\tclasses = getTheJenaModel().createList();\n\t\t\t\t\tclasses = classes.with(cls);\n\t\t\t\t}\n\t\t\t\tfor (int i = 0; i < uclist.size(); i++) {\n\t\t\t\t\tclasses = classes.with(uclist.get(i));\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (classes == null) {\n\t\t\t\t\tclasses = getTheJenaModel().createList();\n\t\t\t\t\tclasses = classes.with(cls);\n\t\t\t\t}\n\t\t\t\tclasses = classes.with(existingCls.as(OntResource.class));\n\t\t\t}\n\t\t}\n\t\tif (allEqual) {\n\t\t\treturn cls;\n\t\t}\n\t\tif (classes != null) {\n\t\t\tunionClass = getTheJenaModel().createUnionClass(null, classes);\n\t\t}\n\t\treturn unionClass;\n\t}\n\t\n\tprivate OntResource createUnionOfClasses(OntResource cls, ExtendedIterator ditr) throws JenaProcessorException {\n\t\tOntResource unionClass = null;\n\t\tRDFList classes = null;\n\t\tboolean allEqual = true;\n\t\twhile (ditr.hasNext()) {\n\t\t\tOntResource existingCls = ditr.next();\n\t\t\tif (!existingCls.canAs(OntResource.class)){\n\t\t\t\tthrow new JenaProcessorException(\"Unable to '\" + existingCls.toString() + \"' to OntResource to put into union of classes\");\n\t\t\t}\n\t\t\tif (existingCls.equals(cls)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tallEqual = false;\n\t\t\t}\n\t\t\tif (existingCls.as(OntResource.class).canAs(UnionClass.class)) {\n\t\t\t\tif (classes != null) {\n\t\t\t\t\tclasses.append(existingCls.as(UnionClass.class).getOperands());\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\ttry {\n\t\t\t\t\t\texistingCls.as(UnionClass.class).addOperand(cls);\n\t\t\t\t\t\tunionClass = existingCls.as(UnionClass.class);\n\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\t// don't know why this is happening\n\t\t\t\t\t\tlogger.error(\"Union class error that hasn't been resolved or understood.\");\t\t\t\t\t\n\t\t\t\t\t\treturn cls;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (classes == null) {\n\t\t\t\t\tclasses = getTheJenaModel().createList();\n\t\t\t\t}\n\t\t\t\tclasses = classes.with(existingCls.as(OntResource.class));\n\t\t\t\tclasses = classes.with(cls);\n\t\t\t}\n\t\t}\n\t\tif (allEqual) {\n\t\t\treturn cls;\n\t\t}\n\t\tif (classes != null) {\n\t\t\tunionClass = getTheJenaModel().createUnionClass(null, classes);\n\t\t}\n\t\treturn unionClass;\n\t}\n\t\n\tprivate RDFNode primitiveDatatypeToRDFNode(String name) {\n\t\treturn getTheJenaModel().getResource(XSD.getURI() + name);\n\t}\n\n\tprivate OntClass getOrCreateOntClass(String name) {\n\t\tOntClass cls = getTheJenaModel().getOntClass(name);\n\t\tif (cls == null) {\n\t\t\tcls = createOntClass(name, (OntClass)null);\n\t\t}\n\t\treturn cls;\n\t}\n\t\n\tprivate OntClass createOntClass(String newName, String superSRUri, EObject superSR) {\n\t\tif (superSRUri != null) {\n\t\t\tOntClass superCls = getTheJenaModel().getOntClass(superSRUri);\n\t\t\tif (superCls == null) {\n\t\t\t\tsuperCls = getTheJenaModel().createClass(superSRUri);\n\t\t\t}\n\t\t\treturn createOntClass(newName, superCls);\n\t\t}\n\t\treturn createOntClass(newName, (OntClass)null);\n\t}\n\t\n\tprivate OntClass createOntClass(String newName, OntClass superCls) {\n\t\tOntClass newCls = getTheJenaModel().createClass(newName);\n\t\tlogger.debug(\"New class '\" + newCls.getURI() + \"' created\");\n\t\tif (superCls != null) {\n\t\t\tnewCls.addSuperClass(superCls);\n\t\t\tlogger.debug(\" Class '\" + newCls.getURI() + \"' given super class '\" + superCls.toString() + \"'\");\n\t\t}\n\t\treturn newCls;\n\t}\n\t\n\tprivate OntClass getOrCreateListSubclass(String newName, String typeUri, Resource resource) throws JenaProcessorException {\n\t\tif (sadlListModel == null) {\n\t\t\ttry {\n\t\t\t\timportSadlListModel(resource);\n\t\t\t} catch (Exception e) {\n\t\t\t\te.printStackTrace();\n\t\t\t\tthrow new JenaProcessorException(\"Failed to load SADL List model\", e);\n\t\t\t}\n\t\t}\n\t\tOntClass lstcls = getTheJenaModel().getOntClass(SadlConstants.SADL_LIST_MODEL_LIST_URI);\n\t\tExtendedIterator lscitr = lstcls.listSubClasses();\n\t\twhile (lscitr.hasNext()) {\n\t\t\tOntClass scls = lscitr.next();\n\t\t\tif (newName != null && scls.isURIResource() && newName.equals(scls.getURI())) {\n\t\t\t\t// same class\n\t\t\t\treturn scls;\n\t\t\t}\n\t\t\tif (newName == null && scls.isAnon()) {\n\t\t\t\t// both are unnamed, check type (and length restrictions in future)\n\t\t\t\tExtendedIterator spcitr = scls.listSuperClasses(true);\n\t\t\t\twhile (spcitr.hasNext()) {\n\t\t\t\t\tOntClass spcls = spcitr.next();\n\t\t\t\t\tif (spcls.isRestriction() && spcls.asRestriction().isAllValuesFromRestriction()) {\n\t\t\t\t\t\tOntProperty onprop = spcls.asRestriction().getOnProperty();\n\t\t\t\t\t\tif (onprop.isURIResource() && onprop.getURI().equals(SadlConstants.SADL_LIST_MODEL_FIRST_URI)) {\n\t\t\t\t\t\t\tcom.hp.hpl.jena.rdf.model.Resource avf = spcls.asRestriction().asAllValuesFromRestriction().getAllValuesFrom();\n\t\t\t\t\t\t\tif (avf.isURIResource() && avf.getURI().equals(typeUri)) {\n\t\t\t\t\t\t\t\tspcitr.close();\n\t\t\t\t\t\t\t\tlscitr.close();\n\t\t\t\t\t\t\t\treturn scls;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tOntClass newcls = createOntClass(newName, lstcls);\n\t\tcom.hp.hpl.jena.rdf.model.Resource typeResource = getTheJenaModel().getResource(typeUri);\n\t\tProperty pfirst = getTheJenaModel().getProperty(SadlConstants.SADL_LIST_MODEL_FIRST_URI);\n\t\tAllValuesFromRestriction avf = getTheJenaModel().createAllValuesFromRestriction(null, pfirst, typeResource);\n\t\tnewcls.addSuperClass(avf);\n\t\tProperty prest = getTheJenaModel().getProperty(SadlConstants.SADL_LIST_MODEL_REST_URI);\n\t\tAllValuesFromRestriction avf2 = getTheJenaModel().createAllValuesFromRestriction(null, prest, newcls);\n\t\tnewcls.addSuperClass(avf2);\n\t\treturn newcls;\n\t}\n\t\n\tprivate OntProperty createObjectProperty(String newName, String superSRUri) throws JenaProcessorException {\n\t\tOntProperty newProp = getTheJenaModel().createObjectProperty(newName);\n\t\tlogger.debug(\"New object property '\" + newProp.getURI() + \"' created\");\n\t\tif (superSRUri != null) {\n\t\t\tOntProperty superProp = getTheJenaModel().getOntProperty(superSRUri);\n\t\t\tif (superProp == null) {\n//\t\t\t\tthrow new JenaProcessorException(\"Unable to find super property '\" + superSRUri + \"'\");\n\t\t\t\tgetTheJenaModel().createObjectProperty(superSRUri);\n\t\t\t}\n\t\t\tnewProp.addSuperProperty(superProp);\n\t\t\tlogger.debug(\" Object property '\" + newProp.getURI() + \"' given super property '\" + superSRUri + \"'\");\n\t\t}\n\t\treturn newProp;\n\t}\n\t\n\tprivate AnnotationProperty createAnnotationProperty(String newName, String superSRUri) {\n\t\tAnnotationProperty annProp = getTheJenaModel().createAnnotationProperty(newName);\n\t\tlogger.debug(\"New annotation property '\" + annProp.getURI() + \"' created\");\n\t\tif (superSRUri != null) {\n\t\t\tProperty superProp = getTheJenaModel().getProperty(superSRUri);\n\t\t\tif (superProp == null) {\n\t\t\t\tsuperProp = getTheJenaModel().createOntProperty(superSRUri);\n\t\t\t}\n\t\t\tgetTheJenaModel().add(annProp, RDFS.subPropertyOf, superProp);\n\t\t\tlogger.debug(\" Property '\" + annProp.getURI() + \"' given super property '\" + superSRUri + \"'\");\n\t\t}\n\t\treturn annProp;\n\t}\n\t\n\tprivate OntProperty createRdfProperty(String newName, String superSRUri) {\n\t\tOntProperty newProp = getTheJenaModel().createOntProperty(newName);\n\t\tlogger.debug(\"New object property '\" + newProp.getURI() + \"' created\");\n\t\tif (superSRUri != null) {\n\t\t\tProperty superProp = getTheJenaModel().getProperty(superSRUri);\n\t\t\tif (superProp == null) {\n\t\t\t\tsuperProp = getTheJenaModel().createOntProperty(superSRUri);\n\t\t\t}\n\t\t\tgetTheJenaModel().add(newProp, RDFS.subPropertyOf, superProp);\n\t\t\tlogger.debug(\" Property '\" + newProp.getURI() + \"' given super property '\" + superSRUri + \"'\");\n\t\t}\n\t\treturn newProp;\n\t}\n\t\n\tprivate DatatypeProperty createDatatypeProperty(String newName, String superSRUri) throws JenaProcessorException {\n\t\tDatatypeProperty newProp = getTheJenaModel().createDatatypeProperty(newName);\n\t\tlogger.debug(\"New datatype property '\" + newProp.getURI() + \"' created\");\n\t\tif (superSRUri != null) {\n\t\t\tOntProperty superProp = getTheJenaModel().getOntProperty(superSRUri);\n\t\t\tif (superProp == null) {\n//\t\t\t\tthrow new JenaProcessorException(\"Unable to find super property '\" + superSRUri + \"'\");\n\t\t\t\tif (superProp == null) {\n\t\t\t\t\tgetTheJenaModel().createDatatypeProperty(superSRUri);\n\t\t\t\t}\n\t\t\t}\n\t\t\tnewProp.addSuperProperty(superProp);\n\t\t\tlogger.debug(\" Datatype property '\" + newProp.getURI() + \"' given super property '\" + superSRUri + \"'\");\n\t\t}\n\t\treturn newProp;\n\t}\n\t\n\tprivate Individual createIndividual(SadlResource srsrc, OntClass type) throws JenaProcessorException, TranslationException {\n\t\tNode n = processExpression(srsrc);\n\t\tif (n == null) {\n\t\t\tthrow new JenaProcessorException(\"SadlResource failed to convert to Node\");\n\t\t}\n\t\tIndividual inst = createIndividual(n.toFullyQualifiedString(), type);\n\t\tEList anns = srsrc.getAnnotations();\n\t\tif (anns != null) {\n\t\t\taddAnnotationsToResource(inst, anns);\n\t\t}\n\t\treturn inst;\n\t}\n\t\n\tprivate Individual createIndividual(String newName, OntClass supercls) {\n\t\tIndividual inst = getTheJenaModel().createIndividual(newName, supercls);\n\t\tlogger.debug(\"New instance '\" + (newName != null ? newName : \"(bnode)\") + \"' created\");\n\t\treturn inst;\n\t}\n\t\n\tprivate OntResource sadlTypeReferenceToOntResource(SadlTypeReference sadlTypeRef) throws JenaProcessorException {\n\t\tcom.hp.hpl.jena.rdf.model.Resource obj = sadlTypeReferenceToResource(sadlTypeRef);\n\t\tif (obj == null) {\n\t\t\treturn null;\t// this happens when sadlTypeRef is a variable (even if unintended)\n\t\t}\n\t\tif (obj instanceof OntResource) {\n\t\t\treturn (OntResource)obj;\n\t\t}\n\t\telse if (obj instanceof RDFNode) {\n\t\t\tif (((RDFNode)obj).canAs(OntResource.class)) {\n\t\t\t\treturn ((RDFNode)obj).as(OntResource.class);\n\t\t\t}\n\t\t}\n\t\tthrow new JenaProcessorException(\"Unable to convert SadlTypeReference '\" + sadlTypeRef + \"' to OntResource\");\n\t}\n\t\n\tprivate com.hp.hpl.jena.rdf.model.Resource sadlTypeReferenceToResource(SadlTypeReference sadlTypeRef) throws JenaProcessorException {\n\t\tObject obj = sadlTypeReferenceToObject(sadlTypeRef);\n\t\tif (obj == null) {\n\t\t\treturn null;\t// this happens when sadlTypeRef is a variable (even if unintended)\n\t\t}\n\t\tif (obj instanceof com.hp.hpl.jena.rdf.model.Resource) {\n\t\t\treturn (com.hp.hpl.jena.rdf.model.Resource) obj;\n\t\t}\n\t\telse if (obj instanceof RDFNode) {\n\t\t\tif (((RDFNode)obj).canAs(com.hp.hpl.jena.rdf.model.Resource.class)) {\n\t\t\t\treturn ((RDFNode)obj).as(com.hp.hpl.jena.rdf.model.Resource.class);\n\t\t\t}\n\t\t}\n\t\tthrow new JenaProcessorException(\"Unable to convert SadlTypeReference '\" + sadlTypeRef + \"' to OntResource\");\n\t}\n\t\n\tprivate ConceptName sadlSimpleTypeReferenceToConceptName(SadlTypeReference sadlTypeRef) throws JenaProcessorException {\n\t\tif (sadlTypeRef instanceof SadlSimpleTypeReference) {\n\t\t\tSadlResource strSR = ((SadlSimpleTypeReference)sadlTypeRef).getType();\n\t\t\tOntConceptType ctype;\n\t\t\ttry {\n\t\t\t\tctype = getDeclarationExtensions().getOntConceptType(strSR);\n\t\t\t} catch (CircularDefinitionException e) {\n\t\t\t\tctype = e.getDefinitionType();\n\t\t\t\taddError(e.getMessage(), sadlTypeRef);\n\t\t\t}\n\t\t\tString strSRUri = getDeclarationExtensions().getConceptUri(strSR);\t\n\t\t\tif (strSRUri == null) {\n\t\t\t\tif (ctype.equals(OntConceptType.VARIABLE)) {\n\t\t\t\t\t//throw new JenaProcessorException(\"Failed to get variable URI of SadlResource in sadlSimpleTypeReferenceToConceptName\");\n\t\t\t\t\t// be silent? during clean these URIs won't be found\n\t\t\t\t}\n//\t\t\t\tthrow new JenaProcessorException(\"Failed to get concept URI of SadlResource in sadlSimpleTypeReferenceToConceptName\");\n\t\t\t\t// be silent? during clean these URIs won't be found\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (ctype.equals(OntConceptType.CLASS)) {\n\t\t\t\tConceptName cn = new ConceptName(strSRUri);\n\t\t\t\tcn.setType(ConceptType.ONTCLASS);\n\t\t\t\treturn cn;\n\t\t\t}\n\t\t\telse if (ctype.equals(OntConceptType.CLASS_LIST)) {\n\t\t\t\tConceptName cn = new ConceptName(strSRUri);\n\t\t\t\tcn.setType(ConceptType.ONTCLASS);\n\t\t\t\tcn.setRangeValueType(RangeValueType.LIST);\n\t\t\t\treturn cn;\n\t\t\t}\n\t\t\telse if (ctype.equals(OntConceptType.DATATYPE_LIST)) {\n\t\t\t\tConceptName cn = new ConceptName(strSRUri);\n\t\t\t\tcn.setType(ConceptType.RDFDATATYPE);\n\t\t\t\tcn.setRangeValueType(RangeValueType.LIST);\n\t\t\t\treturn cn;\n\t\t\t}\n\t\t\telse if (ctype.equals(OntConceptType.INSTANCE)) {\n\t\t\t\tConceptName cn = new ConceptName(strSRUri);\n\t\t\t\tcn.setType(ConceptType.INDIVIDUAL);\n\t\t\t\treturn cn;\n\t\t\t}\n\t\t\telse if (ctype.equals(OntConceptType.DATATYPE)) {\t\t\t\t\n\t\t\t\tConceptName cn = new ConceptName(strSRUri);\n\t\t\t\tcn.setType(ConceptType.RDFDATATYPE);\n\t\t\t\treturn cn;\n\t\t\t}\n\t\t\telse if (ctype.equals(OntConceptType.CLASS_PROPERTY)) {\n\t\t\t\tConceptName cn = new ConceptName(strSRUri);\n\t\t\t\tcn.setType(ConceptType.OBJECTPROPERTY);\n\t\t\t\treturn cn;\n\t\t\t}\n\t\t\telse if (ctype.equals(OntConceptType.DATATYPE_PROPERTY)) {\n\t\t\t\tConceptName cn = new ConceptName(strSRUri);\n\t\t\t\tcn.setType(ConceptType.DATATYPEPROPERTY);\n\t\t\t\treturn cn;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthrow new JenaProcessorException(\"SadlSimpleTypeReference '\" + strSRUri + \"' was of a type not yet handled: \" + ctype.toString());\n\t\t\t}\n\t\t}\n\t\telse if (sadlTypeRef instanceof SadlPrimitiveDataType) {\n\t\t\tcom.hp.hpl.jena.rdf.model.Resource trr = getSadlPrimitiveDataTypeResource((SadlPrimitiveDataType) sadlTypeRef);\n\t\t\tConceptName cn = new ConceptName(trr.getURI());\n\t\t\tcn.setType(ConceptType.RDFDATATYPE);\n\t\t\treturn cn;\n\t\t}\n\t\telse {\n\t\t\tthrow new JenaProcessorException(\"SadlTypeReference is not a URI resource\");\n\t\t}\n\t}\n\t\n\tprivate OntConceptType sadlTypeReferenceOntConceptType(SadlTypeReference sadlTypeRef) throws CircularDefinitionException {\n\t\tif (sadlTypeRef instanceof SadlSimpleTypeReference) {\n\t\t\tSadlResource strSR = ((SadlSimpleTypeReference)sadlTypeRef).getType();\n\t\t\treturn getDeclarationExtensions().getOntConceptType(strSR);\n\t\t}\n\t\telse if (sadlTypeRef instanceof SadlPrimitiveDataType) {\n\t\t\treturn OntConceptType.DATATYPE;\n\t\t}\n\t\telse if (sadlTypeRef instanceof SadlPropertyCondition) {\n\t\t\tSadlResource sr = ((SadlPropertyCondition)sadlTypeRef).getProperty();\n\t\t\treturn getDeclarationExtensions().getOntConceptType(sr);\t\t\n\t\t}\n\t\telse if (sadlTypeRef instanceof SadlUnionType || sadlTypeRef instanceof SadlIntersectionType) {\n\t\t\treturn OntConceptType.CLASS;\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprotected Object sadlTypeReferenceToObject(SadlTypeReference sadlTypeRef) throws JenaProcessorException {\n\t\tOntResource rsrc = null;\n\t\t// TODO How do we tell if this is a union versus an intersection?\t\t\t\t\t\t\n\t\tif (sadlTypeRef instanceof SadlSimpleTypeReference) {\n\t\t\tSadlResource strSR = ((SadlSimpleTypeReference)sadlTypeRef).getType();\n\t\t\t//TODO check for proxy, i.e. unresolved references\n\t\t\tOntConceptType ctype;\n\t\t\ttry {\n\t\t\t\tctype = getDeclarationExtensions().getOntConceptType(strSR);\n\t\t\t} catch (CircularDefinitionException e) {\n\t\t\t\tctype = e.getDefinitionType();\n\t\t\t\taddError(e.getMessage(), sadlTypeRef);\n\t\t\t}\n\t\t\tString strSRUri = getDeclarationExtensions().getConceptUri(strSR);\t\n\t\t\tif (strSRUri == null) {\n\t\t\t\tif (ctype.equals(OntConceptType.VARIABLE)) {\n\t\t\t\t\taddError(\"Range should not be a variable.\", sadlTypeRef);\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\tthrow new JenaProcessorException(\"Failed to get concept URI of SadlResource in sadlTypeReferenceToObject\");\n\t\t\t}\n\t\t\tif (ctype.equals(OntConceptType.CLASS)) {\n\t\t\t\tif (((SadlSimpleTypeReference) sadlTypeRef).isList()) {\n\t\t\t\t\trsrc = getOrCreateListSubclass(null, strSRUri, sadlTypeRef.eResource());\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\trsrc = getTheJenaModel().getOntClass(strSRUri);\n\t\t\t\t\tif (rsrc == null) {\n\t\t\t\t\t\treturn createOntClass(strSRUri, (OntClass)null);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (ctype.equals(OntConceptType.CLASS_LIST)) {\n\t\t\t\trsrc = getTheJenaModel().getOntClass(strSRUri);\n\t\t\t\tif (rsrc == null) {\n\t\t\t\t\treturn getOrCreateListSubclass(strSRUri, strSRUri, strSR.eResource());\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (ctype.equals(OntConceptType.DATATYPE_LIST)) {\n\t\t\t\trsrc = getTheJenaModel().getOntClass(strSRUri);\n\t\t\t\tif (rsrc == null) {\n\t\t\t\t\treturn getOrCreateListSubclass(strSRUri, strSRUri, strSR.eResource());\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (ctype.equals(OntConceptType.INSTANCE)) {\n\t\t\t\trsrc = getTheJenaModel().getIndividual(strSRUri);\n\t\t\t\tif (rsrc == null) {\n\t\t\t\t\t// is it OK to create Individual without knowing class??\n\t\t\t\t\treturn createIndividual(strSRUri, (OntClass)null);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (ctype.equals(OntConceptType.DATATYPE)) {\t\t\t\t\n\t\t\t\tOntResource dt = getTheJenaModel().getOntResource(strSRUri);\n\t\t\t\tif (dt == null) {\n\t\t\t\t\tthrow new JenaProcessorException(\"SadlSimpleTypeReference '\" + strSRUri + \"' not found; it should exist as there isn't enough information to create it.\");\n\t\t\t\t}\n\t\t\t\treturn dt;\n\t\t\t}\n\t\t\telse if (ctype.equals(OntConceptType.CLASS_PROPERTY)) {\n\t\t\t\tOntProperty otp = getTheJenaModel().getOntProperty(strSRUri);\n\t\t\t\tif (otp == null) {\n\t\t\t\t\tthrow new JenaProcessorException(\"SadlSimpleTypeReference '\" + strSRUri + \"' not found; should have found an ObjectProperty\");\n\t\t\t\t}\n\t\t\t\treturn otp;\n\t\t\t}\n\t\t\telse if (ctype.equals(OntConceptType.DATATYPE_PROPERTY)) {\n\t\t\t\tOntProperty dtp = getTheJenaModel().getOntProperty(strSRUri);\n\t\t\t\tif (dtp == null) {\n\t\t\t\t\tthrow new JenaProcessorException(\"SadlSimpleTypeReference '\" + strSRUri + \"' not found; should have found an DatatypeProperty\");\n\t\t\t\t}\n\t\t\t\treturn dtp;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthrow new JenaProcessorException(\"SadlSimpleTypeReference '\" + strSRUri + \"' was of a type not yet handled: \" + ctype.toString());\n\t\t\t}\n\t\t}\n\t\telse if (sadlTypeRef instanceof SadlPrimitiveDataType) {\n\t\t\treturn processSadlPrimitiveDataType(null, (SadlPrimitiveDataType) sadlTypeRef, null);\n\t\t}\n\t\telse if (sadlTypeRef instanceof SadlPropertyCondition) {\n\t\t\treturn processSadlPropertyCondition((SadlPropertyCondition) sadlTypeRef);\t\t\n\t\t}\n\t\telse if (sadlTypeRef instanceof SadlUnionType) {\n\t\t\tRDFNode lftNode = null; RDFNode rhtNode = null;\n\t\t\tSadlTypeReference lft = ((SadlUnionType)sadlTypeRef).getLeft();\n\t\t\tObject lftObj = sadlTypeReferenceToObject(lft);\n\t\t\tif (lftObj == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (lftObj instanceof OntResource) {\n\t\t\t\tlftNode = ((OntResource)lftObj).asClass();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (lftObj instanceof RDFNode) {\n\t\t\t\t\tlftNode = (RDFNode) lftObj;\n\t\t\t\t}\n\t\t\t\telse if (lftObj instanceof List) {\n\t\t\t\t\t// carry on: RDFNode list from nested union\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrow new JenaProcessorException(\"Union member of unsupported type: \" + lftObj.getClass().getCanonicalName());\n\t\t\t\t}\n\t\t\t}\n\t\t\tSadlTypeReference rht = ((SadlUnionType)sadlTypeRef).getRight();\n\t\t\tObject rhtObj = sadlTypeReferenceToObject(rht);\n\t\t\tif (rhtObj == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (rhtObj instanceof OntResource && ((OntResource) rhtObj).canAs(OntClass.class)) {\n\t\t\t\trhtNode = ((OntResource)rhtObj).asClass();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (rhtObj instanceof RDFNode) {\n\t\t\t\t\trhtNode = (RDFNode) rhtObj;\n\t\t\t\t}\n\t\t\t\telse if (rhtObj instanceof List) {\n\t\t\t\t\t// carry on: RDFNode list from nested union\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrow new JenaProcessorException(\"Union member of unsupported type: \" + rhtObj != null ? rhtObj.getClass().getCanonicalName() : \"null\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (lftNode instanceof OntResource && rhtNode instanceof OntResource) {\n\t\t\t\tOntClass unionCls = createUnionClass(lftNode, rhtNode);\n\t\t\t\treturn unionCls;\n\t\t\t}\n\t\t\telse if (lftObj instanceof List && rhtNode instanceof RDFNode) {\n\t\t\t\t((List)lftObj).add(rhtNode);\n\t\t\t\treturn lftObj;\n\t\t\t}\n\t\t\telse if (lftObj instanceof RDFNode && rhtNode instanceof List) {\n\t\t\t\t((List)rhtNode).add(lftNode);\n\t\t\t\treturn rhtNode;\n\t\t\t}\n\t\t\telse if (lftNode instanceof RDFNode && rhtNode instanceof RDFNode){\n\t\t\t\tList rdfdatatypelist = new ArrayList();\n\t\t\t\trdfdatatypelist.add((RDFNode) lftNode);\n\t\t\t\trdfdatatypelist.add((RDFNode) rhtNode);\n\t\t\t\treturn rdfdatatypelist;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthrow new JenaProcessorException(\"Left and right sides of union are of incompatible types: \" + lftNode.toString() + \" and \" + rhtNode.toString());\n\t\t\t}\n\t\t}\n\t\telse if (sadlTypeRef instanceof SadlIntersectionType) {\n\t\t\tRDFNode lftNode = null; RDFNode rhtNode = null;\n\t\t\tSadlTypeReference lft = ((SadlIntersectionType)sadlTypeRef).getLeft();\n\t\t\tObject lftObj = sadlTypeReferenceToObject(lft);\n\t\t\tif (lftObj == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (lftObj instanceof OntResource) {\n\t\t\t\tlftNode = ((OntResource)lftObj).asClass();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (lftObj instanceof RDFNode) {\n\t\t\t\t\tlftNode = (RDFNode) lftObj;\n\t\t\t\t}\n\t\t\t\telse if (lftObj == null) {\n\t\t\t\t\taddError(\"SadlIntersectionType did not resolve to an ontology object (null)\", sadlTypeRef);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrow new JenaProcessorException(\"Intersection member of unsupported type: \" + lftObj.getClass().getCanonicalName());\n\t\t\t\t}\n\t\t\t}\n\t\t\tSadlTypeReference rht = ((SadlIntersectionType)sadlTypeRef).getRight();\n\t\t\tif (rht == null) {\n\t\t\t\tthrow new JenaProcessorException(\"No right-hand side to intersection\");\n\t\t\t}\n\t\t\tObject rhtObj = sadlTypeReferenceToObject(rht);\n\t\t\tif (rhtObj == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (rhtObj instanceof OntResource) {\n\t\t\t\trhtNode = ((OntResource)rhtObj).asClass();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (rhtObj instanceof RDFNode) {\n\t\t\t\t\trhtNode = (RDFNode) rhtObj;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrow new JenaProcessorException(\"Intersection member of unsupported type: \" + rhtObj.getClass().getCanonicalName());\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (lftNode instanceof OntResource && rhtNode instanceof OntResource) {\n\t\t\t\tOntClass intersectCls = createIntersectionClass(lftNode, rhtNode);\n\t\t\t\treturn intersectCls;\n\t\t\t}\n\t\t\telse if (lftNode instanceof RDFNode && rhtNode instanceof RDFNode){\n\t\t\t\tList rdfdatatypelist = new ArrayList();\n\t\t\t\trdfdatatypelist.add((RDFNode) lftNode);\n\t\t\t\trdfdatatypelist.add((RDFNode) rhtNode);\n\t\t\t\treturn rdfdatatypelist;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthrow new JenaProcessorException(\"Left and right sides of union are of incompatible types: \" + lftNode.toString() + \" and \" + rhtNode.toString());\n\t\t\t}\n\t\t}\n\t\treturn rsrc;\n\t}\n\n\tprivate com.hp.hpl.jena.rdf.model.Resource processSadlPrimitiveDataType(SadlClassOrPropertyDeclaration element, SadlPrimitiveDataType sadlTypeRef, String newDatatypeUri) throws JenaProcessorException {\n\t\tcom.hp.hpl.jena.rdf.model.Resource onDatatype = getSadlPrimitiveDataTypeResource(sadlTypeRef);\n\t\tif (sadlTypeRef.isList()) {\n\t\t\tonDatatype = getOrCreateListSubclass(null, onDatatype.toString(), sadlTypeRef.eResource());\n\t\t}\n\t\tif (newDatatypeUri == null) {\n\t\t\treturn onDatatype;\n\t\t}\n\t\tSadlDataTypeFacet facet = element.getFacet();\n\t\tOntClass datatype = createRdfsDatatype(newDatatypeUri, null, onDatatype, facet);\n\t\treturn datatype;\n\t}\n\t\n\tprivate com.hp.hpl.jena.rdf.model.Resource getSadlPrimitiveDataTypeResource(SadlPrimitiveDataType sadlTypeRef)\n\t\t\tthrows JenaProcessorException {\n\t\tSadlDataType pt = sadlTypeRef.getPrimitiveType();\n\t\tString typeStr = pt.getLiteral();\n\t\tcom.hp.hpl.jena.rdf.model.Resource onDatatype;\n\t\tif (typeStr.equals(XSD.xstring.getLocalName())) onDatatype = XSD.xstring;\n\t\telse if (typeStr.equals(XSD.anyURI.getLocalName())) onDatatype = XSD.anyURI;\n\t\telse if (typeStr.equals(XSD.base64Binary.getLocalName())) onDatatype = XSD.base64Binary;\n\t\telse if (typeStr.equals(XSD.xbyte.getLocalName())) onDatatype = XSD.xbyte;\n\t\telse if (typeStr.equals(XSD.date.getLocalName())) onDatatype = XSD.date;\n\t\telse if (typeStr.equals(XSD.dateTime.getLocalName())) onDatatype = XSD.dateTime;\n\t\telse if (typeStr.equals(XSD.decimal.getLocalName())) onDatatype = XSD.decimal;\n\t\telse if (typeStr.equals(XSD.duration.getLocalName())) onDatatype = XSD.duration;\n\t\telse if (typeStr.equals(XSD.gDay.getLocalName())) onDatatype = XSD.gDay;\n\t\telse if (typeStr.equals(XSD.gMonth.getLocalName())) onDatatype = XSD.gMonth;\n\t\telse if (typeStr.equals(XSD.gMonthDay.getLocalName())) onDatatype = XSD.gMonthDay;\n\t\telse if (typeStr.equals(XSD.gYear.getLocalName())) onDatatype = XSD.gYear;\n\t\telse if (typeStr.equals(XSD.gYearMonth.getLocalName())) onDatatype = XSD.gYearMonth;\n\t\telse if (typeStr.equals(XSD.hexBinary.getLocalName())) onDatatype = XSD.hexBinary;\n\t\telse if (typeStr.equals(XSD.integer.getLocalName())) onDatatype = XSD.integer;\n\t\telse if (typeStr.equals(XSD.time.getLocalName())) onDatatype = XSD.time;\n\t\telse if (typeStr.equals(XSD.xboolean.getLocalName())) onDatatype = XSD.xboolean;\n\t\telse if (typeStr.equals(XSD.xdouble.getLocalName())) onDatatype = XSD.xdouble;\n\t\telse if (typeStr.equals(XSD.xfloat.getLocalName())) onDatatype = XSD.xfloat;\n\t\telse if (typeStr.equals(XSD.xint.getLocalName())) onDatatype = XSD.xint;\n\t\telse if (typeStr.equals(XSD.xlong.getLocalName())) onDatatype = XSD.xlong;\n\t\telse if (typeStr.equals(XSD.anyURI.getLocalName())) onDatatype = XSD.anyURI;\n\t\telse if (typeStr.equals(XSD.anyURI.getLocalName())) onDatatype = XSD.anyURI;\n\t\telse {\n\t\t\tthrow new JenaProcessorException(\"Unexpected primitive data type: \" + typeStr);\n\t\t}\n\t\treturn onDatatype;\n\t}\n\tprivate OntClass createRdfsDatatype(String newDatatypeUri, List unionOfTypes, com.hp.hpl.jena.rdf.model.Resource onDatatype,\n\t\t\tSadlDataTypeFacet facet) throws JenaProcessorException {\n\t\tOntClass datatype = getTheJenaModel().createOntResource(OntClass.class, RDFS.Datatype, newDatatypeUri);\n\t\tOntClass equivClass = getTheJenaModel().createOntResource(OntClass.class, RDFS.Datatype, null);\n\t\tif (onDatatype != null) {\n\t\t\tequivClass.addProperty(OWL2.onDatatype, onDatatype);\n\t\t\tif (facet != null) {\n\t\t\t\tcom.hp.hpl.jena.rdf.model.Resource restrictions = facetsToRestrictionNode(newDatatypeUri, facet);\n\t\t\t\t// Create a list containing the restrictions\n\t\t\t\tRDFList list = getTheJenaModel().createList(new RDFNode[] {restrictions});\n\t\t\t\tequivClass.addProperty(OWL2.withRestrictions, list);\n\t\t\t}\n\t\t}\n\t\telse if (unionOfTypes != null) {\n\t\t\tIterator iter = unionOfTypes.iterator();\n\t\t\tRDFList collection = getTheJenaModel().createList();\n\t\t\twhile (iter.hasNext()) {\n\t\t\t\tRDFNode dt = iter.next();\n\t\t\t\tcollection = collection.with(dt);\n\t\t\t}\n\t\t\tequivClass.addProperty(OWL.unionOf, collection);\n\t\t}\n\t\telse {\n\t\t\tthrow new JenaProcessorException(\"Invalid arguments to createRdfsDatatype\");\n\t\t}\n\t\tdatatype.addEquivalentClass(equivClass);\n\t\treturn datatype;\n\t}\n\n\tprivate com.hp.hpl.jena.rdf.model.Resource facetsToRestrictionNode(String newName, SadlDataTypeFacet facet) {\n\t\tcom.hp.hpl.jena.rdf.model.Resource anon = getTheJenaModel().createResource();\n\t\t\n\t\tanon.addProperty(xsdProperty(facet.isMinInclusive()?\"minInclusive\":\"minExclusive\"), \"\" + facet.getMin());\n\t\tanon.addProperty(xsdProperty(facet.isMaxInclusive()?\"maxInclusive\":\"maxExclusive\"), \"\" + facet.getMax());\n\t\t\n\t\tif (facet.getLen() != null) {\n\t\t\tanon.addProperty(xsdProperty(\"length\"), \"\" + facet.getLen());\n\t\t}\n\t\tif (facet.getMinlen() != null) {\n\t\t\tanon.addProperty(xsdProperty(\"minLength\"), \"\" + facet.getMinlen());\n\t\t}\n\t\tif (facet.getMaxlen() != null && !facet.getMaxlen().equals(\"*\")) {\n\t\t\tanon.addProperty(xsdProperty(\"maxLength\"), \"\" + facet.getMaxlen());\n\t\t}\n\t\tif (facet.getRegex() != null) {\n\t\t\tanon.addProperty(xsdProperty(\"pattern\"), \"\" + facet.getRegex());\n\t\t}\n\t\tif (facet.getValues() != null) {\n\t\t\tIterator iter = facet.getValues().iterator();\n\t\t\twhile (iter.hasNext()) {\n\t\t\t\tanon.addProperty(xsdProperty(\"enumeration\"), iter.next());\n\t\t\t}\n\t\t}\n\t\treturn anon;\n\t}\n\n\tprotected OntClass processSadlPropertyCondition(SadlPropertyCondition sadlPropCond) throws JenaProcessorException {\n\t\tOntClass retval = null;\n\t\tSadlResource sr = ((SadlPropertyCondition)sadlPropCond).getProperty();\n\t\tString propUri = getDeclarationExtensions().getConceptUri(sr);\n\t\tif (propUri == null) {\n\t\t\tthrow new JenaProcessorException(\"Failed to get concept URI of SadlResource in processSadlPropertyCondition\");\n\t\t}\n\t\tOntConceptType propType;\n\t\ttry {\n\t\t\tpropType = getDeclarationExtensions().getOntConceptType(sr);\n\t\t} catch (CircularDefinitionException e) {\n\t\t\tpropType = e.getDefinitionType();\n\t\t\taddError(e.getMessage(), sadlPropCond);\n\t\t}\n\t\tOntProperty prop = getTheJenaModel().getOntProperty(propUri);\n\t\tif (prop == null) {\n\t\t\tif (propType.equals(OntConceptType.CLASS_PROPERTY)) {\n\t\t\t\tprop = getTheJenaModel().createObjectProperty(propUri);\n\t\t\t}\n\t\t\telse if (propType.equals(OntConceptType.DATATYPE_PROPERTY)) {\n\t\t\t\tprop = getTheJenaModel().createDatatypeProperty(propUri);\n\t\t\t}\n\t\t\telse if (propType.equals(OntConceptType.ANNOTATION_PROPERTY)) {\n\t\t\t\tprop = getTheJenaModel().createAnnotationProperty(propUri);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tprop = getTheJenaModel().createOntProperty(propUri);\n\t\t\t}\n\t\t}\n\t\tIterator conditer = ((SadlPropertyCondition)sadlPropCond).getCond().iterator();\n\t\twhile (conditer.hasNext()) {\n\t\t\tSadlCondition cond = conditer.next();\n\t\t\tretval = sadlConditionToOntClass(cond, prop, propType);\n\t\t\tif (conditer.hasNext()) {\n\t\t\t\tthrow new JenaProcessorException(\"Multiple property conditions not currently handled\");\n\t\t\t}\n\t\t}\n\t\treturn retval;\n\t}\n\n\tprotected OntClass sadlConditionToOntClass(SadlCondition cond, Property prop, OntConceptType propType) throws JenaProcessorException {\n\t\tOntClass retval = null;\n\t\tif (prop == null) {\n\t\t\taddError(SadlErrorMessages.CANNOT_CREATE.get(\"restriction\", \"unresolvable property\"), cond);\n\t\t}\n\t\telse if (cond instanceof SadlAllValuesCondition) {\n\t\t\tSadlTypeReference type = ((SadlAllValuesCondition)cond).getType();\n\t\t\tif (type instanceof SadlPrimitiveDataType) {\n\t\t\t\tSadlDataType pt = ((SadlPrimitiveDataType)type).getPrimitiveType();\n\t\t\t\tString typeStr = pt.getLiteral();\n\t\t\t\ttypeStr = XSD.getURI() + typeStr;\n\t\t\t}\n\t\t\tcom.hp.hpl.jena.rdf.model.Resource typersrc = sadlTypeReferenceToResource(type);\n\t\t\tif (typersrc == null) {\n\t\t\t\taddError(SadlErrorMessages.CANNOT_CREATE.get(\"all values from restriction\",\n\t\t\t\t\t\t\"restriction on unresolvable property value restriction\"), type);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tAllValuesFromRestriction avf = getTheJenaModel().createAllValuesFromRestriction(null, prop, typersrc);\n\t\t\t\tlogger.debug(\"New all values from restriction on '\" + prop.getURI() + \"' to values of type '\" + typersrc.toString() + \"'\");\n\t\t\t\tretval = avf;\n\t\t\t}\n\t\t}\n\t\telse if (cond instanceof SadlHasValueCondition) {\n//\t\t\tSadlExplicitValue value = ((SadlHasValueCondition)cond).getRestriction();\n\t\t\tRDFNode val = null;\n\t\t\tEObject restObj = ((SadlHasValueCondition)cond).getRestriction();\n\t\t\tif (restObj instanceof SadlExplicitValue) {\n\t\t\t\tSadlExplicitValue value = (SadlExplicitValue) restObj;\n\t\t\t\tif (value instanceof SadlResource) {\n\t\t\t\t\tOntConceptType srType;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tsrType = getDeclarationExtensions().getOntConceptType((SadlResource)value);\n\t\t\t\t\t} catch (CircularDefinitionException e) {\n\t\t\t\t\t\tsrType = e.getDefinitionType();\n\t\t\t\t\t\taddError(e.getMessage(), cond);\n\t\t\t\t\t}\n\t\t\t\t\tSadlResource srValue = (SadlResource) value;\n\t\t\t\t\tif (srType == null) {\n\t\t\t\t\t\tsrValue = ((SadlResource)value).getName();\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tsrType = getDeclarationExtensions().getOntConceptType(srValue);\n\t\t\t\t\t\t} catch (CircularDefinitionException e) {\n\t\t\t\t\t\t\tsrType = e.getDefinitionType();\n\t\t\t\t\t\t\taddError(e.getMessage(), cond);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (srType == null) {\n\t\t\t\t\t\tthrow new JenaProcessorException(\"Unable to resolve SadlResource value\");\n\t\t\t\t\t}\n\t\t\t\t\tif (srType.equals(OntConceptType.INSTANCE)) {\n\t\t\t\t\t\tString valUri = getDeclarationExtensions().getConceptUri(srValue);\n\t\t\t\t\t\tif (valUri == null) {\n\t\t\t\t\t\t\tthrow new JenaProcessorException(\"Failed to find SadlResource in Xtext model\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tval = getTheJenaModel().getIndividual(valUri);\n\t\t\t\t\t\tif (val == null) {\n\t\t\t\t\t\t\tSadlResource decl = getDeclarationExtensions().getDeclaration(srValue);\n\t\t\t\t\t\t\tif (decl != null && !decl.equals(srValue)) {\n\t\t\t\t\t\t\t\tEObject cont = decl.eContainer();\n\t\t\t\t\t\t\t\tif (cont instanceof SadlInstance) {\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\tval = processSadlInstance((SadlInstance)cont);\n\t\t\t\t\t\t\t\t\t} catch (CircularDefinitionException e) {\n\t\t\t\t\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse if (cont instanceof SadlMustBeOneOf) {\n\t\t\t\t\t\t\t\t\tcont = ((SadlMustBeOneOf)cont).eContainer();\n\t\t\t\t\t\t\t\t\tif (cont instanceof SadlClassOrPropertyDeclaration) {\n\t\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\t\tprocessSadlClassOrPropertyDeclaration((SadlClassOrPropertyDeclaration) cont);\n\t\t\t\t\t\t\t\t\t\t\teobjectPreprocessed(cont);\n\t\t\t\t\t\t\t\t\t\t} catch (TranslationException e) {\n\t\t\t\t\t\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tval = getTheJenaModel().getIndividual(valUri);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse if (cont instanceof SadlCanOnlyBeOneOf) {\n\t\t\t\t\t\t\t\t\tcont = ((SadlCanOnlyBeOneOf)cont).eContainer();\n\t\t\t\t\t\t\t\t\tif (cont instanceof SadlClassOrPropertyDeclaration) {\n\t\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\t\tprocessSadlClassOrPropertyDeclaration((SadlClassOrPropertyDeclaration) cont);\n\t\t\t\t\t\t\t\t\t\t\teobjectPreprocessed(cont);\n\t\t\t\t\t\t\t\t\t\t} catch (TranslationException e) {\n\t\t\t\t\t\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tval = getTheJenaModel().getIndividual(valUri);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (val == null) {\n\t\t\t\t\t\t\t\tthrow new JenaProcessorException(\"Failed to retrieve instance '\" + valUri + \"' from Jena model\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tthrow new JenaProcessorException(\"A has value restriction is to a SADL resource that did not resolve to an instance in the model\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (prop.canAs(OntProperty.class)) {\n\t\t\t\t\t\tval = sadlExplicitValueToLiteral(value, prop.as(OntProperty.class).getRange());\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tval = sadlExplicitValueToLiteral(value, null);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (restObj instanceof SadlNestedInstance) {\n\t\t\t\ttry {\n\t\t\t\t\tval = processSadlInstance((SadlNestedInstance)restObj);\n\t\t\t\t} catch (CircularDefinitionException e) {\n\t\t\t\t\tthrow new JenaProcessorException(e.getMessage());\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (propType.equals(OntConceptType.CLASS_PROPERTY)) {\n\t\t\t\tIndividual valInst = val.as(Individual.class);\n\t\t\t\tif (prop.canAs(OntProperty.class) && valueInObjectTypePropertyRange(prop.as(OntProperty.class), valInst, cond)) {\n\t\t\t\t\tHasValueRestriction hvr = getTheJenaModel().createHasValueRestriction(null, prop, valInst);\n\t\t\t\t\tlogger.debug(\"New has value restriction on '\" + prop.getURI() + \"' to value '\" + valInst.toString() + \"'\");\n\t\t\t\t\tretval = hvr;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrow new JenaProcessorException(SadlErrorMessages.NOT_IN_RANGE.get(valInst.getURI(), prop.getURI()));\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (propType.equals(OntConceptType.DATATYPE_PROPERTY)) {\n\t\t\t\tif (prop.canAs(OntProperty.class) && val.isLiteral() && valueInDatatypePropertyRange(prop.as(OntProperty.class), val.asLiteral(), cond)) {\n\t\t\t\t\tHasValueRestriction hvr = getTheJenaModel().createHasValueRestriction(null, prop, val);\n\t\t\t\t\tlogger.debug(\"New has value restriction on '\" + prop.getURI() + \"' to value '\" + val.toString() + \"'\");\n\t\t\t\t\tretval = hvr;\n\t\t\t\t}\t\n\t\t\t\telse {\n\t\t\t\t\tthrow new JenaProcessorException(SadlErrorMessages.NOT_IN_RANGE.get(val.toString(), prop.getURI()));\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (propType.equals(OntConceptType.RDF_PROPERTY)) {\n\t\t\t\tHasValueRestriction hvr = getTheJenaModel().createHasValueRestriction(null, prop, val);\n\t\t\t\tlogger.debug(\"New has value restriction on '\" + prop.getURI() + \"' to value '\" + val.toString() + \"'\");\n\t\t\t\tretval = hvr;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthrow new JenaProcessorException(\"Has value restriction on unexpected property type: \" + propType.toString());\n\t\t\t}\n\t\t}\n\t\telse if (cond instanceof SadlCardinalityCondition) {\n\t\t\t// Note: SomeValuesFrom is embedded in cardinality in the SADL grammar--an \"at least\" cardinality with \"one\" instead of # \n\t\t\tString cardinality = ((SadlCardinalityCondition)cond).getCardinality();\n\t\t\tSadlTypeReference type = ((SadlCardinalityCondition)cond).getType();\n\t\t\tOntResource typersrc = null;\n\t\t\tif (type != null) {\n\t\t\t\ttypersrc = sadlTypeReferenceToOntResource(type);\t\t\t\t\t\n\t\t\t}\n\t\t\tif (cardinality.equals(\"one\")) {\n\t\t\t\t// this is interpreted as a someValuesFrom restriction\n\t\t\t\tif (type == null) {\n\t\t\t\t\tthrow new JenaProcessorException(\"'one' means some value from class so a type must be given\");\n\t\t\t\t}\n\t\t\t\tSomeValuesFromRestriction svf = getTheJenaModel().createSomeValuesFromRestriction(null, prop, typersrc);\n\t\t\t\tlogger.debug(\"New some values from restriction on '\" + prop.getURI() + \"' to values of type '\" + typersrc.toString() + \"'\");\n\t\t\t\tretval = svf;\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// cardinality restrictioin\n\t\t\t\tint cardNum = Integer.parseInt(cardinality);\n\t\t\t\tString op = ((SadlCardinalityCondition)cond).getOperator();\n\t\t\t\tif (op == null) {\n\t\t\t\t\tCardinalityRestriction cr = getTheJenaModel().createCardinalityRestriction(null, prop, cardNum);\t\n\t\t\t\t\tlogger.debug(\"New cardinality restriction \" + cardNum + \" on '\" + prop.getURI() + \"' created\");\n\t\t\t\t\tif (type != null) {\n\t\t\t\t\t\tcr.removeAll(OWL.cardinality);\n\t\t\t\t\t\tcr.addLiteral(OWL2.qualifiedCardinality, cardNum);\n\t\t\t\t\t\tcr.addProperty(OWL2.onClass, typersrc);\n\t\t\t\t\t}\n\t\t\t\t\tretval = cr;\n\t\t\t\t}\n\t\t\t\telse if (op.equals(\"least\")) {\n\t\t\t\t\tMinCardinalityRestriction cr = getTheJenaModel().createMinCardinalityRestriction(null, prop, cardNum);\t\t\t\t\t\t\t\n\t\t\t\t\tlogger.debug(\"New min cardinality restriction \" + cardNum + \" on '\" + prop.getURI() + \"' created\");\n\t\t\t\t\tif (type != null) {\n\t\t\t\t\t\tcr.removeAll(OWL.minCardinality);\n\t\t\t\t\t\tcr.addLiteral(OWL2.minQualifiedCardinality, cardNum);\n\t\t\t\t\t\tcr.addProperty(OWL2.onClass, typersrc);\n\t\t\t\t\t}\n\t\t\t\t\tretval = cr;\n\t\t\t\t}\n\t\t\t\telse if (op.equals(\"most\")) {\n\t\t\t\t\tlogger.debug(\"New max cardinality restriction \" + cardNum + \" on '\" + prop.getURI() + \"' created\");\n\t\t\t\t\tMaxCardinalityRestriction cr = getTheJenaModel().createMaxCardinalityRestriction(null, prop, cardNum);\t\t\t\t\t\t\t\n\t\t\t\t\tif (type != null) {\n\t\t\t\t\t\tcr.removeAll(OWL.maxCardinality);\n\t\t\t\t\t\tcr.addLiteral(OWL2.maxQualifiedCardinality, cardNum);\n\t\t\t\t\t\tcr.addProperty(OWL2.onClass, typersrc);\n\t\t\t\t\t}\n\t\t\t\t\tretval = cr;\n\t\t\t\t}\n\t\t\t\tif (logger.isDebugEnabled()) {\n\t\t\t\t\tif (type != null) {\n\t\t\t\t\t\tlogger.debug(\" cardinality is qualified; values must be of type '\" + typersrc + \"'\");\n\t\t\t\t\t}\t\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tthrow new JenaProcessorException(\"Unhandled SadlCondition type: \" + cond.getClass().getCanonicalName());\n\t\t}\n\t\treturn retval;\n\t}\n\n\tprivate boolean valueInDatatypePropertyRange(OntProperty prop, Literal val, EObject cond) {\n\t\ttry {\n\t\t\tif (getModelValidator() != null) {\n\t\t\t\treturn getModelValidator().checkDataPropertyValueInRange(getTheJenaModel(), null, prop, val);\n\t\t\t}\n\t\t} catch (TranslationException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn true;\n\t}\n\n\tprotected Literal sadlExplicitValueToLiteral(SadlExplicitValue value, com.hp.hpl.jena.rdf.model.Resource rng) throws JenaProcessorException {\n\t\ttry {\n\t\t\tif (value instanceof SadlUnaryExpression) {\n\t\t\t\tString op = ((SadlUnaryExpression)value).getOperator();\n\t\t\t\tif (op.equals(\"-\")) {\n\t\t\t\t\tvalue = ((SadlUnaryExpression)value).getValue();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrow new JenaProcessorException(\"Unhandled case of unary operator on SadlExplicitValue: \" + op);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (value instanceof SadlNumberLiteral) {\n\t\t\t\tString val = ((SadlNumberLiteral)value).getLiteralNumber().toPlainString();\n\t\t\t\tif (rng != null && rng.getURI() != null) {\n\t\t\t\t\treturn SadlUtils.getLiteralMatchingDataPropertyRange(getTheJenaModel(), rng.getURI(), val);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (val.contains(\".\")) {\n\t\t\t\t\t\treturn getTheJenaModel().createTypedLiteral(Double.parseDouble(val));\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\treturn getTheJenaModel().createTypedLiteral(Integer.parseInt(val));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (value instanceof SadlStringLiteral) {\n\t\t\t\tString val = ((SadlStringLiteral)value).getLiteralString();\n\t\t\t\tif (rng != null) {\n\t\t\t\t\treturn SadlUtils.getLiteralMatchingDataPropertyRange(getTheJenaModel(), rng.getURI(), val);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\treturn getTheJenaModel().createTypedLiteral(val);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (value instanceof SadlBooleanLiteral) {\n\t\t\t\tSadlBooleanLiteral val = ((SadlBooleanLiteral)value);\n\t\t\t\tif (rng != null) {\n\t\t\t\t\treturn SadlUtils.getLiteralMatchingDataPropertyRange(getTheJenaModel(), rng.getURI(), val.isTruethy());\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\treturn getTheJenaModel().createTypedLiteral(val.isTruethy());\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (value instanceof SadlValueList) {\n\t\t\t\tthrow new JenaProcessorException(\"A SADL value list cannot be converted to a Literal\");\n\t\t\t}\n\t\t\telse if (value instanceof SadlConstantLiteral) {\n\t\t\t\tString val = ((SadlConstantLiteral)value).getTerm();\n\t\t\t\tif (val.equals(\"PI\")) {\n\t\t\t\t\treturn SadlUtils.getLiteralMatchingDataPropertyRange(getTheJenaModel(), rng.getURI(), Math.PI);\n\t\t\t\t}\n\t\t\t\telse if (val.equals(\"e\")) {\n\t\t\t\t\treturn SadlUtils.getLiteralMatchingDataPropertyRange(getTheJenaModel(), rng.getURI(), Math.E);\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\telse if (rng != null) {\n\t\t\t\t\treturn SadlUtils.getLiteralMatchingDataPropertyRange(getTheJenaModel(), rng.getURI(), val);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tint ival = Integer.parseInt(val);\n\t\t\t\t\t\treturn getTheJenaModel().createTypedLiteral(ival);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (Exception e) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tdouble dval = Double.parseDouble(val);\n\t\t\t\t\t\t\treturn getTheJenaModel().createTypedLiteral(dval);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcatch (Exception e2) {\n\t\t\t\t\t\t\treturn getTheJenaModel().createTypedLiteral(val);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (value instanceof SadlResource) {\n\t\t\t\tNode nval = processExpression((SadlResource)value);\n\t\t\t\tthrow new JenaProcessorException(\"Unable to convert concept '\" + nval.toFullyQualifiedString() + \"to a literal\");\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthrow new JenaProcessorException(\"Unhandled sadl explicit vaue type: \" + value.getClass().getCanonicalName());\n\t\t\t}\n\t\t}\n\t\tcatch (Throwable t) {\n\t\t\taddError(t.getMessage(), value);\n\t\t}\n\t\treturn null;\n\t}\n\n\tprivate boolean valueInObjectTypePropertyRange(OntProperty prop, Individual valInst, EObject cond) throws JenaProcessorException {\n\t\tExtendedIterator itr = prop.listRange();\n\t\twhile (itr.hasNext()) {\n\t\t\tOntResource nxt = itr.next();\n\t\t\tif (nxt.isClass()) {\n\t\t\t\tif (instanceBelongsToClass(getTheJenaModel(), valInst, nxt)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprivate IntersectionClass createIntersectionClass(RDFNode... members) throws JenaProcessorException {\n\t\tRDFList classes = getTheJenaModel().createList(members);\n\t\tif (!classes.isEmpty()) {\n\t\t\tIntersectionClass intersectCls = getTheJenaModel().createIntersectionClass(null, classes);\n\t\t\tlogger.debug(\"New intersection class created\");\n\t\t\treturn intersectCls;\n\t\t}\n\t\tthrow new JenaProcessorException(\"createIntersectionClass called with empty list of classes\");\n\t}\n\n\tprivate UnionClass createUnionClass(RDFNode... members) throws JenaProcessorException {\n\t\tUnionClass existingBnodeUnion = null;\n\t\tfor (int i = 0; i < members.length; i++) {\n\t\t\tRDFNode mmbr = members[i];\n\t\t\tif ((mmbr instanceof UnionClass || mmbr.canAs(UnionClass.class) && mmbr.isAnon())) {\n\t\t\t\texistingBnodeUnion = mmbr.as(UnionClass.class);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (existingBnodeUnion != null) {\n\t\t\tfor (int i = 0; i < members.length; i++) {\n\t\t\t\tRDFNode mmbr = members[i];\n\t\t\t\tif (!mmbr.equals(existingBnodeUnion)) {\n\t\t\t\t\texistingBnodeUnion.addOperand(mmbr.asResource());\n\t\t\t\t\tlogger.debug(\"Added member '\" + mmbr.toString() + \"' to existing union class\");\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn existingBnodeUnion;\n\t\t}\n\t\telse {\n\t\t\tRDFList classes = getTheJenaModel().createList(members);\n\t\t\tif (!classes.isEmpty()) {\n\t\t\t\tUnionClass unionCls = getTheJenaModel().createUnionClass(null, classes);\n\t\t\t\tlogger.debug(\"New union class created\");\n\t\t\t\treturn unionCls;\n\t\t\t}\n\t\t}\n\t\tthrow new JenaProcessorException(\"createUnionClass called with empty list of classes\");\n\t}\n\n\tprivate OntConceptType getSadlTypeReferenceType(SadlTypeReference sadlTypeRef) throws JenaProcessorException {\n\t\tif (sadlTypeRef instanceof SadlSimpleTypeReference) {\n\t\t\tSadlResource sr = ((SadlSimpleTypeReference)sadlTypeRef).getType();\n\t\t\ttry {\n\t\t\t\treturn getDeclarationExtensions().getOntConceptType(sr);\n\t\t\t} catch (CircularDefinitionException e) {\n\t\t\t\taddError(e.getMessage(), sadlTypeRef);\n\t\t\t\treturn e.getDefinitionType();\n\t\t\t}\n\t\t}\n\t\telse if (sadlTypeRef instanceof SadlPrimitiveDataType) {\n\t\t\treturn OntConceptType.DATATYPE;\n\t\t}\n\t\telse if (sadlTypeRef instanceof SadlPropertyCondition) {\n\t\t\t// property conditions => OntClass\n\t\t\treturn OntConceptType.CLASS;\n\t\t}\n\t\telse if (sadlTypeRef instanceof SadlUnionType) {\n\t\t\tSadlTypeReference lft = ((SadlUnionType)sadlTypeRef).getLeft();\n\t\t\tOntConceptType lfttype = getSadlTypeReferenceType(lft);\n\t\t\treturn lfttype;\n//\t\t\tSadlTypeReference rght = ((SadlUnionType)sadlTypeRef).getRight();\n\t\t}\n\t\telse if (sadlTypeRef instanceof SadlIntersectionType) {\n\t\t\tSadlTypeReference lft = ((SadlIntersectionType)sadlTypeRef).getLeft();\n\t\t\tOntConceptType lfttype = getSadlTypeReferenceType(lft);\n\t\t\treturn lfttype;\n//\t\t\tSadlTypeReference rght = ((SadlIntersectionType)sadlTypeRef).getRight();\n\t\t}\n\t\tthrow new JenaProcessorException(\"Unexpected SadlTypeReference subtype: \" + sadlTypeRef.getClass().getCanonicalName());\n\t}\n\n\tprotected String assureNamespaceEndsWithHash(String name) {\n\t\tname = name.trim();\n\t\tif (!name.endsWith(\"#\")) {\n\t\t\treturn name + \"#\";\n\t\t}\n\t\treturn name;\n\t}\n\n\tpublic String getModelNamespace() {\n\t\treturn modelNamespace;\n\t}\n\n\tprotected void setModelNamespace(String modelNamespace) {\n\t\tthis.modelNamespace = modelNamespace;\n\t}\n\n\tpublic OntDocumentManager getJenaDocumentMgr(OntModelSpec ontModelSpec) {\n\t\tif (jenaDocumentMgr == null) {\n\t\t\tif (getMappingModel() != null) {\n\t\t\t\tsetJenaDocumentMgr(new OntDocumentManager(getMappingModel()));\n\t\t\t\tif (ontModelSpec != null) {\n\t\t\t\t\tontModelSpec.setDocumentManager(jenaDocumentMgr);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tsetJenaDocumentMgr(OntDocumentManager.getInstance());\n\t\t\t}\n\t\t}\n\t\treturn jenaDocumentMgr;\n\t}\n\n\tprivate void setJenaDocumentMgr(OntDocumentManager ontDocumentManager) {\n\t\tjenaDocumentMgr = ontDocumentManager;\n\t}\n\n\tprivate Model getMappingModel() {\n\t\t// TODO Auto-generated method stub\n\t\treturn null;\n\t}\n\t\n\t/**\n\t * return true if the instance belongs to the class else return false\n\t * \n\t * @param inst\n\t * @param cls\n\t * @return\n\t * @throws JenaProcessorException \n\t */\n\tpublic boolean instanceBelongsToClass(OntModel m, OntResource inst, OntResource cls) throws JenaProcessorException {\n\t\t// The following cases must be considered:\n\t\t// 1) The class is a union of other classes. Check to see if the instance is a member of any of\n\t\t//\t\tthe union classes and if so return true.\n\t\t// 2) The class is an intersection of other classes. Check to see if the instance is \n\t\t//\t\ta member of each class in the intersection and if so return true.\n\t\t// 3) The class is neither a union nor an intersection. If the instance belongs to the class return true. Otherwise\n\t\t//\t\tcheck to see if the instance belongs to a subclass of the class else\n\t\t//\t\treturn false. (Superclasses do not need to be considered because even if the instance belongs to a super\n\t\t//\t\tclass that does not tell us that it belongs to the class.)\n\t\t\n\t\t/*\n\t\t * e.g., \tInternet is a Network.\n\t\t * \t\t\tNetwork is a type of Subsystem.\n\t\t * \t\t\tSubsystem is type of System.\n\t\t */\n\t\tif (cls.isURIResource()) {\n\t\t\tcls = m.getOntClass(cls.getURI());\n\t\t}\n\t\tif (cls == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (cls.canAs(UnionClass.class)) {\n\t\t\tList uclses = getOntResourcesInUnionClass(m, cls.as(UnionClass.class));\t\n\t\t\tfor (int i = 0; i < uclses.size(); i++) {\n\t\t\t\tOntResource ucls = uclses.get(i);\n\t\t\t\tif (instanceBelongsToClass(m, inst, ucls)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if (cls.canAs(IntersectionClass.class)) {\n\t\t\tList uclses = getOntResourcesInIntersectionClass(m, cls.as(IntersectionClass.class));\t\n\t\t\tfor (int i = 0; i < uclses.size(); i++) {\n\t\t\t\tOntResource ucls = uclses.get(i);\n\t\t\t\tif (!instanceBelongsToClass(m, inst, ucls)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\telse if (cls.canAs(Restriction.class)) {\n\t\t\tRestriction rest = cls.as(Restriction.class);\n\t\t\tOntProperty ontp = rest.getOnProperty();\t\t\t\t\n\t\t\tif (rest.isAllValuesFromRestriction()) {\n\t\t\t\tStmtIterator siter = inst.listProperties(ontp);\n\t\t\t\twhile (siter.hasNext()) {\n\t\t\t\t\tStatement stmt = siter.nextStatement();\n\t\t\t\t\tRDFNode obj = stmt.getObject();\n\t\t\t\t\tif (obj.canAs(Individual.class)) {\n\t\t\t\t\t\tcom.hp.hpl.jena.rdf.model.Resource avfc = rest.asAllValuesFromRestriction().getAllValuesFrom();\n\t\t\t\t\t\tif (!instanceBelongsToClass(m, (Individual)obj.as(Individual.class), (OntResource)avfc.as(OntResource.class))) {\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (rest.isSomeValuesFromRestriction()) {\n\t\t\t\tif (inst.hasProperty(ontp)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (rest.isHasValueRestriction()) {\n\t\t\t\tRDFNode hval = rest.as(HasValueRestriction.class).getHasValue();\n\t\t\t\tif (inst.hasProperty(ontp, hval)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (rest.isCardinalityRestriction()) {\n\t\t\t\tthrow new JenaProcessorException(\"Unhandled cardinality restriction\");\n\t\t\t}\n\t\t\telse if (rest.isMaxCardinalityRestriction()) {\n\t\t\t\tthrow new JenaProcessorException(\"Unhandled max cardinality restriction\");\n\t\t\t}\n\t\t\telse if (rest.isMinCardinalityRestriction()) {\n\t\t\t\tthrow new JenaProcessorException(\"Unhandled min cardinality restriction\");\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (inst.canAs(Individual.class)) {\n\t\t\t\tExtendedIterator eitr = inst.asIndividual().listRDFTypes(false);\n\t\t\t\twhile (eitr.hasNext()) {\n\t\t\t\t\tcom.hp.hpl.jena.rdf.model.Resource r = eitr.next();\t\t\t\t\n\t\t\t\t\tOntResource or = m.getOntResource(r);\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (or.isURIResource()) {\n\t\t\t\t\t\t\tOntClass oc = m.getOntClass(or.getURI());\n\t\t\t\t\t\t\tif (SadlUtils.classIsSubclassOf(oc, cls, true, null)) {\n\t\t\t\t\t\t\t\teitr.close();\n\t\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (or.canAs(OntClass.class)) {\n\t\t\t\t\t\t\tif (SadlUtils.classIsSubclassOf(or.as(OntClass.class), cls, true, null)) {\n\t\t\t\t\t\t\t\teitr.close();\n\t\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (CircularDependencyException e) {\n\t\t\t\t\t\tthrow new JenaProcessorException(e.getMessage(), e);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\tpublic List getOntResourcesInUnionClass(OntModel m, UnionClass ucls) {\n\t\tList results = new ArrayList();\n\t\tList clses = ucls.getOperands().asJavaList();\n\t\tfor (int i = 0; i < clses.size(); i++) {\n\t\t\tRDFNode mcls = clses.get(i);\n\t\t\tif (mcls.canAs(OntResource.class)) {\n\t\t\t\tif (mcls.canAs(UnionClass.class)){\n\t\t\t\t\tList innerList = getOntResourcesInUnionClass(m, mcls.as(UnionClass.class));\n\t\t\t\t\tfor (int j = 0; j < innerList.size(); j++) {\n\t\t\t\t\t\tOntResource innerRsrc = innerList.get(j);\n\t\t\t\t\t\tif (!results.contains(innerRsrc)) {\n\t\t\t\t\t\t\tresults.add(innerRsrc);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tresults.add(mcls.as(OntResource.class));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn results;\n\t}\n\t\n\tpublic List getOntResourcesInIntersectionClass(OntModel m, IntersectionClass icls) {\n\t\tList results = new ArrayList();\n\t\tList clses = icls.getOperands().asJavaList();\n\t\tfor (int i = 0; i < clses.size(); i++) {\n\t\t\tRDFNode mcls = clses.get(i);\n\t\t\tif (mcls.canAs(OntResource.class)) {\n\t\t\t\tresults.add(mcls.as(OntResource.class));\n\t\t\t}\n\t\t}\n\t\treturn results;\n\t}\n\n\tpublic ValidationAcceptor getIssueAcceptor() {\n\t\treturn issueAcceptor;\n\t}\n\n\tprotected void setIssueAcceptor(ValidationAcceptor issueAcceptor) {\n\t\tthis.issueAcceptor = issueAcceptor;\n\t}\n\n\tprivate CancelIndicator getCancelIndicator() {\n\t\treturn cancelIndicator;\n\t}\n\n\tprotected void setCancelIndicator(CancelIndicator cancelIndicator) {\n\t\tthis.cancelIndicator = cancelIndicator;\n\t}\n\n\tprotected String getModelName() {\n\t\treturn modelName;\n\t}\n\n\tprotected void setModelName(String modelName) {\n\t\tthis.modelName = modelName;\n\t}\n\n\t@Override\n\tpublic void processExternalModels(String mappingFileFolder, List fileNames) throws IOException {\n\t\tFile mff = new File(mappingFileFolder);\n\t\tif (!mff.exists()) {\n\t\t\tmff.mkdirs();\n\t\t}\n\t\tif (!mff.isDirectory()) {\n\t\t\tthrow new IOException(\"Mapping file location '\" + mappingFileFolder + \"' exists but is not a directory.\");\n\t\t}\n\t\tSystem.out.println(\"Ready to save mappings in folder: \" + mff.getCanonicalPath());\n\t\tfor (int i = 0; i < fileNames.size(); i++) {\n\t\t\tSystem.out.println(\" URL: \" + fileNames.get(i));\n\t\t}\n\t}\n\t\n\tpublic String getModelAlias() {\n\t\treturn modelAlias;\n\t}\n\t\n\tprotected void setModelAlias(String modelAlias) {\n\t\tthis.modelAlias = modelAlias;\n\t}\n\t\n\tprivate OntModelSpec getSpec() {\n\t\treturn spec;\n\t}\n\t\n\tprivate void setSpec(OntModelSpec spec) {\n\t\tthis.spec = spec;\n\t}\n\t\n\t/**\n\t * This method looks in the clauses of a Rule to see if there is already a triple matching the given pattern. If there is\n\t * a new variable of the same name is created (to make sure the count is right) and returned. If not a rule or no match\n\t * a new variable (new name) is created and returned.\n\t * @param expr \n\t * @param subject\n\t * @param predicate\n\t * @param object\n\t * @return\n\t */\n\tprotected VariableNode getVariableNode(Expression expr, Node subject, Node predicate, Node object) {\n\t\tif (getTarget() != null) {\n\t\t\t// Note: when we find a match we still create a new VariableNode with the same name in order to have the right reference counts for the new VariableNode\n\t\t\tif (getTarget() instanceof Rule) {\n\t\t\t\tVariableNode var = findVariableInTripleForReuse(((Rule)getTarget()).getGivens(), subject, predicate, object);\n\t\t\t\tif (var != null) {\n\t\t\t\t\treturn new VariableNode(var.getName());\n\t\t\t\t}\n\t\t\t\tvar = findVariableInTripleForReuse(((Rule)getTarget()).getIfs(), subject, predicate, object);\n\t\t\t\tif (var != null) {\n\t\t\t\t\treturn new VariableNode(var.getName());\n\t\t\t\t}\n\t\t\t\tvar = findVariableInTripleForReuse(((Rule)getTarget()).getThens(), subject, predicate, object);\n\t\t\t\tif (var != null) {\n\t\t\t\t\treturn new VariableNode(var.getName());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn new VariableNode(getNewVar(expr));\n\t}\n\t\n\tprotected String getNewVar(Expression expr) {\n\t\tIScopeProvider scopeProvider = ((XtextResource)expr.eResource()).getResourceServiceProvider().get(IScopeProvider.class);\n\t\tIScope scope = scopeProvider.getScope(expr, SADLPackage.Literals.SADL_RESOURCE__NAME);\n\t\tString proposedName = \"v\" + vNum;\n\t\twhile (userDefinedVariables.contains(proposedName)\n\t\t\t\t|| \tscope.getSingleElement(QualifiedName.create(proposedName)) != null) {\n\t\t\tvNum++;\n\t\t\tproposedName = \"v\" + vNum;\n\t\t}\n\t\tvNum++;\n\t\treturn proposedName;\n\t}\n\t\n\t/**\n\t * Supporting method for the method above (getVariableNode(Node, Node, Node))\n\t * @param gpes\n\t * @param subject\n\t * @param predicate\n\t * @param object\n\t * @return\n\t */\n\tprotected VariableNode findVariableInTripleForReuse(List gpes, Node subject, Node predicate, Node object) {\n\t\tif (gpes != null) {\n\t\t\tIterator itr = gpes.iterator();\n\t\t\twhile (itr.hasNext()) {\n\t\t\t\tGraphPatternElement gpe = itr.next();\n\t\t\t\twhile (gpe != null) {\n\t\t\t\t\tif (gpe instanceof TripleElement) {\n\t\t\t\t\t\tTripleElement tr = (TripleElement)gpe;\n\t\t\t\t\t\tNode tsn = tr.getSubject();\n\t\t\t\t\t\tNode tpn = tr.getPredicate();\n\t\t\t\t\t\tNode ton = tr.getObject();\n\t\t\t\t\t\tif (subject == null && tsn instanceof VariableNode) {\n\t\t\t\t\t\t\tif (predicate != null && predicate.equals(tpn) && object != null && object.equals(ton)) {\n\t\t\t\t\t\t\t\treturn (VariableNode) tsn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (predicate == null && tpn instanceof VariableNode) {\n\t\t\t\t\t\t\tif (subject != null && subject.equals(tsn) && object != null && object.equals(ton)) {\n\t\t\t\t\t\t\t\treturn (VariableNode) tpn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (object == null && ton instanceof VariableNode) {\n\t\t\t\t\t\t\tif (subject != null && subject.equals(tsn) && predicate != null && predicate.equals(tpn)) {\n\t\t\t\t\t\t\t\treturn (VariableNode) ton;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tgpe = gpe.getNext();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tpublic List getRules() {\n\t\treturn rules;\n\t}\n\t\t\n\tprivate java.nio.file.Path checkImplicitSadlModelExistence(Resource resource, ProcessorContext context) throws IOException, ConfigurationException, URISyntaxException, JenaProcessorException {\n\t\tUtilsForJena ufj = new UtilsForJena();\n\t\tString policyFileUrl = ufj.getPolicyFilename(resource);\n\t\tString policyFilename = policyFileUrl != null ? ufj.fileUrlToFileName(policyFileUrl) : null;\n\t\tif (policyFilename != null) {\n\t\t\tFile projectFolder = new File(policyFilename).getParentFile().getParentFile();\n\t\t\tString relPath = SadlConstants.SADL_IMPLICIT_MODEL_FOLDER + \"/\" + SadlConstants.SADL_IMPLICIT_MODEL_FILENAME;\n\t\t\tString platformPath = projectFolder.getName() + \"/\" + relPath;\n\t\t\tString implicitSadlModelFN = projectFolder + \"/\" + relPath;\n\t\t\tFile implicitModelFile = new File(implicitSadlModelFN);\n\t\t\tif (!implicitModelFile.exists()) {\n\t\t\t\tcreateSadlImplicitModel(implicitModelFile);\n\t\t\t\ttry {\n\t\t\t\t\tResource newRsrc = resource.getResourceSet().createResource(URI.createPlatformResourceURI(platformPath, false)); // createFileURI(implicitSadlModelFN));\n//\t\t\t\t\tnewRsrc.load(new StringInputStream(implicitModel), resource.getResourceSet().getLoadOptions());\n\t\t\t\t\tnewRsrc.load(resource.getResourceSet().getLoadOptions());\n\t\t\t\t\trefreshResource(newRsrc);\n\t\t\t\t}\n\t\t\t\tcatch (Throwable t) {}\n\t\t\t}\n\t\t\treturn implicitModelFile.getAbsoluteFile().toPath();\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tstatic public File createBuiltinFunctionImplicitModel(String projectRootPath) throws IOException, ConfigurationException{\n\t\t//First, obtain proper translator for project\n\t\tSadlUtils su = new SadlUtils();\n\t\tif(projectRootPath.startsWith(\"file\")){\n\t\t\tprojectRootPath = su.fileUrlToFileName(projectRootPath);\n\t\t}\n\t\tfinal File mfFolder = new File(projectRootPath + \"/\" + ResourceManager.OWLDIR);\n\t\tfinal String format = ConfigurationManager.RDF_XML_ABBREV_FORMAT;\n\t\tString fixedModelFolderName = mfFolder.getCanonicalPath().replace(\"\\\\\", \"/\");\n\t\tIConfigurationManagerForIDE configMgr = ConfigurationManagerForIdeFactory.getConfigurationManagerForIDE(fixedModelFolderName, format);\n\t\tITranslator translator = configMgr.getTranslator();\n\t\t//Second, obtain built-in function implicit model contents\n\t\tString builtinFunctionModel = translator.getBuiltinFunctionModel();\n\t\t//Third, create built-in function implicit model file\n\t\tFile builtinFunctionFile = new File(projectRootPath + \"/\" +\n\t\t\t\t\t\t\t\t\t\t\tSadlConstants.SADL_IMPLICIT_MODEL_FOLDER + \"/\" +\n\t\t\t\t\t\t\t\t\t\t\tSadlConstants.SADL_BUILTIN_FUNCTIONS_FILENAME);\t\n\t\tsu.stringToFile(builtinFunctionFile, builtinFunctionModel, true);\n\t\t\n\t\treturn builtinFunctionFile;\n\t}\n\t\n\tstatic public String getSadlBaseModel() {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tsb.append(\"\\n\");\n\t\tsb.append(\"\t \\n\");\n\t\tsb.append(\"\t Base model for SADL. These concepts can be used without importing.\\n\");\n\t\tsb.append(\"\t \\n\");\n\t\tsb.append(\"\t \\n\");\n\t\tsb.append(\"\t \\n\");\n\t\tsb.append(\"\t \\n\");\n\t\tsb.append(\"\t \\n\");\n\t\tsb.append(\"\t \\n\");\n\t\tsb.append(\"\t \\n\");\n\t\tsb.append(\"\t \\n\");\n\t\tsb.append(\"\t \\n\");\n\t\tsb.append(\"\t \\n\");\n\t\tsb.append(\"\t \\n\");\n\t\tsb.append(\"\t \\n\");\n\t\tsb.append(\"\t \\n\");\n\t\tsb.append(\"\t \\n\");\n\t\tsb.append(\"\t \\n\");\n\t\tsb.append(\"\\n\");\n\t\treturn sb.toString();\n\t}\n\t\n\tstatic public String getSadlListModel() {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" Typed List model for SADL.\\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\" \\n\");\n\t\tsb.append(\"\\n\");\n\t\treturn sb.toString();\n\t}\n\t\n\tstatic public String getSadlDefaultsModel() {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tsb.append(\"\\n\");\n\t\tsb.append(\"\\n\");\n\t\tsb.append(\"\t\\n\");\n\t\tsb.append(\"\t Copyright 2007, 2008, 2009 - General Electric Company, All Rights Reserved\\n\");\n\t\tsb.append(\"\t $Id: defaults.owl,v 1.1 2014/01/23 21:52:26 crapo Exp $\\n\");\n\t\tsb.append(\"\t\\n\");\n\t\tsb.append(\"\t\\n\");\n\t\tsb.append(\"\t\tThis type of default has a value which is a Literal\\n\");\n\t\tsb.append(\"\t\t\\n\");\n\t\tsb.append(\"\t\t\t\\n\");\n\t\tsb.append(\"\t\t\\n\");\n\t\tsb.append(\"\t\\n\");\n\t\tsb.append(\"\t\\n\");\n\t\tsb.append(\"\t\tThis type of default has a value which is an Individual\\n\");\n\t\tsb.append(\"\t\t\\n\");\n\t\tsb.append(\"\t\t\t\\n\");\n\t\tsb.append(\"\t\t\\n\");\n\t\tsb.append(\"\t\\n\");\n\t\tsb.append(\"\t\\n\");\n\t\tsb.append(\"\t\t\\n\");\n\t\tsb.append(\"\t\t\\n\");\n\t\tsb.append(\"\t\t\\n\");\n\t\tsb.append(\"\t\\n\");\n\t\tsb.append(\"\t\\n\");\n\t\tsb.append(\"\t\t\\n\");\n\t\tsb.append(\"\t\t\\n\");\n\t\tsb.append(\"\t\\n\");\n\t\tsb.append(\"\t\\n\");\n\t\tsb.append(\"\t\t\\n\");\n\t\tsb.append(\"\t\t\\n\");\n\t\tsb.append(\"\t\\n\");\n\t\tsb.append(\"\t\\n\");\n\t\tsb.append(\"\t\tThe value of this Property is the Property to which the default value applies.\\n\");\n\t\tsb.append(\"\t\t\\n\");\n\t\tsb.append(\"\t\t\\n\");\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsb.append(\"\t\t\");\n\t\tsb.append(\"\t\\n\");\n\t\tsb.append(\"\\n\");\n\t\treturn sb.toString();\n\t}\n\t\n\tprivate boolean importSadlListModel(Resource resource) throws JenaProcessorException, ConfigurationException {\n\t\tif (sadlListModel == null) {\n\t\t\ttry {\n\t\t\t\tsadlListModel = getOntModelFromString(resource, getSadlListModel());\n\t\t\t\tOntModelProvider.setSadlListModel(sadlListModel);\n\t\t\t} catch (Exception e) {\n\t\t\t\tthrow new JenaProcessorException(e.getMessage(), e);\n\t\t\t}\n\t\t\taddImportToJenaModel(getModelName(), SadlConstants.SADL_LIST_MODEL_URI, SadlConstants.SADL_LIST_MODEL_PREFIX, sadlListModel);\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tpublic OntModel getOntModelFromString(Resource resource, String serializedModel)\n\t\t\tthrows IOException, ConfigurationException, URISyntaxException, JenaProcessorException {\n\t\tOntModel listModel = prepareEmptyOntModel(resource);\n\t\tInputStream stream = new ByteArrayInputStream(serializedModel.getBytes());\n\t\tlistModel.read(stream, null);\n\t\treturn listModel;\n\t}\n\t\n\tprivate boolean importSadlDefaultsModel(Resource resource) throws JenaProcessorException, ConfigurationException {\n\t\tif (sadlDefaultsModel == null) {\n\t\t\ttry {\n\t\t\t\tsadlDefaultsModel = getOntModelFromString(resource, getSadlDefaultsModel());\n\t\t\t\tOntModelProvider.setSadlDefaultsModel(sadlDefaultsModel);\n\t\t\t} catch (Exception e) {\n\t\t\t\tthrow new JenaProcessorException(e.getMessage(), e);\n\t\t\t}\n\t\t\taddImportToJenaModel(getModelName(), SadlConstants.SADL_DEFAULTS_MODEL_URI, SadlConstants.SADL_DEFAULTS_MODEL_PREFIX, sadlDefaultsModel);\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprotected IConfigurationManagerForIDE getConfigMgr(Resource resource, String format) throws ConfigurationException {\n\t\tif (configMgr == null) {\n\t\t\tString modelFolderPathname = getModelFolderPath(resource);\n\t\t\tif (format == null) {\n\t\t\t\tformat = ConfigurationManager.RDF_XML_ABBREV_FORMAT; // default\n\t\t\t}\n\t\t\tif (isSyntheticUri(modelFolderPathname, resource)) {\n\t\t\t\tmodelFolderPathname = null;\n\t\t\t\tconfigMgr = ConfigurationManagerForIdeFactory.getConfigurationManagerForIDE(modelFolderPathname, format, true);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconfigMgr = ConfigurationManagerForIdeFactory.getConfigurationManagerForIDE(modelFolderPathname , format);\n\t\t\t}\n\t\t}\n\t\treturn configMgr;\n\t}\n\t\n\tprotected boolean isSyntheticUri(String modelFolderPathname, Resource resource) {\n\t\tif ((modelFolderPathname == null && \n\t\t\t\tresource.getURI().toString().startsWith(\"synthetic\")) ||\n\t\t\t\t\t\tresource.getURI().toString().startsWith(SYNTHETIC_FROM_TEST)) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprotected IConfigurationManagerForIDE getConfigMgr() {\n\t\treturn configMgr;\n\t}\n\t\n\tprotected boolean isBooleanOperator(String op) {\n\t\tOPERATORS_RETURNING_BOOLEAN[] ops = OPERATORS_RETURNING_BOOLEAN.values();\n\t\tfor (int i = 0; i < ops.length; i++) {\n\t\t\tif (op.equals(ops[i].toString())) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprotected boolean isConjunction(String op) {\n\t\tif (op.equals(\"and\")) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprotected void resetProcessorState(SadlModelElement element) throws InvalidTypeException {\n\t\ttry {\n\t\t\tif (getModelValidator() != null) {\n\t\t\t\tgetModelValidator().resetValidatorState(element);\n\t\t\t}\n\t\t} catch (TranslationException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\tpublic List getEquations() {\n\t\treturn equations;\n\t}\n\t\n\tpublic void setEquations(List equations) {\n\t\tthis.equations = equations;\n\t}\n\t\n\tprotected boolean isClass(OntConceptType oct){\n\t\tif(oct.equals(OntConceptType.CLASS)){\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprotected boolean isProperty(NodeType oct) {\n\t\tif (oct.equals(NodeType.ObjectProperty) || \n\t\t\t\toct.equals(NodeType.DataTypeProperty) || \n\t\t\t\toct.equals(NodeType.PropertyNode)){\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprotected boolean isProperty(OntConceptType oct) {\n\t\tif (oct.equals(OntConceptType.DATATYPE_PROPERTY) || \n\t\t\t\toct.equals(OntConceptType.CLASS_PROPERTY) || \n\t\t\t\toct.equals(OntConceptType.RDF_PROPERTY) || \n\t\t\t\toct.equals(OntConceptType.ANNOTATION_PROPERTY)){\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic SadlCommand getTargetCommand() {\n\t\treturn targetCommand;\n\t}\n\t\n\tpublic ITranslator getTranslator() throws ConfigurationException {\n\t\tIConfigurationManagerForIDE cm = getConfigMgr(getCurrentResource(), getOwlModelFormat(getProcessorContext()));\n\t\tif (cm.getTranslatorClassName() == null) {\n\t\t\tcm.setTranslatorClassName(translatorClassName );\n\t\t\tcm.setReasonerClassName(reasonerClassName);\n\t\t}\n\t\treturn cm.getTranslator();\n\t}\n\t\n\t/**\n\t * Method to obtain the sadlimplicitmodel:impliedProperty annotation property values for the given class\n\t * @param cls -- the Jena Resource (nominally a class) for which the values are desired\n\t * @return -- a List of the ConceptNames of the values \n\t */\n\tpublic List getImpliedProperties(com.hp.hpl.jena.rdf.model.Resource cls) {\n\t\tList retlst = null;\n\t\tif (cls == null) return null;\n\t\tif (!cls.isURIResource()) return null;\t// impliedProperties can only be given to a named class\n\t\tif (!cls.canAs(OntClass.class)) {\n\t\t\taddError(\"Can't get implied properties of a non-class entity.\", null);\n\t\t\treturn null; \n\t\t}\n\t\tList allImplPropClasses = getAllImpliedPropertyClasses();\n\t\tif (allImplPropClasses != null) {\n\t\t\tfor (OntResource ipcls : allImplPropClasses) {\n\t\t\t\ttry {\n\t\t\t\t\tif (SadlUtils.classIsSubclassOf(cls.as(OntClass.class), ipcls, true, null)) {\n\t\t\t\t\t\tStmtIterator sitr = getTheJenaModel().listStatements(ipcls, getTheJenaModel().getProperty(SadlConstants.SADL_IMPLICIT_MODEL_IMPLIED_PROPERTY_URI), (RDFNode)null);\n\t\t\t\t\t\tif (sitr.hasNext()) {\n\t\t\t\t\t\t\tif (retlst == null) {\n\t\t\t\t\t\t\t\tretlst = new ArrayList();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\twhile (sitr.hasNext()) {\n\t\t\t\t\t\t\t\tRDFNode obj = sitr.nextStatement().getObject();\n\t\t\t\t\t\t\t\tif (obj.isURIResource()) {\n\t\t\t\t\t\t\t\t\tConceptName cn = new ConceptName(obj.asResource().getURI());\n\t\t\t\t\t\t\t\t\tif (!retlst.contains(cn)) {\n\t\t\t\t\t\t\t\t\t\tretlst.add(cn);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} catch (CircularDependencyException e) {\n\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\t\n\t\t\t}\n\t\t}\n//\t\t// check superclasses\n//\t\tif (cls.canAs(OntClass.class)) {\n//\t\t\tOntClass ontcls = cls.as(OntClass.class);\n//\t\t\tExtendedIterator eitr = ontcls.listSuperClasses();\n//\t\t\twhile (eitr.hasNext()) {\n//\t\t\t\tOntClass supercls = eitr.next();\n//\t\t\t\tList scips = getImpliedProperties(supercls);\n//\t\t\t\tif (scips != null) {\n//\t\t\t\t\tif (retlst == null) {\n//\t\t\t\t\t\tretlst = scips;\n//\t\t\t\t\t}\n//\t\t\t\t\telse {\n//\t\t\t\t\t\tfor (int i = 0; i < scips.size(); i++) {\n//\t\t\t\t\t\t\tConceptName cn = scips.get(i);\n//\t\t\t\t\t\t\tif (!scips.contains(cn)) {\n//\t\t\t\t\t\t\t\tretlst.add(scips.get(i));\n//\t\t\t\t\t\t\t}\n//\t\t\t\t\t\t}\n//\t\t\t\t\t}\n//\t\t\t\t}\n//\t\t\t}\n//\t\t}\n//\t\tStmtIterator sitr = getTheJenaModel().listStatements(cls, getTheJenaModel().getProperty(SadlConstants.SADL_IMPLICIT_MODEL_IMPLIED_PROPERTY_URI), (RDFNode)null);\n//\t\tif (sitr.hasNext()) {\n//\t\t\tif (retlst == null) {\n//\t\t\t\tretlst = new ArrayList();\n//\t\t\t}\n//\t\t\twhile (sitr.hasNext()) {\n//\t\t\t\tRDFNode obj = sitr.nextStatement().getObject();\n//\t\t\t\tif (obj.isURIResource()) {\n//\t\t\t\t\tConceptName cn = new ConceptName(obj.asResource().getURI());\n//\t\t\t\t\tif (!retlst.contains(cn)) {\n//\t\t\t\t\t\tretlst.add(cn);\n//\t\t\t\t\t}\n//\t\t\t\t}\n//\t\t\t}\n//\t\t\treturn retlst;\n//\t\t}\n////\t\tif (retlst == null && cls.isURIResource() && cls.getURI().endsWith(\"#DATA\")) {\n//////\t\t\tdumpModel(getTheJenaModel());\n//////\t\t\tStmtIterator stmtitr = cls.listProperties();\n////\t\t\tStmtIterator stmtitr = getTheJenaModel().listStatements(cls, null, (RDFNode)null);\n////\t\t\twhile (stmtitr.hasNext()) {\n////\t\t\t\tSystem.out.println(stmtitr.next().toString());\n////\t\t\t}\n////\t\t}\n\t\treturn retlst;\n\t}\n\t\n\tprivate List getAllImpliedPropertyClasses() {\n\t\treturn allImpliedPropertyClasses;\n\t}\n\t\n\tprotected int initializeAllImpliedPropertyClasses () {\n\t\tint cntr = 0;\n\t\tallImpliedPropertyClasses = new ArrayList();\n\t\tStmtIterator sitr = getTheJenaModel().listStatements(null, getTheJenaModel().getProperty(SadlConstants.SADL_IMPLICIT_MODEL_IMPLIED_PROPERTY_URI), (RDFNode)null);\n\t\tif (sitr.hasNext()) {\n\t\t\twhile (sitr.hasNext()) {\n\t\t\t\tcom.hp.hpl.jena.rdf.model.Resource subj = sitr.nextStatement().getSubject();\n\t\t\t\tif (subj.canAs(OntResource.class)) {\n\t\t\t\t\tOntResource or = subj.as(OntResource.class);\n\t\t\t\t\tif (!allImpliedPropertyClasses.contains(or)) {\n\t\t\t\t\t\tallImpliedPropertyClasses.add(or);\n\t\t\t\t\t\tcntr++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn cntr;\n\t}\n\t\n\t/**\n\t * Method to obtain the sadlimplicitmodel:expandedProperty annotation property values for the given class\n\t * @param cls -- the Jena Resource (nominally a class) for which the values are desired\n\t * @return -- a List of the URI strings of the values \n\t */\n\tpublic List getExpandedProperties(com.hp.hpl.jena.rdf.model.Resource cls) {\n\t\tList retlst = null;\n\t\tif (cls == null) return null;\n\t\t// check superclasses\n\t\tif (cls.canAs(OntClass.class)) {\n\t\t\tOntClass ontcls = cls.as(OntClass.class);\n\t\t\tExtendedIterator eitr = ontcls.listSuperClasses();\n\t\t\twhile (eitr.hasNext()) {\n\t\t\t\tOntClass supercls = eitr.next();\n\t\t\t\tList scips = getExpandedProperties(supercls);\n\t\t\t\tif (scips != null) {\n\t\t\t\t\tif (retlst == null) {\n\t\t\t\t\t\tretlst = scips;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tfor (int i = 0; i < scips.size(); i++) {\n\t\t\t\t\t\t\tString cn = scips.get(i);\n\t\t\t\t\t\t\tif (!scips.contains(cn)) {\n\t\t\t\t\t\t\t\tretlst.add(scips.get(i));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tStmtIterator sitr = getTheJenaModel().listStatements(cls, getTheJenaModel().getProperty(SadlConstants.SADL_IMPLICIT_MODEL_EXPANDED_PROPERTY_URI), (RDFNode)null);\n\t\tif (sitr.hasNext()) {\n\t\t\tif (retlst == null) {\n\t\t\t\tretlst = new ArrayList();\n\t\t\t}\n\t\t\twhile (sitr.hasNext()) {\n\t\t\t\tRDFNode obj = sitr.nextStatement().getObject();\n\t\t\t\tif (obj.isURIResource()) {\n\t\t\t\t\tString cn = obj.asResource().getURI();\n\t\t\t\t\tif (!retlst.contains(cn)) {\n\t\t\t\t\t\tretlst.add(cn);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn retlst;\n\t\t}\n\t\treturn retlst;\n\t}\n\t\n\tprotected boolean isLookingForFirstProperty() {\n\t\treturn lookingForFirstProperty;\n\t}\n\n\tprotected void setLookingForFirstProperty(boolean lookingForFirstProperty) {\n\t\tthis.lookingForFirstProperty = lookingForFirstProperty;\n\t}\n\t\n\tpublic Equation getCurrentEquation() {\n\t\treturn currentEquation;\n\t}\n\t\n\tprotected void setCurrentEquation(Equation currentEquation) {\n\t\tthis.currentEquation = currentEquation;\n\t}\n\t\n\tpublic JenaBasedSadlModelValidator getModelValidator() throws TranslationException {\n\t\treturn modelValidator;\n\t}\n\t\n\tprotected void setModelValidator(JenaBasedSadlModelValidator modelValidator) {\n\t\tthis.modelValidator = modelValidator;\n\t}\n\n\tprotected void initializeModelValidator(){\n\t\tsetModelValidator(new JenaBasedSadlModelValidator(issueAcceptor, getTheJenaModel(), getDeclarationExtensions(), this, getMetricsProcessor()));\n\t}\n\t\n\tprotected IMetricsProcessor getMetricsProcessor() {\n\t\treturn metricsProcessor;\n\t}\n\t\n\tprotected void setMetricsProcessor(IMetricsProcessor metricsProcessor) {\n\t\tthis.metricsProcessor = metricsProcessor;\n\t}\n\n\tprotected String rdfNodeToString(RDFNode node) {\n\t\tif (node.isLiteral()) {\n\t\t\treturn node.asLiteral().getValue().toString();\n\t\t}\n\t\telse if (node.isURIResource() && getConfigMgr() != null) {\n\t\t\tString prefix = getConfigMgr().getGlobalPrefix(node.asResource().getNameSpace());\n\t\t\tif (prefix != null) {\n\t\t\t\treturn prefix + \":\" + node.asResource().getLocalName();\n\t\t\t}\n\t\t}\n\t\treturn node.toString();\n\t}\n\n\tprotected String conceptIdentifierToString(ConceptIdentifier ci) {\n\t\tif (ci instanceof ConceptName) {\n\t\t\tif (getConfigMgr() != null && ((ConceptName)ci).getPrefix() == null && ((ConceptName)ci).getNamespace() != null) {\n\t\t\t\tString ns = ((ConceptName)ci).getNamespace();\n\t\t\t\tif (ns.endsWith(\"#\")) {\n\t\t\t\t\tns = ns.substring(0, ns.length() - 1);\n\t\t\t\t}\n\t\t\t\tString prefix = getConfigMgr().getGlobalPrefix(ns);\n\t\t\t\tif (prefix == null) {\n\t\t\t\t\treturn ((ConceptName)ci).getName();\n\t\t\t\t}\n\t\t\t\t((ConceptName)ci).setPrefix(prefix);\n\t\t\t}\n\t\t\treturn ((ConceptName)ci).toString();\n\t\t}\n\t\treturn ci.toString();\n\t}\n\t\n\tpublic boolean isNumericComparisonOperator(String operation) {\n\t\tif (numericComparisonOperators.contains(operation)) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tpublic boolean isEqualityInequalityComparisonOperator(String operation) {\n\t\tif (equalityInequalityComparisonOperators.contains(operation)) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tpublic boolean isComparisonOperator(String operation) {\n\t\tif (comparisonOperators.contains(operation)) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic boolean isBooleanComparison(List operations) {\n\t\tif(comparisonOperators.containsAll(operations)){\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic boolean canBeNumericOperator(String op) {\n\t\tif (canBeNumericOperators.contains(op)) return true;\n\t\treturn false;\n\t}\n\n\tpublic boolean isNumericOperator(String op) {\n\t\tif (numericOperators.contains(op)) return true;\n\t\treturn false;\n\t}\n\n\tpublic boolean isNumericOperator(List operations) {\n\t\tIterator itr = operations.iterator();\n\t\twhile (itr.hasNext()) {\n\t\t\tif (isNumericOperator(itr.next())) return true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic boolean canBeNumericOperator(List operations) {\n\t\tIterator itr = operations.iterator();\n\t\twhile (itr.hasNext()) {\n\t\t\tif (canBeNumericOperator(itr.next())) return true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tpublic boolean isNumericType(ConceptName conceptName) {\n\t\ttry {\n\t\t\tif (conceptName.getName().equals(\"known\") && conceptName.getNamespace() == null) {\n\t\t\t\t// known matches everything\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tString uri = conceptName.getUri();\n\t\t\treturn isNumericType(uri);\n\t\t} catch (InvalidNameException e) {\n\t\t\t// OK, some constants don't have namespace and so aren't numeric\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic boolean isNumericType(String uri) {\n\t\tif (uri.equals(XSD.decimal.getURI()) ||\n\t\t\t\turi.equals(XSD.integer.getURI()) ||\n\t\t\t\turi.equals(XSD.xdouble.getURI()) ||\n\t\t\t\turi.equals(XSD.xfloat.getURI()) ||\n\t\t\t\turi.equals(XSD.xint.getURI()) ||\n\t\t\t\turi.equals(XSD.xlong.getURI())) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic boolean isBooleanType(String uri) {\n\t\tif (uri.equals(XSD.xboolean.getURI())) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\tprotected void setOwlFlavor(OWL_FLAVOR owlFlavor) {\n\t\tthis.owlFlavor = owlFlavor;\n\t}\n\tprotected boolean isTypeCheckingWarningsOnly() {\n\t\treturn typeCheckingWarningsOnly;\n\t}\n\tprotected void setTypeCheckingWarningsOnly(boolean typeCheckingWarningsOnly) {\n\t\tthis.typeCheckingWarningsOnly = typeCheckingWarningsOnly;\n\t}\n\n\tprotected boolean isBinaryListOperator(String op) {\n\t\tif (op.equals(\"contain\") || op.equals(\"contains\") || op.equals(\"unique\")) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\tprotected boolean sharedDisjunctiveContainer(Expression expr1, Expression expr2) {\n\t\tif (expr1 != null) {\n\t\t\tEObject cont1 = expr1.eContainer();\n\t\t\tdo {\n\t\t\t\tif (cont1 instanceof BinaryOperation && ((BinaryOperation)cont1).getOp().equals(\"or\")) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcont1 = cont1.eContainer();\n\t\t\t} while (cont1 != null && cont1.eContainer() != null);\n\t\n\t\t\tif (expr2 != null) {\n\t\t\t\tEObject cont2 = expr2;\n\t\t\t\tdo {\n\t\t\t\t\tif (cont2 instanceof BinaryOperation && ((BinaryOperation)cont2).getOp().equals(\"or\")) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcont2 = cont2.eContainer();\n\t\t\t\t} while (cont2 != null && cont2.eContainer() != null);\n\t\t\t\tif (cont1 != null && cont2 != null && cont1.equals(cont2)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tpublic boolean isTypedListSubclass(RDFNode node) {\n\t\tif (node != null && node.isResource()) {\n\t\t\tif (node.asResource().hasProperty(RDFS.subClassOf, theJenaModel.getResource(SadlConstants.SADL_LIST_MODEL_LIST_URI))) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprotected boolean isEqualOperator(String op) {\n\t\tBuiltinType optype = BuiltinType.getType(op);\n\t\tif (optype.equals(BuiltinType.Equal)) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tpublic DeclarationExtensions getDeclarationExtensions() {\n\t\treturn declarationExtensions;\n\t}\n\t\n\tpublic void setDeclarationExtensions(DeclarationExtensions declarationExtensions) {\n\t\tthis.declarationExtensions = declarationExtensions;\n\t}\n\tprotected void addNamedStructureAnnotations(Individual namedStructure, EList annotations) throws TranslationException {\n\t\tIterator annitr = annotations.iterator();\n\t\tif (annitr.hasNext()) {\n\t\t\twhile (annitr.hasNext()) {\n\t\t\t\tNamedStructureAnnotation ra = annitr.next();\n\t\t\t\tString annuri = getDeclarationExtensions().getConceptUri(ra.getType());\n\t\t\t\tProperty annProp = getTheJenaModel().getProperty(annuri);\n\t\t\t\ttry {\n\t\t\t\t\tif (annProp == null || !isProperty(getDeclarationExtensions().getOntConceptType(ra.getType()))) {\n\t\t\t\t\t\tissueAcceptor.addError(\"Annotation property '\" + annuri + \"' not found in model\", ra);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t} catch (CircularDefinitionException e1) {\n\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\te1.printStackTrace();\n\t\t\t\t}\n\t\t\t\tIterator cntntitr = ra.getContents().iterator();\n\t\t\t\tStringBuilder sb = new StringBuilder();\n\t\t\t\tint cntr = 0;\n\t\t\t\twhile (cntntitr.hasNext()) {\n\t\t\t\t\tSadlExplicitValue annvalue = cntntitr.next();\n\t\t\t\t\tif (annvalue instanceof SadlResource) {\n\t\t\t\t\t\tNode n = processExpression((SadlResource)annvalue);\n\t\t\t\t\t\tOntResource nor = getTheJenaModel().getOntResource(n.toFullyQualifiedString());\n\t\t\t\t\t\tif (nor != null) {\t\t// can be null during entry of statement in editor\n\t\t\t\t\t\t\tgetTheJenaModel().add(namedStructure, annProp, nor);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tcom.hp.hpl.jena.ontology.OntResource range = annProp.canAs(OntProperty.class) ? annProp.as(OntProperty.class).getRange() : null;\n\t\t\t\t\t\t\tcom.hp.hpl.jena.rdf.model.Literal annLiteral = sadlExplicitValueToLiteral(annvalue, range);\n\t\t\t\t\t\t\tgetTheJenaModel().add(namedStructure, annProp, annLiteral);\n\t\t\t\t\t\t\tif (cntr > 0) sb.append(\", \");\n\t\t\t\t\t\t\tsb.append(\"\\\"\");\n\t\t\t\t\t\t\tsb.append(annvalue);\n\t\t\t\t\t\t\tsb.append(\"\\\"\");\n\t\t\t\t\t\t\tcntr++;\n\t\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t\t} //getTheJenaModel().createTypedLiteral(annvalue);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlogger.debug(\"Named structure annotation: \" + getDeclarationExtensions().getConceptUri(ra.getType()) + \" = \" + sb.toString());\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprotected Declaration getDeclarationFromSubjHasProp(SubjHasProp subject) {\n\t\tExpression left = subject.getLeft();\n\t\tif (left instanceof Declaration) {\n\t\t\treturn (Declaration)left;\n\t\t}\n\t\telse if (left instanceof SubjHasProp) {\n\t\t\treturn getDeclarationFromSubjHasProp((SubjHasProp)left);\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprotected VariableNode getCruleVariable(NamedNode type, int ordNum) {\n\t\tList existingList = cruleVariables != null ? cruleVariables.get(type) : null;\n\t\tif (existingList != null && ordNum >= 0 && ordNum <= existingList.size()) {\n\t\t\treturn existingList.get(ordNum -1);\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprotected VariableNode addCruleVariable(NamedNode type, int ordinalNumber, String name, EObject expr, EObject host) throws TranslationException {\n\t\tif (cruleVariables == null) {\n\t\t\tcruleVariables = new HashMap>();\n\t\t}\n\t\tif (!cruleVariables.containsKey(type)) {\n\t\t\tList newList = new ArrayList();\n\t\t\tVariableNode var = new VariableNode(name);\n\t\t\tvar.setCRulesVariable(true);\n\t\t\tvar.setType(type);\n\t\t\tvar.setHostObject(getHostEObject());\n\t\t\tnewList.add(var);\n\t\t\tcruleVariables.put(type, newList);\n\t\t\treturn var;\n\t\t}\n\t\telse {\n\t\t\tList existingList = cruleVariables.get(type);\n\t\t\tIterator nodeitr = existingList.iterator();\n\t\t\twhile (nodeitr.hasNext()) {\n\t\t\t\tif (nodeitr.next().getName().equals(name)) {\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t}\n\t\t\tint idx = existingList.size();\n\t\t\tif (idx == ordinalNumber - 1) {\n\t\t\t\tVariableNode var = new VariableNode(name);\n\t\t\t\tvar.setCRulesVariable(true);\n\t\t\t\tvar.setType(type);\n\t\t\t\tvar.setHostObject(getHostEObject());\n\t\t\t\texistingList.add(var);\n\t\t\t\treturn var;\n\t\t\t}\n\t\t\telse {\n\t\t\t\taddError(\"There is already an implicit variable with ordinality \" + ordinalNumber + \". Please use 'a \" + nextOrdinal(ordinalNumber) + \n\t\t\t\t\t\t\"' to create another implicit variable or 'the \" + nextOrdinal(ordinalNumber - 1) + \"' to refer to the existing implicit variable.\", expr);\n\t\t\t\treturn existingList.get(existingList.size() - 1);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprotected void clearCruleVariables() {\n\t\tif (cruleVariables != null) {\n\t\t\tcruleVariables.clear();\n\t\t}\n\t\tvNum = 0;\t// reset system-generated variable name counter\n\t}\n\t\n\tprotected void clearCruleVariablesForHostObject(EObject host) {\n\t\tif (cruleVariables != null) {\n\t\t\tIterator crvitr = cruleVariables.keySet().iterator();\n\t\t\twhile (crvitr.hasNext()) {\n\t\t\t\tList varsOfType = cruleVariables.get(crvitr.next());\n\t\t\t\tfor (int i = varsOfType.size() - 1; i >= 0; i--) {\n\t\t\t\t\tif (varsOfType.get(i).getHostObject() != null && varsOfType.get(i).getHostObject().equals(host)) {\n\t\t\t\t\t\tvarsOfType.remove(i);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprotected void processModelImports(Ontology modelOntology, URI importingResourceUri, SadlModel model) throws OperationCanceledError {\n\t\tEList implist = model.getImports();\n\t\tIterator impitr = implist.iterator();\n\t\twhile (impitr.hasNext()) {\n\t\t\tSadlImport simport = impitr.next();\n\t\t\tSadlModel importedResource = simport.getImportedResource();\n\t\t\tif (importedResource != null) {\n\t\t\t\t//\t\t\t\t\tURI importingResourceUri = resource.getURI();\n\t\t\t\tString importUri = importedResource.getBaseUri();\n\t\t\t\tString importPrefix = simport.getAlias();\n\t\t\t\tResource eResource = importedResource.eResource();\n\t\t\t\tif (eResource instanceof XtextResource) {\n\t\t\t\t\tXtextResource xtrsrc = (XtextResource) eResource;\n\t\t\t\t\tURI importedResourceUri = xtrsrc.getURI();\n\t\t\t\t\tOntModel importedOntModel = OntModelProvider.find(xtrsrc);\n\t\t\t\t\tif (importedOntModel == null) {\n\t\t\t\t\t\tlogger.debug(\"JenaBasedSadlModelProcessor failed to resolve null OntModel for Resource '\" + importedResourceUri + \"' while processing Resource '\" + importingResourceUri + \"'\");\n\t\t\t\t\t} else {\n\t\t\t\t\t\taddImportToJenaModel(modelName, importUri, importPrefix, importedOntModel);\t\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t} else if (eResource instanceof ExternalEmfResource) {\n\t\t\t\t\tExternalEmfResource emfResource = (ExternalEmfResource) eResource;\n\t\t\t\t\taddImportToJenaModel(modelName, importUri, importPrefix, emfResource.getJenaModel());\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t}\n\n\t//\tprotected Literal sadlExplicitValueToLiteral(SadlExplicitValue value, OntProperty prop) throws JenaProcessorException, TranslationException {\n\tprotected boolean isEObjectPreprocessed(EObject eobj) {\n\t\tif (preprocessedEObjects != null && preprocessedEObjects.contains(eobj)) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprotected boolean eobjectPreprocessed(EObject eobj) {\n\t\tif (preprocessedEObjects == null) {\n\t\t\tpreprocessedEObjects = new ArrayList();\n\t\t\tpreprocessedEObjects.add(eobj);\n\t\t\treturn true;\n\t\t}\n\t\tif (preprocessedEObjects.contains(eobj)) {\n\t\t\treturn false;\n\t\t}\n\t\tpreprocessedEObjects.add(eobj);\n\t\treturn true;\n\t}\n\t\n//\tprotected Literal sadlExplicitValueToLiteral(SadlExplicitValue value, OntProperty prop) throws JenaProcessorException, TranslationException {\n//\t\tif (value instanceof SadlNumberLiteral) {\n//\t\t\tString strval = ((SadlNumberLiteral)value).getLiteralNumber();\n//\t\t\treturn SadlUtils.getLiteralMatchingDataPropertyRange(getTheJenaModel(), prop, strval);\n//\t\t}\n//\t\telse if (value instanceof SadlStringLiteral) {\n//\t\t\tString val = ((SadlStringLiteral)value).getLiteralString();\n//\t\t\treturn SadlUtils.getLiteralMatchingDataPropertyRange(getTheJenaModel(), prop, val);\n//\t\t}\n//\t\telse if (value instanceof SadlBooleanLiteral) {\n//\t\t\tSadlBooleanLiteral val = ((SadlBooleanLiteral)value);\n//\t\t\treturn SadlUtils.getLiteralMatchingDataPropertyRange(getTheJenaModel(), prop, val.toString());\n//\t\t}\n//\t\telse if (value instanceof SadlValueList) {\n//\t\t\tthrow new JenaProcessorException(\"A SADL value list cannot be converted to a Literal\");\n//\t\t}\n//\t\telse if (value instanceof SadlConstantLiteral) {\n//\t\t\tString val = ((SadlConstantLiteral)value).getTerm();\n//\t\t\treturn SadlUtils.getLiteralMatchingDataPropertyRange(getTheJenaModel(), prop, val);\n//\t\t}\n//\t\telse {\n//\t\t\tthrow new JenaProcessorException(\"Unhandled sadl explicit vaue type: \" + value.getClass().getCanonicalName());\n//\t\t}\n//\t}\n\n\tprotected void checkShallForControlledProperty(Expression expr) {\n\t\tOntConceptType exprType = null;\n\t\tSadlResource sr = null;\n\t\tif (expr instanceof Name) {\n\t\t\tsr = ((Name)expr).getName();\n\t\t}\n\t\telse if (expr instanceof SadlResource) {\n\t\t\tsr = (SadlResource) expr;\n\t\t}\n\t\tif (sr != null) {\n\t\t\ttry {\n\t\t\t\texprType = getDeclarationExtensions().getOntConceptType(sr);\n\t\t\t\tif (!isProperty(exprType)) {\n\t\t\t\t\taddError(\"Expected a property as controlled variable in a Requirement shall statement\", expr);\n\t\t\t\t}\n\t\t\t} catch (CircularDefinitionException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected List getControlledPropertiesForTable(Expression expr) {\n\t\tList results = new ArrayList();\n\t\tif (expr instanceof Name) {\n\t\t\tresults.add(((Name)expr).getName());\n\t\t}\n\t\telse if (expr instanceof SadlResource) {\n\t\t\tresults.add((SadlResource) expr);\n\t\t}\n\t\telse if (expr instanceof BinaryOperation && ((BinaryOperation)expr).getOp().equals(\"and\")) {\n\t\t\tList leftList = getControlledPropertiesForTable(((BinaryOperation)expr).getLeft());\n\t\t\tif (leftList != null) {\n\t\t\t\tresults.addAll(leftList);\n\t\t\t}\n\t\t\tList rightList = getControlledPropertiesForTable(((BinaryOperation)expr).getRight());\n\t\t\tif (rightList != null) {\n\t\t\t\tresults.addAll(rightList);\n\t\t\t}\n\t\t}\n\t\telse if (expr instanceof PropOfSubject) {\n\t\t\tList propList = getControlledPropertiesForTable(((PropOfSubject)expr).getLeft());\n\t\t\tif (propList != null) {\n\t\t\t\tresults.addAll(propList);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\taddError(\"Tabular requirement appears to have an invalid set statement\", expr);\n\t\t}\n\t\treturn results;\n\t}\n\t\n\tpublic VariableNode getVariable(String name) {\n\t\tObject trgt = getTarget();\n\t\tif (trgt instanceof Rule) {\n\t\t\treturn ((Rule)trgt).getVariable(name);\n\t\t}\n\t\telse if (trgt instanceof Query) {\n\t\t\treturn ((Query)trgt).getVariable(name);\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprivate void setSadlCommands(List sadlCommands) {\n\t\tthis.sadlCommands = sadlCommands;\n\t}\n\t\n\t/* (non-Javadoc)\n\t * @see com.ge.research.sadl.jena.IJenaBasedModelProcessor#compareTranslations(java.lang.String, java.lang.String)\n\t */\n\t@Override\n\tpublic boolean compareTranslations(String result, String evalTo) {\n\t\tevalTo = removeNewLines(evalTo);\n\t\tevalTo = removeLocation(evalTo);\n\t\tresult = removeNewLines(result);\n\t\tresult = removeLocation(result);\n\t\tboolean stat = result.equals(evalTo);\n\t\tif (!stat) {\n\t\t\tSystem.err.println(\"Comparison failed:\");\n\t\t\tSystem.err.println(\" \" + result);\n\t\t\tSystem.err.println(\" \" + evalTo);\n\t\t}\n\t\treturn stat;\n\t}\n\t\n\tprotected String removeNewLines(String evalTo) {\n\t String cleanString = evalTo.replaceAll(\"\\r\", \"\").replaceAll(\"\\n\", \"\").replaceAll(\" \", \"\");\n\t\treturn cleanString;\n\t}\n\t\n\tprotected String removeLocation(String str) {\n\t\tint locloc = str.indexOf(\"location(\");\n\t\twhile (locloc > 0) {\n\t\t\tint afterloc = str.indexOf(\"sreq(name(\", locloc);\n\t\t\tString before = str.substring(0, locloc);\n\t\t\tint realStart = before.lastIndexOf(\"sreq(name(\");\n\t\t\tif (realStart > 0) {\n\t\t\t\tbefore = str.substring(0, realStart);\n\t\t\t}\n\t\t\tif (afterloc > 0) {\n\t\t\t\tString after = str.substring(afterloc);\n\t\t\t\tstr = before + after;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tstr = before;\n\t\t\t}\n\t\t\tlocloc = str.indexOf(\"location(\");\n\t\t}\n\t\treturn str;\n\t}\n\tpublic boolean isUseArticlesInValidation() {\n\t\treturn useArticlesInValidation;\n\t}\n\tpublic void setUseArticlesInValidation(boolean useArticlesInValidation) {\n\t\tthis.useArticlesInValidation = useArticlesInValidation;\n\t}\n\n}\n"},"message":{"kind":"string","value":"fixed ignoring of negation on SadlExplicitValue\n"},"old_file":{"kind":"string","value":"sadl3/com.ge.research.sadl.parent/com.ge.research.sadl.jena/src/com/ge/research/sadl/jena/JenaBasedSadlModelProcessor.java"},"subject":{"kind":"string","value":"fixed ignoring of negation on SadlExplicitValue"},"git_diff":{"kind":"string","value":"adl3/com.ge.research.sadl.parent/com.ge.research.sadl.jena/src/com/ge/research/sadl/jena/JenaBasedSadlModelProcessor.java\n \n \tprotected Literal sadlExplicitValueToLiteral(SadlExplicitValue value, com.hp.hpl.jena.rdf.model.Resource rng) throws JenaProcessorException {\n \t\ttry {\n\t\t\tboolean isNegated = false;\n \t\t\tif (value instanceof SadlUnaryExpression) {\n \t\t\t\tString op = ((SadlUnaryExpression)value).getOperator();\n \t\t\t\tif (op.equals(\"-\")) {\n \t\t\t\t\tvalue = ((SadlUnaryExpression)value).getValue();\n\t\t\t\t\tisNegated = true;\n \t\t\t\t}\n \t\t\t\telse {\n \t\t\t\t\tthrow new JenaProcessorException(\"Unhandled case of unary operator on SadlExplicitValue: \" + op);\n \t\t\t}\n \t\t\tif (value instanceof SadlNumberLiteral) {\n \t\t\t\tString val = ((SadlNumberLiteral)value).getLiteralNumber().toPlainString();\n\t\t\t\tif (isNegated) {\n\t\t\t\t\tval = \"-\" + val;\n\t\t\t\t}\n \t\t\t\tif (rng != null && rng.getURI() != null) {\n \t\t\t\t\treturn SadlUtils.getLiteralMatchingDataPropertyRange(getTheJenaModel(), rng.getURI(), val);\n \t\t\t\t}\n \t\t\t}\n \t\t\telse if (value instanceof SadlStringLiteral) {\n \t\t\t\tString val = ((SadlStringLiteral)value).getLiteralString();\n\t\t\t\tif (isNegated) {\n\t\t\t\t\tval = \"-\" + val;\n\t\t\t\t}\n \t\t\t\tif (rng != null) {\n \t\t\t\t\treturn SadlUtils.getLiteralMatchingDataPropertyRange(getTheJenaModel(), rng.getURI(), val);\n \t\t\t\t}\n \t\t\telse if (value instanceof SadlConstantLiteral) {\n \t\t\t\tString val = ((SadlConstantLiteral)value).getTerm();\n \t\t\t\tif (val.equals(\"PI\")) {\n\t\t\t\t\treturn SadlUtils.getLiteralMatchingDataPropertyRange(getTheJenaModel(), rng.getURI(), Math.PI);\n\t\t\t\t\tdouble cv = Math.PI;\n\t\t\t\t\tif (isNegated) {\n\t\t\t\t\t\tcv = cv*-1.0;\n\t\t\t\t\t}\n\t\t\t\t\treturn SadlUtils.getLiteralMatchingDataPropertyRange(getTheJenaModel(), rng.getURI(), cv);\n \t\t\t\t}\n \t\t\t\telse if (val.equals(\"e\")) {\n\t\t\t\t\treturn SadlUtils.getLiteralMatchingDataPropertyRange(getTheJenaModel(), rng.getURI(), Math.E);\t\t\t\t\t\n\t\t\t\t\tdouble cv = Math.E;\n\t\t\t\t\tif (isNegated) {\n\t\t\t\t\t\tcv = cv*-1.0;\n\t\t\t\t\t}\n\t\t\t\t\treturn SadlUtils.getLiteralMatchingDataPropertyRange(getTheJenaModel(), rng.getURI(), cv);\t\t\t\t\t\n \t\t\t\t}\n \t\t\t\telse if (rng != null) {\n\t\t\t\t\tif (isNegated) {\n\t\t\t\t\t\tval = \"-\" + val;\n\t\t\t\t\t}\n \t\t\t\t\treturn SadlUtils.getLiteralMatchingDataPropertyRange(getTheJenaModel(), rng.getURI(), val);\n \t\t\t\t}\n \t\t\t\telse {\n\t\t\t\t\tif (isNegated) {\n\t\t\t\t\t\tval = \"-\" + val;\n\t\t\t\t\t}\n \t\t\t\t\ttry {\n \t\t\t\t\t\tint ival = Integer.parseInt(val);\n \t\t\t\t\t\treturn getTheJenaModel().createTypedLiteral(ival);"}}},{"rowIdx":1976,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"78f62d9b275a083165c8439f6d274ae58c2479a6"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"sheungon/SMSInterceptor"},"new_contents":{"kind":"string","value":"package com.sheungon.smsinterceptor;\n\nimport android.os.Bundle;\nimport android.os.FileObserver;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.support.annotation.UiThread;\nimport android.support.v4.app.Fragment;\nimport android.support.v4.app.FragmentActivity;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.EditText;\nimport android.widget.TextView;\nimport android.widget.ToggleButton;\n\nimport com.sheungon.smsinterceptor.service.SMSInterceptorSettings;\nimport com.sheungon.smsinterceptor.util.FileUtil;\nimport com.sheungon.smsinterceptor.util.Log;\nimport com.sheungon.smsinterceptor.util.LogcatUtil;\nimport com.sheungon.smsinterceptor.util.UIUtil;\n\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.PrintWriter;\nimport java.lang.ref.WeakReference;\n\nimport butterknife.BindView;\nimport butterknife.BindViews;\nimport butterknife.ButterKnife;\nimport butterknife.OnCheckedChanged;\nimport butterknife.OnClick;\nimport butterknife.Unbinder;\n\n/**\n * @author John\n */\npublic class MainFragment extends Fragment {\n\n private static final ButterKnife.Setter BK_ENABLE = new ButterKnife.Setter() {\n @Override public void set(@NonNull View view, Boolean enable, int index) {\n if (!enable) {\n view.clearFocus();\n }\n view.setEnabled(enable);\n }\n };\n\n private static final String REGEX_HTTP_PROTOCOL = \"^[Hh][Tt][Tt][Pp][Ss]?://.+\";\n public static final String SLASH = \"/\";\n public static final String REGEX_START_SLASH = \"^/+\";\n\n\n @BindView(R.id.base_url) EditText mBaseUrl;\n @BindView(R.id.server_api) EditText mServerAPI;\n @BindView(R.id.btn_toggle_service) ToggleButton mServiceBtn;\n @BindView(R.id.log) TextView mLogView;\n\n @BindViews({R.id.base_url, R.id.server_api})\n EditText[] mInputViews;\n\n private boolean mIgnoreToggle = false;\n private boolean mNeedUpdateLogViewOnResume = false;\n private Unbinder mUnbinder;\n private FileObserver mLogObserver;\n\n\n @Nullable\n @Override\n public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {\n\n return inflater.inflate(R.layout.fragment_main, container, false);\n }\n\n @Override\n public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {\n super.onViewCreated(view, savedInstanceState);\n\n mUnbinder = ButterKnife.bind(this, view);\n\n mBaseUrl.setText(SMSInterceptorSettings.getServerBaseUrl());\n mServerAPI.setText(SMSInterceptorSettings.getServerApi());\n\n // Get and show service state\n boolean serviceRunning = SMSReceiver.isReceiverEnabled();\n mIgnoreToggle = true;\n mServiceBtn.setChecked(serviceRunning);\n mIgnoreToggle = false;\n ButterKnife.apply(mInputViews, BK_ENABLE, !serviceRunning);\n\n // Show logcat log\n updateLogView();\n\n // Monitor logcat log file\n File logFile = FileUtil.getLogFile();\n if (logFile != null) {\n mLogObserver = new MyFileObserver(this,\n logFile.getPath(),\n FileObserver.MODIFY | FileObserver.DELETE | FileObserver.CLOSE_WRITE);\n mLogObserver.startWatching();\n }\n }\n\n @Override\n public void onResume() {\n super.onResume();\n\n if (mNeedUpdateLogViewOnResume) {\n updateLogView();\n mNeedUpdateLogViewOnResume = false;\n }\n }\n\n @Override\n public void onDestroyView() {\n super.onDestroyView();\n\n if (mLogObserver != null) {\n mLogObserver.stopWatching();\n mLogObserver = null;\n }\n\n if (mUnbinder != null) {\n mUnbinder.unbind();\n mUnbinder = null;\n }\n }\n\n @SuppressWarnings(\"unused\")\n @OnCheckedChanged(R.id.btn_toggle_service)\n void onToggleService(@NonNull ToggleButton toggleButton, boolean isChecked) {\n\n if (mIgnoreToggle) {\n return;\n }\n\n if (isChecked) {\n String baseUrl = null;\n String serverApi = null;\n\n // Validate input\n FragmentActivity activity = getActivity();\n if (activity != null) {\n UIUtil.hideSoftKeyboard(activity);\n }\n\n boolean inputInvalid = false;\n\n // Empty check\n String errorMsg = null;\n for (EditText inputView : mInputViews) {\n String input = inputView.getText().toString();\n if (input.isEmpty()) {\n if (errorMsg == null) {\n errorMsg = getString(R.string.error_input);\n }\n inputView.setError(errorMsg);\n\n if (!inputInvalid) {\n // Focus to the first missing input\n inputView.requestFocus();\n inputInvalid = true;\n }\n }\n }\n\n // Validate input\n if (!inputInvalid) {\n baseUrl = mBaseUrl.getText().toString();\n if (!baseUrl.matches(REGEX_HTTP_PROTOCOL)) {\n mBaseUrl.setError(getString(R.string.error_base_url_invalid_format));\n mBaseUrl.requestFocus();\n inputInvalid = true;\n }\n if (!baseUrl.endsWith(SLASH)) {\n baseUrl += SLASH;\n mBaseUrl.setText(baseUrl);\n }\n }\n serverApi = mServerAPI.getText().toString();\n serverApi = serverApi.replaceAll(REGEX_START_SLASH, \"\");\n mServerAPI.setText(serverApi);\n\n if (inputInvalid) {\n toggleButton.setChecked(false);\n return;\n }\n\n // Save the setting\n SMSInterceptorSettings.setServerApi(serverApi);\n SMSInterceptorSettings.setServerBaseUrl(baseUrl);\n }\n\n // Update view state\n ButterKnife.apply(mInputViews, BK_ENABLE, !isChecked);\n\n // Update Receiver\n SMSReceiver.enableReceiver(isChecked);\n }\n\n boolean isViewReleased() {\n return mUnbinder == null;\n }\n\n @SuppressWarnings(\"unused\")\n @OnClick(R.id.btn_clear_log)\n void onClickClearLog() {\n\n File logFile = FileUtil.getLogFile();\n if (logFile == null) {\n Log.w(\"No logfile?!\");\n return;\n }\n\n SMSApplication app = SMSApplication.getInstance();\n LogcatUtil.stopLogcat(app);\n\n // Clear log file\n if (logFile.isFile() &&\n logFile.canWrite()) {\n PrintWriter writer = null;\n try {\n writer = new PrintWriter(logFile);\n writer.print(\"\");\n } catch (FileNotFoundException e) {\n Log.e(\"Error on write to log file\", e);\n } finally {\n if (writer != null) {\n try {\n writer.close();\n } catch (Exception e) {\n // Do nothing\n }\n }\n }\n Log.d(\"Log file cleared.\");\n }\n\n LogcatUtil.resetLogcat(app, logFile);\n }\n\n @UiThread\n private void updateLogView() {\n\n if (isViewReleased()) {\n return;\n }\n\n if (!isResumed()) {\n // Suspend the view update to resume\n mNeedUpdateLogViewOnResume = true;\n return;\n }\n\n File logFile = FileUtil.getLogFile();\n if (logFile == null ||\n !logFile.isFile() ||\n !logFile.canRead()) {\n if (logFile != null &&\n !logFile.isFile()) {\n // Log file not yet created\n mLogView.setText(\"\");\n } else {\n mLogView.setText(R.string.error_read_log);\n }\n return;\n }\n\n StringBuilder logContentBuilder = new StringBuilder();\n FileUtil.readTextFile(logFile, logContentBuilder);\n mLogView.setText(logContentBuilder);\n }\n\n\n ///////////////////////////\n // Class and interface\n ///////////////////////////\n private static class MyFileObserver extends FileObserver {\n\n private final WeakReference mFragmentRef;\n private final Runnable mUpdateLogTask = new Runnable() {\n @Override\n public void run() {\n MainFragment fragment = mFragmentRef.get();\n if (fragment == null) {\n return;\n }\n fragment.updateLogView();\n }\n };\n\n public MyFileObserver(@NonNull MainFragment fragment,\n @NonNull String path,\n int mask) {\n super(path, mask);\n\n mFragmentRef = new WeakReference<>(fragment);\n }\n\n @Override\n public void onEvent(int event, String path) {\n\n MainFragment fragment = mFragmentRef.get();\n FragmentActivity activity = fragment == null ? null : fragment.getActivity();\n if (activity == null) {\n return;\n }\n\n switch (event) {\n case FileObserver.MODIFY:\n case FileObserver.CLOSE_WRITE:\n case FileObserver.DELETE:\n case FileObserver.DELETE_SELF:\n activity.runOnUiThread(mUpdateLogTask);\n break;\n }\n }\n }\n}\n"},"new_file":{"kind":"string","value":"app/src/main/java/com/sheungon/smsinterceptor/MainFragment.java"},"old_contents":{"kind":"string","value":"package com.sheungon.smsinterceptor;\n\nimport android.os.Bundle;\nimport android.os.FileObserver;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.support.annotation.UiThread;\nimport android.support.v4.app.Fragment;\nimport android.support.v4.app.FragmentActivity;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.EditText;\nimport android.widget.TextView;\nimport android.widget.ToggleButton;\n\nimport com.sheungon.smsinterceptor.service.SMSInterceptorSettings;\nimport com.sheungon.smsinterceptor.util.FileUtil;\nimport com.sheungon.smsinterceptor.util.Log;\nimport com.sheungon.smsinterceptor.util.LogcatUtil;\nimport com.sheungon.smsinterceptor.util.UIUtil;\n\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.PrintWriter;\nimport java.lang.ref.WeakReference;\n\nimport butterknife.BindView;\nimport butterknife.BindViews;\nimport butterknife.ButterKnife;\nimport butterknife.OnCheckedChanged;\nimport butterknife.OnClick;\nimport butterknife.Unbinder;\n\n/**\n * @author John\n */\npublic class MainFragment extends Fragment {\n\n private static final ButterKnife.Setter BK_ENABLE = new ButterKnife.Setter() {\n @Override public void set(@NonNull View view, Boolean enable, int index) {\n if (!enable) {\n view.clearFocus();\n }\n view.setEnabled(enable);\n }\n };\n\n private static final String REGEX_HTTP_PROTOCOL = \"^[Hh][Tt][Tt][Pp][Ss]?://.+\";\n public static final String SLASH = \"/\";\n public static final String REGEX_START_SLASH = \"^/+\";\n\n\n @BindView(R.id.base_url) EditText mBaseUrl;\n @BindView(R.id.server_api) EditText mServerAPI;\n @BindView(R.id.btn_toggle_service) ToggleButton mServiceBtn;\n @BindView(R.id.log) TextView mLogView;\n\n @BindViews({R.id.base_url, R.id.server_api})\n EditText[] mInputViews;\n\n private boolean mIgnoreToggle = false;\n private boolean mNeedUpdateLogViewOnResume = false;\n private Unbinder mUnbinder;\n private FileObserver mLogObserver;\n\n\n @Nullable\n @Override\n public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {\n\n return inflater.inflate(R.layout.fragment_main, container, false);\n }\n\n @Override\n public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {\n super.onViewCreated(view, savedInstanceState);\n\n mUnbinder = ButterKnife.bind(this, view);\n\n mBaseUrl.setText(SMSInterceptorSettings.getServerBaseUrl());\n mServerAPI.setText(SMSInterceptorSettings.getServerApi());\n\n // Get and show service state\n boolean serviceRunning = SMSReceiver.isReceiverEnabled();\n mIgnoreToggle = true;\n mServiceBtn.setChecked(serviceRunning);\n mIgnoreToggle = false;\n ButterKnife.apply(mInputViews, BK_ENABLE, !serviceRunning);\n\n // Show logcat log\n updateLogView();\n\n // Monitor logcat log file\n File logFile = FileUtil.getLogFile();\n if (logFile != null) {\n mLogObserver = new MyFileObserver(this,\n logFile.getPath(),\n FileObserver.MODIFY | FileObserver.DELETE | FileObserver.CLOSE_WRITE);\n mLogObserver.startWatching();\n }\n }\n\n @Override\n public void onResume() {\n super.onResume();\n\n if (mNeedUpdateLogViewOnResume) {\n updateLogView();\n mNeedUpdateLogViewOnResume = false;\n }\n }\n\n @Override\n public void onDestroyView() {\n super.onDestroyView();\n\n if (mLogObserver != null) {\n mLogObserver.stopWatching();\n mLogObserver = null;\n }\n\n if (mUnbinder != null) {\n mUnbinder.unbind();\n mUnbinder = null;\n }\n }\n\n @SuppressWarnings(\"unused\")\n @OnCheckedChanged(R.id.btn_toggle_service)\n void onToggleService(@NonNull ToggleButton toggleButton, boolean isChecked) {\n\n if (mIgnoreToggle) {\n return;\n }\n\n if (isChecked) {\n String baseUrl = null;\n String serverApi = null;\n\n // Validate input\n FragmentActivity activity = getActivity();\n if (activity != null) {\n UIUtil.hideSoftKeyboard(activity);\n }\n\n boolean inputInvalid = false;\n\n // Empty check\n String errorMsg = null;\n for (EditText inputView : mInputViews) {\n String input = inputView.getText().toString();\n if (input.isEmpty()) {\n if (errorMsg == null) {\n errorMsg = getString(R.string.error_input);\n }\n inputView.setError(errorMsg);\n\n if (!inputInvalid) {\n // Focus to the first missing input\n inputView.requestFocus();\n inputInvalid = true;\n }\n }\n }\n\n // Validate input\n if (!inputInvalid) {\n baseUrl = mBaseUrl.getText().toString();\n if (!baseUrl.matches(REGEX_HTTP_PROTOCOL)) {\n mBaseUrl.setError(getString(R.string.error_base_url_invalid_format));\n mBaseUrl.requestFocus();\n inputInvalid = true;\n }\n if (!baseUrl.endsWith(SLASH)) {\n baseUrl += SLASH;\n mBaseUrl.setText(baseUrl);\n }\n }\n serverApi = mServerAPI.getText().toString();\n serverApi = serverApi.replaceAll(REGEX_START_SLASH, \"\");\n mServerAPI.setText(serverApi);\n\n if (inputInvalid) {\n toggleButton.setChecked(false);\n return;\n }\n\n // Save the setting\n SMSInterceptorSettings.setServerApi(serverApi);\n SMSInterceptorSettings.setServerBaseUrl(baseUrl);\n }\n\n // Update view state\n ButterKnife.apply(mInputViews, BK_ENABLE, !isChecked);\n\n // Update Receiver\n SMSReceiver.enableReceiver(isChecked);\n }\n\n boolean isViewReleased() {\n return mUnbinder == null;\n }\n\n @SuppressWarnings(\"unused\")\n @OnClick(R.id.btn_clear_log)\n void onClickClearLog() {\n\n File logFile = FileUtil.getLogFile();\n if (logFile == null) {\n Log.w(\"No logfile?!\");\n return;\n }\n\n SMSApplication app = SMSApplication.getInstance();\n LogcatUtil.stopLogcat(app);\n\n // Clear log file\n if (logFile.isFile() &&\n logFile.canWrite()) {\n PrintWriter writer = null;\n try {\n writer = new PrintWriter(logFile);\n writer.print(\"\");\n } catch (FileNotFoundException e) {\n Log.e(\"Error on write to log file\", e);\n } finally {\n if (writer != null) {\n try {\n writer.close();\n } catch (Exception e) {\n // Do nothing\n }\n }\n }\n Log.d(\"Log file cleared.\");\n }\n\n LogcatUtil.resetLogcat(app, logFile);\n }\n\n @UiThread\n private void updateLogView() {\n\n if (isViewReleased()) {\n return;\n }\n\n if (!isResumed()) {\n // Suspend the view update to resume\n mNeedUpdateLogViewOnResume = true;\n return;\n }\n\n File logFile = FileUtil.getLogFile();\n if (logFile == null ||\n !logFile.isFile() ||\n !logFile.canRead()) {\n if (logFile != null &&\n !logFile.isFile()) {\n // Log file not yet created\n mLogView.setText(\"\");\n } else {\n mLogView.setText(R.string.error_read_log);\n }\n return;\n }\n\n StringBuilder logContentBuilder = new StringBuilder();\n FileUtil.readTextFile(logFile, logContentBuilder);\n mLogView.setText(logContentBuilder);\n }\n\n\n ///////////////////////////\n // Class and interface\n ///////////////////////////\n private static class MyFileObserver extends FileObserver {\n\n private final WeakReference mFragmentRef;\n private final Runnable mUpdateLogTask = new Runnable() {\n @Override\n public void run() {\n MainFragment fragment = mFragmentRef.get();\n if (fragment == null) {\n return;\n }\n fragment.updateLogView();\n }\n };\n\n public MyFileObserver(@NonNull MainFragment fragment,\n @NonNull String path,\n int mask) {\n super(path, mask);\n\n mFragmentRef = new WeakReference<>(fragment);\n }\n\n @Override\n public void onEvent(int event, String path) {\n\n MainFragment fragment = mFragmentRef.get();\n FragmentActivity activity = fragment == null ? null : fragment.getActivity();\n if (activity == null) {\n return;\n }\n\n switch (event) {\n case FileObserver.MODIFY:\n case FileObserver.CLOSE_WRITE:\n case FileObserver.DELETE:\n activity.runOnUiThread(mUpdateLogTask);\n break;\n }\n }\n }\n}\n"},"message":{"kind":"string","value":"Added missing log file monitor case.\n"},"old_file":{"kind":"string","value":"app/src/main/java/com/sheungon/smsinterceptor/MainFragment.java"},"subject":{"kind":"string","value":"Added missing log file monitor case."},"git_diff":{"kind":"string","value":"pp/src/main/java/com/sheungon/smsinterceptor/MainFragment.java\n case FileObserver.MODIFY:\n case FileObserver.CLOSE_WRITE:\n case FileObserver.DELETE:\n case FileObserver.DELETE_SELF:\n activity.runOnUiThread(mUpdateLogTask);\n break;\n }"}}},{"rowIdx":1977,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"013379fd3ee299ab6f24e8d42686af13249d54c2"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"ebr11/ExoPlayer,saki4510t/ExoPlayer,ened/ExoPlayer,google/ExoPlayer,amzn/exoplayer-amazon-port,stari4ek/ExoPlayer,androidx/media,MaTriXy/ExoPlayer,tntcrowd/ExoPlayer,KiminRyu/ExoPlayer,ebr11/ExoPlayer,androidx/media,ened/ExoPlayer,kiall/ExoPlayer,stari4ek/ExoPlayer,ened/ExoPlayer,amzn/exoplayer-amazon-port,saki4510t/ExoPlayer,superbderrick/ExoPlayer,amzn/exoplayer-amazon-port,tntcrowd/ExoPlayer,androidx/media,kiall/ExoPlayer,google/ExoPlayer,tntcrowd/ExoPlayer,MaTriXy/ExoPlayer,KiminRyu/ExoPlayer,superbderrick/ExoPlayer,google/ExoPlayer,kiall/ExoPlayer,stari4ek/ExoPlayer,ebr11/ExoPlayer,saki4510t/ExoPlayer,MaTriXy/ExoPlayer,superbderrick/ExoPlayer,KiminRyu/ExoPlayer"},"new_contents":{"kind":"string","value":"/*\n * Copyright (C) 2016 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.google.android.exoplayer2.ui;\n\nimport android.annotation.TargetApi;\nimport android.content.Context;\nimport android.content.res.Resources;\nimport android.content.res.TypedArray;\nimport android.graphics.Bitmap;\nimport android.graphics.BitmapFactory;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.util.AttributeSet;\nimport android.view.KeyEvent;\nimport android.view.LayoutInflater;\nimport android.view.MotionEvent;\nimport android.view.SurfaceView;\nimport android.view.TextureView;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.FrameLayout;\nimport android.widget.ImageView;\nimport com.google.android.exoplayer2.C;\nimport com.google.android.exoplayer2.ControlDispatcher;\nimport com.google.android.exoplayer2.DefaultControlDispatcher;\nimport com.google.android.exoplayer2.ExoPlaybackException;\nimport com.google.android.exoplayer2.PlaybackParameters;\nimport com.google.android.exoplayer2.Player;\nimport com.google.android.exoplayer2.SimpleExoPlayer;\nimport com.google.android.exoplayer2.Timeline;\nimport com.google.android.exoplayer2.metadata.Metadata;\nimport com.google.android.exoplayer2.metadata.id3.ApicFrame;\nimport com.google.android.exoplayer2.source.TrackGroupArray;\nimport com.google.android.exoplayer2.text.Cue;\nimport com.google.android.exoplayer2.text.TextOutput;\nimport com.google.android.exoplayer2.trackselection.TrackSelection;\nimport com.google.android.exoplayer2.trackselection.TrackSelectionArray;\nimport com.google.android.exoplayer2.ui.AspectRatioFrameLayout.ResizeMode;\nimport com.google.android.exoplayer2.util.Assertions;\nimport com.google.android.exoplayer2.util.RepeatModeUtil;\nimport com.google.android.exoplayer2.util.Util;\nimport java.util.List;\n\n/**\n * A high level view for {@link SimpleExoPlayer} media playbacks. It displays video, subtitles and\n * album art during playback, and displays playback controls using a {@link PlaybackControlView}.\n *

    \n * A SimpleExoPlayerView can be customized by setting attributes (or calling corresponding methods),\n * overriding the view's layout file or by specifying a custom view layout file, as outlined below.\n *\n *

    Attributes

    \n * The following attributes can be set on a SimpleExoPlayerView when used in a layout XML file:\n *

    \n *

      \n *
    • {@code use_artwork} - Whether artwork is used if available in audio streams.\n *
        \n *
      • Corresponding method: {@link #setUseArtwork(boolean)}
      • \n *
      • Default: {@code true}
      • \n *
      \n *
    • \n *
    • {@code default_artwork} - Default artwork to use if no artwork available in audio\n * streams.\n *
        \n *
      • Corresponding method: {@link #setDefaultArtwork(Bitmap)}
      • \n *
      • Default: {@code null}
      • \n *
      \n *
    • \n *
    • {@code use_controller} - Whether the playback controls can be shown.\n *
        \n *
      • Corresponding method: {@link #setUseController(boolean)}
      • \n *
      • Default: {@code true}
      • \n *
      \n *
    • \n *
    • {@code hide_on_touch} - Whether the playback controls are hidden by touch events.\n *
        \n *
      • Corresponding method: {@link #setControllerHideOnTouch(boolean)}
      • \n *
      • Default: {@code true}
      • \n *
      \n *
    • \n *
    • {@code auto_show} - Whether the playback controls are automatically shown when\n * playback starts, pauses, ends, or fails. If set to false, the playback controls can be\n * manually operated with {@link #showController()} and {@link #hideController()}.\n *
        \n *
      • Corresponding method: {@link #setControllerAutoShow(boolean)}
      • \n *
      • Default: {@code true}
      • \n *
      \n *
    • \n *
    • {@code resize_mode} - Controls how video and album art is resized within the view.\n * Valid values are {@code fit}, {@code fixed_width}, {@code fixed_height} and {@code fill}.\n *
        \n *
      • Corresponding method: {@link #setResizeMode(int)}
      • \n *
      • Default: {@code fit}
      • \n *
      \n *
    • \n *
    • {@code surface_type} - The type of surface view used for video playbacks. Valid\n * values are {@code surface_view}, {@code texture_view} and {@code none}. Using {@code none}\n * is recommended for audio only applications, since creating the surface can be expensive.\n * Using {@code surface_view} is recommended for video applications.\n *
        \n *
      • Corresponding method: None
      • \n *
      • Default: {@code surface_view}
      • \n *
      \n *
    • \n *
    • {@code player_layout_id} - Specifies the id of the layout to be inflated. See below\n * for more details.\n *
        \n *
      • Corresponding method: None
      • \n *
      • Default: {@code R.id.exo_simple_player_view}
      • \n *
      \n *
    • {@code controller_layout_id} - Specifies the id of the layout resource to be\n * inflated by the child {@link PlaybackControlView}. See below for more details.\n *
        \n *
      • Corresponding method: None
      • \n *
      • Default: {@code R.id.exo_playback_control_view}
      • \n *
      \n *
    • All attributes that can be set on a {@link PlaybackControlView} can also be set on a\n * SimpleExoPlayerView, and will be propagated to the inflated {@link PlaybackControlView}\n * unless the layout is overridden to specify a custom {@code exo_controller} (see below).\n *
    • \n *
    \n *\n *

    Overriding the layout file

    \n * To customize the layout of SimpleExoPlayerView throughout your app, or just for certain\n * configurations, you can define {@code exo_simple_player_view.xml} layout files in your\n * application {@code res/layout*} directories. These layouts will override the one provided by the\n * ExoPlayer library, and will be inflated for use by SimpleExoPlayerView. The view identifies and\n * binds its children by looking for the following ids:\n *

    \n *

      \n *
    • {@code exo_content_frame} - A frame whose aspect ratio is resized based on the video\n * or album art of the media being played, and the configured {@code resize_mode}. The video\n * surface view is inflated into this frame as its first child.\n *
        \n *
      • Type: {@link AspectRatioFrameLayout}
      • \n *
      \n *
    • \n *
    • {@code exo_shutter} - A view that's made visible when video should be hidden. This\n * view is typically an opaque view that covers the video surface view, thereby obscuring it\n * when visible.\n *
        \n *
      • Type: {@link View}
      • \n *
      \n *
    • \n *
    • {@code exo_subtitles} - Displays subtitles.\n *
        \n *
      • Type: {@link SubtitleView}
      • \n *
      \n *
    • \n *
    • {@code exo_artwork} - Displays album art.\n *
        \n *
      • Type: {@link ImageView}
      • \n *
      \n *
    • \n *
    • {@code exo_controller_placeholder} - A placeholder that's replaced with the inflated\n * {@link PlaybackControlView}. Ignored if an {@code exo_controller} view exists.\n *
        \n *
      • Type: {@link View}
      • \n *
      \n *
    • \n *
    • {@code exo_controller} - An already inflated {@link PlaybackControlView}. Allows use\n * of a custom extension of {@link PlaybackControlView}. Note that attributes such as\n * {@code rewind_increment} will not be automatically propagated through to this instance. If\n * a view exists with this id, any {@code exo_controller_placeholder} view will be ignored.\n *
        \n *
      • Type: {@link PlaybackControlView}
      • \n *
      \n *
    • \n *
    • {@code exo_overlay} - A {@link FrameLayout} positioned on top of the player which\n * the app can access via {@link #getOverlayFrameLayout()}, provided for convenience.\n *
        \n *
      • Type: {@link FrameLayout}
      • \n *
      \n *
    • \n *
    \n *

    \n * All child views are optional and so can be omitted if not required, however where defined they\n * must be of the expected type.\n *\n *

    Specifying a custom layout file

    \n * Defining your own {@code exo_simple_player_view.xml} is useful to customize the layout of\n * SimpleExoPlayerView throughout your application. It's also possible to customize the layout for a\n * single instance in a layout file. This is achieved by setting the {@code player_layout_id}\n * attribute on a SimpleExoPlayerView. This will cause the specified layout to be inflated instead\n * of {@code exo_simple_player_view.xml} for only the instance on which the attribute is set.\n */\n@TargetApi(16)\npublic final class SimpleExoPlayerView extends FrameLayout {\n\n private static final int SURFACE_TYPE_NONE = 0;\n private static final int SURFACE_TYPE_SURFACE_VIEW = 1;\n private static final int SURFACE_TYPE_TEXTURE_VIEW = 2;\n\n private final AspectRatioFrameLayout contentFrame;\n private final View shutterView;\n private final View surfaceView;\n private final ImageView artworkView;\n private final SubtitleView subtitleView;\n private final PlaybackControlView controller;\n private final ComponentListener componentListener;\n private final FrameLayout overlayFrameLayout;\n\n private SimpleExoPlayer player;\n private boolean useController;\n private boolean useArtwork;\n private Bitmap defaultArtwork;\n private int controllerShowTimeoutMs;\n private boolean controllerAutoShow;\n private boolean controllerHideOnTouch;\n\n public SimpleExoPlayerView(Context context) {\n this(context, null);\n }\n\n public SimpleExoPlayerView(Context context, AttributeSet attrs) {\n this(context, attrs, 0);\n }\n\n public SimpleExoPlayerView(Context context, AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n\n if (isInEditMode()) {\n contentFrame = null;\n shutterView = null;\n surfaceView = null;\n artworkView = null;\n subtitleView = null;\n controller = null;\n componentListener = null;\n overlayFrameLayout = null;\n ImageView logo = new ImageView(context);\n if (Util.SDK_INT >= 23) {\n configureEditModeLogoV23(getResources(), logo);\n } else {\n configureEditModeLogo(getResources(), logo);\n }\n addView(logo);\n return;\n }\n\n int playerLayoutId = R.layout.exo_simple_player_view;\n boolean useArtwork = true;\n int defaultArtworkId = 0;\n boolean useController = true;\n int surfaceType = SURFACE_TYPE_SURFACE_VIEW;\n int resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FIT;\n int controllerShowTimeoutMs = PlaybackControlView.DEFAULT_SHOW_TIMEOUT_MS;\n boolean controllerHideOnTouch = true;\n boolean controllerAutoShow = true;\n if (attrs != null) {\n TypedArray a = context.getTheme().obtainStyledAttributes(attrs,\n R.styleable.SimpleExoPlayerView, 0, 0);\n try {\n playerLayoutId = a.getResourceId(R.styleable.SimpleExoPlayerView_player_layout_id,\n playerLayoutId);\n useArtwork = a.getBoolean(R.styleable.SimpleExoPlayerView_use_artwork, useArtwork);\n defaultArtworkId = a.getResourceId(R.styleable.SimpleExoPlayerView_default_artwork,\n defaultArtworkId);\n useController = a.getBoolean(R.styleable.SimpleExoPlayerView_use_controller, useController);\n surfaceType = a.getInt(R.styleable.SimpleExoPlayerView_surface_type, surfaceType);\n resizeMode = a.getInt(R.styleable.SimpleExoPlayerView_resize_mode, resizeMode);\n controllerShowTimeoutMs = a.getInt(R.styleable.SimpleExoPlayerView_show_timeout,\n controllerShowTimeoutMs);\n controllerHideOnTouch = a.getBoolean(R.styleable.SimpleExoPlayerView_hide_on_touch,\n controllerHideOnTouch);\n controllerAutoShow = a.getBoolean(R.styleable.SimpleExoPlayerView_auto_show,\n controllerAutoShow);\n } finally {\n a.recycle();\n }\n }\n\n LayoutInflater.from(context).inflate(playerLayoutId, this);\n componentListener = new ComponentListener();\n setDescendantFocusability(FOCUS_AFTER_DESCENDANTS);\n\n // Content frame.\n contentFrame = findViewById(R.id.exo_content_frame);\n if (contentFrame != null) {\n setResizeModeRaw(contentFrame, resizeMode);\n }\n\n // Shutter view.\n shutterView = findViewById(R.id.exo_shutter);\n\n // Create a surface view and insert it into the content frame, if there is one.\n if (contentFrame != null && surfaceType != SURFACE_TYPE_NONE) {\n ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(\n ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);\n surfaceView = surfaceType == SURFACE_TYPE_TEXTURE_VIEW ? new TextureView(context)\n : new SurfaceView(context);\n surfaceView.setLayoutParams(params);\n contentFrame.addView(surfaceView, 0);\n } else {\n surfaceView = null;\n }\n\n // Overlay frame layout.\n overlayFrameLayout = findViewById(R.id.exo_overlay);\n\n // Artwork view.\n artworkView = findViewById(R.id.exo_artwork);\n this.useArtwork = useArtwork && artworkView != null;\n if (defaultArtworkId != 0) {\n defaultArtwork = BitmapFactory.decodeResource(context.getResources(), defaultArtworkId);\n }\n\n // Subtitle view.\n subtitleView = findViewById(R.id.exo_subtitles);\n if (subtitleView != null) {\n subtitleView.setUserDefaultStyle();\n subtitleView.setUserDefaultTextSize();\n }\n\n // Playback control view.\n PlaybackControlView customController = findViewById(R.id.exo_controller);\n View controllerPlaceholder = findViewById(R.id.exo_controller_placeholder);\n if (customController != null) {\n this.controller = customController;\n } else if (controllerPlaceholder != null) {\n // Propagate attrs as playbackAttrs so that PlaybackControlView's custom attributes are\n // transferred, but standard FrameLayout attributes (e.g. background) are not.\n this.controller = new PlaybackControlView(context, null, 0, attrs);\n controller.setLayoutParams(controllerPlaceholder.getLayoutParams());\n ViewGroup parent = ((ViewGroup) controllerPlaceholder.getParent());\n int controllerIndex = parent.indexOfChild(controllerPlaceholder);\n parent.removeView(controllerPlaceholder);\n parent.addView(controller, controllerIndex);\n } else {\n this.controller = null;\n }\n this.controllerShowTimeoutMs = controller != null ? controllerShowTimeoutMs : 0;\n this.controllerHideOnTouch = controllerHideOnTouch;\n this.controllerAutoShow = controllerAutoShow;\n this.useController = useController && controller != null;\n hideController();\n }\n\n /**\n * Switches the view targeted by a given {@link SimpleExoPlayer}.\n *\n * @param player The player whose target view is being switched.\n * @param oldPlayerView The old view to detach from the player.\n * @param newPlayerView The new view to attach to the player.\n */\n public static void switchTargetView(@NonNull SimpleExoPlayer player,\n @Nullable SimpleExoPlayerView oldPlayerView, @Nullable SimpleExoPlayerView newPlayerView) {\n if (oldPlayerView == newPlayerView) {\n return;\n }\n // We attach the new view before detaching the old one because this ordering allows the player\n // to swap directly from one surface to another, without transitioning through a state where no\n // surface is attached. This is significantly more efficient and achieves a more seamless\n // transition when using platform provided video decoders.\n if (newPlayerView != null) {\n newPlayerView.setPlayer(player);\n }\n if (oldPlayerView != null) {\n oldPlayerView.setPlayer(null);\n }\n }\n\n /**\n * Returns the player currently set on this view, or null if no player is set.\n */\n public SimpleExoPlayer getPlayer() {\n return player;\n }\n\n /**\n * Set the {@link SimpleExoPlayer} to use.\n *

    \n * To transition a {@link SimpleExoPlayer} from targeting one view to another, it's recommended to\n * use {@link #switchTargetView(SimpleExoPlayer, SimpleExoPlayerView, SimpleExoPlayerView)} rather\n * than this method. If you do wish to use this method directly, be sure to attach the player to\n * the new view before calling {@code setPlayer(null)} to detach it from the old one.\n * This ordering is significantly more efficient and may allow for more seamless transitions.\n *\n * @param player The {@link SimpleExoPlayer} to use.\n */\n public void setPlayer(SimpleExoPlayer player) {\n if (this.player == player) {\n return;\n }\n if (this.player != null) {\n this.player.removeListener(componentListener);\n this.player.removeTextOutput(componentListener);\n this.player.removeVideoListener(componentListener);\n if (surfaceView instanceof TextureView) {\n this.player.clearVideoTextureView((TextureView) surfaceView);\n } else if (surfaceView instanceof SurfaceView) {\n this.player.clearVideoSurfaceView((SurfaceView) surfaceView);\n }\n }\n this.player = player;\n if (useController) {\n controller.setPlayer(player);\n }\n if (shutterView != null) {\n shutterView.setVisibility(VISIBLE);\n }\n if (player != null) {\n if (surfaceView instanceof TextureView) {\n player.setVideoTextureView((TextureView) surfaceView);\n } else if (surfaceView instanceof SurfaceView) {\n player.setVideoSurfaceView((SurfaceView) surfaceView);\n }\n player.addVideoListener(componentListener);\n player.addTextOutput(componentListener);\n player.addListener(componentListener);\n maybeShowController(false);\n updateForCurrentTrackSelections();\n } else {\n hideController();\n hideArtwork();\n }\n }\n\n @Override\n public void setVisibility(int visibility) {\n super.setVisibility(visibility);\n if (surfaceView instanceof SurfaceView) {\n // Work around https://github.com/google/ExoPlayer/issues/3160\n surfaceView.setVisibility(visibility);\n }\n }\n\n /**\n * Sets the resize mode.\n *\n * @param resizeMode The resize mode.\n */\n public void setResizeMode(@ResizeMode int resizeMode) {\n Assertions.checkState(contentFrame != null);\n contentFrame.setResizeMode(resizeMode);\n }\n\n /**\n * Returns whether artwork is displayed if present in the media.\n */\n public boolean getUseArtwork() {\n return useArtwork;\n }\n\n /**\n * Sets whether artwork is displayed if present in the media.\n *\n * @param useArtwork Whether artwork is displayed.\n */\n public void setUseArtwork(boolean useArtwork) {\n Assertions.checkState(!useArtwork || artworkView != null);\n if (this.useArtwork != useArtwork) {\n this.useArtwork = useArtwork;\n updateForCurrentTrackSelections();\n }\n }\n\n /**\n * Returns the default artwork to display.\n */\n public Bitmap getDefaultArtwork() {\n return defaultArtwork;\n }\n\n /**\n * Sets the default artwork to display if {@code useArtwork} is {@code true} and no artwork is\n * present in the media.\n *\n * @param defaultArtwork the default artwork to display.\n */\n public void setDefaultArtwork(Bitmap defaultArtwork) {\n if (this.defaultArtwork != defaultArtwork) {\n this.defaultArtwork = defaultArtwork;\n updateForCurrentTrackSelections();\n }\n }\n\n /**\n * Returns whether the playback controls can be shown.\n */\n public boolean getUseController() {\n return useController;\n }\n\n /**\n * Sets whether the playback controls can be shown. If set to {@code false} the playback controls\n * are never visible and are disconnected from the player.\n *\n * @param useController Whether the playback controls can be shown.\n */\n public void setUseController(boolean useController) {\n Assertions.checkState(!useController || controller != null);\n if (this.useController == useController) {\n return;\n }\n this.useController = useController;\n if (useController) {\n controller.setPlayer(player);\n } else if (controller != null) {\n controller.hide();\n controller.setPlayer(null);\n }\n }\n\n @Override\n public boolean dispatchKeyEvent(KeyEvent event) {\n maybeShowController(true);\n return dispatchMediaKeyEvent(event) || super.dispatchKeyEvent(event);\n }\n\n /**\n * Called to process media key events. Any {@link KeyEvent} can be passed but only media key\n * events will be handled. Does nothing if playback controls are disabled.\n *\n * @param event A key event.\n * @return Whether the key event was handled.\n */\n public boolean dispatchMediaKeyEvent(KeyEvent event) {\n return useController && controller.dispatchMediaKeyEvent(event);\n }\n\n /**\n * Shows the playback controls. Does nothing if playback controls are disabled.\n *\n *

    The playback controls are automatically hidden during playback after\n * {{@link #getControllerShowTimeoutMs()}}. They are shown indefinitely when playback has not\n * started yet, is paused, has ended or failed.\n */\n public void showController() {\n showController(shouldShowControllerIndefinitely());\n }\n\n /**\n * Hides the playback controls. Does nothing if playback controls are disabled.\n */\n public void hideController() {\n if (controller != null) {\n controller.hide();\n }\n }\n\n /**\n * Returns the playback controls timeout. The playback controls are automatically hidden after\n * this duration of time has elapsed without user input and with playback or buffering in\n * progress.\n *\n * @return The timeout in milliseconds. A non-positive value will cause the controller to remain\n * visible indefinitely.\n */\n public int getControllerShowTimeoutMs() {\n return controllerShowTimeoutMs;\n }\n\n /**\n * Sets the playback controls timeout. The playback controls are automatically hidden after this\n * duration of time has elapsed without user input and with playback or buffering in progress.\n *\n * @param controllerShowTimeoutMs The timeout in milliseconds. A non-positive value will cause\n * the controller to remain visible indefinitely.\n */\n public void setControllerShowTimeoutMs(int controllerShowTimeoutMs) {\n Assertions.checkState(controller != null);\n this.controllerShowTimeoutMs = controllerShowTimeoutMs;\n }\n\n /**\n * Returns whether the playback controls are hidden by touch events.\n */\n public boolean getControllerHideOnTouch() {\n return controllerHideOnTouch;\n }\n\n /**\n * Sets whether the playback controls are hidden by touch events.\n *\n * @param controllerHideOnTouch Whether the playback controls are hidden by touch events.\n */\n public void setControllerHideOnTouch(boolean controllerHideOnTouch) {\n Assertions.checkState(controller != null);\n this.controllerHideOnTouch = controllerHideOnTouch;\n }\n\n /**\n * Returns whether the playback controls are automatically shown when playback starts, pauses,\n * ends, or fails. If set to false, the playback controls can be manually operated with {@link\n * #showController()} and {@link #hideController()}.\n */\n public boolean getControllerAutoShow() {\n return controllerAutoShow;\n }\n\n /**\n * Sets whether the playback controls are automatically shown when playback starts, pauses, ends,\n * or fails. If set to false, the playback controls can be manually operated with {@link\n * #showController()} and {@link #hideController()}.\n *\n * @param controllerAutoShow Whether the playback controls are allowed to show automatically.\n */\n public void setControllerAutoShow(boolean controllerAutoShow) {\n this.controllerAutoShow = controllerAutoShow;\n }\n\n /**\n * Set the {@link PlaybackControlView.VisibilityListener}.\n *\n * @param listener The listener to be notified about visibility changes.\n */\n public void setControllerVisibilityListener(PlaybackControlView.VisibilityListener listener) {\n Assertions.checkState(controller != null);\n controller.setVisibilityListener(listener);\n }\n\n /**\n * Sets the {@link ControlDispatcher}.\n *\n * @param controlDispatcher The {@link ControlDispatcher}, or null to use\n * {@link DefaultControlDispatcher}.\n */\n public void setControlDispatcher(@Nullable ControlDispatcher controlDispatcher) {\n Assertions.checkState(controller != null);\n controller.setControlDispatcher(controlDispatcher);\n }\n\n /**\n * Sets the rewind increment in milliseconds.\n *\n * @param rewindMs The rewind increment in milliseconds. A non-positive value will cause the\n * rewind button to be disabled.\n */\n public void setRewindIncrementMs(int rewindMs) {\n Assertions.checkState(controller != null);\n controller.setRewindIncrementMs(rewindMs);\n }\n\n /**\n * Sets the fast forward increment in milliseconds.\n *\n * @param fastForwardMs The fast forward increment in milliseconds. A non-positive value will\n * cause the fast forward button to be disabled.\n */\n public void setFastForwardIncrementMs(int fastForwardMs) {\n Assertions.checkState(controller != null);\n controller.setFastForwardIncrementMs(fastForwardMs);\n }\n\n /**\n * Sets which repeat toggle modes are enabled.\n *\n * @param repeatToggleModes A set of {@link RepeatModeUtil.RepeatToggleModes}.\n */\n public void setRepeatToggleModes(@RepeatModeUtil.RepeatToggleModes int repeatToggleModes) {\n Assertions.checkState(controller != null);\n controller.setRepeatToggleModes(repeatToggleModes);\n }\n\n /**\n * Sets whether the shuffle button is shown.\n *\n * @param showShuffleButton Whether the shuffle button is shown.\n */\n public void setShowShuffleButton(boolean showShuffleButton) {\n Assertions.checkState(controller != null);\n controller.setShowShuffleButton(showShuffleButton);\n }\n\n /**\n * Sets whether the time bar should show all windows, as opposed to just the current one.\n *\n * @param showMultiWindowTimeBar Whether to show all windows.\n */\n public void setShowMultiWindowTimeBar(boolean showMultiWindowTimeBar) {\n Assertions.checkState(controller != null);\n controller.setShowMultiWindowTimeBar(showMultiWindowTimeBar);\n }\n\n /**\n * Gets the view onto which video is rendered. This is a:\n *

      \n *
    • {@link SurfaceView} by default, or if the {@code surface_type} attribute is set to\n * {@code surface_view}.
    • \n *
    • {@link TextureView} if {@code surface_type} is {@code texture_view}.
    • \n *
    • {@code null} if {@code surface_type} is {@code none}.
    • \n *
    \n *\n * @return The {@link SurfaceView}, {@link TextureView} or {@code null}.\n */\n public View getVideoSurfaceView() {\n return surfaceView;\n }\n\n /**\n * Gets the overlay {@link FrameLayout}, which can be populated with UI elements to show on top of\n * the player.\n *\n * @return The overlay {@link FrameLayout}, or {@code null} if the layout has been customized and\n * the overlay is not present.\n */\n public FrameLayout getOverlayFrameLayout() {\n return overlayFrameLayout;\n }\n\n /**\n * Gets the {@link SubtitleView}.\n *\n * @return The {@link SubtitleView}, or {@code null} if the layout has been customized and the\n * subtitle view is not present.\n */\n public SubtitleView getSubtitleView() {\n return subtitleView;\n }\n\n @Override\n public boolean onTouchEvent(MotionEvent ev) {\n if (!useController || player == null || ev.getActionMasked() != MotionEvent.ACTION_DOWN) {\n return false;\n }\n if (!controller.isVisible()) {\n maybeShowController(true);\n } else if (controllerHideOnTouch) {\n controller.hide();\n }\n return true;\n }\n\n @Override\n public boolean onTrackballEvent(MotionEvent ev) {\n if (!useController || player == null) {\n return false;\n }\n maybeShowController(true);\n return true;\n }\n\n /**\n * Shows the playback controls, but only if forced or shown indefinitely.\n */\n private void maybeShowController(boolean isForced) {\n if (useController) {\n boolean wasShowingIndefinitely = controller.isVisible() && controller.getShowTimeoutMs() <= 0;\n boolean shouldShowIndefinitely = shouldShowControllerIndefinitely();\n if (isForced || wasShowingIndefinitely || shouldShowIndefinitely) {\n showController(shouldShowIndefinitely);\n }\n }\n }\n\n private boolean shouldShowControllerIndefinitely() {\n if (player == null) {\n return true;\n }\n int playbackState = player.getPlaybackState();\n return controllerAutoShow && (playbackState == Player.STATE_IDLE\n || playbackState == Player.STATE_ENDED || !player.getPlayWhenReady());\n }\n\n private void showController(boolean showIndefinitely) {\n if (!useController) {\n return;\n }\n controller.setShowTimeoutMs(showIndefinitely ? 0 : controllerShowTimeoutMs);\n controller.show();\n }\n\n private void updateForCurrentTrackSelections() {\n if (player == null) {\n return;\n }\n TrackSelectionArray selections = player.getCurrentTrackSelections();\n for (int i = 0; i < selections.length; i++) {\n if (player.getRendererType(i) == C.TRACK_TYPE_VIDEO && selections.get(i) != null) {\n // Video enabled so artwork must be hidden. If the shutter is closed, it will be opened in\n // onRenderedFirstFrame().\n hideArtwork();\n return;\n }\n }\n // Video disabled so the shutter must be closed.\n if (shutterView != null) {\n shutterView.setVisibility(VISIBLE);\n }\n // Display artwork if enabled and available, else hide it.\n if (useArtwork) {\n for (int i = 0; i < selections.length; i++) {\n TrackSelection selection = selections.get(i);\n if (selection != null) {\n for (int j = 0; j < selection.length(); j++) {\n Metadata metadata = selection.getFormat(j).metadata;\n if (metadata != null && setArtworkFromMetadata(metadata)) {\n return;\n }\n }\n }\n }\n if (setArtworkFromBitmap(defaultArtwork)) {\n return;\n }\n }\n // Artwork disabled or unavailable.\n hideArtwork();\n }\n\n private boolean setArtworkFromMetadata(Metadata metadata) {\n for (int i = 0; i < metadata.length(); i++) {\n Metadata.Entry metadataEntry = metadata.get(i);\n if (metadataEntry instanceof ApicFrame) {\n byte[] bitmapData = ((ApicFrame) metadataEntry).pictureData;\n Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapData, 0, bitmapData.length);\n return setArtworkFromBitmap(bitmap);\n }\n }\n return false;\n }\n\n private boolean setArtworkFromBitmap(Bitmap bitmap) {\n if (bitmap != null) {\n int bitmapWidth = bitmap.getWidth();\n int bitmapHeight = bitmap.getHeight();\n if (bitmapWidth > 0 && bitmapHeight > 0) {\n if (contentFrame != null) {\n contentFrame.setAspectRatio((float) bitmapWidth / bitmapHeight);\n }\n artworkView.setImageBitmap(bitmap);\n artworkView.setVisibility(VISIBLE);\n return true;\n }\n }\n return false;\n }\n\n private void hideArtwork() {\n if (artworkView != null) {\n artworkView.setImageResource(android.R.color.transparent); // Clears any bitmap reference.\n artworkView.setVisibility(INVISIBLE);\n }\n }\n\n @TargetApi(23)\n private static void configureEditModeLogoV23(Resources resources, ImageView logo) {\n logo.setImageDrawable(resources.getDrawable(R.drawable.exo_edit_mode_logo, null));\n logo.setBackgroundColor(resources.getColor(R.color.exo_edit_mode_background_color, null));\n }\n\n @SuppressWarnings(\"deprecation\")\n private static void configureEditModeLogo(Resources resources, ImageView logo) {\n logo.setImageDrawable(resources.getDrawable(R.drawable.exo_edit_mode_logo));\n logo.setBackgroundColor(resources.getColor(R.color.exo_edit_mode_background_color));\n }\n\n\n @SuppressWarnings(\"ResourceType\")\n private static void setResizeModeRaw(AspectRatioFrameLayout aspectRatioFrame, int resizeMode) {\n aspectRatioFrame.setResizeMode(resizeMode);\n }\n\n private final class ComponentListener implements TextOutput, SimpleExoPlayer.VideoListener,\n Player.EventListener {\n\n // TextOutput implementation\n\n @Override\n public void onCues(List cues) {\n if (subtitleView != null) {\n subtitleView.onCues(cues);\n }\n }\n\n // SimpleExoPlayer.VideoInfoListener implementation\n\n @Override\n public void onVideoSizeChanged(int width, int height, int unappliedRotationDegrees,\n float pixelWidthHeightRatio) {\n if (contentFrame != null) {\n float aspectRatio = height == 0 ? 1 : (width * pixelWidthHeightRatio) / height;\n contentFrame.setAspectRatio(aspectRatio);\n }\n }\n\n @Override\n public void onRenderedFirstFrame() {\n if (shutterView != null) {\n shutterView.setVisibility(INVISIBLE);\n }\n }\n\n @Override\n public void onTracksChanged(TrackGroupArray tracks, TrackSelectionArray selections) {\n updateForCurrentTrackSelections();\n }\n\n // Player.EventListener implementation\n\n @Override\n public void onLoadingChanged(boolean isLoading) {\n // Do nothing.\n }\n\n @Override\n public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {\n maybeShowController(false);\n }\n\n @Override\n public void onRepeatModeChanged(int repeatMode) {\n // Do nothing.\n }\n\n @Override\n public void onShuffleModeEnabledChanged(boolean shuffleModeEnabled) {\n // Do nothing.\n }\n\n @Override\n public void onPlayerError(ExoPlaybackException e) {\n // Do nothing.\n }\n\n @Override\n public void onPositionDiscontinuity() {\n // Do nothing.\n }\n\n @Override\n public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {\n // Do nothing.\n }\n\n @Override\n public void onTimelineChanged(Timeline timeline, Object manifest) {\n // Do nothing.\n }\n\n }\n\n}\n"},"new_file":{"kind":"string","value":"library/ui/src/main/java/com/google/android/exoplayer2/ui/SimpleExoPlayerView.java"},"old_contents":{"kind":"string","value":"/*\n * Copyright (C) 2016 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.google.android.exoplayer2.ui;\n\nimport android.annotation.TargetApi;\nimport android.content.Context;\nimport android.content.res.Resources;\nimport android.content.res.TypedArray;\nimport android.graphics.Bitmap;\nimport android.graphics.BitmapFactory;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.util.AttributeSet;\nimport android.view.KeyEvent;\nimport android.view.LayoutInflater;\nimport android.view.MotionEvent;\nimport android.view.SurfaceView;\nimport android.view.TextureView;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.FrameLayout;\nimport android.widget.ImageView;\nimport com.google.android.exoplayer2.C;\nimport com.google.android.exoplayer2.ControlDispatcher;\nimport com.google.android.exoplayer2.DefaultControlDispatcher;\nimport com.google.android.exoplayer2.ExoPlaybackException;\nimport com.google.android.exoplayer2.PlaybackParameters;\nimport com.google.android.exoplayer2.Player;\nimport com.google.android.exoplayer2.SimpleExoPlayer;\nimport com.google.android.exoplayer2.Timeline;\nimport com.google.android.exoplayer2.metadata.Metadata;\nimport com.google.android.exoplayer2.metadata.id3.ApicFrame;\nimport com.google.android.exoplayer2.source.TrackGroupArray;\nimport com.google.android.exoplayer2.text.Cue;\nimport com.google.android.exoplayer2.text.TextOutput;\nimport com.google.android.exoplayer2.trackselection.TrackSelection;\nimport com.google.android.exoplayer2.trackselection.TrackSelectionArray;\nimport com.google.android.exoplayer2.ui.AspectRatioFrameLayout.ResizeMode;\nimport com.google.android.exoplayer2.util.Assertions;\nimport com.google.android.exoplayer2.util.RepeatModeUtil;\nimport com.google.android.exoplayer2.util.Util;\nimport java.util.List;\n\n/**\n * A high level view for {@link SimpleExoPlayer} media playbacks. It displays video, subtitles and\n * album art during playback, and displays playback controls using a {@link PlaybackControlView}.\n *

    \n * A SimpleExoPlayerView can be customized by setting attributes (or calling corresponding methods),\n * overriding the view's layout file or by specifying a custom view layout file, as outlined below.\n *\n *

    Attributes

    \n * The following attributes can be set on a SimpleExoPlayerView when used in a layout XML file:\n *

    \n *

      \n *
    • {@code use_artwork} - Whether artwork is used if available in audio streams.\n *
        \n *
      • Corresponding method: {@link #setUseArtwork(boolean)}
      • \n *
      • Default: {@code true}
      • \n *
      \n *
    • \n *
    • {@code default_artwork} - Default artwork to use if no artwork available in audio\n * streams.\n *
        \n *
      • Corresponding method: {@link #setDefaultArtwork(Bitmap)}
      • \n *
      • Default: {@code null}
      • \n *
      \n *
    • \n *
    • {@code use_controller} - Whether the playback controls can be shown.\n *
        \n *
      • Corresponding method: {@link #setUseController(boolean)}
      • \n *
      • Default: {@code true}
      • \n *
      \n *
    • \n *
    • {@code hide_on_touch} - Whether the playback controls are hidden by touch events.\n *
        \n *
      • Corresponding method: {@link #setControllerHideOnTouch(boolean)}
      • \n *
      • Default: {@code true}
      • \n *
      \n *
    • \n *
    • {@code auto_show} - Whether the playback controls are automatically shown when\n * playback starts, pauses, ends, or fails. If set to false, the playback controls can be\n * manually operated with {@link #showController()} and {@link #hideController()}.\n *
        \n *
      • Corresponding method: {@link #setControllerAutoShow(boolean)}
      • \n *
      • Default: {@code true}
      • \n *
      \n *
    • \n *
    • {@code resize_mode} - Controls how video and album art is resized within the view.\n * Valid values are {@code fit}, {@code fixed_width}, {@code fixed_height} and {@code fill}.\n *
        \n *
      • Corresponding method: {@link #setResizeMode(int)}
      • \n *
      • Default: {@code fit}
      • \n *
      \n *
    • \n *
    • {@code surface_type} - The type of surface view used for video playbacks. Valid\n * values are {@code surface_view}, {@code texture_view} and {@code none}. Using {@code none}\n * is recommended for audio only applications, since creating the surface can be expensive.\n * Using {@code surface_view} is recommended for video applications.\n *
        \n *
      • Corresponding method: None
      • \n *
      • Default: {@code surface_view}
      • \n *
      \n *
    • \n *
    • {@code player_layout_id} - Specifies the id of the layout to be inflated. See below\n * for more details.\n *
        \n *
      • Corresponding method: None
      • \n *
      • Default: {@code R.id.exo_simple_player_view}
      • \n *
      \n *
    • {@code controller_layout_id} - Specifies the id of the layout resource to be\n * inflated by the child {@link PlaybackControlView}. See below for more details.\n *
        \n *
      • Corresponding method: None
      • \n *
      • Default: {@code R.id.exo_playback_control_view}
      • \n *
      \n *
    • All attributes that can be set on a {@link PlaybackControlView} can also be set on a\n * SimpleExoPlayerView, and will be propagated to the inflated {@link PlaybackControlView}\n * unless the layout is overridden to specify a custom {@code exo_controller} (see below).\n *
    • \n *
    \n *\n *

    Overriding the layout file

    \n * To customize the layout of SimpleExoPlayerView throughout your app, or just for certain\n * configurations, you can define {@code exo_simple_player_view.xml} layout files in your\n * application {@code res/layout*} directories. These layouts will override the one provided by the\n * ExoPlayer library, and will be inflated for use by SimpleExoPlayerView. The view identifies and\n * binds its children by looking for the following ids:\n *

    \n *

      \n *
    • {@code exo_content_frame} - A frame whose aspect ratio is resized based on the video\n * or album art of the media being played, and the configured {@code resize_mode}. The video\n * surface view is inflated into this frame as its first child.\n *
        \n *
      • Type: {@link AspectRatioFrameLayout}
      • \n *
      \n *
    • \n *
    • {@code exo_shutter} - A view that's made visible when video should be hidden. This\n * view is typically an opaque view that covers the video surface view, thereby obscuring it\n * when visible.\n *
        \n *
      • Type: {@link View}
      • \n *
      \n *
    • \n *
    • {@code exo_subtitles} - Displays subtitles.\n *
        \n *
      • Type: {@link SubtitleView}
      • \n *
      \n *
    • \n *
    • {@code exo_artwork} - Displays album art.\n *
        \n *
      • Type: {@link ImageView}
      • \n *
      \n *
    • \n *
    • {@code exo_controller_placeholder} - A placeholder that's replaced with the inflated\n * {@link PlaybackControlView}. Ignored if an {@code exo_controller} view exists.\n *
        \n *
      • Type: {@link View}
      • \n *
      \n *
    • \n *
    • {@code exo_controller} - An already inflated {@link PlaybackControlView}. Allows use\n * of a custom extension of {@link PlaybackControlView}. Note that attributes such as\n * {@code rewind_increment} will not be automatically propagated through to this instance. If\n * a view exists with this id, any {@code exo_controller_placeholder} view will be ignored.\n *
        \n *
      • Type: {@link PlaybackControlView}
      • \n *
      \n *
    • \n *
    • {@code exo_overlay} - A {@link FrameLayout} positioned on top of the player which\n * the app can access via {@link #getOverlayFrameLayout()}, provided for convenience.\n *
        \n *
      • Type: {@link FrameLayout}
      • \n *
      \n *
    • \n *
    \n *

    \n * All child views are optional and so can be omitted if not required, however where defined they\n * must be of the expected type.\n *\n *

    Specifying a custom layout file

    \n * Defining your own {@code exo_simple_player_view.xml} is useful to customize the layout of\n * SimpleExoPlayerView throughout your application. It's also possible to customize the layout for a\n * single instance in a layout file. This is achieved by setting the {@code player_layout_id}\n * attribute on a SimpleExoPlayerView. This will cause the specified layout to be inflated instead\n * of {@code exo_simple_player_view.xml} for only the instance on which the attribute is set.\n */\n@TargetApi(16)\npublic final class SimpleExoPlayerView extends FrameLayout {\n\n private static final int SURFACE_TYPE_NONE = 0;\n private static final int SURFACE_TYPE_SURFACE_VIEW = 1;\n private static final int SURFACE_TYPE_TEXTURE_VIEW = 2;\n\n private final AspectRatioFrameLayout contentFrame;\n private final View shutterView;\n private final View surfaceView;\n private final ImageView artworkView;\n private final SubtitleView subtitleView;\n private final PlaybackControlView controller;\n private final ComponentListener componentListener;\n private final FrameLayout overlayFrameLayout;\n\n private SimpleExoPlayer player;\n private boolean useController;\n private boolean useArtwork;\n private Bitmap defaultArtwork;\n private int controllerShowTimeoutMs;\n private boolean controllerAutoShow;\n private boolean controllerHideOnTouch;\n\n public SimpleExoPlayerView(Context context) {\n this(context, null);\n }\n\n public SimpleExoPlayerView(Context context, AttributeSet attrs) {\n this(context, attrs, 0);\n }\n\n public SimpleExoPlayerView(Context context, AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n\n if (isInEditMode()) {\n contentFrame = null;\n shutterView = null;\n surfaceView = null;\n artworkView = null;\n subtitleView = null;\n controller = null;\n componentListener = null;\n overlayFrameLayout = null;\n ImageView logo = new ImageView(context);\n if (Util.SDK_INT >= 23) {\n configureEditModeLogoV23(getResources(), logo);\n } else {\n configureEditModeLogo(getResources(), logo);\n }\n addView(logo);\n return;\n }\n\n int playerLayoutId = R.layout.exo_simple_player_view;\n boolean useArtwork = true;\n int defaultArtworkId = 0;\n boolean useController = true;\n int surfaceType = SURFACE_TYPE_SURFACE_VIEW;\n int resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FIT;\n int controllerShowTimeoutMs = PlaybackControlView.DEFAULT_SHOW_TIMEOUT_MS;\n boolean controllerHideOnTouch = true;\n boolean controllerAutoShow = true;\n if (attrs != null) {\n TypedArray a = context.getTheme().obtainStyledAttributes(attrs,\n R.styleable.SimpleExoPlayerView, 0, 0);\n try {\n playerLayoutId = a.getResourceId(R.styleable.SimpleExoPlayerView_player_layout_id,\n playerLayoutId);\n useArtwork = a.getBoolean(R.styleable.SimpleExoPlayerView_use_artwork, useArtwork);\n defaultArtworkId = a.getResourceId(R.styleable.SimpleExoPlayerView_default_artwork,\n defaultArtworkId);\n useController = a.getBoolean(R.styleable.SimpleExoPlayerView_use_controller, useController);\n surfaceType = a.getInt(R.styleable.SimpleExoPlayerView_surface_type, surfaceType);\n resizeMode = a.getInt(R.styleable.SimpleExoPlayerView_resize_mode, resizeMode);\n controllerShowTimeoutMs = a.getInt(R.styleable.SimpleExoPlayerView_show_timeout,\n controllerShowTimeoutMs);\n controllerHideOnTouch = a.getBoolean(R.styleable.SimpleExoPlayerView_hide_on_touch,\n controllerHideOnTouch);\n controllerAutoShow = a.getBoolean(R.styleable.SimpleExoPlayerView_auto_show,\n controllerAutoShow);\n } finally {\n a.recycle();\n }\n }\n\n LayoutInflater.from(context).inflate(playerLayoutId, this);\n componentListener = new ComponentListener();\n setDescendantFocusability(FOCUS_AFTER_DESCENDANTS);\n\n // Content frame.\n contentFrame = findViewById(R.id.exo_content_frame);\n if (contentFrame != null) {\n setResizeModeRaw(contentFrame, resizeMode);\n }\n\n // Shutter view.\n shutterView = findViewById(R.id.exo_shutter);\n\n // Create a surface view and insert it into the content frame, if there is one.\n if (contentFrame != null && surfaceType != SURFACE_TYPE_NONE) {\n ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(\n ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);\n surfaceView = surfaceType == SURFACE_TYPE_TEXTURE_VIEW ? new TextureView(context)\n : new SurfaceView(context);\n surfaceView.setLayoutParams(params);\n contentFrame.addView(surfaceView, 0);\n } else {\n surfaceView = null;\n }\n\n // Overlay frame layout.\n overlayFrameLayout = findViewById(R.id.exo_overlay);\n\n // Artwork view.\n artworkView = findViewById(R.id.exo_artwork);\n this.useArtwork = useArtwork && artworkView != null;\n if (defaultArtworkId != 0) {\n defaultArtwork = BitmapFactory.decodeResource(context.getResources(), defaultArtworkId);\n }\n\n // Subtitle view.\n subtitleView = findViewById(R.id.exo_subtitles);\n if (subtitleView != null) {\n subtitleView.setUserDefaultStyle();\n subtitleView.setUserDefaultTextSize();\n }\n\n // Playback control view.\n PlaybackControlView customController = findViewById(R.id.exo_controller);\n View controllerPlaceholder = findViewById(R.id.exo_controller_placeholder);\n if (customController != null) {\n this.controller = customController;\n } else if (controllerPlaceholder != null) {\n // Propagate attrs as playbackAttrs so that PlaybackControlView's custom attributes are\n // transferred, but standard FrameLayout attributes (e.g. background) are not.\n this.controller = new PlaybackControlView(context, null, 0, attrs);\n controller.setLayoutParams(controllerPlaceholder.getLayoutParams());\n ViewGroup parent = ((ViewGroup) controllerPlaceholder.getParent());\n int controllerIndex = parent.indexOfChild(controllerPlaceholder);\n parent.removeView(controllerPlaceholder);\n parent.addView(controller, controllerIndex);\n } else {\n this.controller = null;\n }\n this.controllerShowTimeoutMs = controller != null ? controllerShowTimeoutMs : 0;\n this.controllerHideOnTouch = controllerHideOnTouch;\n this.controllerAutoShow = controllerAutoShow;\n this.useController = useController && controller != null;\n hideController();\n }\n\n /**\n * Switches the view targeted by a given {@link SimpleExoPlayer}.\n *\n * @param player The player whose target view is being switched.\n * @param oldPlayerView The old view to detach from the player.\n * @param newPlayerView The new view to attach to the player.\n */\n public static void switchTargetView(@NonNull SimpleExoPlayer player,\n @Nullable SimpleExoPlayerView oldPlayerView, @Nullable SimpleExoPlayerView newPlayerView) {\n if (oldPlayerView == newPlayerView) {\n return;\n }\n // We attach the new view before detaching the old one because this ordering allows the player\n // to swap directly from one surface to another, without transitioning through a state where no\n // surface is attached. This is significantly more efficient and achieves a more seamless\n // transition when using platform provided video decoders.\n if (newPlayerView != null) {\n newPlayerView.setPlayer(player);\n }\n if (oldPlayerView != null) {\n oldPlayerView.setPlayer(null);\n }\n }\n\n /**\n * Returns the player currently set on this view, or null if no player is set.\n */\n public SimpleExoPlayer getPlayer() {\n return player;\n }\n\n /**\n * Set the {@link SimpleExoPlayer} to use.\n *

    \n * To transition a {@link SimpleExoPlayer} from targeting one view to another, it's recommended to\n * use {@link #switchTargetView(SimpleExoPlayer, SimpleExoPlayerView, SimpleExoPlayerView)} rather\n * than this method. If you do wish to use this method directly, be sure to attach the player to\n * the new view before calling {@code setPlayer(null)} to detach it from the old one.\n * This ordering is significantly more efficient and may allow for more seamless transitions.\n *\n * @param player The {@link SimpleExoPlayer} to use.\n */\n public void setPlayer(SimpleExoPlayer player) {\n if (this.player == player) {\n return;\n }\n if (this.player != null) {\n this.player.removeListener(componentListener);\n this.player.removeTextOutput(componentListener);\n this.player.removeVideoListener(componentListener);\n if (surfaceView instanceof TextureView) {\n this.player.clearVideoTextureView((TextureView) surfaceView);\n } else if (surfaceView instanceof SurfaceView) {\n this.player.clearVideoSurfaceView((SurfaceView) surfaceView);\n }\n }\n this.player = player;\n if (useController) {\n controller.setPlayer(player);\n }\n if (shutterView != null) {\n shutterView.setVisibility(VISIBLE);\n }\n if (player != null) {\n if (surfaceView instanceof TextureView) {\n player.setVideoTextureView((TextureView) surfaceView);\n } else if (surfaceView instanceof SurfaceView) {\n player.setVideoSurfaceView((SurfaceView) surfaceView);\n }\n player.addVideoListener(componentListener);\n player.addTextOutput(componentListener);\n player.addListener(componentListener);\n maybeShowController(false);\n updateForCurrentTrackSelections();\n } else {\n hideController();\n hideArtwork();\n }\n }\n\n /**\n * Sets the resize mode.\n *\n * @param resizeMode The resize mode.\n */\n public void setResizeMode(@ResizeMode int resizeMode) {\n Assertions.checkState(contentFrame != null);\n contentFrame.setResizeMode(resizeMode);\n }\n\n /**\n * Returns whether artwork is displayed if present in the media.\n */\n public boolean getUseArtwork() {\n return useArtwork;\n }\n\n /**\n * Sets whether artwork is displayed if present in the media.\n *\n * @param useArtwork Whether artwork is displayed.\n */\n public void setUseArtwork(boolean useArtwork) {\n Assertions.checkState(!useArtwork || artworkView != null);\n if (this.useArtwork != useArtwork) {\n this.useArtwork = useArtwork;\n updateForCurrentTrackSelections();\n }\n }\n\n /**\n * Returns the default artwork to display.\n */\n public Bitmap getDefaultArtwork() {\n return defaultArtwork;\n }\n\n /**\n * Sets the default artwork to display if {@code useArtwork} is {@code true} and no artwork is\n * present in the media.\n *\n * @param defaultArtwork the default artwork to display.\n */\n public void setDefaultArtwork(Bitmap defaultArtwork) {\n if (this.defaultArtwork != defaultArtwork) {\n this.defaultArtwork = defaultArtwork;\n updateForCurrentTrackSelections();\n }\n }\n\n /**\n * Returns whether the playback controls can be shown.\n */\n public boolean getUseController() {\n return useController;\n }\n\n /**\n * Sets whether the playback controls can be shown. If set to {@code false} the playback controls\n * are never visible and are disconnected from the player.\n *\n * @param useController Whether the playback controls can be shown.\n */\n public void setUseController(boolean useController) {\n Assertions.checkState(!useController || controller != null);\n if (this.useController == useController) {\n return;\n }\n this.useController = useController;\n if (useController) {\n controller.setPlayer(player);\n } else if (controller != null) {\n controller.hide();\n controller.setPlayer(null);\n }\n }\n\n @Override\n public boolean dispatchKeyEvent(KeyEvent event) {\n maybeShowController(true);\n return dispatchMediaKeyEvent(event) || super.dispatchKeyEvent(event);\n }\n\n /**\n * Called to process media key events. Any {@link KeyEvent} can be passed but only media key\n * events will be handled. Does nothing if playback controls are disabled.\n *\n * @param event A key event.\n * @return Whether the key event was handled.\n */\n public boolean dispatchMediaKeyEvent(KeyEvent event) {\n return useController && controller.dispatchMediaKeyEvent(event);\n }\n\n /**\n * Shows the playback controls. Does nothing if playback controls are disabled.\n *\n *

    The playback controls are automatically hidden during playback after\n * {{@link #getControllerShowTimeoutMs()}}. They are shown indefinitely when playback has not\n * started yet, is paused, has ended or failed.\n */\n public void showController() {\n showController(shouldShowControllerIndefinitely());\n }\n\n /**\n * Hides the playback controls. Does nothing if playback controls are disabled.\n */\n public void hideController() {\n if (controller != null) {\n controller.hide();\n }\n }\n\n /**\n * Returns the playback controls timeout. The playback controls are automatically hidden after\n * this duration of time has elapsed without user input and with playback or buffering in\n * progress.\n *\n * @return The timeout in milliseconds. A non-positive value will cause the controller to remain\n * visible indefinitely.\n */\n public int getControllerShowTimeoutMs() {\n return controllerShowTimeoutMs;\n }\n\n /**\n * Sets the playback controls timeout. The playback controls are automatically hidden after this\n * duration of time has elapsed without user input and with playback or buffering in progress.\n *\n * @param controllerShowTimeoutMs The timeout in milliseconds. A non-positive value will cause\n * the controller to remain visible indefinitely.\n */\n public void setControllerShowTimeoutMs(int controllerShowTimeoutMs) {\n Assertions.checkState(controller != null);\n this.controllerShowTimeoutMs = controllerShowTimeoutMs;\n }\n\n /**\n * Returns whether the playback controls are hidden by touch events.\n */\n public boolean getControllerHideOnTouch() {\n return controllerHideOnTouch;\n }\n\n /**\n * Sets whether the playback controls are hidden by touch events.\n *\n * @param controllerHideOnTouch Whether the playback controls are hidden by touch events.\n */\n public void setControllerHideOnTouch(boolean controllerHideOnTouch) {\n Assertions.checkState(controller != null);\n this.controllerHideOnTouch = controllerHideOnTouch;\n }\n\n /**\n * Returns whether the playback controls are automatically shown when playback starts, pauses,\n * ends, or fails. If set to false, the playback controls can be manually operated with {@link\n * #showController()} and {@link #hideController()}.\n */\n public boolean getControllerAutoShow() {\n return controllerAutoShow;\n }\n\n /**\n * Sets whether the playback controls are automatically shown when playback starts, pauses, ends,\n * or fails. If set to false, the playback controls can be manually operated with {@link\n * #showController()} and {@link #hideController()}.\n *\n * @param controllerAutoShow Whether the playback controls are allowed to show automatically.\n */\n public void setControllerAutoShow(boolean controllerAutoShow) {\n this.controllerAutoShow = controllerAutoShow;\n }\n\n /**\n * Set the {@link PlaybackControlView.VisibilityListener}.\n *\n * @param listener The listener to be notified about visibility changes.\n */\n public void setControllerVisibilityListener(PlaybackControlView.VisibilityListener listener) {\n Assertions.checkState(controller != null);\n controller.setVisibilityListener(listener);\n }\n\n /**\n * Sets the {@link ControlDispatcher}.\n *\n * @param controlDispatcher The {@link ControlDispatcher}, or null to use\n * {@link DefaultControlDispatcher}.\n */\n public void setControlDispatcher(@Nullable ControlDispatcher controlDispatcher) {\n Assertions.checkState(controller != null);\n controller.setControlDispatcher(controlDispatcher);\n }\n\n /**\n * Sets the rewind increment in milliseconds.\n *\n * @param rewindMs The rewind increment in milliseconds. A non-positive value will cause the\n * rewind button to be disabled.\n */\n public void setRewindIncrementMs(int rewindMs) {\n Assertions.checkState(controller != null);\n controller.setRewindIncrementMs(rewindMs);\n }\n\n /**\n * Sets the fast forward increment in milliseconds.\n *\n * @param fastForwardMs The fast forward increment in milliseconds. A non-positive value will\n * cause the fast forward button to be disabled.\n */\n public void setFastForwardIncrementMs(int fastForwardMs) {\n Assertions.checkState(controller != null);\n controller.setFastForwardIncrementMs(fastForwardMs);\n }\n\n /**\n * Sets which repeat toggle modes are enabled.\n *\n * @param repeatToggleModes A set of {@link RepeatModeUtil.RepeatToggleModes}.\n */\n public void setRepeatToggleModes(@RepeatModeUtil.RepeatToggleModes int repeatToggleModes) {\n Assertions.checkState(controller != null);\n controller.setRepeatToggleModes(repeatToggleModes);\n }\n\n /**\n * Sets whether the shuffle button is shown.\n *\n * @param showShuffleButton Whether the shuffle button is shown.\n */\n public void setShowShuffleButton(boolean showShuffleButton) {\n Assertions.checkState(controller != null);\n controller.setShowShuffleButton(showShuffleButton);\n }\n\n /**\n * Sets whether the time bar should show all windows, as opposed to just the current one.\n *\n * @param showMultiWindowTimeBar Whether to show all windows.\n */\n public void setShowMultiWindowTimeBar(boolean showMultiWindowTimeBar) {\n Assertions.checkState(controller != null);\n controller.setShowMultiWindowTimeBar(showMultiWindowTimeBar);\n }\n\n /**\n * Gets the view onto which video is rendered. This is a:\n *

      \n *
    • {@link SurfaceView} by default, or if the {@code surface_type} attribute is set to\n * {@code surface_view}.
    • \n *
    • {@link TextureView} if {@code surface_type} is {@code texture_view}.
    • \n *
    • {@code null} if {@code surface_type} is {@code none}.
    • \n *
    \n *\n * @return The {@link SurfaceView}, {@link TextureView} or {@code null}.\n */\n public View getVideoSurfaceView() {\n return surfaceView;\n }\n\n /**\n * Gets the overlay {@link FrameLayout}, which can be populated with UI elements to show on top of\n * the player.\n *\n * @return The overlay {@link FrameLayout}, or {@code null} if the layout has been customized and\n * the overlay is not present.\n */\n public FrameLayout getOverlayFrameLayout() {\n return overlayFrameLayout;\n }\n\n /**\n * Gets the {@link SubtitleView}.\n *\n * @return The {@link SubtitleView}, or {@code null} if the layout has been customized and the\n * subtitle view is not present.\n */\n public SubtitleView getSubtitleView() {\n return subtitleView;\n }\n\n @Override\n public boolean onTouchEvent(MotionEvent ev) {\n if (!useController || player == null || ev.getActionMasked() != MotionEvent.ACTION_DOWN) {\n return false;\n }\n if (!controller.isVisible()) {\n maybeShowController(true);\n } else if (controllerHideOnTouch) {\n controller.hide();\n }\n return true;\n }\n\n @Override\n public boolean onTrackballEvent(MotionEvent ev) {\n if (!useController || player == null) {\n return false;\n }\n maybeShowController(true);\n return true;\n }\n\n /**\n * Shows the playback controls, but only if forced or shown indefinitely.\n */\n private void maybeShowController(boolean isForced) {\n if (useController) {\n boolean wasShowingIndefinitely = controller.isVisible() && controller.getShowTimeoutMs() <= 0;\n boolean shouldShowIndefinitely = shouldShowControllerIndefinitely();\n if (isForced || wasShowingIndefinitely || shouldShowIndefinitely) {\n showController(shouldShowIndefinitely);\n }\n }\n }\n\n private boolean shouldShowControllerIndefinitely() {\n if (player == null) {\n return true;\n }\n int playbackState = player.getPlaybackState();\n return controllerAutoShow && (playbackState == Player.STATE_IDLE\n || playbackState == Player.STATE_ENDED || !player.getPlayWhenReady());\n }\n\n private void showController(boolean showIndefinitely) {\n if (!useController) {\n return;\n }\n controller.setShowTimeoutMs(showIndefinitely ? 0 : controllerShowTimeoutMs);\n controller.show();\n }\n\n private void updateForCurrentTrackSelections() {\n if (player == null) {\n return;\n }\n TrackSelectionArray selections = player.getCurrentTrackSelections();\n for (int i = 0; i < selections.length; i++) {\n if (player.getRendererType(i) == C.TRACK_TYPE_VIDEO && selections.get(i) != null) {\n // Video enabled so artwork must be hidden. If the shutter is closed, it will be opened in\n // onRenderedFirstFrame().\n hideArtwork();\n return;\n }\n }\n // Video disabled so the shutter must be closed.\n if (shutterView != null) {\n shutterView.setVisibility(VISIBLE);\n }\n // Display artwork if enabled and available, else hide it.\n if (useArtwork) {\n for (int i = 0; i < selections.length; i++) {\n TrackSelection selection = selections.get(i);\n if (selection != null) {\n for (int j = 0; j < selection.length(); j++) {\n Metadata metadata = selection.getFormat(j).metadata;\n if (metadata != null && setArtworkFromMetadata(metadata)) {\n return;\n }\n }\n }\n }\n if (setArtworkFromBitmap(defaultArtwork)) {\n return;\n }\n }\n // Artwork disabled or unavailable.\n hideArtwork();\n }\n\n private boolean setArtworkFromMetadata(Metadata metadata) {\n for (int i = 0; i < metadata.length(); i++) {\n Metadata.Entry metadataEntry = metadata.get(i);\n if (metadataEntry instanceof ApicFrame) {\n byte[] bitmapData = ((ApicFrame) metadataEntry).pictureData;\n Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapData, 0, bitmapData.length);\n return setArtworkFromBitmap(bitmap);\n }\n }\n return false;\n }\n\n private boolean setArtworkFromBitmap(Bitmap bitmap) {\n if (bitmap != null) {\n int bitmapWidth = bitmap.getWidth();\n int bitmapHeight = bitmap.getHeight();\n if (bitmapWidth > 0 && bitmapHeight > 0) {\n if (contentFrame != null) {\n contentFrame.setAspectRatio((float) bitmapWidth / bitmapHeight);\n }\n artworkView.setImageBitmap(bitmap);\n artworkView.setVisibility(VISIBLE);\n return true;\n }\n }\n return false;\n }\n\n private void hideArtwork() {\n if (artworkView != null) {\n artworkView.setImageResource(android.R.color.transparent); // Clears any bitmap reference.\n artworkView.setVisibility(INVISIBLE);\n }\n }\n\n @TargetApi(23)\n private static void configureEditModeLogoV23(Resources resources, ImageView logo) {\n logo.setImageDrawable(resources.getDrawable(R.drawable.exo_edit_mode_logo, null));\n logo.setBackgroundColor(resources.getColor(R.color.exo_edit_mode_background_color, null));\n }\n\n @SuppressWarnings(\"deprecation\")\n private static void configureEditModeLogo(Resources resources, ImageView logo) {\n logo.setImageDrawable(resources.getDrawable(R.drawable.exo_edit_mode_logo));\n logo.setBackgroundColor(resources.getColor(R.color.exo_edit_mode_background_color));\n }\n\n\n @SuppressWarnings(\"ResourceType\")\n private static void setResizeModeRaw(AspectRatioFrameLayout aspectRatioFrame, int resizeMode) {\n aspectRatioFrame.setResizeMode(resizeMode);\n }\n\n private final class ComponentListener implements TextOutput, SimpleExoPlayer.VideoListener,\n Player.EventListener {\n\n // TextOutput implementation\n\n @Override\n public void onCues(List cues) {\n if (subtitleView != null) {\n subtitleView.onCues(cues);\n }\n }\n\n // SimpleExoPlayer.VideoInfoListener implementation\n\n @Override\n public void onVideoSizeChanged(int width, int height, int unappliedRotationDegrees,\n float pixelWidthHeightRatio) {\n if (contentFrame != null) {\n float aspectRatio = height == 0 ? 1 : (width * pixelWidthHeightRatio) / height;\n contentFrame.setAspectRatio(aspectRatio);\n }\n }\n\n @Override\n public void onRenderedFirstFrame() {\n if (shutterView != null) {\n shutterView.setVisibility(INVISIBLE);\n }\n }\n\n @Override\n public void onTracksChanged(TrackGroupArray tracks, TrackSelectionArray selections) {\n updateForCurrentTrackSelections();\n }\n\n // Player.EventListener implementation\n\n @Override\n public void onLoadingChanged(boolean isLoading) {\n // Do nothing.\n }\n\n @Override\n public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {\n maybeShowController(false);\n }\n\n @Override\n public void onRepeatModeChanged(int repeatMode) {\n // Do nothing.\n }\n\n @Override\n public void onShuffleModeEnabledChanged(boolean shuffleModeEnabled) {\n // Do nothing.\n }\n\n @Override\n public void onPlayerError(ExoPlaybackException e) {\n // Do nothing.\n }\n\n @Override\n public void onPositionDiscontinuity() {\n // Do nothing.\n }\n\n @Override\n public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {\n // Do nothing.\n }\n\n @Override\n public void onTimelineChanged(Timeline timeline, Object manifest) {\n // Do nothing.\n }\n\n }\n\n}\n"},"message":{"kind":"string","value":"Workaround for SurfaceView not being hidden properly\n\nThis appears to be fixed in Oreo, but given how harmless\nthe workaround is we can probably just apply it on all\nAPI levels to be sure.\n\nIssue: #3160\n\n-------------\nCreated by MOE: https://github.com/google/moe\nMOE_MIGRATED_REVID=167709070\n"},"old_file":{"kind":"string","value":"library/ui/src/main/java/com/google/android/exoplayer2/ui/SimpleExoPlayerView.java"},"subject":{"kind":"string","value":"Workaround for SurfaceView not being hidden properly"},"git_diff":{"kind":"string","value":"ibrary/ui/src/main/java/com/google/android/exoplayer2/ui/SimpleExoPlayerView.java\n }\n }\n \n @Override\n public void setVisibility(int visibility) {\n super.setVisibility(visibility);\n if (surfaceView instanceof SurfaceView) {\n // Work around https://github.com/google/ExoPlayer/issues/3160\n surfaceView.setVisibility(visibility);\n }\n }\n\n /**\n * Sets the resize mode.\n *"}}},{"rowIdx":1978,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"eb80b4e104f7f04e8c3e0e3c36dd85776b1efbf0"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"CliffYuan/netty,KeyNexus/netty,CliffYuan/netty,KeyNexus/netty"},"new_contents":{"kind":"string","value":"/*\n * Copyright 2012 The Netty Project\n *\n * The Netty Project licenses this file to you under the Apache License,\n * version 2.0 (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at:\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations\n * under the License.\n */\npackage org.jboss.netty.channel.local;\n\nimport static org.jboss.netty.channel.Channels.*;\n\nimport java.nio.channels.ClosedChannelException;\nimport java.nio.channels.NotYetConnectedException;\nimport java.util.Queue;\nimport java.util.concurrent.ConcurrentLinkedQueue;\nimport java.util.concurrent.atomic.AtomicInteger;\n\nimport org.jboss.netty.channel.AbstractChannel;\nimport org.jboss.netty.channel.ChannelConfig;\nimport org.jboss.netty.channel.ChannelException;\nimport org.jboss.netty.channel.ChannelFactory;\nimport org.jboss.netty.channel.ChannelFuture;\nimport org.jboss.netty.channel.ChannelFutureListener;\nimport org.jboss.netty.channel.ChannelPipeline;\nimport org.jboss.netty.channel.ChannelSink;\nimport org.jboss.netty.channel.DefaultChannelConfig;\nimport org.jboss.netty.channel.MessageEvent;\nimport org.jboss.netty.util.internal.ThreadLocalBoolean;\n\n/**\n */\nfinal class DefaultLocalChannel extends AbstractChannel implements LocalChannel {\n\n // TODO Move the state management up to AbstractChannel to remove duplication.\n private static final int ST_OPEN = 0;\n private static final int ST_BOUND = 1;\n private static final int ST_CONNECTED = 2;\n private static final int ST_CLOSED = -1;\n final AtomicInteger state = new AtomicInteger(ST_OPEN);\n\n private final ChannelConfig config;\n private final ThreadLocalBoolean delivering = new ThreadLocalBoolean();\n\n final Queue writeBuffer = new ConcurrentLinkedQueue();\n\n volatile DefaultLocalChannel pairedChannel;\n volatile LocalAddress localAddress;\n volatile LocalAddress remoteAddress;\n\n DefaultLocalChannel(\n LocalServerChannel parent, ChannelFactory factory, ChannelPipeline pipeline,\n ChannelSink sink, DefaultLocalChannel pairedChannel) {\n super(parent, factory, pipeline, sink);\n this.pairedChannel = pairedChannel;\n config = new DefaultChannelConfig();\n\n // TODO Move the state variable to AbstractChannel so that we don't need\n // to add many listeners.\n getCloseFuture().addListener(new ChannelFutureListener() {\n public void operationComplete(ChannelFuture future) throws Exception {\n state.set(ST_CLOSED);\n }\n });\n\n fireChannelOpen(this);\n }\n\n public ChannelConfig getConfig() {\n return config;\n }\n\n @Override\n public boolean isOpen() {\n return state.get() >= ST_OPEN;\n }\n\n public boolean isBound() {\n return state.get() >= ST_BOUND;\n }\n\n public boolean isConnected() {\n return state.get() == ST_CONNECTED;\n }\n\n void setBound() throws ClosedChannelException {\n if (!state.compareAndSet(ST_OPEN, ST_BOUND)) {\n switch (state.get()) {\n case ST_CLOSED:\n throw new ClosedChannelException();\n default:\n throw new ChannelException(\"already bound\");\n }\n }\n }\n\n void setConnected() {\n if (state.get() != ST_CLOSED) {\n state.set(ST_CONNECTED);\n }\n }\n\n @Override\n protected boolean setClosed() {\n return super.setClosed();\n }\n\n public LocalAddress getLocalAddress() {\n return localAddress;\n }\n\n public LocalAddress getRemoteAddress() {\n return remoteAddress;\n }\n\n void closeNow(ChannelFuture future) {\n LocalAddress localAddress = this.localAddress;\n try {\n // Close the self.\n if (!setClosed()) {\n return;\n }\n\n DefaultLocalChannel pairedChannel = this.pairedChannel;\n if (pairedChannel != null) {\n this.pairedChannel = null;\n fireChannelDisconnected(this);\n fireChannelUnbound(this);\n }\n fireChannelClosed(this);\n\n // Close the peer.\n if (pairedChannel == null || !pairedChannel.setClosed()) {\n return;\n }\n\n DefaultLocalChannel me = pairedChannel.pairedChannel;\n if (me != null) {\n pairedChannel.pairedChannel = null;\n fireChannelDisconnected(pairedChannel);\n fireChannelUnbound(pairedChannel);\n }\n fireChannelClosed(pairedChannel);\n } finally {\n future.setSuccess();\n if (localAddress != null && getParent() == null) {\n LocalChannelRegistry.unregister(localAddress);\n }\n }\n }\n\n void flushWriteBuffer() {\n DefaultLocalChannel pairedChannel = this.pairedChannel;\n if (pairedChannel != null) {\n if (pairedChannel.isConnected()) {\n // Channel is open and connected and channelConnected event has\n // been fired.\n if (!delivering.get()) {\n delivering.set(true);\n try {\n for (;;) {\n MessageEvent e = writeBuffer.poll();\n if (e == null) {\n break;\n }\n\n fireMessageReceived(pairedChannel, e.getMessage());\n e.getFuture().setSuccess();\n fireWriteComplete(this, 1);\n }\n } finally {\n delivering.set(false);\n }\n }\n } else {\n // Channel is open and connected but channelConnected event has\n // not been fired yet.\n }\n } else {\n // Channel is closed or not connected yet - notify as failures.\n Exception cause;\n if (isOpen()) {\n cause = new NotYetConnectedException();\n } else {\n cause = new ClosedChannelException();\n }\n\n for (;;) {\n MessageEvent e = writeBuffer.poll();\n if (e == null) {\n break;\n }\n\n fireExceptionCaught(this, cause);\n e.getFuture().setFailure(cause);\n }\n }\n }\n}\n"},"new_file":{"kind":"string","value":"src/main/java/org/jboss/netty/channel/local/DefaultLocalChannel.java"},"old_contents":{"kind":"string","value":"/*\n * Copyright 2012 The Netty Project\n *\n * The Netty Project licenses this file to you under the Apache License,\n * version 2.0 (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at:\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations\n * under the License.\n */\npackage org.jboss.netty.channel.local;\n\nimport static org.jboss.netty.channel.Channels.*;\n\nimport java.nio.channels.ClosedChannelException;\nimport java.nio.channels.NotYetConnectedException;\nimport java.util.Queue;\nimport java.util.concurrent.ConcurrentLinkedQueue;\nimport java.util.concurrent.atomic.AtomicInteger;\n\nimport org.jboss.netty.channel.AbstractChannel;\nimport org.jboss.netty.channel.ChannelConfig;\nimport org.jboss.netty.channel.ChannelException;\nimport org.jboss.netty.channel.ChannelFactory;\nimport org.jboss.netty.channel.ChannelFuture;\nimport org.jboss.netty.channel.ChannelFutureListener;\nimport org.jboss.netty.channel.ChannelPipeline;\nimport org.jboss.netty.channel.ChannelSink;\nimport org.jboss.netty.channel.DefaultChannelConfig;\nimport org.jboss.netty.channel.MessageEvent;\nimport org.jboss.netty.util.internal.ThreadLocalBoolean;\n\n/**\n */\nfinal class DefaultLocalChannel extends AbstractChannel implements LocalChannel {\n\n // TODO Move the state management up to AbstractChannel to remove duplication.\n private static final int ST_OPEN = 0;\n private static final int ST_BOUND = 1;\n private static final int ST_CONNECTED = 2;\n private static final int ST_CLOSED = -1;\n final AtomicInteger state = new AtomicInteger(ST_OPEN);\n\n private final ChannelConfig config;\n private final ThreadLocalBoolean delivering = new ThreadLocalBoolean();\n\n final Queue writeBuffer = new ConcurrentLinkedQueue();\n\n volatile DefaultLocalChannel pairedChannel;\n volatile LocalAddress localAddress;\n volatile LocalAddress remoteAddress;\n\n DefaultLocalChannel(\n LocalServerChannel parent, ChannelFactory factory, ChannelPipeline pipeline,\n ChannelSink sink, DefaultLocalChannel pairedChannel) {\n super(parent, factory, pipeline, sink);\n this.pairedChannel = pairedChannel;\n config = new DefaultChannelConfig();\n\n // TODO Move the state variable to AbstractChannel so that we don't need\n // to add many listeners.\n getCloseFuture().addListener(new ChannelFutureListener() {\n public void operationComplete(ChannelFuture future) throws Exception {\n state.set(ST_CLOSED);\n }\n });\n\n fireChannelOpen(this);\n }\n\n public ChannelConfig getConfig() {\n return config;\n }\n\n @Override\n public boolean isOpen() {\n return state.get() >= ST_OPEN;\n }\n\n public boolean isBound() {\n return state.get() >= ST_BOUND;\n }\n\n public boolean isConnected() {\n return state.get() == ST_CONNECTED;\n }\n\n void setBound() throws ClosedChannelException {\n if (!state.compareAndSet(ST_OPEN, ST_BOUND)) {\n switch (state.get()) {\n case ST_CLOSED:\n throw new ClosedChannelException();\n default:\n throw new ChannelException(\"already bound\");\n }\n }\n }\n\n void setConnected() {\n if (state.get() != ST_CLOSED) {\n state.set(ST_CONNECTED);\n }\n }\n\n @Override\n protected boolean setClosed() {\n return super.setClosed();\n }\n\n public LocalAddress getLocalAddress() {\n return localAddress;\n }\n\n public LocalAddress getRemoteAddress() {\n return remoteAddress;\n }\n\n void closeNow(ChannelFuture future) {\n LocalAddress localAddress = this.localAddress;\n try {\n // Close the self.\n if (!setClosed()) {\n return;\n }\n\n DefaultLocalChannel pairedChannel = this.pairedChannel;\n if (pairedChannel != null) {\n this.pairedChannel = null;\n fireChannelDisconnected(this);\n fireChannelUnbound(this);\n }\n fireChannelClosed(this);\n\n // Close the peer.\n if (pairedChannel == null || !pairedChannel.setClosed()) {\n return;\n }\n\n DefaultLocalChannel me = pairedChannel.pairedChannel;\n if (me != null) {\n pairedChannel.pairedChannel = null;\n fireChannelDisconnected(pairedChannel);\n fireChannelUnbound(pairedChannel);\n }\n fireChannelClosed(pairedChannel);\n } finally {\n future.setSuccess();\n if (localAddress != null && getParent() == null) {\n LocalChannelRegistry.unregister(localAddress);\n }\n }\n }\n\n void flushWriteBuffer() {\n DefaultLocalChannel pairedChannel = this.pairedChannel;\n if (pairedChannel != null) {\n if (pairedChannel.isConnected()) {\n // Channel is open and connected and channelConnected event has\n // been fired.\n if (!delivering.get()) {\n delivering.set(true);\n try {\n for (;;) {\n MessageEvent e = writeBuffer.poll();\n if (e == null) {\n break;\n }\n\n e.getFuture().setSuccess();\n fireMessageReceived(pairedChannel, e.getMessage());\n fireWriteComplete(this, 1);\n }\n } finally {\n delivering.set(false);\n }\n }\n } else {\n // Channel is open and connected but channelConnected event has\n // not been fired yet.\n }\n } else {\n // Channel is closed or not connected yet - notify as failures.\n Exception cause;\n if (isOpen()) {\n cause = new NotYetConnectedException();\n } else {\n cause = new ClosedChannelException();\n }\n\n for (;;) {\n MessageEvent e = writeBuffer.poll();\n if (e == null) {\n break;\n }\n\n e.getFuture().setFailure(cause);\n fireExceptionCaught(this, cause);\n }\n }\n }\n}\n"},"message":{"kind":"string","value":"intermittent: local channel sometimes sends messages after close\n"},"old_file":{"kind":"string","value":"src/main/java/org/jboss/netty/channel/local/DefaultLocalChannel.java"},"subject":{"kind":"string","value":"intermittent: local channel sometimes sends messages after close"},"git_diff":{"kind":"string","value":"rc/main/java/org/jboss/netty/channel/local/DefaultLocalChannel.java\n break;\n }\n \n fireMessageReceived(pairedChannel, e.getMessage());\n e.getFuture().setSuccess();\n fireMessageReceived(pairedChannel, e.getMessage());\n fireWriteComplete(this, 1);\n }\n } finally {\n break;\n }\n \n fireExceptionCaught(this, cause);\n e.getFuture().setFailure(cause);\n fireExceptionCaught(this, cause);\n }\n }\n }"}}},{"rowIdx":1979,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"1381454d663679fc25eab2eeff41a0e15a60aef0"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"Braunch/jabref,tobiasdiez/jabref,oscargus/jabref,mairdl/jabref,Mr-DLib/jabref,bartsch-dev/jabref,ayanai1/jabref,tschechlovdev/jabref,jhshinn/jabref,mredaelli/jabref,mredaelli/jabref,JabRef/jabref,Braunch/jabref,motokito/jabref,grimes2/jabref,shitikanth/jabref,oscargus/jabref,mairdl/jabref,shitikanth/jabref,tschechlovdev/jabref,zellerdev/jabref,zellerdev/jabref,zellerdev/jabref,Siedlerchr/jabref,motokito/jabref,jhshinn/jabref,ayanai1/jabref,jhshinn/jabref,sauliusg/jabref,bartsch-dev/jabref,jhshinn/jabref,JabRef/jabref,mairdl/jabref,oscargus/jabref,mredaelli/jabref,sauliusg/jabref,ayanai1/jabref,grimes2/jabref,zellerdev/jabref,motokito/jabref,tschechlovdev/jabref,ayanai1/jabref,sauliusg/jabref,Braunch/jabref,oscargus/jabref,tobiasdiez/jabref,tschechlovdev/jabref,grimes2/jabref,JabRef/jabref,mairdl/jabref,shitikanth/jabref,shitikanth/jabref,tschechlovdev/jabref,ayanai1/jabref,sauliusg/jabref,tobiasdiez/jabref,grimes2/jabref,bartsch-dev/jabref,grimes2/jabref,zellerdev/jabref,motokito/jabref,oscargus/jabref,mairdl/jabref,Braunch/jabref,Siedlerchr/jabref,Mr-DLib/jabref,obraliar/jabref,tobiasdiez/jabref,shitikanth/jabref,bartsch-dev/jabref,bartsch-dev/jabref,motokito/jabref,JabRef/jabref,obraliar/jabref,obraliar/jabref,Braunch/jabref,mredaelli/jabref,Mr-DLib/jabref,Mr-DLib/jabref,mredaelli/jabref,Siedlerchr/jabref,Mr-DLib/jabref,jhshinn/jabref,Siedlerchr/jabref,obraliar/jabref,obraliar/jabref"},"new_contents":{"kind":"string","value":"/* Copyright (C) 2003-2015 JabRef contributors.\n This program is free software; you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License along\n with this program; if not, write to the Free Software Foundation, Inc.,\n 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n*/\npackage net.sf.jabref.logic.search.rules;\n\nimport net.sf.jabref.model.entry.BibtexEntry;\nimport net.sf.jabref.search.SearchBaseVisitor;\nimport net.sf.jabref.logic.search.SearchRule;\nimport net.sf.jabref.search.SearchLexer;\nimport net.sf.jabref.search.SearchParser;\nimport org.antlr.v4.runtime.*;\nimport org.antlr.v4.runtime.misc.ParseCancellationException;\nimport org.antlr.v4.runtime.tree.ParseTree;\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\n\nimport java.util.Objects;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\n/**\n * The search query must be specified in an expression that is acceptable by the Search.g4 grammar.\n */\npublic class GrammarBasedSearchRule implements SearchRule {\n\n private static final Log LOGGER = LogFactory.getLog(GrammarBasedSearchRule.class);\n\n\n public static class ThrowingErrorListener extends BaseErrorListener {\n\n public static final ThrowingErrorListener INSTANCE = new ThrowingErrorListener();\n\n @Override\n public void syntaxError(Recognizer recognizer, Object offendingSymbol,\n int line, int charPositionInLine, String msg, RecognitionException e)\n throws ParseCancellationException {\n throw new ParseCancellationException(\"line \" + line + \":\" + charPositionInLine + \" \" + msg);\n }\n }\n\n private final boolean caseSensitiveSearch;\n private final boolean regExpSearch;\n\n private ParseTree tree;\n private String query;\n\n public GrammarBasedSearchRule(boolean caseSensitiveSearch, boolean regExpSearch) throws RecognitionException {\n this.caseSensitiveSearch = caseSensitiveSearch;\n this.regExpSearch = regExpSearch;\n }\n\n public static boolean isValid(boolean caseSensitive, boolean regExp, String query) {\n return new GrammarBasedSearchRule(caseSensitive, regExp).validateSearchStrings(query);\n }\n\n public boolean isCaseSensitiveSearch() {\n return this.caseSensitiveSearch;\n }\n\n public boolean isRegExpSearch() {\n return this.regExpSearch;\n }\n\n public ParseTree getTree() {\n return this.tree;\n }\n\n public String getQuery() {\n return this.query;\n }\n\n private void init(String query) throws ParseCancellationException {\n if(Objects.equals(this.query, query)) {\n return;\n }\n\n SearchLexer lexer = new SearchLexer(new ANTLRInputStream(query));\n lexer.removeErrorListeners(); // no infos on file system\n lexer.addErrorListener(ThrowingErrorListener.INSTANCE);\n SearchParser parser = new SearchParser(new CommonTokenStream(lexer));\n parser.removeErrorListeners(); // no infos on file system\n parser.addErrorListener(ThrowingErrorListener.INSTANCE);\n parser.setErrorHandler(new BailErrorStrategy()); // ParseCancellationException on parse errors\n tree = parser.start();\n this.query = query;\n }\n\n @Override\n public boolean applyRule(String query, BibtexEntry bibtexEntry) {\n try {\n return new BibtexSearchVisitor(caseSensitiveSearch, regExpSearch, bibtexEntry).visit(tree);\n } catch (Exception e) {\n LOGGER.debug(\"Search failed\", e);\n return false;\n }\n }\n\n @Override\n public boolean validateSearchStrings(String query) {\n try {\n init(query);\n return true;\n } catch (ParseCancellationException e) {\n return false;\n }\n }\n\n public enum ComparisonOperator {\n EXACT, CONTAINS, DOES_NOT_CONTAIN;\n\n public static ComparisonOperator build(String value) {\n if (\"CONTAINS\".equalsIgnoreCase(value) || \"=\".equals(value)) {\n return CONTAINS;\n } else if (\"MATCHES\".equalsIgnoreCase(value) || \"==\".equals(value)) {\n return EXACT;\n } else {\n return DOES_NOT_CONTAIN;\n }\n }\n }\n\n public static class Comparator {\n\n private final ComparisonOperator operator;\n private final Pattern fieldPattern;\n private final Pattern valuePattern;\n\n public Comparator(String field, String value, ComparisonOperator operator, boolean caseSensitive, boolean regex) {\n this.operator = operator;\n\n this.fieldPattern = Pattern.compile(regex ? field : \"\\\\Q\" + field + \"\\\\E\", caseSensitive ? 0 : Pattern.CASE_INSENSITIVE);\n this.valuePattern = Pattern.compile(regex ? value : \"\\\\Q\" + value + \"\\\\E\", caseSensitive ? 0 : Pattern.CASE_INSENSITIVE);\n }\n\n public boolean compare(BibtexEntry entry) {\n // specification of fields to search is done in the search expression itself\n String[] searchKeys = entry.getFieldNames().toArray(new String[entry.getFieldNames().size()]);\n\n boolean noSuchField = true;\n // this loop iterates over all regular keys, then over pseudo keys like \"type\"\n for (int i = 0; i < (searchKeys.length + 1); i++) {\n String content;\n if ((i - searchKeys.length) == 0) {\n // PSEUDOFIELD_TYPE\n if (!fieldPattern.matcher(\"entrytype\").matches()) {\n continue;\n }\n content = entry.getType().getName();\n } else {\n String searchKey = searchKeys[i];\n if (!fieldPattern.matcher(searchKey).matches()) {\n continue;\n }\n content = entry.getField(searchKey);\n }\n noSuchField = false;\n if (content == null) {\n continue; // paranoia\n }\n\n if(matchInField(content)) {\n return true;\n }\n }\n\n return noSuchField && (operator == ComparisonOperator.DOES_NOT_CONTAIN);\n }\n\n public boolean matchInField(String content) {\n Matcher matcher = valuePattern.matcher(content);\n if (operator == ComparisonOperator.CONTAINS) {\n return matcher.find();\n } else if (operator == ComparisonOperator.EXACT) {\n return matcher.matches();\n } else if (operator == ComparisonOperator.DOES_NOT_CONTAIN) {\n return !matcher.find();\n } else {\n throw new IllegalStateException(\"MUST NOT HAPPEN\");\n }\n }\n\n }\n\n\n /**\n * Search results in boolean. It may be later on converted to an int.\n */\n static class BibtexSearchVisitor extends SearchBaseVisitor {\n\n private final boolean caseSensitive;\n private final boolean regex;\n\n private final BibtexEntry entry;\n\n public BibtexSearchVisitor(boolean caseSensitive, boolean regex, BibtexEntry bibtexEntry) {\n this.caseSensitive = caseSensitive;\n this.regex = regex;\n this.entry = bibtexEntry;\n }\n\n public boolean comparison(String field, ComparisonOperator operator, String value) {\n return new Comparator(field, value, operator, caseSensitive, regex).compare(entry);\n }\n\n @Override public Boolean visitStart(SearchParser.StartContext ctx) {\n return visit(ctx.expression());\n }\n\n @Override\n public Boolean visitComparison(SearchParser.ComparisonContext ctx) {\n return comparison(ctx.left.getText(), ComparisonOperator.build(ctx.operator.getText()), ctx.right.getText());\n }\n\n @Override\n public Boolean visitUnaryExpression(SearchParser.UnaryExpressionContext ctx) {\n return !visit(ctx.expression()); // negate\n }\n\n @Override\n public Boolean visitParenExpression(SearchParser.ParenExpressionContext ctx) {\n return visit(ctx.expression()); // ignore parenthesis\n }\n\n @Override\n public Boolean visitBinaryExpression(SearchParser.BinaryExpressionContext ctx) {\n if (\"AND\".equalsIgnoreCase(ctx.operator.getText())) {\n return visit(ctx.left) && visit(ctx.right); // and\n } else {\n return visit(ctx.left) || visit(ctx.right); // or\n }\n }\n\n }\n\n}\n"},"new_file":{"kind":"string","value":"src/main/java/net/sf/jabref/logic/search/rules/GrammarBasedSearchRule.java"},"old_contents":{"kind":"string","value":"/* Copyright (C) 2003-2015 JabRef contributors.\n This program is free software; you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License along\n with this program; if not, write to the Free Software Foundation, Inc.,\n 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n*/\npackage net.sf.jabref.logic.search.rules;\n\nimport net.sf.jabref.model.entry.BibtexEntry;\nimport net.sf.jabref.search.SearchBaseVisitor;\nimport net.sf.jabref.logic.search.SearchRule;\nimport net.sf.jabref.search.SearchLexer;\nimport net.sf.jabref.search.SearchParser;\nimport org.antlr.v4.runtime.*;\nimport org.antlr.v4.runtime.misc.ParseCancellationException;\nimport org.antlr.v4.runtime.tree.ParseTree;\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\n\nimport java.util.Objects;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\n/**\n * The search query must be specified in an expression that is acceptable by the Search.g4 grammar.\n */\npublic class GrammarBasedSearchRule implements SearchRule {\n\n private static final Log LOGGER = LogFactory.getLog(GrammarBasedSearchRule.class);\n\n\n public static class ThrowingErrorListener extends BaseErrorListener {\n\n public static final ThrowingErrorListener INSTANCE = new ThrowingErrorListener();\n\n @Override\n public void syntaxError(Recognizer recognizer, Object offendingSymbol,\n int line, int charPositionInLine, String msg, RecognitionException e)\n throws ParseCancellationException {\n throw new ParseCancellationException(\"line \" + line + \":\" + charPositionInLine + \" \" + msg);\n }\n }\n\n private final boolean caseSensitiveSearch;\n private final boolean regExpSearch;\n\n private ParseTree tree;\n private String query;\n\n public GrammarBasedSearchRule(boolean caseSensitiveSearch, boolean regExpSearch) throws RecognitionException {\n this.caseSensitiveSearch = caseSensitiveSearch;\n this.regExpSearch = regExpSearch;\n }\n\n public static boolean isValid(boolean caseSensitive, boolean regExp, String query) {\n return new GrammarBasedSearchRule(caseSensitive, regExp).validateSearchStrings(query);\n }\n\n public boolean isCaseSensitiveSearch() {\n return this.caseSensitiveSearch;\n }\n\n public boolean isRegExpSearch() {\n return this.regExpSearch;\n }\n\n public ParseTree getTree() {\n return this.tree;\n }\n\n public String getQuery() {\n return this.query;\n }\n\n private void init(String query) throws ParseCancellationException {\n if(Objects.equals(this.query, query)) {\n return;\n }\n\n SearchLexer lexer = new SearchLexer(new ANTLRInputStream(query));\n lexer.removeErrorListeners(); // no infos on file system\n lexer.addErrorListener(ThrowingErrorListener.INSTANCE);\n SearchParser parser = new SearchParser(new CommonTokenStream(lexer));\n parser.removeErrorListeners(); // no infos on file system\n parser.addErrorListener(ThrowingErrorListener.INSTANCE);\n parser.setErrorHandler(new BailErrorStrategy()); // ParseCancellationException on parse errors\n tree = parser.start();\n this.query = query;\n }\n\n @Override\n public boolean applyRule(String query, BibtexEntry bibtexEntry) {\n try {\n return new BibtexSearchVisitor(caseSensitiveSearch, regExpSearch, bibtexEntry).visit(tree);\n } catch (Exception e) {\n LOGGER.debug(\"Search failed: \" + e.getMessage());\n return false;\n }\n }\n\n @Override\n public boolean validateSearchStrings(String query) {\n try {\n init(query);\n return true;\n } catch (ParseCancellationException e) {\n return false;\n }\n }\n\n public enum ComparisonOperator {\n EXACT, CONTAINS, DOES_NOT_CONTAIN;\n\n public static ComparisonOperator build(String value) {\n if (\"CONTAINS\".equalsIgnoreCase(value) || \"=\".equals(value)) {\n return CONTAINS;\n } else if (\"MATCHES\".equalsIgnoreCase(value) || \"==\".equals(value)) {\n return EXACT;\n } else {\n return DOES_NOT_CONTAIN;\n }\n }\n }\n\n public static class Comparator {\n\n private final ComparisonOperator operator;\n private final Pattern fieldPattern;\n private final Pattern valuePattern;\n\n public Comparator(String field, String value, ComparisonOperator operator, boolean caseSensitive, boolean regex) {\n this.operator = operator;\n\n this.fieldPattern = Pattern.compile(regex ? field : \"\\\\Q\" + field + \"\\\\E\", caseSensitive ? 0 : Pattern.CASE_INSENSITIVE);\n this.valuePattern = Pattern.compile(regex ? value : \"\\\\Q\" + value + \"\\\\E\", caseSensitive ? 0 : Pattern.CASE_INSENSITIVE);\n }\n\n public boolean compare(BibtexEntry entry) {\n // specification of fields to search is done in the search expression itself\n String[] searchKeys = entry.getFieldNames().toArray(new String[entry.getFieldNames().size()]);\n\n boolean noSuchField = true;\n // this loop iterates over all regular keys, then over pseudo keys like \"type\"\n for (int i = 0; i < searchKeys.length + 1; i++) {\n String content;\n if (i - searchKeys.length == 0) {\n // PSEUDOFIELD_TYPE\n if (!fieldPattern.matcher(\"entrytype\").matches()) {\n continue;\n }\n content = entry.getType().getName();\n } else {\n String searchKey = searchKeys[i];\n if (!fieldPattern.matcher(searchKey).matches()) {\n continue;\n }\n content = entry.getField(searchKey);\n }\n noSuchField = false;\n if (content == null) {\n continue; // paranoia\n }\n\n if(matchInField(content)) {\n return true;\n }\n }\n\n return noSuchField && operator == ComparisonOperator.DOES_NOT_CONTAIN;\n }\n\n public boolean matchInField(String content) {\n Matcher matcher = valuePattern.matcher(content);\n if (operator == ComparisonOperator.CONTAINS) {\n return matcher.find();\n } else if (operator == ComparisonOperator.EXACT) {\n return matcher.matches();\n } else if (operator == ComparisonOperator.DOES_NOT_CONTAIN) {\n return !matcher.find();\n } else {\n throw new IllegalStateException(\"MUST NOT HAPPEN\");\n }\n }\n\n }\n\n\n /**\n * Search results in boolean. It may be later on converted to an int.\n */\n static class BibtexSearchVisitor extends SearchBaseVisitor {\n\n private final boolean caseSensitive;\n private final boolean regex;\n\n private final BibtexEntry entry;\n\n public BibtexSearchVisitor(boolean caseSensitive, boolean regex, BibtexEntry bibtexEntry) {\n this.caseSensitive = caseSensitive;\n this.regex = regex;\n this.entry = bibtexEntry;\n }\n\n public boolean comparison(String field, ComparisonOperator operator, String value) {\n return new Comparator(field, value, operator, caseSensitive, regex).compare(entry);\n }\n\n @Override public Boolean visitStart(SearchParser.StartContext ctx) {\n return visit(ctx.expression());\n }\n\n @Override\n public Boolean visitComparison(SearchParser.ComparisonContext ctx) {\n return comparison(ctx.left.getText(), ComparisonOperator.build(ctx.operator.getText()), ctx.right.getText());\n }\n\n @Override\n public Boolean visitUnaryExpression(SearchParser.UnaryExpressionContext ctx) {\n return !visit(ctx.expression()); // negate\n }\n\n @Override\n public Boolean visitParenExpression(SearchParser.ParenExpressionContext ctx) {\n return visit(ctx.expression()); // ignore parenthesis\n }\n\n @Override\n public Boolean visitBinaryExpression(SearchParser.BinaryExpressionContext ctx) {\n if (\"AND\".equalsIgnoreCase(ctx.operator.getText())) {\n return visit(ctx.left) && visit(ctx.right); // and\n } else {\n return visit(ctx.left) || visit(ctx.right); // or\n }\n }\n\n }\n\n}\n"},"message":{"kind":"string","value":"Pass whole exception to LOGGER.debug (and add some brackets to the expressions due to Eclipse formatter)\n"},"old_file":{"kind":"string","value":"src/main/java/net/sf/jabref/logic/search/rules/GrammarBasedSearchRule.java"},"subject":{"kind":"string","value":"Pass whole exception to LOGGER.debug (and add some brackets to the expressions due to Eclipse formatter)"},"git_diff":{"kind":"string","value":"rc/main/java/net/sf/jabref/logic/search/rules/GrammarBasedSearchRule.java\n try {\n return new BibtexSearchVisitor(caseSensitiveSearch, regExpSearch, bibtexEntry).visit(tree);\n } catch (Exception e) {\n LOGGER.debug(\"Search failed: \" + e.getMessage());\n LOGGER.debug(\"Search failed\", e);\n return false;\n }\n }\n \n boolean noSuchField = true;\n // this loop iterates over all regular keys, then over pseudo keys like \"type\"\n for (int i = 0; i < searchKeys.length + 1; i++) {\n for (int i = 0; i < (searchKeys.length + 1); i++) {\n String content;\n if (i - searchKeys.length == 0) {\n if ((i - searchKeys.length) == 0) {\n // PSEUDOFIELD_TYPE\n if (!fieldPattern.matcher(\"entrytype\").matches()) {\n continue;\n }\n }\n \n return noSuchField && operator == ComparisonOperator.DOES_NOT_CONTAIN;\n return noSuchField && (operator == ComparisonOperator.DOES_NOT_CONTAIN);\n }\n \n public boolean matchInField(String content) {"}}},{"rowIdx":1980,"cells":{"lang":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"521ba4d81df10aa44e7661ea30a28a55cfed84aa"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"fedebertolini/uno-score-tracker,fedebertolini/uno-score-tracker"},"new_contents":{"kind":"string","value":"import React, { PropTypes } from 'react';\nimport { Link } from 'react-router';\nimport { GAME_STATUS_IN_PROGRESS, GAME_STATUS_FINISHED } from '../constants';\n\nclass RoundTable extends React.Component {\n\n componentWillMount() {\n this.roundScores = this.buildScores(this.props.players, this.props.rounds);\n this.winner = null;\n\n if (this.roundScores.length) {\n const lastRoundScores = this.roundScores[this.roundScores.length - 1].scores;\n const nonLosers = lastRoundScores.filter(score => score.accumulativePoints <= this.props.game.maxScore);\n\n if (nonLosers.length === 1) {\n const winnerId = nonLosers[0].playerId;\n this.winner = this.props.players.find(player => player.id === winnerId);\n if (this.props.game.status === GAME_STATUS_IN_PROGRESS) {\n this.props.onGameComplete();\n }\n }\n }\n }\n\n render() {\n return (\n
    \n

    \n \n \n { this.props.players.map(player => ) }\n \n \n \n { this.props.rounds.length ? this.scoreRows() : this.emptyRow() }\n \n
    {player.name}
    \n { this.props.game.status === GAME_STATUS_IN_PROGRESS && New Round! }\n { this.winner &&

    Winner: {this.winner.name}!

    }\n \n )\n }\n\n emptyRow() {\n return (\n \n { this.props.players.map(player => 0) }\n \n );\n }\n\n scoreRows() {\n return this.roundScores.map(round => (\n \n {round.scores.map(score =>(\n {score.accumulativePoints}\n ))}\n \n ));\n }\n\n buildScores(players, rounds) {\n let accumulativePoints = {};\n players.forEach(player => accumulativePoints[player.id] = 0);\n\n return rounds.map(round => ({\n roundId: round.id,\n scores: players.map(player => ({\n playerId: player.id,\n roundPoints: round.scores[player.id],\n accumulativePoints: (accumulativePoints[player.id] += round.scores[player.id])\n }))\n }));\n };\n}\n\nRoundTable.propTypes = {\n players: PropTypes.array.isRequired,\n rounds: PropTypes.array.isRequired,\n game: PropTypes.shape({\n status: React.PropTypes.string,\n maxScore: React.PropTypes.number\n }).isRequired,\n onGameComplete: PropTypes.func.isRequired,\n};\n\nexport default RoundTable;\n"},"new_file":{"kind":"string","value":"src/components/RoundTable.js"},"old_contents":{"kind":"string","value":"import React, { PropTypes } from 'react';\nimport { Link } from 'react-router';\nimport { GAME_STATUS_IN_PROGRESS, GAME_STATUS_FINISHED } from '../constants';\n\nclass RoundTable extends React.Component {\n constructor(props) {\n super(props);\n\n this.roundScores = this.buildScores(props.players, props.rounds);\n this.winner = null;\n\n if (this.roundScores.length) {\n const lastRoundScores = this.roundScores[this.roundScores.length - 1].scores;\n const nonLosers = lastRoundScores.filter(score => score.accumulativePoints <= props.game.maxScore);\n\n if (nonLosers.length === 1) {\n this.winner = nonLosers[0];\n if (props.game.status === GAME_STATUS_IN_PROGRESS) {\n props.onGameComplete();\n }\n }\n }\n }\n\n render() {\n return (\n
    \n \n \n \n { this.props.players.map(player => ) }\n \n \n \n { this.props.rounds.length ? this.scoreRows() : this.emptyRow() }\n \n
    {player.name}
    \n { this.props.game.status === GAME_STATUS_IN_PROGRESS && New Round! }\n\n
    \n )\n }\n\n emptyRow() {\n return (\n \n { this.props.players.map(player => 0) }\n \n );\n }\n\n scoreRows() {\n return this.roundScores.map(round => (\n \n {round.scores.map(score =>(\n {score.accumulativePoints}\n ))}\n \n ));\n }\n\n buildScores(players, rounds) {\n let accumulativePoints = {};\n players.forEach(player => accumulativePoints[player.id] = 0);\n\n return rounds.map(round => ({\n roundId: round.id,\n scores: players.map(player => ({\n playerId: player.id,\n roundPoints: round.scores[player.id],\n accumulativePoints: (accumulativePoints[player.id] += round.scores[player.id])\n }))\n }));\n };\n}\n\nRoundTable.propTypes = {\n players: PropTypes.array.isRequired,\n rounds: PropTypes.array.isRequired,\n game: PropTypes.shape({\n status: React.PropTypes.string,\n maxScore: React.PropTypes.number\n }).isRequired,\n onGameComplete: PropTypes.func.isRequired,\n};\n\nexport default RoundTable;\n"},"message":{"kind":"string","value":"show winner\n"},"old_file":{"kind":"string","value":"src/components/RoundTable.js"},"subject":{"kind":"string","value":"show winner"},"git_diff":{"kind":"string","value":"rc/components/RoundTable.js\n import { GAME_STATUS_IN_PROGRESS, GAME_STATUS_FINISHED } from '../constants';\n \n class RoundTable extends React.Component {\n constructor(props) {\n super(props);\n \n this.roundScores = this.buildScores(props.players, props.rounds);\n componentWillMount() {\n this.roundScores = this.buildScores(this.props.players, this.props.rounds);\n this.winner = null;\n \n if (this.roundScores.length) {\n const lastRoundScores = this.roundScores[this.roundScores.length - 1].scores;\n const nonLosers = lastRoundScores.filter(score => score.accumulativePoints <= props.game.maxScore);\n const nonLosers = lastRoundScores.filter(score => score.accumulativePoints <= this.props.game.maxScore);\n \n if (nonLosers.length === 1) {\n this.winner = nonLosers[0];\n if (props.game.status === GAME_STATUS_IN_PROGRESS) {\n props.onGameComplete();\n const winnerId = nonLosers[0].playerId;\n this.winner = this.props.players.find(player => player.id === winnerId);\n if (this.props.game.status === GAME_STATUS_IN_PROGRESS) {\n this.props.onGameComplete();\n }\n }\n }\n \n \n { this.props.game.status === GAME_STATUS_IN_PROGRESS && New Round! }\n\n { this.winner &&

    Winner: {this.winner.name}!

    }\n \n )\n }"}}},{"rowIdx":1981,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"bsd-3-clause"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"b4e6e6eec19b1ee528414744ce3374fcd823d404"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"ndexbio/ndex-rest,ndexbio/ndex-rest,ndexbio/ndex-rest,ndexbio/ndex-rest"},"new_contents":{"kind":"string","value":"/**\n * Copyright (c) 2013, 2016, The Regents of the University of California, The Cytoscape Consortium\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and/or other materials provided with the distribution.\n *\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n */\npackage org.ndexbio.rest.services;\n\nimport java.io.ByteArrayOutputStream;\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.io.PipedInputStream;\nimport java.io.PipedOutputStream;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.nio.file.Files;\nimport java.nio.file.LinkOption;\nimport java.nio.file.Paths;\nimport java.nio.file.StandardCopyOption;\nimport java.nio.file.attribute.FileAttribute;\nimport java.nio.file.attribute.PosixFilePermission;\nimport java.nio.file.attribute.PosixFilePermissions;\nimport java.sql.SQLException;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.UUID;\n\nimport javax.annotation.security.PermitAll;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.ws.rs.Consumes;\nimport javax.ws.rs.DELETE;\nimport javax.ws.rs.DefaultValue;\nimport javax.ws.rs.GET;\nimport javax.ws.rs.POST;\nimport javax.ws.rs.PUT;\nimport javax.ws.rs.Path;\nimport javax.ws.rs.PathParam;\nimport javax.ws.rs.Produces;\nimport javax.ws.rs.QueryParam;\nimport javax.ws.rs.core.Context;\nimport javax.ws.rs.core.MediaType;\nimport javax.ws.rs.core.Response;\nimport javax.ws.rs.core.Response.ResponseBuilder;\n\nimport org.apache.commons.io.FileUtils;\nimport org.apache.solr.client.solrj.SolrServerException;\nimport org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;\nimport org.ndexbio.common.NdexClasses;\nimport org.ndexbio.common.cx.CX2NetworkFileGenerator;\nimport org.ndexbio.common.cx.CXNetworkFileGenerator;\nimport org.ndexbio.common.models.dao.postgresql.NetworkDAO;\nimport org.ndexbio.common.models.dao.postgresql.UserDAO;\nimport org.ndexbio.common.persistence.CX2NetworkLoader;\nimport org.ndexbio.common.persistence.CXNetworkAspectsUpdater;\nimport org.ndexbio.common.persistence.CXNetworkLoader;\nimport org.ndexbio.common.util.NdexUUIDFactory;\nimport org.ndexbio.common.util.Util;\nimport org.ndexbio.cx2.aspect.element.core.CxAttributeDeclaration;\nimport org.ndexbio.cx2.aspect.element.core.CxMetadata;\nimport org.ndexbio.cx2.aspect.element.core.CxNetworkAttribute;\nimport org.ndexbio.cx2.converter.AspectAttributeStat;\nimport org.ndexbio.cx2.converter.CXToCX2Converter;\nimport org.ndexbio.cx2.io.CX2AspectWriter;\nimport org.ndexbio.cxio.aspects.datamodels.ATTRIBUTE_DATA_TYPE;\nimport org.ndexbio.cxio.aspects.datamodels.NetworkAttributesElement;\nimport org.ndexbio.cxio.core.CXAspectWriter;\nimport org.ndexbio.cxio.core.OpaqueAspectIterator;\nimport org.ndexbio.cxio.metadata.MetaDataCollection;\nimport org.ndexbio.cxio.metadata.MetaDataElement;\nimport org.ndexbio.cxio.util.JsonWriter;\nimport org.ndexbio.model.exceptions.BadRequestException;\nimport org.ndexbio.model.exceptions.ForbiddenOperationException;\nimport org.ndexbio.model.exceptions.InvalidNetworkException;\nimport org.ndexbio.model.exceptions.NdexException;\nimport org.ndexbio.model.exceptions.NetworkConcurrentModificationException;\nimport org.ndexbio.model.exceptions.ObjectNotFoundException;\nimport org.ndexbio.model.exceptions.UnauthorizedOperationException;\nimport org.ndexbio.model.object.NdexPropertyValuePair;\nimport org.ndexbio.model.object.Permissions;\nimport org.ndexbio.model.object.ProvenanceEntity;\nimport org.ndexbio.model.object.User;\nimport org.ndexbio.model.object.network.NetworkIndexLevel;\nimport org.ndexbio.model.object.network.NetworkSummary;\nimport org.ndexbio.model.object.network.VisibilityType;\nimport org.ndexbio.rest.Configuration;\nimport org.ndexbio.rest.filters.BasicAuthenticationFilter;\nimport org.ndexbio.task.CXNetworkLoadingTask;\nimport org.ndexbio.task.NdexServerQueue;\nimport org.ndexbio.task.SolrIndexScope;\nimport org.ndexbio.task.SolrTaskDeleteNetwork;\nimport org.ndexbio.task.SolrTaskRebuildNetworkIdx;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.fasterxml.jackson.core.JsonParseException;\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.fasterxml.jackson.databind.JsonMappingException;\nimport com.fasterxml.jackson.databind.ObjectMapper;\n\n@Path(\"/v2/network\")\npublic class NetworkServiceV2 extends NdexService {\n\t\n//\tstatic Logger logger = LoggerFactory.getLogger(NetworkService.class);\n\tstatic Logger accLogger = LoggerFactory.getLogger(BasicAuthenticationFilter.accessLoggerName);\n\t\n\tstatic private final String readOnlyParameter = \"readOnly\";\n\t\n\tprivate static final String cx1NetworkFileName = \"network.cx\";\n\n\tpublic NetworkServiceV2(@Context HttpServletRequest httpRequest\n\t\t//\t@Context org.jboss.resteasy.spi.HttpResponse response\n\t\t\t) {\n\t\tsuper(httpRequest);\n\t}\n\n\n\n /**************************************************************************\n * Returns network provenance.\n * @throws IOException\n * @throws JsonMappingException\n * @throws JsonParseException\n * @throws NdexException\n * @throws SQLException \n *\n **************************************************************************/\n\t@PermitAll\n\t@GET\n\t@Path(\"/{networkid}/provenance\")\n\t@Produces(\"application/json\")\n\n\tpublic ProvenanceEntity getProvenance(\n\t\t\t@PathParam(\"networkid\") final String networkIdStr,\n\t\t\t@QueryParam(\"accesskey\") String accessKey)\n\n\t\t\tthrows IllegalArgumentException, JsonParseException, JsonMappingException, IOException, NdexException, SQLException {\n\t\t\n\t\t\n\t\tUUID networkId = UUID.fromString(networkIdStr);\n\t\t\n\t\ttry (NetworkDAO daoNew = new NetworkDAO()) {\n\t\t\tif ( !daoNew.isReadable(networkId, getLoggedInUserId()) && (!daoNew.accessKeyIsValid(networkId, accessKey)))\n\t\t\t\t\tthrow new UnauthorizedOperationException(\"Network \" + networkId + \" is not readable to this user.\");\n\n\t\t\treturn daoNew.getProvenance(networkId);\n\n\t\t} \n\t}\n\n /**************************************************************************\n * Updates network provenance.\n * @throws Exception\n *\n **************************************************************************/\n @PUT\n\t@Path(\"/{networkid}/provenance\")\n\t@Produces(\"application/json\")\n public void setProvenance(@PathParam(\"networkid\")final String networkIdStr, final ProvenanceEntity provenance)\n \t\tthrows Exception {\n \n\t\tUser user = getLoggedInUser();\n\n\t\tsetProvenance_aux(networkIdStr, provenance, user);\n }\n\n\n @Deprecated\n\tprotected static void setProvenance_aux(final String networkIdStr, final ProvenanceEntity provenance, User user)\n\t\t\tthrows Exception {\n\t\ttry (NetworkDAO daoNew = new NetworkDAO()){\n\t\t\t\n\t\t\tUUID networkId = UUID.fromString(networkIdStr);\n\n\t\t\tif ( !daoNew.isWriteable(networkId, user.getExternalId())) {\n\n\t\t throw new UnauthorizedOperationException(\"User doesn't have write permissions for this network.\");\n\t\t\t}\n\t\n\t\t\tif(daoNew.isReadOnly(networkId)) {\n\t\t\t\tdaoNew.close();\n\t\t\t\tthrow new NdexException (\"Can't update readonly network.\");\n\t\t\t} \n\n\n\t\t\tif (!daoNew.networkIsValid(networkId))\n\t\t\t\tthrow new InvalidNetworkException();\n\t\t\t\t\n\t/*\t\tif ( daoNew.networkIsLocked(networkId,6)) {\n\t\t\t\tdaoNew.close();\n\t\t\t\tthrow new NetworkConcurrentModificationException ();\n\t\t\t}\n\t\t\t\n\t\t\tdaoNew.lockNetwork(networkId); */\n\t\t\tdaoNew.setProvenance(networkId, provenance);\n\t\t\tdaoNew.commit();\n\t\t\t\n\t\t\t//Recreate the CX file \t\t\t\t\t\n\t\t//\tNetworkSummary fullSummary = daoNew.getNetworkSummaryById(networkId);\n\t\t//\tMetaDataCollection metadata = daoNew.getMetaDataCollection(networkId);\n\t//\t\tCXNetworkFileGenerator g = new CXNetworkFileGenerator(networkId, daoNew, new Provenance(provenance));\n\t//\t\tg.reCreateCXFile();\n\t//\t\tdaoNew.unlockNetwork(networkId);\n\t\t\t\n\t\t\t\n\t\t\treturn ; // provenance; // daoNew.getProvenance(networkUUID);\n\t\t} catch (Exception e) {\n\t\t\t//if (null != daoNew) daoNew.rollback();\n\t\t\tthrow e;\n\t\t} \n\t}\n\n\n\n /**************************************************************************\n * Sets network properties.\n * @throws Exception\n *\n **************************************************************************/\n @PUT\n\t@Path(\"/{networkid}/properties\")\n\t@Produces(\"application/json\")\n \n public int setNetworkProperties(\n \t\t@PathParam(\"networkid\")final String networkId,\n \t\tfinal List properties)\n \t\tthrows Exception {\n\n\t\tUser user = getLoggedInUser();\n\t\tUUID networkUUID = UUID.fromString(networkId);\n\n\t\ttry (NetworkDAO daoNew = new NetworkDAO()) {\n\t\t\t\n\t \t if(daoNew.isReadOnly(networkUUID)) {\n\t\t\t\tthrow new NdexException (\"Can't update readonly network.\");\t\t\t\t\n\t\t\t} \n\t\t\t\n\t\t\tif ( !daoNew.isWriteable(networkUUID, user.getExternalId())) {\n\t\t throw new UnauthorizedOperationException(\"User doesn't have write permissions for this network.\");\n\t\t\t} \n\t\t\t\n\t\t\tif ( daoNew.networkIsLocked(networkUUID,10)) {\n\t\t\t\tthrow new NetworkConcurrentModificationException ();\n\t\t\t} \n\t\t\t\n\t\t\tif ( !daoNew.networkIsValid(networkUUID))\n\t\t\t\tthrow new InvalidNetworkException();\n\n\t\t\tdaoNew.lockNetwork(networkUUID);\n\t\t\t\n\t\t\tint i = 0;\n\t\t\ttry {\n\t\t\t\ti = daoNew.setNetworkProperties(networkUUID, properties);\n\n\t\t\t\t// recreate files and update db\n\t\t\t\tupdateNetworkAttributesAspect(daoNew, networkUUID);\n\n\t\t\t} finally {\n\t\t\t\tdaoNew.unlockNetwork(networkUUID);\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\tNetworkIndexLevel idxLvl = daoNew.getIndexLevel(networkUUID);\n\t\t\tif ( idxLvl != NetworkIndexLevel.NONE) {\n\t\t\t\tdaoNew.setFlag(networkUUID, \"iscomplete\",false);\n\t\t\t\tdaoNew.commit();\n\t\t\t\tNdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkUUID,SolrIndexScope.global,false,null,idxLvl,false));\n\t\t\t} else {\n\t\t\t\tdaoNew.setFlag(networkUUID, \"iscomplete\", true);\n\t\t\t}\n\t\t\t\n\t\t\treturn i;\n\t\t} catch (Exception e) {\n\t\t\t//logger.severe(\"Error occurred when update network properties: \" + e.getMessage());\n\t\t\t//e.printStackTrace();\n\t\t\t//if (null != daoNew) daoNew.rollback();\n\t\t\tlogger.error(\"Updating properties of network {}. Exception caught:]{}\", networkId, e);\n\t\t\t\n\t\t\tthrow new NdexException(e.getMessage(), e);\n\t\t} \n }\n \n\t/*\n\t *\n\t * Operations returning Networks \n\t * \n\t */\n\n\t@PermitAll\n\t@GET\n\t@Path(\"/{networkid}/summary\")\n\t@Produces(\"application/json\")\n\t\n\tpublic NetworkSummary getNetworkSummary(\n\t\t\t@PathParam(\"networkid\") final String networkIdStr ,\n\t\t\t@QueryParam(\"accesskey\") String accessKey /*,\n\t\t\t@Context org.jboss.resteasy.spi.HttpResponse response*/)\n\n\t\t\tthrows IllegalArgumentException, NdexException, SQLException, JsonParseException, JsonMappingException, IOException {\n\t\t\n\t\ttry (NetworkDAO dao = new NetworkDAO()) {\n\t\t\tUUID userId = getLoggedInUserId();\n\t\t\tUUID networkId = UUID.fromString(networkIdStr);\n\t\t\tif ( dao.isReadable(networkId, userId) || dao.accessKeyIsValid(networkId, accessKey)) {\n\t\t\t\tNetworkSummary summary = dao.getNetworkSummaryById(networkId);\n\n\t\t\t\treturn summary;\n\t\t\t}\n\t\t\t\t\n\t\t\tthrow new UnauthorizedOperationException (\"Unauthorized access to network \" + networkId);\n\t\t} \n\t\t\t\n\t\t\t\n\t}\n\n\n\t@PermitAll\n\t@GET\n\t@Path(\"/{networkid}/aspect\")\n\t\n\tpublic Response getNetworkCXMetadataCollection(\t@PathParam(\"networkid\") final String networkId,\n\t\t\t@QueryParam(\"accesskey\") String accessKey)\n\t\t\tthrows Exception {\n\n \tlogger.info(\"[start: Getting CX metadata from network {}]\", networkId);\n\n \tUUID networkUUID = UUID.fromString(networkId);\n\n\t\ttry (NetworkDAO dao = new NetworkDAO() ) {\n\t\t\tif ( dao.isReadable(networkUUID, getLoggedInUserId()) || dao.accessKeyIsValid(networkUUID, accessKey)) {\n\t\t\t\tMetaDataCollection mdc = dao.getMetaDataCollection(networkUUID);\n\t\t \tlogger.info(\"[end: Return CX metadata from network {}]\", networkId);\n\t\t \tByteArrayOutputStream baos = new ByteArrayOutputStream();\n\t\t\t\tJsonWriter wtr = JsonWriter.createInstance(baos,true);\n\t\t\t\tmdc.toJson(wtr);\n\t\t\t\tString s = baos.toString();//\"java.nio.charset.StandardCharsets.UTF_8\");\n\t\t\t\treturn \tResponse.ok().type(MediaType.APPLICATION_JSON_TYPE).entity(s).build();\n//\t\t \treturn mdc;\n\t\t\t}\n\t\t\tthrow new UnauthorizedOperationException(\"User doesn't have access to this network.\");\n\t\t}\n\t} \n\t\n\t@PermitAll\n\t@GET\n\t@Path(\"/{networkid}/aspect/{aspectname}/metadata\")\n\t@Produces(\"application/json\")\n\t\n\tpublic MetaDataElement getNetworkCXMetadata(\t\n\t\t\t@PathParam(\"networkid\") final String networkId,\n\t\t\t@PathParam(\"aspectname\") final String aspectName\n\t\t\t)\n\t\t\tthrows Exception {\n\n \tlogger.info(\"[start: Getting {} metadata from network {}]\", aspectName, networkId);\n\n \tUUID networkUUID = UUID.fromString(networkId);\n\n\t\ttry (NetworkDAO dao = new NetworkDAO() ) {\n\t\t\tif ( dao.isReadable(networkUUID, getLoggedInUserId())) {\n\t\t\t\tMetaDataCollection mdc = dao.getMetaDataCollection(networkUUID);\n\t\t \tlogger.info(\"[end: Return CX metadata from network {}]\", networkId);\n\t\t \treturn mdc.getMetaDataElement(aspectName);\n\t\t\t}\n\t\t\tthrow new UnauthorizedOperationException(\"User doesn't have access to this network.\");\n\t\t}\n\t} \n\t\n\t\n\t@PermitAll\n\t@GET\n\t@Path(\"/{networkid}/aspect/{aspectname}\")\n\tpublic Response getAspectElements(\t@PathParam(\"networkid\") final String networkId,\n\t\t\t@PathParam(\"aspectname\") final String aspectName,\n\t\t\t@DefaultValue(\"-1\") @QueryParam(\"size\") int limit) throws SQLException, NdexException\n\t\t {\n\n \tlogger.info(\"[start: Getting one aspect in network {}]\", networkId);\n \tUUID networkUUID = UUID.fromString(networkId);\n \t\n \ttry (NetworkDAO dao = new NetworkDAO()) {\n \t\tif ( !dao.isReadable(networkUUID, getLoggedInUserId())) {\n \t\t\tthrow new UnauthorizedOperationException(\"User doesn't have access to this network.\");\n \t\t}\n \t\t\n \t\tFile cx1AspectDir = new File (Configuration.getInstance().getNdexRoot() + \"/data/\" + networkId \n \t\t\t\t+ \"/\" + CXNetworkLoader.CX1AspectDir);\n \t\tboolean hasCX1AspDir = cx1AspectDir.exists();\n \t\t\n\t\t\tFileInputStream in = null;\n\t\t\ttry {\n\t\t\t\tif ( hasCX1AspDir) {\n\t\t\t\t in = new FileInputStream(cx1AspectDir + \"/\" + aspectName);\n\t\t\t\t if ( limit <= 0) {\n\t\t\t\t\t\treturn \tResponse.ok().type(MediaType.APPLICATION_JSON_TYPE).entity(in).build();\n\t\t\t \t} \n\t\t\t\t \n\t\t\t\t PipedInputStream pin = new PipedInputStream();\n\t\t\t\t\tPipedOutputStream out;\n\t\t\t\t\t\t\n\t\t\t\t\ttry {\n\t\t\t\t\t\t\tout = new PipedOutputStream(pin);\n\t\t\t\t\t} catch (IOException e) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tpin.close();\n\t\t\t\t\t\t\tin.close();\n\t\t\t\t\t\t} catch (IOException e1) {\n\t\t\t\t\t\t\te1.printStackTrace();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthrow new NdexException(\"IOExcetion when creating the piped output stream: \"+ e.getMessage());\n\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\tnew CXAspectElementsWriterThread(out,in, /*aspectName,*/ limit).start();\n\t\t\t\t//\tlogger.info(\"[end: Return get one aspect in network {}]\", networkId);\n\t\t\t\t\treturn \tResponse.ok().type(MediaType.APPLICATION_JSON_TYPE).entity(pin).build();\n\t\t\t\t} \n\t\t\t\t\n\t\t\t} catch (FileNotFoundException e) {\n\t\t\t\t\tthrow new ObjectNotFoundException(\"Aspect \"+ aspectName + \" not found in this network: \" + e.getMessage());\n\t\t\t}\n\t \t\n\t\t\t\n\t\t\t//get aspect from cx2 aspects\n\t\t\tPipedInputStream pin = new PipedInputStream();\n\t\t\tPipedOutputStream out;\n\t\t\t\t\n\t\t\ttry {\n\t\t\t\t\tout = new PipedOutputStream(pin);\n\t\t\t} catch (IOException e) {\n\t\t\t\ttry {\n\t\t\t\t\tpin.close();\n\t\t\t\t} catch (IOException e1) {\n\t\t\t\t\te1.printStackTrace();\n\t\t\t\t}\n\t\t\t\tthrow new NdexException(\"IOExcetion when creating the piped output stream: \"+ e.getMessage());\n\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\tnew CXAspectElementWriter2Thread(out,networkId, aspectName, limit, accLogger).start();\n\t\t//\tlogger.info(\"[end: Return get one aspect in network {}]\", networkId);\n\t\t\treturn \tResponse.ok().type(MediaType.APPLICATION_JSON_TYPE).entity(pin).build();\n\t\t\n\t\t\n \t}\n\n\t} \n\t\n\t\n\t@PermitAll\n\t@GET\n\t@Path(\"/{networkid}\")\n\n\tpublic Response getCompleteNetworkAsCX(\t@PathParam(\"networkid\") final String networkId,\n\t\t\t@QueryParam(\"download\") boolean isDownload,\n\t\t\t@QueryParam(\"accesskey\") String accessKey,\n\t\t\t@QueryParam(\"id_token\") String id_token,\n\t\t\t@QueryParam(\"auth_token\") String auth_token)\n\t\t\tthrows Exception {\n \t\n \tString title = null;\n \ttry (NetworkDAO dao = new NetworkDAO()) {\n \t\tUUID networkUUID = UUID.fromString(networkId);\n \t\tUUID userId = getLoggedInUserId();\n \t\tif ( userId == null ) {\n \t\t\tif ( auth_token != null) {\n \t\t\t\tuserId = getUserIdFromBasicAuthString(auth_token);\n \t\t\t} else if ( id_token !=null) {\n \t\t\t\tif ( getGoogleAuthenticator() == null)\n \t\t\t\t\tthrow new UnauthorizedOperationException(\"Google OAuth is not enabled on this server.\");\n \t\t\t\tuserId = getGoogleAuthenticator().getUserUUIDByIdToken(id_token);\n \t\t\t}\n \t\t}\n \t\tif ( ! dao.isReadable(networkUUID, userId) && (!dao.accessKeyIsValid(networkUUID, accessKey))) \n throw new UnauthorizedOperationException(\"User doesn't have read access to this network.\");\n \t\t\n \t\ttitle = dao.getNetworkName(networkUUID);\n \t}\n \n\t\tString cxFilePath = Configuration.getInstance().getNdexRoot() + \"/data/\" + networkId + \"/\" + cx1NetworkFileName;\n\n \ttry {\n\t\t\tFileInputStream in = new FileInputStream(cxFilePath) ;\n\t\t\n\t\t//\tsetZipFlag();\n\t\t\tlogger.info(\"[end: Return network {}]\", networkId);\n\t\t\tResponseBuilder r = Response.ok();\n\t\t\tif (isDownload) {\n\t\t\t\tif (title == null || title.length() < 1) {\n\t\t\t\t\ttitle = networkId;\n\t\t\t\t}\n\t\t\t\ttitle.replace('\"', '_');\n\t\t\t\tr.header(\"Content-Disposition\", \"attachment; filename=\\\"\" + title + \".cx\\\"\");\n\t\t\t\tr.header(\"Access-Control-Expose-Headers\", \"Content-Disposition\");\n\t\t\t}\n\t\t\treturn \tr.type(isDownload ? MediaType.APPLICATION_OCTET_STREAM_TYPE : MediaType.APPLICATION_JSON_TYPE)\n\t\t\t\t\t.entity(in).build();\n\t\t} catch (IOException e) {\n\t\t\tlogger.error(\"[end: Ndex server can't find file: {}]\", e.getMessage());\n\t\t\tthrow new NdexException (\"Ndex server can't find file: \" + e.getMessage());\n\t\t}\n\t\t\n\t} \n\n\n\t\n\t@PermitAll\n\t@GET\n\t@Path(\"/{networkid}/sample\")\n\n\tpublic Response getSampleNetworkAsCX(\t@PathParam(\"networkid\") final String networkIdStr ,\n\t\t\t@QueryParam(\"accesskey\") String accessKey)\n\t\t\tthrows IllegalArgumentException, NdexException, SQLException {\n \t\n \tUUID networkId = UUID.fromString(networkIdStr);\n \ttry (NetworkDAO dao = new NetworkDAO()) {\n \t\tif ( ! dao.isReadable(networkId, getLoggedInUserId()) && (!dao.accessKeyIsValid(networkId, accessKey)))\n throw new UnauthorizedOperationException(\"User doesn't have read access to this network.\");\n\n \t}\n \t\n\t\tString cxFilePath = Configuration.getInstance().getNdexRoot() + \"/data/\" + networkId + \"/sample.cx\";\n\t\t\n\t\ttry {\n\t\t\tFileInputStream in = new FileInputStream(cxFilePath) ;\n\t\t\n\t\t\t//\tsetZipFlag();\n\t\t\treturn \tResponse.ok().type(MediaType.APPLICATION_JSON_TYPE).entity(in).build();\n\t\t} catch ( FileNotFoundException e) {\n\t\t\t\tthrow new ObjectNotFoundException(\"Sample network of \" + networkId + \" not found. Error: \" + e.getMessage());\n\t\t} \n\t\t\n\t} \n\t\n\t@GET\n\t@Path(\"/{networkid}/accesskey\")\n\t@Produces(\"application/json\")\n\tpublic Map getNetworkAccessKey(@PathParam(\"networkid\") final String networkIdStr)\n\t\t\tthrows IllegalArgumentException, NdexException, SQLException {\n \t\n\t\tUUID networkId = UUID.fromString(networkIdStr);\n \ttry (NetworkDAO dao = new NetworkDAO()) {\n \t\tif ( ! dao.isAdmin(networkId, getLoggedInUserId()))\n throw new UnauthorizedOperationException(\"User is not admin of this network.\");\n\n \t\tString key = dao.getNetworkAccessKey(networkId);\n \t\tif (key == null || key.length()==0)\n \t\t\treturn null;\n \t\tMap result = new HashMap<>(1);\n \t\tresult.put(\"accessKey\", key);\n \t\treturn result;\n \t}\n\t} \n\t\t\n\t@PUT\n\t@Path(\"/{networkid}/accesskey\")\n\t@Produces(\"application/json\")\n\tpublic Map disableEnableNetworkAccessKey(@PathParam(\"networkid\") final String networkIdStr,\n\t\t\t@QueryParam(\"action\") String action)\n\t\t\tthrows IllegalArgumentException, NdexException, SQLException {\n \t\n\t\tUUID networkId = UUID.fromString(networkIdStr);\n\t\tif ( ! action.equalsIgnoreCase(\"disable\") && ! action.equalsIgnoreCase(\"enable\"))\n\t\t\tthrow new NdexException(\"Value of 'action' paramter can only be 'disable' or 'enable'\");\n\t\t\n \ttry (NetworkDAO dao = new NetworkDAO()) {\n \t\tif ( ! dao.isAdmin(networkId, getLoggedInUserId()))\n throw new UnauthorizedOperationException(\"User is not admin of this network.\");\n\n \t\tString key = null;\n \t\tif ( action.equalsIgnoreCase(\"disable\"))\n \t\t\tdao.disableNetworkAccessKey(networkId);\n \t\telse \n \t\t\tkey = dao.enableNetworkAccessKey(networkId);\n \t\tdao.commit();\n \t\t\n \t\tif (key == null || key.length()==0)\n \t\t\treturn null;\n \t\tMap result = new HashMap<>(1);\n \t\tresult.put(\"accessKey\", key);\n \t\treturn result;\n \t}\n\t} \n\t\n\t\n\t@PUT\n\t@Path(\"/{networkid}/sample\")\n\t\n\tpublic void setSampleNetwork(\t@PathParam(\"networkid\") final String networkId,\n\t\t\tString CXString)\n\t\t\tthrows IllegalArgumentException, NdexException, SQLException, InterruptedException {\n \t\n\t\tUUID networkUUID = UUID.fromString(networkId);\n\t\ttry (NetworkDAO dao = new NetworkDAO()) {\n\t\t\tif (!dao.isAdmin(networkUUID, getLoggedInUserId()))\n\t\t\t\tthrow new UnauthorizedOperationException(\"User is not admin of this network.\");\n\n\t\t\tif (dao.networkIsLocked(networkUUID, 10))\n\t\t\t\tthrow new NetworkConcurrentModificationException();\n\n\t\t\tif (!dao.networkIsValid(networkUUID))\n\t\t\t\tthrow new InvalidNetworkException();\n\n\t\t\tString cxFilePath = Configuration.getInstance().getNdexRoot() + \"/data/\" + networkId + \"/sample.cx\";\n\n\t\t\ttry (FileWriter w = new FileWriter(cxFilePath)) {\n\t\t\t\tw.write(CXString);\n\t\t\t\tdao.setFlag(networkUUID, \"has_sample\", true);\n\t\t\t\tdao.commit();\n\t\t\t} catch (IOException e) {\n\t\t\t\tthrow new NdexException(\"Failed to write sample network of \" + networkId + \": \" + e.getMessage(), e);\n\t\t\t}\n\t\t}\n\t} \n\t\n\t\n\n\tprivate class CXAspectElementsWriterThread extends Thread {\n\t\tprivate OutputStream o;\n\t//\tprivate String networkId;\n\t\tprivate FileInputStream in;\n\t//\tprivate String aspect;\n\t\tprivate int limit;\n\t\tpublic CXAspectElementsWriterThread (OutputStream out, FileInputStream inputStream, /*String aspectName,*/ int limit) {\n\t\t\to = out;\n\t\t//\tthis.networkId = networkId;\n\t\t//\taspect = aspectName;\n\t\t\tthis.limit = limit;\n\t\t\tin = inputStream;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic void run() {\n\n\t\t\ttry {\n\t\t\t\tOpaqueAspectIterator asi = new OpaqueAspectIterator(in);\n\t\t\t\ttry (CXAspectWriter wtr = new CXAspectWriter (o)) {\n\t\t\t\t\tfor ( int i = 0 ; i < limit && asi.hasNext() ; i++) {\n\t\t\t\t\t\twtr.writeCXElement(asi.next());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (IOException e) {\n\t\t\t\t\tlogger.error(\"IOException in CXAspectElementWriterThread: \" + e.getMessage());\n\t\t\t} catch (Exception e1) {\n\t\t\t\tlogger.error(\"Ndex exception: \" + e1.getMessage());\n\t\t\t} finally {\n\t\t\t\ttry {\n\t\t\t\t\to.flush();\n\t\t\t\t\to.close();\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\tlogger.error(\"Failed to close outputstream in CXElementWriterWriterThread\");\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t} \n\t\t}\n\t\t\n\t}\n\n\n\n\t/**************************************************************************\n\t * Retrieves array of user membership objects\n\t *\n\t * @param networkId\n\t * The network ID.\n\t * @throws IllegalArgumentException\n\t * Bad input.\n\t * @throws ObjectNotFoundException\n\t * The group doesn't exist.\n\t * @throws NdexException\n\t * Failed to query the database.\n\t * @throws SQLException \n\t **************************************************************************/\n\n\t@GET\n\t@Path(\"/{networkid}/permission\")\n\t@Produces(\"application/json\")\n\n\tpublic Map getNetworkUserMemberships(\n\t\t\t@PathParam(\"networkid\") final String networkId,\n\t\t @QueryParam(\"type\") String sourceType,\n\t\t\t@QueryParam(\"permission\") final String permissions ,\n\t\t\t@DefaultValue(\"0\") @QueryParam(\"start\") int skipBlocks,\n\t\t\t@DefaultValue(\"100\") @QueryParam(\"size\") int blockSize) throws NdexException, SQLException {\n\t\t\n\t\tPermissions permission = null;\n\t\tif ( permissions != null ){\n\t\t\tpermission = Permissions.valueOf(permissions.toUpperCase());\n\t\t} \n\t\t\n\t\tUUID networkUUID = UUID.fromString(networkId);\n\t\t\n\t\t\n\t\tboolean returnUsers = true;\n\t\tif ( sourceType != null ) {\n\t\t\tif ( sourceType.toLowerCase().equals(\"group\")) \n\t\t\t\treturnUsers = false;\n\t\t\telse if ( !sourceType.toLowerCase().equals(\"user\"))\n\t\t\t\tthrow new NdexException(\"Invalid parameter 'type' \" + sourceType + \" received, it can only be 'user' or 'group'.\");\n\t\t} else \n\t\t\tthrow new NdexException(\"Parameter 'type' is required in this function.\");\n\t\t\n\t\ttry (NetworkDAO networkDao = new NetworkDAO()) {\n\t\t\tif ( !networkDao.isAdmin(networkUUID, getLoggedInUserId()) ) \n\t\t\t\tthrow new UnauthorizedOperationException(\"Authenticate user is not the admin of this network.\");\n\t\t\t\n\t\t\tMap result = returnUsers?\n\t\t\t\t\tnetworkDao.getNetworkUserPermissions(networkUUID, permission, skipBlocks, blockSize):\n\t\t\t\t\tnetworkDao.getNetworkGroupPermissions(networkUUID,permission,skipBlocks,blockSize);\n\t\t\t\t\t\n\t\t\treturn result;\n\t\t} \n\t}\n\n\t\n\t@DELETE\n\t@Path(\"/{networkid}/permission\")\n\t@Produces(\"application/json\")\n\n\tpublic int deleteNetworkPermission(\n\t\t\t@PathParam(\"networkid\") final String networkIdStr,\n\t\t\t@QueryParam(\"userid\") String userIdStr,\n\t\t\t@QueryParam(\"groupid\") String groupIdStr\t\t\n\t\t\t)\n\t\t\tthrows IllegalArgumentException, NdexException, IOException, SQLException {\n\t\t\t\t\n\t\tUUID networkId = UUID.fromString(networkIdStr);\n\n\t\tUUID userId = null;\n\t\tif ( userIdStr != null)\n\t\t\tuserId = UUID.fromString(userIdStr);\n\t\tUUID groupId = null;\n\t\tif ( groupIdStr != null)\n\t\t\tgroupId = UUID.fromString(groupIdStr);\n\t\t\n\t\tif ( userId == null && groupId == null)\n\t\t\tthrow new NdexException (\"Either userid or groupid parameter need to be set for this function.\");\n\t\tif ( userId !=null && groupId != null)\n\t\t\tthrow new NdexException (\"userid and gorupid can't both be set for this function.\");\n\t\t\n\t\t\n\t\ttry (NetworkDAO networkDao = new NetworkDAO()){ \n\t\t//\tUser user = getLoggedInUser();\n\t\t//\tnetworkDao.checkPermissionOperationCondition(networkId, user.getExternalId());\n\t\t\t\n\t\t\tif (!networkDao.isAdmin(networkId,getLoggedInUserId())) {\n\t\t\t\tif ( userId != null && !userId.equals(getLoggedInUserId())) {\n\t\t\t\t\tthrow new UnauthorizedOperationException(\"Unable to delete network permisison: user need to be admin of this network or grantee of this permission.\");\n\t\t\t\t}\n\t\t\t\tif ( groupId!=null ) {\t\n\t\t\t\t\tthrow new UnauthorizedOperationException(\"Unable to delete network permission: user is not an admin of this network.\");\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif( !networkDao.networkIsValid(networkId))\n\t\t\t\tthrow new InvalidNetworkException();\n\t\t\n\t\t\tint count;\n\t\t\tif ( userId !=null)\n\t\t\t\tcount = networkDao.revokeUserPrivilege(networkId, userId);\n\t\t\telse \n\t\t\t\tcount = networkDao.revokeGroupPrivilege(networkId, groupId);\n\n\t\t\t// update the solr Index\n\t\t\tNetworkIndexLevel lvl = networkDao.getIndexLevel(networkId);\n\t\t\tif ( lvl != NetworkIndexLevel.NONE) {\n\t\t\t\tnetworkDao.setFlag(networkId, \"iscomplete\", false); \n\t\t\t\tnetworkDao.commit();\n\t\t\t\tNdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkId,SolrIndexScope.global,false,null,lvl, false));\n\t\t\t}\n return count;\n\t\t} \n\t}\n\t\n\t/*\n\t *\n\t * Operations on Network permissions\n\t * \n\t */\n\n\n\t@PUT\n\t@Path(\"/{networkid}/permission\")\n\t@Produces(\"application/json\")\n\tpublic int updateNetworkPermission(\n\t\t\t@PathParam(\"networkid\") final String networkIdStr,\n\t\t\t@QueryParam(\"userid\") String userIdStr,\n\t\t\t@QueryParam(\"groupid\") String groupIdStr,\t\t\t\n\t\t\t@QueryParam(\"permission\") final String permissions \n\t\t\t)\n\t\t\tthrows IllegalArgumentException, NdexException, IOException, SQLException {\n\n\t\tlogger.info(\"[start: Updating membership for network {}]\", networkIdStr);\n\t\tUUID networkId = UUID.fromString(networkIdStr);\n\t\t\n\t\tUUID userId = null;\n\t\tif ( userIdStr != null)\n\t\t\tuserId = UUID.fromString(userIdStr);\n\t\tUUID groupId = null;\n\t\tif ( groupIdStr != null)\n\t\t\tgroupId = UUID.fromString(groupIdStr);\n\t\t\n\t\tif ( userId == null && groupId == null)\n\t\t\tthrow new NdexException (\"Either userid or groupid parameter need to be set for this function.\");\n\t\tif ( userId !=null && groupId != null)\n\t\t\tthrow new NdexException (\"userid and gorupid can't both be set for this function.\");\n\t\t\n\t\tif ( permissions == null)\n\t\t\tthrow new NdexException (\"permission parameter is required in this function.\");\n\t\tPermissions p = Permissions.valueOf(permissions.toUpperCase());\n\t\t\n\t\ttry (NetworkDAO networkDao = new NetworkDAO()){\n\t\t\t\n\t\t\tUser user = getLoggedInUser();\n\t\t\t\n\t\t\tif (!networkDao.isAdmin(networkId,user.getExternalId())) {\n\t\t\t\tthrow new UnauthorizedOperationException(\"Unable to update network permission: user is not an admin of this network.\");\n\t\t\t}\n\t\t\t\n\t\t\tif ( !networkDao.networkIsValid(networkId))\n \t\t\tthrow new InvalidNetworkException();\n\t\t\t\n\t\t\t\n\t\t\tint count;\n\t\t\tif ( userId!=null) {\n\t\t\t\tcount = networkDao.grantPrivilegeToUser(networkId, userId, p);\n\t\t\t} else \n\t\t\t\tcount = networkDao.grantPrivilegeToGroup(networkId, groupId, p);\n\t\t\t//networkDao.commit();\n\t\t\t\n\t\t\t// update the solr Index\n\t\t\tNetworkIndexLevel lvl = networkDao.getIndexLevel(networkId);\n\t\t\tif ( lvl != NetworkIndexLevel.NONE) {\n\t\t\t\tnetworkDao.setFlag(networkId, \"iscomplete\", false);\n\t\t\t\tnetworkDao.commit();\n\t\t\t\tNdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkId,SolrIndexScope.global,false,null,lvl, false));\n\t\t\t}\n\t\t\t\n\t\t\tlogger.info(\"[end: Updated permission for network {}]\", networkId);\n\t return count;\n\t\t} \n\t}\t\n\n\t\n\t@PUT\n\t@Path(\"/{networkid}/reference\")\n\t@Produces(\"application/json\")\n\tpublic void updateReferenceOnPreCertifiedNetwork(@PathParam(\"networkid\") final String networkId,\n\t\t\tMap reference) throws SQLException, NdexException, SolrServerException, IOException {\n\n\t\tUUID networkUUID = UUID.fromString(networkId);\n\t\tUUID userId = getLoggedInUser().getExternalId();\n\t\t\n\t\tif ( reference.get(\"reference\") == null) {\n\t\t\tthrow new BadRequestException(\"Field reference is missing in the object.\");\n\t\t}\n\n\t\ttry (NetworkDAO networkDao = new NetworkDAO()){\n\t\t\tif(networkDao.isAdmin(networkUUID, userId) ) {\n\n\t\t\t\tif ( networkDao.hasDOI(networkUUID) && (!networkDao.isCertified(networkUUID)) ) {\n\t\t\t\t\tList props = networkDao.getNetworkSummaryById(networkUUID).getProperties();\n\t\t\t\t\tboolean updated= false;\n\t\t\t\t\tfor ( NdexPropertyValuePair p : props ) {\n\t\t\t\t\t\tif ( p.getPredicateString().equals(\"reference\")) {\n\t\t\t\t\t\t\tp.setValue(reference.get(\"reference\"));\n\t\t\t\t\t\t\tupdated=true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif ( !updated) {\n\t\t\t\t\t\tprops.add(new NdexPropertyValuePair(\"reference\", reference.get(\"reference\")));\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tnetworkDao.lockNetwork(networkUUID);\n\n\t\t\t\t\tnetworkDao.updateNetworkProperties(networkUUID,props);\n\t\t\t\t\t\n\t\t\t\t\t// recreate files and update db\n\t\t\t\t\tupdateNetworkAttributesAspect(networkDao, networkUUID);\n\n\t\t\t\t\tnetworkDao.unlockNetwork(networkUUID);\n\t\t\t\t\t\n\t\t\t\t\tnetworkDao.updateNetworkVisibility(networkUUID, VisibilityType.PUBLIC, true);\n\t\t\t\t\t//networkDao.setFlag(networkUUID, \"solr_indexed\", true);\n\t\t\t\t\tnetworkDao.setIndexLevel(networkUUID, NetworkIndexLevel.ALL);\n\t\t\t\t\tnetworkDao.setFlag(networkUUID, \"certified\", true);\n\t\t\t\t\t\n\t\t\t\t\tnetworkDao.setFlag(networkUUID, \"iscomplete\", false);\n\t\t\t\t\tnetworkDao.commit();\n\t\t\t\t\tNdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkUUID,SolrIndexScope.global,false,null,NetworkIndexLevel.ALL, false));\n\t\t\t\t\t\n\t\t\t\t} else {\n\t\t\t\t\tif ( networkDao.isCertified(networkUUID))\n\t\t\t\t\t\tthrow new ForbiddenOperationException(\"This network has already been certified, updating reference is not allowed.\");\n\t\t\t\t\t\n\t\t\t\t\tthrow new ForbiddenOperationException(\"This network doesn't have a DOI or a pending DOI request.\");\n\t\t\t\t}\n\t\t\t}\n\t\t\n\t\t}\t\n\t\t\n\t}\n\t\n\t@PUT\n\t@Path(\"/{networkid}/profile\")\n\t@Produces(\"application/json\")\n\n\tpublic void updateNetworkProfile(\n\t\t\t@PathParam(\"networkid\") final String networkId,\n\t\t\tfinal NetworkSummary partialSummary\n\t\t\t)\n throws NdexException, SQLException , IOException, IllegalArgumentException \n {\n\t\t\n\t\ttry (NetworkDAO networkDao = new NetworkDAO()){\n\n\t\t\tUser user = getLoggedInUser();\n\t\t\tUUID networkUUID = UUID.fromString(networkId);\n\t\n\t \t if(networkDao.isReadOnly(networkUUID)) {\n\t\t\t\tthrow new NdexException (\"Can't update readonly network.\");\t\t\t\t\n\t\t\t} \n\t\t\t\n\t\t\tif ( !networkDao.isWriteable(networkUUID, user.getExternalId())) {\n\t\t throw new UnauthorizedOperationException(\"User doesn't have write permissions for this network.\");\n\t\t\t} \n\t\t\t\n\t\t\tMap newValues = new HashMap<> ();\n//\t List entityProperties = new ArrayList<>();\n\n\t\t\tif ( partialSummary.getName() != null) {\n\t\t\t\tnewValues.put(NdexClasses.Network_P_name, partialSummary.getName());\n//\t\t\t entityProperties.add( new SimplePropertyValuePair(\"dc:title\", partialSummary.getName()) );\n\t\t\t}\n\t\t\t\t\t\n\t\t\tif ( partialSummary.getDescription() != null) {\n\t\t\t\t\tnewValues.put( NdexClasses.Network_P_desc, partialSummary.getDescription());\n//\t\t entityProperties.add( new SimplePropertyValuePair(\"description\", partialSummary.getDescription()) );\n\t\t\t}\n\t\t\t\t\n\t\t\tif ( partialSummary.getVersion()!=null ) {\n\t\t\t\t\tnewValues.put( NdexClasses.Network_P_version, partialSummary.getVersion());\n//\t\t entityProperties.add( new SimplePropertyValuePair(\"version\", partialSummary.getVersion()) );\n\t\t\t}\n\n\t\t\tif ( newValues.size() > 0 ) { \n\t\t\t\t\n\t\t\t\tif (!networkDao.networkIsValid(networkUUID))\n\t\t\t\t\tthrow new InvalidNetworkException();\n\n\t\t\t\ttry {\n\t\t\t\t\tif ( networkDao.networkIsLocked(networkUUID,10)) {\n\t\t\t\t\t\tthrow new NetworkConcurrentModificationException ();\n\t\t\t\t\t}\n\t\t\t\t} catch (InterruptedException e2) {\n\t\t\t\t\te2.printStackTrace();\n\t\t\t\t\tthrow new NdexException(\"Failed to check network lock: \" + e2.getMessage());\n\t\t\t\t} \n\t\t\t\t\n\t\t\t\t\n\t\t\t\ttry {\n\t\t\t\t\tnetworkDao.lockNetwork(networkUUID);\n\t\t\t\t\n\t\t\t\t\tnetworkDao.updateNetworkProfile(networkUUID, newValues);\n\t\t\t\t\t\n\t\t\t\t\t// recreate files and update db\n\t\t\t\t\tupdateNetworkAttributesAspect(networkDao, networkUUID);\n\n\t\t\t\t\tnetworkDao.unlockNetwork(networkUUID);\n\t\t\t\t\t\n\t\t\t\t\t// update the solr Index \n\t\t\t\t\tNetworkIndexLevel lvl = networkDao.getIndexLevel(networkUUID);\n\t\t\t\t\tif ( lvl != NetworkIndexLevel.NONE) {\n\t\t\t\t\t networkDao.setFlag(networkUUID, \"iscomplete\", false);\n\t\t\t\t\t networkDao.commit();\n\t\t\t\t\t NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkUUID,SolrIndexScope.global,false,null,lvl, false));\n\t\t\t\t\t} else {\n\t\t\t\t\t\t networkDao.setFlag(networkUUID, \"iscomplete\", true);\n\t\t\t\t\t\t networkDao.commit();\n\t\t\t\t\t}\n\t\t\t\t} catch ( SQLException | IOException | IllegalArgumentException |NdexException e ) {\n\t\t\t\t\tnetworkDao.rollback();\n\t\t\t\t\ttry {\n\t\t\t\t\t\tnetworkDao.unlockNetwork(networkUUID);\n\t\t\t\t\t} catch (SQLException e1) {\n\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\te1.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t\tthrow e;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t} \n\t}\n\n\t\n\t/**\n\t * \n\t * @param pathPrefix path of the directory that has the CxAttributeDeclaration aspect file. \n\t * It should end with \"/\"\n\t * @return the declaration object. null if network has no attributes declared.\n\t * @throws JsonParseException\n\t * @throws JsonMappingException\n\t * @throws IOException\n\t */\n\tprotected static CxAttributeDeclaration getAttrDeclarations(String pathPrefix) throws JsonParseException, JsonMappingException, IOException {\t\t\t\n\t\tFile attrDeclF = new File ( pathPrefix + CxAttributeDeclaration.ASPECT_NAME);\n\t\tCxAttributeDeclaration[] declarations = null;\n\t\tif ( attrDeclF.exists() ) {\n\t\t\tObjectMapper om = new ObjectMapper();\n\t\t\tdeclarations = om.readValue(attrDeclF, CxAttributeDeclaration[].class);\n\t\t}\n\n\t\tif ( declarations != null)\n\t\t\treturn declarations[0];\n\t\t\n\t\treturn null;\n\t}\n\t\n\t// update the networkAttributes aspect file and also update the metadata in the db.\n\tprotected static void updateNetworkAttributesAspect(NetworkDAO networkDao, UUID networkUUID) throws JsonParseException, JsonMappingException, SQLException, IOException, NdexException {\n\t\tNetworkSummary fullSummary = networkDao.getNetworkSummaryById(networkUUID);\n\t\tString fileStoreDir = Configuration.getInstance().getNdexRoot() + \"/data/\" + networkUUID.toString() + \"/\";\n\t\tString aspectFilePath = fileStoreDir + CXNetworkLoader.CX1AspectDir + \"/\" + NetworkAttributesElement.ASPECT_NAME;\n\t\tString cx2AspectDirPath = fileStoreDir + CX2NetworkLoader.cx2AspectDirName + \"/\";\n\t\t\n\t\t//update the networkAttributes aspect in cx and cx2 \n\t\tList attrs = getNetworkAttributeAspectsFromSummary(fullSummary);\n\t\t\n\t\tCxAttributeDeclaration networkAttrDecl = null;\n\t\tif ( attrs.size() > 0 ) {\t\t\t\t\t\n\t\t\tAspectAttributeStat attributeStats = new AspectAttributeStat();\n\t\t\tCxNetworkAttribute cx2NetAttr = new CxNetworkAttribute();\n\n\t\t\t// write cx network attribute aspect file.\n\t\t\ttry (CXAspectWriter writer = new CXAspectWriter(aspectFilePath) ) {\n\t\t\t\tfor ( NetworkAttributesElement e : attrs) {\n\t\t\t\t\twriter.writeCXElement(e);\t\n\t\t\t\t\twriter.flush();\n\n\t\t\t\t\tattributeStats.addNetworkAttribute(e);\n\t\t\t\t\t\n\t\t\t\t\tObject attrValue = CXToCX2Converter.convertAttributeValue(e);\n\t\t\t\t\tObject oldV = cx2NetAttr.getAttributes().put(e.getName(), attrValue);\n\t\t\t\t\tif ( oldV !=null)\n\t\t\t\t\t\tthrow new NdexException(\"Duplicated network attribute name found: \" + e.getName());\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t// write cx2 network attribute aspect file\n\t\t\tnetworkAttrDecl = attributeStats.createCxDeclaration();\n\t\t\t\n\t\t\ttry (CX2AspectWriter aspWtr = new CX2AspectWriter<>(cx2AspectDirPath + CxNetworkAttribute.ASPECT_NAME)) {\n\t\t\t\taspWtr.writeCXElement(cx2NetAttr);\n\t\t\t}\n\t\t\t\n\t\t} else { // remove the aspect file if it exists\n\t\t\tFile f = new File ( aspectFilePath);\n\t\t\tif ( f.exists())\n\t\t\t\tf.delete();\n\t\t\tf = new File(cx2AspectDirPath + CxNetworkAttribute.ASPECT_NAME);\n\t\t\tif ( f.exists())\n\t\t\t\tf.delete();\n\t\t}\n\t\t\n\t\t\t\t\n\t\t//update cx and cx2 metadata for networkAttributes\n\t\tMetaDataCollection metadata = networkDao.getMetaDataCollection(networkUUID);\n\t\tList cx2metadata = networkDao.getCxMetaDataList(networkUUID);\n\t\tif ( attrs.size() == 0 ) {\n\t\t\tmetadata.remove(NetworkAttributesElement.ASPECT_NAME);\n\t\t\tcx2metadata.removeIf( n -> n.getName().equals(CxNetworkAttribute.ASPECT_NAME));\n\t\t} else {\n\t\t\tMetaDataElement elmt = metadata.getMetaDataElement(NetworkAttributesElement.ASPECT_NAME);\n\t\t\tif ( elmt == null) {\n\t\t\t\telmt = new MetaDataElement(NetworkAttributesElement.ASPECT_NAME, \"1.0\");\n\t\t\t}\n\t\t\telmt.setElementCount(Long.valueOf(attrs.size()));\n\t\t\t\n\t\t\tif ( ! cx2metadata.stream().anyMatch(\n\t\t\t\t\t(CxMetadata n) -> n.getName().equals(CxNetworkAttribute.ASPECT_NAME) )) {\n\t\t\t\n\t\t\t\tCxMetadata m = new CxMetadata(CxNetworkAttribute.ASPECT_NAME, 1);\n\t\t\t\tcx2metadata.add(m);\n\t\t\t}\n\t\t}\n\t\tnetworkDao.updateMetadataColleciton(networkUUID, metadata);\n\n\t\t\n\t\t// update attribute declaration aspect and cx2 metadata\n\t\tCxAttributeDeclaration decls = getAttrDeclarations(cx2AspectDirPath);\n\t\tif ( decls == null) {\n\t\t\tif ( networkAttrDecl != null ) { // has new attributes\n\t\t\t\tdecls = new CxAttributeDeclaration();\n\t\t\t\tdecls.add(CxNetworkAttribute.ASPECT_NAME,\n\t\t\t\t\t\tnetworkAttrDecl.getAttributesInAspect(CxNetworkAttribute.ASPECT_NAME));\n\t\t\t\tcx2metadata.add(new CxMetadata(CxAttributeDeclaration.ASPECT_NAME, 1));\n\t\t\t} \n\t\t} else {\n\t\t\tif ( networkAttrDecl != null) {\n\t\t\t\tdecls.getDeclarations().put(CxNetworkAttribute.ASPECT_NAME, \n\t\t\t\t\t\tnetworkAttrDecl.getAttributesInAspect(CxNetworkAttribute.ASPECT_NAME));\n\t\t\t} else { \n\t\t\t\tdecls.removeAspectDeclaration(CxNetworkAttribute.ASPECT_NAME);\n\t\t\t cx2metadata.removeIf((CxMetadata m) -> m.getName().equals(CxAttributeDeclaration.ASPECT_NAME));\n\t\t\t} \n\t\t}\n\n\t\tnetworkDao.setCxMetadata(networkUUID, cx2metadata);\n\t\ttry (CX2AspectWriter aspWtr = new \n\t\t\t\tCX2AspectWriter<>(cx2AspectDirPath + CxAttributeDeclaration.ASPECT_NAME)) {\n\t\t\taspWtr.writeCXElement(decls);\n\t\t}\n\t\t\n\t\t//Recreate the CX file \t\t\t\t\t\n\t\tCXNetworkFileGenerator g = new CXNetworkFileGenerator(networkUUID, metadata);\n\t\tg.reCreateCXFile();\n \n\t\t//Recreate cx2 file\n\t\tCX2NetworkFileGenerator g2 = new CX2NetworkFileGenerator(networkUUID, cx2metadata);\n\t\tString tmpFilePath = g2.createCX2File();\n\t\tFiles.move(Paths.get(tmpFilePath), \n\t\t\t\tPaths.get(fileStoreDir + CX2NetworkLoader.cx2NetworkFileName), \n\t\t\t\tStandardCopyOption.ATOMIC_MOVE); \n\t}\n\n\t@PUT\n\t@Path(\"/{networkid}/summary\")\n\t@Produces(\"application/json\")\n\tpublic void updateNetworkSummary(\n\t\t\t@PathParam(\"networkid\") final String networkId,\n\t\t\tfinal NetworkSummary summary\n\t\t\t)\n throws NdexException, SQLException , IOException, IllegalArgumentException \n {\n\t\t\n\t\ttry (NetworkDAO networkDao = new NetworkDAO()){\n\n\t\t\tUser user = getLoggedInUser();\n\t\t\tUUID networkUUID = UUID.fromString(networkId);\n\t\n\t \t if(networkDao.isReadOnly(networkUUID)) {\n\t\t\t\tthrow new NdexException (\"Can't update readonly network.\");\t\t\t\t\n\t\t\t} \n\t\t\t\n\t\t\tif ( !networkDao.isWriteable(networkUUID, user.getExternalId())) {\n\t\t throw new UnauthorizedOperationException(\"User doesn't have write permissions for this network.\");\n\t\t\t} \n\t\t\t\n\t\t\tif (!networkDao.networkIsValid(networkUUID))\n\t\t\t\tthrow new InvalidNetworkException();\n\n\t\t\ttry {\n\t\t\t\t\tif ( networkDao.networkIsLocked(networkUUID,10)) {\n\t\t\t\t\t\tthrow new NetworkConcurrentModificationException ();\n\t\t\t\t\t}\n\t\t\t} catch (InterruptedException e2) {\n\t\t\t\t\te2.printStackTrace();\n\t\t\t\t\tthrow new NdexException(\"Failed to check network lock: \" + e2.getMessage());\n\t\t\t} \n\t\t\t\t\n\t\t\t\t\n\t\t\ttry {\n\t\t\t\tnetworkDao.lockNetwork(networkUUID);\n\t\t\t\t\n\t\t\t\tnetworkDao.updateNetworkSummary(networkUUID, summary);\n\t\t\t\t\n\t\t\t\t//recreate files and update db\n\t\t\t\tupdateNetworkAttributesAspect(networkDao, networkUUID);\n\t\t\t\t\t\n\t\t\t\tnetworkDao.unlockNetwork(networkUUID);\n\t\t\t\t\t\n\t\t\t\t// update the solr Index\n\t\t\t\tNetworkIndexLevel lvl = networkDao.getIndexLevel(networkUUID);\n\t\t\t\tif ( lvl != NetworkIndexLevel.NONE) {\n\t\t\t\t\t\t networkDao.setFlag(networkUUID, \"iscomplete\", false);\n\t\t\t\t\t\t networkDao.commit();\n\t\t\t\t\t\t NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkUUID,SolrIndexScope.global,false,null,lvl,false));\n\t\t\t\t} else {\n\t\t\t\t\t\t networkDao.setFlag(networkUUID, \"iscomplete\", true);\n\t\t\t\t\t\t networkDao.commit();\n\t\t\t\t}\n\t\t\t} catch ( SQLException | IOException | IllegalArgumentException |NdexException e ) {\n\t\t\t\t\tnetworkDao.rollback();\n\t\t\t\t\ttry {\n\t\t\t\t\t\tnetworkDao.unlockNetwork(networkUUID);\n\t\t\t\t\t} catch (SQLException e1) {\n\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\te1.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t\tthrow e;\n\t\t\t}\n\t\t\t\t\n\t\t}\n\t\t\n\t}\n\n\n\n\n\t\n @PUT\n @Path(\"/{networkid}\")\n @Consumes(\"multipart/form-data\")\n @Produces(\"application/json\")\n\n public void updateCXNetwork(final @PathParam(\"networkid\") String networkIdStr,\n \t\t @QueryParam(\"visibility\") String visibilityStr,\n\t\t @QueryParam(\"extranodeindex\") String fieldListStr, // comma seperated list\t\t\n \t\tMultipartFormDataInput input) throws Exception \n {\n \t VisibilityType visibility = null;\n\t\t if ( visibilityStr !=null) {\n\t\t\t visibility = VisibilityType.valueOf(visibilityStr);\n\t\t }\n\t\t \n\t\t Set extraIndexOnNodes = null;\n\t\t if ( fieldListStr != null) {\n\t\t\t extraIndexOnNodes = new HashSet<>(10);\n\t\t\t for ( String f: fieldListStr.split(\"\\\\s*,\\\\s*\") ) {\n\t\t\t\t extraIndexOnNodes.add(f);\n\t\t\t }\n\t\t }\n\t\t\n\t\ttry (UserDAO dao = new UserDAO()) {\n\t\t\t dao.checkDiskSpace(getLoggedInUserId());\n\t\t}\n \t\n UUID networkId = UUID.fromString(networkIdStr);\n\n // String ownerAccName = null;\n try ( NetworkDAO daoNew = new NetworkDAO() ) {\n User user = getLoggedInUser();\n \n try {\n\t \t if( daoNew.isReadOnly(networkId)) {\n\t\t\t\tthrow new NdexException (\"Can't update readonly network.\");\t\t\t\t\n\t\t\t} \n\t\t\t\n\t\t\tif ( !daoNew.isWriteable(networkId, user.getExternalId())) {\n\t\t throw new UnauthorizedOperationException(\"User doesn't have write permissions for this network.\");\n\t\t\t} \n\t\t\t\n\t\t\tif ( daoNew.networkIsLocked(networkId)) {\n\t\t\t\tdaoNew.close();\n\t\t\t\tthrow new NetworkConcurrentModificationException ();\n\t\t\t} \n\t\t\t\n\t\t\tdaoNew.lockNetwork(networkId);\n\t\t\t\t\t\t\n\t UUID tmpNetworkId = storeRawNetworkFromMultipart (input, cx1NetworkFileName);\n\n\t updateNetworkFromSavedFile( networkId, daoNew, tmpNetworkId);\n\t\t\t\n } catch (SQLException | NdexException | IOException e) {\n \t e.printStackTrace();\n \t daoNew.rollback();\n \t daoNew.unlockNetwork(networkId); \n\n \t throw e;\n } \n\t\t\t\n } \n \t \n\t NdexServerQueue.INSTANCE.addSystemTask(new CXNetworkLoadingTask(networkId, /* ownerAccName,*/ true, visibility,extraIndexOnNodes));\n }\n\n\n @PUT\n @Path(\"/{networkid}\")\n @Consumes(MediaType.APPLICATION_JSON)\n @Produces(\"application/json\")\n\n public void updateNetworkJson(final @PathParam(\"networkid\") String networkIdStr,\n \t\t @QueryParam(\"visibility\") String visibilityStr,\n\t\t @QueryParam(\"extranodeindex\") String fieldListStr // comma seperated list\t\t\n \t\t) throws Exception \n {\n \t VisibilityType visibility = null;\n\t\t if ( visibilityStr !=null) {\n\t\t\t visibility = VisibilityType.valueOf(visibilityStr);\n\t\t }\n\t\t \n\t\t Set extraIndexOnNodes = null;\n\t\t if ( fieldListStr != null) {\n\t\t\t extraIndexOnNodes = new HashSet<>(10);\n\t\t\t for ( String f: fieldListStr.split(\"\\\\s*,\\\\s*\") ) {\n\t\t\t\t extraIndexOnNodes.add(f);\n\t\t\t }\n\t\t }\n \t\n UUID networkId = UUID.fromString(networkIdStr);\n\n // String ownerAccName = null;\n try ( NetworkDAO daoNew = lockNetworkForUpdate(networkId) ) {\n \t\n\t\t\ttry (InputStream in = this.getInputStreamFromRequest()) {\n\t\t\t\t\tUUID tmpNetworkId = storeRawNetworkFromStream(in, cx1NetworkFileName);\n\n\t\t\t\t\tupdateNetworkFromSavedFile(networkId, daoNew, tmpNetworkId);\t\t\t\t\n\t\t\t\n } catch (SQLException | NdexException | IOException e) {\n \t daoNew.rollback();\n \t daoNew.unlockNetwork(networkId); \n\n \t throw e;\n } \n\t\t\t\n\t\t\t\n } \n \t \n\t NdexServerQueue.INSTANCE.addSystemTask(new CXNetworkLoadingTask(networkId, /* ownerAccName,*/ true, visibility,extraIndexOnNodes));\n\t // return networkIdStr; \n }\n\n\n\n\tprivate static void updateNetworkFromSavedFile(UUID networkId, NetworkDAO daoNew,\n\t\t\tUUID tmpNetworkId) throws SQLException, NdexException, IOException, JsonParseException,\n\t\t\tJsonMappingException, ObjectNotFoundException {\n\t\tString cxFileName = Configuration.getInstance().getNdexRoot() + \"/data/\" + tmpNetworkId.toString()\n\t\t\t\t+ \"/network.cx\";\n\t\tlong fileSize = new File(cxFileName).length();\n\n\t\tdaoNew.clearNetworkSummary(networkId, fileSize);\n\n\t\tjava.nio.file.Path src = Paths\n\t\t\t\t.get(Configuration.getInstance().getNdexRoot() + \"/data/\" + tmpNetworkId);\n\t\tjava.nio.file.Path tgt = Paths\n\t\t\t\t.get(Configuration.getInstance().getNdexRoot() + \"/data/\" + networkId);\n\t\tFileUtils.deleteDirectory(\n\t\t\t\tnew File(Configuration.getInstance().getNdexRoot() + \"/data/\" + networkId));\n\t\tFiles.move(src, tgt, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);\n\n\t\tdaoNew.commit();\n\t}\n \n \n /**\n * This function updates aspects of a network. The payload is a CX document which contains the aspects (and their metadata that we will use\n * to update the network). If an aspect only has metadata but no actual data, an Exception will be thrown.\n * @param networkIdStr\n * @param input\n * @throws Exception\n */\n @PUT\n @Path(\"/{networkid}/aspects\")\n @Consumes(\"multipart/form-data\")\n @Produces(\"application/json\")\n public void updateCXNetworkAspects(final @PathParam(\"networkid\") String networkIdStr,\n \t\tMultipartFormDataInput input) throws Exception \n {\n \t\n \ttry (UserDAO dao = new UserDAO()) {\n\t\t\t dao.checkDiskSpace(getLoggedInUserId());\n\t\t}\n \t\n UUID networkId = UUID.fromString(networkIdStr);\n\n // String ownerAccName = null;\n try ( NetworkDAO daoNew = new NetworkDAO() ) {\n User user = getLoggedInUser();\n \n\t \t if( daoNew.isReadOnly(networkId)) {\n\t\t\t\tthrow new NdexException (\"Can't update readonly network.\");\t\t\t\t\n\t\t\t} \n\t\t\t\n\t\t\tif ( !daoNew.isWriteable(networkId, user.getExternalId())) {\n\t\t throw new UnauthorizedOperationException(\"User doesn't have write permissions for this network.\");\n\t\t\t} \n\t\t\t\n\t\t\tif ( daoNew.networkIsLocked(networkId)) {\n\t\t\t\tdaoNew.close();\n\t\t\t\tthrow new NetworkConcurrentModificationException ();\n\t\t\t} \n\t\t\t\n\t\t\tdaoNew.lockNetwork(networkId);\n\t\t\t\n\t//\t\townerAccName = daoNew.getNetworkOwnerAcc(networkId);\n\t\t\t\n\t UUID tmpNetworkId = storeRawNetworkFromMultipart (input, cx1NetworkFileName); //network stored as a temp network\n\t \n\t \tupdateNetworkFromSavedAspects(networkId, daoNew, tmpNetworkId);\n\t\t\t\n } \n }\n \n @PUT\n @Path(\"/{networkid}/aspects\")\n @Consumes(MediaType.APPLICATION_JSON)\n @Produces(\"application/json\")\n public void updateAspectsJson(final @PathParam(\"networkid\") String networkIdStr\n \t\t) throws Exception \n {\n \t\n \ttry (UserDAO dao = new UserDAO()) {\n\t\t\t dao.checkDiskSpace(getLoggedInUserId());\n\t\t}\n \t\n UUID networkId = UUID.fromString(networkIdStr);\n\n // String ownerAccName = null;\n try ( NetworkDAO daoNew = new NetworkDAO() ) {\n User user = getLoggedInUser();\n \n\t \t if( daoNew.isReadOnly(networkId)) {\n\t\t\t\tthrow new NdexException (\"Can't update readonly network.\");\t\t\t\t\n\t\t\t} \n\t\t\t\n\t\t\tif ( !daoNew.isWriteable(networkId, user.getExternalId())) {\n\t\t throw new UnauthorizedOperationException(\"User doesn't have write permissions for this network.\");\n\t\t\t} \n\t\t\t\n\t\t\tif ( daoNew.networkIsLocked(networkId)) {\n\t\t\t\tdaoNew.close();\n\t\t\t\tthrow new NetworkConcurrentModificationException ();\n\t\t\t} \n\t\t\t\n\t\t\tdaoNew.lockNetwork(networkId);\n\t\t\t\n\t//\t\townerAccName = daoNew.getNetworkOwnerAcc(networkId);\n\t\t\ttry (InputStream in = this.getInputStreamFromRequest()) {\n\n\t UUID tmpNetworkId = storeRawNetworkFromStream(in, cx1NetworkFileName); //network stored as a temp network\n\t \n\t \tupdateNetworkFromSavedAspects( networkId, daoNew, tmpNetworkId);\n\t\t\t}\n } \n }\n\n\n\n\tprivate static void updateNetworkFromSavedAspects( UUID networkId, NetworkDAO daoNew,\n\t\t\tUUID tmpNetworkId) throws SQLException, IOException {\n\t\ttry ( CXNetworkAspectsUpdater aspectUpdater = new CXNetworkAspectsUpdater(networkId, /*ownerAccName,*/daoNew, tmpNetworkId) ) {\n\t\t\t\n\t\t\taspectUpdater.update();\n\n\t\t} catch ( IOException | NdexException | SQLException | RuntimeException e1) {\n\t\t\t\tlogger.error(\"Error occurred when updating aspects of network \" + networkId + \": \" + e1.getMessage());\n\t\t\t\te1.printStackTrace();\n\t\t\t\tdaoNew.setErrorMessage(networkId, e1.getMessage());\n\t\t\t\tdaoNew.unlockNetwork(networkId); \t\t\t\t \t\t\n\t\t} \n\t\t \n\t\tFileUtils.deleteDirectory(new File(Configuration.getInstance().getNdexRoot() + \"/data/\" + tmpNetworkId.toString()));\n\t\t \n\t\tdaoNew.unlockNetwork(networkId);\n\t}\n \n\t@DELETE\n\t@Path(\"/{networkid}\")\n\t@Produces(\"application/json\")\n\n\tpublic void deleteNetwork(final @PathParam(\"networkid\") String id) throws NdexException, SQLException {\n\t\t \n\t\ttry (NetworkDAO networkDao = new NetworkDAO()) {\n\t\t\tUUID networkId = UUID.fromString(id);\n\t\t\tUUID userId = getLoggedInUser().getExternalId();\n\t\t\tif(networkDao.isAdmin(networkId, userId) ) {\n\t\t\t\tif (!networkDao.isReadOnly(networkId) ) {\n\t\t\t\t\tif ( !networkDao.networkIsLocked(networkId)) {\n\t\t\t\t\t/*\n\t\t\t\t\t\tNetworkGlobalIndexManager globalIdx = new NetworkGlobalIndexManager();\n\t\t\t\t\t\tglobalIdx.deleteNetwork(id);\n\t\t\t\t\t\ttry (SingleNetworkSolrIdxManager idxManager = new SingleNetworkSolrIdxManager(id)) {\n\t\t\t\t\t\t\tidxManager.dropIndex();\n\t\t\t\t\t\t}\t\n\t\t\t\t\t*/\t\n\t\t\t\t\t\tnetworkDao.deleteNetwork(UUID.fromString(id), getLoggedInUser().getExternalId());\n\t\t\t\t\t\tnetworkDao.commit();\n\n\t\t\t\t\t\t// move the row network to archive folder and delete the folder\n\t\t\t\t\t String pathPrefix = Configuration.getInstance().getNdexRoot() + \"/data/\" + networkId.toString();\n\t\t\t\t /*String archivePath = Configuration.getInstance().getNdexRoot() + \"/data/_archive/\";\n\t\t\t\t \n\t\t\t\t File archiveDir = new File(archivePath);\n\t\t\t\t if (!archiveDir.exists())\n\t\t\t\t \t\tarchiveDir.mkdir();\n\t\t\t\t \n\t\t\t\t \n\t\t\t\t java.nio.file.Path src = Paths.get(pathPrefix+ \"/network.cx\"); \n\t\t\t\t\t\tjava.nio.file.Path tgt = Paths.get(archivePath + \"/\" + networkId.toString() + \".cx\");\n\t\t\t\t\t\t*/\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t//\tFiles.move(src, tgt, StandardCopyOption.ATOMIC_MOVE); \t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\tFileUtils.deleteDirectory(new File(pathPrefix));\n\t\t\t\t\t\t} catch (IOException e) {\n\t\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t\t\tthrow new NdexException(\"Failed to delete directory. Error: \" + e.getMessage());\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tNdexServerQueue.INSTANCE.addSystemTask(new SolrTaskDeleteNetwork(networkId));\n\t\t\t\t\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tthrow new NetworkConcurrentModificationException ();\n\t\t\t\t}\n\t\t\t\t throw new NdexException(\"Can't delete a read-only network.\");\n\t\t\t}\n\t\t\t//TODO: need to check if the network actually exists and give an 404 error for that case.\n\t\t\tthrow new NdexException(\"Only network owner can delete a network.\");\t\n\t\t} catch ( IOException e ) {\n\t\t\tthrow new NdexException (\"Error occurred when deleting network: \" + e.getMessage(), e);\n\t\t}\n\t\t\t\n\t}\n\t\n\n\t/* *************************************************************************\n\t * Saves an uploaded network file. Determines the type of file uploaded,\n\t * saves the file, and creates a task.\n\t *\n\t * Removing it. No longer relevent in v2.\n\t * @param uploadedNetwork\n\t * The uploaded network file.\n\t * @throws IllegalArgumentException\n\t * Bad input.\n\t * @throws NdexException\n\t * Failed to parse the file, or create the network in the\n\t * database.\n\t * @throws IOException \n\t * @throws SQLException \n\t **************************************************************************/\n\t/*\n\t * refactored to support non-transactional database operations\n\t */\n/*\t@POST\n\t@Path(\"/upload\")\n\t@Consumes(\"multipart/form-data\")\n\t@Produces(\"application/json\")\n\tpublic Task uploadNetwork( MultipartFormDataInput input) \n //@MultipartForm UploadedFile uploadedNetwork)\n\t\t\tthrows IllegalArgumentException, SecurityException, NdexException, IOException, SQLException {\n\n\n\t\t try (UserDAO dao = new UserDAO()) {\n\t\t\t dao.checkDiskSpace(getLoggedInUserId());\n\t\t }\n\t\t \n\t\tMap> uploadForm = input.getFormDataMap();\n\n\t\tList foo = uploadForm.get(\"filename\");\n\t\t\n\t\tString fname = \"\";\n\t\tfor (InputPart inputPart : foo)\n\t {\n\t // convert the uploaded file to inputstream and write it to disk\n\t fname += inputPart.getBodyAsString();\n\t }\n\n\t\tif (fname.length() <1) {\n\t\t\tthrow new NdexException (\"\");\n\t\t}\n\t\tString ext = FilenameUtils.getExtension(fname).toLowerCase();\n\n\t\tif ( !ext.equals(\"sif\") && !ext.equals(\"xbel\") && !ext.equals(\"xgmml\") && !ext.equals(\"owl\") && !ext.equals(\"cx\")\n\t\t\t\t&& !ext.equals(\"xls\") && ! ext.equals(\"xlsx\")) {\n\t\t\tthrow new NdexException(\n\t\t\t\t\t\"The uploaded file type is not supported; must be Excel, XGMML, SIF, BioPAX, cx or XBEL.\");\n\t\t}\n\t\t\n\t\tUUID taskId = NdexUUIDFactory.INSTANCE.createNewNDExUUID();\n\n\t\tfinal File uploadedNetworkPath = new File(Configuration.getInstance().getNdexRoot() +\n\t\t\t\t\"/uploaded-networks\");\n\t\tif (!uploadedNetworkPath.exists())\n\t\t\tuploadedNetworkPath.mkdir();\n\n\t\tString fileFullPath = uploadedNetworkPath.getAbsolutePath() + \"/\" + taskId + \".\" + ext;\n\n\t //Get file data to save\n\t List inputParts = uploadForm.get(\"fileUpload\");\n\n\t\t\n\t\tfinal File uploadedNetworkFile = new File(fileFullPath);\n\n\t\tif (!uploadedNetworkFile.exists())\n\t\t\ttry {\n\t\t\t\tuploadedNetworkFile.createNewFile();\n\t\t\t} catch (IOException e1) {\n\t\t\t\tthrow new NdexException (\"Failed to create file \" + fileFullPath + \" on server when uploading \" + \n\t\t\t\t\t\tfname + \": \" + e1.getMessage());\t\t\t\t\n\t\t\t}\n\n byte[] bytes = new byte[2048];\n\t\tfor (InputPart inputPart : inputParts)\n\t {\n\t \n\t // convert the uploaded file to inputstream and write it to disk\n\t InputStream inputStream = inputPart.getBody(InputStream.class, null);\n\t \n\t OutputStream out = new FileOutputStream(new File(fileFullPath));\n\n\t int read = 0;\n\t while ((read = inputStream.read(bytes)) != -1) {\n\t out.write(bytes, 0, read);\n\t }\n\t inputStream.close();\n\t out.flush();\n\t out.close();\n\t \n\t }\t\n\n\t\tTask processNetworkTask = new Task();\n\t\tprocessNetworkTask.setExternalId(taskId);\n\t\tprocessNetworkTask.setDescription(fname); //uploadedNetwork.getFilename());\n\t\tprocessNetworkTask.setTaskType(TaskType.PROCESS_UPLOADED_NETWORK);\n\t\tprocessNetworkTask.setPriority(Priority.LOW);\n\t\tprocessNetworkTask.setProgress(0);\n\t\tprocessNetworkTask.setResource(fileFullPath);\n\t\tprocessNetworkTask.setStatus(Status.QUEUED);\n\t\tprocessNetworkTask.setTaskOwnerId(this.getLoggedInUser().getExternalId());\n\n\t\ttry (TaskDAO dao = new TaskDAO()){\n\t\t\tdao.createTask(processNetworkTask);\n\t\t\tdao.commit();\t\t\n\t\t\t\n\t\t} catch (IllegalArgumentException iae) {\n\t\t\tlogger.error(\"[end: Exception caught:]{}\", iae);\n\t\t\tthrow iae;\n\t\t} catch (Exception e) {\n\t\t\tlogger.error(\"[end: Exception caught:]{}\", e);\n\t\t\tthrow new NdexException(e.getMessage());\n\t\t}\n\n\t\tlogger.info(\"[end: Uploading network file. Task for uploading network is created.]\");\n\t\treturn processNetworkTask;\n\t}\n\n*/\n\n\t@PUT\n\t@Path(\"/{networkid}/systemproperty\")\n\t@Produces(\"application/json\")\n\tpublic void setNetworkFlag(\n\t\t\t@PathParam(\"networkid\") final String networkIdStr,\n\t\t\tfinal Map parameters)\n\n\t\t\tthrows IllegalArgumentException, NdexException, SQLException, IOException {\n\t\t\n\t\t\taccLogger.info(\"[data]\\t[\" + parameters.entrySet()\n\t .stream()\n\t .map(entry -> entry.getKey() + \":\" + entry.getValue()).reduce(null, ((r,e) -> {String rr = r==null? e:r+\",\" +e; return rr;}))\n\t\t\t\t\t + \"]\" );\t\t\n\n\t\t\n\t\t\ttry (NetworkDAO networkDao = new NetworkDAO()) {\n\t\t\t\tUUID networkId = UUID.fromString(networkIdStr);\n\t\t\t\tif ( networkDao.hasDOI(networkId)) {\n\t\t\t\t\tif ( parameters.size() >1 || !parameters.containsKey(\"showcase\"))\n\t\t\t\t\t\tthrow new ForbiddenOperationException(\"Network with DOI can't be modified.\");\t\n\t\t\t\t}\t\n\t\t\t\tUUID userId = getLoggedInUser().getExternalId();\n\t\t\t\t\tif ( !networkDao.networkIsValid(networkId))\n\t\t\t\t\t\tthrow new InvalidNetworkException();\n\t\t\t\t\t\n\t\t\t\t\tif ( parameters.containsKey(readOnlyParameter)) {\n\t\t\t\t\t\tif (!networkDao.isAdmin(networkId, userId))\n\t\t\t\t\t\t\tthrow new UnauthorizedOperationException(\"Only network owner can set readOnly Parameter.\");\n\t\t\t\t\t\tboolean bv = ((Boolean)parameters.get(readOnlyParameter)).booleanValue();\n\t\t\t\t\t\tnetworkDao.setFlag(networkId, \"readonly\",bv);\t \n\t\t\t\t\t}\n\t\t\t\t\tif ( parameters.containsKey(\"visibility\")) {\n\t\t\t\t\t\tif (!networkDao.isAdmin(networkId, userId))\n\t\t\t\t\t\t\tthrow new UnauthorizedOperationException(\"Only network owner can set visibility Parameter.\");\n\t\t\t\t\t\t\n\t\t\t\t\t\tVisibilityType visType = VisibilityType.valueOf((String)parameters.get(\"visibility\"));\n\t\t\t\t\t\tnetworkDao.updateNetworkVisibility(networkId, visType, false);\n\t\t\t\t\t\tif ( !parameters.containsKey(\"index_level\")) {\n\t\t\t\t\t\t\tNetworkIndexLevel lvl = networkDao.getIndexLevel(networkId);\n\t\t\t\t\t\t\tnetworkDao.commit();\n\t\t\t\t\t\t\tif ( lvl != NetworkIndexLevel.NONE) {\n\t\t\t\t\t\t\t\tNdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkId,SolrIndexScope.global,false,null,lvl,false));\n\t\t\t\t\t\t\t} \n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t/*if ( parameters.containsKey(\"index\")) {\n\t\t\t\t\t\tboolean bv = ((Boolean)parameters.get(\"index\")).booleanValue();\n\t\t\t\t\t\tnetworkDao.setFlag(networkId, \"solr_indexed\",bv);\t \n\t\t\t\t\t\tif (bv) {\n\t\t\t\t\t\t\tnetworkDao.setFlag(networkId, \"iscomplete\",false);\t \t\t\t\t\n\t\t\t\t\t\t\tnetworkDao.commit();\n\t\t\t\t\t\t\tNdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkId,SolrIndexScope.global,false,null));\n\t\t\t\t\t\t} else\n\t\t\t\t\t\t\tNdexServerQueue.INSTANCE.addSystemTask(new SolrTaskDeleteNetwork(networkId, true)); //delete the entry from global idx.\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t}*/\n\t\t\t\t\tif ( parameters.containsKey(\"index_level\")) {\n\t\t\t\t\t\tNetworkIndexLevel lvl = parameters.get(\"index_level\") == null? \n\t\t\t\t\t\t\t\tNetworkIndexLevel.NONE : \n\t\t\t\t\t\t\t\tNetworkIndexLevel.valueOf((String)parameters.get(\"index_level\"));\n\t\t\t\t\t\tnetworkDao.setIndexLevel(networkId, lvl);\t \n\t\t\t\t\t\tif (lvl !=NetworkIndexLevel.NONE) {\n\t\t\t\t\t\t\tnetworkDao.setFlag(networkId, \"iscomplete\",false);\t \t\t\t\t\n\t\t\t\t\t\t\tnetworkDao.commit();\n\t\t\t\t\t\t\tNdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkId,SolrIndexScope.global,false,null,lvl,true));\n\t\t\t\t\t\t} else\n\t\t\t\t\t\t\tNdexServerQueue.INSTANCE.addSystemTask(new SolrTaskDeleteNetwork(networkId, true)); //delete the entry from global idx.\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\tif ( parameters.containsKey(\"showcase\")) {\n\t\t\t\t\t\tboolean bv = ((Boolean)parameters.get(\"showcase\")).booleanValue();\n\t\t\t\t\t\tnetworkDao.setShowcaseFlag(networkId, userId, bv);\n\t\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t networkDao.commit();\n\t\t\t\t\treturn;\n\t\t\t}\n\t\t \n\t}\n\n\t\n\t\n\n\t\n\t @POST\n\t//\t@PermitAll\n\n\t @Path(\"\")\n\t @Produces(\"text/plain\")\n\t @Consumes(\"multipart/form-data\")\n\t public Response createCXNetwork( MultipartFormDataInput input,\n\t\t\t @QueryParam(\"visibility\") String visibilityStr,\n\t\t\t\t@QueryParam(\"indexedfields\") String fieldListStr // comma seperated list\t\t\n\t\t\t ) throws Exception\n\t {\n\t \n\t\t VisibilityType visibility = null;\n\t\t if ( visibilityStr !=null) {\n\t\t\t visibility = VisibilityType.valueOf(visibilityStr);\n\t\t }\n\t\t \n\t\t Set extraIndexOnNodes = null;\n\t\t if ( fieldListStr != null) {\n\t\t\t extraIndexOnNodes = new HashSet<>(10);\n\t\t\t for ( String f: fieldListStr.split(\"\\\\s*,\\\\s*\") ) {\n\t\t\t\t extraIndexOnNodes.add(f);\n\t\t\t }\n\t\t }\n\t\t try (UserDAO dao = new UserDAO()) {\n\t\t\t dao.checkDiskSpace(getLoggedInUserId());\n\t\t }\n\t\t \n\t\t \n\t\t UUID uuid = storeRawNetworkFromMultipart ( input, cx1NetworkFileName);\n\t\t return processRawNetwork(visibility, extraIndexOnNodes, uuid);\n\n\t \t}\n\n\n\n\tprivate Response processRawNetwork(VisibilityType visibility, Set extraIndexOnNodes, UUID uuid)\n\t\t\tthrows SQLException, NdexException, IOException, ObjectNotFoundException, JsonProcessingException,\n\t\t\tURISyntaxException {\n\t\tString uuidStr = uuid.toString();\n\t\t accLogger.info(\"[data]\\t[uuid:\" +uuidStr + \"]\" );\n\t \n\t\t String urlStr = Configuration.getInstance().getHostURI() + \n\t\t Configuration.getInstance().getRestAPIPrefix()+\"/network/\"+ uuidStr;\n\t\t \n\t\t String cxFileName = Configuration.getInstance().getNdexRoot() + \"/data/\" + uuidStr + \"/\" + cx1NetworkFileName;\n\t\t long fileSize = new File(cxFileName).length();\n\n\t\t // create entry in db. \n\t try (NetworkDAO dao = new NetworkDAO()) {\n\t \t // NetworkSummary summary = \n\t \t\t\t dao.CreateEmptyNetworkEntry(uuid, getLoggedInUser().getExternalId(), getLoggedInUser().getUserName(), fileSize,null);\n \n\t\t\t\tdao.commit();\n\t }\n\t \n\t NdexServerQueue.INSTANCE.addSystemTask(new CXNetworkLoadingTask(uuid, /*getLoggedInUser().getUserName(),*/ false, visibility, extraIndexOnNodes));\t\t \n\t\t URI l = new URI (urlStr);\n\n\t\t return Response.created(l).entity(l).build();\n\t}\n\t \n\n\t @POST\t \n\t @Path(\"\")\n\t @Produces(\"text/plain\")\n\t @Consumes(MediaType.APPLICATION_JSON)\n\t public Response createNetworkJson( \n\t\t\t @QueryParam(\"visibility\") String visibilityStr,\n\t\t\t\t@QueryParam(\"indexedfields\") String fieldListStr // comma seperated list\t\t\n\t\t\t ) throws Exception\n\t {\n\t \n\t\t VisibilityType visibility = null;\n\t\t if ( visibilityStr !=null) {\n\t\t\t visibility = VisibilityType.valueOf(visibilityStr);\n\t\t }\n\t\t \n\t\t Set extraIndexOnNodes = null;\n\t\t if ( fieldListStr != null) {\n\t\t\t extraIndexOnNodes = new HashSet<>(10);\n\t\t\t for ( String f: fieldListStr.split(\"\\\\s*,\\\\s*\") ) {\n\t\t\t\t extraIndexOnNodes.add(f);\n\t\t\t }\n\t\t }\n\t\t try (UserDAO dao = new UserDAO()) {\n\t\t\t dao.checkDiskSpace(getLoggedInUserId());\n\t\t }\n\t\t \n\t\t try (InputStream in = this.getInputStreamFromRequest()) {\n\t\t\t UUID uuid = storeRawNetworkFromStream(in, cx1NetworkFileName);\n\t\t\t return processRawNetwork(visibility, extraIndexOnNodes, uuid);\n\n\t\t }\t\t \n\n\t \t}\n\t \n\t \n/*\t private static UUID storeRawNetworkFromStream(InputStream in) throws IOException {\n\t\t \n\t\t UUID uuid = NdexUUIDFactory.INSTANCE.createNewNDExUUID();\n\t\t String pathPrefix = Configuration.getInstance().getNdexRoot() + \"/data/\" + uuid.toString();\n\t\t \n\t\t //Create dir\n\t\t java.nio.file.Path dir = Paths.get(pathPrefix);\n\t\t Set perms =\n\t\t\t\t PosixFilePermissions.fromString(\"rwxrwxr-x\");\n\t\t\t\tFileAttribute> attr =\n\t\t\t\t PosixFilePermissions.asFileAttribute(perms);\n\t\t Files.createDirectory(dir,attr);\n\t\t \n\t\t //write content to file\n\t\t String cxFilePath = pathPrefix + \"/network.cx\";\n\t\t \n\t\t try (OutputStream outputStream = new FileOutputStream(cxFilePath)) {\n\t\t\t IOUtils.copy(in, outputStream);\n\t\t\t outputStream.close();\n\t\t } \n\t\t return uuid;\n\t }\n*/\t \n\t \n\t /* private static UUID storeRawNetwork (MultipartFormDataInput input) throws IOException, BadRequestException {\n\t\t Map> uploadForm = input.getFormDataMap();\n\t \t\t\t \n\t\t //Get file data to save\n\t\t List inputParts = uploadForm.get(\"CXNetworkStream\");\n\t\t if (inputParts == null)\n\t\t\t throw new BadRequestException(\"Field CXNetworkStream is not found in the POSTed Data.\");\n\t\t\t \n\t\t byte[] bytes = new byte[8192];\n\t\t UUID uuid = NdexUUIDFactory.INSTANCE.createNewNDExUUID();\n\t\t String pathPrefix = Configuration.getInstance().getNdexRoot() + \"/data/\" + uuid.toString();\n\t\t\t\t \n\t\t //Create dir\n\t\t java.nio.file.Path dir = Paths.get(pathPrefix);\n\t\t Set perms =\n\t\t\t\t\t\t PosixFilePermissions.fromString(\"rwxrwxr-x\");\n\t\t FileAttribute> attr =\n\t\t\t\t\t\t PosixFilePermissions.asFileAttribute(perms);\n\t\t Files.createDirectory(dir,attr);\n\t\t\t\t \n\t\t //write content to file\n\t\t String cxFilePath = pathPrefix + \"/network.cx\";\n\t\t try (FileOutputStream out = new FileOutputStream (cxFilePath ) ){ \n\t\t\t for (InputPart inputPart : inputParts) {\n\t\t\t\t // convert the uploaded file to inputstream and write it to disk\n\t\t\t\t org.jboss.resteasy.plugins.providers.multipart.MultipartInputImpl.PartImpl p =\n\t\t\t\t \t(org.jboss.resteasy.plugins.providers.multipart.MultipartInputImpl.PartImpl) inputPart;\n\t\t\t\t try (InputStream inputStream = p.getBody()) {\n\t\t\t\t \n\t\t\t\t int read = 0;\n\t\t\t\t while ((read = inputStream.read(bytes)) != -1) {\n\t\t\t\t out.write(bytes, 0, read);\n\t\t\t\t }\n\t\t\t\t }\n\t\t\t\t \n\t\t\t }\n\t\t }\n\t\t return uuid; \n\t }\n\t */\n\t \n\t \n\t private static List getNetworkAttributeAspectsFromSummary(NetworkSummary summary) \n\t\t\t throws JsonParseException, JsonMappingException, IOException {\n\t\t\tList result = new ArrayList<>();\n\t\t\tif ( summary.getName() !=null) \n\t\t\t\tresult.add(new NetworkAttributesElement(null, NdexClasses.Network_P_name, summary.getName()));\n\t\t\tif ( summary.getDescription() != null)\n\t\t\t\tresult.add(new NetworkAttributesElement(null, NdexClasses.Network_P_desc, summary.getDescription()));\n\t\t\tif ( summary.getVersion() !=null)\n\t\t\t\tresult.add(new NetworkAttributesElement(null, NdexClasses.Network_P_version, summary.getVersion()));\n\t\t\t\n\t\t\tif ( summary.getProperties() != null) {\n\t\t\t\tfor ( NdexPropertyValuePair p : summary.getProperties()) {\n\t\t\t\t\tresult.add(NetworkAttributesElement.createInstanceWithJsonValue(p.getSubNetworkId(), p.getPredicateString(),\n\t\t\t\t\t\t\tp.getValue(), ATTRIBUTE_DATA_TYPE.fromCxLabel(p.getDataType())));\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn result;\n\t\t}\n\t \n\t \n\t \t@POST\n\t\t @Path(\"/{networkid}/copy\")\n\t\t @Produces(\"text/plain\")\n\t\t public Response cloneNetwork( @PathParam(\"networkid\") final String srcNetworkUUIDStr) throws Exception\n\t\t {\n\t\t \n\t\t\t try (UserDAO dao = new UserDAO()) {\n\t\t\t\t dao.checkDiskSpace(getLoggedInUserId());\n\t\t\t }\n\t\t\t \n\t\t\t UUID srcNetUUID = UUID.fromString(srcNetworkUUIDStr);\n\t\t\t \n\t\t\t try ( NetworkDAO dao = new NetworkDAO ()) {\n\t\t\t\t if ( ! dao.isReadable(srcNetUUID, getLoggedInUserId()) ) \n\t\t throw new UnauthorizedOperationException(\"User doesn't have read access to this network.\");\n\t\t \t\t\n\t\t\t\t if (!dao.networkIsValid(srcNetUUID)) {\n\t\t\t\t\t throw new NdexException (\"Invalid networks can not be copied.\");\n\t\t\t\t }\n\t\t\t }\n\t\t\t \n\t\t\t UUID uuid = NdexUUIDFactory.INSTANCE.createNewNDExUUID();\n\t\t\t String uuidStr = uuid.toString();\n\t\t\t \n\t\t\t//\tjava.nio.file.Path src = Paths.get(Configuration.getInstance().getNdexRoot() + \"/data/\" + srcNetUUID.toString());\n\t\t\t\tjava.nio.file.Path tgt = Paths.get(Configuration.getInstance().getNdexRoot() + \"/data/\" + uuidStr);\n\t\t\t\t\n\t\t\t\t//Create dir\n\t\t\t\tSet perms =\n\t\t\t\t\t\t PosixFilePermissions.fromString(\"rwxrwxr-x\");\n\t\t\t\tFileAttribute> attr =\n\t\t\t\t\t\t PosixFilePermissions.asFileAttribute(perms);\n\t\t\t\tFiles.createDirectory(tgt,attr);\n\t\t\t\t\n\t\t\t\tString srcPathPrefix = Configuration.getInstance().getNdexRoot() + \"/data/\" + srcNetUUID.toString() + \"/\";\n\t\t\t\tString tgtPathPrefix = Configuration.getInstance().getNdexRoot() + \"/data/\" + uuidStr + \"/\";\n\n\t\t\t File srcAspectDir = new File ( srcPathPrefix + CXNetworkLoader.CX1AspectDir);\n\t\t\t if ( srcAspectDir.exists()) {\n\t\t\t \tFile tgtAspectDir = new File ( tgtPathPrefix + CXNetworkLoader.CX1AspectDir);\n\t\t\t \tFileUtils.copyDirectory(srcAspectDir, tgtAspectDir);\n\t\t\t }\n\t\t\t \n\t\t\t //copy the cx2 aspect directories\n\t\t\t String tgtCX2AspectPathPrefix = tgtPathPrefix + CX2NetworkLoader.cx2AspectDirName;\n\t\t\t String srcCX2AspectPathPrefix = srcPathPrefix + CX2NetworkLoader.cx2AspectDirName;\n\t\t\t File srcCX2AspectDir = new File (srcCX2AspectPathPrefix );\n\t\t\t Files.createDirectories(Paths.get(tgtCX2AspectPathPrefix), attr);\n\t\t\t for ( String fname : srcCX2AspectDir.list() ) {\n\t\t\t \tjava.nio.file.Path src = Paths.get(srcPathPrefix + CX2NetworkLoader.cx2AspectDirName , fname);\n\t\t\t \tif (Files.isSymbolicLink(src)) {\n\t\t\t \t\tjava.nio.file.Path link = Paths.get(tgtCX2AspectPathPrefix, fname);\n\t\t\t \t\tjava.nio.file.Path target = Paths.get(tgtPathPrefix + CXNetworkLoader.CX1AspectDir, fname);\n\t\t\t \t\tFiles.createSymbolicLink(link, target);\n\t\t\t \t} else {\n\t\t\t \t\tFiles.copy(Paths.get(srcCX2AspectPathPrefix, fname),\n\t\t\t \t\t\t\tPaths.get(tgtCX2AspectPathPrefix, fname));\n\t\t\t \t}\n\t\t\t \t\n\t\t\t }\n\t\t\t \n\t\t\t String urlStr = Configuration.getInstance().getHostURI() + \n\t\t\t Configuration.getInstance().getRestAPIPrefix()+\"/network/\"+ uuidStr;\n\t\t\t // ProvenanceEntity entity = new ProvenanceEntity();\n\t\t\t // entity.setUri(urlStr + \"/summary\");\n\t\t\t \n\t\t\t String cxFileName = Configuration.getInstance().getNdexRoot() + \"/data/\" + srcNetUUID.toString() + \"/\" + cx1NetworkFileName;\n\t\t\t long fileSize = new File(cxFileName).length();\n\n\t\t\t // copy sample \n\t\t\t java.nio.file.Path srcSample = Paths.get(Configuration.getInstance().getNdexRoot() + \"/data/\" + srcNetUUID.toString() + \"/sample.cx\");\n\t\t\t if ( Files.exists(srcSample, LinkOption.NOFOLLOW_LINKS)) {\n\t\t\t\t java.nio.file.Path tgtSample = Paths.get(Configuration.getInstance().getNdexRoot() + \"/data/\" + uuidStr + \"/sample.cx\");\n\t\t\t\t Files.copy(srcSample, tgtSample);\n\t\t\t }\n\t\t\t \n\t\t\t \n\t\t\t //TODO: generate prov:wasDerivedFrom and prov:wasGeneratedby field in both db record and the recreated CX file.\n\t\t\t // Need to handle the case when this network was a clone (means it already has prov:wasGeneratedBy and wasDerivedFrom attributes\n\t\t\t // create entry in db. \n\t\t try (NetworkDAO dao = new NetworkDAO()) {\n\t\t //\t NetworkSummary summary = \n\t\t \t\t\t dao.CreateCloneNetworkEntry(uuid, getLoggedInUser().getExternalId(), getLoggedInUser().getUserName(), fileSize, srcNetUUID);\n\t\n\t\t\t\t\tCXNetworkFileGenerator g = new CXNetworkFileGenerator(uuid, dao /*, new Provenance(copyProv)*/);\n\t\t\t\t\tg.reCreateCXFile();\n\t\t\t\t\tCX2NetworkFileGenerator g2 = new CX2NetworkFileGenerator(uuid, dao);\n\t\t\t\t\tString tmpFilePath = g2.createCX2File();\n\t\t\t\t\tFiles.move(Paths.get(tmpFilePath), \n\t\t\t\t\t\t\tPaths.get(tgtPathPrefix + CX2NetworkLoader.cx2NetworkFileName), \n\t\t\t\t\t\t\tStandardCopyOption.ATOMIC_MOVE); \t\t\t\t\n\n\t\t\t\t\tdao.setFlag(uuid, \"iscomplete\", true);\n\t\t\t\t\tdao.commit();\n\t\t }\n\t\t \n\t\t\t\tNdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(uuid, SolrIndexScope.individual,true,null, NetworkIndexLevel.NONE,false));\n\t\t \t\t\t \n\t\t\t URI l = new URI (urlStr);\n\n\t\t\t return Response.created(l).entity(l).build();\n\n\t\t \t}\n\t\t \n\n\t @POST\n\t\t@PermitAll\n\t\t@Path(\"/properties/score\")\n\t\t@Produces(\"application/json\")\n\t public static int getScoresFromProperties(\n\t \t\tfinal List properties)\n\t \t\tthrows Exception {\n\n\t\t\treturn Util.getNetworkScores (properties, true);\n\t }\n\t \n\t @POST\n\t\t@PermitAll\n\t\t@Path(\"/summary/score\")\n\t\t@Produces(\"application/json\")\n\t public static int getScoresFromNetworkSummary(\n\t \t\tfinal NetworkSummary summary)\n\t \t\tthrows Exception {\n\n\t\t\treturn Util.getNdexScoreFromSummary(summary);\n\t }\n\t \t\n\t \t\n}\n"},"new_file":{"kind":"string","value":"src/main/java/org/ndexbio/rest/services/NetworkServiceV2.java"},"old_contents":{"kind":"string","value":"/**\n * Copyright (c) 2013, 2016, The Regents of the University of California, The Cytoscape Consortium\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and/or other materials provided with the distribution.\n *\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n */\npackage org.ndexbio.rest.services;\n\nimport java.io.ByteArrayOutputStream;\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.io.PipedInputStream;\nimport java.io.PipedOutputStream;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.nio.file.Files;\nimport java.nio.file.LinkOption;\nimport java.nio.file.Paths;\nimport java.nio.file.StandardCopyOption;\nimport java.nio.file.attribute.FileAttribute;\nimport java.nio.file.attribute.PosixFilePermission;\nimport java.nio.file.attribute.PosixFilePermissions;\nimport java.sql.SQLException;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.UUID;\n\nimport javax.annotation.security.PermitAll;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.ws.rs.Consumes;\nimport javax.ws.rs.DELETE;\nimport javax.ws.rs.DefaultValue;\nimport javax.ws.rs.GET;\nimport javax.ws.rs.POST;\nimport javax.ws.rs.PUT;\nimport javax.ws.rs.Path;\nimport javax.ws.rs.PathParam;\nimport javax.ws.rs.Produces;\nimport javax.ws.rs.QueryParam;\nimport javax.ws.rs.core.Context;\nimport javax.ws.rs.core.MediaType;\nimport javax.ws.rs.core.Response;\nimport javax.ws.rs.core.Response.ResponseBuilder;\n\nimport org.apache.commons.io.FileUtils;\nimport org.apache.solr.client.solrj.SolrServerException;\nimport org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;\nimport org.ndexbio.common.NdexClasses;\nimport org.ndexbio.common.cx.CX2NetworkFileGenerator;\nimport org.ndexbio.common.cx.CXNetworkFileGenerator;\nimport org.ndexbio.common.models.dao.postgresql.NetworkDAO;\nimport org.ndexbio.common.models.dao.postgresql.UserDAO;\nimport org.ndexbio.common.persistence.CX2NetworkLoader;\nimport org.ndexbio.common.persistence.CXNetworkAspectsUpdater;\nimport org.ndexbio.common.persistence.CXNetworkLoader;\nimport org.ndexbio.common.util.NdexUUIDFactory;\nimport org.ndexbio.common.util.Util;\nimport org.ndexbio.cx2.aspect.element.core.CxAttributeDeclaration;\nimport org.ndexbio.cx2.aspect.element.core.CxMetadata;\nimport org.ndexbio.cx2.aspect.element.core.CxNetworkAttribute;\nimport org.ndexbio.cx2.converter.AspectAttributeStat;\nimport org.ndexbio.cx2.converter.CXToCX2Converter;\nimport org.ndexbio.cx2.io.CX2AspectWriter;\nimport org.ndexbio.cxio.aspects.datamodels.ATTRIBUTE_DATA_TYPE;\nimport org.ndexbio.cxio.aspects.datamodels.NetworkAttributesElement;\nimport org.ndexbio.cxio.core.CXAspectWriter;\nimport org.ndexbio.cxio.core.OpaqueAspectIterator;\nimport org.ndexbio.cxio.metadata.MetaDataCollection;\nimport org.ndexbio.cxio.metadata.MetaDataElement;\nimport org.ndexbio.cxio.util.JsonWriter;\nimport org.ndexbio.model.exceptions.BadRequestException;\nimport org.ndexbio.model.exceptions.ForbiddenOperationException;\nimport org.ndexbio.model.exceptions.InvalidNetworkException;\nimport org.ndexbio.model.exceptions.NdexException;\nimport org.ndexbio.model.exceptions.NetworkConcurrentModificationException;\nimport org.ndexbio.model.exceptions.ObjectNotFoundException;\nimport org.ndexbio.model.exceptions.UnauthorizedOperationException;\nimport org.ndexbio.model.object.NdexPropertyValuePair;\nimport org.ndexbio.model.object.Permissions;\nimport org.ndexbio.model.object.ProvenanceEntity;\nimport org.ndexbio.model.object.User;\nimport org.ndexbio.model.object.network.NetworkIndexLevel;\nimport org.ndexbio.model.object.network.NetworkSummary;\nimport org.ndexbio.model.object.network.VisibilityType;\nimport org.ndexbio.rest.Configuration;\nimport org.ndexbio.rest.filters.BasicAuthenticationFilter;\nimport org.ndexbio.task.CXNetworkLoadingTask;\nimport org.ndexbio.task.NdexServerQueue;\nimport org.ndexbio.task.SolrIndexScope;\nimport org.ndexbio.task.SolrTaskDeleteNetwork;\nimport org.ndexbio.task.SolrTaskRebuildNetworkIdx;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.fasterxml.jackson.core.JsonParseException;\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.fasterxml.jackson.databind.JsonMappingException;\nimport com.fasterxml.jackson.databind.ObjectMapper;\n\n@Path(\"/v2/network\")\npublic class NetworkServiceV2 extends NdexService {\n\t\n//\tstatic Logger logger = LoggerFactory.getLogger(NetworkService.class);\n\tstatic Logger accLogger = LoggerFactory.getLogger(BasicAuthenticationFilter.accessLoggerName);\n\t\n\tstatic private final String readOnlyParameter = \"readOnly\";\n\t\n\tprivate static final String cx1NetworkFileName = \"network.cx\";\n\n\tpublic NetworkServiceV2(@Context HttpServletRequest httpRequest\n\t\t//\t@Context org.jboss.resteasy.spi.HttpResponse response\n\t\t\t) {\n\t\tsuper(httpRequest);\n\t}\n\n\n\n /**************************************************************************\n * Returns network provenance.\n * @throws IOException\n * @throws JsonMappingException\n * @throws JsonParseException\n * @throws NdexException\n * @throws SQLException \n *\n **************************************************************************/\n\t@PermitAll\n\t@GET\n\t@Path(\"/{networkid}/provenance\")\n\t@Produces(\"application/json\")\n\n\tpublic ProvenanceEntity getProvenance(\n\t\t\t@PathParam(\"networkid\") final String networkIdStr,\n\t\t\t@QueryParam(\"accesskey\") String accessKey)\n\n\t\t\tthrows IllegalArgumentException, JsonParseException, JsonMappingException, IOException, NdexException, SQLException {\n\t\t\n\t\t\n\t\tUUID networkId = UUID.fromString(networkIdStr);\n\t\t\n\t\ttry (NetworkDAO daoNew = new NetworkDAO()) {\n\t\t\tif ( !daoNew.isReadable(networkId, getLoggedInUserId()) && (!daoNew.accessKeyIsValid(networkId, accessKey)))\n\t\t\t\t\tthrow new UnauthorizedOperationException(\"Network \" + networkId + \" is not readable to this user.\");\n\n\t\t\treturn daoNew.getProvenance(networkId);\n\n\t\t} \n\t}\n\n /**************************************************************************\n * Updates network provenance.\n * @throws Exception\n *\n **************************************************************************/\n @PUT\n\t@Path(\"/{networkid}/provenance\")\n\t@Produces(\"application/json\")\n public void setProvenance(@PathParam(\"networkid\")final String networkIdStr, final ProvenanceEntity provenance)\n \t\tthrows Exception {\n \n\t\tUser user = getLoggedInUser();\n\n\t\tsetProvenance_aux(networkIdStr, provenance, user);\n }\n\n\n @Deprecated\n\tprotected static void setProvenance_aux(final String networkIdStr, final ProvenanceEntity provenance, User user)\n\t\t\tthrows Exception {\n\t\ttry (NetworkDAO daoNew = new NetworkDAO()){\n\t\t\t\n\t\t\tUUID networkId = UUID.fromString(networkIdStr);\n\n\t\t\tif ( !daoNew.isWriteable(networkId, user.getExternalId())) {\n\n\t\t throw new UnauthorizedOperationException(\"User doesn't have write permissions for this network.\");\n\t\t\t}\n\t\n\t\t\tif(daoNew.isReadOnly(networkId)) {\n\t\t\t\tdaoNew.close();\n\t\t\t\tthrow new NdexException (\"Can't update readonly network.\");\n\t\t\t} \n\n\n\t\t\tif (!daoNew.networkIsValid(networkId))\n\t\t\t\tthrow new InvalidNetworkException();\n\t\t\t\t\n\t/*\t\tif ( daoNew.networkIsLocked(networkId,6)) {\n\t\t\t\tdaoNew.close();\n\t\t\t\tthrow new NetworkConcurrentModificationException ();\n\t\t\t}\n\t\t\t\n\t\t\tdaoNew.lockNetwork(networkId); */\n\t\t\tdaoNew.setProvenance(networkId, provenance);\n\t\t\tdaoNew.commit();\n\t\t\t\n\t\t\t//Recreate the CX file \t\t\t\t\t\n\t\t//\tNetworkSummary fullSummary = daoNew.getNetworkSummaryById(networkId);\n\t\t//\tMetaDataCollection metadata = daoNew.getMetaDataCollection(networkId);\n\t//\t\tCXNetworkFileGenerator g = new CXNetworkFileGenerator(networkId, daoNew, new Provenance(provenance));\n\t//\t\tg.reCreateCXFile();\n\t//\t\tdaoNew.unlockNetwork(networkId);\n\t\t\t\n\t\t\t\n\t\t\treturn ; // provenance; // daoNew.getProvenance(networkUUID);\n\t\t} catch (Exception e) {\n\t\t\t//if (null != daoNew) daoNew.rollback();\n\t\t\tthrow e;\n\t\t} \n\t}\n\n\n\n /**************************************************************************\n * Sets network properties.\n * @throws Exception\n *\n **************************************************************************/\n @PUT\n\t@Path(\"/{networkid}/properties\")\n\t@Produces(\"application/json\")\n \n public int setNetworkProperties(\n \t\t@PathParam(\"networkid\")final String networkId,\n \t\tfinal List properties)\n \t\tthrows Exception {\n\n\t\tUser user = getLoggedInUser();\n\t\tUUID networkUUID = UUID.fromString(networkId);\n\n\t\ttry (NetworkDAO daoNew = new NetworkDAO()) {\n\t\t\t\n\t \t if(daoNew.isReadOnly(networkUUID)) {\n\t\t\t\tthrow new NdexException (\"Can't update readonly network.\");\t\t\t\t\n\t\t\t} \n\t\t\t\n\t\t\tif ( !daoNew.isWriteable(networkUUID, user.getExternalId())) {\n\t\t throw new UnauthorizedOperationException(\"User doesn't have write permissions for this network.\");\n\t\t\t} \n\t\t\t\n\t\t\tif ( daoNew.networkIsLocked(networkUUID,10)) {\n\t\t\t\tthrow new NetworkConcurrentModificationException ();\n\t\t\t} \n\t\t\t\n\t\t\tif ( !daoNew.networkIsValid(networkUUID))\n\t\t\t\tthrow new InvalidNetworkException();\n\n\t\t\tdaoNew.lockNetwork(networkUUID);\n\t\t\t\n\t\t\tint i = 0;\n\t\t\ttry {\n\t\t\t\ti = daoNew.setNetworkProperties(networkUUID, properties);\n\n\t\t\t\t// recreate files and update db\n\t\t\t\tupdateNetworkAttributesAspect(daoNew, networkUUID);\n\n\t\t\t} finally {\n\t\t\t\tdaoNew.unlockNetwork(networkUUID);\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\tNetworkIndexLevel idxLvl = daoNew.getIndexLevel(networkUUID);\n\t\t\tif ( idxLvl != NetworkIndexLevel.NONE) {\n\t\t\t\tdaoNew.setFlag(networkUUID, \"iscomplete\",false);\n\t\t\t\tdaoNew.commit();\n\t\t\t\tNdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkUUID,SolrIndexScope.global,false,null,idxLvl,false));\n\t\t\t} else {\n\t\t\t\tdaoNew.setFlag(networkUUID, \"iscomplete\", true);\n\t\t\t}\n\t\t\t\n\t\t\treturn i;\n\t\t} catch (Exception e) {\n\t\t\t//logger.severe(\"Error occurred when update network properties: \" + e.getMessage());\n\t\t\t//e.printStackTrace();\n\t\t\t//if (null != daoNew) daoNew.rollback();\n\t\t\tlogger.error(\"Updating properties of network {}. Exception caught:]{}\", networkId, e);\n\t\t\t\n\t\t\tthrow new NdexException(e.getMessage(), e);\n\t\t} \n }\n \n\t/*\n\t *\n\t * Operations returning Networks \n\t * \n\t */\n\n\t@PermitAll\n\t@GET\n\t@Path(\"/{networkid}/summary\")\n\t@Produces(\"application/json\")\n\t\n\tpublic NetworkSummary getNetworkSummary(\n\t\t\t@PathParam(\"networkid\") final String networkIdStr ,\n\t\t\t@QueryParam(\"accesskey\") String accessKey /*,\n\t\t\t@Context org.jboss.resteasy.spi.HttpResponse response*/)\n\n\t\t\tthrows IllegalArgumentException, NdexException, SQLException, JsonParseException, JsonMappingException, IOException {\n\t\t\n\t\ttry (NetworkDAO dao = new NetworkDAO()) {\n\t\t\tUUID userId = getLoggedInUserId();\n\t\t\tUUID networkId = UUID.fromString(networkIdStr);\n\t\t\tif ( dao.isReadable(networkId, userId) || dao.accessKeyIsValid(networkId, accessKey)) {\n\t\t\t\tNetworkSummary summary = dao.getNetworkSummaryById(networkId);\n\n\t\t\t\treturn summary;\n\t\t\t}\n\t\t\t\t\n\t\t\tthrow new UnauthorizedOperationException (\"Unauthorized access to network \" + networkId);\n\t\t} \n\t\t\t\n\t\t\t\n\t}\n\n\n\t@PermitAll\n\t@GET\n\t@Path(\"/{networkid}/aspect\")\n\t\n\tpublic Response getNetworkCXMetadataCollection(\t@PathParam(\"networkid\") final String networkId,\n\t\t\t@QueryParam(\"accesskey\") String accessKey)\n\t\t\tthrows Exception {\n\n \tlogger.info(\"[start: Getting CX metadata from network {}]\", networkId);\n\n \tUUID networkUUID = UUID.fromString(networkId);\n\n\t\ttry (NetworkDAO dao = new NetworkDAO() ) {\n\t\t\tif ( dao.isReadable(networkUUID, getLoggedInUserId()) || dao.accessKeyIsValid(networkUUID, accessKey)) {\n\t\t\t\tMetaDataCollection mdc = dao.getMetaDataCollection(networkUUID);\n\t\t \tlogger.info(\"[end: Return CX metadata from network {}]\", networkId);\n\t\t \tByteArrayOutputStream baos = new ByteArrayOutputStream();\n\t\t\t\tJsonWriter wtr = JsonWriter.createInstance(baos,true);\n\t\t\t\tmdc.toJson(wtr);\n\t\t\t\tString s = baos.toString();//\"java.nio.charset.StandardCharsets.UTF_8\");\n\t\t\t\treturn \tResponse.ok().type(MediaType.APPLICATION_JSON_TYPE).entity(s).build();\n//\t\t \treturn mdc;\n\t\t\t}\n\t\t\tthrow new UnauthorizedOperationException(\"User doesn't have access to this network.\");\n\t\t}\n\t} \n\t\n\t@PermitAll\n\t@GET\n\t@Path(\"/{networkid}/aspect/{aspectname}/metadata\")\n\t@Produces(\"application/json\")\n\t\n\tpublic MetaDataElement getNetworkCXMetadata(\t\n\t\t\t@PathParam(\"networkid\") final String networkId,\n\t\t\t@PathParam(\"aspectname\") final String aspectName\n\t\t\t)\n\t\t\tthrows Exception {\n\n \tlogger.info(\"[start: Getting {} metadata from network {}]\", aspectName, networkId);\n\n \tUUID networkUUID = UUID.fromString(networkId);\n\n\t\ttry (NetworkDAO dao = new NetworkDAO() ) {\n\t\t\tif ( dao.isReadable(networkUUID, getLoggedInUserId())) {\n\t\t\t\tMetaDataCollection mdc = dao.getMetaDataCollection(networkUUID);\n\t\t \tlogger.info(\"[end: Return CX metadata from network {}]\", networkId);\n\t\t \treturn mdc.getMetaDataElement(aspectName);\n\t\t\t}\n\t\t\tthrow new UnauthorizedOperationException(\"User doesn't have access to this network.\");\n\t\t}\n\t} \n\t\n\t\n\t@PermitAll\n\t@GET\n\t@Path(\"/{networkid}/aspect/{aspectname}\")\n\tpublic Response getAspectElements(\t@PathParam(\"networkid\") final String networkId,\n\t\t\t@PathParam(\"aspectname\") final String aspectName,\n\t\t\t@DefaultValue(\"-1\") @QueryParam(\"size\") int limit) throws SQLException, NdexException\n\t\t {\n\n \tlogger.info(\"[start: Getting one aspect in network {}]\", networkId);\n \tUUID networkUUID = UUID.fromString(networkId);\n \t\n \ttry (NetworkDAO dao = new NetworkDAO()) {\n \t\tif ( !dao.isReadable(networkUUID, getLoggedInUserId())) {\n \t\t\tthrow new UnauthorizedOperationException(\"User doesn't have access to this network.\");\n \t\t}\n \t\t\n \t\tFile cx1AspectDir = new File (Configuration.getInstance().getNdexRoot() + \"/data/\" + networkId \n \t\t\t\t+ \"/\" + CXNetworkLoader.CX1AspectDir);\n \t\tboolean hasCX1AspDir = cx1AspectDir.exists();\n \t\t\n\t\t\tFileInputStream in = null;\n\t\t\ttry {\n\t\t\t\tif ( hasCX1AspDir) {\n\t\t\t\t in = new FileInputStream(cx1AspectDir + \"/\" + aspectName);\n\t\t\t\t if ( limit <= 0) {\n\t\t\t\t\t\treturn \tResponse.ok().type(MediaType.APPLICATION_JSON_TYPE).entity(in).build();\n\t\t\t \t} \n\t\t\t\t \n\t\t\t\t PipedInputStream pin = new PipedInputStream();\n\t\t\t\t\tPipedOutputStream out;\n\t\t\t\t\t\t\n\t\t\t\t\ttry {\n\t\t\t\t\t\t\tout = new PipedOutputStream(pin);\n\t\t\t\t\t} catch (IOException e) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tpin.close();\n\t\t\t\t\t\t\tin.close();\n\t\t\t\t\t\t} catch (IOException e1) {\n\t\t\t\t\t\t\te1.printStackTrace();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthrow new NdexException(\"IOExcetion when creating the piped output stream: \"+ e.getMessage());\n\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\tnew CXAspectElementsWriterThread(out,in, /*aspectName,*/ limit).start();\n\t\t\t\t//\tlogger.info(\"[end: Return get one aspect in network {}]\", networkId);\n\t\t\t\t\treturn \tResponse.ok().type(MediaType.APPLICATION_JSON_TYPE).entity(pin).build();\n\t\t\t\t} \n\t\t\t\t\n\t\t\t} catch (FileNotFoundException e) {\n\t\t\t\t\tthrow new ObjectNotFoundException(\"Aspect \"+ aspectName + \" not found in this network: \" + e.getMessage());\n\t\t\t}\n\t \t\n\t\t\t\n\t\t\t//get aspect from cx2 aspects\n\t\t\tPipedInputStream pin = new PipedInputStream();\n\t\t\tPipedOutputStream out;\n\t\t\t\t\n\t\t\ttry {\n\t\t\t\t\tout = new PipedOutputStream(pin);\n\t\t\t} catch (IOException e) {\n\t\t\t\ttry {\n\t\t\t\t\tpin.close();\n\t\t\t\t} catch (IOException e1) {\n\t\t\t\t\te1.printStackTrace();\n\t\t\t\t}\n\t\t\t\tthrow new NdexException(\"IOExcetion when creating the piped output stream: \"+ e.getMessage());\n\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\tnew CXAspectElementWriter2Thread(out,networkId, aspectName, limit, accLogger).start();\n\t\t//\tlogger.info(\"[end: Return get one aspect in network {}]\", networkId);\n\t\t\treturn \tResponse.ok().type(MediaType.APPLICATION_JSON_TYPE).entity(pin).build();\n\t\t\n\t\t\n \t}\n\n\t} \n\t\n\t\n\t@PermitAll\n\t@GET\n\t@Path(\"/{networkid}\")\n\n\tpublic Response getCompleteNetworkAsCX(\t@PathParam(\"networkid\") final String networkId,\n\t\t\t@QueryParam(\"download\") boolean isDownload,\n\t\t\t@QueryParam(\"accesskey\") String accessKey,\n\t\t\t@QueryParam(\"id_token\") String id_token,\n\t\t\t@QueryParam(\"auth_token\") String auth_token)\n\t\t\tthrows Exception {\n \t\n \tString title = null;\n \ttry (NetworkDAO dao = new NetworkDAO()) {\n \t\tUUID networkUUID = UUID.fromString(networkId);\n \t\tUUID userId = getLoggedInUserId();\n \t\tif ( userId == null ) {\n \t\t\tif ( auth_token != null) {\n \t\t\t\tuserId = getUserIdFromBasicAuthString(auth_token);\n \t\t\t} else if ( id_token !=null) {\n \t\t\t\tif ( getGoogleAuthenticator() == null)\n \t\t\t\t\tthrow new UnauthorizedOperationException(\"Google OAuth is not enabled on this server.\");\n \t\t\t\tuserId = getGoogleAuthenticator().getUserUUIDByIdToken(id_token);\n \t\t\t}\n \t\t}\n \t\tif ( ! dao.isReadable(networkUUID, userId) && (!dao.accessKeyIsValid(networkUUID, accessKey))) \n throw new UnauthorizedOperationException(\"User doesn't have read access to this network.\");\n \t\t\n \t\ttitle = dao.getNetworkName(networkUUID);\n \t}\n \n\t\tString cxFilePath = Configuration.getInstance().getNdexRoot() + \"/data/\" + networkId + \"/\" + cx1NetworkFileName;\n\n \ttry {\n\t\t\tFileInputStream in = new FileInputStream(cxFilePath) ;\n\t\t\n\t\t//\tsetZipFlag();\n\t\t\tlogger.info(\"[end: Return network {}]\", networkId);\n\t\t\tResponseBuilder r = Response.ok();\n\t\t\tif (isDownload) {\n\t\t\t\tif (title == null || title.length() < 1) {\n\t\t\t\t\ttitle = networkId;\n\t\t\t\t}\n\t\t\t\ttitle.replace('\"', '_');\n\t\t\t\tr.header(\"Content-Disposition\", \"attachment; filename=\\\"\" + title + \".cx\\\"\");\n\t\t\t\tr.header(\"Access-Control-Expose-Headers\", \"Content-Disposition\");\n\t\t\t}\n\t\t\treturn \tr.type(isDownload ? MediaType.APPLICATION_OCTET_STREAM_TYPE : MediaType.APPLICATION_JSON_TYPE)\n\t\t\t\t\t.entity(in).build();\n\t\t} catch (IOException e) {\n\t\t\tlogger.error(\"[end: Ndex server can't find file: {}]\", e.getMessage());\n\t\t\tthrow new NdexException (\"Ndex server can't find file: \" + e.getMessage());\n\t\t}\n\t\t\n\t} \n\n\n\t\n\t@PermitAll\n\t@GET\n\t@Path(\"/{networkid}/sample\")\n\n\tpublic Response getSampleNetworkAsCX(\t@PathParam(\"networkid\") final String networkIdStr ,\n\t\t\t@QueryParam(\"accesskey\") String accessKey)\n\t\t\tthrows IllegalArgumentException, NdexException, SQLException {\n \t\n \tUUID networkId = UUID.fromString(networkIdStr);\n \ttry (NetworkDAO dao = new NetworkDAO()) {\n \t\tif ( ! dao.isReadable(networkId, getLoggedInUserId()) && (!dao.accessKeyIsValid(networkId, accessKey)))\n throw new UnauthorizedOperationException(\"User doesn't have read access to this network.\");\n\n \t}\n \t\n\t\tString cxFilePath = Configuration.getInstance().getNdexRoot() + \"/data/\" + networkId + \"/sample.cx\";\n\t\t\n\t\ttry {\n\t\t\tFileInputStream in = new FileInputStream(cxFilePath) ;\n\t\t\n\t\t\t//\tsetZipFlag();\n\t\t\treturn \tResponse.ok().type(MediaType.APPLICATION_JSON_TYPE).entity(in).build();\n\t\t} catch ( FileNotFoundException e) {\n\t\t\t\tthrow new ObjectNotFoundException(\"Sample network of \" + networkId + \" not found. Error: \" + e.getMessage());\n\t\t} \n\t\t\n\t} \n\t\n\t@GET\n\t@Path(\"/{networkid}/accesskey\")\n\t@Produces(\"application/json\")\n\tpublic Map getNetworkAccessKey(@PathParam(\"networkid\") final String networkIdStr)\n\t\t\tthrows IllegalArgumentException, NdexException, SQLException {\n \t\n\t\tUUID networkId = UUID.fromString(networkIdStr);\n \ttry (NetworkDAO dao = new NetworkDAO()) {\n \t\tif ( ! dao.isAdmin(networkId, getLoggedInUserId()))\n throw new UnauthorizedOperationException(\"User is not admin of this network.\");\n\n \t\tString key = dao.getNetworkAccessKey(networkId);\n \t\tif (key == null || key.length()==0)\n \t\t\treturn null;\n \t\tMap result = new HashMap<>(1);\n \t\tresult.put(\"accessKey\", key);\n \t\treturn result;\n \t}\n\t} \n\t\t\n\t@PUT\n\t@Path(\"/{networkid}/accesskey\")\n\t@Produces(\"application/json\")\n\tpublic Map disableEnableNetworkAccessKey(@PathParam(\"networkid\") final String networkIdStr,\n\t\t\t@QueryParam(\"action\") String action)\n\t\t\tthrows IllegalArgumentException, NdexException, SQLException {\n \t\n\t\tUUID networkId = UUID.fromString(networkIdStr);\n\t\tif ( ! action.equalsIgnoreCase(\"disable\") && ! action.equalsIgnoreCase(\"enable\"))\n\t\t\tthrow new NdexException(\"Value of 'action' paramter can only be 'disable' or 'enable'\");\n\t\t\n \ttry (NetworkDAO dao = new NetworkDAO()) {\n \t\tif ( ! dao.isAdmin(networkId, getLoggedInUserId()))\n throw new UnauthorizedOperationException(\"User is not admin of this network.\");\n\n \t\tString key = null;\n \t\tif ( action.equalsIgnoreCase(\"disable\"))\n \t\t\tdao.disableNetworkAccessKey(networkId);\n \t\telse \n \t\t\tkey = dao.enableNetworkAccessKey(networkId);\n \t\tdao.commit();\n \t\t\n \t\tif (key == null || key.length()==0)\n \t\t\treturn null;\n \t\tMap result = new HashMap<>(1);\n \t\tresult.put(\"accessKey\", key);\n \t\treturn result;\n \t}\n\t} \n\t\n\t\n\t@PUT\n\t@Path(\"/{networkid}/sample\")\n\t\n\tpublic void setSampleNetwork(\t@PathParam(\"networkid\") final String networkId,\n\t\t\tString CXString)\n\t\t\tthrows IllegalArgumentException, NdexException, SQLException, InterruptedException {\n \t\n\t\tUUID networkUUID = UUID.fromString(networkId);\n\t\ttry (NetworkDAO dao = new NetworkDAO()) {\n\t\t\tif (!dao.isAdmin(networkUUID, getLoggedInUserId()))\n\t\t\t\tthrow new UnauthorizedOperationException(\"User is not admin of this network.\");\n\n\t\t\tif (dao.networkIsLocked(networkUUID, 10))\n\t\t\t\tthrow new NetworkConcurrentModificationException();\n\n\t\t\tif (!dao.networkIsValid(networkUUID))\n\t\t\t\tthrow new InvalidNetworkException();\n\n\t\t\tString cxFilePath = Configuration.getInstance().getNdexRoot() + \"/data/\" + networkId + \"/sample.cx\";\n\n\t\t\ttry (FileWriter w = new FileWriter(cxFilePath)) {\n\t\t\t\tw.write(CXString);\n\t\t\t\tdao.setFlag(networkUUID, \"has_sample\", true);\n\t\t\t\tdao.commit();\n\t\t\t} catch (IOException e) {\n\t\t\t\tthrow new NdexException(\"Failed to write sample network of \" + networkId + \": \" + e.getMessage(), e);\n\t\t\t}\n\t\t}\n\t} \n\t\n\t\n\n\tprivate class CXAspectElementsWriterThread extends Thread {\n\t\tprivate OutputStream o;\n\t//\tprivate String networkId;\n\t\tprivate FileInputStream in;\n\t//\tprivate String aspect;\n\t\tprivate int limit;\n\t\tpublic CXAspectElementsWriterThread (OutputStream out, FileInputStream inputStream, /*String aspectName,*/ int limit) {\n\t\t\to = out;\n\t\t//\tthis.networkId = networkId;\n\t\t//\taspect = aspectName;\n\t\t\tthis.limit = limit;\n\t\t\tin = inputStream;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic void run() {\n\n\t\t\ttry {\n\t\t\t\tOpaqueAspectIterator asi = new OpaqueAspectIterator(in);\n\t\t\t\ttry (CXAspectWriter wtr = new CXAspectWriter (o)) {\n\t\t\t\t\tfor ( int i = 0 ; i < limit && asi.hasNext() ; i++) {\n\t\t\t\t\t\twtr.writeCXElement(asi.next());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (IOException e) {\n\t\t\t\t\tlogger.error(\"IOException in CXAspectElementWriterThread: \" + e.getMessage());\n\t\t\t} catch (Exception e1) {\n\t\t\t\tlogger.error(\"Ndex exception: \" + e1.getMessage());\n\t\t\t} finally {\n\t\t\t\ttry {\n\t\t\t\t\to.flush();\n\t\t\t\t\to.close();\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\tlogger.error(\"Failed to close outputstream in CXElementWriterWriterThread\");\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t} \n\t\t}\n\t\t\n\t}\n\n\n\n\t/**************************************************************************\n\t * Retrieves array of user membership objects\n\t *\n\t * @param networkId\n\t * The network ID.\n\t * @throws IllegalArgumentException\n\t * Bad input.\n\t * @throws ObjectNotFoundException\n\t * The group doesn't exist.\n\t * @throws NdexException\n\t * Failed to query the database.\n\t * @throws SQLException \n\t **************************************************************************/\n\n\t@GET\n\t@Path(\"/{networkid}/permission\")\n\t@Produces(\"application/json\")\n\n\tpublic Map getNetworkUserMemberships(\n\t\t\t@PathParam(\"networkid\") final String networkId,\n\t\t @QueryParam(\"type\") String sourceType,\n\t\t\t@QueryParam(\"permission\") final String permissions ,\n\t\t\t@DefaultValue(\"0\") @QueryParam(\"start\") int skipBlocks,\n\t\t\t@DefaultValue(\"100\") @QueryParam(\"size\") int blockSize) throws NdexException, SQLException {\n\t\t\n\t\tPermissions permission = null;\n\t\tif ( permissions != null ){\n\t\t\tpermission = Permissions.valueOf(permissions.toUpperCase());\n\t\t} \n\t\t\n\t\tUUID networkUUID = UUID.fromString(networkId);\n\t\t\n\t\t\n\t\tboolean returnUsers = true;\n\t\tif ( sourceType != null ) {\n\t\t\tif ( sourceType.toLowerCase().equals(\"group\")) \n\t\t\t\treturnUsers = false;\n\t\t\telse if ( !sourceType.toLowerCase().equals(\"user\"))\n\t\t\t\tthrow new NdexException(\"Invalid parameter 'type' \" + sourceType + \" received, it can only be 'user' or 'group'.\");\n\t\t} else \n\t\t\tthrow new NdexException(\"Parameter 'type' is required in this function.\");\n\t\t\n\t\ttry (NetworkDAO networkDao = new NetworkDAO()) {\n\t\t\tif ( !networkDao.isAdmin(networkUUID, getLoggedInUserId()) ) \n\t\t\t\tthrow new UnauthorizedOperationException(\"Authenticate user is not the admin of this network.\");\n\t\t\t\n\t\t\tMap result = returnUsers?\n\t\t\t\t\tnetworkDao.getNetworkUserPermissions(networkUUID, permission, skipBlocks, blockSize):\n\t\t\t\t\tnetworkDao.getNetworkGroupPermissions(networkUUID,permission,skipBlocks,blockSize);\n\t\t\t\t\t\n\t\t\treturn result;\n\t\t} \n\t}\n\n\t\n\t@DELETE\n\t@Path(\"/{networkid}/permission\")\n\t@Produces(\"application/json\")\n\n\tpublic int deleteNetworkPermission(\n\t\t\t@PathParam(\"networkid\") final String networkIdStr,\n\t\t\t@QueryParam(\"userid\") String userIdStr,\n\t\t\t@QueryParam(\"groupid\") String groupIdStr\t\t\n\t\t\t)\n\t\t\tthrows IllegalArgumentException, NdexException, IOException, SQLException {\n\t\t\t\t\n\t\tUUID networkId = UUID.fromString(networkIdStr);\n\n\t\tUUID userId = null;\n\t\tif ( userIdStr != null)\n\t\t\tuserId = UUID.fromString(userIdStr);\n\t\tUUID groupId = null;\n\t\tif ( groupIdStr != null)\n\t\t\tgroupId = UUID.fromString(groupIdStr);\n\t\t\n\t\tif ( userId == null && groupId == null)\n\t\t\tthrow new NdexException (\"Either userid or groupid parameter need to be set for this function.\");\n\t\tif ( userId !=null && groupId != null)\n\t\t\tthrow new NdexException (\"userid and gorupid can't both be set for this function.\");\n\t\t\n\t\t\n\t\ttry (NetworkDAO networkDao = new NetworkDAO()){ \n\t\t//\tUser user = getLoggedInUser();\n\t\t//\tnetworkDao.checkPermissionOperationCondition(networkId, user.getExternalId());\n\t\t\t\n\t\t\tif (!networkDao.isAdmin(networkId,getLoggedInUserId())) {\n\t\t\t\tif ( userId != null && !userId.equals(getLoggedInUserId())) {\n\t\t\t\t\tthrow new UnauthorizedOperationException(\"Unable to delete network permisison: user need to be admin of this network or grantee of this permission.\");\n\t\t\t\t}\n\t\t\t\tif ( groupId!=null ) {\t\n\t\t\t\t\tthrow new UnauthorizedOperationException(\"Unable to delete network permission: user is not an admin of this network.\");\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif( !networkDao.networkIsValid(networkId))\n\t\t\t\tthrow new InvalidNetworkException();\n\t\t\n\t\t\tint count;\n\t\t\tif ( userId !=null)\n\t\t\t\tcount = networkDao.revokeUserPrivilege(networkId, userId);\n\t\t\telse \n\t\t\t\tcount = networkDao.revokeGroupPrivilege(networkId, groupId);\n\n\t\t\t// update the solr Index\n\t\t\tNetworkIndexLevel lvl = networkDao.getIndexLevel(networkId);\n\t\t\tif ( lvl != NetworkIndexLevel.NONE) {\n\t\t\t\tnetworkDao.setFlag(networkId, \"iscomplete\", false); \n\t\t\t\tnetworkDao.commit();\n\t\t\t\tNdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkId,SolrIndexScope.global,false,null,lvl, false));\n\t\t\t}\n return count;\n\t\t} \n\t}\n\t\n\t/*\n\t *\n\t * Operations on Network permissions\n\t * \n\t */\n\n\n\t@PUT\n\t@Path(\"/{networkid}/permission\")\n\t@Produces(\"application/json\")\n\tpublic int updateNetworkPermission(\n\t\t\t@PathParam(\"networkid\") final String networkIdStr,\n\t\t\t@QueryParam(\"userid\") String userIdStr,\n\t\t\t@QueryParam(\"groupid\") String groupIdStr,\t\t\t\n\t\t\t@QueryParam(\"permission\") final String permissions \n\t\t\t)\n\t\t\tthrows IllegalArgumentException, NdexException, IOException, SQLException {\n\n\t\tlogger.info(\"[start: Updating membership for network {}]\", networkIdStr);\n\t\tUUID networkId = UUID.fromString(networkIdStr);\n\t\t\n\t\tUUID userId = null;\n\t\tif ( userIdStr != null)\n\t\t\tuserId = UUID.fromString(userIdStr);\n\t\tUUID groupId = null;\n\t\tif ( groupIdStr != null)\n\t\t\tgroupId = UUID.fromString(groupIdStr);\n\t\t\n\t\tif ( userId == null && groupId == null)\n\t\t\tthrow new NdexException (\"Either userid or groupid parameter need to be set for this function.\");\n\t\tif ( userId !=null && groupId != null)\n\t\t\tthrow new NdexException (\"userid and gorupid can't both be set for this function.\");\n\t\t\n\t\tif ( permissions == null)\n\t\t\tthrow new NdexException (\"permission parameter is required in this function.\");\n\t\tPermissions p = Permissions.valueOf(permissions.toUpperCase());\n\t\t\n\t\ttry (NetworkDAO networkDao = new NetworkDAO()){\n\t\t\t\n\t\t\tUser user = getLoggedInUser();\n\t\t\t\n\t\t\tif (!networkDao.isAdmin(networkId,user.getExternalId())) {\n\t\t\t\tthrow new UnauthorizedOperationException(\"Unable to update network permission: user is not an admin of this network.\");\n\t\t\t}\n\t\t\t\n\t\t\tif ( !networkDao.networkIsValid(networkId))\n \t\t\tthrow new InvalidNetworkException();\n\t\t\t\n\t\t\t\n\t\t\tint count;\n\t\t\tif ( userId!=null) {\n\t\t\t\tcount = networkDao.grantPrivilegeToUser(networkId, userId, p);\n\t\t\t} else \n\t\t\t\tcount = networkDao.grantPrivilegeToGroup(networkId, groupId, p);\n\t\t\t//networkDao.commit();\n\t\t\t\n\t\t\t// update the solr Index\n\t\t\tNetworkIndexLevel lvl = networkDao.getIndexLevel(networkId);\n\t\t\tif ( lvl != NetworkIndexLevel.NONE) {\n\t\t\t\tnetworkDao.setFlag(networkId, \"iscomplete\", false);\n\t\t\t\tnetworkDao.commit();\n\t\t\t\tNdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkId,SolrIndexScope.global,false,null,lvl, false));\n\t\t\t}\n\t\t\t\n\t\t\tlogger.info(\"[end: Updated permission for network {}]\", networkId);\n\t return count;\n\t\t} \n\t}\t\n\n\t\n\t@PUT\n\t@Path(\"/{networkid}/reference\")\n\t@Produces(\"application/json\")\n\tpublic void updateReferenceOnPreCertifiedNetwork(@PathParam(\"networkid\") final String networkId,\n\t\t\tMap reference) throws SQLException, NdexException, SolrServerException, IOException {\n\n\t\tUUID networkUUID = UUID.fromString(networkId);\n\t\tUUID userId = getLoggedInUser().getExternalId();\n\t\t\n\t\tif ( reference.get(\"reference\") == null) {\n\t\t\tthrow new BadRequestException(\"Field reference is missing in the object.\");\n\t\t}\n\n\t\ttry (NetworkDAO networkDao = new NetworkDAO()){\n\t\t\tif(networkDao.isAdmin(networkUUID, userId) ) {\n\n\t\t\t\tif ( networkDao.hasDOI(networkUUID) && (!networkDao.isCertified(networkUUID)) ) {\n\t\t\t\t\tList props = networkDao.getNetworkSummaryById(networkUUID).getProperties();\n\t\t\t\t\tboolean updated= false;\n\t\t\t\t\tfor ( NdexPropertyValuePair p : props ) {\n\t\t\t\t\t\tif ( p.getPredicateString().equals(\"reference\")) {\n\t\t\t\t\t\t\tp.setValue(reference.get(\"reference\"));\n\t\t\t\t\t\t\tupdated=true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif ( !updated) {\n\t\t\t\t\t\tprops.add(new NdexPropertyValuePair(\"reference\", reference.get(\"reference\")));\n\t\t\t\t\t}\n\t\t\t\t\tnetworkDao.updateNetworkProperties(networkUUID,props);\n\t\t\t\t\tnetworkDao.updateNetworkVisibility(networkUUID, VisibilityType.PUBLIC, true);\n\t\t\t\t\t//networkDao.setFlag(networkUUID, \"solr_indexed\", true);\n\t\t\t\t\tnetworkDao.setIndexLevel(networkUUID, NetworkIndexLevel.ALL);\n\t\t\t\t\tnetworkDao.setFlag(networkUUID, \"certified\", true);\n\t\t\t\t\t\n\t\t\t\t\tnetworkDao.setFlag(networkUUID, \"iscomplete\", false);\n\t\t\t\t\tnetworkDao.commit();\n\t\t\t\t\tNdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkUUID,SolrIndexScope.global,false,null,NetworkIndexLevel.ALL, false));\n\t\t\t\t\t\n\t\t\t\t} else {\n\t\t\t\t\tif ( networkDao.isCertified(networkUUID))\n\t\t\t\t\t\tthrow new ForbiddenOperationException(\"This network has already been certified, updating reference is not allowed.\");\n\t\t\t\t\t\n\t\t\t\t\tthrow new ForbiddenOperationException(\"This network doesn't have a DOI or a pending DOI request.\");\n\t\t\t\t}\n\t\t\t}\n\t\t\n\t\t}\t\n\t\t\n\t}\n\t\n\t@PUT\n\t@Path(\"/{networkid}/profile\")\n\t@Produces(\"application/json\")\n\n\tpublic void updateNetworkProfile(\n\t\t\t@PathParam(\"networkid\") final String networkId,\n\t\t\tfinal NetworkSummary partialSummary\n\t\t\t)\n throws NdexException, SQLException , IOException, IllegalArgumentException \n {\n\t\t\n\t\ttry (NetworkDAO networkDao = new NetworkDAO()){\n\n\t\t\tUser user = getLoggedInUser();\n\t\t\tUUID networkUUID = UUID.fromString(networkId);\n\t\n\t \t if(networkDao.isReadOnly(networkUUID)) {\n\t\t\t\tthrow new NdexException (\"Can't update readonly network.\");\t\t\t\t\n\t\t\t} \n\t\t\t\n\t\t\tif ( !networkDao.isWriteable(networkUUID, user.getExternalId())) {\n\t\t throw new UnauthorizedOperationException(\"User doesn't have write permissions for this network.\");\n\t\t\t} \n\t\t\t\n\t\t\tMap newValues = new HashMap<> ();\n//\t List entityProperties = new ArrayList<>();\n\n\t\t\tif ( partialSummary.getName() != null) {\n\t\t\t\tnewValues.put(NdexClasses.Network_P_name, partialSummary.getName());\n//\t\t\t entityProperties.add( new SimplePropertyValuePair(\"dc:title\", partialSummary.getName()) );\n\t\t\t}\n\t\t\t\t\t\n\t\t\tif ( partialSummary.getDescription() != null) {\n\t\t\t\t\tnewValues.put( NdexClasses.Network_P_desc, partialSummary.getDescription());\n//\t\t entityProperties.add( new SimplePropertyValuePair(\"description\", partialSummary.getDescription()) );\n\t\t\t}\n\t\t\t\t\n\t\t\tif ( partialSummary.getVersion()!=null ) {\n\t\t\t\t\tnewValues.put( NdexClasses.Network_P_version, partialSummary.getVersion());\n//\t\t entityProperties.add( new SimplePropertyValuePair(\"version\", partialSummary.getVersion()) );\n\t\t\t}\n\n\t\t\tif ( newValues.size() > 0 ) { \n\t\t\t\t\n\t\t\t\tif (!networkDao.networkIsValid(networkUUID))\n\t\t\t\t\tthrow new InvalidNetworkException();\n\n\t\t\t\ttry {\n\t\t\t\t\tif ( networkDao.networkIsLocked(networkUUID,10)) {\n\t\t\t\t\t\tthrow new NetworkConcurrentModificationException ();\n\t\t\t\t\t}\n\t\t\t\t} catch (InterruptedException e2) {\n\t\t\t\t\te2.printStackTrace();\n\t\t\t\t\tthrow new NdexException(\"Failed to check network lock: \" + e2.getMessage());\n\t\t\t\t} \n\t\t\t\t\n\t\t\t\t\n\t\t\t\ttry {\n\t\t\t\t\tnetworkDao.lockNetwork(networkUUID);\n\t\t\t\t\n\t\t\t\t\tnetworkDao.updateNetworkProfile(networkUUID, newValues);\n\t\t\t\t\t\n\t\t\t\t\t// recreate files and update db\n\t\t\t\t\tupdateNetworkAttributesAspect(networkDao, networkUUID);\n\n\t\t\t\t\tnetworkDao.unlockNetwork(networkUUID);\n\t\t\t\t\t\n\t\t\t\t\t// update the solr Index \n\t\t\t\t\tNetworkIndexLevel lvl = networkDao.getIndexLevel(networkUUID);\n\t\t\t\t\tif ( lvl != NetworkIndexLevel.NONE) {\n\t\t\t\t\t networkDao.setFlag(networkUUID, \"iscomplete\", false);\n\t\t\t\t\t networkDao.commit();\n\t\t\t\t\t NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkUUID,SolrIndexScope.global,false,null,lvl, false));\n\t\t\t\t\t} else {\n\t\t\t\t\t\t networkDao.setFlag(networkUUID, \"iscomplete\", true);\n\t\t\t\t\t\t networkDao.commit();\n\t\t\t\t\t}\n\t\t\t\t} catch ( SQLException | IOException | IllegalArgumentException |NdexException e ) {\n\t\t\t\t\tnetworkDao.rollback();\n\t\t\t\t\ttry {\n\t\t\t\t\t\tnetworkDao.unlockNetwork(networkUUID);\n\t\t\t\t\t} catch (SQLException e1) {\n\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\te1.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t\tthrow e;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t} \n\t}\n\n\t\n\t/**\n\t * \n\t * @param pathPrefix path of the directory that has the CxAttributeDeclaration aspect file. \n\t * It should end with \"/\"\n\t * @return the declaration object. null if network has no attributes declared.\n\t * @throws JsonParseException\n\t * @throws JsonMappingException\n\t * @throws IOException\n\t */\n\tprotected static CxAttributeDeclaration getAttrDeclarations(String pathPrefix) throws JsonParseException, JsonMappingException, IOException {\t\t\t\n\t\tFile attrDeclF = new File ( pathPrefix + CxAttributeDeclaration.ASPECT_NAME);\n\t\tCxAttributeDeclaration[] declarations = null;\n\t\tif ( attrDeclF.exists() ) {\n\t\t\tObjectMapper om = new ObjectMapper();\n\t\t\tdeclarations = om.readValue(attrDeclF, CxAttributeDeclaration[].class);\n\t\t}\n\n\t\tif ( declarations != null)\n\t\t\treturn declarations[0];\n\t\t\n\t\treturn null;\n\t}\n\t\n\t// update the networkAttributes aspect file and also update the metadata in the db.\n\tprotected static void updateNetworkAttributesAspect(NetworkDAO networkDao, UUID networkUUID) throws JsonParseException, JsonMappingException, SQLException, IOException, NdexException {\n\t\tNetworkSummary fullSummary = networkDao.getNetworkSummaryById(networkUUID);\n\t\tString aspectFilePath = Configuration.getInstance().getNdexRoot() + \"/data/\" + \n\t\t\t\tnetworkUUID.toString() + \"/\" + CXNetworkLoader.CX1AspectDir + \"/\" + NetworkAttributesElement.ASPECT_NAME;\n\t\tString cx2AspectDirPath = Configuration.getInstance().getNdexRoot() + \"/data/\" + \n\t\t\t\tnetworkUUID.toString() + \"/\" + CX2NetworkLoader.cx2AspectDirName + \"/\";\n\t\tString cx2AspectFilePath = cx2AspectDirPath + CxNetworkAttribute.ASPECT_NAME;\n\t\t\n\t\t//update the networkAttributes aspect in cx and cx2 \n\t\tList attrs = getNetworkAttributeAspectsFromSummary(fullSummary);\n\t\t\n\t\tCxAttributeDeclaration networkAttrDecl = null;\n\t\tif ( attrs.size() > 0 ) {\t\t\t\t\t\n\t\t\tAspectAttributeStat attributeStats = new AspectAttributeStat();\n\t\t\tCxNetworkAttribute cx2NetAttr = new CxNetworkAttribute();\n\n\t\t\t// write cx network attribute aspect file.\n\t\t\ttry (CXAspectWriter writer = new CXAspectWriter(aspectFilePath) ) {\n\t\t\t\tfor ( NetworkAttributesElement e : attrs) {\n\t\t\t\t\twriter.writeCXElement(e);\t\n\t\t\t\t\twriter.flush();\n\n\t\t\t\t\tattributeStats.addNetworkAttribute(e);\n\t\t\t\t\t\n\t\t\t\t\tObject attrValue = CXToCX2Converter.convertAttributeValue(e);\n\t\t\t\t\tObject oldV = cx2NetAttr.getAttributes().put(e.getName(), attrValue);\n\t\t\t\t\tif ( oldV !=null)\n\t\t\t\t\t\tthrow new NdexException(\"Duplicated network attribute name found: \" + e.getName());\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t// write cx2 network attribute aspect file\n\t\t\tnetworkAttrDecl = attributeStats.createCxDeclaration();\n\t\t\t\n\t\t\ttry (CX2AspectWriter aspWtr = new CX2AspectWriter<>(cx2AspectDirPath + CxNetworkAttribute.ASPECT_NAME)) {\n\t\t\t\taspWtr.writeCXElement(cx2NetAttr);\n\t\t\t}\n\t\t\t\n\t\t} else { // remove the aspect file if it exists\n\t\t\tFile f = new File ( aspectFilePath);\n\t\t\tif ( f.exists())\n\t\t\t\tf.delete();\n\t\t\tf = new File(cx2AspectFilePath);\n\t\t\tif ( f.exists())\n\t\t\t\tf.delete();\n\t\t}\n\t\t\n\t\t\t\t\n\t\t//update cx and cx2 metadata for networkAttributes\n\t\tMetaDataCollection metadata = networkDao.getMetaDataCollection(networkUUID);\n\t\tList cx2metadata = networkDao.getCxMetaDataList(networkUUID);\n\t\tif ( attrs.size() == 0 ) {\n\t\t\tmetadata.remove(NetworkAttributesElement.ASPECT_NAME);\n\t\t\tcx2metadata.removeIf( n -> n.getName().equals(CxNetworkAttribute.ASPECT_NAME));\n\t\t} else {\n\t\t\tMetaDataElement elmt = metadata.getMetaDataElement(NetworkAttributesElement.ASPECT_NAME);\n\t\t\tif ( elmt == null) {\n\t\t\t\telmt = new MetaDataElement(NetworkAttributesElement.ASPECT_NAME, \"1.0\");\n\t\t\t}\n\t\t\telmt.setElementCount(Long.valueOf(attrs.size()));\n\t\t\t\n\t\t\tif ( ! cx2metadata.stream().anyMatch(\n\t\t\t\t\t(CxMetadata n) -> n.getName().equals(CxNetworkAttribute.ASPECT_NAME) )) {\n\t\t\t\n\t\t\t\tCxMetadata m = new CxMetadata(CxNetworkAttribute.ASPECT_NAME, 1);\n\t\t\t\tcx2metadata.add(m);\n\t\t\t}\n\t\t}\n\t\tnetworkDao.updateMetadataColleciton(networkUUID, metadata);\n\n\t\t\n\t\t// update attribute declaration aspect and cx2 metadata\n\t\tCxAttributeDeclaration decls = getAttrDeclarations(cx2AspectDirPath);\n\t\tif ( decls == null) {\n\t\t\tif ( networkAttrDecl != null ) { // has new attributes\n\t\t\t\tdecls = new CxAttributeDeclaration();\n\t\t\t\tdecls.add(CxNetworkAttribute.ASPECT_NAME,\n\t\t\t\t\t\tnetworkAttrDecl.getAttributesInAspect(CxNetworkAttribute.ASPECT_NAME));\n\t\t\t\tcx2metadata.add(new CxMetadata(CxAttributeDeclaration.ASPECT_NAME, 1));\n\t\t\t} \n\t\t} else {\n\t\t\tif ( networkAttrDecl != null) {\n\t\t\t\tdecls.getDeclarations().put(CxNetworkAttribute.ASPECT_NAME, \n\t\t\t\t\t\tnetworkAttrDecl.getAttributesInAspect(CxNetworkAttribute.ASPECT_NAME));\n\t\t\t} else { \n\t\t\t\tdecls.removeAspectDeclaration(CxNetworkAttribute.ASPECT_NAME);\n\t\t\t cx2metadata.removeIf((CxMetadata m) -> m.getName().equals(CxAttributeDeclaration.ASPECT_NAME));\n\t\t\t} \n\t\t}\n\n\t\tnetworkDao.setCxMetadata(networkUUID, cx2metadata);\n\t\ttry (CX2AspectWriter aspWtr = new \n\t\t\t\tCX2AspectWriter<>(cx2AspectDirPath + CxAttributeDeclaration.ASPECT_NAME)) {\n\t\t\taspWtr.writeCXElement(decls);\n\t\t}\n\t\t\n\t\t//Recreate the CX file \t\t\t\t\t\n\t\tCXNetworkFileGenerator g = new CXNetworkFileGenerator(networkUUID, /*fullSummary,*/ metadata /*, newProv*/);\n\t\tg.reCreateCXFile();\n \n\t\t//Recreate cx2 file\n\t\tCX2NetworkFileGenerator g2 = new CX2NetworkFileGenerator(networkUUID, cx2metadata);\n\t\tg2.createCX2File();\n\n\t}\n\n\t@PUT\n\t@Path(\"/{networkid}/summary\")\n\t@Produces(\"application/json\")\n\tpublic void updateNetworkSummary(\n\t\t\t@PathParam(\"networkid\") final String networkId,\n\t\t\tfinal NetworkSummary summary\n\t\t\t)\n throws NdexException, SQLException , IOException, IllegalArgumentException \n {\n\t\t\n\t\ttry (NetworkDAO networkDao = new NetworkDAO()){\n\n\t\t\tUser user = getLoggedInUser();\n\t\t\tUUID networkUUID = UUID.fromString(networkId);\n\t\n\t \t if(networkDao.isReadOnly(networkUUID)) {\n\t\t\t\tthrow new NdexException (\"Can't update readonly network.\");\t\t\t\t\n\t\t\t} \n\t\t\t\n\t\t\tif ( !networkDao.isWriteable(networkUUID, user.getExternalId())) {\n\t\t throw new UnauthorizedOperationException(\"User doesn't have write permissions for this network.\");\n\t\t\t} \n\t\t\t\n\t\t\tif (!networkDao.networkIsValid(networkUUID))\n\t\t\t\tthrow new InvalidNetworkException();\n\n\t\t\ttry {\n\t\t\t\t\tif ( networkDao.networkIsLocked(networkUUID,10)) {\n\t\t\t\t\t\tthrow new NetworkConcurrentModificationException ();\n\t\t\t\t\t}\n\t\t\t} catch (InterruptedException e2) {\n\t\t\t\t\te2.printStackTrace();\n\t\t\t\t\tthrow new NdexException(\"Failed to check network lock: \" + e2.getMessage());\n\t\t\t} \n\t\t\t\t\n\t\t\t\t\n\t\t\ttry {\n\t\t\t\tnetworkDao.lockNetwork(networkUUID);\n\t\t\t\t\n\t\t\t\tnetworkDao.updateNetworkSummary(networkUUID, summary);\n\t\t\t\t\n\t\t\t\t//recreate files and update db\n\t\t\t\tupdateNetworkAttributesAspect(networkDao, networkUUID);\n\t\t\t\t\t\n\t\t\t\tnetworkDao.unlockNetwork(networkUUID);\n\t\t\t\t\t\n\t\t\t\t// update the solr Index\n\t\t\t\tNetworkIndexLevel lvl = networkDao.getIndexLevel(networkUUID);\n\t\t\t\tif ( lvl != NetworkIndexLevel.NONE) {\n\t\t\t\t\t\t networkDao.setFlag(networkUUID, \"iscomplete\", false);\n\t\t\t\t\t\t networkDao.commit();\n\t\t\t\t\t\t NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkUUID,SolrIndexScope.global,false,null,lvl,false));\n\t\t\t\t} else {\n\t\t\t\t\t\t networkDao.setFlag(networkUUID, \"iscomplete\", true);\n\t\t\t\t\t\t networkDao.commit();\n\t\t\t\t}\n\t\t\t} catch ( SQLException | IOException | IllegalArgumentException |NdexException e ) {\n\t\t\t\t\tnetworkDao.rollback();\n\t\t\t\t\ttry {\n\t\t\t\t\t\tnetworkDao.unlockNetwork(networkUUID);\n\t\t\t\t\t} catch (SQLException e1) {\n\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\te1.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t\tthrow e;\n\t\t\t}\n\t\t\t\t\n\t\t}\n\t\t\n\t}\n\n\n\n\n\t\n @PUT\n @Path(\"/{networkid}\")\n @Consumes(\"multipart/form-data\")\n @Produces(\"application/json\")\n\n public void updateCXNetwork(final @PathParam(\"networkid\") String networkIdStr,\n \t\t @QueryParam(\"visibility\") String visibilityStr,\n\t\t @QueryParam(\"extranodeindex\") String fieldListStr, // comma seperated list\t\t\n \t\tMultipartFormDataInput input) throws Exception \n {\n \t VisibilityType visibility = null;\n\t\t if ( visibilityStr !=null) {\n\t\t\t visibility = VisibilityType.valueOf(visibilityStr);\n\t\t }\n\t\t \n\t\t Set extraIndexOnNodes = null;\n\t\t if ( fieldListStr != null) {\n\t\t\t extraIndexOnNodes = new HashSet<>(10);\n\t\t\t for ( String f: fieldListStr.split(\"\\\\s*,\\\\s*\") ) {\n\t\t\t\t extraIndexOnNodes.add(f);\n\t\t\t }\n\t\t }\n\t\t\n\t\ttry (UserDAO dao = new UserDAO()) {\n\t\t\t dao.checkDiskSpace(getLoggedInUserId());\n\t\t}\n \t\n UUID networkId = UUID.fromString(networkIdStr);\n\n // String ownerAccName = null;\n try ( NetworkDAO daoNew = new NetworkDAO() ) {\n User user = getLoggedInUser();\n \n try {\n\t \t if( daoNew.isReadOnly(networkId)) {\n\t\t\t\tthrow new NdexException (\"Can't update readonly network.\");\t\t\t\t\n\t\t\t} \n\t\t\t\n\t\t\tif ( !daoNew.isWriteable(networkId, user.getExternalId())) {\n\t\t throw new UnauthorizedOperationException(\"User doesn't have write permissions for this network.\");\n\t\t\t} \n\t\t\t\n\t\t\tif ( daoNew.networkIsLocked(networkId)) {\n\t\t\t\tdaoNew.close();\n\t\t\t\tthrow new NetworkConcurrentModificationException ();\n\t\t\t} \n\t\t\t\n\t\t\tdaoNew.lockNetwork(networkId);\n\t\t\t\t\t\t\n\t UUID tmpNetworkId = storeRawNetworkFromMultipart (input, cx1NetworkFileName);\n\n\t updateNetworkFromSavedFile( networkId, daoNew, tmpNetworkId);\n\t\t\t\n } catch (SQLException | NdexException | IOException e) {\n \t e.printStackTrace();\n \t daoNew.rollback();\n \t daoNew.unlockNetwork(networkId); \n\n \t throw e;\n } \n\t\t\t\n } \n \t \n\t NdexServerQueue.INSTANCE.addSystemTask(new CXNetworkLoadingTask(networkId, /* ownerAccName,*/ true, visibility,extraIndexOnNodes));\n }\n\n\n @PUT\n @Path(\"/{networkid}\")\n @Consumes(MediaType.APPLICATION_JSON)\n @Produces(\"application/json\")\n\n public void updateNetworkJson(final @PathParam(\"networkid\") String networkIdStr,\n \t\t @QueryParam(\"visibility\") String visibilityStr,\n\t\t @QueryParam(\"extranodeindex\") String fieldListStr // comma seperated list\t\t\n \t\t) throws Exception \n {\n \t VisibilityType visibility = null;\n\t\t if ( visibilityStr !=null) {\n\t\t\t visibility = VisibilityType.valueOf(visibilityStr);\n\t\t }\n\t\t \n\t\t Set extraIndexOnNodes = null;\n\t\t if ( fieldListStr != null) {\n\t\t\t extraIndexOnNodes = new HashSet<>(10);\n\t\t\t for ( String f: fieldListStr.split(\"\\\\s*,\\\\s*\") ) {\n\t\t\t\t extraIndexOnNodes.add(f);\n\t\t\t }\n\t\t }\n \t\n UUID networkId = UUID.fromString(networkIdStr);\n\n // String ownerAccName = null;\n try ( NetworkDAO daoNew = lockNetworkForUpdate(networkId) ) {\n \t\n\t\t\ttry (InputStream in = this.getInputStreamFromRequest()) {\n\t\t\t\t\tUUID tmpNetworkId = storeRawNetworkFromStream(in, cx1NetworkFileName);\n\n\t\t\t\t\tupdateNetworkFromSavedFile(networkId, daoNew, tmpNetworkId);\t\t\t\t\n\t\t\t\n } catch (SQLException | NdexException | IOException e) {\n \t daoNew.rollback();\n \t daoNew.unlockNetwork(networkId); \n\n \t throw e;\n } \n\t\t\t\n\t\t\t\n } \n \t \n\t NdexServerQueue.INSTANCE.addSystemTask(new CXNetworkLoadingTask(networkId, /* ownerAccName,*/ true, visibility,extraIndexOnNodes));\n\t // return networkIdStr; \n }\n\n\n\n\tprivate static void updateNetworkFromSavedFile(UUID networkId, NetworkDAO daoNew,\n\t\t\tUUID tmpNetworkId) throws SQLException, NdexException, IOException, JsonParseException,\n\t\t\tJsonMappingException, ObjectNotFoundException {\n\t\tString cxFileName = Configuration.getInstance().getNdexRoot() + \"/data/\" + tmpNetworkId.toString()\n\t\t\t\t+ \"/network.cx\";\n\t\tlong fileSize = new File(cxFileName).length();\n\n\t\tdaoNew.clearNetworkSummary(networkId, fileSize);\n\n\t\tjava.nio.file.Path src = Paths\n\t\t\t\t.get(Configuration.getInstance().getNdexRoot() + \"/data/\" + tmpNetworkId);\n\t\tjava.nio.file.Path tgt = Paths\n\t\t\t\t.get(Configuration.getInstance().getNdexRoot() + \"/data/\" + networkId);\n\t\tFileUtils.deleteDirectory(\n\t\t\t\tnew File(Configuration.getInstance().getNdexRoot() + \"/data/\" + networkId));\n\t\tFiles.move(src, tgt, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);\n\n\t\tdaoNew.commit();\n\t}\n \n \n /**\n * This function updates aspects of a network. The payload is a CX document which contains the aspects (and their metadata that we will use\n * to update the network). If an aspect only has metadata but no actual data, an Exception will be thrown.\n * @param networkIdStr\n * @param input\n * @throws Exception\n */\n @PUT\n @Path(\"/{networkid}/aspects\")\n @Consumes(\"multipart/form-data\")\n @Produces(\"application/json\")\n public void updateCXNetworkAspects(final @PathParam(\"networkid\") String networkIdStr,\n \t\tMultipartFormDataInput input) throws Exception \n {\n \t\n \ttry (UserDAO dao = new UserDAO()) {\n\t\t\t dao.checkDiskSpace(getLoggedInUserId());\n\t\t}\n \t\n UUID networkId = UUID.fromString(networkIdStr);\n\n // String ownerAccName = null;\n try ( NetworkDAO daoNew = new NetworkDAO() ) {\n User user = getLoggedInUser();\n \n\t \t if( daoNew.isReadOnly(networkId)) {\n\t\t\t\tthrow new NdexException (\"Can't update readonly network.\");\t\t\t\t\n\t\t\t} \n\t\t\t\n\t\t\tif ( !daoNew.isWriteable(networkId, user.getExternalId())) {\n\t\t throw new UnauthorizedOperationException(\"User doesn't have write permissions for this network.\");\n\t\t\t} \n\t\t\t\n\t\t\tif ( daoNew.networkIsLocked(networkId)) {\n\t\t\t\tdaoNew.close();\n\t\t\t\tthrow new NetworkConcurrentModificationException ();\n\t\t\t} \n\t\t\t\n\t\t\tdaoNew.lockNetwork(networkId);\n\t\t\t\n\t//\t\townerAccName = daoNew.getNetworkOwnerAcc(networkId);\n\t\t\t\n\t UUID tmpNetworkId = storeRawNetworkFromMultipart (input, cx1NetworkFileName); //network stored as a temp network\n\t \n\t \tupdateNetworkFromSavedAspects(networkId, daoNew, tmpNetworkId);\n\t\t\t\n } \n }\n \n @PUT\n @Path(\"/{networkid}/aspects\")\n @Consumes(MediaType.APPLICATION_JSON)\n @Produces(\"application/json\")\n public void updateAspectsJson(final @PathParam(\"networkid\") String networkIdStr\n \t\t) throws Exception \n {\n \t\n \ttry (UserDAO dao = new UserDAO()) {\n\t\t\t dao.checkDiskSpace(getLoggedInUserId());\n\t\t}\n \t\n UUID networkId = UUID.fromString(networkIdStr);\n\n // String ownerAccName = null;\n try ( NetworkDAO daoNew = new NetworkDAO() ) {\n User user = getLoggedInUser();\n \n\t \t if( daoNew.isReadOnly(networkId)) {\n\t\t\t\tthrow new NdexException (\"Can't update readonly network.\");\t\t\t\t\n\t\t\t} \n\t\t\t\n\t\t\tif ( !daoNew.isWriteable(networkId, user.getExternalId())) {\n\t\t throw new UnauthorizedOperationException(\"User doesn't have write permissions for this network.\");\n\t\t\t} \n\t\t\t\n\t\t\tif ( daoNew.networkIsLocked(networkId)) {\n\t\t\t\tdaoNew.close();\n\t\t\t\tthrow new NetworkConcurrentModificationException ();\n\t\t\t} \n\t\t\t\n\t\t\tdaoNew.lockNetwork(networkId);\n\t\t\t\n\t//\t\townerAccName = daoNew.getNetworkOwnerAcc(networkId);\n\t\t\ttry (InputStream in = this.getInputStreamFromRequest()) {\n\n\t UUID tmpNetworkId = storeRawNetworkFromStream(in, cx1NetworkFileName); //network stored as a temp network\n\t \n\t \tupdateNetworkFromSavedAspects( networkId, daoNew, tmpNetworkId);\n\t\t\t}\n } \n }\n\n\n\n\tprivate static void updateNetworkFromSavedAspects( UUID networkId, NetworkDAO daoNew,\n\t\t\tUUID tmpNetworkId) throws SQLException, IOException {\n\t\ttry ( CXNetworkAspectsUpdater aspectUpdater = new CXNetworkAspectsUpdater(networkId, /*ownerAccName,*/daoNew, tmpNetworkId) ) {\n\t\t\t\n\t\t\taspectUpdater.update();\n\n\t\t} catch ( IOException | NdexException | SQLException | RuntimeException e1) {\n\t\t\t\tlogger.error(\"Error occurred when updating aspects of network \" + networkId + \": \" + e1.getMessage());\n\t\t\t\te1.printStackTrace();\n\t\t\t\tdaoNew.setErrorMessage(networkId, e1.getMessage());\n\t\t\t\tdaoNew.unlockNetwork(networkId); \t\t\t\t \t\t\n\t\t} \n\t\t \n\t\tFileUtils.deleteDirectory(new File(Configuration.getInstance().getNdexRoot() + \"/data/\" + tmpNetworkId.toString()));\n\t\t \n\t\tdaoNew.unlockNetwork(networkId);\n\t}\n \n\t@DELETE\n\t@Path(\"/{networkid}\")\n\t@Produces(\"application/json\")\n\n\tpublic void deleteNetwork(final @PathParam(\"networkid\") String id) throws NdexException, SQLException {\n\t\t \n\t\ttry (NetworkDAO networkDao = new NetworkDAO()) {\n\t\t\tUUID networkId = UUID.fromString(id);\n\t\t\tUUID userId = getLoggedInUser().getExternalId();\n\t\t\tif(networkDao.isAdmin(networkId, userId) ) {\n\t\t\t\tif (!networkDao.isReadOnly(networkId) ) {\n\t\t\t\t\tif ( !networkDao.networkIsLocked(networkId)) {\n\t\t\t\t\t/*\n\t\t\t\t\t\tNetworkGlobalIndexManager globalIdx = new NetworkGlobalIndexManager();\n\t\t\t\t\t\tglobalIdx.deleteNetwork(id);\n\t\t\t\t\t\ttry (SingleNetworkSolrIdxManager idxManager = new SingleNetworkSolrIdxManager(id)) {\n\t\t\t\t\t\t\tidxManager.dropIndex();\n\t\t\t\t\t\t}\t\n\t\t\t\t\t*/\t\n\t\t\t\t\t\tnetworkDao.deleteNetwork(UUID.fromString(id), getLoggedInUser().getExternalId());\n\t\t\t\t\t\tnetworkDao.commit();\n\n\t\t\t\t\t\t// move the row network to archive folder and delete the folder\n\t\t\t\t\t String pathPrefix = Configuration.getInstance().getNdexRoot() + \"/data/\" + networkId.toString();\n\t\t\t\t /*String archivePath = Configuration.getInstance().getNdexRoot() + \"/data/_archive/\";\n\t\t\t\t \n\t\t\t\t File archiveDir = new File(archivePath);\n\t\t\t\t if (!archiveDir.exists())\n\t\t\t\t \t\tarchiveDir.mkdir();\n\t\t\t\t \n\t\t\t\t \n\t\t\t\t java.nio.file.Path src = Paths.get(pathPrefix+ \"/network.cx\"); \n\t\t\t\t\t\tjava.nio.file.Path tgt = Paths.get(archivePath + \"/\" + networkId.toString() + \".cx\");\n\t\t\t\t\t\t*/\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t//\tFiles.move(src, tgt, StandardCopyOption.ATOMIC_MOVE); \t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\tFileUtils.deleteDirectory(new File(pathPrefix));\n\t\t\t\t\t\t} catch (IOException e) {\n\t\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t\t\tthrow new NdexException(\"Failed to delete directory. Error: \" + e.getMessage());\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tNdexServerQueue.INSTANCE.addSystemTask(new SolrTaskDeleteNetwork(networkId));\n\t\t\t\t\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tthrow new NetworkConcurrentModificationException ();\n\t\t\t\t}\n\t\t\t\t throw new NdexException(\"Can't delete a read-only network.\");\n\t\t\t}\n\t\t\t//TODO: need to check if the network actually exists and give an 404 error for that case.\n\t\t\tthrow new NdexException(\"Only network owner can delete a network.\");\t\n\t\t} catch ( IOException e ) {\n\t\t\tthrow new NdexException (\"Error occurred when deleting network: \" + e.getMessage(), e);\n\t\t}\n\t\t\t\n\t}\n\t\n\n\t/* *************************************************************************\n\t * Saves an uploaded network file. Determines the type of file uploaded,\n\t * saves the file, and creates a task.\n\t *\n\t * Removing it. No longer relevent in v2.\n\t * @param uploadedNetwork\n\t * The uploaded network file.\n\t * @throws IllegalArgumentException\n\t * Bad input.\n\t * @throws NdexException\n\t * Failed to parse the file, or create the network in the\n\t * database.\n\t * @throws IOException \n\t * @throws SQLException \n\t **************************************************************************/\n\t/*\n\t * refactored to support non-transactional database operations\n\t */\n/*\t@POST\n\t@Path(\"/upload\")\n\t@Consumes(\"multipart/form-data\")\n\t@Produces(\"application/json\")\n\tpublic Task uploadNetwork( MultipartFormDataInput input) \n //@MultipartForm UploadedFile uploadedNetwork)\n\t\t\tthrows IllegalArgumentException, SecurityException, NdexException, IOException, SQLException {\n\n\n\t\t try (UserDAO dao = new UserDAO()) {\n\t\t\t dao.checkDiskSpace(getLoggedInUserId());\n\t\t }\n\t\t \n\t\tMap> uploadForm = input.getFormDataMap();\n\n\t\tList foo = uploadForm.get(\"filename\");\n\t\t\n\t\tString fname = \"\";\n\t\tfor (InputPart inputPart : foo)\n\t {\n\t // convert the uploaded file to inputstream and write it to disk\n\t fname += inputPart.getBodyAsString();\n\t }\n\n\t\tif (fname.length() <1) {\n\t\t\tthrow new NdexException (\"\");\n\t\t}\n\t\tString ext = FilenameUtils.getExtension(fname).toLowerCase();\n\n\t\tif ( !ext.equals(\"sif\") && !ext.equals(\"xbel\") && !ext.equals(\"xgmml\") && !ext.equals(\"owl\") && !ext.equals(\"cx\")\n\t\t\t\t&& !ext.equals(\"xls\") && ! ext.equals(\"xlsx\")) {\n\t\t\tthrow new NdexException(\n\t\t\t\t\t\"The uploaded file type is not supported; must be Excel, XGMML, SIF, BioPAX, cx or XBEL.\");\n\t\t}\n\t\t\n\t\tUUID taskId = NdexUUIDFactory.INSTANCE.createNewNDExUUID();\n\n\t\tfinal File uploadedNetworkPath = new File(Configuration.getInstance().getNdexRoot() +\n\t\t\t\t\"/uploaded-networks\");\n\t\tif (!uploadedNetworkPath.exists())\n\t\t\tuploadedNetworkPath.mkdir();\n\n\t\tString fileFullPath = uploadedNetworkPath.getAbsolutePath() + \"/\" + taskId + \".\" + ext;\n\n\t //Get file data to save\n\t List inputParts = uploadForm.get(\"fileUpload\");\n\n\t\t\n\t\tfinal File uploadedNetworkFile = new File(fileFullPath);\n\n\t\tif (!uploadedNetworkFile.exists())\n\t\t\ttry {\n\t\t\t\tuploadedNetworkFile.createNewFile();\n\t\t\t} catch (IOException e1) {\n\t\t\t\tthrow new NdexException (\"Failed to create file \" + fileFullPath + \" on server when uploading \" + \n\t\t\t\t\t\tfname + \": \" + e1.getMessage());\t\t\t\t\n\t\t\t}\n\n byte[] bytes = new byte[2048];\n\t\tfor (InputPart inputPart : inputParts)\n\t {\n\t \n\t // convert the uploaded file to inputstream and write it to disk\n\t InputStream inputStream = inputPart.getBody(InputStream.class, null);\n\t \n\t OutputStream out = new FileOutputStream(new File(fileFullPath));\n\n\t int read = 0;\n\t while ((read = inputStream.read(bytes)) != -1) {\n\t out.write(bytes, 0, read);\n\t }\n\t inputStream.close();\n\t out.flush();\n\t out.close();\n\t \n\t }\t\n\n\t\tTask processNetworkTask = new Task();\n\t\tprocessNetworkTask.setExternalId(taskId);\n\t\tprocessNetworkTask.setDescription(fname); //uploadedNetwork.getFilename());\n\t\tprocessNetworkTask.setTaskType(TaskType.PROCESS_UPLOADED_NETWORK);\n\t\tprocessNetworkTask.setPriority(Priority.LOW);\n\t\tprocessNetworkTask.setProgress(0);\n\t\tprocessNetworkTask.setResource(fileFullPath);\n\t\tprocessNetworkTask.setStatus(Status.QUEUED);\n\t\tprocessNetworkTask.setTaskOwnerId(this.getLoggedInUser().getExternalId());\n\n\t\ttry (TaskDAO dao = new TaskDAO()){\n\t\t\tdao.createTask(processNetworkTask);\n\t\t\tdao.commit();\t\t\n\t\t\t\n\t\t} catch (IllegalArgumentException iae) {\n\t\t\tlogger.error(\"[end: Exception caught:]{}\", iae);\n\t\t\tthrow iae;\n\t\t} catch (Exception e) {\n\t\t\tlogger.error(\"[end: Exception caught:]{}\", e);\n\t\t\tthrow new NdexException(e.getMessage());\n\t\t}\n\n\t\tlogger.info(\"[end: Uploading network file. Task for uploading network is created.]\");\n\t\treturn processNetworkTask;\n\t}\n\n*/\n\n\t@PUT\n\t@Path(\"/{networkid}/systemproperty\")\n\t@Produces(\"application/json\")\n\tpublic void setNetworkFlag(\n\t\t\t@PathParam(\"networkid\") final String networkIdStr,\n\t\t\tfinal Map parameters)\n\n\t\t\tthrows IllegalArgumentException, NdexException, SQLException, IOException {\n\t\t\n\t\t\taccLogger.info(\"[data]\\t[\" + parameters.entrySet()\n\t .stream()\n\t .map(entry -> entry.getKey() + \":\" + entry.getValue()).reduce(null, ((r,e) -> {String rr = r==null? e:r+\",\" +e; return rr;}))\n\t\t\t\t\t + \"]\" );\t\t\n\n\t\t\n\t\t\ttry (NetworkDAO networkDao = new NetworkDAO()) {\n\t\t\t\tUUID networkId = UUID.fromString(networkIdStr);\n\t\t\t\tif ( networkDao.hasDOI(networkId)) {\n\t\t\t\t\tif ( parameters.size() >1 || !parameters.containsKey(\"showcase\"))\n\t\t\t\t\t\tthrow new ForbiddenOperationException(\"Network with DOI can't be modified.\");\t\n\t\t\t\t}\t\n\t\t\t\tUUID userId = getLoggedInUser().getExternalId();\n\t\t\t\t\tif ( !networkDao.networkIsValid(networkId))\n\t\t\t\t\t\tthrow new InvalidNetworkException();\n\t\t\t\t\t\n\t\t\t\t\tif ( parameters.containsKey(readOnlyParameter)) {\n\t\t\t\t\t\tif (!networkDao.isAdmin(networkId, userId))\n\t\t\t\t\t\t\tthrow new UnauthorizedOperationException(\"Only network owner can set readOnly Parameter.\");\n\t\t\t\t\t\tboolean bv = ((Boolean)parameters.get(readOnlyParameter)).booleanValue();\n\t\t\t\t\t\tnetworkDao.setFlag(networkId, \"readonly\",bv);\t \n\t\t\t\t\t}\n\t\t\t\t\tif ( parameters.containsKey(\"visibility\")) {\n\t\t\t\t\t\tif (!networkDao.isAdmin(networkId, userId))\n\t\t\t\t\t\t\tthrow new UnauthorizedOperationException(\"Only network owner can set visibility Parameter.\");\n\t\t\t\t\t\t\n\t\t\t\t\t\tVisibilityType visType = VisibilityType.valueOf((String)parameters.get(\"visibility\"));\n\t\t\t\t\t\tnetworkDao.updateNetworkVisibility(networkId, visType, false);\n\t\t\t\t\t\tif ( !parameters.containsKey(\"index_level\")) {\n\t\t\t\t\t\t\tNetworkIndexLevel lvl = networkDao.getIndexLevel(networkId);\n\t\t\t\t\t\t\tnetworkDao.commit();\n\t\t\t\t\t\t\tif ( lvl != NetworkIndexLevel.NONE) {\n\t\t\t\t\t\t\t\tNdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkId,SolrIndexScope.global,false,null,lvl,false));\n\t\t\t\t\t\t\t} \n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t/*if ( parameters.containsKey(\"index\")) {\n\t\t\t\t\t\tboolean bv = ((Boolean)parameters.get(\"index\")).booleanValue();\n\t\t\t\t\t\tnetworkDao.setFlag(networkId, \"solr_indexed\",bv);\t \n\t\t\t\t\t\tif (bv) {\n\t\t\t\t\t\t\tnetworkDao.setFlag(networkId, \"iscomplete\",false);\t \t\t\t\t\n\t\t\t\t\t\t\tnetworkDao.commit();\n\t\t\t\t\t\t\tNdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkId,SolrIndexScope.global,false,null));\n\t\t\t\t\t\t} else\n\t\t\t\t\t\t\tNdexServerQueue.INSTANCE.addSystemTask(new SolrTaskDeleteNetwork(networkId, true)); //delete the entry from global idx.\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t}*/\n\t\t\t\t\tif ( parameters.containsKey(\"index_level\")) {\n\t\t\t\t\t\tNetworkIndexLevel lvl = parameters.get(\"index_level\") == null? \n\t\t\t\t\t\t\t\tNetworkIndexLevel.NONE : \n\t\t\t\t\t\t\t\tNetworkIndexLevel.valueOf((String)parameters.get(\"index_level\"));\n\t\t\t\t\t\tnetworkDao.setIndexLevel(networkId, lvl);\t \n\t\t\t\t\t\tif (lvl !=NetworkIndexLevel.NONE) {\n\t\t\t\t\t\t\tnetworkDao.setFlag(networkId, \"iscomplete\",false);\t \t\t\t\t\n\t\t\t\t\t\t\tnetworkDao.commit();\n\t\t\t\t\t\t\tNdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkId,SolrIndexScope.global,false,null,lvl,true));\n\t\t\t\t\t\t} else\n\t\t\t\t\t\t\tNdexServerQueue.INSTANCE.addSystemTask(new SolrTaskDeleteNetwork(networkId, true)); //delete the entry from global idx.\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\tif ( parameters.containsKey(\"showcase\")) {\n\t\t\t\t\t\tboolean bv = ((Boolean)parameters.get(\"showcase\")).booleanValue();\n\t\t\t\t\t\tnetworkDao.setShowcaseFlag(networkId, userId, bv);\n\t\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t networkDao.commit();\n\t\t\t\t\treturn;\n\t\t\t}\n\t\t \n\t}\n\n\t\n\t\n\n\t\n\t @POST\n\t//\t@PermitAll\n\n\t @Path(\"\")\n\t @Produces(\"text/plain\")\n\t @Consumes(\"multipart/form-data\")\n\t public Response createCXNetwork( MultipartFormDataInput input,\n\t\t\t @QueryParam(\"visibility\") String visibilityStr,\n\t\t\t\t@QueryParam(\"indexedfields\") String fieldListStr // comma seperated list\t\t\n\t\t\t ) throws Exception\n\t {\n\t \n\t\t VisibilityType visibility = null;\n\t\t if ( visibilityStr !=null) {\n\t\t\t visibility = VisibilityType.valueOf(visibilityStr);\n\t\t }\n\t\t \n\t\t Set extraIndexOnNodes = null;\n\t\t if ( fieldListStr != null) {\n\t\t\t extraIndexOnNodes = new HashSet<>(10);\n\t\t\t for ( String f: fieldListStr.split(\"\\\\s*,\\\\s*\") ) {\n\t\t\t\t extraIndexOnNodes.add(f);\n\t\t\t }\n\t\t }\n\t\t try (UserDAO dao = new UserDAO()) {\n\t\t\t dao.checkDiskSpace(getLoggedInUserId());\n\t\t }\n\t\t \n\t\t \n\t\t UUID uuid = storeRawNetworkFromMultipart ( input, cx1NetworkFileName);\n\t\t return processRawNetwork(visibility, extraIndexOnNodes, uuid);\n\n\t \t}\n\n\n\n\tprivate Response processRawNetwork(VisibilityType visibility, Set extraIndexOnNodes, UUID uuid)\n\t\t\tthrows SQLException, NdexException, IOException, ObjectNotFoundException, JsonProcessingException,\n\t\t\tURISyntaxException {\n\t\tString uuidStr = uuid.toString();\n\t\t accLogger.info(\"[data]\\t[uuid:\" +uuidStr + \"]\" );\n\t \n\t\t String urlStr = Configuration.getInstance().getHostURI() + \n\t\t Configuration.getInstance().getRestAPIPrefix()+\"/network/\"+ uuidStr;\n\t\t \n\t\t String cxFileName = Configuration.getInstance().getNdexRoot() + \"/data/\" + uuidStr + \"/\" + cx1NetworkFileName;\n\t\t long fileSize = new File(cxFileName).length();\n\n\t\t // create entry in db. \n\t try (NetworkDAO dao = new NetworkDAO()) {\n\t \t // NetworkSummary summary = \n\t \t\t\t dao.CreateEmptyNetworkEntry(uuid, getLoggedInUser().getExternalId(), getLoggedInUser().getUserName(), fileSize,null);\n \n\t\t\t\tdao.commit();\n\t }\n\t \n\t NdexServerQueue.INSTANCE.addSystemTask(new CXNetworkLoadingTask(uuid, /*getLoggedInUser().getUserName(),*/ false, visibility, extraIndexOnNodes));\t\t \n\t\t URI l = new URI (urlStr);\n\n\t\t return Response.created(l).entity(l).build();\n\t}\n\t \n\n\t @POST\t \n\t @Path(\"\")\n\t @Produces(\"text/plain\")\n\t @Consumes(MediaType.APPLICATION_JSON)\n\t public Response createNetworkJson( \n\t\t\t @QueryParam(\"visibility\") String visibilityStr,\n\t\t\t\t@QueryParam(\"indexedfields\") String fieldListStr // comma seperated list\t\t\n\t\t\t ) throws Exception\n\t {\n\t \n\t\t VisibilityType visibility = null;\n\t\t if ( visibilityStr !=null) {\n\t\t\t visibility = VisibilityType.valueOf(visibilityStr);\n\t\t }\n\t\t \n\t\t Set extraIndexOnNodes = null;\n\t\t if ( fieldListStr != null) {\n\t\t\t extraIndexOnNodes = new HashSet<>(10);\n\t\t\t for ( String f: fieldListStr.split(\"\\\\s*,\\\\s*\") ) {\n\t\t\t\t extraIndexOnNodes.add(f);\n\t\t\t }\n\t\t }\n\t\t try (UserDAO dao = new UserDAO()) {\n\t\t\t dao.checkDiskSpace(getLoggedInUserId());\n\t\t }\n\t\t \n\t\t try (InputStream in = this.getInputStreamFromRequest()) {\n\t\t\t UUID uuid = storeRawNetworkFromStream(in, cx1NetworkFileName);\n\t\t\t return processRawNetwork(visibility, extraIndexOnNodes, uuid);\n\n\t\t }\t\t \n\n\t \t}\n\t \n\t \n/*\t private static UUID storeRawNetworkFromStream(InputStream in) throws IOException {\n\t\t \n\t\t UUID uuid = NdexUUIDFactory.INSTANCE.createNewNDExUUID();\n\t\t String pathPrefix = Configuration.getInstance().getNdexRoot() + \"/data/\" + uuid.toString();\n\t\t \n\t\t //Create dir\n\t\t java.nio.file.Path dir = Paths.get(pathPrefix);\n\t\t Set perms =\n\t\t\t\t PosixFilePermissions.fromString(\"rwxrwxr-x\");\n\t\t\t\tFileAttribute> attr =\n\t\t\t\t PosixFilePermissions.asFileAttribute(perms);\n\t\t Files.createDirectory(dir,attr);\n\t\t \n\t\t //write content to file\n\t\t String cxFilePath = pathPrefix + \"/network.cx\";\n\t\t \n\t\t try (OutputStream outputStream = new FileOutputStream(cxFilePath)) {\n\t\t\t IOUtils.copy(in, outputStream);\n\t\t\t outputStream.close();\n\t\t } \n\t\t return uuid;\n\t }\n*/\t \n\t \n\t /* private static UUID storeRawNetwork (MultipartFormDataInput input) throws IOException, BadRequestException {\n\t\t Map> uploadForm = input.getFormDataMap();\n\t \t\t\t \n\t\t //Get file data to save\n\t\t List inputParts = uploadForm.get(\"CXNetworkStream\");\n\t\t if (inputParts == null)\n\t\t\t throw new BadRequestException(\"Field CXNetworkStream is not found in the POSTed Data.\");\n\t\t\t \n\t\t byte[] bytes = new byte[8192];\n\t\t UUID uuid = NdexUUIDFactory.INSTANCE.createNewNDExUUID();\n\t\t String pathPrefix = Configuration.getInstance().getNdexRoot() + \"/data/\" + uuid.toString();\n\t\t\t\t \n\t\t //Create dir\n\t\t java.nio.file.Path dir = Paths.get(pathPrefix);\n\t\t Set perms =\n\t\t\t\t\t\t PosixFilePermissions.fromString(\"rwxrwxr-x\");\n\t\t FileAttribute> attr =\n\t\t\t\t\t\t PosixFilePermissions.asFileAttribute(perms);\n\t\t Files.createDirectory(dir,attr);\n\t\t\t\t \n\t\t //write content to file\n\t\t String cxFilePath = pathPrefix + \"/network.cx\";\n\t\t try (FileOutputStream out = new FileOutputStream (cxFilePath ) ){ \n\t\t\t for (InputPart inputPart : inputParts) {\n\t\t\t\t // convert the uploaded file to inputstream and write it to disk\n\t\t\t\t org.jboss.resteasy.plugins.providers.multipart.MultipartInputImpl.PartImpl p =\n\t\t\t\t \t(org.jboss.resteasy.plugins.providers.multipart.MultipartInputImpl.PartImpl) inputPart;\n\t\t\t\t try (InputStream inputStream = p.getBody()) {\n\t\t\t\t \n\t\t\t\t int read = 0;\n\t\t\t\t while ((read = inputStream.read(bytes)) != -1) {\n\t\t\t\t out.write(bytes, 0, read);\n\t\t\t\t }\n\t\t\t\t }\n\t\t\t\t \n\t\t\t }\n\t\t }\n\t\t return uuid; \n\t }\n\t */\n\t \n\t \n\t private static List getNetworkAttributeAspectsFromSummary(NetworkSummary summary) \n\t\t\t throws JsonParseException, JsonMappingException, IOException {\n\t\t\tList result = new ArrayList<>();\n\t\t\tif ( summary.getName() !=null) \n\t\t\t\tresult.add(new NetworkAttributesElement(null, NdexClasses.Network_P_name, summary.getName()));\n\t\t\tif ( summary.getDescription() != null)\n\t\t\t\tresult.add(new NetworkAttributesElement(null, NdexClasses.Network_P_desc, summary.getDescription()));\n\t\t\tif ( summary.getVersion() !=null)\n\t\t\t\tresult.add(new NetworkAttributesElement(null, NdexClasses.Network_P_version, summary.getVersion()));\n\t\t\t\n\t\t\tif ( summary.getProperties() != null) {\n\t\t\t\tfor ( NdexPropertyValuePair p : summary.getProperties()) {\n\t\t\t\t\tresult.add(NetworkAttributesElement.createInstanceWithJsonValue(p.getSubNetworkId(), p.getPredicateString(),\n\t\t\t\t\t\t\tp.getValue(), ATTRIBUTE_DATA_TYPE.fromCxLabel(p.getDataType())));\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn result;\n\t\t}\n\t \n\t \n\t \t@POST\n\t\t @Path(\"/{networkid}/copy\")\n\t\t @Produces(\"text/plain\")\n\t\t public Response cloneNetwork( @PathParam(\"networkid\") final String srcNetworkUUIDStr) throws Exception\n\t\t {\n\t\t \n\t\t\t try (UserDAO dao = new UserDAO()) {\n\t\t\t\t dao.checkDiskSpace(getLoggedInUserId());\n\t\t\t }\n\t\t\t \n\t\t\t UUID srcNetUUID = UUID.fromString(srcNetworkUUIDStr);\n\t\t\t \n\t\t\t try ( NetworkDAO dao = new NetworkDAO ()) {\n\t\t\t\t if ( ! dao.isReadable(srcNetUUID, getLoggedInUserId()) ) \n\t\t throw new UnauthorizedOperationException(\"User doesn't have read access to this network.\");\n\t\t \t\t\n\t\t\t\t if (!dao.networkIsValid(srcNetUUID)) {\n\t\t\t\t\t throw new NdexException (\"Invalid networks can not be copied.\");\n\t\t\t\t }\n\t\t\t }\n\t\t\t \n\t\t\t UUID uuid = NdexUUIDFactory.INSTANCE.createNewNDExUUID();\n\t\t\t String uuidStr = uuid.toString();\n\t\t\t \n\t\t\t//\tjava.nio.file.Path src = Paths.get(Configuration.getInstance().getNdexRoot() + \"/data/\" + srcNetUUID.toString());\n\t\t\t\tjava.nio.file.Path tgt = Paths.get(Configuration.getInstance().getNdexRoot() + \"/data/\" + uuidStr);\n\t\t\t\t\n\t\t\t\t//Create dir\n\t\t\t\tSet perms =\n\t\t\t\t\t\t PosixFilePermissions.fromString(\"rwxrwxr-x\");\n\t\t\t\tFileAttribute> attr =\n\t\t\t\t\t\t PosixFilePermissions.asFileAttribute(perms);\n\t\t\t\tFiles.createDirectory(tgt,attr);\n\t\t\t\t\n\t\t\t\tString srcPathPrefix = Configuration.getInstance().getNdexRoot() + \"/data/\" + srcNetUUID.toString() + \"/\";\n\t\t\t\tString tgtPathPrefix = Configuration.getInstance().getNdexRoot() + \"/data/\" + uuidStr + \"/\";\n\n\t\t\t File srcAspectDir = new File ( srcPathPrefix + CXNetworkLoader.CX1AspectDir);\n\t\t\t if ( srcAspectDir.exists()) {\n\t\t\t \tFile tgtAspectDir = new File ( tgtPathPrefix + CXNetworkLoader.CX1AspectDir);\n\t\t\t \tFileUtils.copyDirectory(srcAspectDir, tgtAspectDir);\n\t\t\t }\n\t\t\t \n\t\t\t //copy the cx2 aspect directories\n\t\t\t String tgtCX2AspectPathPrefix = tgtPathPrefix + CX2NetworkLoader.cx2AspectDirName;\n\t\t\t String srcCX2AspectPathPrefix = srcPathPrefix + CX2NetworkLoader.cx2AspectDirName;\n\t\t\t File srcCX2AspectDir = new File (srcCX2AspectPathPrefix );\n\t\t\t Files.createDirectories(Paths.get(tgtCX2AspectPathPrefix), attr);\n\t\t\t for ( String fname : srcCX2AspectDir.list() ) {\n\t\t\t \tjava.nio.file.Path src = Paths.get(srcPathPrefix + CX2NetworkLoader.cx2AspectDirName , fname);\n\t\t\t \tif (Files.isSymbolicLink(src)) {\n\t\t\t \t\tjava.nio.file.Path link = Paths.get(tgtCX2AspectPathPrefix, fname);\n\t\t\t \t\tjava.nio.file.Path target = Paths.get(tgtPathPrefix + CXNetworkLoader.CX1AspectDir, fname);\n\t\t\t \t\tFiles.createSymbolicLink(link, target);\n\t\t\t \t} else {\n\t\t\t \t\tFiles.copy(Paths.get(srcCX2AspectPathPrefix, fname),\n\t\t\t \t\t\t\tPaths.get(tgtCX2AspectPathPrefix, fname));\n\t\t\t \t}\n\t\t\t \t\n\t\t\t }\n\t\t\t \n\t\t\t String urlStr = Configuration.getInstance().getHostURI() + \n\t\t\t Configuration.getInstance().getRestAPIPrefix()+\"/network/\"+ uuidStr;\n\t\t\t // ProvenanceEntity entity = new ProvenanceEntity();\n\t\t\t // entity.setUri(urlStr + \"/summary\");\n\t\t\t \n\t\t\t String cxFileName = Configuration.getInstance().getNdexRoot() + \"/data/\" + srcNetUUID.toString() + \"/\" + cx1NetworkFileName;\n\t\t\t long fileSize = new File(cxFileName).length();\n\n\t\t\t // copy sample \n\t\t\t java.nio.file.Path srcSample = Paths.get(Configuration.getInstance().getNdexRoot() + \"/data/\" + srcNetUUID.toString() + \"/sample.cx\");\n\t\t\t if ( Files.exists(srcSample, LinkOption.NOFOLLOW_LINKS)) {\n\t\t\t\t java.nio.file.Path tgtSample = Paths.get(Configuration.getInstance().getNdexRoot() + \"/data/\" + uuidStr + \"/sample.cx\");\n\t\t\t\t Files.copy(srcSample, tgtSample);\n\t\t\t }\n\t\t\t \n\t\t\t \n\t\t\t //TODO: generate prov:wasDerivedFrom and prov:wasGeneratedby field in both db record and the recreated CX file.\n\t\t\t // Need to handle the case when this network was a clone (means it already has prov:wasGeneratedBy and wasDerivedFrom attributes\n\t\t\t // create entry in db. \n\t\t try (NetworkDAO dao = new NetworkDAO()) {\n\t\t //\t NetworkSummary summary = \n\t\t \t\t\t dao.CreateCloneNetworkEntry(uuid, getLoggedInUser().getExternalId(), getLoggedInUser().getUserName(), fileSize, srcNetUUID);\n\t\n\t\t\t\t\tCXNetworkFileGenerator g = new CXNetworkFileGenerator(uuid, dao /*, new Provenance(copyProv)*/);\n\t\t\t\t\tg.reCreateCXFile();\n\t\t\t\t\tCX2NetworkFileGenerator g2 = new CX2NetworkFileGenerator(uuid, dao);\n\t\t\t\t\tString tmpFilePath = g2.createCX2File();\n\t\t\t\t\tFiles.move(Paths.get(tmpFilePath), \n\t\t\t\t\t\t\tPaths.get(tgtPathPrefix + CX2NetworkLoader.cx2NetworkFileName), \n\t\t\t\t\t\t\tStandardCopyOption.ATOMIC_MOVE); \t\t\t\t\n\n\t\t\t\t\tdao.setFlag(uuid, \"iscomplete\", true);\n\t\t\t\t\tdao.commit();\n\t\t }\n\t\t \n\t\t\t\tNdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(uuid, SolrIndexScope.individual,true,null, NetworkIndexLevel.NONE,false));\n\t\t \t\t\t \n\t\t\t URI l = new URI (urlStr);\n\n\t\t\t return Response.created(l).entity(l).build();\n\n\t\t \t}\n\t\t \n\n\t @POST\n\t\t@PermitAll\n\t\t@Path(\"/properties/score\")\n\t\t@Produces(\"application/json\")\n\t public static int getScoresFromProperties(\n\t \t\tfinal List properties)\n\t \t\tthrows Exception {\n\n\t\t\treturn Util.getNetworkScores (properties, true);\n\t }\n\t \n\t @POST\n\t\t@PermitAll\n\t\t@Path(\"/summary/score\")\n\t\t@Produces(\"application/json\")\n\t public static int getScoresFromNetworkSummary(\n\t \t\tfinal NetworkSummary summary)\n\t \t\tthrows Exception {\n\n\t\t\treturn Util.getNdexScoreFromSummary(summary);\n\t }\n\t \t\n\t \t\n}\n"},"message":{"kind":"string","value":"SRV2-166. change network attribute update functions trigger cx2 file\nstore and cx2metadata refresh."},"old_file":{"kind":"string","value":"src/main/java/org/ndexbio/rest/services/NetworkServiceV2.java"},"subject":{"kind":"string","value":"SRV2-166. change network attribute update functions trigger cx2 file store and cx2metadata refresh."},"git_diff":{"kind":"string","value":"rc/main/java/org/ndexbio/rest/services/NetworkServiceV2.java\n \t\t\t\t\tif ( !updated) {\n \t\t\t\t\t\tprops.add(new NdexPropertyValuePair(\"reference\", reference.get(\"reference\")));\n \t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tnetworkDao.lockNetwork(networkUUID);\n\n \t\t\t\t\tnetworkDao.updateNetworkProperties(networkUUID,props);\n\t\t\t\t\t\n\t\t\t\t\t// recreate files and update db\n\t\t\t\t\tupdateNetworkAttributesAspect(networkDao, networkUUID);\n\n\t\t\t\t\tnetworkDao.unlockNetwork(networkUUID);\n\t\t\t\t\t\n \t\t\t\t\tnetworkDao.updateNetworkVisibility(networkUUID, VisibilityType.PUBLIC, true);\n \t\t\t\t\t//networkDao.setFlag(networkUUID, \"solr_indexed\", true);\n \t\t\t\t\tnetworkDao.setIndexLevel(networkUUID, NetworkIndexLevel.ALL);\n \t// update the networkAttributes aspect file and also update the metadata in the db.\n \tprotected static void updateNetworkAttributesAspect(NetworkDAO networkDao, UUID networkUUID) throws JsonParseException, JsonMappingException, SQLException, IOException, NdexException {\n \t\tNetworkSummary fullSummary = networkDao.getNetworkSummaryById(networkUUID);\n\t\tString aspectFilePath = Configuration.getInstance().getNdexRoot() + \"/data/\" + \n\t\t\t\tnetworkUUID.toString() + \"/\" + CXNetworkLoader.CX1AspectDir + \"/\" + NetworkAttributesElement.ASPECT_NAME;\n\t\tString cx2AspectDirPath = Configuration.getInstance().getNdexRoot() + \"/data/\" + \n\t\t\t\tnetworkUUID.toString() + \"/\" + CX2NetworkLoader.cx2AspectDirName + \"/\";\n\t\tString cx2AspectFilePath = cx2AspectDirPath + CxNetworkAttribute.ASPECT_NAME;\n\t\tString fileStoreDir = Configuration.getInstance().getNdexRoot() + \"/data/\" + networkUUID.toString() + \"/\";\n\t\tString aspectFilePath = fileStoreDir + CXNetworkLoader.CX1AspectDir + \"/\" + NetworkAttributesElement.ASPECT_NAME;\n\t\tString cx2AspectDirPath = fileStoreDir + CX2NetworkLoader.cx2AspectDirName + \"/\";\n \t\t\n \t\t//update the networkAttributes aspect in cx and cx2 \n \t\tList attrs = getNetworkAttributeAspectsFromSummary(fullSummary);\n \t\t\tFile f = new File ( aspectFilePath);\n \t\t\tif ( f.exists())\n \t\t\t\tf.delete();\n\t\t\tf = new File(cx2AspectFilePath);\n\t\t\tf = new File(cx2AspectDirPath + CxNetworkAttribute.ASPECT_NAME);\n \t\t\tif ( f.exists())\n \t\t\t\tf.delete();\n \t\t}\n \t\t}\n \t\t\n \t\t//Recreate the CX file \t\t\t\t\t\n\t\tCXNetworkFileGenerator g = new CXNetworkFileGenerator(networkUUID, /*fullSummary,*/ metadata /*, newProv*/);\n\t\tCXNetworkFileGenerator g = new CXNetworkFileGenerator(networkUUID, metadata);\n \t\tg.reCreateCXFile();\n \n \t\t//Recreate cx2 file\n \t\tCX2NetworkFileGenerator g2 = new CX2NetworkFileGenerator(networkUUID, cx2metadata);\n\t\tg2.createCX2File();\n\n\t\tString tmpFilePath = g2.createCX2File();\n\t\tFiles.move(Paths.get(tmpFilePath), \n\t\t\t\tPaths.get(fileStoreDir + CX2NetworkLoader.cx2NetworkFileName), \n\t\t\t\tStandardCopyOption.ATOMIC_MOVE); \n \t}\n \n \t@PUT"}}},{"rowIdx":1982,"cells":{"lang":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"fcdac34d0703d4b01e908eb7a45ec143cac84321"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"fiuba08/robotframework,ldtri0209/robotframework,waldenner/robotframework,fiuba08/robotframework,waldenner/robotframework,ldtri0209/robotframework,waldenner/robotframework,ldtri0209/robotframework,ldtri0209/robotframework,fiuba08/robotframework,waldenner/robotframework,fiuba08/robotframework,waldenner/robotframework,ldtri0209/robotframework,fiuba08/robotframework"},"new_contents":{"kind":"string","value":"window.output = {};\nwindow.output[\"suite\"] = [1,2,3,4,[5,6,7,8,9,10,11,12],[0,0,3289],[[13,14,15,0,[],[1,26,12],[],[[16,0,1,0,[17,18,19],[1,36,2],[[0,20,0,21,22,[1,37,0],[],[[37,2,23]]],[0,24,0,25,26,[1,37,1],[],[[37,2,27]]]]]],[[1,28,0,0,0,[1,33,3],[[0,29,0,0,0,[1,34,1],[[0,24,0,25,30,[1,34,0],[],[[34,2,30]]],[0,31,0,0,0,[1,34,1],[[0,24,0,25,32,[1,35,0],[],[[35,2,33]]]],[]]],[]],[0,34,0,35,0,[1,35,0],[],[]],[0,36,0,0,0,[1,35,1],[[0,24,0,25,32,[1,36,0],[],[[36,2,33]]]],[[36,2,37]]]],[]]],[1,1,1,1]],[38,39,40,0,[],[0,38,6],[],[[41,0,1,0,[17,18,19],[1,40,1],[[0,42,0,43,44,[1,41,0],[],[[41,2,45]]],[0,24,0,25,46,[1,41,0],[],[[41,2,47]]]]],[48,0,1,0,[18,19,49],[0,42,2,50],[[0,51,0,0,0,[1,43,0],[[0,34,0,35,0,[1,43,0],[],[]]],[]],[0,52,0,0,53,[0,43,1],[],[[44,4,50]]]]]],[],[2,1,2,1]],[54,55,56,57,[58,59,60,12],[0,45,3243,61],[],[[62,0,1,0,[58,63,64,18,19,65],[0,48,1,66],[[1,24,0,25,67,[1,48,1],[],[[48,2,67]]],[0,24,0,25,68,[1,49,0],[],[[49,2,68]]],[2,24,0,25,69,[1,49,0],[],[[49,2,69]]]]],[70,0,1,0,[58,64,18,19,71,72,73,65],[0,50,502,66],[[1,24,0,25,67,[1,50,0],[],[[50,2,67]]],[0,74,0,75,76,[1,50,502],[],[[551,2,77]]],[2,24,0,25,69,[1,552,0],[],[[552,2,69]]]]],[78,0,1,0,[58,64,18,19,72,73,65],[0,552,704,66],[[1,24,0,25,67,[1,553,0],[],[[553,2,67]]],[0,74,0,75,79,[1,553,702],[],[[1255,2,80]]],[2,24,0,25,69,[1,1255,1],[],[[1256,2,69]]]]],[81,0,0,0,[82,58,64,18,19,73,65],[0,1256,2004,66],[[1,24,0,25,67,[1,1257,1],[],[[1258,2,67]]],[0,74,0,75,83,[1,1258,2002],[],[[3259,2,84]]],[2,24,0,25,69,[1,3260,0],[],[[3260,2,69]]]]],[85,0,1,86,[87,58,64,18,19,65],[0,3260,6,88],[[1,24,0,25,67,[1,3261,0],[],[[3261,2,67]]],[0,24,0,25,89,[1,3261,1],[],[[3262,2,90]]],[0,24,0,25,91,[1,3262,0],[],[[3262,2,92]]],[0,24,0,25,93,[1,3262,0],[],[[3262,2,93]]],[0,94,0,95,93,[0,3263,2],[],[[3265,4,93],[3265,1,96]]],[2,24,0,25,69,[1,3266,0],[],[[3266,2,69]]]]],[97,0,1,98,[58,63,64,18,19,65],[0,3266,2,66],[[1,24,0,25,67,[1,3267,0],[],[[3267,2,67]]],[0,34,0,35,0,[1,3267,1],[],[]],[2,24,0,25,69,[1,3268,0],[],[[3268,2,69]]]]],[99,0,1,100,[58,64,18,19,101,65],[0,3268,2,66],[[1,24,0,25,67,[1,3269,1],[],[[3270,2,67]]],[0,24,0,25,102,[1,3270,0],[],[[3270,2,102]]],[2,24,0,25,69,[1,3270,0],[],[[3270,2,69]]]]],[103,0,0,104,[58,64,18,19,105,106,65],[0,3271,4,66],[[1,24,0,25,107,[1,3271,0],[],[[3271,2,107]]],[0,24,0,25,108,[1,3272,0],[],[[3272,2,108]]],[0,109,0,0,0,[1,3272,1],[[0,24,0,25,110,[1,3272,0],[],[[3272,2,110]]]],[]],[3,111,0,0,0,[1,3273,2],[[4,112,0,0,0,[1,3273,0],[[0,24,0,25,113,[1,3273,0],[],[[3273,2,114]]]],[]],[4,115,0,0,0,[1,3273,1],[[0,24,0,25,113,[1,3273,1],[],[[3274,2,116]]]],[]],[4,117,0,0,0,[1,3274,0],[[0,24,0,25,113,[1,3274,0],[],[[3274,2,118]]]],[]],[4,119,0,0,0,[1,3274,1],[[0,24,0,25,113,[1,3274,1],[],[[3274,2,120]]]],[]]],[]],[2,24,0,25,121,[1,3275,0],[],[[3275,2,121]]]]],[122,0,1,0,[58,63,64,18,19,65],[0,3275,3,66],[[1,24,0,25,67,[1,3276,0],[],[[3276,2,67]]],[0,24,0,25,123,[1,3276,0],[],[[3276,3,125]]],[0,24,0,25,126,[1,3277,0],[],[[3277,2,127]]],[0,24,0,25,128,[1,3277,0],[],[[3277,1,129]]],[2,24,0,25,69,[1,3277,0],[],[[3277,2,69]]]]],[130,0,1,0,[58,63,64,18,19,65],[0,3278,2,131],[[1,24,0,25,67,[1,3278,1],[],[[3279,2,67]]],[0,94,0,95,132,[0,3279,0],[],[[3279,4,132],[3279,1,96]]],[0,94,0,95,133,[0,3279,1],[],[[3279,4,134],[3280,1,96]]],[2,24,0,25,69,[1,3280,0],[],[[3280,2,69]]]]],[135,0,1,136,[58,5,64,18,19,65],[0,3280,4,137],[[1,24,0,25,67,[1,3281,0],[],[[3281,2,67]]],[0,24,0,25,5,[1,3281,0],[],[[3281,2,5]]],[0,138,0,0,0,[1,3282,0],[[0,34,0,35,0,[1,3282,0],[],[]]],[]],[0,5,0,0,0,[0,3282,1],[[0,94,0,95,5,[0,3283,0],[],[[3283,4,5],[3283,1,96]]]],[]],[2,24,0,25,69,[1,3283,1],[],[[3284,2,69]]]]],[139,0,1,0,[58,63,64,18,19,65],[0,3284,3,140],[[1,24,0,25,67,[1,3284,1],[],[[3285,2,67]]],[0,141,0,142,143,[1,3285,0],[],[[3285,2,144]]],[0,24,0,25,145,[1,3285,1],[],[[3285,3,147]]],[0,94,0,95,148,[0,3286,1],[],[[3286,4,147],[3286,1,96]]],[2,24,0,25,69,[1,3287,0],[],[[3287,2,69]]]]]],[[1,24,0,25,149,[1,47,1],[],[[48,2,149]]],[2,94,0,95,0,[0,3288,0,150],[],[[3288,4,150],[3288,1,96]]]],[12,0,10,0]]],[],[[1,24,0,25,151,[1,26,0],[],[[26,2,151]]]],[15,2,13,2]];\nwindow.output[\"strings\"] = [];\nwindow.output[\"strings\"] = window.output[\"strings\"].concat([\"*\",\"*&lt;Suite.Name&gt;\",\"*/Users/mikhanni/koodi/robotframework/src/robot/htmldata/testdata/dir.suite\",\"*dir.suite\",\"eNrFlOGK2zAMxz+vTyH6ADFNDwZHLmMwDgbdl657ACdRHHNOZGRn3b39ZKdd29HBMQb7Ylrpp78lxVLl60/UziNOUUdLE/TEEAeE40AOIWKIEGYbsYCPzonHhoSMATQEOxlhvGZtWPsBQtQcxQg90wj7ZyiL90UpkVOXNS+kqBiMmfUsP17B0WT+N/l19p44YpdL1AshcIcjTSGyTq4GHR2LSvl6VQ1lfbBRerDD7+hgUymxrCpfH/BHzK10Z0fGtzd4Kfj2Hl6e8IcbfCv4wz18u+Czk8PZumrqb/vdY6WaGioNA2P/tB5i9I9KMTUUe9YjHolfCmKzrv/oqpSuKyWKi6ytP4/aoAhbEbajgcDtL+WWOiwMkbyIoqVR+d8ElSNDHyTxwk9mDTEV9pfBt0lJuTs7veR6l9TeUPM+2eD5bLytNJcJLom+Sezf9uLuDZf8VP7MA8sRdSOPoyHukJ/Wm3UyZXuXmvLldemI/DubDingyqoW/BSzubDlXaAnupK7JlROJb9NRjM7zal9uLxLGbF6JQdIBqe5wi5lsQJoaYqyet4dbRxk5cieCV63GEQyhy2Fnl92b1nWkbNyCDlevlhAEeounjS0SdpOs0wszGlTpevjkfJYdLbvkeVi0N4z6XbAcNXfn1KauKA=\",\"*&lt;/script&gt;\",\"*

    &lt; &amp;lt; &lt;/script&gt;

    \",\"*Formatting\",\"*

    Bold and italics

    \",\"*Image\",\"eNqdy9ENgCAMBcBVDAPQf4M4i2KtRPA1tYmO7w7e/yXNqXYZbitTONx1JCrYOAogjWNBJyXDCt9t6fzATmoQzPx61EvC4NUb/8w5keYPXLwvxw==\",\"*URL\",\"*

    http://robotframework.org

    \",\"*Test.Suite.1\",\"*/Users/mikhanni/koodi/robotframework/src/robot/htmldata/testdata/dir.suite/test.suite.1.txt\",\"*dir.suite/test.suite.1.txt\",\"*list test\",\"*collections\",\"*i1\",\"*i2\",\"*${list} = BuiltIn.Create List\",\"*

    Returns a list containing given items.

    \",\"*foo, bar, quux\",\"*${list} = [u'foo', u'bar', u'quux']\",\"*BuiltIn.Log\",\"*

    Logs the given message with the given level.

    \",\"*${list}\",\"*[u'foo', u'bar', u'quux']\",\"*User Keyword\",\"*User Keyword 2\",\"*Several levels...\",\"*User Keyword 3\",\"*&lt;b&gt;The End&lt;/b&gt;, HTML\",\"*The End\",\"*BuiltIn.No Operation\",\"*

    Does absolutely nothing.

    \",\"*${ret} = User Keyword 3\",\"*${ret} = None\",\"*Test.Suite.2\",\"*/Users/mikhanni/koodi/robotframework/src/robot/htmldata/testdata/dir.suite/test.suite.2.txt\",\"*dir.suite/test.suite.2.txt\",\"*Dictionary test\",\"*${dict} = Collections.Create Dictionary\",\"*

    Creates and returns a dictionary from the given `key_value_pairs`.

    \",\"*key, value\",\"*${dict} = {u'key': u'value'}\",\"*${dict}\",\"*{u'key': u'value'}\",\"*Test with a rather long name here we have and the name really is pretty long long long long longer than you think it could be\",\"*this test also has a pretty long tag that really is long long long long long longer than you think it could be\",\"*No keyword with name 'This keyword gets many arguments' found.\",\"eNrzTq0szy9KUShPVchILAMSqUWpCpnFCkWJJUCmQk5+XjpOAihfkpGYp1CZXwpkZOZlK2SWKCTnl+akKCSlYiIIAAAZ9Cgs\",\"*This keyword gets many arguments\",\"eNrLLNFRKEpNzMmp1FFITy0p1lHITcwDshOL0ktzU/NAAplDSQkAaktIdQ==\",\"*Tests\",\"*/Users/mikhanni/koodi/robotframework/src/robot/htmldata/testdata/dir.suite/tests.txt\",\"*dir.suite/tests.txt\",\"*

    Some suite docs with links: http://robotframework.org

    \",\"*&lt; &amp;lt; \\u00e4\",\"*

    &lt; &amp;lt; \\u00e4

    \",\"*home *page*\",\"*Suite teardown failed:\\nAssertionError\",\"*Simple\",\"*default with percent %\",\"*force\",\"*with space\",\"*Teardown of the parent suite failed:\\nAssertionError\",\"*Test Setup\",\"*do nothing\",\"*Test Teardown\",\"*Long\",\"*long1\",\"*long2\",\"*long3\",\"*BuiltIn.Sleep\",\"*

    Pauses the test executed for the given time.

    \",\"*0.5 seconds\",\"*Slept 500 milliseconds\",\"*Longer\",\"*0.7 second\",\"*Slept 700 milliseconds\",\"*Longest\",\"**kek*kone*\",\"*2 seconds\",\"*Slept 2 seconds\",\"*Log HTML\",\"*

    This test uses formatted HTML.

    \\n\\n\\n\\n\\n\\n\\n
    Isn'tthatcool?
    \",\"*!\\\"#%&amp;/()=\",\"*escape &lt; &amp;lt; &lt;b&gt;no bold&lt;/b&gt;\\n\\nAlso teardown of the parent suite failed:\\nAssertionError\",\"*&lt;blink&gt;&lt;b&gt;&lt;font face=\\\"comic sans ms\\\" size=\\\"42\\\" color=\\\"red\\\"&gt;CAN HAZ HMTL &amp; NO CSS?!?!??!!?&lt;/font&gt;&lt;/b&gt;&lt;/blink&gt;, HTML\",\"*CAN HAZ HMTL & NO CSS?!?!??!!?\",\"eNpTyymxLklMyklVSy+xVgNxiuCsFBArJCOzWAGiAi5WnJFfmpOikJFYlopNS16+QnFBanJmYg5CLC2/KDexpCQzLx0kpg+3UkfBI8TXBwBuyS8B\",\"*
    This tableshould have
    no specialformatting
    \",\"*escape &lt; &amp;lt; &lt;b&gt;no bold&lt;/b&gt;\",\"*BuiltIn.Fail\",\"*

    Fails the test with the given message and optionally alters its tags.

    \",\"*Traceback (most recent call last):\\n File \\\"/Users/mikhanni/koodi/robotframework/src/robot/libraries/BuiltIn.py\\\", line 330, in fail\\n raise AssertionError(msg) if msg else AssertionError()\",\"*Long doc with formatting\",\"eNqNj8FqwzAMhu97CjUPULPrcH3eoLuU7gGUxE1MHMtICqFvX8cLdDsM5oOQfn36ZdnsrmMQUC8KIwogZPaqd4iUBuipW2afFDVQOlqT3YvN7kOhoyKGJDAvUUOOHphWgZBAaOHOA6b+2cvIODDmsRLv18/zT69t7dflLBDD5MEijOxvp2ZUzW/GMLWkN8bZr8TTkXho3J8ta9DV1f9x6RZRmsvWNMk2uP9piSXE4GIQLXrJaqm0vb02FVJsy3Etce/51Lw2m8Rb6F05afXRmpLu9Z6bb2LHqoM8scPhF2Zq3z0ADI2NwA==\",\"*Non-ASCII \\u5b98\\u8bdd\",\"*

    with n\\u00f6n-\\u00e4scii \\u5b98\\u8bdd

    \",\"*with n\\u00f6n-\\u00e4scii \\u5b98\\u8bdd\",\"*hyv\\u00e4\\u00e4 joulua\",\"*Complex\",\"*

    Test doc

    \",\"*owner-kekkonen\",\"*t1\",\"*in own setup\",\"*in test\",\"*User Kw\",\"*in User Kw\",\"*${i} IN [ @{list} ]\",\"*${i} = 1\",\"*Got ${i}\",\"*Got 1\",\"*${i} = 2\",\"*Got 2\",\"*${i} = 3\",\"*Got 3\",\"*${i} = 4\",\"*Got 4\",\"*in own teardown\",\"*Log levels\",\"*This is a WARNING!\\\\n\\\\nWith multiple lines., WARN\",\"*s1-s3-t9-k2\",\"*This is a WARNING!\\n\\nWith multiple lines.\",\"*This is info, INFO\",\"*This is info\",\"*This is debug, DEBUG\",\"*This is debug\",\"*Multi-line failure\",\"*Several failures occurred:\\n\\n1) First failure\\n\\n2) Second failure\\nhas multiple\\nlines\\n\\nAlso teardown of the parent suite failed:\\nAssertionError\",\"*First failure\",\"*Second failure\\\\nhas multiple\\\\nlines\",\"*Second failure\\nhas multiple\\nlines\",\"*Escape JS &lt;/script&gt; \\\" http://url.com\",\"*

    &lt;/script&gt;

    \",\"*&lt;/script&gt;\\n\\nAlso teardown of the parent suite failed:\\nAssertionError\",\"*kw http://url.com\",\"*Long messages\",\"eNrtxsEJwCAMBdC7U2SO3jwU3KBnwUiF4JeflK7fPYrv9Iqa4QKtlb29vZ8upWwOCa1seKegS9wqq1JniD8jVHodpu1I2V0ZA/MkwQ+JA6N8\",\"*${msg} = BuiltIn.Evaluate\",\"*

    Evaluates the given expression in Python and returns the results.

    \",\"*'HelloWorld' * 100\",\"eNpTqc4tTq9VsFXwSM3JyQ/PL8pJGdosPT09AIaQUxs=\",\"*${msg}, WARN\",\"*s1-s3-t12-k3\",\"eNrzSM3JyQ/PL8pJ8RhljbJGWcOUBQDtvo6A\",\"*${msg}\",\"*Suite setup\",\"*AssertionError\",\"*higher level suite setup\",\"*Error in file '/Users/mikhanni/koodi/robotframework/src/robot/htmldata/testdata/dir.suite/tests.txt' in table 'Settings': Test library 'p\\u00f6lk\\u00fc/myLib.py' does not exist.\"]);\nwindow.output[\"generatedTimestamp\"] = \"20130415 12:34:12 GMT +03:00\";\nwindow.output[\"errors\"] = [[47,5,152],[3276,3,125,124],[3285,3,147,146]];\nwindow.output[\"stats\"] = [[{\"elapsed\":\"00:00:01\",\"fail\":11,\"label\":\"Critical Tests\",\"pass\":2},{\"elapsed\":\"00:00:03\",\"fail\":13,\"label\":\"All Tests\",\"pass\":2}],[{\"doc\":\"Me, myself, and I.\",\"elapsed\":\"00:00:03\",\"fail\":13,\"info\":\"critical\",\"label\":\"i1\",\"links\":\"Title of i1:http://1/:::Title:http://i/\",\"pass\":2},{\"doc\":\"Me, myself, and I.\",\"elapsed\":\"00:00:03\",\"fail\":13,\"info\":\"critical\",\"label\":\"i2\",\"links\":\"Title of i2:http://2/\",\"pass\":2},{\"elapsed\":\"00:00:02\",\"fail\":1,\"info\":\"non-critical\",\"label\":\"*kek*kone*\",\"pass\":0},{\"elapsed\":\"00:00:00\",\"fail\":1,\"info\":\"non-critical\",\"label\":\"owner-kekkonen\",\"pass\":0},{\"combined\":\"&lt;*&gt;\",\"elapsed\":\"00:00:00\",\"fail\":1,\"info\":\"combined\",\"label\":\"&lt;any&gt;\",\"pass\":0},{\"combined\":\"i?\",\"doc\":\"*Combined* and escaped &lt;&amp;lt; tag doc &amp; Me, myself, and I.\",\"elapsed\":\"00:00:03\",\"fail\":13,\"info\":\"combined\",\"label\":\"IX\",\"links\":\"Title of iX:http://X/\",\"pass\":2},{\"combined\":\"foo AND i*\",\"elapsed\":\"00:00:00\",\"fail\":0,\"info\":\"combined\",\"label\":\"No Match\",\"pass\":0},{\"elapsed\":\"00:00:00\",\"fail\":1,\"label\":\"!\\\"#%&amp;/()=\",\"pass\":0},{\"elapsed\":\"00:00:03\",\"fail\":12,\"label\":\"&lt; &amp;lt; \\u00e4\",\"pass\":0},{\"doc\":\"&lt;doc&gt;\",\"elapsed\":\"00:00:00\",\"fail\":1,\"label\":\"&lt;/script&gt;\",\"links\":\"&lt;title&gt;:&lt;url&gt;\",\"pass\":0},{\"elapsed\":\"00:00:00\",\"fail\":0,\"label\":\"collections\",\"pass\":2},{\"elapsed\":\"00:00:00\",\"fail\":5,\"label\":\"default with percent %\",\"pass\":0},{\"elapsed\":\"00:00:03\",\"fail\":12,\"label\":\"force\",\"links\":\"&lt;kuukkeli&amp;gt;:http://google.com\",\"pass\":0},{\"elapsed\":\"00:00:01\",\"fail\":1,\"label\":\"long1\",\"pass\":0},{\"elapsed\":\"00:00:01\",\"fail\":2,\"label\":\"long2\",\"pass\":0},{\"elapsed\":\"00:00:03\",\"fail\":3,\"label\":\"long3\",\"pass\":0},{\"elapsed\":\"00:00:00\",\"fail\":1,\"label\":\"t1\",\"links\":\"Title:http://t/\",\"pass\":0},{\"elapsed\":\"00:00:00\",\"fail\":1,\"label\":\"this test also has a pretty long tag that really is long long long long long longer than you think it could be\",\"pass\":0},{\"elapsed\":\"00:00:00\",\"fail\":1,\"label\":\"with n\\u00f6n-\\u00e4scii \\u5b98\\u8bdd\",\"pass\":0},{\"elapsed\":\"00:00:03\",\"fail\":12,\"label\":\"with space\",\"pass\":0}],[{\"elapsed\":\"00:00:03\",\"fail\":13,\"id\":\"s1\",\"label\":\"&lt;Suite.Name&gt;\",\"name\":\"&lt;Suite.Name&gt;\",\"pass\":2},{\"elapsed\":\"00:00:00\",\"fail\":0,\"id\":\"s1-s1\",\"label\":\"&lt;Suite.Name&gt;.Test.Suite.1\",\"name\":\"Test.Suite.1\",\"pass\":1},{\"elapsed\":\"00:00:00\",\"fail\":1,\"id\":\"s1-s2\",\"label\":\"&lt;Suite.Name&gt;.Test.Suite.2\",\"name\":\"Test.Suite.2\",\"pass\":1},{\"elapsed\":\"00:00:03\",\"fail\":12,\"id\":\"s1-s3\",\"label\":\"&lt;Suite.Name&gt;.Tests\",\"name\":\"Tests\",\"pass\":0}]];\nwindow.output[\"generatedMillis\"] = 2480;\nwindow.output[\"baseMillis\"] = 1366018449520;\nwindow.settings = {\"background\":{\"fail\":\"DeepPink\"},\"defaultLevel\":\"DEBUG\",\"logURL\":\"log.html\",\"minLevel\":\"DEBUG\",\"reportURL\":\"report.html\",\"title\":\"This is a long long title. A very long title indeed. And it even contains some stuff to . Yet it should still look good.\"};\n"},"new_file":{"kind":"string","value":"src/robot/htmldata/testdata/data.js"},"old_contents":{"kind":"string","value":"window.output = {};\nwindow.output[\"suite\"] = [1,2,3,4,[5,6,7,8,9,10,11,12],[0,0,3265],[[13,14,15,0,[],[1,17,8],[],[[16,0,1,0,[17,18,19],[1,24,0],[[0,20,0,21,22,[1,24,0],[],[[24,2,23]]],[0,24,0,25,26,[1,24,0],[],[[24,2,27]]]]]],[[1,28,0,0,0,[1,21,3],[[0,29,0,0,0,[1,22,1],[[0,24,0,25,30,[1,22,0],[],[[22,2,30]]],[0,31,0,0,0,[1,22,1],[[0,24,0,25,32,[1,22,1],[],[[22,2,33]]]],[]]],[]],[0,34,0,35,0,[1,23,0],[],[]],[0,36,0,0,0,[1,23,0],[[0,24,0,25,32,[1,23,0],[],[[23,2,33]]]],[[23,2,37]]]],[]]],[1,1,1,1]],[38,39,40,0,[],[0,25,5],[],[[41,0,1,0,[17,18,19],[1,26,2],[[0,42,0,43,44,[1,27,0],[],[[27,2,45]]],[0,24,0,25,46,[1,27,1],[],[[27,2,47]]]]],[48,0,1,0,[18,19,49],[0,28,1,50],[[0,51,0,0,0,[1,28,1],[[0,34,0,35,0,[1,29,0],[],[]]],[]],[0,52,0,0,53,[0,29,0],[],[[29,4,50]]]]]],[],[2,1,2,1]],[54,55,56,57,[58,59,60,12],[0,30,3234,61],[],[[62,0,1,0,[58,63,64,18,19,65],[0,32,1,66],[[1,24,0,25,67,[1,32,0],[],[[32,2,67]]],[0,24,0,25,68,[1,32,1],[],[[33,2,68]]],[2,24,0,25,69,[1,33,0],[],[[33,2,69]]]]],[70,0,1,0,[58,64,18,19,71,72,73,65],[0,33,503,66],[[1,24,0,25,67,[1,34,0],[],[[34,2,67]]],[0,74,0,75,76,[1,34,501],[],[[534,2,77]]],[2,24,0,25,69,[1,535,1],[],[[536,2,69]]]]],[78,0,1,0,[58,64,18,19,72,73,65],[0,537,704,66],[[1,24,0,25,67,[1,538,0],[],[[538,2,67]]],[0,74,0,75,79,[1,539,701],[],[[1239,2,80]]],[2,24,0,25,69,[1,1240,1],[],[[1241,2,69]]]]],[81,0,0,0,[82,58,64,18,19,73,65],[0,1242,2003,66],[[1,24,0,25,67,[1,1243,1],[],[[1243,2,67]]],[0,74,0,75,83,[1,1244,2000],[],[[3244,2,84]]],[2,24,0,25,69,[1,3245,0],[],[[3245,2,69]]]]],[85,0,1,86,[87,58,64,18,19,65],[0,3245,3,88],[[1,24,0,25,67,[1,3246,0],[],[[3246,2,67]]],[0,24,0,25,89,[1,3246,0],[],[[3246,2,90]]],[0,24,0,25,91,[1,3246,0],[],[[3246,2,92]]],[0,24,0,25,93,[1,3246,1],[],[[3247,2,93]]],[0,94,0,95,93,[0,3247,0],[],[[3247,4,93],[3247,1,96]]],[2,24,0,25,69,[1,3248,0],[],[[3248,2,69]]]]],[97,0,1,98,[58,63,64,18,19,65],[0,3248,1,66],[[1,24,0,25,67,[1,3249,0],[],[[3249,2,67]]],[0,34,0,35,0,[1,3249,0],[],[]],[2,24,0,25,69,[1,3249,0],[],[[3249,2,69]]]]],[99,0,1,100,[58,64,18,19,101,65],[0,3250,1,66],[[1,24,0,25,67,[1,3250,1],[],[[3251,2,67]]],[0,24,0,25,102,[1,3251,0],[],[[3251,2,102]]],[2,24,0,25,69,[1,3251,0],[],[[3251,2,69]]]]],[103,0,0,104,[58,64,18,19,105,106,65],[0,3251,4,66],[[1,24,0,25,107,[1,3252,0],[],[[3252,2,107]]],[0,24,0,25,108,[1,3252,0],[],[[3252,2,108]]],[0,109,0,0,0,[1,3252,1],[[0,24,0,25,110,[1,3253,0],[],[[3253,2,110]]]],[]],[3,111,0,0,0,[1,3253,2],[[4,112,0,0,0,[1,3253,0],[[0,24,0,25,113,[1,3253,0],[],[[3253,2,114]]]],[]],[4,115,0,0,0,[1,3254,0],[[0,24,0,25,113,[1,3254,0],[],[[3254,2,116]]]],[]],[4,117,0,0,0,[1,3254,0],[[0,24,0,25,113,[1,3254,0],[],[[3254,2,118]]]],[]],[4,119,0,0,0,[1,3254,1],[[0,24,0,25,113,[1,3254,1],[],[[3255,2,120]]]],[]]],[]],[2,24,0,25,121,[1,3255,0],[],[[3255,2,121]]]]],[122,0,1,0,[58,63,64,18,19,65],[0,3255,2,66],[[1,24,0,25,67,[1,3256,0],[],[[3256,2,67]]],[0,24,0,25,123,[1,3256,0],[],[[3256,3,125]]],[0,24,0,25,126,[1,3256,0],[],[[3256,2,127]]],[0,24,0,25,128,[1,3257,0],[],[[3257,1,129]]],[2,24,0,25,69,[1,3257,0],[],[[3257,2,69]]]]],[130,0,1,0,[58,63,64,18,19,65],[0,3257,2,131],[[1,24,0,25,67,[1,3258,0],[],[[3258,2,67]]],[0,94,0,95,132,[0,3258,0],[],[[3258,4,132],[3258,1,96]]],[0,94,0,95,133,[0,3258,1],[],[[3259,4,134],[3259,1,96]]],[2,24,0,25,69,[1,3259,0],[],[[3259,2,69]]]]],[135,0,1,136,[58,5,64,18,19,65],[0,3259,3,137],[[1,24,0,25,67,[1,3260,0],[],[[3260,2,67]]],[0,24,0,25,5,[1,3260,0],[],[[3260,2,5]]],[0,138,0,0,0,[1,3260,1],[[0,34,0,35,0,[1,3260,1],[],[]]],[]],[0,5,0,0,0,[0,3261,0],[[0,94,0,95,5,[0,3261,0],[],[[3261,4,5],[3261,1,96]]]],[]],[2,24,0,25,69,[1,3261,1],[],[[3262,2,69]]]]],[139,0,1,0,[58,63,64,18,19,65],[0,3262,2,140],[[1,24,0,25,67,[1,3262,0],[],[[3262,2,67]]],[0,141,0,142,143,[1,3262,1],[],[[3263,2,144]]],[0,24,0,25,145,[1,3263,0],[],[[3263,3,147]]],[0,94,0,95,148,[0,3263,0],[],[[3263,4,147],[3263,1,96]]],[2,24,0,25,69,[1,3263,1],[],[[3264,2,69]]]]]],[[1,24,0,25,149,[1,32,0],[],[[32,2,149]]],[2,94,0,95,0,[0,3264,0,150],[],[[3264,4,150],[3264,1,96]]]],[12,0,10,0]]],[],[[1,24,0,25,151,[1,17,0],[],[[17,2,151]]]],[15,2,13,2]];\nwindow.output[\"strings\"] = [];\nwindow.output[\"strings\"] = window.output[\"strings\"].concat([\"*\",\"*&lt;Suite.Name&gt;\",\"*/home/peke/Devel/robotframework/src/robot/htmldata/testdata/dir.suite\",\"*dir.suite\",\"eNrFVNFq3TAMfd79CpEPiOl9GZQ0YzAKg+7lbvsAJ1EcU8cyskLWv5+c9O7ejg7KGOxFJEdHx5IsuUntJ+qXGaNY8RRhJAaZENaJAoJgFsiLF6zhYwjq8blQ5gwWso9OOcmydWzTBFksi4IwMs1wuodj/b4+amQcNs0LU1UcysZNrB9PECi6/838uqRELDhsJdqdoeQBZ4pZ2BZXh4HWujGpPTRLUBN823Tt99PDbWO6FhoLE+N4V00i6dYYpo5kZDvjSvxYE7uq/aOrMbZtjCrusr79PFuHKuxV2M8OMve/lHsasHZEegl1T7NJvwmaQI4+4A+pU3QViJeAfxn8Mikt98HHx63ePbU31HwqGNyfwZeVbmVCKKJvEvu3vXj1hEt+ZrvmidWI7XTiO+IB+a66qQq04UNpypenvSP6d4a+lYAr1Oz055ibC/f4KmEkupK7ZpgtFf1ILaNbguXSPtznUqe6PagBzeB5lHEoWRwAeoqi2/5u9TLplutq52R7zCq5he2Fnid79KwvQPBqlDlfbiyjCg0XT9mTIu3joksCS3kcyvGy0rYWgx9HZD0YbEpMtp8wX/X3J45wjUo=\",\"*&lt;/script&gt;\",\"*

    &lt; &amp;lt; &lt;/script&gt;

    \",\"*Formatting\",\"*

    Bold and italics

    \",\"*Image\",\"eNqdy9ENgCAMBcBVDAPQf4M4i2KtRPA1tYmO7w7e/yXNqXYZbitTONx1JCrYOAogjWNBJyXDCt9t6fzATmoQzPx61EvC4NUb/8w5keYPXLwvxw==\",\"*URL\",\"*

    http://robotframework.org

    \",\"*Test.Suite.1\",\"*/home/peke/Devel/robotframework/src/robot/htmldata/testdata/dir.suite/test.suite.1.txt\",\"*dir.suite/test.suite.1.txt\",\"*list test\",\"*collections\",\"*i1\",\"*i2\",\"*${list} = BuiltIn.Create List\",\"*

    Returns a list containing given items.

    \",\"*foo, bar, quux\",\"*${list} = [u'foo', u'bar', u'quux']\",\"*BuiltIn.Log\",\"*

    Logs the given message with the given level.

    \",\"*${list}\",\"*[u'foo', u'bar', u'quux']\",\"*User Keyword\",\"*User Keyword 2\",\"*Several levels...\",\"*User Keyword 3\",\"*&lt;b&gt;The End&lt;/b&gt;, HTML\",\"*The End\",\"*BuiltIn.No Operation\",\"*

    Does absolutely nothing.

    \",\"*${ret} = User Keyword 3\",\"*${ret} = None\",\"*Test.Suite.2\",\"*/home/peke/Devel/robotframework/src/robot/htmldata/testdata/dir.suite/test.suite.2.txt\",\"*dir.suite/test.suite.2.txt\",\"*Dictionary test\",\"*${dict} = Collections.Create Dictionary\",\"*

    Creates and returns a dictionary from the given `key_value_pairs`.

    \",\"*key, value\",\"*${dict} = {u'key': u'value'}\",\"*${dict}\",\"*{u'key': u'value'}\",\"*Test with a rather long name here we have and the name really is pretty long long long long longer than you think it could be\",\"*this test also has a pretty long tag that really is long long long long long longer than you think it could be\",\"*No keyword with name 'This keyword gets many arguments' found.\",\"eNrzTq0szy9KUShPVchILAMSqUWpCpnFCkWJJUCmQk5+XjpOAihfkpGYp1CZXwpkZOZlK2SWKCTnl+akKCSlYiIIAAAZ9Cgs\",\"*This keyword gets many arguments\",\"eNrLLNFRKEpNzMmp1FFITy0p1lHITcwDshOL0ktzU/NAAplDSQkAaktIdQ==\",\"*Tests\",\"*/home/peke/Devel/robotframework/src/robot/htmldata/testdata/dir.suite/tests.txt\",\"*dir.suite/tests.txt\",\"*

    Some suite docs with links: http://robotframework.org

    \",\"*&lt; &amp;lt; \\u00e4\",\"*

    &lt; &amp;lt; \\u00e4

    \",\"*home *page*\",\"*Suite teardown failed:\\nAssertionError\",\"*Simple\",\"*default with percent %\",\"*force\",\"*with space\",\"*Teardown of the parent suite failed:\\nAssertionError\",\"*Test Setup\",\"*do nothing\",\"*Test Teardown\",\"*Long\",\"*long1\",\"*long2\",\"*long3\",\"*BuiltIn.Sleep\",\"*

    Pauses the test executed for the given time.

    \",\"*0.5 seconds\",\"*Slept 500 milliseconds\",\"*Longer\",\"*0.7 second\",\"*Slept 700 milliseconds\",\"*Longest\",\"**kek*kone*\",\"*2 seconds\",\"*Slept 2 seconds\",\"*Log HTML\",\"*

    This test uses formatted HTML.

    \\n\\n\\n\\n\\n\\n\\n
    Isn'tthatcool?
    \",\"*!\\\"#%&amp;/()=\",\"*escape &lt; &amp;lt; &lt;b&gt;no bold&lt;/b&gt;\\n\\nAlso teardown of the parent suite failed:\\nAssertionError\",\"*&lt;blink&gt;&lt;b&gt;&lt;font face=\\\"comic sans ms\\\" size=\\\"42\\\" color=\\\"red\\\"&gt;CAN HAZ HMTL &amp; NO CSS?!?!??!!?&lt;/font&gt;&lt;/b&gt;&lt;/blink&gt;, HTML\",\"*CAN HAZ HMTL & NO CSS?!?!??!!?\",\"eNpTyymxLklMyklVSy+xVgNxiuCsFBArJCOzWAGiAi5WnJFfmpOikJFYlopNS16+QnFBanJmYg5CLC2/KDexpCQzLx0kpg+3UkfBI8TXBwBuyS8B\",\"*
    This tableshould have
    no specialformatting
    \",\"*escape &lt; &amp;lt; &lt;b&gt;no bold&lt;/b&gt;\",\"*BuiltIn.Fail\",\"*

    Fails the test with the given message and optionally alters its tags.

    \",\"*Traceback (most recent call last):\\n File \\\"/home/peke/Devel/robotframework/src/robot/libraries/BuiltIn.py\\\", line 330, in fail\\n raise AssertionError(msg) if msg else AssertionError()\",\"*Long doc with formatting\",\"eNqNj8FqwzAMhu97CjUPULPrcH3eoLuU7gGUxE1MHMtICqFvX8cLdDsM5oOQfn36ZdnsrmMQUC8KIwogZPaqd4iUBuipW2afFDVQOlqT3YvN7kOhoyKGJDAvUUOOHphWgZBAaOHOA6b+2cvIODDmsRLv18/zT69t7dflLBDD5MEijOxvp2ZUzW/GMLWkN8bZr8TTkXho3J8ta9DV1f9x6RZRmsvWNMk2uP9piSXE4GIQLXrJaqm0vb02FVJsy3Etce/51Lw2m8Rb6F05afXRmpLu9Z6bb2LHqoM8scPhF2Zq3z0ADI2NwA==\",\"*Non-ASCII \\u5b98\\u8bdd\",\"*

    with n\\u00f6n-\\u00e4scii \\u5b98\\u8bdd

    \",\"*with n\\u00f6n-\\u00e4scii \\u5b98\\u8bdd\",\"*hyv\\u00e4\\u00e4 joulua\",\"*Complex\",\"*

    Test doc

    \",\"*owner-kekkonen\",\"*t1\",\"*in own setup\",\"*in test\",\"*User Kw\",\"*in User Kw\",\"*${i} IN [ @{list} ]\",\"*${i} = 1\",\"*Got ${i}\",\"*Got 1\",\"*${i} = 2\",\"*Got 2\",\"*${i} = 3\",\"*Got 3\",\"*${i} = 4\",\"*Got 4\",\"*in own teardown\",\"*Log levels\",\"*This is a WARNING!\\\\n\\\\nWith multiple lines., WARN\",\"*s1-s3-t9-k2\",\"*This is a WARNING!\\n\\nWith multiple lines.\",\"*This is info, INFO\",\"*This is info\",\"*This is debug, DEBUG\",\"*This is debug\",\"*Multi-line failure\",\"*Several failures occurred:\\n\\n1) First failure\\n\\n2) Second failure\\nhas multiple\\nlines\\n\\nAlso teardown of the parent suite failed:\\nAssertionError\",\"*First failure\",\"*Second failure\\\\nhas multiple\\\\nlines\",\"*Second failure\\nhas multiple\\nlines\",\"*Escape JS &lt;/script&gt; \\\" http://url.com\",\"*

    &lt;/script&gt;

    \",\"*&lt;/script&gt;\\n\\nAlso teardown of the parent suite failed:\\nAssertionError\",\"*kw http://url.com\",\"*Long messages\",\"eNrtxsEJwCAMBdC7U2SO3jwU3KBnwUiF4JeflK7fPYrv9Iqa4QKtlb29vZ8upWwOCa1seKegS9wqq1JniD8jVHodpu1I2V0ZA/MkwQ+JA6N8\",\"*${msg} = BuiltIn.Evaluate\",\"*

    Evaluates the given expression in Python and returns the results.

    \",\"*'HelloWorld' * 100\",\"eNpTqc4tTq9VsFXwSM3JyQ/PL8pJGdosPT09AIaQUxs=\",\"*${msg}, WARN\",\"*s1-s3-t12-k3\",\"eNrzSM3JyQ/PL8pJ8RhljbJGWcOUBQDtvo6A\",\"*${msg}\",\"*Suite setup\",\"*AssertionError\",\"*higher level suite setup\",\"*Error in file '/home/peke/Devel/robotframework/src/robot/htmldata/testdata/dir.suite/tests.txt' in table 'Settings': Test library 'p\\u00f6lk\\u00fc/myLib.py' does not exist.\"]);\nwindow.output[\"generatedTimestamp\"] = \"20130213 16:37:39 GMT +03:00\";\nwindow.output[\"errors\"] = [[31,5,152],[3256,3,125,124],[3263,3,147,146]];\nwindow.output[\"stats\"] = [[{\"elapsed\":\"00:00:01\",\"fail\":11,\"label\":\"Critical Tests\",\"pass\":2},{\"elapsed\":\"00:00:03\",\"fail\":13,\"label\":\"All Tests\",\"pass\":2}],[{\"doc\":\"Me, myself, and I.\",\"elapsed\":\"00:00:03\",\"fail\":13,\"info\":\"critical\",\"label\":\"i1\",\"links\":\"Title of i1:http://1/:::Title:http://i/\",\"pass\":2},{\"doc\":\"Me, myself, and I.\",\"elapsed\":\"00:00:03\",\"fail\":13,\"info\":\"critical\",\"label\":\"i2\",\"links\":\"Title of i2:http://2/\",\"pass\":2},{\"elapsed\":\"00:00:02\",\"fail\":1,\"info\":\"non-critical\",\"label\":\"*kek*kone*\",\"pass\":0},{\"elapsed\":\"00:00:00\",\"fail\":1,\"info\":\"non-critical\",\"label\":\"owner-kekkonen\",\"pass\":0},{\"combined\":\"&lt;*&gt;\",\"elapsed\":\"00:00:00\",\"fail\":1,\"info\":\"combined\",\"label\":\"&lt;any&gt;\",\"pass\":0},{\"combined\":\"i?\",\"doc\":\"*Combined* and escaped &lt;&amp;lt; tag doc &amp; Me, myself, and I.\",\"elapsed\":\"00:00:03\",\"fail\":13,\"info\":\"combined\",\"label\":\"IX\",\"links\":\"Title of iX:http://X/\",\"pass\":2},{\"combined\":\"foo AND i*\",\"elapsed\":\"00:00:00\",\"fail\":0,\"info\":\"combined\",\"label\":\"No Match\",\"pass\":0},{\"elapsed\":\"00:00:00\",\"fail\":1,\"label\":\"!\\\"#%&amp;/()=\",\"pass\":0},{\"elapsed\":\"00:00:03\",\"fail\":12,\"label\":\"&lt; &amp;lt; \\u00e4\",\"pass\":0},{\"doc\":\"&lt;doc&gt;\",\"elapsed\":\"00:00:00\",\"fail\":1,\"label\":\"&lt;/script&gt;\",\"links\":\"&lt;title&gt;:&lt;url&gt;\",\"pass\":0},{\"elapsed\":\"00:00:00\",\"fail\":0,\"label\":\"collections\",\"pass\":2},{\"elapsed\":\"00:00:00\",\"fail\":5,\"label\":\"default with percent %\",\"pass\":0},{\"elapsed\":\"00:00:03\",\"fail\":12,\"label\":\"force\",\"links\":\"&lt;kuukkeli&amp;gt;:http://google.com\",\"pass\":0},{\"elapsed\":\"00:00:01\",\"fail\":1,\"label\":\"long1\",\"pass\":0},{\"elapsed\":\"00:00:01\",\"fail\":2,\"label\":\"long2\",\"pass\":0},{\"elapsed\":\"00:00:03\",\"fail\":3,\"label\":\"long3\",\"pass\":0},{\"elapsed\":\"00:00:00\",\"fail\":1,\"label\":\"t1\",\"links\":\"Title:http://t/\",\"pass\":0},{\"elapsed\":\"00:00:00\",\"fail\":1,\"label\":\"this test also has a pretty long tag that really is long long long long long longer than you think it could be\",\"pass\":0},{\"elapsed\":\"00:00:00\",\"fail\":1,\"label\":\"with n\\u00f6n-\\u00e4scii \\u5b98\\u8bdd\",\"pass\":0},{\"elapsed\":\"00:00:03\",\"fail\":12,\"label\":\"with space\",\"pass\":0}],[{\"elapsed\":\"00:00:03\",\"fail\":13,\"id\":\"s1\",\"label\":\"&lt;Suite.Name&gt;\",\"name\":\"&lt;Suite.Name&gt;\",\"pass\":2},{\"elapsed\":\"00:00:00\",\"fail\":0,\"id\":\"s1-s1\",\"label\":\"&lt;Suite.Name&gt;.Test.Suite.1\",\"name\":\"Test.Suite.1\",\"pass\":1},{\"elapsed\":\"00:00:00\",\"fail\":1,\"id\":\"s1-s2\",\"label\":\"&lt;Suite.Name&gt;.Test.Suite.2\",\"name\":\"Test.Suite.2\",\"pass\":1},{\"elapsed\":\"00:00:03\",\"fail\":12,\"id\":\"s1-s3\",\"label\":\"&lt;Suite.Name&gt;.Tests\",\"name\":\"Tests\",\"pass\":0}]];\nwindow.output[\"generatedMillis\"] = 3102;\nwindow.output[\"baseMillis\"] = 1360766255898;\nwindow.settings = {\"background\":{\"fail\":\"DeepPink\"},\"defaultLevel\":\"DEBUG\",\"logURL\":\"log.html\",\"minLevel\":\"DEBUG\",\"reportURL\":\"report.html\",\"title\":\"This is a long long title. A very long title indeed. And it even contains some stuff to . Yet it should still look good.\"};\n"},"message":{"kind":"string","value":"Update issue 1389\nChanged data.js\n"},"old_file":{"kind":"string","value":"src/robot/htmldata/testdata/data.js"},"subject":{"kind":"string","value":"Update issue 1389 Changed data.js"},"git_diff":{"kind":"string","value":"rc/robot/htmldata/testdata/data.js\n window.output = {};\nwindow.output[\"suite\"] = [1,2,3,4,[5,6,7,8,9,10,11,12],[0,0,3265],[[13,14,15,0,[],[1,17,8],[],[[16,0,1,0,[17,18,19],[1,24,0],[[0,20,0,21,22,[1,24,0],[],[[24,2,23]]],[0,24,0,25,26,[1,24,0],[],[[24,2,27]]]]]],[[1,28,0,0,0,[1,21,3],[[0,29,0,0,0,[1,22,1],[[0,24,0,25,30,[1,22,0],[],[[22,2,30]]],[0,31,0,0,0,[1,22,1],[[0,24,0,25,32,[1,22,1],[],[[22,2,33]]]],[]]],[]],[0,34,0,35,0,[1,23,0],[],[]],[0,36,0,0,0,[1,23,0],[[0,24,0,25,32,[1,23,0],[],[[23,2,33]]]],[[23,2,37]]]],[]]],[1,1,1,1]],[38,39,40,0,[],[0,25,5],[],[[41,0,1,0,[17,18,19],[1,26,2],[[0,42,0,43,44,[1,27,0],[],[[27,2,45]]],[0,24,0,25,46,[1,27,1],[],[[27,2,47]]]]],[48,0,1,0,[18,19,49],[0,28,1,50],[[0,51,0,0,0,[1,28,1],[[0,34,0,35,0,[1,29,0],[],[]]],[]],[0,52,0,0,53,[0,29,0],[],[[29,4,50]]]]]],[],[2,1,2,1]],[54,55,56,57,[58,59,60,12],[0,30,3234,61],[],[[62,0,1,0,[58,63,64,18,19,65],[0,32,1,66],[[1,24,0,25,67,[1,32,0],[],[[32,2,67]]],[0,24,0,25,68,[1,32,1],[],[[33,2,68]]],[2,24,0,25,69,[1,33,0],[],[[33,2,69]]]]],[70,0,1,0,[58,64,18,19,71,72,73,65],[0,33,503,66],[[1,24,0,25,67,[1,34,0],[],[[34,2,67]]],[0,74,0,75,76,[1,34,501],[],[[534,2,77]]],[2,24,0,25,69,[1,535,1],[],[[536,2,69]]]]],[78,0,1,0,[58,64,18,19,72,73,65],[0,537,704,66],[[1,24,0,25,67,[1,538,0],[],[[538,2,67]]],[0,74,0,75,79,[1,539,701],[],[[1239,2,80]]],[2,24,0,25,69,[1,1240,1],[],[[1241,2,69]]]]],[81,0,0,0,[82,58,64,18,19,73,65],[0,1242,2003,66],[[1,24,0,25,67,[1,1243,1],[],[[1243,2,67]]],[0,74,0,75,83,[1,1244,2000],[],[[3244,2,84]]],[2,24,0,25,69,[1,3245,0],[],[[3245,2,69]]]]],[85,0,1,86,[87,58,64,18,19,65],[0,3245,3,88],[[1,24,0,25,67,[1,3246,0],[],[[3246,2,67]]],[0,24,0,25,89,[1,3246,0],[],[[3246,2,90]]],[0,24,0,25,91,[1,3246,0],[],[[3246,2,92]]],[0,24,0,25,93,[1,3246,1],[],[[3247,2,93]]],[0,94,0,95,93,[0,3247,0],[],[[3247,4,93],[3247,1,96]]],[2,24,0,25,69,[1,3248,0],[],[[3248,2,69]]]]],[97,0,1,98,[58,63,64,18,19,65],[0,3248,1,66],[[1,24,0,25,67,[1,3249,0],[],[[3249,2,67]]],[0,34,0,35,0,[1,3249,0],[],[]],[2,24,0,25,69,[1,3249,0],[],[[3249,2,69]]]]],[99,0,1,100,[58,64,18,19,101,65],[0,3250,1,66],[[1,24,0,25,67,[1,3250,1],[],[[3251,2,67]]],[0,24,0,25,102,[1,3251,0],[],[[3251,2,102]]],[2,24,0,25,69,[1,3251,0],[],[[3251,2,69]]]]],[103,0,0,104,[58,64,18,19,105,106,65],[0,3251,4,66],[[1,24,0,25,107,[1,3252,0],[],[[3252,2,107]]],[0,24,0,25,108,[1,3252,0],[],[[3252,2,108]]],[0,109,0,0,0,[1,3252,1],[[0,24,0,25,110,[1,3253,0],[],[[3253,2,110]]]],[]],[3,111,0,0,0,[1,3253,2],[[4,112,0,0,0,[1,3253,0],[[0,24,0,25,113,[1,3253,0],[],[[3253,2,114]]]],[]],[4,115,0,0,0,[1,3254,0],[[0,24,0,25,113,[1,3254,0],[],[[3254,2,116]]]],[]],[4,117,0,0,0,[1,3254,0],[[0,24,0,25,113,[1,3254,0],[],[[3254,2,118]]]],[]],[4,119,0,0,0,[1,3254,1],[[0,24,0,25,113,[1,3254,1],[],[[3255,2,120]]]],[]]],[]],[2,24,0,25,121,[1,3255,0],[],[[3255,2,121]]]]],[122,0,1,0,[58,63,64,18,19,65],[0,3255,2,66],[[1,24,0,25,67,[1,3256,0],[],[[3256,2,67]]],[0,24,0,25,123,[1,3256,0],[],[[3256,3,125]]],[0,24,0,25,126,[1,3256,0],[],[[3256,2,127]]],[0,24,0,25,128,[1,3257,0],[],[[3257,1,129]]],[2,24,0,25,69,[1,3257,0],[],[[3257,2,69]]]]],[130,0,1,0,[58,63,64,18,19,65],[0,3257,2,131],[[1,24,0,25,67,[1,3258,0],[],[[3258,2,67]]],[0,94,0,95,132,[0,3258,0],[],[[3258,4,132],[3258,1,96]]],[0,94,0,95,133,[0,3258,1],[],[[3259,4,134],[3259,1,96]]],[2,24,0,25,69,[1,3259,0],[],[[3259,2,69]]]]],[135,0,1,136,[58,5,64,18,19,65],[0,3259,3,137],[[1,24,0,25,67,[1,3260,0],[],[[3260,2,67]]],[0,24,0,25,5,[1,3260,0],[],[[3260,2,5]]],[0,138,0,0,0,[1,3260,1],[[0,34,0,35,0,[1,3260,1],[],[]]],[]],[0,5,0,0,0,[0,3261,0],[[0,94,0,95,5,[0,3261,0],[],[[3261,4,5],[3261,1,96]]]],[]],[2,24,0,25,69,[1,3261,1],[],[[3262,2,69]]]]],[139,0,1,0,[58,63,64,18,19,65],[0,3262,2,140],[[1,24,0,25,67,[1,3262,0],[],[[3262,2,67]]],[0,141,0,142,143,[1,3262,1],[],[[3263,2,144]]],[0,24,0,25,145,[1,3263,0],[],[[3263,3,147]]],[0,94,0,95,148,[0,3263,0],[],[[3263,4,147],[3263,1,96]]],[2,24,0,25,69,[1,3263,1],[],[[3264,2,69]]]]]],[[1,24,0,25,149,[1,32,0],[],[[32,2,149]]],[2,94,0,95,0,[0,3264,0,150],[],[[3264,4,150],[3264,1,96]]]],[12,0,10,0]]],[],[[1,24,0,25,151,[1,17,0],[],[[17,2,151]]]],[15,2,13,2]];\nwindow.output[\"suite\"] = [1,2,3,4,[5,6,7,8,9,10,11,12],[0,0,3289],[[13,14,15,0,[],[1,26,12],[],[[16,0,1,0,[17,18,19],[1,36,2],[[0,20,0,21,22,[1,37,0],[],[[37,2,23]]],[0,24,0,25,26,[1,37,1],[],[[37,2,27]]]]]],[[1,28,0,0,0,[1,33,3],[[0,29,0,0,0,[1,34,1],[[0,24,0,25,30,[1,34,0],[],[[34,2,30]]],[0,31,0,0,0,[1,34,1],[[0,24,0,25,32,[1,35,0],[],[[35,2,33]]]],[]]],[]],[0,34,0,35,0,[1,35,0],[],[]],[0,36,0,0,0,[1,35,1],[[0,24,0,25,32,[1,36,0],[],[[36,2,33]]]],[[36,2,37]]]],[]]],[1,1,1,1]],[38,39,40,0,[],[0,38,6],[],[[41,0,1,0,[17,18,19],[1,40,1],[[0,42,0,43,44,[1,41,0],[],[[41,2,45]]],[0,24,0,25,46,[1,41,0],[],[[41,2,47]]]]],[48,0,1,0,[18,19,49],[0,42,2,50],[[0,51,0,0,0,[1,43,0],[[0,34,0,35,0,[1,43,0],[],[]]],[]],[0,52,0,0,53,[0,43,1],[],[[44,4,50]]]]]],[],[2,1,2,1]],[54,55,56,57,[58,59,60,12],[0,45,3243,61],[],[[62,0,1,0,[58,63,64,18,19,65],[0,48,1,66],[[1,24,0,25,67,[1,48,1],[],[[48,2,67]]],[0,24,0,25,68,[1,49,0],[],[[49,2,68]]],[2,24,0,25,69,[1,49,0],[],[[49,2,69]]]]],[70,0,1,0,[58,64,18,19,71,72,73,65],[0,50,502,66],[[1,24,0,25,67,[1,50,0],[],[[50,2,67]]],[0,74,0,75,76,[1,50,502],[],[[551,2,77]]],[2,24,0,25,69,[1,552,0],[],[[552,2,69]]]]],[78,0,1,0,[58,64,18,19,72,73,65],[0,552,704,66],[[1,24,0,25,67,[1,553,0],[],[[553,2,67]]],[0,74,0,75,79,[1,553,702],[],[[1255,2,80]]],[2,24,0,25,69,[1,1255,1],[],[[1256,2,69]]]]],[81,0,0,0,[82,58,64,18,19,73,65],[0,1256,2004,66],[[1,24,0,25,67,[1,1257,1],[],[[1258,2,67]]],[0,74,0,75,83,[1,1258,2002],[],[[3259,2,84]]],[2,24,0,25,69,[1,3260,0],[],[[3260,2,69]]]]],[85,0,1,86,[87,58,64,18,19,65],[0,3260,6,88],[[1,24,0,25,67,[1,3261,0],[],[[3261,2,67]]],[0,24,0,25,89,[1,3261,1],[],[[3262,2,90]]],[0,24,0,25,91,[1,3262,0],[],[[3262,2,92]]],[0,24,0,25,93,[1,3262,0],[],[[3262,2,93]]],[0,94,0,95,93,[0,3263,2],[],[[3265,4,93],[3265,1,96]]],[2,24,0,25,69,[1,3266,0],[],[[3266,2,69]]]]],[97,0,1,98,[58,63,64,18,19,65],[0,3266,2,66],[[1,24,0,25,67,[1,3267,0],[],[[3267,2,67]]],[0,34,0,35,0,[1,3267,1],[],[]],[2,24,0,25,69,[1,3268,0],[],[[3268,2,69]]]]],[99,0,1,100,[58,64,18,19,101,65],[0,3268,2,66],[[1,24,0,25,67,[1,3269,1],[],[[3270,2,67]]],[0,24,0,25,102,[1,3270,0],[],[[3270,2,102]]],[2,24,0,25,69,[1,3270,0],[],[[3270,2,69]]]]],[103,0,0,104,[58,64,18,19,105,106,65],[0,3271,4,66],[[1,24,0,25,107,[1,3271,0],[],[[3271,2,107]]],[0,24,0,25,108,[1,3272,0],[],[[3272,2,108]]],[0,109,0,0,0,[1,3272,1],[[0,24,0,25,110,[1,3272,0],[],[[3272,2,110]]]],[]],[3,111,0,0,0,[1,3273,2],[[4,112,0,0,0,[1,3273,0],[[0,24,0,25,113,[1,3273,0],[],[[3273,2,114]]]],[]],[4,115,0,0,0,[1,3273,1],[[0,24,0,25,113,[1,3273,1],[],[[3274,2,116]]]],[]],[4,117,0,0,0,[1,3274,0],[[0,24,0,25,113,[1,3274,0],[],[[3274,2,118]]]],[]],[4,119,0,0,0,[1,3274,1],[[0,24,0,25,113,[1,3274,1],[],[[3274,2,120]]]],[]]],[]],[2,24,0,25,121,[1,3275,0],[],[[3275,2,121]]]]],[122,0,1,0,[58,63,64,18,19,65],[0,3275,3,66],[[1,24,0,25,67,[1,3276,0],[],[[3276,2,67]]],[0,24,0,25,123,[1,3276,0],[],[[3276,3,125]]],[0,24,0,25,126,[1,3277,0],[],[[3277,2,127]]],[0,24,0,25,128,[1,3277,0],[],[[3277,1,129]]],[2,24,0,25,69,[1,3277,0],[],[[3277,2,69]]]]],[130,0,1,0,[58,63,64,18,19,65],[0,3278,2,131],[[1,24,0,25,67,[1,3278,1],[],[[3279,2,67]]],[0,94,0,95,132,[0,3279,0],[],[[3279,4,132],[3279,1,96]]],[0,94,0,95,133,[0,3279,1],[],[[3279,4,134],[3280,1,96]]],[2,24,0,25,69,[1,3280,0],[],[[3280,2,69]]]]],[135,0,1,136,[58,5,64,18,19,65],[0,3280,4,137],[[1,24,0,25,67,[1,3281,0],[],[[3281,2,67]]],[0,24,0,25,5,[1,3281,0],[],[[3281,2,5]]],[0,138,0,0,0,[1,3282,0],[[0,34,0,35,0,[1,3282,0],[],[]]],[]],[0,5,0,0,0,[0,3282,1],[[0,94,0,95,5,[0,3283,0],[],[[3283,4,5],[3283,1,96]]]],[]],[2,24,0,25,69,[1,3283,1],[],[[3284,2,69]]]]],[139,0,1,0,[58,63,64,18,19,65],[0,3284,3,140],[[1,24,0,25,67,[1,3284,1],[],[[3285,2,67]]],[0,141,0,142,143,[1,3285,0],[],[[3285,2,144]]],[0,24,0,25,145,[1,3285,1],[],[[3285,3,147]]],[0,94,0,95,148,[0,3286,1],[],[[3286,4,147],[3286,1,96]]],[2,24,0,25,69,[1,3287,0],[],[[3287,2,69]]]]]],[[1,24,0,25,149,[1,47,1],[],[[48,2,149]]],[2,94,0,95,0,[0,3288,0,150],[],[[3288,4,150],[3288,1,96]]]],[12,0,10,0]]],[],[[1,24,0,25,151,[1,26,0],[],[[26,2,151]]]],[15,2,13,2]];\n window.output[\"strings\"] = [];\nwindow.output[\"strings\"] = window.output[\"strings\"].concat([\"*\",\"*&lt;Suite.Name&gt;\",\"*/home/peke/Devel/robotframework/src/robot/htmldata/testdata/dir.suite\",\"*dir.suite\",\"eNrFVNFq3TAMfd79CpEPiOl9GZQ0YzAKg+7lbvsAJ1EcU8cyskLWv5+c9O7ejg7KGOxFJEdHx5IsuUntJ+qXGaNY8RRhJAaZENaJAoJgFsiLF6zhYwjq8blQ5gwWso9OOcmydWzTBFksi4IwMs1wuodj/b4+amQcNs0LU1UcysZNrB9PECi6/838uqRELDhsJdqdoeQBZ4pZ2BZXh4HWujGpPTRLUBN823Tt99PDbWO6FhoLE+N4V00i6dYYpo5kZDvjSvxYE7uq/aOrMbZtjCrusr79PFuHKuxV2M8OMve/lHsasHZEegl1T7NJvwmaQI4+4A+pU3QViJeAfxn8Mikt98HHx63ePbU31HwqGNyfwZeVbmVCKKJvEvu3vXj1hEt+ZrvmidWI7XTiO+IB+a66qQq04UNpypenvSP6d4a+lYAr1Oz055ibC/f4KmEkupK7ZpgtFf1ILaNbguXSPtznUqe6PagBzeB5lHEoWRwAeoqi2/5u9TLplutq52R7zCq5he2Fnid79KwvQPBqlDlfbiyjCg0XT9mTIu3joksCS3kcyvGy0rYWgx9HZD0YbEpMtp8wX/X3J45wjUo=\",\"*&lt;/script&gt;\",\"*

    &lt; &amp;lt; &lt;/script&gt;

    \",\"*Formatting\",\"*

    Bold and italics

    \",\"*Image\",\"eNqdy9ENgCAMBcBVDAPQf4M4i2KtRPA1tYmO7w7e/yXNqXYZbitTONx1JCrYOAogjWNBJyXDCt9t6fzATmoQzPx61EvC4NUb/8w5keYPXLwvxw==\",\"*URL\",\"*

    http://robotframework.org

    \",\"*Test.Suite.1\",\"*/home/peke/Devel/robotframework/src/robot/htmldata/testdata/dir.suite/test.suite.1.txt\",\"*dir.suite/test.suite.1.txt\",\"*list test\",\"*collections\",\"*i1\",\"*i2\",\"*${list} = BuiltIn.Create List\",\"*

    Returns a list containing given items.

    \",\"*foo, bar, quux\",\"*${list} = [u'foo', u'bar', u'quux']\",\"*BuiltIn.Log\",\"*

    Logs the given message with the given level.

    \",\"*${list}\",\"*[u'foo', u'bar', u'quux']\",\"*User Keyword\",\"*User Keyword 2\",\"*Several levels...\",\"*User Keyword 3\",\"*&lt;b&gt;The End&lt;/b&gt;, HTML\",\"*The End\",\"*BuiltIn.No Operation\",\"*

    Does absolutely nothing.

    \",\"*${ret} = User Keyword 3\",\"*${ret} = None\",\"*Test.Suite.2\",\"*/home/peke/Devel/robotframework/src/robot/htmldata/testdata/dir.suite/test.suite.2.txt\",\"*dir.suite/test.suite.2.txt\",\"*Dictionary test\",\"*${dict} = Collections.Create Dictionary\",\"*

    Creates and returns a dictionary from the given `key_value_pairs`.

    \",\"*key, value\",\"*${dict} = {u'key': u'value'}\",\"*${dict}\",\"*{u'key': u'value'}\",\"*Test with a rather long name here we have and the name really is pretty long long long long longer than you think it could be\",\"*this test also has a pretty long tag that really is long long long long long longer than you think it could be\",\"*No keyword with name 'This keyword gets many arguments' found.\",\"eNrzTq0szy9KUShPVchILAMSqUWpCpnFCkWJJUCmQk5+XjpOAihfkpGYp1CZXwpkZOZlK2SWKCTnl+akKCSlYiIIAAAZ9Cgs\",\"*This keyword gets many arguments\",\"eNrLLNFRKEpNzMmp1FFITy0p1lHITcwDshOL0ktzU/NAAplDSQkAaktIdQ==\",\"*Tests\",\"*/home/peke/Devel/robotframework/src/robot/htmldata/testdata/dir.suite/tests.txt\",\"*dir.suite/tests.txt\",\"*

    Some suite docs with links: http://robotframework.org

    \",\"*&lt; &amp;lt; \\u00e4\",\"*

    &lt; &amp;lt; \\u00e4

    \",\"*home *page*\",\"*Suite teardown failed:\\nAssertionError\",\"*Simple\",\"*default with percent %\",\"*force\",\"*with space\",\"*Teardown of the parent suite failed:\\nAssertionError\",\"*Test Setup\",\"*do nothing\",\"*Test Teardown\",\"*Long\",\"*long1\",\"*long2\",\"*long3\",\"*BuiltIn.Sleep\",\"*

    Pauses the test executed for the given time.

    \",\"*0.5 seconds\",\"*Slept 500 milliseconds\",\"*Longer\",\"*0.7 second\",\"*Slept 700 milliseconds\",\"*Longest\",\"**kek*kone*\",\"*2 seconds\",\"*Slept 2 seconds\",\"*Log HTML\",\"*

    This test uses formatted HTML.

    \\n\\n\\n\\n\\n\\n\\n
    Isn'tthatcool?
    \",\"*!\\\"#%&amp;/()=\",\"*escape &lt; &amp;lt; &lt;b&gt;no bold&lt;/b&gt;\\n\\nAlso teardown of the parent suite failed:\\nAssertionError\",\"*&lt;blink&gt;&lt;b&gt;&lt;font face=\\\"comic sans ms\\\" size=\\\"42\\\" color=\\\"red\\\"&gt;CAN HAZ HMTL &amp; NO CSS?!?!??!!?&lt;/font&gt;&lt;/b&gt;&lt;/blink&gt;, HTML\",\"*CAN HAZ HMTL & NO CSS?!?!??!!?\",\"eNpTyymxLklMyklVSy+xVgNxiuCsFBArJCOzWAGiAi5WnJFfmpOikJFYlopNS16+QnFBanJmYg5CLC2/KDexpCQzLx0kpg+3UkfBI8TXBwBuyS8B\",\"*
    This tableshould have
    no specialformatting
    \",\"*escape &lt; &amp;lt; &lt;b&gt;no bold&lt;/b&gt;\",\"*BuiltIn.Fail\",\"*

    Fails the test with the given message and optionally alters its tags.

    \",\"*Traceback (most recent call last):\\n File \\\"/home/peke/Devel/robotframework/src/robot/libraries/BuiltIn.py\\\", line 330, in fail\\n raise AssertionError(msg) if msg else AssertionError()\",\"*Long doc with formatting\",\"eNqNj8FqwzAMhu97CjUPULPrcH3eoLuU7gGUxE1MHMtICqFvX8cLdDsM5oOQfn36ZdnsrmMQUC8KIwogZPaqd4iUBuipW2afFDVQOlqT3YvN7kOhoyKGJDAvUUOOHphWgZBAaOHOA6b+2cvIODDmsRLv18/zT69t7dflLBDD5MEijOxvp2ZUzW/GMLWkN8bZr8TTkXho3J8ta9DV1f9x6RZRmsvWNMk2uP9piSXE4GIQLXrJaqm0vb02FVJsy3Etce/51Lw2m8Rb6F05afXRmpLu9Z6bb2LHqoM8scPhF2Zq3z0ADI2NwA==\",\"*Non-ASCII \\u5b98\\u8bdd\",\"*

    with n\\u00f6n-\\u00e4scii \\u5b98\\u8bdd

    \",\"*with n\\u00f6n-\\u00e4scii \\u5b98\\u8bdd\",\"*hyv\\u00e4\\u00e4 joulua\",\"*Complex\",\"*

    Test doc

    \",\"*owner-kekkonen\",\"*t1\",\"*in own setup\",\"*in test\",\"*User Kw\",\"*in User Kw\",\"*${i} IN [ @{list} ]\",\"*${i} = 1\",\"*Got ${i}\",\"*Got 1\",\"*${i} = 2\",\"*Got 2\",\"*${i} = 3\",\"*Got 3\",\"*${i} = 4\",\"*Got 4\",\"*in own teardown\",\"*Log levels\",\"*This is a WARNING!\\\\n\\\\nWith multiple lines., WARN\",\"*s1-s3-t9-k2\",\"*This is a WARNING!\\n\\nWith multiple lines.\",\"*This is info, INFO\",\"*This is info\",\"*This is debug, DEBUG\",\"*This is debug\",\"*Multi-line failure\",\"*Several failures occurred:\\n\\n1) First failure\\n\\n2) Second failure\\nhas multiple\\nlines\\n\\nAlso teardown of the parent suite failed:\\nAssertionError\",\"*First failure\",\"*Second failure\\\\nhas multiple\\\\nlines\",\"*Second failure\\nhas multiple\\nlines\",\"*Escape JS &lt;/script&gt; \\\" http://url.com\",\"*

    &lt;/script&gt;

    \",\"*&lt;/script&gt;\\n\\nAlso teardown of the parent suite failed:\\nAssertionError\",\"*kw http://url.com\",\"*Long messages\",\"eNrtxsEJwCAMBdC7U2SO3jwU3KBnwUiF4JeflK7fPYrv9Iqa4QKtlb29vZ8upWwOCa1seKegS9wqq1JniD8jVHodpu1I2V0ZA/MkwQ+JA6N8\",\"*${msg} = BuiltIn.Evaluate\",\"*

    Evaluates the given expression in Python and returns the results.

    \",\"*'HelloWorld' * 100\",\"eNpTqc4tTq9VsFXwSM3JyQ/PL8pJGdosPT09AIaQUxs=\",\"*${msg}, WARN\",\"*s1-s3-t12-k3\",\"eNrzSM3JyQ/PL8pJ8RhljbJGWcOUBQDtvo6A\",\"*${msg}\",\"*Suite setup\",\"*AssertionError\",\"*higher level suite setup\",\"*Error in file '/home/peke/Devel/robotframework/src/robot/htmldata/testdata/dir.suite/tests.txt' in table 'Settings': Test library 'p\\u00f6lk\\u00fc/myLib.py' does not exist.\"]);\nwindow.output[\"generatedTimestamp\"] = \"20130213 16:37:39 GMT +03:00\";\nwindow.output[\"errors\"] = [[31,5,152],[3256,3,125,124],[3263,3,147,146]];\nwindow.output[\"strings\"] = window.output[\"strings\"].concat([\"*\",\"*&lt;Suite.Name&gt;\",\"*/Users/mikhanni/koodi/robotframework/src/robot/htmldata/testdata/dir.suite\",\"*dir.suite\",\"eNrFlOGK2zAMxz+vTyH6ADFNDwZHLmMwDgbdl657ACdRHHNOZGRn3b39ZKdd29HBMQb7Ylrpp78lxVLl60/UziNOUUdLE/TEEAeE40AOIWKIEGYbsYCPzonHhoSMATQEOxlhvGZtWPsBQtQcxQg90wj7ZyiL90UpkVOXNS+kqBiMmfUsP17B0WT+N/l19p44YpdL1AshcIcjTSGyTq4GHR2LSvl6VQ1lfbBRerDD7+hgUymxrCpfH/BHzK10Z0fGtzd4Kfj2Hl6e8IcbfCv4wz18u+Czk8PZumrqb/vdY6WaGioNA2P/tB5i9I9KMTUUe9YjHolfCmKzrv/oqpSuKyWKi6ytP4/aoAhbEbajgcDtL+WWOiwMkbyIoqVR+d8ElSNDHyTxwk9mDTEV9pfBt0lJuTs7veR6l9TeUPM+2eD5bLytNJcJLom+Sezf9uLuDZf8VP7MA8sRdSOPoyHukJ/Wm3UyZXuXmvLldemI/DubDingyqoW/BSzubDlXaAnupK7JlROJb9NRjM7zal9uLxLGbF6JQdIBqe5wi5lsQJoaYqyet4dbRxk5cieCV63GEQyhy2Fnl92b1nWkbNyCDlevlhAEeounjS0SdpOs0wszGlTpevjkfJYdLbvkeVi0N4z6XbAcNXfn1KauKA=\",\"*&lt;/script&gt;\",\"*

    &lt; &amp;lt; &lt;/script&gt;

    \",\"*Formatting\",\"*

    Bold and italics

    \",\"*Image\",\"eNqdy9ENgCAMBcBVDAPQf4M4i2KtRPA1tYmO7w7e/yXNqXYZbitTONx1JCrYOAogjWNBJyXDCt9t6fzATmoQzPx61EvC4NUb/8w5keYPXLwvxw==\",\"*URL\",\"*

    http://robotframework.org

    \",\"*Test.Suite.1\",\"*/Users/mikhanni/koodi/robotframework/src/robot/htmldata/testdata/dir.suite/test.suite.1.txt\",\"*dir.suite/test.suite.1.txt\",\"*list test\",\"*collections\",\"*i1\",\"*i2\",\"*${list} = BuiltIn.Create List\",\"*

    Returns a list containing given items.

    \",\"*foo, bar, quux\",\"*${list} = [u'foo', u'bar', u'quux']\",\"*BuiltIn.Log\",\"*

    Logs the given message with the given level.

    \",\"*${list}\",\"*[u'foo', u'bar', u'quux']\",\"*User Keyword\",\"*User Keyword 2\",\"*Several levels...\",\"*User Keyword 3\",\"*&lt;b&gt;The End&lt;/b&gt;, HTML\",\"*The End\",\"*BuiltIn.No Operation\",\"*

    Does absolutely nothing.

    \",\"*${ret} = User Keyword 3\",\"*${ret} = None\",\"*Test.Suite.2\",\"*/Users/mikhanni/koodi/robotframework/src/robot/htmldata/testdata/dir.suite/test.suite.2.txt\",\"*dir.suite/test.suite.2.txt\",\"*Dictionary test\",\"*${dict} = Collections.Create Dictionary\",\"*

    Creates and returns a dictionary from the given `key_value_pairs`.

    \",\"*key, value\",\"*${dict} = {u'key': u'value'}\",\"*${dict}\",\"*{u'key': u'value'}\",\"*Test with a rather long name here we have and the name really is pretty long long long long longer than you think it could be\",\"*this test also has a pretty long tag that really is long long long long long longer than you think it could be\",\"*No keyword with name 'This keyword gets many arguments' found.\",\"eNrzTq0szy9KUShPVchILAMSqUWpCpnFCkWJJUCmQk5+XjpOAihfkpGYp1CZXwpkZOZlK2SWKCTnl+akKCSlYiIIAAAZ9Cgs\",\"*This keyword gets many arguments\",\"eNrLLNFRKEpNzMmp1FFITy0p1lHITcwDshOL0ktzU/NAAplDSQkAaktIdQ==\",\"*Tests\",\"*/Users/mikhanni/koodi/robotframework/src/robot/htmldata/testdata/dir.suite/tests.txt\",\"*dir.suite/tests.txt\",\"*

    Some suite docs with links: http://robotframework.org

    \",\"*&lt; &amp;lt; \\u00e4\",\"*

    &lt; &amp;lt; \\u00e4

    \",\"*home *page*\",\"*Suite teardown failed:\\nAssertionError\",\"*Simple\",\"*default with percent %\",\"*force\",\"*with space\",\"*Teardown of the parent suite failed:\\nAssertionError\",\"*Test Setup\",\"*do nothing\",\"*Test Teardown\",\"*Long\",\"*long1\",\"*long2\",\"*long3\",\"*BuiltIn.Sleep\",\"*

    Pauses the test executed for the given time.

    \",\"*0.5 seconds\",\"*Slept 500 milliseconds\",\"*Longer\",\"*0.7 second\",\"*Slept 700 milliseconds\",\"*Longest\",\"**kek*kone*\",\"*2 seconds\",\"*Slept 2 seconds\",\"*Log HTML\",\"*

    This test uses formatted HTML.

    \\n\\n\\n\\n\\n\\n\\n
    Isn'tthatcool?
    \",\"*!\\\"#%&amp;/()=\",\"*escape &lt; &amp;lt; &lt;b&gt;no bold&lt;/b&gt;\\n\\nAlso teardown of the parent suite failed:\\nAssertionError\",\"*&lt;blink&gt;&lt;b&gt;&lt;font face=\\\"comic sans ms\\\" size=\\\"42\\\" color=\\\"red\\\"&gt;CAN HAZ HMTL &amp; NO CSS?!?!??!!?&lt;/font&gt;&lt;/b&gt;&lt;/blink&gt;, HTML\",\"*CAN HAZ HMTL & NO CSS?!?!??!!?\",\"eNpTyymxLklMyklVSy+xVgNxiuCsFBArJCOzWAGiAi5WnJFfmpOikJFYlopNS16+QnFBanJmYg5CLC2/KDexpCQzLx0kpg+3UkfBI8TXBwBuyS8B\",\"*
    This tableshould have
    no specialformatting
    \",\"*escape &lt; &amp;lt; &lt;b&gt;no bold&lt;/b&gt;\",\"*BuiltIn.Fail\",\"*

    Fails the test with the given message and optionally alters its tags.

    \",\"*Traceback (most recent call last):\\n File \\\"/Users/mikhanni/koodi/robotframework/src/robot/libraries/BuiltIn.py\\\", line 330, in fail\\n raise AssertionError(msg) if msg else AssertionError()\",\"*Long doc with formatting\",\"eNqNj8FqwzAMhu97CjUPULPrcH3eoLuU7gGUxE1MHMtICqFvX8cLdDsM5oOQfn36ZdnsrmMQUC8KIwogZPaqd4iUBuipW2afFDVQOlqT3YvN7kOhoyKGJDAvUUOOHphWgZBAaOHOA6b+2cvIODDmsRLv18/zT69t7dflLBDD5MEijOxvp2ZUzW/GMLWkN8bZr8TTkXho3J8ta9DV1f9x6RZRmsvWNMk2uP9piSXE4GIQLXrJaqm0vb02FVJsy3Etce/51Lw2m8Rb6F05afXRmpLu9Z6bb2LHqoM8scPhF2Zq3z0ADI2NwA==\",\"*Non-ASCII \\u5b98\\u8bdd\",\"*

    with n\\u00f6n-\\u00e4scii \\u5b98\\u8bdd

    \",\"*with n\\u00f6n-\\u00e4scii \\u5b98\\u8bdd\",\"*hyv\\u00e4\\u00e4 joulua\",\"*Complex\",\"*

    Test doc

    \",\"*owner-kekkonen\",\"*t1\",\"*in own setup\",\"*in test\",\"*User Kw\",\"*in User Kw\",\"*${i} IN [ @{list} ]\",\"*${i} = 1\",\"*Got ${i}\",\"*Got 1\",\"*${i} = 2\",\"*Got 2\",\"*${i} = 3\",\"*Got 3\",\"*${i} = 4\",\"*Got 4\",\"*in own teardown\",\"*Log levels\",\"*This is a WARNING!\\\\n\\\\nWith multiple lines., WARN\",\"*s1-s3-t9-k2\",\"*This is a WARNING!\\n\\nWith multiple lines.\",\"*This is info, INFO\",\"*This is info\",\"*This is debug, DEBUG\",\"*This is debug\",\"*Multi-line failure\",\"*Several failures occurred:\\n\\n1) First failure\\n\\n2) Second failure\\nhas multiple\\nlines\\n\\nAlso teardown of the parent suite failed:\\nAssertionError\",\"*First failure\",\"*Second failure\\\\nhas multiple\\\\nlines\",\"*Second failure\\nhas multiple\\nlines\",\"*Escape JS &lt;/script&gt; \\\" http://url.com\",\"*

    &lt;/script&gt;

    \",\"*&lt;/script&gt;\\n\\nAlso teardown of the parent suite failed:\\nAssertionError\",\"*kw http://url.com\",\"*Long messages\",\"eNrtxsEJwCAMBdC7U2SO3jwU3KBnwUiF4JeflK7fPYrv9Iqa4QKtlb29vZ8upWwOCa1seKegS9wqq1JniD8jVHodpu1I2V0ZA/MkwQ+JA6N8\",\"*${msg} = BuiltIn.Evaluate\",\"*

    Evaluates the given expression in Python and returns the results.

    \",\"*'HelloWorld' * 100\",\"eNpTqc4tTq9VsFXwSM3JyQ/PL8pJGdosPT09AIaQUxs=\",\"*${msg}, WARN\",\"*s1-s3-t12-k3\",\"eNrzSM3JyQ/PL8pJ8RhljbJGWcOUBQDtvo6A\",\"*${msg}\",\"*Suite setup\",\"*AssertionError\",\"*higher level suite setup\",\"*Error in file '/Users/mikhanni/koodi/robotframework/src/robot/htmldata/testdata/dir.suite/tests.txt' in table 'Settings': Test library 'p\\u00f6lk\\u00fc/myLib.py' does not exist.\"]);\nwindow.output[\"generatedTimestamp\"] = \"20130415 12:34:12 GMT +03:00\";\nwindow.output[\"errors\"] = [[47,5,152],[3276,3,125,124],[3285,3,147,146]];\n window.output[\"stats\"] = [[{\"elapsed\":\"00:00:01\",\"fail\":11,\"label\":\"Critical Tests\",\"pass\":2},{\"elapsed\":\"00:00:03\",\"fail\":13,\"label\":\"All Tests\",\"pass\":2}],[{\"doc\":\"Me, myself, and I.\",\"elapsed\":\"00:00:03\",\"fail\":13,\"info\":\"critical\",\"label\":\"i1\",\"links\":\"Title of i1:http://1/:::Title:http://i/\",\"pass\":2},{\"doc\":\"Me, myself, and I.\",\"elapsed\":\"00:00:03\",\"fail\":13,\"info\":\"critical\",\"label\":\"i2\",\"links\":\"Title of i2:http://2/\",\"pass\":2},{\"elapsed\":\"00:00:02\",\"fail\":1,\"info\":\"non-critical\",\"label\":\"*kek*kone*\",\"pass\":0},{\"elapsed\":\"00:00:00\",\"fail\":1,\"info\":\"non-critical\",\"label\":\"owner-kekkonen\",\"pass\":0},{\"combined\":\"&lt;*&gt;\",\"elapsed\":\"00:00:00\",\"fail\":1,\"info\":\"combined\",\"label\":\"&lt;any&gt;\",\"pass\":0},{\"combined\":\"i?\",\"doc\":\"*Combined* and escaped &lt;&amp;lt; tag doc &amp; Me, myself, and I.\",\"elapsed\":\"00:00:03\",\"fail\":13,\"info\":\"combined\",\"label\":\"IX\",\"links\":\"Title of iX:http://X/\",\"pass\":2},{\"combined\":\"foo AND i*\",\"elapsed\":\"00:00:00\",\"fail\":0,\"info\":\"combined\",\"label\":\"No Match\",\"pass\":0},{\"elapsed\":\"00:00:00\",\"fail\":1,\"label\":\"!\\\"#%&amp;/()=\",\"pass\":0},{\"elapsed\":\"00:00:03\",\"fail\":12,\"label\":\"&lt; &amp;lt; \\u00e4\",\"pass\":0},{\"doc\":\"&lt;doc&gt;\",\"elapsed\":\"00:00:00\",\"fail\":1,\"label\":\"&lt;/script&gt;\",\"links\":\"&lt;title&gt;:&lt;url&gt;\",\"pass\":0},{\"elapsed\":\"00:00:00\",\"fail\":0,\"label\":\"collections\",\"pass\":2},{\"elapsed\":\"00:00:00\",\"fail\":5,\"label\":\"default with percent %\",\"pass\":0},{\"elapsed\":\"00:00:03\",\"fail\":12,\"label\":\"force\",\"links\":\"&lt;kuukkeli&amp;gt;:http://google.com\",\"pass\":0},{\"elapsed\":\"00:00:01\",\"fail\":1,\"label\":\"long1\",\"pass\":0},{\"elapsed\":\"00:00:01\",\"fail\":2,\"label\":\"long2\",\"pass\":0},{\"elapsed\":\"00:00:03\",\"fail\":3,\"label\":\"long3\",\"pass\":0},{\"elapsed\":\"00:00:00\",\"fail\":1,\"label\":\"t1\",\"links\":\"Title:http://t/\",\"pass\":0},{\"elapsed\":\"00:00:00\",\"fail\":1,\"label\":\"this test also has a pretty long tag that really is long long long long long longer than you think it could be\",\"pass\":0},{\"elapsed\":\"00:00:00\",\"fail\":1,\"label\":\"with n\\u00f6n-\\u00e4scii \\u5b98\\u8bdd\",\"pass\":0},{\"elapsed\":\"00:00:03\",\"fail\":12,\"label\":\"with space\",\"pass\":0}],[{\"elapsed\":\"00:00:03\",\"fail\":13,\"id\":\"s1\",\"label\":\"&lt;Suite.Name&gt;\",\"name\":\"&lt;Suite.Name&gt;\",\"pass\":2},{\"elapsed\":\"00:00:00\",\"fail\":0,\"id\":\"s1-s1\",\"label\":\"&lt;Suite.Name&gt;.Test.Suite.1\",\"name\":\"Test.Suite.1\",\"pass\":1},{\"elapsed\":\"00:00:00\",\"fail\":1,\"id\":\"s1-s2\",\"label\":\"&lt;Suite.Name&gt;.Test.Suite.2\",\"name\":\"Test.Suite.2\",\"pass\":1},{\"elapsed\":\"00:00:03\",\"fail\":12,\"id\":\"s1-s3\",\"label\":\"&lt;Suite.Name&gt;.Tests\",\"name\":\"Tests\",\"pass\":0}]];\nwindow.output[\"generatedMillis\"] = 3102;\nwindow.output[\"baseMillis\"] = 1360766255898;\nwindow.output[\"generatedMillis\"] = 2480;\nwindow.output[\"baseMillis\"] = 1366018449520;\n window.settings = {\"background\":{\"fail\":\"DeepPink\"},\"defaultLevel\":\"DEBUG\",\"logURL\":\"log.html\",\"minLevel\":\"DEBUG\",\"reportURL\":\"report.html\",\"title\":\"This is a long long title. A very long title indeed. And it even contains some stuff to . Yet it should still look good.\"};"}}},{"rowIdx":1983,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"eb2720de4f69c6902e621380baba92192c0f7869"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"apache/creadur-rat,eskatos/creadur-rat,eskatos/creadur-rat,eskatos/creadur-rat,apache/creadur-rat,apache/creadur-rat,eskatos/creadur-rat,apache/creadur-rat,eskatos/creadur-rat,apache/creadur-rat,apache/creadur-rat,eskatos/creadur-rat"},"new_contents":{"kind":"string","value":"/*\n * Licensed to the Apache Software Foundation (ASF) under one *\n * or more contributor license agreements. See the NOTICE file *\n * distributed with this work for additional information *\n * regarding copyright ownership. The ASF licenses this file *\n * to you under the Apache License, Version 2.0 (the *\n * \"License\"); you may not use this file except in compliance *\n * with the License. You may obtain a copy of the License at *\n * *\n * http://www.apache.org/licenses/LICENSE-2.0 *\n * *\n * Unless required by applicable law or agreed to in writing, *\n * software distributed under the License is distributed on an *\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *\n * KIND, either express or implied. See the License for the *\n * specific language governing permissions and limitations *\n * under the License. *\n */ \npackage org.apache.rat.annotation;\n\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.util.Random;\n\nimport junit.framework.TestCase;\n\npublic class TestLicenceAppender extends TestCase {\n /** Used to ensure that temporary files have unq */\n private Random random = new Random();\n \n public void testAddLicenceToUnknownFile() throws IOException {\n String filename = \"tmp\" + random.nextLong() + \".unknownType\";\n File file = new File(System.getProperty(\"java.io.tmpdir\") + File.separator + filename);\n FileWriter writer = new FileWriter(file);\n writer.write(\"Unkown file type\\n\");\n writer.close();\n \n ApacheV2LicenceAppender appender = new ApacheV2LicenceAppender();\n appender.append(file);\n \n File newFile = new File(System.getProperty(\"java.io.tmpdir\") + File.separator + filename + \".new\");\n assertFalse(\"No new file should have been written\", newFile.exists());\n }\n \n public void testAddLicenceToJava() throws IOException {\n String filename = \"tmp.java\";\n String firstLine = \"package foo;\";\n String secondLine = \"/*\";\n \n File file = new File(System.getProperty(\"java.io.tmpdir\") + File.separator + filename);\n FileWriter writer = new FileWriter(file);\n writer.write(firstLine + \"\\n\");\n writer.write(\"\\n\");\n writer.write(\"public class test {\\n\");\n writer.write(\"}\\n\");\n writer.close();\n \n ApacheV2LicenceAppender appender = new ApacheV2LicenceAppender();\n appender.append(file);\n \n File newFile = new File(System.getProperty(\"java.io.tmpdir\") + File.separator + filename + \".new\");\n BufferedReader reader = new BufferedReader(new FileReader(newFile));\n String line = reader.readLine();\n assertEquals(\"First line is incorrect\", firstLine, line);\n line = reader.readLine();\n assertEquals(\"Second line is incorrect\", secondLine, line);\n \n file.delete();\n newFile.delete();\n }\n \n public void testAddLicenceToXML() throws IOException {\n String filename = \"tmp.xml\";\n String firstLine = \"\";\n String secondLine = \"