{ // 获取包含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 } else {\n _readTemplateFile_old.call(emailService, language, filename, cb);\n }\n };\n helpers.stubUtxos(server, wallet, [1, 1], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 0.8, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n setTimeout(function() {\n var calls = mailerStub.sendMail.getCalls();\n calls.length.should.equal(2);\n var emails = _.map(calls, function(c) {\n return c.args[0];\n });\n _.difference(['copayer2@domain.com', 'copayer3@domain.com'], _.pluck(emails, 'to')).should.be.empty;\n var one = emails[0];\n one.from.should.equal('bws@dummy.net');\n one.subject.should.contain('New payment proposal');\n one.text.should.contain(wallet.name);\n one.text.should.contain(wallet.copayers[0].name);\n should.exist(one.html);\n one.html.indexOf('').should.equal(0);\n one.html.should.contain(wallet.name);\n server.storage.fetchUnsentEmails(function(err, unsent) {\n should.not.exist(err);\n unsent.should.be.empty;\n emailService._readTemplateFile = _readTemplateFile_old;\n done();\n });\n }, 100);\n });\n });\n });\n\n it('should not send email if unable to apply template to notification', function(done) {\n var _applyTemplate_old = emailService._applyTemplate;\n emailService._applyTemplate = function(template, data, cb) {\n _applyTemplate_old.call(emailService, template, undefined, cb);\n };\n helpers.stubUtxos(server, wallet, [1, 1], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 0.8, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n setTimeout(function() {\n var calls = mailerStub.sendMail.getCalls();\n calls.length.should.equal(0);\n server.storage.fetchUnsentEmails(function(err, unsent) {\n should.not.exist(err);\n unsent.should.be.empty;\n emailService._applyTemplate = _applyTemplate_old;\n done();\n });\n }, 100);\n });\n });\n });\n\n it('should notify copayers a new outgoing tx has been created', function(done) {\n var _readTemplateFile_old = emailService._readTemplateFile;\n emailService._readTemplateFile = function(language, filename, cb) {\n if (_.endsWith(filename, '.html')) {\n return cb(null, '{{&urlForTx}}');\n } else {\n _readTemplateFile_old.call(emailService, language, filename, cb);\n }\n };\n helpers.stubUtxos(server, wallet, [1, 1], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 0.8, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n\n var txp;\n async.waterfall([\n\n function(next) {\n server.createTx(txOpts, next);\n },\n function(t, next) {\n txp = t;\n async.eachSeries(_.range(2), function(i, next) {\n var copayer = TestData.copayers[i];\n helpers.getAuthServer(copayer.id44, function(server) {\n var signatures = helpers.clientSign(txp, copayer.xPrivKey);\n server.signTx({\n txProposalId: txp.id,\n signatures: signatures,\n }, function(err, t) {\n txp = t;\n next();\n });\n });\n }, next);\n },\n function(next) {\n helpers.stubBroadcast();\n server.broadcastTx({\n txProposalId: txp.id,\n }, next);\n },\n ], function(err) {\n should.not.exist(err);\n\n setTimeout(function() {\n var calls = mailerStub.sendMail.getCalls();\n var emails = _.map(_.takeRight(calls, 3), function(c) {\n return c.args[0];\n });\n _.difference(['copayer1@domain.com', 'copayer2@domain.com', 'copayer3@domain.com'], _.pluck(emails, 'to')).should.be.empty;\n var one = emails[0];\n one.from.should.equal('bws@dummy.net');\n one.subject.should.contain('Payment sent');\n one.text.should.contain(wallet.name);\n one.text.should.contain('800,000');\n should.exist(one.html);\n one.html.should.contain('https://insight.bitpay.com/tx/' + txp.txid);\n server.storage.fetchUnsentEmails(function(err, unsent) {\n should.not.exist(err);\n unsent.should.be.empty;\n emailService._readTemplateFile = _readTemplateFile_old;\n done();\n });\n }, 100);\n });\n });\n });\n\n it('should notify copayers a tx has been finally rejected', function(done) {\n helpers.stubUtxos(server, wallet, 1, function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 0.8, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n\n var txpId;\n async.waterfall([\n\n function(next) {\n server.createTx(txOpts, next);\n },\n function(txp, next) {\n txpId = txp.id;\n async.eachSeries(_.range(1, 3), function(i, next) {\n var copayer = TestData.copayers[i];\n helpers.getAuthServer(copayer.id44, function(server) {\n server.rejectTx({\n txProposalId: txp.id,\n }, next);\n });\n }, next);\n },\n ], function(err) {\n should.not.exist(err);\n\n setTimeout(function() {\n var calls = mailerStub.sendMail.getCalls();\n var emails = _.map(_.takeRight(calls, 2), function(c) {\n return c.args[0];\n });\n _.difference(['copayer1@domain.com', 'copayer2@domain.com'], _.pluck(emails, 'to')).should.be.empty;\n var one = emails[0];\n one.from.should.equal('bws@dummy.net');\n one.subject.should.contain('Payment proposal rejected');\n one.text.should.contain(wallet.name);\n one.text.should.contain('copayer 2, copayer 3');\n one.text.should.not.contain('copayer 1');\n server.storage.fetchUnsentEmails(function(err, unsent) {\n should.not.exist(err);\n unsent.should.be.empty;\n done();\n });\n }, 100);\n });\n });\n });\n\n it('should notify copayers of incoming txs', function(done) {\n server.createAddress({}, function(err, address) {\n should.not.exist(err);\n\n // Simulate incoming tx notification\n server._notify('NewIncomingTx', {\n txid: '999',\n address: address,\n amount: 12300000,\n }, function(err) {\n setTimeout(function() {\n var calls = mailerStub.sendMail.getCalls();\n calls.length.should.equal(3);\n var emails = _.map(calls, function(c) {\n return c.args[0];\n });\n _.difference(['copayer1@domain.com', 'copayer2@domain.com', 'copayer3@domain.com'], _.pluck(emails, 'to')).should.be.empty;\n var one = emails[0];\n one.from.should.equal('bws@dummy.net');\n one.subject.should.contain('New payment received');\n one.text.should.contain(wallet.name);\n one.text.should.contain('123,000');\n server.storage.fetchUnsentEmails(function(err, unsent) {\n should.not.exist(err);\n unsent.should.be.empty;\n done();\n });\n }, 100);\n });\n });\n });\n\n it('should notify each email address only once', function(done) {\n // Set same email address for copayer1 and copayer2\n server.savePreferences({\n email: 'copayer2@domain.com',\n }, function(err) {\n server.createAddress({}, function(err, address) {\n should.not.exist(err);\n\n // Simulate incoming tx notification\n server._notify('NewIncomingTx', {\n txid: '999',\n address: address,\n amount: 12300000,\n }, function(err) {\n setTimeout(function() {\n var calls = mailerStub.sendMail.getCalls();\n calls.length.should.equal(2);\n var emails = _.map(calls, function(c) {\n return c.args[0];\n });\n _.difference(['copayer2@domain.com', 'copayer3@domain.com'], _.pluck(emails, 'to')).should.be.empty;\n var one = emails[0];\n one.from.should.equal('bws@dummy.net');\n one.subject.should.contain('New payment received');\n one.text.should.contain(wallet.name);\n one.text.should.contain('123,000');\n server.storage.fetchUnsentEmails(function(err, unsent) {\n should.not.exist(err);\n unsent.should.be.empty;\n done();\n });\n }, 100);\n });\n });\n });\n });\n\n it('should build each email using preferences of the copayers', function(done) {\n // Set same email address for copayer1 and copayer2\n server.savePreferences({\n email: 'copayer1@domain.com',\n language: 'es',\n unit: 'btc',\n }, function(err) {\n server.createAddress({}, function(err, address) {\n should.not.exist(err);\n\n // Simulate incoming tx notification\n server._notify('NewIncomingTx', {\n txid: '999',\n address: address,\n amount: 12300000,\n }, function(err) {\n setTimeout(function() {\n var calls = mailerStub.sendMail.getCalls();\n calls.length.should.equal(3);\n var emails = _.map(calls, function(c) {\n return c.args[0];\n });\n var spanish = _.find(emails, {\n to: 'copayer1@domain.com'\n });\n spanish.from.should.equal('bws@dummy.net');\n spanish.subject.should.contain('Nuevo pago recibido');\n spanish.text.should.contain(wallet.name);\n spanish.text.should.contain('0.123 BTC');\n var english = _.find(emails, {\n to: 'copayer2@domain.com'\n });\n english.from.should.equal('bws@dummy.net');\n english.subject.should.contain('New payment received');\n english.text.should.contain(wallet.name);\n english.text.should.contain('123,000 bits');\n done();\n }, 100);\n });\n });\n });\n });\n\n it('should support multiple emailservice instances running concurrently', function(done) {\n var emailService2 = new EmailService();\n emailService2.start({\n lock: emailService.lock, // Use same locker service\n messageBroker: server.messageBroker,\n storage: storage,\n mailer: mailerStub,\n emailOpts: {\n from: 'bws2@dummy.net',\n subjectPrefix: '[test wallet 2]',\n },\n }, function(err) {\n helpers.stubUtxos(server, wallet, 1, function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 0.8, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n setTimeout(function() {\n var calls = mailerStub.sendMail.getCalls();\n calls.length.should.equal(2);\n server.storage.fetchUnsentEmails(function(err, unsent) {\n should.not.exist(err);\n unsent.should.be.empty;\n done();\n });\n }, 100);\n });\n });\n });\n });\n });\n\n describe('1-of-N wallet', function() {\n beforeEach(function(done) {\n helpers.createAndJoinWallet(1, 2, function(s, w) {\n server = s;\n wallet = w;\n\n var i = 0;\n async.eachSeries(w.copayers, function(copayer, next) {\n helpers.getAuthServer(copayer.id, function(server) {\n server.savePreferences({\n email: 'copayer' + (++i) + '@domain.com',\n unit: 'bit',\n }, next);\n });\n }, function(err) {\n should.not.exist(err);\n\n mailerStub = sinon.stub();\n mailerStub.sendMail = sinon.stub();\n mailerStub.sendMail.yields();\n\n emailService = new EmailService();\n emailService.start({\n lockOpts: {},\n messageBroker: server.messageBroker,\n storage: storage,\n mailer: mailerStub,\n emailOpts: {\n from: 'bws@dummy.net',\n subjectPrefix: '[test wallet]',\n publicTxUrlTemplate: {\n livenet: 'https://insight.bitpay.com/tx/{{txid}}',\n testnet: 'https://test-insight.bitpay.com/tx/{{txid}}',\n },\n },\n }, function(err) {\n should.not.exist(err);\n done();\n });\n });\n });\n });\n\n it('should NOT notify copayers a new tx proposal has been created', function(done) {\n helpers.stubUtxos(server, wallet, [1, 1], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 0.8, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n setTimeout(function() {\n var calls = mailerStub.sendMail.getCalls();\n calls.length.should.equal(0);\n done();\n }, 100);\n });\n });\n });\n });\n\n });\n\n describe('#getServiceVersion', function() {\n it('should get version from package', function() {\n WalletService.getServiceVersion().should.equal('bws-' + require('../../package').version);\n });\n });\n\n describe('#getInstance', function() {\n it('should get server instance', function() {\n var server = WalletService.getInstance({\n clientVersion: 'bwc-0.0.1',\n });\n server.clientVersion.should.equal('bwc-0.0.1');\n });\n });\n\n describe('#getInstanceWithAuth', function() {\n it('should get server instance for existing copayer', function(done) {\n helpers.createAndJoinWallet(1, 2, function(s, wallet) {\n var xpriv = TestData.copayers[0].xPrivKey;\n var priv = TestData.copayers[0].privKey_1H_0;\n\n var sig = WalletUtils.signMessage('hello world', priv);\n\n WalletService.getInstanceWithAuth({\n copayerId: wallet.copayers[0].id,\n message: 'hello world',\n signature: sig,\n clientVersion: 'bwc-0.0.1',\n }, function(err, server) {\n should.not.exist(err);\n server.walletId.should.equal(wallet.id);\n server.copayerId.should.equal(wallet.copayers[0].id);\n server.clientVersion.should.equal('bwc-0.0.1');\n done();\n });\n });\n });\n\n it('should fail when requesting for non-existent copayer', function(done) {\n var message = 'hello world';\n var opts = {\n copayerId: 'dummy',\n message: message,\n signature: WalletUtils.signMessage(message, TestData.copayers[0].privKey_1H_0),\n };\n WalletService.getInstanceWithAuth(opts, function(err, server) {\n err.code.should.equal('NOT_AUTHORIZED');\n err.message.should.contain('Copayer not found');\n done();\n });\n });\n\n it('should fail when message signature cannot be verified', function(done) {\n helpers.createAndJoinWallet(1, 2, function(s, wallet) {\n WalletService.getInstanceWithAuth({\n copayerId: wallet.copayers[0].id,\n message: 'dummy',\n signature: 'dummy',\n }, function(err, server) {\n err.code.should.equal('NOT_AUTHORIZED');\n err.message.should.contain('Invalid signature');\n done();\n });\n });\n });\n });\n\n describe('#createWallet', function() {\n var server;\n beforeEach(function() {\n server = new WalletService();\n });\n\n it('should create and store wallet', function(done) {\n var opts = {\n name: 'my wallet',\n m: 2,\n n: 3,\n pubKey: TestData.keyPair.pub,\n };\n server.createWallet(opts, function(err, walletId) {\n should.not.exist(err);\n server.storage.fetchWallet(walletId, function(err, wallet) {\n should.not.exist(err);\n wallet.id.should.equal(walletId);\n wallet.name.should.equal('my wallet');\n done();\n });\n });\n });\n\n it('should create wallet with given id', function(done) {\n var opts = {\n name: 'my wallet',\n m: 2,\n n: 3,\n pubKey: TestData.keyPair.pub,\n id: '1234',\n };\n server.createWallet(opts, function(err, walletId) {\n should.not.exist(err);\n server.storage.fetchWallet('1234', function(err, wallet) {\n should.not.exist(err);\n wallet.id.should.equal(walletId);\n wallet.name.should.equal('my wallet');\n done();\n });\n });\n });\n\n it('should fail to create wallets with same id', function(done) {\n var opts = {\n name: 'my wallet',\n m: 2,\n n: 3,\n pubKey: TestData.keyPair.pub,\n id: '1234',\n };\n server.createWallet(opts, function(err, walletId) {\n server.createWallet(opts, function(err, walletId) {\n err.message.should.contain('Wallet already exists');\n done();\n });\n });\n });\n\n\n it('should fail to create wallet with no name', function(done) {\n var opts = {\n name: '',\n m: 2,\n n: 3,\n pubKey: TestData.keyPair.pub,\n };\n server.createWallet(opts, function(err, walletId) {\n should.not.exist(walletId);\n should.exist(err);\n err.message.should.contain('name');\n done();\n });\n });\n\n it('should fail to create wallet with invalid copayer pairs', function(done) {\n var invalidPairs = [{\n m: 0,\n n: 0\n }, {\n m: 0,\n n: 2\n }, {\n m: 2,\n n: 1\n }, {\n m: 0,\n n: 10\n }, {\n m: 1,\n n: 20\n }, {\n m: 10,\n n: 10\n }, ];\n var opts = {\n id: '123',\n name: 'my wallet',\n pubKey: TestData.keyPair.pub,\n };\n async.each(invalidPairs, function(pair, cb) {\n opts.m = pair.m;\n opts.n = pair.n;\n server.createWallet(opts, function(err) {\n should.exist(err);\n err.message.should.equal('Invalid combination of required copayers / total copayers');\n return cb();\n });\n }, function(err) {\n done();\n });\n });\n\n it('should fail to create wallet with invalid pubKey argument', function(done) {\n var opts = {\n name: 'my wallet',\n m: 2,\n n: 3,\n pubKey: 'dummy',\n };\n server.createWallet(opts, function(err, walletId) {\n should.not.exist(walletId);\n should.exist(err);\n err.message.should.contain('Invalid public key');\n done();\n });\n });\n });\n\n describe('#joinWallet', function() {\n var server, walletId;\n beforeEach(function(done) {\n server = new WalletService();\n var walletOpts = {\n name: 'my wallet',\n m: 1,\n n: 2,\n pubKey: TestData.keyPair.pub,\n };\n server.createWallet(walletOpts, function(err, wId) {\n should.not.exist(err);\n walletId = wId;\n should.exist(walletId);\n done();\n });\n });\n\n it('should join existing wallet', function(done) {\n var copayerOpts = helpers.getSignedCopayerOpts({\n walletId: walletId,\n name: 'me',\n xPubKey: TestData.copayers[0].xPubKey_44H_0H_0H,\n requestPubKey: TestData.copayers[0].pubKey_1H_0,\n customData: 'dummy custom data',\n });\n server.joinWallet(copayerOpts, function(err, result) {\n should.not.exist(err);\n var copayerId = result.copayerId;\n helpers.getAuthServer(copayerId, function(server) {\n server.getWallet({}, function(err, wallet) {\n wallet.id.should.equal(walletId);\n wallet.copayers.length.should.equal(1);\n var copayer = wallet.copayers[0];\n copayer.name.should.equal('me');\n copayer.id.should.equal(copayerId);\n copayer.customData.should.equal('dummy custom data');\n server.getNotifications({}, function(err, notifications) {\n should.not.exist(err);\n var notif = _.find(notifications, {\n type: 'NewCopayer'\n });\n should.exist(notif);\n notif.data.walletId.should.equal(walletId);\n notif.data.copayerId.should.equal(copayerId);\n notif.data.copayerName.should.equal('me');\n\n notif = _.find(notifications, {\n type: 'WalletComplete'\n });\n should.not.exist(notif);\n done();\n });\n });\n });\n });\n });\n\n it('should fail to join with no name', function(done) {\n var copayerOpts = helpers.getSignedCopayerOpts({\n walletId: walletId,\n name: '',\n xPubKey: TestData.copayers[0].xPubKey_44H_0H_0H,\n requestPubKey: TestData.copayers[0].pubKey_1H_0,\n });\n server.joinWallet(copayerOpts, function(err, result) {\n should.not.exist(result);\n should.exist(err);\n err.message.should.contain('name');\n done();\n });\n });\n\n it('should fail to join non-existent wallet', function(done) {\n var copayerOpts = {\n walletId: '123',\n name: 'me',\n xPubKey: 'dummy',\n requestPubKey: 'dummy',\n copayerSignature: 'dummy',\n };\n server.joinWallet(copayerOpts, function(err) {\n should.exist(err);\n done();\n });\n });\n\n it('should fail to join full wallet', function(done) {\n helpers.createAndJoinWallet(1, 1, function(s, wallet) {\n var copayerOpts = helpers.getSignedCopayerOpts({\n walletId: wallet.id,\n name: 'me',\n xPubKey: TestData.copayers[1].xPubKey_44H_0H_0H,\n requestPubKey: TestData.copayers[1].pubKey_1H_0,\n });\n server.joinWallet(copayerOpts, function(err) {\n should.exist(err);\n err.code.should.equal('WALLET_FULL');\n err.message.should.equal('Wallet full');\n done();\n });\n });\n });\n\n it('should return copayer in wallet error before full wallet', function(done) {\n helpers.createAndJoinWallet(1, 1, function(s, wallet) {\n var copayerOpts = helpers.getSignedCopayerOpts({\n walletId: wallet.id,\n name: 'me',\n xPubKey: TestData.copayers[0].xPubKey_44H_0H_0H,\n requestPubKey: TestData.copayers[0].pubKey_1H_0,\n });\n server.joinWallet(copayerOpts, function(err) {\n should.exist(err);\n err.code.should.equal('COPAYER_IN_WALLET');\n done();\n });\n });\n });\n\n it('should fail to re-join wallet', function(done) {\n var copayerOpts = helpers.getSignedCopayerOpts({\n walletId: walletId,\n name: 'me',\n xPubKey: TestData.copayers[0].xPubKey_44H_0H_0H,\n requestPubKey: TestData.copayers[0].pubKey_1H_0,\n });\n server.joinWallet(copayerOpts, function(err) {\n should.not.exist(err);\n server.joinWallet(copayerOpts, function(err) {\n should.exist(err);\n err.code.should.equal('COPAYER_IN_WALLET');\n err.message.should.equal('Copayer already in wallet');\n done();\n });\n });\n });\n\n it('should be able to get wallet info without actually joining', function(done) {\n var copayerOpts = helpers.getSignedCopayerOpts({\n walletId: walletId,\n name: 'me',\n xPubKey: TestData.copayers[0].xPubKey_44H_0H_0H,\n requestPubKey: TestData.copayers[0].pubKey_1H_0,\n customData: 'dummy custom data',\n dryRun: true,\n });\n server.joinWallet(copayerOpts, function(err, result) {\n should.not.exist(err);\n should.exist(result);\n should.not.exist(result.copayerId);\n result.wallet.id.should.equal(walletId);\n result.wallet.m.should.equal(1);\n result.wallet.n.should.equal(2);\n result.wallet.copayers.should.be.empty;\n server.storage.fetchWallet(walletId, function(err, wallet) {\n should.not.exist(err);\n wallet.id.should.equal(walletId);\n wallet.copayers.should.be.empty;\n done();\n });\n });\n });\n\n it('should fail to join two wallets with same xPubKey', function(done) {\n var copayerOpts = helpers.getSignedCopayerOpts({\n walletId: walletId,\n name: 'me',\n xPubKey: TestData.copayers[0].xPubKey_44H_0H_0H,\n requestPubKey: TestData.copayers[0].pubKey_1H_0,\n });\n server.joinWallet(copayerOpts, function(err) {\n should.not.exist(err);\n\n var walletOpts = {\n name: 'my other wallet',\n m: 1,\n n: 1,\n pubKey: TestData.keyPair.pub,\n };\n server.createWallet(walletOpts, function(err, walletId) {\n should.not.exist(err);\n copayerOpts = helpers.getSignedCopayerOpts({\n walletId: walletId,\n name: 'me',\n xPubKey: TestData.copayers[0].xPubKey_44H_0H_0H,\n requestPubKey: TestData.copayers[0].pubKey_1H_0,\n });\n server.joinWallet(copayerOpts, function(err) {\n should.exist(err);\n err.code.should.equal('COPAYER_REGISTERED');\n err.message.should.equal('Copayer ID already registered on server');\n done();\n });\n });\n });\n });\n\n it('should fail to join with bad formated signature', function(done) {\n var copayerOpts = {\n walletId: walletId,\n name: 'me',\n xPubKey: TestData.copayers[0].xPubKey_44H_0H_0H,\n requestPubKey: TestData.copayers[0].pubKey_1H_0,\n copayerSignature: 'bad sign',\n };\n server.joinWallet(copayerOpts, function(err) {\n err.message.should.equal('Bad request');\n done();\n });\n });\n\n it('should fail to join with null signature', function(done) {\n var copayerOpts = {\n walletId: walletId,\n name: 'me',\n xPubKey: TestData.copayers[0].xPubKey_44H_0H_0H,\n requestPubKey: TestData.copayers[0].pubKey_1H_0,\n };\n server.joinWallet(copayerOpts, function(err) {\n should.exist(err);\n err.message.should.contain('argument missing');\n done();\n });\n });\n\n it('should fail to join with wrong signature', function(done) {\n var copayerOpts = helpers.getSignedCopayerOpts({\n walletId: walletId,\n name: 'me',\n xPubKey: TestData.copayers[0].xPubKey_44H_0H_0H,\n requestPubKey: TestData.copayers[0].pubKey_1H_0,\n });\n copayerOpts.name = 'me2';\n server.joinWallet(copayerOpts, function(err) {\n err.message.should.equal('Bad request');\n done();\n });\n });\n\n it('should set pkr and status = complete on last copayer joining (2-3)', function(done) {\n helpers.createAndJoinWallet(2, 3, function(server) {\n server.getWallet({}, function(err, wallet) {\n should.not.exist(err);\n wallet.status.should.equal('complete');\n wallet.publicKeyRing.length.should.equal(3);\n server.getNotifications({}, function(err, notifications) {\n should.not.exist(err);\n var notif = _.find(notifications, {\n type: 'WalletComplete'\n });\n should.exist(notif);\n notif.data.walletId.should.equal(wallet.id);\n done();\n });\n });\n });\n });\n\n it('should not notify WalletComplete if 1-of-1', function(done) {\n helpers.createAndJoinWallet(1, 1, function(server) {\n server.getNotifications({}, function(err, notifications) {\n should.not.exist(err);\n var notif = _.find(notifications, {\n type: 'WalletComplete'\n });\n should.not.exist(notif);\n done();\n });\n });\n });\n });\n\n describe('#joinWallet new/legacy clients', function() {\n var server;\n beforeEach(function() {\n server = new WalletService();\n });\n\n it('should fail to join legacy wallet from new client', function(done) {\n var walletOpts = {\n name: 'my wallet',\n m: 1,\n n: 2,\n pubKey: TestData.keyPair.pub,\n supportBIP44AndP2PKH: false,\n };\n server.createWallet(walletOpts, function(err, walletId) {\n should.not.exist(err);\n should.exist(walletId);\n var copayerOpts = helpers.getSignedCopayerOpts({\n walletId: walletId,\n name: 'me',\n xPubKey: TestData.copayers[0].xPubKey_44H_0H_0H,\n requestPubKey: TestData.copayers[0].pubKey_1H_0,\n });\n server.joinWallet(copayerOpts, function(err, result) {\n should.exist(err);\n err.message.should.contain('The wallet you are trying to join was created with an older version of the client app');\n done();\n });\n });\n });\n it('should fail to join new wallet from legacy client', function(done) {\n var walletOpts = {\n name: 'my wallet',\n m: 1,\n n: 2,\n pubKey: TestData.keyPair.pub,\n };\n server.createWallet(walletOpts, function(err, walletId) {\n should.not.exist(err);\n should.exist(walletId);\n var copayerOpts = helpers.getSignedCopayerOpts({\n walletId: walletId,\n name: 'me',\n xPubKey: TestData.copayers[0].xPubKey_45H,\n requestPubKey: TestData.copayers[0].pubKey_1H_0,\n supportBIP44AndP2PKH: false,\n });\n server.joinWallet(copayerOpts, function(err, result) {\n should.exist(err);\n err.code.should.equal('UPGRADE_NEEDED');\n done();\n });\n });\n });\n });\n\n describe('Address derivation strategy', function() {\n var server;\n beforeEach(function() {\n server = WalletService.getInstance();\n });\n it('should use BIP44 & P2PKH for 1-of-1 wallet if supported', function(done) {\n var walletOpts = {\n name: 'my wallet',\n m: 1,\n n: 1,\n pubKey: TestData.keyPair.pub,\n };\n server.createWallet(walletOpts, function(err, wid) {\n should.not.exist(err);\n server.storage.fetchWallet(wid, function(err, wallet) {\n should.not.exist(err);\n wallet.derivationStrategy.should.equal('BIP44');\n wallet.addressType.should.equal('P2PKH');\n done();\n });\n });\n });\n it('should use BIP45 & P2SH for 1-of-1 wallet if not supported', function(done) {\n var walletOpts = {\n name: 'my wallet',\n m: 1,\n n: 1,\n pubKey: TestData.keyPair.pub,\n supportBIP44AndP2PKH: false,\n };\n server.createWallet(walletOpts, function(err, wid) {\n should.not.exist(err);\n server.storage.fetchWallet(wid, function(err, wallet) {\n should.not.exist(err);\n wallet.derivationStrategy.should.equal('BIP45');\n wallet.addressType.should.equal('P2SH');\n done();\n });\n });\n });\n it('should use BIP44 & P2SH for shared wallet if supported', function(done) {\n var walletOpts = {\n name: 'my wallet',\n m: 2,\n n: 3,\n pubKey: TestData.keyPair.pub,\n };\n server.createWallet(walletOpts, function(err, wid) {\n should.not.exist(err);\n server.storage.fetchWallet(wid, function(err, wallet) {\n should.not.exist(err);\n wallet.derivationStrategy.should.equal('BIP44');\n wallet.addressType.should.equal('P2SH');\n done();\n });\n });\n });\n it('should use BIP45 & P2SH for shared wallet if supported', function(done) {\n var walletOpts = {\n name: 'my wallet',\n m: 2,\n n: 3,\n pubKey: TestData.keyPair.pub,\n supportBIP44AndP2PKH: false,\n };\n server.createWallet(walletOpts, function(err, wid) {\n should.not.exist(err);\n server.storage.fetchWallet(wid, function(err, wallet) {\n should.not.exist(err);\n wallet.derivationStrategy.should.equal('BIP45');\n wallet.addressType.should.equal('P2SH');\n done();\n });\n });\n });\n });\n\n describe('#getStatus', function() {\n var server, wallet;\n beforeEach(function(done) {\n helpers.createAndJoinWallet(1, 2, function(s, w) {\n server = s;\n wallet = w;\n done();\n });\n });\n\n it('should get status', function(done) {\n server.getStatus({}, function(err, status) {\n should.not.exist(err);\n should.exist(status);\n should.exist(status.wallet);\n status.wallet.name.should.equal(wallet.name);\n should.exist(status.wallet.copayers);\n status.wallet.copayers.length.should.equal(2);\n should.exist(status.balance);\n status.balance.totalAmount.should.equal(0);\n should.exist(status.preferences);\n should.exist(status.pendingTxps);\n status.pendingTxps.should.be.empty;\n\n should.not.exist(status.wallet.publicKeyRing);\n should.not.exist(status.wallet.pubKey);\n should.not.exist(status.wallet.addressManager);\n _.each(status.wallet.copayers, function(copayer) {\n should.not.exist(copayer.xPubKey);\n should.not.exist(copayer.requestPubKey);\n should.not.exist(copayer.signature);\n should.not.exist(copayer.requestPubKey);\n should.not.exist(copayer.addressManager);\n should.not.exist(copayer.customData);\n });\n done();\n });\n });\n it('should get status including extended info', function(done) {\n server.getStatus({\n includeExtendedInfo: true\n }, function(err, status) {\n should.not.exist(err);\n should.exist(status);\n should.exist(status.wallet.publicKeyRing);\n should.exist(status.wallet.pubKey);\n should.exist(status.wallet.addressManager);\n should.exist(status.wallet.copayers[0].xPubKey);\n should.exist(status.wallet.copayers[0].requestPubKey);\n should.exist(status.wallet.copayers[0].signature);\n should.exist(status.wallet.copayers[0].requestPubKey);\n should.exist(status.wallet.copayers[0].customData);\n // Do not return other copayer's custom data\n _.each(_.rest(status.wallet.copayers), function(copayer) {\n should.not.exist(copayer.customData);\n });\n done();\n });\n });\n it('should get status after tx creation', function(done) {\n helpers.stubUtxos(server, wallet, [100, 200], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 80, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n should.exist(tx);\n server.getStatus({}, function(err, status) {\n should.not.exist(err);\n status.pendingTxps.length.should.equal(1);\n var balance = status.balance;\n balance.totalAmount.should.equal(helpers.toSatoshi(300));\n balance.lockedAmount.should.equal(tx.inputs[0].satoshis);\n balance.availableAmount.should.equal(balance.totalAmount - balance.lockedAmount);\n done();\n });\n });\n });\n });\n });\n\n describe('#verifyMessageSignature', function() {\n var server, wallet;\n beforeEach(function(done) {\n helpers.createAndJoinWallet(2, 3, function(s, w) {\n server = s;\n wallet = w;\n done();\n });\n });\n\n it('should successfully verify message signature', function(done) {\n var message = 'hello world';\n var opts = {\n message: message,\n signature: WalletUtils.signMessage(message, TestData.copayers[0].privKey_1H_0),\n };\n server.verifyMessageSignature(opts, function(err, isValid) {\n should.not.exist(err);\n isValid.should.be.true;\n done();\n });\n });\n\n it('should fail to verify message signature for different copayer', function(done) {\n var message = 'hello world';\n var opts = {\n message: message,\n signature: WalletUtils.signMessage(message, TestData.copayers[0].privKey_1H_0),\n };\n helpers.getAuthServer(wallet.copayers[1].id, function(server) {\n server.verifyMessageSignature(opts, function(err, isValid) {\n should.not.exist(err);\n isValid.should.be.false;\n done();\n });\n });\n });\n });\n\n describe('#createAddress', function() {\n var server, wallet;\n\n describe('shared wallets (BIP45)', function() {\n beforeEach(function(done) {\n helpers.createAndJoinWallet(2, 2, {\n supportBIP44AndP2PKH: false\n }, function(s, w) {\n server = s;\n wallet = w;\n done();\n });\n });\n\n it('should create address', function(done) {\n server.createAddress({}, function(err, address) {\n should.not.exist(err);\n should.exist(address);\n address.walletId.should.equal(wallet.id);\n address.network.should.equal('livenet');\n address.address.should.equal('3BVJZ4CYzeTtawDtgwHvWV5jbvnXtYe97i');\n address.isChange.should.be.false;\n address.path.should.equal('m/2147483647/0/0');\n address.type.should.equal('P2SH');\n server.getNotifications({}, function(err, notifications) {\n should.not.exist(err);\n var notif = _.find(notifications, {\n type: 'NewAddress'\n });\n should.exist(notif);\n notif.data.address.should.equal(address.address);\n done();\n });\n });\n });\n\n it('should protect against storing same address multiple times', function(done) {\n server.createAddress({}, function(err, address) {\n should.not.exist(err);\n should.exist(address);\n delete address._id;\n server.storage.storeAddressAndWallet(wallet, address, function(err) {\n should.not.exist(err);\n server.getMainAddresses({}, function(err, addresses) {\n should.not.exist(err);\n addresses.length.should.equal(1);\n done();\n });\n });\n });\n });\n\n it('should create many addresses on simultaneous requests', function(done) {\n var N = 5;\n async.map(_.range(N), function(i, cb) {\n server.createAddress({}, cb);\n }, function(err, addresses) {\n addresses.length.should.equal(N);\n _.each(_.range(N), function(i) {\n addresses[i].path.should.equal('m/2147483647/0/' + i);\n });\n // No two identical addresses\n _.uniq(_.pluck(addresses, 'address')).length.should.equal(N);\n done();\n });\n });\n });\n\n describe('shared wallets (BIP44)', function() {\n beforeEach(function(done) {\n helpers.createAndJoinWallet(2, 2, function(s, w) {\n server = s;\n wallet = w;\n done();\n });\n });\n\n it('should create address', function(done) {\n server.createAddress({}, function(err, address) {\n should.not.exist(err);\n should.exist(address);\n address.walletId.should.equal(wallet.id);\n address.network.should.equal('livenet');\n address.address.should.equal('36q2G5FMGvJbPgAVEaiyAsFGmpkhPKwk2r');\n address.isChange.should.be.false;\n address.path.should.equal('m/0/0');\n address.type.should.equal('P2SH');\n server.getNotifications({}, function(err, notifications) {\n should.not.exist(err);\n var notif = _.find(notifications, {\n type: 'NewAddress'\n });\n should.exist(notif);\n notif.data.address.should.equal(address.address);\n done();\n });\n });\n });\n\n it('should create many addresses on simultaneous requests', function(done) {\n var N = 5;\n async.map(_.range(N), function(i, cb) {\n server.createAddress({}, cb);\n }, function(err, addresses) {\n addresses.length.should.equal(N);\n _.each(_.range(N), function(i) {\n addresses[i].path.should.equal('m/0/' + i);\n });\n // No two identical addresses\n _.uniq(_.pluck(addresses, 'address')).length.should.equal(N);\n done();\n });\n });\n\n it('should not create address if unable to store it', function(done) {\n sinon.stub(server.storage, 'storeAddressAndWallet').yields('dummy error');\n server.createAddress({}, function(err, address) {\n should.exist(err);\n should.not.exist(address);\n\n server.getMainAddresses({}, function(err, addresses) {\n addresses.length.should.equal(0);\n\n server.storage.storeAddressAndWallet.restore();\n server.createAddress({}, function(err, address) {\n should.not.exist(err);\n should.exist(address);\n done();\n });\n });\n });\n });\n });\n\n describe('1-of-1 (BIP44 & P2PKH)', function() {\n beforeEach(function(done) {\n helpers.createAndJoinWallet(1, 1, function(s, w) {\n server = s;\n wallet = w;\n w.copayers[0].id.should.equal(TestData.copayers[0].id44);\n done();\n });\n });\n\n it('should create address', function(done) {\n server.createAddress({}, function(err, address) {\n should.not.exist(err);\n should.exist(address);\n address.walletId.should.equal(wallet.id);\n address.network.should.equal('livenet');\n address.address.should.equal('1L3z9LPd861FWQhf3vDn89Fnc9dkdBo2CG');\n address.isChange.should.be.false;\n address.path.should.equal('m/0/0');\n address.type.should.equal('P2PKH');\n server.getNotifications({}, function(err, notifications) {\n should.not.exist(err);\n var notif = _.find(notifications, {\n type: 'NewAddress'\n });\n should.exist(notif);\n notif.data.address.should.equal(address.address);\n done();\n });\n });\n });\n\n it('should create many addresses on simultaneous requests', function(done) {\n var N = 5;\n async.map(_.range(N), function(i, cb) {\n server.createAddress({}, cb);\n }, function(err, addresses) {\n addresses.length.should.equal(N);\n _.each(_.range(N), function(i) {\n addresses[i].path.should.equal('m/0/' + i);\n });\n // No two identical addresses\n _.uniq(_.pluck(addresses, 'address')).length.should.equal(N);\n done();\n });\n });\n });\n });\n\n describe('Preferences', function() {\n var server, wallet;\n beforeEach(function(done) {\n helpers.createAndJoinWallet(2, 2, function(s, w) {\n server = s;\n wallet = w;\n done();\n });\n });\n\n it('should save & retrieve preferences', function(done) {\n server.savePreferences({\n email: 'dummy@dummy.com',\n language: 'es',\n unit: 'bit',\n dummy: 'ignored',\n }, function(err) {\n should.not.exist(err);\n server.getPreferences({}, function(err, preferences) {\n should.not.exist(err);\n should.exist(preferences);\n preferences.email.should.equal('dummy@dummy.com');\n preferences.language.should.equal('es');\n preferences.unit.should.equal('bit');\n should.not.exist(preferences.dummy);\n done();\n });\n });\n });\n it('should save preferences only for requesting copayer', function(done) {\n server.savePreferences({\n email: 'dummy@dummy.com'\n }, function(err) {\n should.not.exist(err);\n helpers.getAuthServer(wallet.copayers[1].id, function(server2) {\n server2.getPreferences({}, function(err, preferences) {\n should.not.exist(err);\n should.not.exist(preferences.email);\n done();\n });\n });\n });\n });\n it('should save preferences incrementally', function(done) {\n async.series([\n\n function(next) {\n server.savePreferences({\n email: 'dummy@dummy.com',\n }, next);\n },\n function(next) {\n server.getPreferences({}, function(err, preferences) {\n should.not.exist(err);\n should.exist(preferences);\n preferences.email.should.equal('dummy@dummy.com');\n should.not.exist(preferences.language);\n next();\n });\n },\n function(next) {\n server.savePreferences({\n language: 'es',\n }, next);\n },\n function(next) {\n server.getPreferences({}, function(err, preferences) {\n should.not.exist(err);\n should.exist(preferences);\n preferences.language.should.equal('es');\n preferences.email.should.equal('dummy@dummy.com');\n next();\n });\n },\n function(next) {\n server.savePreferences({\n language: null,\n unit: 'bit',\n }, next);\n },\n function(next) {\n server.getPreferences({}, function(err, preferences) {\n should.not.exist(err);\n should.exist(preferences);\n preferences.unit.should.equal('bit');\n should.not.exist(preferences.language);\n preferences.email.should.equal('dummy@dummy.com');\n next();\n });\n },\n ], function(err) {\n should.not.exist(err);\n done();\n });\n });\n it.skip('should save preferences only for requesting wallet', function(done) {});\n it('should validate entries', function(done) {\n var invalid = [{\n preferences: {\n email: ' ',\n },\n expected: 'email'\n }, {\n preferences: {\n email: 'dummy@' + _.repeat('domain', 50),\n },\n expected: 'email'\n }, {\n preferences: {\n language: 'xxxxx',\n },\n expected: 'language'\n }, {\n preferences: {\n language: 123,\n },\n expected: 'language'\n }, {\n preferences: {\n unit: 'xxxxx',\n },\n expected: 'unit'\n }, ];\n async.each(invalid, function(item, next) {\n server.savePreferences(item.preferences, function(err) {\n should.exist(err);\n err.message.should.contain(item.expected);\n next();\n });\n }, done);\n });\n });\n\n describe('#getUtxos', function() {\n var server, wallet;\n beforeEach(function(done) {\n helpers.createAndJoinWallet(1, 1, function(s, w) {\n server = s;\n wallet = w;\n done();\n });\n });\n\n it('should get UTXOs for wallet addresses', function(done) {\n helpers.stubUtxos(server, wallet, [1, 2], function() {\n server.getUtxos({}, function(err, utxos) {\n should.not.exist(err);\n should.exist(utxos);\n utxos.length.should.equal(2);\n _.sum(utxos, 'satoshis').should.equal(3 * 1e8);\n server.getMainAddresses({}, function(err, addresses) {\n var utxo = utxos[0];\n var address = _.find(addresses, {\n address: utxo.address\n });\n should.exist(address);\n utxo.path.should.equal(address.path);\n utxo.publicKeys.should.deep.equal(address.publicKeys);\n done();\n });\n });\n });\n });\n it('should get UTXOs for specific addresses', function(done) {\n helpers.stubUtxos(server, wallet, [1, 2, 3], function(utxos) {\n _.uniq(utxos, 'address').length.should.be.above(1);\n var address = utxos[0].address;\n var amount = _.sum(_.filter(utxos, {\n address: address\n }), 'satoshis');\n server.getUtxos({\n addresses: [address]\n }, function(err, utxos) {\n should.not.exist(err);\n should.exist(utxos);\n _.sum(utxos, 'satoshis').should.equal(amount);\n done();\n });\n });\n });\n });\n\n\n describe('Multiple request Pub Keys', function() {\n var server, wallet;\n var opts, reqPrivKey, ws;\n var getAuthServer = function(copayerId, privKey, cb) {\n var msg = 'dummy';\n var sig = WalletUtils.signMessage(msg, privKey);\n WalletService.getInstanceWithAuth({\n copayerId: copayerId,\n message: msg,\n signature: sig,\n clientVersion: CLIENT_VERSION,\n }, function(err, server) {\n return cb(err, server);\n });\n };\n\n beforeEach(function() {\n reqPrivKey = new Bitcore.PrivateKey();\n var requestPubKey = reqPrivKey.toPublicKey();\n\n var xPrivKey = TestData.copayers[0].xPrivKey_44H_0H_0H;\n var sig = WalletUtils.signRequestPubKey(requestPubKey, xPrivKey);\n\n var copayerId = WalletUtils.xPubToCopayerId(TestData.copayers[0].xPubKey_44H_0H_0H);\n opts = {\n copayerId: copayerId,\n requestPubKey: requestPubKey,\n signature: sig,\n };\n ws = new WalletService();\n });\n\n describe('#addAccess 1-1', function() {\n beforeEach(function(done) {\n helpers.createAndJoinWallet(1, 1, function(s, w) {\n server = s;\n wallet = w;\n\n helpers.stubUtxos(server, wallet, 1, function() {\n done();\n });\n });\n });\n\n it('should be able to re-gain access from xPrivKey', function(done) {\n ws.addAccess(opts, function(err, res) {\n should.not.exist(err);\n res.wallet.copayers[0].requestPubKeys.length.should.equal(2);\n res.wallet.copayers[0].requestPubKeys[0].selfSigned.should.equal(true);\n\n server.getBalance(res.wallet.walletId, function(err, bal) {\n should.not.exist(err);\n bal.totalAmount.should.equal(1e8);\n getAuthServer(opts.copayerId, reqPrivKey, function(err, server2) {\n server2.getBalance(res.wallet.walletId, function(err, bal2) {\n should.not.exist(err);\n bal2.totalAmount.should.equal(1e8);\n done();\n });\n });\n });\n });\n });\n\n it('should fail to gain access with wrong xPrivKey', function(done) {\n opts.signature = 'xx';\n ws.addAccess(opts, function(err, res) {\n err.code.should.equal('NOT_AUTHORIZED');\n done();\n });\n });\n\n it('should fail to access with wrong privkey after gaining access', function(done) {\n ws.addAccess(opts, function(err, res) {\n should.not.exist(err);\n server.getBalance(res.wallet.walletId, function(err, bal) {\n should.not.exist(err);\n var privKey = new Bitcore.PrivateKey();\n (getAuthServer(opts.copayerId, privKey, function(err, server2) {\n err.code.should.equal('NOT_AUTHORIZED');\n done();\n }));\n });\n });\n });\n\n it('should be able to create TXs after regaining access', function(done) {\n ws.addAccess(opts, function(err, res) {\n should.not.exist(err);\n getAuthServer(opts.copayerId, reqPrivKey, function(err, server2) {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 0.8, reqPrivKey);\n server2.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n done();\n });\n });\n });\n });\n });\n\n describe('#addAccess 2-2', function() {\n beforeEach(function(done) {\n helpers.createAndJoinWallet(2, 2, function(s, w) {\n server = s;\n wallet = w;\n helpers.stubUtxos(server, wallet, 1, function() {\n done();\n });\n });\n });\n\n it('should be able to re-gain access from xPrivKey', function(done) {\n ws.addAccess(opts, function(err, res) {\n should.not.exist(err);\n server.getBalance(res.wallet.walletId, function(err, bal) {\n should.not.exist(err);\n bal.totalAmount.should.equal(1e8);\n getAuthServer(opts.copayerId, reqPrivKey, function(err, server2) {\n server2.getBalance(res.wallet.walletId, function(err, bal2) {\n should.not.exist(err);\n bal2.totalAmount.should.equal(1e8);\n done();\n });\n });\n });\n });\n });\n\n it('TX proposals should include info to be verified', function(done) {\n ws.addAccess(opts, function(err, res) {\n should.not.exist(err);\n getAuthServer(opts.copayerId, reqPrivKey, function(err, server2) {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 0.8, reqPrivKey);\n server2.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n server2.getPendingTxs({}, function(err, txs) {\n should.not.exist(err);\n should.exist(txs[0].proposalSignaturePubKey);\n should.exist(txs[0].proposalSignaturePubKeySig);\n done();\n });\n });\n });\n });\n });\n\n });\n });\n\n describe('#getBalance', function() {\n var server, wallet;\n beforeEach(function(done) {\n helpers.createAndJoinWallet(1, 1, function(s, w) {\n server = s;\n wallet = w;\n done();\n });\n });\n\n it('should get balance', function(done) {\n helpers.stubUtxos(server, wallet, [1, 'u2', 3], function() {\n server.getBalance({}, function(err, balance) {\n should.not.exist(err);\n should.exist(balance);\n balance.totalAmount.should.equal(helpers.toSatoshi(6));\n balance.lockedAmount.should.equal(0);\n balance.availableAmount.should.equal(helpers.toSatoshi(6));\n balance.totalBytesToSendMax.should.equal(578);\n\n balance.totalConfirmedAmount.should.equal(helpers.toSatoshi(4));\n balance.lockedConfirmedAmount.should.equal(0);\n balance.availableConfirmedAmount.should.equal(helpers.toSatoshi(4));\n\n should.exist(balance.byAddress);\n balance.byAddress.length.should.equal(2);\n balance.byAddress[0].amount.should.equal(helpers.toSatoshi(4));\n balance.byAddress[1].amount.should.equal(helpers.toSatoshi(2));\n server.getMainAddresses({}, function(err, addresses) {\n should.not.exist(err);\n var addresses = _.uniq(_.pluck(addresses, 'address'));\n _.intersection(addresses, _.pluck(balance.byAddress, 'address')).length.should.equal(2);\n done();\n });\n });\n });\n });\n it('should get balance when there are no addresses', function(done) {\n server.getBalance({}, function(err, balance) {\n should.not.exist(err);\n should.exist(balance);\n balance.totalAmount.should.equal(0);\n balance.lockedAmount.should.equal(0);\n balance.availableAmount.should.equal(0);\n balance.totalBytesToSendMax.should.equal(0);\n should.exist(balance.byAddress);\n balance.byAddress.length.should.equal(0);\n done();\n });\n });\n it('should get balance when there are no funds', function(done) {\n blockchainExplorer.getUnspentUtxos = sinon.stub().callsArgWith(1, null, []);\n server.createAddress({}, function(err, address) {\n should.not.exist(err);\n server.getBalance({}, function(err, balance) {\n should.not.exist(err);\n should.exist(balance);\n balance.totalAmount.should.equal(0);\n balance.lockedAmount.should.equal(0);\n balance.availableAmount.should.equal(0);\n balance.totalBytesToSendMax.should.equal(0);\n should.exist(balance.byAddress);\n balance.byAddress.length.should.equal(0);\n done();\n });\n });\n });\n it('should only include addresses with balance', function(done) {\n helpers.stubUtxos(server, wallet, 1, function(utxos) {\n server.createAddress({}, function(err, address) {\n should.not.exist(err);\n server.getBalance({}, function(err, balance) {\n should.not.exist(err);\n balance.byAddress.length.should.equal(1);\n balance.byAddress[0].amount.should.equal(helpers.toSatoshi(1));\n balance.byAddress[0].address.should.equal(utxos[0].address);\n done();\n });\n });\n });\n });\n it('should return correct kb to send max', function(done) {\n helpers.stubUtxos(server, wallet, _.range(1, 10, 0), function() {\n server.getBalance({}, function(err, balance) {\n should.not.exist(err);\n should.exist(balance);\n balance.totalAmount.should.equal(helpers.toSatoshi(9));\n balance.lockedAmount.should.equal(0);\n balance.totalBytesToSendMax.should.equal(1535);\n done();\n });\n });\n });\n it('should fail gracefully when blockchain is unreachable', function(done) {\n blockchainExplorer.getUnspentUtxos = sinon.stub().callsArgWith(1, 'dummy error');\n server.createAddress({}, function(err, address) {\n should.not.exist(err);\n server.getBalance({}, function(err, balance) {\n should.exist(err);\n err.toString().should.equal('dummy error');\n done();\n });\n });\n });\n });\n\n describe('#getFeeLevels', function() {\n var server, wallet;\n beforeEach(function(done) {\n helpers.createAndJoinWallet(1, 1, function(s, w) {\n server = s;\n wallet = w;\n done();\n });\n });\n\n it('should get current fee levels', function(done) {\n helpers.stubFeeLevels({\n 1: 40000,\n 2: 20000,\n 6: 18000,\n });\n server.getFeeLevels({}, function(err, fees) {\n should.not.exist(err);\n fees = _.zipObject(_.map(fees, function(item) {\n return [item.level, item];\n }));\n fees.priority.feePerKb.should.equal(40000);\n fees.priority.nbBlocks.should.equal(1);\n\n fees.normal.feePerKb.should.equal(20000);\n fees.normal.nbBlocks.should.equal(2);\n\n fees.economy.feePerKb.should.equal(18000);\n fees.economy.nbBlocks.should.equal(6);\n done();\n });\n });\n it('should get default fees if network cannot be accessed', function(done) {\n blockchainExplorer.estimateFee = sinon.stub().yields('dummy error');\n server.getFeeLevels({}, function(err, fees) {\n should.not.exist(err);\n fees = _.zipObject(_.map(fees, function(item) {\n return [item.level, item.feePerKb];\n }));\n fees.priority.should.equal(50000);\n fees.normal.should.equal(20000);\n fees.economy.should.equal(10000);\n done();\n });\n });\n it('should get default fees if network cannot estimate (returns -1)', function(done) {\n helpers.stubFeeLevels({\n 1: -1,\n 2: 18000,\n 6: 0,\n });\n server.getFeeLevels({}, function(err, fees) {\n should.not.exist(err);\n fees = _.zipObject(_.map(fees, function(item) {\n return [item.level, item];\n }));\n fees.priority.feePerKb.should.equal(50000);\n should.not.exist(fees.priority.nbBlocks);\n\n fees.normal.feePerKb.should.equal(18000);\n fees.normal.nbBlocks.should.equal(2);\n\n fees.economy.feePerKb.should.equal(0);\n fees.economy.nbBlocks.should.equal(6);\n done();\n });\n });\n });\n\n describe('Wallet not complete tests', function() {\n it('should fail to create address when wallet is not complete', function(done) {\n var server = new WalletService();\n var walletOpts = {\n name: 'my wallet',\n m: 2,\n n: 3,\n pubKey: TestData.keyPair.pub,\n };\n server.createWallet(walletOpts, function(err, walletId) {\n should.not.exist(err);\n var copayerOpts = helpers.getSignedCopayerOpts({\n walletId: walletId,\n name: 'me',\n xPubKey: TestData.copayers[0].xPubKey_45H,\n requestPubKey: TestData.copayers[0].pubKey_1H_0,\n });\n server.joinWallet(copayerOpts, function(err, result) {\n should.not.exist(err);\n helpers.getAuthServer(result.copayerId, function(server) {\n server.createAddress({}, function(err, address) {\n should.not.exist(address);\n should.exist(err);\n err.code.should.equal('WALLET_NOT_COMPLETE');\n err.message.should.equal('Wallet is not complete');\n done();\n });\n });\n });\n });\n });\n\n it('should fail to create tx when wallet is not complete', function(done) {\n var server = new WalletService();\n var walletOpts = {\n name: 'my wallet',\n m: 2,\n n: 3,\n pubKey: TestData.keyPair.pub,\n };\n server.createWallet(walletOpts, function(err, walletId) {\n should.not.exist(err);\n var copayerOpts = helpers.getSignedCopayerOpts({\n walletId: walletId,\n name: 'me',\n xPubKey: TestData.copayers[0].xPubKey_45H,\n requestPubKey: TestData.copayers[0].pubKey_1H_0,\n });\n server.joinWallet(copayerOpts, function(err, result) {\n should.not.exist(err);\n helpers.getAuthServer(result.copayerId, function(server, wallet) {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 80, TestData.copayers[0].privKey);\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(tx);\n should.exist(err);\n err.code.should.equal('WALLET_NOT_COMPLETE');\n done();\n });\n });\n });\n });\n });\n });\n\n describe('#createTx', function() {\n var server, wallet;\n beforeEach(function(done) {\n helpers.createAndJoinWallet(2, 3, function(s, w) {\n server = s;\n wallet = w;\n done();\n });\n });\n\n it('should create a tx', function(done) {\n helpers.stubUtxos(server, wallet, [100, 200], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 80, TestData.copayers[0].privKey_1H_0, {\n message: 'some message',\n customData: 'some custom data'\n });\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n should.exist(tx);\n tx.walletId.should.equal(wallet.id);\n tx.network.should.equal('livenet');\n tx.creatorId.should.equal(wallet.copayers[0].id);\n tx.message.should.equal('some message');\n tx.customData.should.equal('some custom data');\n tx.isAccepted().should.equal.false;\n tx.isRejected().should.equal.false;\n tx.amount.should.equal(helpers.toSatoshi(80));\n var estimatedFee = WalletUtils.DEFAULT_FEE_PER_KB * 400 / 1000; // fully signed tx should have about 400 bytes\n tx.fee.should.be.within(0.9 * estimatedFee, 1.1 * estimatedFee);\n server.getPendingTxs({}, function(err, txs) {\n should.not.exist(err);\n txs.length.should.equal(1);\n // creator\n txs[0].deleteLockTime.should.equal(0);\n server.getBalance({}, function(err, balance) {\n should.not.exist(err);\n balance.totalAmount.should.equal(helpers.toSatoshi(300));\n balance.lockedAmount.should.equal(tx.inputs[0].satoshis);\n balance.lockedAmount.should.be.below(balance.totalAmount);\n balance.availableAmount.should.equal(balance.totalAmount - balance.lockedAmount);\n server.storage.fetchAddresses(wallet.id, function(err, addresses) {\n should.not.exist(err);\n var change = _.filter(addresses, {\n isChange: true\n });\n change.length.should.equal(1);\n done();\n });\n });\n });\n });\n });\n });\n\n it('should create a tx with legacy signature', function(done) {\n helpers.stubUtxos(server, wallet, [100, 200], function() {\n var txOpts = helpers.createProposalOptsLegacy('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 80, 'some message', TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n should.exist(tx);\n done();\n });\n });\n });\n\n it('should create a tx using confirmed utxos first', function(done) {\n helpers.stubUtxos(server, wallet, [1.3, 'u0.5', 'u0.1', 1.2], function(utxos) {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 1.5, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n should.exist(tx);\n tx.inputs.length.should.equal(2);\n _.difference(_.pluck(tx.inputs, 'txid'), [utxos[0].txid, utxos[3].txid]).length.should.equal(0);\n done();\n });\n });\n });\n\n it('should use unconfirmed utxos only when no more confirmed utxos are available', function(done) {\n helpers.stubUtxos(server, wallet, [1.3, 'u0.5', 'u0.1', 1.2], function(utxos) {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 2.55, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n should.exist(tx);\n tx.inputs.length.should.equal(3);\n var txids = _.pluck(tx.inputs, 'txid');\n txids.should.contain(utxos[0].txid);\n txids.should.contain(utxos[3].txid);\n done();\n });\n });\n });\n\n it('should exclude unconfirmed utxos if specified', function(done) {\n helpers.stubUtxos(server, wallet, [1.3, 'u2', 'u0.1', 1.2], function(utxos) {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 3, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n txOpts.excludeUnconfirmedUtxos = true;\n server.createTx(txOpts, function(err, tx) {\n should.exist(err);\n err.code.should.equal('INSUFFICIENT_FUNDS');\n err.message.should.equal('Insufficient funds');\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 2.5, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n txOpts.excludeUnconfirmedUtxos = true;\n server.createTx(txOpts, function(err, tx) {\n should.exist(err);\n err.code.should.equal('INSUFFICIENT_FUNDS_FOR_FEE');\n err.message.should.equal('Insufficient funds for fee');\n done();\n });\n });\n });\n });\n\n it('should use non-locked confirmed utxos when specified', function(done) {\n helpers.stubUtxos(server, wallet, [1.3, 'u2', 'u0.1', 1.2], function(utxos) {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 1.4, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n txOpts.excludeUnconfirmedUtxos = true;\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n should.exist(tx);\n tx.inputs.length.should.equal(2);\n server.getBalance({}, function(err, balance) {\n should.not.exist(err);\n balance.lockedConfirmedAmount.should.equal(helpers.toSatoshi(2.5));\n balance.availableConfirmedAmount.should.equal(0);\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 0.01, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n txOpts.excludeUnconfirmedUtxos = true;\n server.createTx(txOpts, function(err, tx) {\n should.exist(err);\n err.code.should.equal('LOCKED_FUNDS');\n done();\n });\n });\n });\n });\n });\n\n it('should fail gracefully if unable to reach the blockchain', function(done) {\n blockchainExplorer.getUnspentUtxos = sinon.stub().callsArgWith(1, 'dummy error');\n server.createAddress({}, function(err, address) {\n should.not.exist(err);\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 80, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n server.createTx(txOpts, function(err, tx) {\n should.exist(err);\n err.toString().should.equal('dummy error');\n done();\n });\n });\n });\n\n it('should fail to create tx with invalid proposal signature', function(done) {\n helpers.stubUtxos(server, wallet, [100, 200], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 80, 'dummy');\n\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(tx);\n should.exist(err);\n err.message.should.equal('Invalid proposal signature');\n done();\n });\n });\n });\n\n it('should fail to create tx with proposal signed by another copayer', function(done) {\n helpers.stubUtxos(server, wallet, [100, 200], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 80, TestData.copayers[1].privKey_1H_0);\n\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(tx);\n should.exist(err);\n err.message.should.equal('Invalid proposal signature');\n done();\n });\n });\n });\n\n it('should fail to create tx for invalid address', function(done) {\n helpers.stubUtxos(server, wallet, [100, 200], function() {\n var txOpts = helpers.createSimpleProposalOpts('invalid address', 80, TestData.copayers[0].privKey_1H_0);\n\n server.createTx(txOpts, function(err, tx) {\n should.exist(err);\n should.not.exist(tx);\n // may fail due to Non-base58 character, or Checksum mismatch, or other\n done();\n });\n });\n });\n\n it('should fail to create tx for address of different network', function(done) {\n helpers.stubUtxos(server, wallet, [100, 200], function() {\n var txOpts = helpers.createSimpleProposalOpts('myE38JHdxmQcTJGP1ZiX4BiGhDxMJDvLJD', 80, TestData.copayers[0].privKey_1H_0);\n\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(tx);\n should.exist(err);\n err.code.should.equal('INCORRECT_ADDRESS_NETWORK');\n err.message.should.equal('Incorrect address network');\n done();\n });\n });\n });\n\n it('should fail to create tx for invalid amount', function(done) {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 0, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(tx);\n should.exist(err);\n err.message.should.equal('Invalid amount');\n done();\n });\n });\n\n it('should fail to create tx when insufficient funds', function(done) {\n helpers.stubUtxos(server, wallet, [100], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 120, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n should.exist(err);\n err.code.should.equal('INSUFFICIENT_FUNDS');\n err.message.should.equal('Insufficient funds');\n server.getPendingTxs({}, function(err, txs) {\n should.not.exist(err);\n txs.length.should.equal(0);\n server.getBalance({}, function(err, balance) {\n should.not.exist(err);\n balance.lockedAmount.should.equal(0);\n balance.totalAmount.should.equal(10000000000);\n done();\n });\n });\n });\n });\n });\n\n it('should fail to create tx when insufficient funds for fee', function(done) {\n helpers.stubUtxos(server, wallet, 0.048222, function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 0.048200, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n should.exist(err);\n err.code.should.equal('INSUFFICIENT_FUNDS_FOR_FEE');\n err.message.should.equal('Insufficient funds for fee');\n done();\n });\n });\n });\n\n it('should scale fees according to tx size', function(done) {\n helpers.stubUtxos(server, wallet, [1, 1, 1, 1], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 3.5, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n var estimatedFee = WalletUtils.DEFAULT_FEE_PER_KB * 1300 / 1000; // fully signed tx should have about 1300 bytes\n tx.fee.should.be.within(0.9 * estimatedFee, 1.1 * estimatedFee);\n done();\n });\n });\n });\n\n it('should be possible to use a smaller fee', function(done) {\n helpers.stubUtxos(server, wallet, 1, function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 0.99995, TestData.copayers[0].privKey_1H_0, {\n feePerKb: 80000\n });\n server.createTx(txOpts, function(err, tx) {\n should.exist(err);\n err.code.should.equal('INSUFFICIENT_FUNDS_FOR_FEE');\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 0.99995, TestData.copayers[0].privKey_1H_0, {\n feePerKb: 5000\n });\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n var estimatedFee = 5000 * 400 / 1000; // fully signed tx should have about 400 bytes\n tx.fee.should.be.within(0.9 * estimatedFee, 1.1 * estimatedFee);\n\n // Sign it to make sure Bitcore doesn't complain about the fees\n var signatures = helpers.clientSign(tx, TestData.copayers[0].xPrivKey);\n server.signTx({\n txProposalId: tx.id,\n signatures: signatures,\n }, function(err) {\n should.not.exist(err);\n done();\n });\n });\n });\n });\n });\n\n it('should fail to create tx for dust amount', function(done) {\n helpers.stubUtxos(server, wallet, [1], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 0.00000001, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n should.exist(err);\n err.code.should.equal('DUST_AMOUNT');\n err.message.should.equal('Amount below dust threshold');\n done();\n });\n });\n });\n\n it('should fail to create tx that would return change for dust amount', function(done) {\n helpers.stubUtxos(server, wallet, [1], function() {\n var fee = 4095 / 1e8; // The exact fee of the resulting tx\n var change = 100 / 1e8; // Below dust\n var amount = 1 - fee - change;\n\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', amount, TestData.copayers[0].privKey_1H_0, {\n feePerKb: 10000\n });\n server.createTx(txOpts, function(err, tx) {\n should.exist(err);\n err.code.should.equal('DUST_AMOUNT');\n err.message.should.equal('Amount below dust threshold');\n done();\n });\n });\n });\n\n it('should fail with different error for insufficient funds and locked funds', function(done) {\n helpers.stubUtxos(server, wallet, [10, 10], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 11, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n server.getBalance({}, function(err, balance) {\n should.not.exist(err);\n balance.totalAmount.should.equal(helpers.toSatoshi(20));\n balance.lockedAmount.should.equal(helpers.toSatoshi(20));\n txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 8, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n should.exist(err);\n err.code.should.equal('LOCKED_FUNDS');\n err.message.should.equal('Funds are locked by pending transaction proposals');\n done();\n });\n });\n });\n });\n });\n\n it('should create tx with 0 change output', function(done) {\n helpers.stubUtxos(server, wallet, [1], function() {\n var fee = 4100 / 1e8; // The exact fee of the resulting tx\n var amount = 1 - fee;\n\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', amount, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n should.exist(tx);\n var bitcoreTx = tx.getBitcoreTx();\n bitcoreTx.outputs.length.should.equal(1);\n bitcoreTx.outputs[0].satoshis.should.equal(tx.amount);\n done();\n });\n });\n });\n\n it('should fail gracefully when bitcore throws exception on raw tx creation', function(done) {\n helpers.stubUtxos(server, wallet, [10], function() {\n var bitcoreStub = sinon.stub(Bitcore, 'Transaction');\n bitcoreStub.throws({\n name: 'dummy',\n message: 'dummy exception'\n });\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 2, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n should.exist(err);\n err.message.should.equal('dummy exception');\n bitcoreStub.restore();\n done();\n });\n });\n });\n\n it('should create tx when there is a pending tx and enough UTXOs', function(done) {\n helpers.stubUtxos(server, wallet, [10.1, 10.2, 10.3], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 12, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n should.exist(tx);\n var txOpts2 = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 8, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts2, function(err, tx) {\n should.not.exist(err);\n should.exist(tx);\n server.getPendingTxs({}, function(err, txs) {\n should.not.exist(err);\n txs.length.should.equal(2);\n server.getBalance({}, function(err, balance) {\n should.not.exist(err);\n balance.totalAmount.should.equal(3060000000);\n balance.lockedAmount.should.equal(3060000000);\n done();\n });\n });\n });\n });\n });\n });\n\n it('should fail to create tx when there is a pending tx and not enough UTXOs', function(done) {\n helpers.stubUtxos(server, wallet, [10.1, 10.2, 10.3], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 12, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n should.exist(tx);\n var txOpts2 = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 24, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts2, function(err, tx) {\n err.code.should.equal('LOCKED_FUNDS');\n should.not.exist(tx);\n server.getPendingTxs({}, function(err, txs) {\n should.not.exist(err);\n txs.length.should.equal(1);\n server.getBalance({}, function(err, balance) {\n should.not.exist(err);\n balance.totalAmount.should.equal(helpers.toSatoshi(30.6));\n var amountInputs = _.sum(txs[0].inputs, 'satoshis');\n balance.lockedAmount.should.equal(amountInputs);\n balance.lockedAmount.should.be.below(balance.totalAmount);\n balance.availableAmount.should.equal(balance.totalAmount - balance.lockedAmount);\n done();\n });\n });\n });\n });\n });\n });\n\n it('should create tx using different UTXOs for simultaneous requests', function(done) {\n var N = 5;\n helpers.stubUtxos(server, wallet, _.range(100, 100 + N, 0), function(utxos) {\n server.getBalance({}, function(err, balance) {\n should.not.exist(err);\n balance.totalAmount.should.equal(helpers.toSatoshi(N * 100));\n balance.lockedAmount.should.equal(0);\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 80, TestData.copayers[0].privKey_1H_0);\n async.map(_.range(N), function(i, cb) {\n server.createTx(txOpts, function(err, tx) {\n cb(err, tx);\n });\n }, function(err) {\n server.getPendingTxs({}, function(err, txs) {\n should.not.exist(err);\n txs.length.should.equal(N);\n _.uniq(_.pluck(txs, 'changeAddress')).length.should.equal(N);\n server.getBalance({}, function(err, balance) {\n should.not.exist(err);\n balance.totalAmount.should.equal(helpers.toSatoshi(N * 100));\n balance.lockedAmount.should.equal(balance.totalAmount);\n done();\n });\n });\n });\n });\n });\n });\n\n it('should create tx for type multiple_outputs', function(done) {\n helpers.stubUtxos(server, wallet, [100, 200], function() {\n var outputs = [{\n toAddress: '18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7',\n amount: 75,\n message: 'message #1'\n }, {\n toAddress: '18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7',\n amount: 75,\n message: 'message #2'\n }];\n var txOpts = helpers.createProposalOpts(Model.TxProposal.Types.MULTIPLEOUTPUTS, outputs, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n should.exist(tx);\n done();\n });\n });\n });\n\n it('should fail to create tx for type multiple_outputs with missing output argument', function(done) {\n helpers.stubUtxos(server, wallet, [100, 200], function() {\n var outputs = [{\n amount: 80,\n message: 'message #1',\n }, {\n toAddress: '18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7',\n amount: 90,\n message: 'message #2'\n }];\n var txOpts = helpers.createProposalOpts(Model.TxProposal.Types.MULTIPLEOUTPUTS, outputs, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n server.createTx(txOpts, function(err, tx) {\n should.exist(err);\n err.message.should.contain('outputs argument missing');\n done();\n });\n });\n });\n\n it('should fail to create tx for unsupported proposal type', function(done) {\n helpers.stubUtxos(server, wallet, [100, 200], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 80, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n txOpts.type = 'bogus';\n server.createTx(txOpts, function(err, tx) {\n should.exist(err);\n err.message.should.contain('Invalid proposal type');\n done();\n });\n });\n });\n\n it('should be able to send max amount', function(done) {\n helpers.stubUtxos(server, wallet, _.range(1, 10, 0), function() {\n server.getBalance({}, function(err, balance) {\n should.not.exist(err);\n balance.totalAmount.should.equal(helpers.toSatoshi(9));\n balance.lockedAmount.should.equal(0);\n balance.availableAmount.should.equal(helpers.toSatoshi(9));\n balance.totalBytesToSendMax.should.equal(2896);\n var fee = parseInt((balance.totalBytesToSendMax * 10000 / 1000).toFixed(0));\n var max = balance.availableAmount - fee;\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', max / 1e8, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n should.exist(tx);\n tx.amount.should.equal(max);\n var estimatedFee = 2896 * 10000 / 1000;\n tx.fee.should.be.within(0.9 * estimatedFee, 1.1 * estimatedFee);\n server.getBalance({}, function(err, balance) {\n should.not.exist(err);\n balance.lockedAmount.should.equal(helpers.toSatoshi(9));\n balance.availableAmount.should.equal(0);\n done();\n });\n });\n });\n });\n });\n it('should be able to send max non-locked amount', function(done) {\n helpers.stubUtxos(server, wallet, _.range(1, 10, 0), function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 3.5, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n server.getBalance({}, function(err, balance) {\n should.not.exist(err);\n balance.totalAmount.should.equal(helpers.toSatoshi(9));\n balance.lockedAmount.should.equal(helpers.toSatoshi(4));\n balance.availableAmount.should.equal(helpers.toSatoshi(5));\n balance.totalBytesToSendMax.should.equal(1653);\n var fee = parseInt((balance.totalBytesToSendMax * 2000 / 1000).toFixed(0));\n var max = balance.availableAmount - fee;\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', max / 1e8, TestData.copayers[0].privKey_1H_0, {\n feePerKb: 2000\n });\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n should.exist(tx);\n tx.amount.should.equal(max);\n var estimatedFee = 1653 * 2000 / 1000;\n tx.fee.should.be.within(0.9 * estimatedFee, 1.1 * estimatedFee);\n server.getBalance({}, function(err, balance) {\n should.not.exist(err);\n balance.lockedAmount.should.equal(helpers.toSatoshi(9));\n done();\n });\n });\n });\n });\n });\n });\n it('should not use UTXO provided in utxosToExclude option', function(done) {\n helpers.stubUtxos(server, wallet, [1, 2, 3], function(utxos) {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 4.5, TestData.copayers[0].privKey_1H_0);\n txOpts.utxosToExclude = [utxos[1].txid + ':' + utxos[1].vout];\n server.createTx(txOpts, function(err, tx) {\n should.exist(err);\n err.code.should.equal('INSUFFICIENT_FUNDS');\n err.message.should.equal('Insufficient funds');\n done();\n });\n });\n });\n it('should use non-excluded UTXOs', function(done) {\n helpers.stubUtxos(server, wallet, [1, 2], function(utxos) {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 0.5, TestData.copayers[0].privKey_1H_0);\n txOpts.utxosToExclude = [utxos[0].txid + ':' + utxos[0].vout];\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n tx.inputs.length.should.equal(1);\n tx.inputs[0].txid.should.equal(utxos[1].txid);\n tx.inputs[0].vout.should.equal(utxos[1].vout);\n done();\n });\n });\n });\n });\n\n describe('#createTx backoff time', function(done) {\n var server, wallet, txid;\n\n beforeEach(function(done) {\n helpers.createAndJoinWallet(2, 2, function(s, w) {\n server = s;\n wallet = w;\n helpers.stubUtxos(server, wallet, _.range(2, 6), function() {\n done();\n });\n });\n });\n\n it('should follow backoff time after consecutive rejections', function(done) {\n async.series([\n\n function(next) {\n async.each(_.range(3), function(i, next) {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 1, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n server.rejectTx({\n txProposalId: tx.id,\n reason: 'some reason',\n }, next);\n });\n },\n next);\n },\n function(next) {\n // Allow a 4th tx\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 1, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n server.rejectTx({\n txProposalId: tx.id,\n reason: 'some reason',\n }, next);\n });\n },\n function(next) {\n // Do not allow before backoff time\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 1, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n should.exist(err);\n err.code.should.equal('TX_CANNOT_CREATE');\n next();\n });\n },\n function(next) {\n var clock = sinon.useFakeTimers(Date.now() + (WalletService.BACKOFF_TIME + 2) * 60 * 1000, 'Date');\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 1, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n clock.restore();\n server.rejectTx({\n txProposalId: tx.id,\n reason: 'some reason',\n }, next);\n });\n },\n function(next) {\n // Do not allow a 5th tx before backoff time\n var clock = sinon.useFakeTimers(Date.now() + (WalletService.BACKOFF_TIME + 2) * 60 * 1000 + 1, 'Date');\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 1, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n clock.restore();\n should.exist(err);\n err.code.should.equal('TX_CANNOT_CREATE');\n next();\n });\n },\n ], function(err) {\n should.not.exist(err);\n done();\n });\n });\n });\n\n describe('#rejectTx', function() {\n var server, wallet, txid;\n\n beforeEach(function(done) {\n helpers.createAndJoinWallet(2, 2, function(s, w) {\n server = s;\n wallet = w;\n helpers.stubUtxos(server, wallet, _.range(1, 9), function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 10, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n should.exist(tx);\n txid = tx.id;\n done();\n });\n });\n });\n });\n\n it('should reject a TX', function(done) {\n server.getPendingTxs({}, function(err, txs) {\n var tx = txs[0];\n tx.id.should.equal(txid);\n\n server.rejectTx({\n txProposalId: txid,\n reason: 'some reason',\n }, function(err) {\n should.not.exist(err);\n server.getPendingTxs({}, function(err, txs) {\n should.not.exist(err);\n txs.should.be.empty;\n server.getTx({\n txProposalId: txid\n }, function(err, tx) {\n var actors = tx.getActors();\n actors.length.should.equal(1);\n actors[0].should.equal(wallet.copayers[0].id);\n var action = tx.getActionBy(wallet.copayers[0].id);\n action.type.should.equal('reject');\n action.comment.should.equal('some reason');\n done();\n });\n });\n });\n });\n });\n\n it('should fail to reject non-pending TX', function(done) {\n async.waterfall([\n\n function(next) {\n server.getPendingTxs({}, function(err, txs) {\n var tx = txs[0];\n tx.id.should.equal(txid);\n next();\n });\n },\n function(next) {\n server.rejectTx({\n txProposalId: txid,\n reason: 'some reason',\n }, function(err) {\n should.not.exist(err);\n next();\n });\n },\n function(next) {\n server.getPendingTxs({}, function(err, txs) {\n should.not.exist(err);\n txs.should.be.empty;\n next();\n });\n },\n function(next) {\n helpers.getAuthServer(wallet.copayers[1].id, function(server) {\n server.rejectTx({\n txProposalId: txid,\n reason: 'some other reason',\n }, function(err) {\n should.exist(err);\n err.code.should.equal('TX_NOT_PENDING');\n done();\n });\n });\n },\n ]);\n });\n });\n\n describe('#signTx', function() {\n describe('1-of-1 (BIP44 & P2PKH)', function() {\n var server, wallet, txid;\n\n beforeEach(function(done) {\n helpers.createAndJoinWallet(1, 1, function(s, w) {\n server = s;\n wallet = w;\n helpers.stubUtxos(server, wallet, [1, 2], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 2.5, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n should.exist(tx);\n tx.derivationStrategy.should.equal('BIP44');\n tx.addressType.should.equal('P2PKH');\n txid = tx.id;\n done();\n });\n });\n });\n });\n\n it('should sign a TX with multiple inputs, different paths, and return raw', function(done) {\n blockchainExplorer.getTransaction = sinon.stub().callsArgWith(1, null, null);\n server.getPendingTxs({}, function(err, txs) {\n var tx = txs[0];\n tx.id.should.equal(txid);\n var signatures = helpers.clientSign(tx, TestData.copayers[0].xPrivKey);\n should.not.exist(tx.raw);\n server.signTx({\n txProposalId: txid,\n signatures: signatures,\n }, function(err, txp) {\n should.not.exist(err);\n txp.status.should.equal('accepted');\n // The raw Tx should contain the Signatures.\n txp.raw.should.contain(signatures[0]);\n\n // Get pending should also contains the raw TX\n server.getPendingTxs({}, function(err, txs) {\n var tx = txs[0];\n should.not.exist(err);\n tx.status.should.equal('accepted');\n tx.raw.should.contain(signatures[0]);\n done();\n });\n });\n });\n });\n });\n\n describe('Multisig', function() {\n var server, wallet, txid;\n\n beforeEach(function(done) {\n helpers.createAndJoinWallet(2, 3, function(s, w) {\n server = s;\n wallet = w;\n helpers.stubUtxos(server, wallet, _.range(1, 9), function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 20, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n should.exist(tx);\n txid = tx.id;\n done();\n });\n });\n });\n });\n\n it('should sign a TX with multiple inputs, different paths', function(done) {\n server.getPendingTxs({}, function(err, txs) {\n var tx = txs[0];\n tx.id.should.equal(txid);\n\n var signatures = helpers.clientSign(tx, TestData.copayers[0].xPrivKey);\n server.signTx({\n txProposalId: txid,\n signatures: signatures,\n }, function(err, txp) {\n should.not.exist(err);\n should.not.exist(tx.raw);\n server.getPendingTxs({}, function(err, txs) {\n should.not.exist(err);\n var tx = txs[0];\n tx.id.should.equal(txid);\n\n var actors = tx.getActors();\n actors.length.should.equal(1);\n actors[0].should.equal(wallet.copayers[0].id);\n tx.getActionBy(wallet.copayers[0].id).type.should.equal('accept');\n\n done();\n });\n });\n });\n });\n\n it('should fail to sign with a xpriv from other copayer', function(done) {\n server.getPendingTxs({}, function(err, txs) {\n var tx = txs[0];\n tx.id.should.equal(txid);\n var signatures = helpers.clientSign(tx, TestData.copayers[1].xPrivKey);\n server.signTx({\n txProposalId: txid,\n signatures: signatures,\n }, function(err) {\n err.code.should.equal('BAD_SIGNATURES');\n done();\n });\n });\n });\n\n it('should fail if one signature is broken', function(done) {\n server.getPendingTxs({}, function(err, txs) {\n var tx = txs[0];\n tx.id.should.equal(txid);\n\n var signatures = helpers.clientSign(tx, TestData.copayers[0].xPrivKey);\n signatures[0] = 1;\n\n server.signTx({\n txProposalId: txid,\n signatures: signatures,\n }, function(err) {\n err.message.should.contain('signatures');\n done();\n });\n });\n });\n\n it('should fail on invalid signature', function(done) {\n server.getPendingTxs({}, function(err, txs) {\n var tx = txs[0];\n tx.id.should.equal(txid);\n\n var signatures = ['11', '22', '33', '44', '55'];\n server.signTx({\n txProposalId: txid,\n signatures: signatures,\n }, function(err) {\n should.exist(err);\n err.message.should.contain('Bad signatures');\n done();\n });\n });\n });\n\n it('should fail on wrong number of invalid signatures', function(done) {\n server.getPendingTxs({}, function(err, txs) {\n var tx = txs[0];\n tx.id.should.equal(txid);\n\n var signatures = _.take(helpers.clientSign(tx, TestData.copayers[0].xPrivKey), tx.inputs.length - 1);\n server.signTx({\n txProposalId: txid,\n signatures: signatures,\n }, function(err) {\n should.exist(err);\n err.message.should.contain('Bad signatures');\n done();\n });\n });\n });\n\n it('should fail when signing a TX previously rejected', function(done) {\n server.getPendingTxs({}, function(err, txs) {\n var tx = txs[0];\n tx.id.should.equal(txid);\n\n var signatures = helpers.clientSign(tx, TestData.copayers[0].xPrivKey);\n server.signTx({\n txProposalId: txid,\n signatures: signatures,\n }, function(err) {\n server.rejectTx({\n txProposalId: txid,\n }, function(err) {\n err.code.should.contain('COPAYER_VOTED');\n done();\n });\n });\n });\n });\n\n it('should fail when rejected a previously signed TX', function(done) {\n server.getPendingTxs({}, function(err, txs) {\n var tx = txs[0];\n tx.id.should.equal(txid);\n\n server.rejectTx({\n txProposalId: txid,\n }, function(err) {\n var signatures = helpers.clientSign(tx, TestData.copayers[0].xPrivKey);\n server.signTx({\n txProposalId: txid,\n signatures: signatures,\n }, function(err) {\n err.code.should.contain('COPAYER_VOTED');\n done();\n });\n });\n });\n });\n\n it('should fail to sign a non-pending TX', function(done) {\n async.waterfall([\n\n function(next) {\n server.rejectTx({\n txProposalId: txid,\n reason: 'some reason',\n }, function(err) {\n should.not.exist(err);\n next();\n });\n },\n function(next) {\n helpers.getAuthServer(wallet.copayers[1].id, function(server) {\n server.rejectTx({\n txProposalId: txid,\n reason: 'some reason',\n }, function(err) {\n should.not.exist(err);\n next();\n });\n });\n },\n function(next) {\n server.getPendingTxs({}, function(err, txs) {\n should.not.exist(err);\n txs.should.be.empty;\n next();\n });\n },\n function(next) {\n helpers.getAuthServer(wallet.copayers[2].id, function(server) {\n server.getTx({\n txProposalId: txid\n }, function(err, tx) {\n should.not.exist(err);\n var signatures = helpers.clientSign(tx, TestData.copayers[2].xPrivKey);\n server.signTx({\n txProposalId: txid,\n signatures: signatures,\n }, function(err) {\n should.exist(err);\n err.code.should.equal('TX_NOT_PENDING');\n done();\n });\n });\n });\n },\n ]);\n });\n });\n });\n\n describe('#broadcastTx & #broadcastRawTx', function() {\n var server, wallet, txpid, txid;\n beforeEach(function(done) {\n helpers.createAndJoinWallet(1, 1, function(s, w) {\n server = s;\n wallet = w;\n helpers.stubUtxos(server, wallet, [10, 10], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 9, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n server.createTx(txOpts, function(err, txp) {\n should.not.exist(err);\n should.exist(txp);\n var signatures = helpers.clientSign(txp, TestData.copayers[0].xPrivKey);\n server.signTx({\n txProposalId: txp.id,\n signatures: signatures,\n }, function(err, txp) {\n should.not.exist(err);\n should.exist(txp);\n txp.isAccepted().should.be.true;\n txp.isBroadcasted().should.be.false;\n txid = txp.txid;\n txpid = txp.id;\n done();\n });\n });\n });\n });\n });\n\n it('should broadcast a tx', function(done) {\n var clock = sinon.useFakeTimers(1234000, 'Date');\n helpers.stubBroadcast();\n server.broadcastTx({\n txProposalId: txpid\n }, function(err) {\n should.not.exist(err);\n server.getTx({\n txProposalId: txpid\n }, function(err, txp) {\n should.not.exist(err);\n should.not.exist(txp.raw);\n txp.txid.should.equal(txid);\n txp.isBroadcasted().should.be.true;\n txp.broadcastedOn.should.equal(1234);\n clock.restore();\n done();\n });\n });\n });\n\n it('should broadcast a raw tx', function(done) {\n helpers.stubBroadcast();\n server.broadcastRawTx({\n network: 'testnet',\n rawTx: 'raw tx',\n }, function(err, txid) {\n should.not.exist(err);\n should.exist(txid);\n done();\n });\n });\n\n it('should fail to brodcast a tx already marked as broadcasted', function(done) {\n helpers.stubBroadcast();\n server.broadcastTx({\n txProposalId: txpid\n }, function(err) {\n should.not.exist(err);\n server.broadcastTx({\n txProposalId: txpid\n }, function(err) {\n should.exist(err);\n err.code.should.equal('TX_ALREADY_BROADCASTED');\n done();\n });\n });\n });\n\n it('should auto process already broadcasted txs', function(done) {\n helpers.stubBroadcast();\n server.getPendingTxs({}, function(err, txs) {\n should.not.exist(err);\n txs.length.should.equal(1);\n blockchainExplorer.getTransaction = sinon.stub().callsArgWith(1, null, {\n txid: 999\n });\n server.getPendingTxs({}, function(err, txs) {\n should.not.exist(err);\n txs.length.should.equal(0);\n done();\n });\n });\n });\n\n it('should process only broadcasted txs', function(done) {\n helpers.stubBroadcast();\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 9, TestData.copayers[0].privKey_1H_0, {\n message: 'some message 2'\n });\n server.createTx(txOpts, function(err, txp) {\n should.not.exist(err);\n server.getPendingTxs({}, function(err, txs) {\n should.not.exist(err);\n txs.length.should.equal(2);\n blockchainExplorer.getTransaction = sinon.stub().callsArgWith(1, null, {\n txid: 999\n });\n server.getPendingTxs({}, function(err, txs) {\n should.not.exist(err);\n txs.length.should.equal(1);\n txs[0].status.should.equal('pending');\n should.not.exist(txs[0].txid);\n done();\n });\n });\n });\n });\n\n\n\n\n\n it('should fail to brodcast a not yet accepted tx', function(done) {\n helpers.stubBroadcast();\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 9, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n server.createTx(txOpts, function(err, txp) {\n should.not.exist(err);\n should.exist(txp);\n server.broadcastTx({\n txProposalId: txp.id\n }, function(err) {\n should.exist(err);\n err.code.should.equal('TX_NOT_ACCEPTED');\n done();\n });\n });\n });\n\n it('should keep tx as accepted if unable to broadcast it', function(done) {\n blockchainExplorer.broadcast = sinon.stub().callsArgWith(1, 'broadcast error');\n blockchainExplorer.getTransaction = sinon.stub().callsArgWith(1, null, null);\n server.broadcastTx({\n txProposalId: txpid\n }, function(err) {\n should.exist(err);\n err.toString().should.equal('broadcast error');\n server.getTx({\n txProposalId: txpid\n }, function(err, txp) {\n should.not.exist(err);\n should.exist(txp.txid);\n txp.isBroadcasted().should.be.false;\n should.not.exist(txp.broadcastedOn);\n txp.isAccepted().should.be.true;\n done();\n });\n });\n });\n\n it('should mark tx as broadcasted if accepted but already in blockchain', function(done) {\n blockchainExplorer.broadcast = sinon.stub().callsArgWith(1, 'broadcast error');\n blockchainExplorer.getTransaction = sinon.stub().callsArgWith(1, null, {\n txid: '999'\n });\n server.broadcastTx({\n txProposalId: txpid\n }, function(err) {\n should.not.exist(err);\n server.getTx({\n txProposalId: txpid\n }, function(err, txp) {\n should.not.exist(err);\n should.exist(txp.txid);\n txp.isBroadcasted().should.be.true;\n should.exist(txp.broadcastedOn);\n done();\n });\n });\n });\n\n it('should keep tx as accepted if broadcast fails and cannot check tx in blockchain', function(done) {\n blockchainExplorer.broadcast = sinon.stub().callsArgWith(1, 'broadcast error');\n blockchainExplorer.getTransaction = sinon.stub().callsArgWith(1, 'bc check error');\n server.broadcastTx({\n txProposalId: txpid\n }, function(err) {\n should.exist(err);\n err.toString().should.equal('bc check error');\n server.getTx({\n txProposalId: txpid\n }, function(err, txp) {\n should.not.exist(err);\n should.exist(txp.txid);\n txp.isBroadcasted().should.be.false;\n should.not.exist(txp.broadcastedOn);\n txp.isAccepted().should.be.true;\n done();\n });\n });\n });\n });\n\n describe('Tx proposal workflow', function() {\n var server, wallet;\n beforeEach(function(done) {\n helpers.createAndJoinWallet(2, 3, function(s, w) {\n server = s;\n wallet = w;\n helpers.stubUtxos(server, wallet, _.range(1, 9), function() {\n helpers.stubBroadcast();\n done();\n });\n });\n });\n\n it('other copayers should see pending proposal created by one copayer', function(done) {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 10, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n server.createTx(txOpts, function(err, txp) {\n should.not.exist(err);\n should.exist(txp);\n helpers.getAuthServer(wallet.copayers[1].id, function(server2, wallet) {\n server2.getPendingTxs({}, function(err, txps) {\n should.not.exist(err);\n txps.length.should.equal(1);\n txps[0].id.should.equal(txp.id);\n txps[0].message.should.equal('some message');\n done();\n });\n });\n });\n });\n\n it('tx proposals should not be finally accepted until quorum is reached', function(done) {\n var txpId;\n async.waterfall([\n\n function(next) {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 10, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n server.createTx(txOpts, function(err, txp) {\n txpId = txp.id;\n should.not.exist(err);\n should.exist(txp);\n next();\n });\n },\n function(next) {\n server.getPendingTxs({}, function(err, txps) {\n should.not.exist(err);\n txps.length.should.equal(1);\n var txp = txps[0];\n txp.actions.should.be.empty;\n next(null, txp);\n });\n },\n function(txp, next) {\n var signatures = helpers.clientSign(txp, TestData.copayers[0].xPrivKey);\n server.signTx({\n txProposalId: txpId,\n signatures: signatures,\n }, function(err) {\n should.not.exist(err);\n next();\n });\n },\n function(next) {\n server.getPendingTxs({}, function(err, txps) {\n should.not.exist(err);\n txps.length.should.equal(1);\n var txp = txps[0];\n txp.isPending().should.be.true;\n txp.isAccepted().should.be.false;\n txp.isRejected().should.be.false;\n txp.isBroadcasted().should.be.false;\n txp.actions.length.should.equal(1);\n var action = txp.getActionBy(wallet.copayers[0].id);\n action.type.should.equal('accept');\n server.getNotifications({}, function(err, notifications) {\n should.not.exist(err);\n var last = _.last(notifications);\n last.type.should.not.equal('TxProposalFinallyAccepted');\n next(null, txp);\n });\n });\n },\n function(txp, next) {\n helpers.getAuthServer(wallet.copayers[1].id, function(server, wallet) {\n var signatures = helpers.clientSign(txp, TestData.copayers[1].xPrivKey);\n server.signTx({\n txProposalId: txpId,\n signatures: signatures,\n }, function(err) {\n should.not.exist(err);\n next();\n });\n });\n },\n function(next) {\n server.getPendingTxs({}, function(err, txps) {\n should.not.exist(err);\n txps.length.should.equal(1);\n var txp = txps[0];\n txp.isPending().should.be.true;\n txp.isAccepted().should.be.true;\n txp.isBroadcasted().should.be.false;\n should.exist(txp.txid);\n txp.actions.length.should.equal(2);\n server.getNotifications({}, function(err, notifications) {\n should.not.exist(err);\n var last = _.last(notifications);\n last.type.should.equal('TxProposalFinallyAccepted');\n last.walletId.should.equal(wallet.id);\n last.creatorId.should.equal(wallet.copayers[1].id);\n last.data.txProposalId.should.equal(txp.id);\n done();\n });\n });\n },\n ]);\n });\n\n it('tx proposals should accept as many rejections as possible without finally rejecting', function(done) {\n var txpId;\n async.waterfall([\n\n function(next) {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 10, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n server.createTx(txOpts, function(err, txp) {\n txpId = txp.id;\n should.not.exist(err);\n should.exist(txp);\n next();\n });\n },\n function(next) {\n server.getPendingTxs({}, function(err, txps) {\n should.not.exist(err);\n txps.length.should.equal(1);\n var txp = txps[0];\n txp.actions.should.be.empty;\n next();\n });\n },\n function(next) {\n server.rejectTx({\n txProposalId: txpId,\n reason: 'just because'\n }, function(err) {\n should.not.exist(err);\n next();\n });\n },\n function(next) {\n server.getPendingTxs({}, function(err, txps) {\n should.not.exist(err);\n txps.length.should.equal(1);\n var txp = txps[0];\n txp.isPending().should.be.true;\n txp.isRejected().should.be.false;\n txp.isAccepted().should.be.false;\n txp.actions.length.should.equal(1);\n var action = txp.getActionBy(wallet.copayers[0].id);\n action.type.should.equal('reject');\n action.comment.should.equal('just because');\n next();\n });\n },\n function(next) {\n helpers.getAuthServer(wallet.copayers[1].id, function(server, wallet) {\n server.rejectTx({\n txProposalId: txpId,\n reason: 'some other reason'\n }, function(err) {\n should.not.exist(err);\n next();\n });\n });\n },\n function(next) {\n server.getPendingTxs({}, function(err, txps) {\n should.not.exist(err);\n txps.length.should.equal(0);\n next();\n });\n },\n function(next) {\n server.getTx({\n txProposalId: txpId\n }, function(err, txp) {\n should.not.exist(err);\n txp.isPending().should.be.false;\n txp.isRejected().should.be.true;\n txp.isAccepted().should.be.false;\n txp.actions.length.should.equal(2);\n done();\n });\n },\n ]);\n });\n });\n\n describe('#getTx', function() {\n var server, wallet, txpid;\n beforeEach(function(done) {\n helpers.createAndJoinWallet(2, 3, function(s, w) {\n server = s;\n wallet = w;\n helpers.stubUtxos(server, wallet, 10, function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 9, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n server.createTx(txOpts, function(err, txp) {\n should.not.exist(err);\n should.exist(txp);\n txpid = txp.id;\n done();\n });\n });\n });\n });\n\n it('should get own transaction proposal', function(done) {\n server.getTx({\n txProposalId: txpid\n }, function(err, txp) {\n should.not.exist(err);\n should.exist(txp);\n txp.id.should.equal(txpid);\n done();\n });\n });\n it('should get someone elses transaction proposal', function(done) {\n helpers.getAuthServer(wallet.copayers[1].id, function(server2, wallet) {\n server2.getTx({\n txProposalId: txpid\n }, function(err, res) {\n should.not.exist(err);\n res.id.should.equal(txpid);\n done();\n });\n });\n\n });\n it('should fail to get non-existent transaction proposal', function(done) {\n server.getTx({\n txProposalId: 'dummy'\n }, function(err, txp) {\n should.exist(err);\n should.not.exist(txp);\n err.code.should.equal('TX_NOT_FOUND')\n err.message.should.equal('Transaction proposal not found');\n done();\n });\n });\n it.skip('should get accepted/rejected transaction proposal', function(done) {});\n it.skip('should get broadcasted transaction proposal', function(done) {});\n });\n\n describe('#getTxs', function() {\n var server, wallet, clock;\n\n beforeEach(function(done) {\n this.timeout(5000);\n clock = sinon.useFakeTimers('Date');\n helpers.createAndJoinWallet(1, 1, function(s, w) {\n server = s;\n wallet = w;\n helpers.stubUtxos(server, wallet, _.range(1, 11), function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 0.1, TestData.copayers[0].privKey_1H_0);\n async.eachSeries(_.range(10), function(i, next) {\n clock.tick(10 * 1000);\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n next();\n });\n }, function(err) {\n clock.restore();\n return done(err);\n });\n });\n });\n });\n afterEach(function() {\n clock.restore();\n });\n\n it('should pull 4 txs, down to to time 60', function(done) {\n server.getTxs({\n minTs: 60,\n limit: 8\n }, function(err, txps) {\n should.not.exist(err);\n var times = _.pluck(txps, 'createdOn');\n times.should.deep.equal([100, 90, 80, 70, 60]);\n done();\n });\n });\n\n it('should pull the first 5 txs', function(done) {\n server.getTxs({\n maxTs: 50,\n limit: 5\n }, function(err, txps) {\n should.not.exist(err);\n var times = _.pluck(txps, 'createdOn');\n times.should.deep.equal([50, 40, 30, 20, 10]);\n done();\n });\n });\n\n it('should pull the last 4 txs', function(done) {\n server.getTxs({\n limit: 4\n }, function(err, txps) {\n should.not.exist(err);\n var times = _.pluck(txps, 'createdOn');\n times.should.deep.equal([100, 90, 80, 70]);\n done();\n });\n });\n\n it('should pull all txs', function(done) {\n server.getTxs({}, function(err, txps) {\n should.not.exist(err);\n var times = _.pluck(txps, 'createdOn');\n times.should.deep.equal([100, 90, 80, 70, 60, 50, 40, 30, 20, 10]);\n done();\n });\n });\n\n\n it('should txs from times 50 to 70',\n function(done) {\n server.getTxs({\n minTs: 50,\n maxTs: 70,\n }, function(err, txps) {\n should.not.exist(err);\n var times = _.pluck(txps, 'createdOn');\n times.should.deep.equal([70, 60, 50]);\n done();\n });\n });\n });\n\n describe('#getNotifications', function() {\n var clock;\n var server, wallet;\n\n beforeEach(function(done) {\n clock = sinon.useFakeTimers(10 * 1000, 'Date');\n helpers.createAndJoinWallet(1, 1, function(s, w) {\n server = s;\n wallet = w;\n helpers.stubUtxos(server, wallet, _.range(4), function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 0.01, TestData.copayers[0].privKey_1H_0);\n async.eachSeries(_.range(3), function(i, next) {\n clock.tick(25 * 1000);\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n next();\n });\n }, function(err) {\n clock.tick(20 * 1000);\n return done(err);\n });\n });\n });\n });\n afterEach(function() {\n clock.restore();\n });\n\n it('should pull all notifications', function(done) {\n server.getNotifications({}, function(err, notifications) {\n should.not.exist(err);\n var types = _.pluck(notifications, 'type');\n types.should.deep.equal(['NewCopayer', 'NewAddress', 'NewAddress', 'NewTxProposal', 'NewTxProposal', 'NewTxProposal']);\n var walletIds = _.uniq(_.pluck(notifications, 'walletId'));\n walletIds.length.should.equal(1);\n walletIds[0].should.equal(wallet.id);\n var creators = _.uniq(_.compact(_.pluck(notifications, 'creatorId')));\n creators.length.should.equal(1);\n creators[0].should.equal(wallet.copayers[0].id);\n done();\n });\n });\n\n it('should pull new block notifications along with wallet notifications in the last 60 seconds', function(done) {\n // Simulate new block notification\n server.walletId = 'livenet';\n server._notify('NewBlock', {\n hash: 'dummy hash',\n }, {\n isGlobal: true\n }, function(err) {\n should.not.exist(err);\n server.walletId = 'testnet';\n server._notify('NewBlock', {\n hash: 'dummy hash',\n }, {\n isGlobal: true\n }, function(err) {\n should.not.exist(err);\n server.walletId = wallet.id;\n server.getNotifications({\n minTs: +Date.now() - (60 * 1000),\n }, function(err, notifications) {\n should.not.exist(err);\n var types = _.pluck(notifications, 'type');\n types.should.deep.equal(['NewTxProposal', 'NewTxProposal', 'NewBlock']);\n var walletIds = _.uniq(_.pluck(notifications, 'walletId'));\n walletIds.length.should.equal(1);\n walletIds[0].should.equal(wallet.id);\n done();\n });\n });\n });\n });\n\n it('should pull notifications in the last 60 seconds', function(done) {\n server.getNotifications({\n minTs: +Date.now() - (60 * 1000),\n }, function(err, notifications) {\n should.not.exist(err);\n var types = _.pluck(notifications, 'type');\n types.should.deep.equal(['NewTxProposal', 'NewTxProposal']);\n done();\n });\n });\n\n it('should pull notifications after a given notification id', function(done) {\n server.getNotifications({}, function(err, notifications) {\n should.not.exist(err);\n var from = _.first(_.takeRight(notifications, 2)).id; // second to last\n server.getNotifications({\n notificationId: from,\n minTs: +Date.now() - (60 * 1000),\n }, function(err, res) {\n should.not.exist(err);\n res.length.should.equal(1);\n res[0].id.should.equal(_.first(_.takeRight(notifications)).id);\n done();\n });\n });\n });\n\n it('should return empty if no notifications found after a given id', function(done) {\n server.getNotifications({}, function(err, notifications) {\n should.not.exist(err);\n var from = _.first(_.takeRight(notifications)).id; // last one\n server.getNotifications({\n notificationId: from,\n }, function(err, res) {\n should.not.exist(err);\n res.length.should.equal(0);\n done();\n });\n });\n });\n\n it('should return empty if no notifications exist in the given timespan', function(done) {\n clock.tick(100 * 1000);\n server.getNotifications({\n minTs: +Date.now() - (60 * 1000),\n }, function(err, res) {\n should.not.exist(err);\n res.length.should.equal(0);\n done();\n });\n });\n\n it('should contain walletId & creatorId on NewCopayer', function(done) {\n server.getNotifications({}, function(err, notifications) {\n should.not.exist(err);\n var newCopayer = notifications[0];\n newCopayer.type.should.equal('NewCopayer');\n newCopayer.walletId.should.equal(wallet.id);\n newCopayer.creatorId.should.equal(wallet.copayers[0].id);\n done();\n });\n });\n\n it('should notify sign and acceptance', function(done) {\n server.getPendingTxs({}, function(err, txs) {\n blockchainExplorer.broadcast = sinon.stub().callsArgWith(1, 'broadcast error');\n var tx = txs[0];\n var signatures = helpers.clientSign(tx, TestData.copayers[0].xPrivKey);\n server.signTx({\n txProposalId: tx.id,\n signatures: signatures,\n }, function(err) {\n server.getNotifications({\n minTs: Date.now(),\n }, function(err, notifications) {\n should.not.exist(err);\n notifications.length.should.equal(2);\n var types = _.pluck(notifications, 'type');\n types.should.deep.equal(['TxProposalAcceptedBy', 'TxProposalFinallyAccepted']);\n done();\n });\n });\n });\n });\n\n it('should notify rejection', function(done) {\n server.getPendingTxs({}, function(err, txs) {\n var tx = txs[1];\n server.rejectTx({\n txProposalId: tx.id,\n }, function(err) {\n should.not.exist(err);\n server.getNotifications({\n minTs: Date.now(),\n }, function(err, notifications) {\n should.not.exist(err);\n notifications.length.should.equal(2);\n var types = _.pluck(notifications, 'type');\n types.should.deep.equal(['TxProposalRejectedBy', 'TxProposalFinallyRejected']);\n done();\n });\n });\n });\n });\n\n\n it('should notify sign, acceptance, and broadcast, and emit', function(done) {\n server.getPendingTxs({}, function(err, txs) {\n var tx = txs[2];\n var signatures = helpers.clientSign(tx, TestData.copayers[0].xPrivKey);\n server.signTx({\n txProposalId: tx.id,\n signatures: signatures,\n }, function(err) {\n should.not.exist(err);\n helpers.stubBroadcast();\n server.broadcastTx({\n txProposalId: tx.id\n }, function(err, txp) {\n should.not.exist(err);\n server.getNotifications({\n minTs: Date.now(),\n }, function(err, notifications) {\n should.not.exist(err);\n notifications.length.should.equal(3);\n var types = _.pluck(notifications, 'type');\n types.should.deep.equal(['TxProposalAcceptedBy', 'TxProposalFinallyAccepted', 'NewOutgoingTx']);\n done();\n });\n });\n });\n });\n });\n\n\n it('should notify sign, acceptance, and broadcast, and emit (with 3rd party broadcast', function(done) {\n server.getPendingTxs({}, function(err, txs) {\n var tx = txs[2];\n var signatures = helpers.clientSign(tx, TestData.copayers[0].xPrivKey);\n server.signTx({\n txProposalId: tx.id,\n signatures: signatures,\n }, function(err) {\n should.not.exist(err);\n blockchainExplorer.broadcast = sinon.stub().callsArgWith(1, 'err');\n blockchainExplorer.getTransaction = sinon.stub().callsArgWith(1, null, {\n txid: 11\n });\n server.broadcastTx({\n txProposalId: tx.id\n }, function(err, txp) {\n should.not.exist(err);\n server.getNotifications({\n minTs: Date.now(),\n }, function(err, notifications) {\n should.not.exist(err);\n notifications.length.should.equal(3);\n var types = _.pluck(notifications, 'type');\n types.should.deep.equal(['TxProposalAcceptedBy', 'TxProposalFinallyAccepted', 'NewOutgoingTxByThirdParty']);\n done();\n });\n });\n });\n });\n });\n });\n\n describe('#removeWallet', function() {\n var server, wallet, clock;\n\n beforeEach(function(done) {\n helpers.createAndJoinWallet(1, 1, function(s, w) {\n server = s;\n wallet = w;\n\n helpers.stubUtxos(server, wallet, _.range(2), function() {\n var txOpts = {\n toAddress: '18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7',\n amount: helpers.toSatoshi(0.1),\n };\n async.eachSeries(_.range(2), function(i, next) {\n server.createTx(txOpts, function(err, tx) {\n next();\n });\n }, done);\n });\n });\n });\n\n it('should delete a wallet', function(done) {\n server.removeWallet({}, function(err) {\n should.not.exist(err);\n server.getWallet({}, function(err, w) {\n should.exist(err);\n err.code.should.equal('WALLET_NOT_FOUND');\n should.not.exist(w);\n async.parallel([\n\n function(next) {\n server.storage.fetchAddresses(wallet.id, function(err, items) {\n items.length.should.equal(0);\n next();\n });\n },\n function(next) {\n server.storage.fetchTxs(wallet.id, {}, function(err, items) {\n items.length.should.equal(0);\n next();\n });\n },\n function(next) {\n server.storage.fetchNotifications(wallet.id, null, 0, function(err, items) {\n items.length.should.equal(0);\n next();\n });\n },\n ], function(err) {\n should.not.exist(err);\n done();\n });\n });\n });\n });\n\n // creates 2 wallet, and deletes only 1.\n it('should delete a wallet, and only that wallet', function(done) {\n var server2, wallet2;\n async.series([\n\n function(next) {\n helpers.createAndJoinWallet(1, 1, {\n offset: 1\n }, function(s, w) {\n server2 = s;\n wallet2 = w;\n\n helpers.stubUtxos(server2, wallet2, _.range(1, 3), function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 0.1, TestData.copayers[1].privKey_1H_0, {\n message: 'some message'\n });\n async.eachSeries(_.range(2), function(i, next) {\n server2.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n next(err);\n });\n }, next);\n });\n });\n },\n function(next) {\n server.removeWallet({}, next);\n },\n function(next) {\n server.getWallet({}, function(err, wallet) {\n should.exist(err);\n err.code.should.equal('WALLET_NOT_FOUND');\n next();\n });\n },\n function(next) {\n server2.getWallet({}, function(err, wallet) {\n should.not.exist(err);\n should.exist(wallet);\n wallet.id.should.equal(wallet2.id);\n next();\n });\n },\n function(next) {\n server2.getMainAddresses({}, function(err, addresses) {\n should.not.exist(err);\n should.exist(addresses);\n addresses.length.should.above(0);\n next();\n });\n },\n function(next) {\n server2.getTxs({}, function(err, txs) {\n should.not.exist(err);\n should.exist(txs);\n txs.length.should.equal(2);\n next();\n });\n },\n function(next) {\n server2.getNotifications({}, function(err, notifications) {\n should.not.exist(err);\n should.exist(notifications);\n notifications.length.should.above(0);\n next();\n });\n },\n ], function(err) {\n should.not.exist(err);\n done();\n });\n });\n });\n\n describe('#removePendingTx', function() {\n var server, wallet, txp;\n beforeEach(function(done) {\n helpers.createAndJoinWallet(2, 3, function(s, w) {\n server = s;\n wallet = w;\n helpers.stubUtxos(server, wallet, [100, 200], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 80, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n server.createTx(txOpts, function(err, tx) {\n server.getPendingTxs({}, function(err, txs) {\n txp = txs[0];\n done();\n });\n });\n });\n });\n });\n\n\n it('should allow creator to remove an unsigned TX', function(done) {\n server.removePendingTx({\n txProposalId: txp.id\n }, function(err) {\n should.not.exist(err);\n server.getPendingTxs({}, function(err, txs) {\n txs.length.should.equal(0);\n done();\n });\n });\n });\n\n it('should allow creator to remove a signed TX by himself', function(done) {\n var signatures = helpers.clientSign(txp, TestData.copayers[0].xPrivKey);\n server.signTx({\n txProposalId: txp.id,\n signatures: signatures,\n }, function(err) {\n should.not.exist(err);\n server.removePendingTx({\n txProposalId: txp.id\n }, function(err) {\n should.not.exist(err);\n server.getPendingTxs({}, function(err, txs) {\n txs.length.should.equal(0);\n done();\n });\n });\n });\n });\n\n it('should fail to remove non-pending TX', function(done) {\n async.waterfall([\n\n function(next) {\n var signatures = helpers.clientSign(txp, TestData.copayers[0].xPrivKey);\n server.signTx({\n txProposalId: txp.id,\n signatures: signatures,\n }, function(err) {\n should.not.exist(err);\n next();\n });\n },\n function(next) {\n helpers.getAuthServer(wallet.copayers[1].id, function(server) {\n server.rejectTx({\n txProposalId: txp.id,\n }, function(err) {\n should.not.exist(err);\n next();\n });\n });\n },\n function(next) {\n helpers.getAuthServer(wallet.copayers[2].id, function(server) {\n server.rejectTx({\n txProposalId: txp.id,\n }, function(err) {\n should.not.exist(err);\n next();\n });\n });\n },\n function(next) {\n server.getPendingTxs({}, function(err, txs) {\n should.not.exist(err);\n txs.should.be.empty;\n next();\n });\n },\n function(next) {\n server.removePendingTx({\n txProposalId: txp.id\n }, function(err) {\n should.exist(err);\n err.code.should.equal('TX_NOT_PENDING');\n done();\n });\n },\n ]);\n });\n\n it('should not allow non-creator copayer to remove an unsigned TX ', function(done) {\n helpers.getAuthServer(wallet.copayers[1].id, function(server2) {\n server2.removePendingTx({\n txProposalId: txp.id\n }, function(err) {\n should.exist(err);\n err.code.should.contain('TX_CANNOT_REMOVE');\n server2.getPendingTxs({}, function(err, txs) {\n txs.length.should.equal(1);\n done();\n });\n });\n });\n });\n\n it('should not allow creator copayer to remove a TX signed by other copayer, in less than 24hrs', function(done) {\n helpers.getAuthServer(wallet.copayers[1].id, function(server2) {\n var signatures = helpers.clientSign(txp, TestData.copayers[1].xPrivKey);\n server2.signTx({\n txProposalId: txp.id,\n signatures: signatures,\n }, function(err) {\n should.not.exist(err);\n server.removePendingTx({\n txProposalId: txp.id\n }, function(err) {\n err.code.should.equal('TX_CANNOT_REMOVE');\n err.message.should.contain('Cannot remove');\n done();\n });\n });\n });\n });\n\n it('should allow creator copayer to remove a TX rejected by other copayer, in less than 24hrs', function(done) {\n helpers.getAuthServer(wallet.copayers[1].id, function(server2) {\n var signatures = helpers.clientSign(txp, TestData.copayers[1].xPrivKey);\n server2.rejectTx({\n txProposalId: txp.id,\n signatures: signatures,\n }, function(err) {\n should.not.exist(err);\n server.removePendingTx({\n txProposalId: txp.id\n }, function(err) {\n should.not.exist(err);\n done();\n });\n });\n });\n });\n\n\n\n it('should allow creator copayer to remove a TX signed by other copayer, after 24hrs', function(done) {\n helpers.getAuthServer(wallet.copayers[1].id, function(server2) {\n var signatures = helpers.clientSign(txp, TestData.copayers[1].xPrivKey);\n server2.signTx({\n txProposalId: txp.id,\n signatures: signatures,\n }, function(err) {\n should.not.exist(err);\n\n server.getPendingTxs({}, function(err, txs) {\n should.not.exist(err);\n txs[0].deleteLockTime.should.be.above(WalletService.DELETE_LOCKTIME - 10);\n\n var clock = sinon.useFakeTimers(Date.now() + 1 + 24 * 3600 * 1000, 'Date');\n server.removePendingTx({\n txProposalId: txp.id\n }, function(err) {\n should.not.exist(err);\n clock.restore();\n done();\n });\n });\n });\n });\n });\n\n\n it('should allow other copayer to remove a TX signed, after 24hrs', function(done) {\n helpers.getAuthServer(wallet.copayers[1].id, function(server2) {\n var signatures = helpers.clientSign(txp, TestData.copayers[1].xPrivKey);\n server2.signTx({\n txProposalId: txp.id,\n signatures: signatures,\n }, function(err) {\n should.not.exist(err);\n\n var clock = sinon.useFakeTimers(Date.now() + 2000 + WalletService.DELETE_LOCKTIME * 1000, 'Date');\n server2.removePendingTx({\n txProposalId: txp.id\n }, function(err) {\n should.not.exist(err);\n clock.restore();\n done();\n });\n });\n });\n });\n });\n\n describe('#getTxHistory', function() {\n var server, wallet, mainAddresses, changeAddresses;\n beforeEach(function(done) {\n helpers.createAndJoinWallet(1, 1, function(s, w) {\n server = s;\n wallet = w;\n helpers.createAddresses(server, wallet, 1, 1, function(main, change) {\n mainAddresses = main;\n changeAddresses = change;\n done();\n });\n });\n });\n\n it('should get tx history from insight', function(done) {\n helpers.stubHistory(TestData.history);\n server.getTxHistory({}, function(err, txs) {\n should.not.exist(err);\n should.exist(txs);\n txs.length.should.equal(2);\n done();\n });\n });\n it('should get tx history for incoming txs', function(done) {\n server._normalizeTxHistory = sinon.stub().returnsArg(0);\n var txs = [{\n txid: '1',\n confirmations: 1,\n fees: 100,\n time: 20,\n inputs: [{\n address: 'external',\n amount: 500,\n }],\n outputs: [{\n address: mainAddresses[0].address,\n amount: 200,\n }],\n }];\n helpers.stubHistory(txs);\n server.getTxHistory({}, function(err, txs) {\n should.not.exist(err);\n should.exist(txs);\n txs.length.should.equal(1);\n var tx = txs[0];\n tx.action.should.equal('received');\n tx.amount.should.equal(200);\n tx.fees.should.equal(100);\n tx.time.should.equal(20);\n done();\n });\n });\n it('should get tx history for outgoing txs', function(done) {\n server._normalizeTxHistory = sinon.stub().returnsArg(0);\n var txs = [{\n txid: '1',\n confirmations: 1,\n fees: 100,\n time: 1,\n inputs: [{\n address: mainAddresses[0].address,\n amount: 500,\n }],\n outputs: [{\n address: 'external',\n amount: 400,\n }],\n }];\n helpers.stubHistory(txs);\n server.getTxHistory({}, function(err, txs) {\n should.not.exist(err);\n should.exist(txs);\n txs.length.should.equal(1);\n var tx = txs[0];\n tx.action.should.equal('sent');\n tx.amount.should.equal(400);\n tx.fees.should.equal(100);\n tx.time.should.equal(1);\n done();\n });\n });\n it('should get tx history for outgoing txs + change', function(done) {\n server._normalizeTxHistory = sinon.stub().returnsArg(0);\n var txs = [{\n txid: '1',\n confirmations: 1,\n fees: 100,\n time: 1,\n inputs: [{\n address: mainAddresses[0].address,\n amount: 500,\n }],\n outputs: [{\n address: 'external',\n amount: 300,\n }, {\n address: changeAddresses[0].address,\n amount: 100,\n }],\n }];\n helpers.stubHistory(txs);\n server.getTxHistory({}, function(err, txs) {\n should.not.exist(err);\n should.exist(txs);\n txs.length.should.equal(1);\n var tx = txs[0];\n tx.action.should.equal('sent');\n tx.amount.should.equal(300);\n tx.fees.should.equal(100);\n tx.outputs[0].address.should.equal('external');\n tx.outputs[0].amount.should.equal(300);\n done();\n });\n });\n it('should get tx history with accepted proposal', function(done) {\n server._normalizeTxHistory = sinon.stub().returnsArg(0);\n var external = '18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7';\n\n helpers.stubUtxos(server, wallet, [100, 200], function(utxos) {\n var outputs = [{\n toAddress: external,\n amount: 50,\n message: undefined // no message\n }, {\n toAddress: external,\n amount: 30,\n message: 'message #2'\n }];\n var txOpts = helpers.createProposalOpts(Model.TxProposal.Types.MULTIPLEOUTPUTS, outputs, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n should.exist(tx);\n\n var signatures = helpers.clientSign(tx, TestData.copayers[0].xPrivKey);\n server.signTx({\n txProposalId: tx.id,\n signatures: signatures,\n }, function(err, tx) {\n should.not.exist(err);\n\n helpers.stubBroadcast();\n server.broadcastTx({\n txProposalId: tx.id\n }, function(err, txp) {\n should.not.exist(err);\n var txs = [{\n txid: txp.txid,\n confirmations: 1,\n fees: 5460,\n time: 1,\n inputs: [{\n address: tx.inputs[0].address,\n amount: utxos[0].satoshis,\n }],\n outputs: [{\n address: changeAddresses[0].address,\n amount: helpers.toSatoshi(20) - 5460,\n }, {\n address: external,\n amount: helpers.toSatoshi(50)\n }, {\n address: external,\n amount: helpers.toSatoshi(30)\n }]\n }];\n helpers.stubHistory(txs);\n\n server.getTxHistory({}, function(err, txs) {\n should.not.exist(err);\n should.exist(txs);\n txs.length.should.equal(1);\n var tx = txs[0];\n tx.action.should.equal('sent');\n tx.amount.should.equal(helpers.toSatoshi(80));\n tx.message.should.equal('some message');\n tx.addressTo.should.equal(external);\n tx.actions.length.should.equal(1);\n tx.actions[0].type.should.equal('accept');\n tx.actions[0].copayerName.should.equal('copayer 1');\n tx.proposalType.should.equal(Model.TxProposal.Types.MULTIPLEOUTPUTS);\n tx.outputs[0].address.should.equal(external);\n tx.outputs[0].amount.should.equal(helpers.toSatoshi(50));\n should.not.exist(tx.outputs[0].message);\n should.not.exist(tx.outputs[0]['isMine']);\n should.not.exist(tx.outputs[0]['isChange']);\n tx.outputs[1].address.should.equal(external);\n tx.outputs[1].amount.should.equal(helpers.toSatoshi(30));\n should.exist(tx.outputs[1].message);\n tx.outputs[1].message.should.equal('message #2');\n done();\n });\n });\n });\n });\n });\n });\n it('should get various paginated tx history', function(done) {\n var testCases = [{\n opts: {},\n expected: [50, 40, 30, 20, 10],\n }, {\n opts: {\n skip: 1,\n limit: 3,\n },\n expected: [40, 30, 20],\n }, {\n opts: {\n skip: 1,\n limit: 2,\n },\n expected: [40, 30],\n }, {\n opts: {\n skip: 2,\n },\n expected: [30, 20, 10],\n }, {\n opts: {\n limit: 4,\n },\n expected: [50, 40, 30, 20],\n }, {\n opts: {\n skip: 0,\n limit: 3,\n },\n expected: [50, 40, 30],\n }, {\n opts: {\n skip: 0,\n limit: 0,\n },\n expected: [],\n }, {\n opts: {\n skip: 4,\n limit: 20,\n },\n expected: [10],\n }, {\n opts: {\n skip: 20,\n limit: 1,\n },\n expected: [],\n }];\n\n server._normalizeTxHistory = sinon.stub().returnsArg(0);\n var timestamps = [50, 40, 30, 20, 10];\n var txs = _.map(timestamps, function(ts, idx) {\n return {\n txid: (idx + 1).toString(),\n confirmations: ts / 10,\n fees: 100,\n time: ts,\n inputs: [{\n address: 'external',\n amount: 500,\n }],\n outputs: [{\n address: mainAddresses[0].address,\n amount: 200,\n }],\n };\n });\n helpers.stubHistory(txs);\n\n async.each(testCases, function(testCase, next) {\n server.getTxHistory(testCase.opts, function(err, txs) {\n should.not.exist(err);\n should.exist(txs);\n _.pluck(txs, 'time').should.deep.equal(testCase.expected);\n next();\n });\n }, done);\n });\n it('should fail gracefully if unable to reach the blockchain', function(done) {\n blockchainExplorer.getTransactions = sinon.stub().callsArgWith(3, 'dummy error');\n server.getTxHistory({}, function(err, txs) {\n should.exist(err);\n err.toString().should.equal('dummy error');\n done();\n });\n });\n it('should handle invalid tx in history ', function(done) {\n var h = _.clone(TestData.history);\n h.push({\n txid: 'xx'\n })\n helpers.stubHistory(h);\n\n server.getTxHistory({}, function(err, txs) {\n should.not.exist(err);\n should.exist(txs);\n txs.length.should.equal(3);\n txs[2].action.should.equal('invalid');\n done();\n });\n });\n });\n\n describe('#scan', function() {\n var server, wallet;\n var scanConfigOld = WalletService.SCAN_CONFIG;\n\n describe('1-of-1 wallet (BIP44 & P2PKH)', function() {\n beforeEach(function(done) {\n this.timeout(5000);\n WalletService.SCAN_CONFIG.maxGap = 2;\n\n helpers.createAndJoinWallet(1, 1, function(s, w) {\n server = s;\n wallet = w;\n done();\n });\n });\n afterEach(function() {\n WalletService.SCAN_CONFIG = scanConfigOld;\n });\n\n it('should scan main addresses', function(done) {\n helpers.stubAddressActivity(\n ['1L3z9LPd861FWQhf3vDn89Fnc9dkdBo2CG', // m/0/0\n '1GdXraZ1gtoVAvBh49D4hK9xLm6SKgesoE', // m/0/2\n '1FUzgKcyPJsYwDLUEVJYeE2N3KVaoxTjGS', // m/1/0\n ]);\n var expectedPaths = [\n 'm/0/0',\n 'm/0/1',\n 'm/0/2',\n 'm/1/0',\n ];\n server.scan({}, function(err) {\n should.not.exist(err);\n server.getWallet({}, function(err, wallet) {\n should.not.exist(err);\n wallet.scanStatus.should.equal('success');\n server.storage.fetchAddresses(wallet.id, function(err, addresses) {\n should.exist(addresses);\n addresses.length.should.equal(expectedPaths.length);\n var paths = _.pluck(addresses, 'path');\n _.difference(paths, expectedPaths).length.should.equal(0);\n server.createAddress({}, function(err, address) {\n should.not.exist(err);\n address.path.should.equal('m/0/3');\n done();\n });\n });\n });\n });\n });\n\n it('should not go beyond max gap', function(done) {\n helpers.stubAddressActivity(\n ['1L3z9LPd861FWQhf3vDn89Fnc9dkdBo2CG', // m/0/0\n '1GdXraZ1gtoVAvBh49D4hK9xLm6SKgesoE', // m/0/2\n '1DY9exavapgnCUWDnSTJe1BPzXcpgwAQC4', // m/0/5\n '1LD7Cr68LvBPTUeXrr6YXfGrogR7TVj3WQ', // m/1/3\n ]);\n var expectedPaths = [\n 'm/0/0',\n 'm/0/1',\n 'm/0/2',\n ];\n server.scan({}, function(err) {\n should.not.exist(err);\n server.getWallet({}, function(err, wallet) {\n should.not.exist(err);\n wallet.scanStatus.should.equal('success');\n server.storage.fetchAddresses(wallet.id, function(err, addresses) {\n should.exist(addresses);\n addresses.length.should.equal(expectedPaths.length);\n var paths = _.pluck(addresses, 'path');\n _.difference(paths, expectedPaths).length.should.equal(0);\n server.createAddress({}, function(err, address) {\n should.not.exist(err);\n address.path.should.equal('m/0/3');\n // A rescan should see the m/0/5 address initially beyond the gap\n server.scan({}, function(err) {\n server.createAddress({}, function(err, address) {\n should.not.exist(err);\n address.path.should.equal('m/0/6');\n done();\n });\n });\n });\n });\n });\n });\n });\n\n it('should not affect indexes on new wallet', function(done) {\n helpers.stubAddressActivity([]);\n server.scan({}, function(err) {\n should.not.exist(err);\n server.getWallet({}, function(err, wallet) {\n should.not.exist(err);\n wallet.scanStatus.should.equal('success');\n server.storage.fetchAddresses(wallet.id, function(err, addresses) {\n should.not.exist(err);\n addresses.length.should.equal(0);\n server.createAddress({}, function(err, address) {\n should.not.exist(err);\n address.path.should.equal('m/0/0');\n done();\n });\n });\n });\n });\n });\n\n it('should not rewind already generated addresses on error', function(done) {\n server.createAddress({}, function(err, address) {\n should.not.exist(err);\n address.path.should.equal('m/0/0');\n blockchainExplorer.getAddressActivity = sinon.stub().callsArgWith(1, 'dummy error');\n server.scan({}, function(err) {\n should.exist(err);\n err.toString().should.equal('dummy error');\n server.getWallet({}, function(err, wallet) {\n should.not.exist(err);\n wallet.scanStatus.should.equal('error');\n wallet.addressManager.receiveAddressIndex.should.equal(1);\n wallet.addressManager.changeAddressIndex.should.equal(0);\n server.createAddress({}, function(err, address) {\n should.not.exist(err);\n address.path.should.equal('m/0/1');\n done();\n });\n });\n });\n });\n });\n\n it('should restore wallet balance', function(done) {\n async.waterfall([\n\n function(next) {\n helpers.stubUtxos(server, wallet, [1, 2, 3], function(utxos) {\n should.exist(utxos);\n helpers.stubAddressActivity(_.pluck(utxos, 'address'));\n server.getBalance({}, function(err, balance) {\n balance.totalAmount.should.equal(helpers.toSatoshi(6));\n next(null, server, wallet);\n });\n });\n },\n function(server, wallet, next) {\n server.removeWallet({}, function(err) {\n next(err);\n });\n },\n function(next) {\n // NOTE: this works because it creates the exact same wallet!\n helpers.createAndJoinWallet(1, 1, function(server, wallet) {\n server.getBalance({}, function(err, balance) {\n balance.totalAmount.should.equal(0);\n next(null, server, wallet);\n });\n });\n },\n function(server, wallet, next) {\n server.scan({}, function(err) {\n should.not.exist(err);\n server.getBalance(wallet.id, function(err, balance) {\n balance.totalAmount.should.equal(helpers.toSatoshi(6));\n next();\n })\n });\n },\n ], function(err) {\n should.not.exist(err);\n done();\n });\n });\n\n it('should abort scan if there is an error checking address activity', function(done) {\n blockchainExplorer.getAddressActivity = sinon.stub().callsArgWith(1, 'dummy error');\n server.scan({}, function(err) {\n should.exist(err);\n err.toString().should.equal('dummy error');\n server.getWallet({}, function(err, wallet) {\n should.not.exist(err);\n wallet.scanStatus.should.equal('error');\n wallet.addressManager.receiveAddressIndex.should.equal(0);\n wallet.addressManager.changeAddressIndex.should.equal(0);\n server.storage.fetchAddresses(wallet.id, function(err, addresses) {\n should.not.exist(err);\n addresses.should.be.empty;\n done();\n });\n });\n });\n });\n });\n\n describe('shared wallet (BIP45)', function() {\n\n beforeEach(function(done) {\n this.timeout(5000);\n WalletService.SCAN_CONFIG.maxGap = 2;\n\n helpers.createAndJoinWallet(1, 2, {\n supportBIP44AndP2PKH: false\n }, function(s, w) {\n server = s;\n wallet = w;\n done();\n });\n });\n afterEach(function() {\n WalletService.SCAN_CONFIG = scanConfigOld;\n });\n\n it('should scan main addresses', function(done) {\n helpers.stubAddressActivity(\n ['39AA1Y2VvPJhV3RFbc7cKbUax1WgkPwweR', // m/2147483647/0/0\n '3QX2MNSijnhCALBmUVnDo5UGPj3SEGASWx', // m/2147483647/0/2\n '3MzGaz4KKX66w8ShKaR536ZqzVvREBqqYu', // m/2147483647/1/0\n ]);\n var expectedPaths = [\n 'm/2147483647/0/0',\n 'm/2147483647/0/1',\n 'm/2147483647/0/2',\n 'm/2147483647/1/0',\n ];\n server.scan({}, function(err) {\n should.not.exist(err);\n server.getWallet({}, function(err, wallet) {\n should.not.exist(err);\n wallet.scanStatus.should.equal('success');\n server.storage.fetchAddresses(wallet.id, function(err, addresses) {\n should.exist(addresses);\n addresses.length.should.equal(expectedPaths.length);\n var paths = _.pluck(addresses, 'path');\n _.difference(paths, expectedPaths).length.should.equal(0);\n server.createAddress({}, function(err, address) {\n should.not.exist(err);\n address.path.should.equal('m/2147483647/0/3');\n done();\n });\n });\n });\n });\n });\n it('should scan main addresses & copayer addresses', function(done) {\n helpers.stubAddressActivity(\n ['39AA1Y2VvPJhV3RFbc7cKbUax1WgkPwweR', // m/2147483647/0/0\n '3MzGaz4KKX66w8ShKaR536ZqzVvREBqqYu', // m/2147483647/1/0\n '3BYoynejwBH9q4Jhr9m9P5YTnLTu57US6g', // m/0/0/1\n '37Pb8c32hzm16tCZaVHj4Dtjva45L2a3A3', // m/1/1/0\n '32TB2n283YsXdseMqUm9zHSRcfS5JxTWxx', // m/1/0/0\n ]);\n var expectedPaths = [\n 'm/2147483647/0/0',\n 'm/2147483647/1/0',\n 'm/0/0/0',\n 'm/0/0/1',\n 'm/1/0/0',\n 'm/1/1/0',\n ];\n server.scan({\n includeCopayerBranches: true\n }, function(err) {\n should.not.exist(err);\n server.storage.fetchAddresses(wallet.id, function(err, addresses) {\n should.exist(addresses);\n addresses.length.should.equal(expectedPaths.length);\n var paths = _.pluck(addresses, 'path');\n _.difference(paths, expectedPaths).length.should.equal(0);\n done();\n })\n });\n });\n });\n });\n\n describe('#startScan', function() {\n var server, wallet;\n var scanConfigOld = WalletService.SCAN_CONFIG;\n beforeEach(function(done) {\n this.timeout(5000);\n WalletService.SCAN_CONFIG.maxGap = 2;\n\n helpers.createAndJoinWallet(1, 1, {\n supportBIP44AndP2PKH: false\n }, function(s, w) {\n server = s;\n wallet = w;\n done();\n });\n });\n afterEach(function() {\n WalletService.SCAN_CONFIG = scanConfigOld;\n server.messageBroker.removeAllListeners();\n });\n\n it('should start an asynchronous scan', function(done) {\n helpers.stubAddressActivity(\n ['3GvvHimEMk2GBZnPxTF89GHZL6QhZjUZVs', // m/2147483647/0/0\n '37pd1jjTUiGBh8JL2hKLDgsyrhBoiz5vsi', // m/2147483647/0/2\n '3C3tBn8Sr1wHTp2brMgYsj9ncB7R7paYuB', // m/2147483647/1/0\n ]);\n var expectedPaths = [\n 'm/2147483647/0/0',\n 'm/2147483647/0/1',\n 'm/2147483647/0/2',\n 'm/2147483647/1/0',\n ];\n server.messageBroker.onMessage(function(n) {\n if (n.type == 'ScanFinished') {\n server.getWallet({}, function(err, wallet) {\n should.exist(wallet.scanStatus);\n wallet.scanStatus.should.equal('success');\n should.not.exist(n.creatorId);\n server.storage.fetchAddresses(wallet.id, function(err, addresses) {\n should.exist(addresses);\n addresses.length.should.equal(expectedPaths.length);\n var paths = _.pluck(addresses, 'path');\n _.difference(paths, expectedPaths).length.should.equal(0);\n server.createAddress({}, function(err, address) {\n should.not.exist(err);\n address.path.should.equal('m/2147483647/0/3');\n done();\n });\n })\n });\n }\n });\n server.startScan({}, function(err) {\n should.not.exist(err);\n });\n });\n it('should set scan status error when unable to reach blockchain', function(done) {\n blockchainExplorer.getAddressActivity = sinon.stub().yields('dummy error');\n server.messageBroker.onMessage(function(n) {\n if (n.type == 'ScanFinished') {\n should.exist(n.data.error);\n server.getWallet({}, function(err, wallet) {\n should.exist(wallet.scanStatus);\n wallet.scanStatus.should.equal('error');\n done();\n });\n }\n });\n server.startScan({}, function(err) {\n should.not.exist(err);\n });\n });\n it('should start multiple asynchronous scans for different wallets', function(done) {\n helpers.stubAddressActivity(['3K2VWMXheGZ4qG35DyGjA2dLeKfaSr534A']);\n WalletService.SCAN_CONFIG.scanWindow = 1;\n\n var scans = 0;\n server.messageBroker.onMessage(function(n) {\n if (n.type == 'ScanFinished') {\n scans++;\n if (scans == 2) done();\n }\n });\n\n // Create a second wallet\n var server2 = new WalletService();\n var opts = {\n name: 'second wallet',\n m: 1,\n n: 1,\n pubKey: TestData.keyPair.pub,\n };\n server2.createWallet(opts, function(err, walletId) {\n should.not.exist(err);\n var copayerOpts = helpers.getSignedCopayerOpts({\n walletId: walletId,\n name: 'copayer 1',\n xPubKey: TestData.copayers[3].xPubKey_45H,\n requestPubKey: TestData.copayers[3].pubKey_1H_0,\n });\n server.joinWallet(copayerOpts, function(err, result) {\n should.not.exist(err);\n helpers.getAuthServer(result.copayerId, function(server2) {\n server.startScan({}, function(err) {\n should.not.exist(err);\n scans.should.equal(0);\n });\n server2.startScan({}, function(err) {\n should.not.exist(err);\n scans.should.equal(0);\n });\n scans.should.equal(0);\n });\n });\n });\n });\n });\n\n describe('Legacy', function() {\n describe('Fees', function() {\n var server, wallet;\n beforeEach(function(done) {\n helpers.createAndJoinWallet(2, 3, function(s, w) {\n server = s;\n wallet = w;\n done();\n });\n });\n\n it('should create a tx from legacy (bwc-0.0.*) client', function(done) {\n helpers.stubUtxos(server, wallet, [100, 200], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 80, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n\n var verifyStub = sinon.stub(WalletService.prototype, '_verifySignature');\n verifyStub.returns(true);\n WalletService.getInstanceWithAuth({\n copayerId: wallet.copayers[0].id,\n message: 'dummy',\n signature: 'dummy',\n clientVersion: 'bwc-0.0.40',\n }, function(err, server) {\n should.not.exist(err);\n should.exist(server);\n verifyStub.restore();\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n should.exist(tx);\n tx.amount.should.equal(helpers.toSatoshi(80));\n tx.fee.should.equal(WalletUtils.DEFAULT_FEE_PER_KB);\n done();\n });\n });\n });\n });\n\n it('should not return error when fetching new txps from legacy (bwc-0.0.*) client', function(done) {\n helpers.stubUtxos(server, wallet, [100, 200], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 80, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n should.exist(tx);\n\n var verifyStub = sinon.stub(WalletService.prototype, '_verifySignature');\n verifyStub.returns(true);\n WalletService.getInstanceWithAuth({\n copayerId: wallet.copayers[0].id,\n message: 'dummy',\n signature: 'dummy',\n clientVersion: 'bwc-0.0.40',\n }, function(err, server) {\n verifyStub.restore();\n should.not.exist(err);\n should.exist(server);\n server.getPendingTxs({}, function(err, txps) {\n should.not.exist(err);\n should.exist(txps);\n done();\n });\n });\n });\n });\n });\n it('should fail to sign tx from legacy (bwc-0.0.*) client', function(done) {\n helpers.stubUtxos(server, wallet, [100, 200], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 80, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n should.exist(tx);\n _.startsWith(tx.version, '1.').should.be.false;\n\n var verifyStub = sinon.stub(WalletService.prototype, '_verifySignature');\n verifyStub.returns(true);\n WalletService.getInstanceWithAuth({\n copayerId: wallet.copayers[0].id,\n message: 'dummy',\n signature: 'dummy',\n clientVersion: 'bwc-0.0.40',\n }, function(err, server) {\n var signatures = helpers.clientSign(tx, TestData.copayers[0].xPrivKey);\n server.signTx({\n txProposalId: tx.id,\n signatures: signatures,\n }, function(err) {\n verifyStub.restore();\n should.exist(err);\n err.code.should.equal('UPGRADE_NEEDED');\n err.message.should.contain('sign this spend proposal');\n done();\n });\n });\n });\n });\n });\n it('should create a tx from legacy (bwc-0.0.*) client and sign it from newer client', function(done) {\n helpers.stubUtxos(server, wallet, [100, 200], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 80, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n\n var verifyStub = sinon.stub(WalletService.prototype, '_verifySignature');\n verifyStub.returns(true);\n WalletService.getInstanceWithAuth({\n copayerId: wallet.copayers[0].id,\n message: 'dummy',\n signature: 'dummy',\n clientVersion: 'bwc-0.0.40',\n }, function(err, server) {\n should.not.exist(err);\n should.exist(server);\n verifyStub.restore();\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n should.exist(tx);\n tx.amount.should.equal(helpers.toSatoshi(80));\n tx.fee.should.equal(WalletUtils.DEFAULT_FEE_PER_KB);\n helpers.getAuthServer(wallet.copayers[0].id, function(server) {\n var signatures = helpers.clientSign(tx, TestData.copayers[0].xPrivKey);\n server.signTx({\n txProposalId: tx.id,\n signatures: signatures,\n }, function(err) {\n should.not.exist(err);\n done();\n });\n });\n });\n });\n });\n });\n it('should fail with insufficient fee when invoked from legacy (bwc-0.0.*) client', function(done) {\n helpers.stubUtxos(server, wallet, 1, function() {\n var verifyStub = sinon.stub(WalletService.prototype, '_verifySignature');\n verifyStub.returns(true);\n WalletService.getInstanceWithAuth({\n copayerId: wallet.copayers[0].id,\n message: 'dummy',\n signature: 'dummy',\n clientVersion: 'bwc-0.0.40',\n }, function(err, server) {\n should.not.exist(err);\n should.exist(server);\n verifyStub.restore();\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 0.99995, TestData.copayers[0].privKey_1H_0);\n\n server.createTx(txOpts, function(err, tx) {\n should.exist(err);\n err.code.should.equal('INSUFFICIENT_FUNDS_FOR_FEE');\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 0.99995, TestData.copayers[0].privKey_1H_0, {\n feePerKb: 5000\n });\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n tx.fee.should.equal(5000);\n\n // Sign it to make sure Bitcore doesn't complain about the fees\n var signatures = helpers.clientSign(tx, TestData.copayers[0].xPrivKey);\n server.signTx({\n txProposalId: tx.id,\n signatures: signatures,\n }, function(err) {\n should.not.exist(err);\n done();\n });\n });\n });\n });\n });\n });\n });\n });\n});\n"},"new_file":{"kind":"string","value":"test/integration/server.js"},"old_contents":{"kind":"string","value":"'use strict';\n\nvar _ = require('lodash');\nvar async = require('async');\nvar inspect = require('util').inspect;\n\nvar chai = require('chai');\nvar sinon = require('sinon');\nvar should = chai.should();\nvar log = require('npmlog');\nlog.debug = log.verbose;\n\nvar fs = require('fs');\nvar tingodb = require('tingodb')({\n memStore: true\n});\n\nvar Utils = require('../../lib/utils');\nvar WalletUtils = require('bitcore-wallet-utils');\nvar Bitcore = WalletUtils.Bitcore;\nvar Storage = require('../../lib/storage');\n\nvar Model = require('../../lib/model');\n\nvar WalletService = require('../../lib/server');\nvar EmailService = require('../../lib/emailservice');\n\nvar TestData = require('../testdata');\nvar CLIENT_VERSION = 'bwc-0.1.1';\n\nvar helpers = {};\nhelpers.getAuthServer = function(copayerId, cb) {\n var verifyStub = sinon.stub(WalletService.prototype, '_verifySignature');\n verifyStub.returns(true);\n WalletService.getInstanceWithAuth({\n copayerId: copayerId,\n message: 'dummy',\n signature: 'dummy',\n clientVersion: 'bwc-0.1.0',\n }, function(err, server) {\n verifyStub.restore();\n if (err || !server) throw new Error('Could not login as copayerId ' + copayerId);\n return cb(server);\n });\n};\n\nhelpers._generateCopayersTestData = function(n) {\n console.log('var copayers = [');\n _.each(_.range(n), function(c) {\n var xpriv = new Bitcore.HDPrivateKey();\n var xpub = Bitcore.HDPublicKey(xpriv);\n\n var xpriv_45H = xpriv.derive(45, true);\n var xpub_45H = Bitcore.HDPublicKey(xpriv_45H);\n var id45 = WalletUtils.xPubToCopayerId(xpub_45H.toString());\n\n var xpriv_44H_0H_0H = xpriv.derive(44, true).derive(0, true).derive(0, true);\n var xpub_44H_0H_0H = Bitcore.HDPublicKey(xpriv_44H_0H_0H);\n var id44 = WalletUtils.xPubToCopayerId(xpub_44H_0H_0H.toString());\n\n var xpriv_1H = xpriv.derive(1, true);\n var xpub_1H = Bitcore.HDPublicKey(xpriv_1H);\n var priv = xpriv_1H.derive(0).privateKey;\n var pub = xpub_1H.derive(0).publicKey;\n\n console.log('{id44: ', \"'\" + id44 + \"',\");\n console.log('id45: ', \"'\" + id45 + \"',\");\n console.log('xPrivKey: ', \"'\" + xpriv.toString() + \"',\");\n console.log('xPubKey: ', \"'\" + xpub.toString() + \"',\");\n console.log('xPrivKey_45H: ', \"'\" + xpriv_45H.toString() + \"',\");\n console.log('xPubKey_45H: ', \"'\" + xpub_45H.toString() + \"',\");\n console.log('xPrivKey_44H_0H_0H: ', \"'\" + xpriv_44H_0H_0H.toString() + \"',\");\n console.log('xPubKey_44H_0H_0H: ', \"'\" + xpub_44H_0H_0H.toString() + \"',\");\n console.log('xPrivKey_1H: ', \"'\" + xpriv_1H.toString() + \"',\");\n console.log('xPubKey_1H: ', \"'\" + xpub_1H.toString() + \"',\");\n console.log('privKey_1H_0: ', \"'\" + priv.toString() + \"',\");\n console.log('pubKey_1H_0: ', \"'\" + pub.toString() + \"'},\");\n });\n console.log('];');\n};\n\nhelpers.getSignedCopayerOpts = function(opts) {\n var hash = WalletUtils.getCopayerHash(opts.name, opts.xPubKey, opts.requestPubKey);\n opts.copayerSignature = WalletUtils.signMessage(hash, TestData.keyPair.priv);\n return opts;\n};\n\nhelpers.createAndJoinWallet = function(m, n, opts, cb) {\n if (_.isFunction(opts)) {\n cb = opts;\n opts = {};\n }\n opts = opts || {};\n\n var server = new WalletService();\n var copayerIds = [];\n var offset = opts.offset || 0;\n\n var walletOpts = {\n name: 'a wallet',\n m: m,\n n: n,\n pubKey: TestData.keyPair.pub,\n };\n if (_.isBoolean(opts.supportBIP44AndP2PKH))\n walletOpts.supportBIP44AndP2PKH = opts.supportBIP44AndP2PKH;\n\n server.createWallet(walletOpts, function(err, walletId) {\n if (err) return cb(err);\n\n async.each(_.range(n), function(i, cb) {\n var copayerData = TestData.copayers[i + offset];\n var copayerOpts = helpers.getSignedCopayerOpts({\n walletId: walletId,\n name: 'copayer ' + (i + 1),\n xPubKey: (_.isBoolean(opts.supportBIP44AndP2PKH) && !opts.supportBIP44AndP2PKH) ? copayerData.xPubKey_45H : copayerData.xPubKey_44H_0H_0H,\n requestPubKey: copayerData.pubKey_1H_0,\n customData: 'custom data ' + (i + 1),\n });\n if (_.isBoolean(opts.supportBIP44AndP2PKH))\n copayerOpts.supportBIP44AndP2PKH = opts.supportBIP44AndP2PKH;\n\n server.joinWallet(copayerOpts, function(err, result) {\n should.not.exist(err);\n copayerIds.push(result.copayerId);\n return cb(err);\n });\n }, function(err) {\n if (err) return new Error('Could not generate wallet');\n helpers.getAuthServer(copayerIds[0], function(s) {\n s.getWallet({}, function(err, w) {\n cb(s, w);\n });\n });\n });\n });\n};\n\n\nhelpers.randomTXID = function() {\n return Bitcore.crypto.Hash.sha256(new Buffer(Math.random() * 100000)).toString('hex');;\n};\n\n\nhelpers.toSatoshi = function(btc) {\n if (_.isArray(btc)) {\n return _.map(btc, helpers.toSatoshi);\n } else {\n return Utils.strip(btc * 1e8);\n }\n};\n\nhelpers.stubUtxos = function(server, wallet, amounts, cb) {\n async.mapSeries(_.range(0, amounts.length > 2 ? 2 : 1), function(i, next) {\n server.createAddress({}, next);\n }, function(err, addresses) {\n should.not.exist(err);\n addresses.should.not.be.empty;\n var utxos = _.map([].concat(amounts), function(amount, i) {\n var address = addresses[i % addresses.length];\n var confirmations;\n if (_.isString(amount) && _.startsWith(amount, 'u')) {\n amount = parseFloat(amount.substring(1));\n confirmations = 0;\n } else {\n confirmations = Math.floor(Math.random() * 100 + 1);\n }\n\n var scriptPubKey;\n switch (wallet.addressType) {\n case WalletUtils.SCRIPT_TYPES.P2SH:\n scriptPubKey = Bitcore.Script.buildMultisigOut(address.publicKeys, wallet.m).toScriptHashOut();\n break;\n case WalletUtils.SCRIPT_TYPES.P2PKH:\n scriptPubKey = Bitcore.Script.buildPublicKeyHashOut(address.address);\n break;\n }\n should.exist(scriptPubKey);\n\n return {\n txid: helpers.randomTXID(),\n vout: Math.floor(Math.random() * 10 + 1),\n satoshis: helpers.toSatoshi(amount).toString(),\n scriptPubKey: scriptPubKey.toBuffer().toString('hex'),\n address: address.address,\n confirmations: confirmations,\n };\n });\n blockchainExplorer.getUnspentUtxos = function(addresses, cb) {\n var selected = _.filter(utxos, function(utxo) {\n return _.contains(addresses, utxo.address);\n });\n return cb(null, selected);\n };\n\n return cb(utxos);\n });\n};\n\nhelpers.stubBroadcast = function(thirdPartyBroadcast) {\n blockchainExplorer.broadcast = sinon.stub().callsArgWith(1, null, '112233');\n blockchainExplorer.getTransaction = sinon.stub().callsArgWith(1, null, null);\n};\n\nhelpers.stubHistory = function(txs) {\n blockchainExplorer.getTransactions = function(addresses, from, to, cb) {\n var MAX_BATCH_SIZE = 100;\n var nbTxs = txs.length;\n\n if (_.isUndefined(from) && _.isUndefined(to)) {\n from = 0;\n to = MAX_BATCH_SIZE;\n }\n if (!_.isUndefined(from) && _.isUndefined(to))\n to = from + MAX_BATCH_SIZE;\n\n if (!_.isUndefined(from) && !_.isUndefined(to) && to - from > MAX_BATCH_SIZE)\n to = from + MAX_BATCH_SIZE;\n\n if (from < 0) from = 0;\n if (to < 0) to = 0;\n if (from > nbTxs) from = nbTxs;\n if (to > nbTxs) to = nbTxs;\n\n var page = txs.slice(from, to);\n return cb(null, page);\n };\n};\n\nhelpers.stubFeeLevels = function(levels) {\n blockchainExplorer.estimateFee = function(nbBlocks, cb) {\n var result = _.zipObject(_.map(_.pick(levels, nbBlocks), function(fee, n) {\n return [+n, fee > 0 ? fee / 1e8 : fee];\n }));\n return cb(null, result);\n };\n};\n\nhelpers.stubAddressActivity = function(activeAddresses) {\n blockchainExplorer.getAddressActivity = function(address, cb) {\n return cb(null, _.contains(activeAddresses, address));\n };\n};\n\nhelpers.clientSign = WalletUtils.signTxp;\n\nhelpers.createProposalOptsLegacy = function(toAddress, amount, message, signingKey, feePerKb) {\n var opts = {\n toAddress: toAddress,\n amount: helpers.toSatoshi(amount),\n message: message,\n proposalSignature: null,\n };\n if (feePerKb) opts.feePerKb = feePerKb;\n\n var hash = WalletUtils.getProposalHash(toAddress, opts.amount, message);\n\n try {\n opts.proposalSignature = WalletUtils.signMessage(hash, signingKey);\n } catch (ex) {}\n\n return opts;\n};\n\nhelpers.createSimpleProposalOpts = function(toAddress, amount, signingKey, opts) {\n var outputs = [{\n toAddress: toAddress,\n amount: amount,\n }];\n return helpers.createProposalOpts(Model.TxProposal.Types.SIMPLE, outputs, signingKey, opts);\n};\n\nhelpers.createProposalOpts = function(type, outputs, signingKey, moreOpts) {\n _.each(outputs, function(output) {\n output.amount = helpers.toSatoshi(output.amount);\n });\n\n var opts = {\n type: type,\n proposalSignature: null\n };\n\n if (moreOpts) {\n moreOpts = _.chain(moreOpts)\n .pick(['feePerKb', 'customData', 'message'])\n .value();\n opts = _.assign(opts, moreOpts);\n }\n\n opts = _.defaults(opts, {\n message: null\n });\n\n var hash;\n if (type == Model.TxProposal.Types.SIMPLE) {\n opts.toAddress = outputs[0].toAddress;\n opts.amount = outputs[0].amount;\n hash = WalletUtils.getProposalHash(opts.toAddress, opts.amount,\n opts.message, opts.payProUrl);\n } else if (type == Model.TxProposal.Types.MULTIPLEOUTPUTS) {\n opts.outputs = outputs;\n var header = {\n outputs: outputs,\n message: opts.message,\n payProUrl: opts.payProUrl\n };\n hash = WalletUtils.getProposalHash(header);\n }\n\n try {\n opts.proposalSignature = WalletUtils.signMessage(hash, signingKey);\n } catch (ex) {}\n\n return opts;\n};\n\nhelpers.createAddresses = function(server, wallet, main, change, cb) {\n async.map(_.range(main + change), function(i, next) {\n var address = wallet.createAddress(i >= main);\n server.storage.storeAddressAndWallet(wallet, address, function(err) {\n if (err) return next(err);\n next(null, address);\n });\n }, function(err, addresses) {\n if (err) throw new Error('Could not generate addresses');\n return cb(_.take(addresses, main), _.takeRight(addresses, change));\n });\n};\n\nvar storage, blockchainExplorer;\n\nvar useMongoDb = !!process.env.USE_MONGO_DB;\n\nfunction initStorage(cb) {\n function getDb(cb) {\n if (useMongoDb) {\n var mongodb = require('mongodb');\n mongodb.MongoClient.connect('mongodb://localhost:27017/bws_test', function(err, db) {\n if (err) throw err;\n return cb(db);\n });\n } else {\n var db = new tingodb.Db('./db/test', {});\n return cb(db);\n }\n }\n getDb(function(db) {\n storage = new Storage({\n db: db\n });\n return cb();\n });\n};\n\nfunction resetStorage(cb) {\n if (!storage.db) return cb();\n storage.db.dropDatabase(function(err) {\n return cb();\n });\n};\n\n\ndescribe('Wallet service', function() {\n before(function(done) {\n initStorage(done);\n });\n beforeEach(function(done) {\n resetStorage(function() {\n blockchainExplorer = sinon.stub();\n WalletService.initialize({\n storage: storage,\n blockchainExplorer: blockchainExplorer,\n }, done);\n });\n });\n after(function(done) {\n WalletService.shutDown(done);\n });\n\n describe('Email notifications', function() {\n var server, wallet, mailerStub, emailService;\n\n describe('Shared wallet', function() {\n beforeEach(function(done) {\n helpers.createAndJoinWallet(2, 3, function(s, w) {\n server = s;\n wallet = w;\n\n var i = 0;\n async.eachSeries(w.copayers, function(copayer, next) {\n helpers.getAuthServer(copayer.id, function(server) {\n server.savePreferences({\n email: 'copayer' + (++i) + '@domain.com',\n unit: 'bit',\n }, next);\n });\n }, function(err) {\n should.not.exist(err);\n\n mailerStub = sinon.stub();\n mailerStub.sendMail = sinon.stub();\n mailerStub.sendMail.yields();\n\n emailService = new EmailService();\n emailService.start({\n lockOpts: {},\n messageBroker: server.messageBroker,\n storage: storage,\n mailer: mailerStub,\n emailOpts: {\n from: 'bws@dummy.net',\n subjectPrefix: '[test wallet]',\n publicTxUrlTemplate: {\n livenet: 'https://insight.bitpay.com/tx/{{txid}}',\n testnet: 'https://test-insight.bitpay.com/tx/{{txid}}',\n },\n },\n }, function(err) {\n should.not.exist(err);\n done();\n });\n });\n });\n });\n\n it('should notify copayers a new tx proposal has been created', function(done) {\n var _readTemplateFile_old = emailService._readTemplateFile;\n emailService._readTemplateFile = function(language, filename, cb) {\n if (_.endsWith(filename, '.html')) {\n return cb(null, '{{walletName}}');\n } else {\n _readTemplateFile_old.call(emailService, language, filename, cb);\n }\n };\n helpers.stubUtxos(server, wallet, [1, 1], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 0.8, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n setTimeout(function() {\n var calls = mailerStub.sendMail.getCalls();\n calls.length.should.equal(2);\n var emails = _.map(calls, function(c) {\n return c.args[0];\n });\n _.difference(['copayer2@domain.com', 'copayer3@domain.com'], _.pluck(emails, 'to')).should.be.empty;\n var one = emails[0];\n one.from.should.equal('bws@dummy.net');\n one.subject.should.contain('New payment proposal');\n one.text.should.contain(wallet.name);\n one.text.should.contain(wallet.copayers[0].name);\n should.exist(one.html);\n one.html.indexOf('').should.equal(0);\n one.html.should.contain(wallet.name);\n server.storage.fetchUnsentEmails(function(err, unsent) {\n should.not.exist(err);\n unsent.should.be.empty;\n emailService._readTemplateFile = _readTemplateFile_old;\n done();\n });\n }, 100);\n });\n });\n });\n\n it('should not send email if unable to apply template to notification', function(done) {\n var _applyTemplate_old = emailService._applyTemplate;\n emailService._applyTemplate = function(template, data, cb) {\n _applyTemplate_old.call(emailService, template, undefined, cb);\n };\n helpers.stubUtxos(server, wallet, [1, 1], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 0.8, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n setTimeout(function() {\n var calls = mailerStub.sendMail.getCalls();\n calls.length.should.equal(0);\n server.storage.fetchUnsentEmails(function(err, unsent) {\n should.not.exist(err);\n unsent.should.be.empty;\n emailService._applyTemplate = _applyTemplate_old;\n done();\n });\n }, 100);\n });\n });\n });\n\n it('should notify copayers a new outgoing tx has been created', function(done) {\n var _readTemplateFile_old = emailService._readTemplateFile;\n emailService._readTemplateFile = function(language, filename, cb) {\n if (_.endsWith(filename, '.html')) {\n return cb(null, '{{&urlForTx}}');\n } else {\n _readTemplateFile_old.call(emailService, language, filename, cb);\n }\n };\n helpers.stubUtxos(server, wallet, [1, 1], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 0.8, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n\n var txp;\n async.waterfall([\n\n function(next) {\n server.createTx(txOpts, next);\n },\n function(t, next) {\n txp = t;\n async.eachSeries(_.range(2), function(i, next) {\n var copayer = TestData.copayers[i];\n helpers.getAuthServer(copayer.id44, function(server) {\n var signatures = helpers.clientSign(txp, copayer.xPrivKey);\n server.signTx({\n txProposalId: txp.id,\n signatures: signatures,\n }, function(err, t) {\n txp = t;\n next();\n });\n });\n }, next);\n },\n function(next) {\n helpers.stubBroadcast();\n server.broadcastTx({\n txProposalId: txp.id,\n }, next);\n },\n ], function(err) {\n should.not.exist(err);\n\n setTimeout(function() {\n var calls = mailerStub.sendMail.getCalls();\n var emails = _.map(_.takeRight(calls, 3), function(c) {\n return c.args[0];\n });\n _.difference(['copayer1@domain.com', 'copayer2@domain.com', 'copayer3@domain.com'], _.pluck(emails, 'to')).should.be.empty;\n var one = emails[0];\n one.from.should.equal('bws@dummy.net');\n one.subject.should.contain('Payment sent');\n one.text.should.contain(wallet.name);\n one.text.should.contain('800,000');\n should.exist(one.html);\n one.html.should.contain('https://insight.bitpay.com/tx/' + txp.txid);\n server.storage.fetchUnsentEmails(function(err, unsent) {\n should.not.exist(err);\n unsent.should.be.empty;\n emailService._readTemplateFile = _readTemplateFile_old;\n done();\n });\n }, 100);\n });\n });\n });\n\n it('should notify copayers a tx has been finally rejected', function(done) {\n helpers.stubUtxos(server, wallet, 1, function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 0.8, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n\n var txpId;\n async.waterfall([\n\n function(next) {\n server.createTx(txOpts, next);\n },\n function(txp, next) {\n txpId = txp.id;\n async.eachSeries(_.range(1, 3), function(i, next) {\n var copayer = TestData.copayers[i];\n helpers.getAuthServer(copayer.id44, function(server) {\n server.rejectTx({\n txProposalId: txp.id,\n }, next);\n });\n }, next);\n },\n ], function(err) {\n should.not.exist(err);\n\n setTimeout(function() {\n var calls = mailerStub.sendMail.getCalls();\n var emails = _.map(_.takeRight(calls, 2), function(c) {\n return c.args[0];\n });\n _.difference(['copayer1@domain.com', 'copayer2@domain.com'], _.pluck(emails, 'to')).should.be.empty;\n var one = emails[0];\n one.from.should.equal('bws@dummy.net');\n one.subject.should.contain('Payment proposal rejected');\n one.text.should.contain(wallet.name);\n one.text.should.contain('copayer 2, copayer 3');\n one.text.should.not.contain('copayer 1');\n server.storage.fetchUnsentEmails(function(err, unsent) {\n should.not.exist(err);\n unsent.should.be.empty;\n done();\n });\n }, 100);\n });\n });\n });\n\n it('should notify copayers of incoming txs', function(done) {\n server.createAddress({}, function(err, address) {\n should.not.exist(err);\n\n // Simulate incoming tx notification\n server._notify('NewIncomingTx', {\n txid: '999',\n address: address,\n amount: 12300000,\n }, function(err) {\n setTimeout(function() {\n var calls = mailerStub.sendMail.getCalls();\n calls.length.should.equal(3);\n var emails = _.map(calls, function(c) {\n return c.args[0];\n });\n _.difference(['copayer1@domain.com', 'copayer2@domain.com', 'copayer3@domain.com'], _.pluck(emails, 'to')).should.be.empty;\n var one = emails[0];\n one.from.should.equal('bws@dummy.net');\n one.subject.should.contain('New payment received');\n one.text.should.contain(wallet.name);\n one.text.should.contain('123,000');\n server.storage.fetchUnsentEmails(function(err, unsent) {\n should.not.exist(err);\n unsent.should.be.empty;\n done();\n });\n }, 100);\n });\n });\n });\n\n it('should notify each email address only once', function(done) {\n // Set same email address for copayer1 and copayer2\n server.savePreferences({\n email: 'copayer2@domain.com',\n }, function(err) {\n server.createAddress({}, function(err, address) {\n should.not.exist(err);\n\n // Simulate incoming tx notification\n server._notify('NewIncomingTx', {\n txid: '999',\n address: address,\n amount: 12300000,\n }, function(err) {\n setTimeout(function() {\n var calls = mailerStub.sendMail.getCalls();\n calls.length.should.equal(2);\n var emails = _.map(calls, function(c) {\n return c.args[0];\n });\n _.difference(['copayer2@domain.com', 'copayer3@domain.com'], _.pluck(emails, 'to')).should.be.empty;\n var one = emails[0];\n one.from.should.equal('bws@dummy.net');\n one.subject.should.contain('New payment received');\n one.text.should.contain(wallet.name);\n one.text.should.contain('123,000');\n server.storage.fetchUnsentEmails(function(err, unsent) {\n should.not.exist(err);\n unsent.should.be.empty;\n done();\n });\n }, 100);\n });\n });\n });\n });\n\n it('should build each email using preferences of the copayers', function(done) {\n // Set same email address for copayer1 and copayer2\n server.savePreferences({\n email: 'copayer1@domain.com',\n language: 'es',\n unit: 'btc',\n }, function(err) {\n server.createAddress({}, function(err, address) {\n should.not.exist(err);\n\n // Simulate incoming tx notification\n server._notify('NewIncomingTx', {\n txid: '999',\n address: address,\n amount: 12300000,\n }, function(err) {\n setTimeout(function() {\n var calls = mailerStub.sendMail.getCalls();\n calls.length.should.equal(3);\n var emails = _.map(calls, function(c) {\n return c.args[0];\n });\n var spanish = _.find(emails, {\n to: 'copayer1@domain.com'\n });\n spanish.from.should.equal('bws@dummy.net');\n spanish.subject.should.contain('Nuevo pago recibido');\n spanish.text.should.contain(wallet.name);\n spanish.text.should.contain('0.123 BTC');\n var english = _.find(emails, {\n to: 'copayer2@domain.com'\n });\n english.from.should.equal('bws@dummy.net');\n english.subject.should.contain('New payment received');\n english.text.should.contain(wallet.name);\n english.text.should.contain('123,000 bits');\n done();\n }, 100);\n });\n });\n });\n });\n\n it('should support multiple emailservice instances running concurrently', function(done) {\n var emailService2 = new EmailService();\n emailService2.start({\n lock: emailService.lock, // Use same locker service\n messageBroker: server.messageBroker,\n storage: storage,\n mailer: mailerStub,\n emailOpts: {\n from: 'bws2@dummy.net',\n subjectPrefix: '[test wallet 2]',\n },\n }, function(err) {\n helpers.stubUtxos(server, wallet, 1, function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 0.8, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n setTimeout(function() {\n var calls = mailerStub.sendMail.getCalls();\n calls.length.should.equal(2);\n server.storage.fetchUnsentEmails(function(err, unsent) {\n should.not.exist(err);\n unsent.should.be.empty;\n done();\n });\n }, 100);\n });\n });\n });\n });\n });\n\n describe('1-of-N wallet', function() {\n beforeEach(function(done) {\n helpers.createAndJoinWallet(1, 2, function(s, w) {\n server = s;\n wallet = w;\n\n var i = 0;\n async.eachSeries(w.copayers, function(copayer, next) {\n helpers.getAuthServer(copayer.id, function(server) {\n server.savePreferences({\n email: 'copayer' + (++i) + '@domain.com',\n unit: 'bit',\n }, next);\n });\n }, function(err) {\n should.not.exist(err);\n\n mailerStub = sinon.stub();\n mailerStub.sendMail = sinon.stub();\n mailerStub.sendMail.yields();\n\n emailService = new EmailService();\n emailService.start({\n lockOpts: {},\n messageBroker: server.messageBroker,\n storage: storage,\n mailer: mailerStub,\n emailOpts: {\n from: 'bws@dummy.net',\n subjectPrefix: '[test wallet]',\n publicTxUrlTemplate: {\n livenet: 'https://insight.bitpay.com/tx/{{txid}}',\n testnet: 'https://test-insight.bitpay.com/tx/{{txid}}',\n },\n },\n }, function(err) {\n should.not.exist(err);\n done();\n });\n });\n });\n });\n\n it('should NOT notify copayers a new tx proposal has been created', function(done) {\n helpers.stubUtxos(server, wallet, [1, 1], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 0.8, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n setTimeout(function() {\n var calls = mailerStub.sendMail.getCalls();\n calls.length.should.equal(0);\n done();\n }, 100);\n });\n });\n });\n });\n\n });\n\n describe('#getServiceVersion', function() {\n it('should get version from package', function() {\n WalletService.getServiceVersion().should.equal('bws-' + require('../../package').version);\n });\n });\n\n describe('#getInstance', function() {\n it('should get server instance', function() {\n var server = WalletService.getInstance({\n clientVersion: 'bwc-0.0.1',\n });\n server.clientVersion.should.equal('bwc-0.0.1');\n });\n });\n\n describe('#getInstanceWithAuth', function() {\n it('should get server instance for existing copayer', function(done) {\n helpers.createAndJoinWallet(1, 2, function(s, wallet) {\n var xpriv = TestData.copayers[0].xPrivKey;\n var priv = TestData.copayers[0].privKey_1H_0;\n\n var sig = WalletUtils.signMessage('hello world', priv);\n\n WalletService.getInstanceWithAuth({\n copayerId: wallet.copayers[0].id,\n message: 'hello world',\n signature: sig,\n clientVersion: 'bwc-0.0.1',\n }, function(err, server) {\n should.not.exist(err);\n server.walletId.should.equal(wallet.id);\n server.copayerId.should.equal(wallet.copayers[0].id);\n server.clientVersion.should.equal('bwc-0.0.1');\n done();\n });\n });\n });\n\n it('should fail when requesting for non-existent copayer', function(done) {\n var message = 'hello world';\n var opts = {\n copayerId: 'dummy',\n message: message,\n signature: WalletUtils.signMessage(message, TestData.copayers[0].privKey_1H_0),\n };\n WalletService.getInstanceWithAuth(opts, function(err, server) {\n err.code.should.equal('NOT_AUTHORIZED');\n err.message.should.contain('Copayer not found');\n done();\n });\n });\n\n it('should fail when message signature cannot be verified', function(done) {\n helpers.createAndJoinWallet(1, 2, function(s, wallet) {\n WalletService.getInstanceWithAuth({\n copayerId: wallet.copayers[0].id,\n message: 'dummy',\n signature: 'dummy',\n }, function(err, server) {\n err.code.should.equal('NOT_AUTHORIZED');\n err.message.should.contain('Invalid signature');\n done();\n });\n });\n });\n });\n\n describe('#createWallet', function() {\n var server;\n beforeEach(function() {\n server = new WalletService();\n });\n\n it('should create and store wallet', function(done) {\n var opts = {\n name: 'my wallet',\n m: 2,\n n: 3,\n pubKey: TestData.keyPair.pub,\n };\n server.createWallet(opts, function(err, walletId) {\n should.not.exist(err);\n server.storage.fetchWallet(walletId, function(err, wallet) {\n should.not.exist(err);\n wallet.id.should.equal(walletId);\n wallet.name.should.equal('my wallet');\n done();\n });\n });\n });\n\n it('should create wallet with given id', function(done) {\n var opts = {\n name: 'my wallet',\n m: 2,\n n: 3,\n pubKey: TestData.keyPair.pub,\n id: '1234',\n };\n server.createWallet(opts, function(err, walletId) {\n should.not.exist(err);\n server.storage.fetchWallet('1234', function(err, wallet) {\n should.not.exist(err);\n wallet.id.should.equal(walletId);\n wallet.name.should.equal('my wallet');\n done();\n });\n });\n });\n\n it('should fail to create wallets with same id', function(done) {\n var opts = {\n name: 'my wallet',\n m: 2,\n n: 3,\n pubKey: TestData.keyPair.pub,\n id: '1234',\n };\n server.createWallet(opts, function(err, walletId) {\n server.createWallet(opts, function(err, walletId) {\n err.message.should.contain('Wallet already exists');\n done();\n });\n });\n });\n\n\n it('should fail to create wallet with no name', function(done) {\n var opts = {\n name: '',\n m: 2,\n n: 3,\n pubKey: TestData.keyPair.pub,\n };\n server.createWallet(opts, function(err, walletId) {\n should.not.exist(walletId);\n should.exist(err);\n err.message.should.contain('name');\n done();\n });\n });\n\n it('should fail to create wallet with invalid copayer pairs', function(done) {\n var invalidPairs = [{\n m: 0,\n n: 0\n }, {\n m: 0,\n n: 2\n }, {\n m: 2,\n n: 1\n }, {\n m: 0,\n n: 10\n }, {\n m: 1,\n n: 20\n }, {\n m: 10,\n n: 10\n }, ];\n var opts = {\n id: '123',\n name: 'my wallet',\n pubKey: TestData.keyPair.pub,\n };\n async.each(invalidPairs, function(pair, cb) {\n opts.m = pair.m;\n opts.n = pair.n;\n server.createWallet(opts, function(err) {\n should.exist(err);\n err.message.should.equal('Invalid combination of required copayers / total copayers');\n return cb();\n });\n }, function(err) {\n done();\n });\n });\n\n it('should fail to create wallet with invalid pubKey argument', function(done) {\n var opts = {\n name: 'my wallet',\n m: 2,\n n: 3,\n pubKey: 'dummy',\n };\n server.createWallet(opts, function(err, walletId) {\n should.not.exist(walletId);\n should.exist(err);\n err.message.should.contain('Invalid public key');\n done();\n });\n });\n });\n\n describe('#joinWallet', function() {\n var server, walletId;\n beforeEach(function(done) {\n server = new WalletService();\n var walletOpts = {\n name: 'my wallet',\n m: 1,\n n: 2,\n pubKey: TestData.keyPair.pub,\n };\n server.createWallet(walletOpts, function(err, wId) {\n should.not.exist(err);\n walletId = wId;\n should.exist(walletId);\n done();\n });\n });\n\n it('should join existing wallet', function(done) {\n var copayerOpts = helpers.getSignedCopayerOpts({\n walletId: walletId,\n name: 'me',\n xPubKey: TestData.copayers[0].xPubKey_44H_0H_0H,\n requestPubKey: TestData.copayers[0].pubKey_1H_0,\n customData: 'dummy custom data',\n });\n server.joinWallet(copayerOpts, function(err, result) {\n should.not.exist(err);\n var copayerId = result.copayerId;\n helpers.getAuthServer(copayerId, function(server) {\n server.getWallet({}, function(err, wallet) {\n wallet.id.should.equal(walletId);\n wallet.copayers.length.should.equal(1);\n var copayer = wallet.copayers[0];\n copayer.name.should.equal('me');\n copayer.id.should.equal(copayerId);\n copayer.customData.should.equal('dummy custom data');\n server.getNotifications({}, function(err, notifications) {\n should.not.exist(err);\n var notif = _.find(notifications, {\n type: 'NewCopayer'\n });\n should.exist(notif);\n notif.data.walletId.should.equal(walletId);\n notif.data.copayerId.should.equal(copayerId);\n notif.data.copayerName.should.equal('me');\n\n notif = _.find(notifications, {\n type: 'WalletComplete'\n });\n should.not.exist(notif);\n done();\n });\n });\n });\n });\n });\n\n it('should fail to join with no name', function(done) {\n var copayerOpts = helpers.getSignedCopayerOpts({\n walletId: walletId,\n name: '',\n xPubKey: TestData.copayers[0].xPubKey_44H_0H_0H,\n requestPubKey: TestData.copayers[0].pubKey_1H_0,\n });\n server.joinWallet(copayerOpts, function(err, result) {\n should.not.exist(result);\n should.exist(err);\n err.message.should.contain('name');\n done();\n });\n });\n\n it('should fail to join non-existent wallet', function(done) {\n var copayerOpts = {\n walletId: '123',\n name: 'me',\n xPubKey: 'dummy',\n requestPubKey: 'dummy',\n copayerSignature: 'dummy',\n };\n server.joinWallet(copayerOpts, function(err) {\n should.exist(err);\n done();\n });\n });\n\n it('should fail to join full wallet', function(done) {\n helpers.createAndJoinWallet(1, 1, function(s, wallet) {\n var copayerOpts = helpers.getSignedCopayerOpts({\n walletId: wallet.id,\n name: 'me',\n xPubKey: TestData.copayers[1].xPubKey_44H_0H_0H,\n requestPubKey: TestData.copayers[1].pubKey_1H_0,\n });\n server.joinWallet(copayerOpts, function(err) {\n should.exist(err);\n err.code.should.equal('WALLET_FULL');\n err.message.should.equal('Wallet full');\n done();\n });\n });\n });\n\n it('should return copayer in wallet error before full wallet', function(done) {\n helpers.createAndJoinWallet(1, 1, function(s, wallet) {\n var copayerOpts = helpers.getSignedCopayerOpts({\n walletId: wallet.id,\n name: 'me',\n xPubKey: TestData.copayers[0].xPubKey_44H_0H_0H,\n requestPubKey: TestData.copayers[0].pubKey_1H_0,\n });\n server.joinWallet(copayerOpts, function(err) {\n should.exist(err);\n err.code.should.equal('COPAYER_IN_WALLET');\n done();\n });\n });\n });\n\n it('should fail to re-join wallet', function(done) {\n var copayerOpts = helpers.getSignedCopayerOpts({\n walletId: walletId,\n name: 'me',\n xPubKey: TestData.copayers[0].xPubKey_44H_0H_0H,\n requestPubKey: TestData.copayers[0].pubKey_1H_0,\n });\n server.joinWallet(copayerOpts, function(err) {\n should.not.exist(err);\n server.joinWallet(copayerOpts, function(err) {\n should.exist(err);\n err.code.should.equal('COPAYER_IN_WALLET');\n err.message.should.equal('Copayer already in wallet');\n done();\n });\n });\n });\n\n it('should be able to get wallet info without actually joining', function(done) {\n var copayerOpts = helpers.getSignedCopayerOpts({\n walletId: walletId,\n name: 'me',\n xPubKey: TestData.copayers[0].xPubKey_44H_0H_0H,\n requestPubKey: TestData.copayers[0].pubKey_1H_0,\n customData: 'dummy custom data',\n dryRun: true,\n });\n server.joinWallet(copayerOpts, function(err, result) {\n should.not.exist(err);\n should.exist(result);\n should.not.exist(result.copayerId);\n result.wallet.id.should.equal(walletId);\n result.wallet.m.should.equal(1);\n result.wallet.n.should.equal(2);\n result.wallet.copayers.should.be.empty;\n server.storage.fetchWallet(walletId, function(err, wallet) {\n should.not.exist(err);\n wallet.id.should.equal(walletId);\n wallet.copayers.should.be.empty;\n done();\n });\n });\n });\n\n it('should fail to join two wallets with same xPubKey', function(done) {\n var copayerOpts = helpers.getSignedCopayerOpts({\n walletId: walletId,\n name: 'me',\n xPubKey: TestData.copayers[0].xPubKey_44H_0H_0H,\n requestPubKey: TestData.copayers[0].pubKey_1H_0,\n });\n server.joinWallet(copayerOpts, function(err) {\n should.not.exist(err);\n\n var walletOpts = {\n name: 'my other wallet',\n m: 1,\n n: 1,\n pubKey: TestData.keyPair.pub,\n };\n server.createWallet(walletOpts, function(err, walletId) {\n should.not.exist(err);\n copayerOpts = helpers.getSignedCopayerOpts({\n walletId: walletId,\n name: 'me',\n xPubKey: TestData.copayers[0].xPubKey_44H_0H_0H,\n requestPubKey: TestData.copayers[0].pubKey_1H_0,\n });\n server.joinWallet(copayerOpts, function(err) {\n should.exist(err);\n err.code.should.equal('COPAYER_REGISTERED');\n err.message.should.equal('Copayer ID already registered on server');\n done();\n });\n });\n });\n });\n\n it('should fail to join with bad formated signature', function(done) {\n var copayerOpts = {\n walletId: walletId,\n name: 'me',\n xPubKey: TestData.copayers[0].xPubKey_44H_0H_0H,\n requestPubKey: TestData.copayers[0].pubKey_1H_0,\n copayerSignature: 'bad sign',\n };\n server.joinWallet(copayerOpts, function(err) {\n err.message.should.equal('Bad request');\n done();\n });\n });\n\n it('should fail to join with null signature', function(done) {\n var copayerOpts = {\n walletId: walletId,\n name: 'me',\n xPubKey: TestData.copayers[0].xPubKey_44H_0H_0H,\n requestPubKey: TestData.copayers[0].pubKey_1H_0,\n };\n server.joinWallet(copayerOpts, function(err) {\n should.exist(err);\n err.message.should.contain('argument missing');\n done();\n });\n });\n\n it('should fail to join with wrong signature', function(done) {\n var copayerOpts = helpers.getSignedCopayerOpts({\n walletId: walletId,\n name: 'me',\n xPubKey: TestData.copayers[0].xPubKey_44H_0H_0H,\n requestPubKey: TestData.copayers[0].pubKey_1H_0,\n });\n copayerOpts.name = 'me2';\n server.joinWallet(copayerOpts, function(err) {\n err.message.should.equal('Bad request');\n done();\n });\n });\n\n it('should set pkr and status = complete on last copayer joining (2-3)', function(done) {\n helpers.createAndJoinWallet(2, 3, function(server) {\n server.getWallet({}, function(err, wallet) {\n should.not.exist(err);\n wallet.status.should.equal('complete');\n wallet.publicKeyRing.length.should.equal(3);\n server.getNotifications({}, function(err, notifications) {\n should.not.exist(err);\n var notif = _.find(notifications, {\n type: 'WalletComplete'\n });\n should.exist(notif);\n notif.data.walletId.should.equal(wallet.id);\n done();\n });\n });\n });\n });\n\n it('should not notify WalletComplete if 1-of-1', function(done) {\n helpers.createAndJoinWallet(1, 1, function(server) {\n server.getNotifications({}, function(err, notifications) {\n should.not.exist(err);\n var notif = _.find(notifications, {\n type: 'WalletComplete'\n });\n should.not.exist(notif);\n done();\n });\n });\n });\n });\n\n describe('#joinWallet new/legacy clients', function() {\n var server;\n beforeEach(function() {\n server = new WalletService();\n });\n\n it('should fail to join legacy wallet from new client', function(done) {\n var walletOpts = {\n name: 'my wallet',\n m: 1,\n n: 2,\n pubKey: TestData.keyPair.pub,\n supportBIP44AndP2PKH: false,\n };\n server.createWallet(walletOpts, function(err, walletId) {\n should.not.exist(err);\n should.exist(walletId);\n var copayerOpts = helpers.getSignedCopayerOpts({\n walletId: walletId,\n name: 'me',\n xPubKey: TestData.copayers[0].xPubKey_44H_0H_0H,\n requestPubKey: TestData.copayers[0].pubKey_1H_0,\n });\n server.joinWallet(copayerOpts, function(err, result) {\n should.exist(err);\n err.message.should.contain('The wallet you are trying to join was created with an older version of the client app');\n done();\n });\n });\n });\n it('should fail to join new wallet from legacy client', function(done) {\n var walletOpts = {\n name: 'my wallet',\n m: 1,\n n: 2,\n pubKey: TestData.keyPair.pub,\n };\n server.createWallet(walletOpts, function(err, walletId) {\n should.not.exist(err);\n should.exist(walletId);\n var copayerOpts = helpers.getSignedCopayerOpts({\n walletId: walletId,\n name: 'me',\n xPubKey: TestData.copayers[0].xPubKey_45H,\n requestPubKey: TestData.copayers[0].pubKey_1H_0,\n supportBIP44AndP2PKH: false,\n });\n server.joinWallet(copayerOpts, function(err, result) {\n should.exist(err);\n err.code.should.equal('UPGRADE_NEEDED');\n done();\n });\n });\n });\n });\n\n describe('Address derivation strategy', function() {\n var server;\n beforeEach(function() {\n server = WalletService.getInstance();\n });\n it('should use BIP44 & P2PKH for 1-of-1 wallet if supported', function(done) {\n var walletOpts = {\n name: 'my wallet',\n m: 1,\n n: 1,\n pubKey: TestData.keyPair.pub,\n };\n server.createWallet(walletOpts, function(err, wid) {\n should.not.exist(err);\n server.storage.fetchWallet(wid, function(err, wallet) {\n should.not.exist(err);\n wallet.derivationStrategy.should.equal('BIP44');\n wallet.addressType.should.equal('P2PKH');\n done();\n });\n });\n });\n it('should use BIP45 & P2SH for 1-of-1 wallet if not supported', function(done) {\n var walletOpts = {\n name: 'my wallet',\n m: 1,\n n: 1,\n pubKey: TestData.keyPair.pub,\n supportBIP44AndP2PKH: false,\n };\n server.createWallet(walletOpts, function(err, wid) {\n should.not.exist(err);\n server.storage.fetchWallet(wid, function(err, wallet) {\n should.not.exist(err);\n wallet.derivationStrategy.should.equal('BIP45');\n wallet.addressType.should.equal('P2SH');\n done();\n });\n });\n });\n it('should use BIP44 & P2SH for shared wallet if supported', function(done) {\n var walletOpts = {\n name: 'my wallet',\n m: 2,\n n: 3,\n pubKey: TestData.keyPair.pub,\n };\n server.createWallet(walletOpts, function(err, wid) {\n should.not.exist(err);\n server.storage.fetchWallet(wid, function(err, wallet) {\n should.not.exist(err);\n wallet.derivationStrategy.should.equal('BIP44');\n wallet.addressType.should.equal('P2SH');\n done();\n });\n });\n });\n it('should use BIP45 & P2SH for shared wallet if supported', function(done) {\n var walletOpts = {\n name: 'my wallet',\n m: 2,\n n: 3,\n pubKey: TestData.keyPair.pub,\n supportBIP44AndP2PKH: false,\n };\n server.createWallet(walletOpts, function(err, wid) {\n should.not.exist(err);\n server.storage.fetchWallet(wid, function(err, wallet) {\n should.not.exist(err);\n wallet.derivationStrategy.should.equal('BIP45');\n wallet.addressType.should.equal('P2SH');\n done();\n });\n });\n });\n });\n\n describe('#getStatus', function() {\n var server, wallet;\n beforeEach(function(done) {\n helpers.createAndJoinWallet(1, 2, function(s, w) {\n server = s;\n wallet = w;\n done();\n });\n });\n\n it('should get status', function(done) {\n server.getStatus({}, function(err, status) {\n should.not.exist(err);\n should.exist(status);\n should.exist(status.wallet);\n status.wallet.name.should.equal(wallet.name);\n should.exist(status.wallet.copayers);\n status.wallet.copayers.length.should.equal(2);\n should.exist(status.balance);\n status.balance.totalAmount.should.equal(0);\n should.exist(status.preferences);\n should.exist(status.pendingTxps);\n status.pendingTxps.should.be.empty;\n\n should.not.exist(status.wallet.publicKeyRing);\n should.not.exist(status.wallet.pubKey);\n should.not.exist(status.wallet.addressManager);\n _.each(status.wallet.copayers, function(copayer) {\n should.not.exist(copayer.xPubKey);\n should.not.exist(copayer.requestPubKey);\n should.not.exist(copayer.signature);\n should.not.exist(copayer.requestPubKey);\n should.not.exist(copayer.addressManager);\n should.not.exist(copayer.customData);\n });\n done();\n });\n });\n it('should get status including extended info', function(done) {\n server.getStatus({\n includeExtendedInfo: true\n }, function(err, status) {\n should.not.exist(err);\n should.exist(status);\n should.exist(status.wallet.publicKeyRing);\n should.exist(status.wallet.pubKey);\n should.exist(status.wallet.addressManager);\n should.exist(status.wallet.copayers[0].xPubKey);\n should.exist(status.wallet.copayers[0].requestPubKey);\n should.exist(status.wallet.copayers[0].signature);\n should.exist(status.wallet.copayers[0].requestPubKey);\n should.exist(status.wallet.copayers[0].customData);\n // Do not return other copayer's custom data\n _.each(_.rest(status.wallet.copayers), function(copayer) {\n should.not.exist(copayer.customData);\n });\n done();\n });\n });\n it('should get status after tx creation', function(done) {\n helpers.stubUtxos(server, wallet, [100, 200], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 80, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n should.exist(tx);\n server.getStatus({}, function(err, status) {\n should.not.exist(err);\n status.pendingTxps.length.should.equal(1);\n var balance = status.balance;\n balance.totalAmount.should.equal(helpers.toSatoshi(300));\n balance.lockedAmount.should.equal(tx.inputs[0].satoshis);\n balance.availableAmount.should.equal(balance.totalAmount - balance.lockedAmount);\n done();\n });\n });\n });\n });\n });\n\n describe('#verifyMessageSignature', function() {\n var server, wallet;\n beforeEach(function(done) {\n helpers.createAndJoinWallet(2, 3, function(s, w) {\n server = s;\n wallet = w;\n done();\n });\n });\n\n it('should successfully verify message signature', function(done) {\n var message = 'hello world';\n var opts = {\n message: message,\n signature: WalletUtils.signMessage(message, TestData.copayers[0].privKey_1H_0),\n };\n server.verifyMessageSignature(opts, function(err, isValid) {\n should.not.exist(err);\n isValid.should.be.true;\n done();\n });\n });\n\n it('should fail to verify message signature for different copayer', function(done) {\n var message = 'hello world';\n var opts = {\n message: message,\n signature: WalletUtils.signMessage(message, TestData.copayers[0].privKey_1H_0),\n };\n helpers.getAuthServer(wallet.copayers[1].id, function(server) {\n server.verifyMessageSignature(opts, function(err, isValid) {\n should.not.exist(err);\n isValid.should.be.false;\n done();\n });\n });\n });\n });\n\n describe('#createAddress', function() {\n var server, wallet;\n\n describe('shared wallets (BIP45)', function() {\n beforeEach(function(done) {\n helpers.createAndJoinWallet(2, 2, {\n supportBIP44AndP2PKH: false\n }, function(s, w) {\n server = s;\n wallet = w;\n done();\n });\n });\n\n it('should create address', function(done) {\n server.createAddress({}, function(err, address) {\n should.not.exist(err);\n should.exist(address);\n address.walletId.should.equal(wallet.id);\n address.network.should.equal('livenet');\n address.address.should.equal('3BVJZ4CYzeTtawDtgwHvWV5jbvnXtYe97i');\n address.isChange.should.be.false;\n address.path.should.equal('m/2147483647/0/0');\n address.type.should.equal('P2SH');\n server.getNotifications({}, function(err, notifications) {\n should.not.exist(err);\n var notif = _.find(notifications, {\n type: 'NewAddress'\n });\n should.exist(notif);\n notif.data.address.should.equal(address.address);\n done();\n });\n });\n });\n\n it('should protect against storing same address multiple times', function(done) {\n server.createAddress({}, function(err, address) {\n should.not.exist(err);\n should.exist(address);\n delete address._id;\n server.storage.storeAddressAndWallet(wallet, address, function(err) {\n should.not.exist(err);\n server.getMainAddresses({}, function(err, addresses) {\n should.not.exist(err);\n addresses.length.should.equal(1);\n done();\n });\n });\n });\n });\n\n it('should create many addresses on simultaneous requests', function(done) {\n var N = 5;\n async.map(_.range(N), function(i, cb) {\n server.createAddress({}, cb);\n }, function(err, addresses) {\n addresses.length.should.equal(N);\n _.each(_.range(N), function(i) {\n addresses[i].path.should.equal('m/2147483647/0/' + i);\n });\n // No two identical addresses\n _.uniq(_.pluck(addresses, 'address')).length.should.equal(N);\n done();\n });\n });\n });\n\n describe('shared wallets (BIP44)', function() {\n beforeEach(function(done) {\n helpers.createAndJoinWallet(2, 2, function(s, w) {\n server = s;\n wallet = w;\n done();\n });\n });\n\n it('should create address', function(done) {\n server.createAddress({}, function(err, address) {\n should.not.exist(err);\n should.exist(address);\n address.walletId.should.equal(wallet.id);\n address.network.should.equal('livenet');\n address.address.should.equal('36q2G5FMGvJbPgAVEaiyAsFGmpkhPKwk2r');\n address.isChange.should.be.false;\n address.path.should.equal('m/0/0');\n address.type.should.equal('P2SH');\n server.getNotifications({}, function(err, notifications) {\n should.not.exist(err);\n var notif = _.find(notifications, {\n type: 'NewAddress'\n });\n should.exist(notif);\n notif.data.address.should.equal(address.address);\n done();\n });\n });\n });\n\n it('should create many addresses on simultaneous requests', function(done) {\n var N = 5;\n async.map(_.range(N), function(i, cb) {\n server.createAddress({}, cb);\n }, function(err, addresses) {\n addresses.length.should.equal(N);\n _.each(_.range(N), function(i) {\n addresses[i].path.should.equal('m/0/' + i);\n });\n // No two identical addresses\n _.uniq(_.pluck(addresses, 'address')).length.should.equal(N);\n done();\n });\n });\n\n it('should not create address if unable to store it', function(done) {\n sinon.stub(server.storage, 'storeAddressAndWallet').yields('dummy error');\n server.createAddress({}, function(err, address) {\n should.exist(err);\n should.not.exist(address);\n\n server.getMainAddresses({}, function(err, addresses) {\n addresses.length.should.equal(0);\n\n server.storage.storeAddressAndWallet.restore();\n server.createAddress({}, function(err, address) {\n should.not.exist(err);\n should.exist(address);\n done();\n });\n });\n });\n });\n });\n\n describe('1-of-1 (BIP44 & P2PKH)', function() {\n beforeEach(function(done) {\n helpers.createAndJoinWallet(1, 1, function(s, w) {\n server = s;\n wallet = w;\n w.copayers[0].id.should.equal(TestData.copayers[0].id44);\n done();\n });\n });\n\n it('should create address', function(done) {\n server.createAddress({}, function(err, address) {\n should.not.exist(err);\n should.exist(address);\n address.walletId.should.equal(wallet.id);\n address.network.should.equal('livenet');\n address.address.should.equal('1L3z9LPd861FWQhf3vDn89Fnc9dkdBo2CG');\n address.isChange.should.be.false;\n address.path.should.equal('m/0/0');\n address.type.should.equal('P2PKH');\n server.getNotifications({}, function(err, notifications) {\n should.not.exist(err);\n var notif = _.find(notifications, {\n type: 'NewAddress'\n });\n should.exist(notif);\n notif.data.address.should.equal(address.address);\n done();\n });\n });\n });\n\n it('should create many addresses on simultaneous requests', function(done) {\n var N = 5;\n async.map(_.range(N), function(i, cb) {\n server.createAddress({}, cb);\n }, function(err, addresses) {\n addresses.length.should.equal(N);\n _.each(_.range(N), function(i) {\n addresses[i].path.should.equal('m/0/' + i);\n });\n // No two identical addresses\n _.uniq(_.pluck(addresses, 'address')).length.should.equal(N);\n done();\n });\n });\n });\n });\n\n describe('Preferences', function() {\n var server, wallet;\n beforeEach(function(done) {\n helpers.createAndJoinWallet(2, 2, function(s, w) {\n server = s;\n wallet = w;\n done();\n });\n });\n\n it('should save & retrieve preferences', function(done) {\n server.savePreferences({\n email: 'dummy@dummy.com',\n language: 'es',\n unit: 'bit',\n dummy: 'ignored',\n }, function(err) {\n should.not.exist(err);\n server.getPreferences({}, function(err, preferences) {\n should.not.exist(err);\n should.exist(preferences);\n preferences.email.should.equal('dummy@dummy.com');\n preferences.language.should.equal('es');\n preferences.unit.should.equal('bit');\n should.not.exist(preferences.dummy);\n done();\n });\n });\n });\n it('should save preferences only for requesting copayer', function(done) {\n server.savePreferences({\n email: 'dummy@dummy.com'\n }, function(err) {\n should.not.exist(err);\n helpers.getAuthServer(wallet.copayers[1].id, function(server2) {\n server2.getPreferences({}, function(err, preferences) {\n should.not.exist(err);\n should.not.exist(preferences.email);\n done();\n });\n });\n });\n });\n it('should save preferences incrementally', function(done) {\n async.series([\n\n function(next) {\n server.savePreferences({\n email: 'dummy@dummy.com',\n }, next);\n },\n function(next) {\n server.getPreferences({}, function(err, preferences) {\n should.not.exist(err);\n should.exist(preferences);\n preferences.email.should.equal('dummy@dummy.com');\n should.not.exist(preferences.language);\n next();\n });\n },\n function(next) {\n server.savePreferences({\n language: 'es',\n }, next);\n },\n function(next) {\n server.getPreferences({}, function(err, preferences) {\n should.not.exist(err);\n should.exist(preferences);\n preferences.language.should.equal('es');\n preferences.email.should.equal('dummy@dummy.com');\n next();\n });\n },\n function(next) {\n server.savePreferences({\n language: null,\n unit: 'bit',\n }, next);\n },\n function(next) {\n server.getPreferences({}, function(err, preferences) {\n should.not.exist(err);\n should.exist(preferences);\n preferences.unit.should.equal('bit');\n should.not.exist(preferences.language);\n preferences.email.should.equal('dummy@dummy.com');\n next();\n });\n },\n ], function(err) {\n should.not.exist(err);\n done();\n });\n });\n it.skip('should save preferences only for requesting wallet', function(done) {});\n it('should validate entries', function(done) {\n var invalid = [{\n preferences: {\n email: ' ',\n },\n expected: 'email'\n }, {\n preferences: {\n email: 'dummy@' + _.repeat('domain', 50),\n },\n expected: 'email'\n }, {\n preferences: {\n language: 'xxxxx',\n },\n expected: 'language'\n }, {\n preferences: {\n language: 123,\n },\n expected: 'language'\n }, {\n preferences: {\n unit: 'xxxxx',\n },\n expected: 'unit'\n }, ];\n async.each(invalid, function(item, next) {\n server.savePreferences(item.preferences, function(err) {\n should.exist(err);\n err.message.should.contain(item.expected);\n next();\n });\n }, done);\n });\n });\n\n describe('#getUtxos', function() {\n var server, wallet;\n beforeEach(function(done) {\n helpers.createAndJoinWallet(1, 1, function(s, w) {\n server = s;\n wallet = w;\n done();\n });\n });\n\n it('should get UTXOs for wallet addresses', function(done) {\n helpers.stubUtxos(server, wallet, [1, 2], function() {\n server.getUtxos({}, function(err, utxos) {\n should.not.exist(err);\n should.exist(utxos);\n utxos.length.should.equal(2);\n _.sum(utxos, 'satoshis').should.equal(3 * 1e8);\n server.getMainAddresses({}, function(err, addresses) {\n var utxo = utxos[0];\n var address = _.find(addresses, {\n address: utxo.address\n });\n should.exist(address);\n utxo.path.should.equal(address.path);\n utxo.publicKeys.should.deep.equal(address.publicKeys);\n done();\n });\n });\n });\n });\n it('should get UTXOs for specific addresses', function(done) {\n helpers.stubUtxos(server, wallet, [1, 2, 3], function(utxos) {\n _.uniq(utxos, 'address').length.should.be.above(1);\n var address = utxos[0].address;\n var amount = _.sum(_.filter(utxos, {\n address: address\n }), 'satoshis');\n server.getUtxos({\n addresses: [address]\n }, function(err, utxos) {\n should.not.exist(err);\n should.exist(utxos);\n _.sum(utxos, 'satoshis').should.equal(amount);\n done();\n });\n });\n });\n });\n\n\n describe('Multiple request Pub Keys', function() {\n var server, wallet;\n var opts, reqPrivKey, ws;\n var getAuthServer = function(copayerId, privKey, cb) {\n var msg = 'dummy';\n var sig = WalletUtils.signMessage(msg, privKey);\n WalletService.getInstanceWithAuth({\n copayerId: copayerId,\n message: msg,\n signature: sig,\n clientVersion: CLIENT_VERSION,\n }, function(err, server) {\n return cb(err, server);\n });\n };\n\n beforeEach(function() {\n reqPrivKey = new Bitcore.PrivateKey();\n var requestPubKey = reqPrivKey.toPublicKey();\n\n var xPrivKey = TestData.copayers[0].xPrivKey_44H_0H_0H;\n var sig = WalletUtils.signRequestPubKey(requestPubKey, xPrivKey);\n\n var copayerId = WalletUtils.xPubToCopayerId(TestData.copayers[0].xPubKey_44H_0H_0H);\n opts = {\n copayerId: copayerId,\n requestPubKey: requestPubKey,\n signature: sig,\n };\n ws = new WalletService();\n });\n\n describe('#addAccess 1-1', function() {\n beforeEach(function(done) {\n helpers.createAndJoinWallet(1, 1, function(s, w) {\n server = s;\n wallet = w;\n\n helpers.stubUtxos(server, wallet, 1, function() {\n done();\n });\n });\n });\n\n it('should be able to re-gain access from xPrivKey', function(done) {\n ws.addAccess(opts, function(err, res) {\n should.not.exist(err);\n res.wallet.copayers[0].requestPubKeys.length.should.equal(2);\n res.wallet.copayers[0].requestPubKeys[0].selfSigned.should.equal(true);\n\n server.getBalance(res.wallet.walletId, function(err, bal) {\n should.not.exist(err);\n bal.totalAmount.should.equal(1e8);\n getAuthServer(opts.copayerId, reqPrivKey, function(err, server2) {\n server2.getBalance(res.wallet.walletId, function(err, bal2) {\n should.not.exist(err);\n bal2.totalAmount.should.equal(1e8);\n done();\n });\n });\n });\n });\n });\n\n it('should fail to gain access with wrong xPrivKey', function(done) {\n opts.signature = 'xx';\n ws.addAccess(opts, function(err, res) {\n err.code.should.equal('NOT_AUTHORIZED');\n done();\n });\n });\n\n it('should fail to access with wrong privkey after gaining access', function(done) {\n ws.addAccess(opts, function(err, res) {\n should.not.exist(err);\n server.getBalance(res.wallet.walletId, function(err, bal) {\n should.not.exist(err);\n var privKey = new Bitcore.PrivateKey();\n (getAuthServer(opts.copayerId, privKey, function(err, server2) {\n err.code.should.equal('NOT_AUTHORIZED');\n done();\n }));\n });\n });\n });\n\n it('should be able to create TXs after regaining access', function(done) {\n ws.addAccess(opts, function(err, res) {\n should.not.exist(err);\n getAuthServer(opts.copayerId, reqPrivKey, function(err, server2) {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 0.8, reqPrivKey);\n server2.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n done();\n });\n });\n });\n });\n });\n\n describe('#addAccess 2-2', function() {\n beforeEach(function(done) {\n helpers.createAndJoinWallet(2, 2, function(s, w) {\n server = s;\n wallet = w;\n helpers.stubUtxos(server, wallet, 1, function() {\n done();\n });\n });\n });\n\n it('should be able to re-gain access from xPrivKey', function(done) {\n ws.addAccess(opts, function(err, res) {\n should.not.exist(err);\n server.getBalance(res.wallet.walletId, function(err, bal) {\n should.not.exist(err);\n bal.totalAmount.should.equal(1e8);\n getAuthServer(opts.copayerId, reqPrivKey, function(err, server2) {\n server2.getBalance(res.wallet.walletId, function(err, bal2) {\n should.not.exist(err);\n bal2.totalAmount.should.equal(1e8);\n done();\n });\n });\n });\n });\n });\n\n it('TX proposals should include info to be verified', function(done) {\n ws.addAccess(opts, function(err, res) {\n should.not.exist(err);\n getAuthServer(opts.copayerId, reqPrivKey, function(err, server2) {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 0.8, reqPrivKey);\n server2.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n server2.getPendingTxs({}, function(err, txs) {\n should.not.exist(err);\n should.exist(txs[0].proposalSignaturePubKey);\n should.exist(txs[0].proposalSignaturePubKeySig);\n done();\n });\n });\n });\n });\n });\n\n });\n });\n\n describe('#getBalance', function() {\n var server, wallet;\n beforeEach(function(done) {\n helpers.createAndJoinWallet(1, 1, function(s, w) {\n server = s;\n wallet = w;\n done();\n });\n });\n\n it('should get balance', function(done) {\n helpers.stubUtxos(server, wallet, [1, 'u2', 3], function() {\n server.getBalance({}, function(err, balance) {\n should.not.exist(err);\n should.exist(balance);\n balance.totalAmount.should.equal(helpers.toSatoshi(6));\n balance.lockedAmount.should.equal(0);\n balance.availableAmount.should.equal(helpers.toSatoshi(6));\n balance.totalBytesToSendMax.should.equal(578);\n\n balance.totalConfirmedAmount.should.equal(helpers.toSatoshi(4));\n balance.lockedConfirmedAmount.should.equal(0);\n balance.availableConfirmedAmount.should.equal(helpers.toSatoshi(4));\n\n should.exist(balance.byAddress);\n balance.byAddress.length.should.equal(2);\n balance.byAddress[0].amount.should.equal(helpers.toSatoshi(4));\n balance.byAddress[1].amount.should.equal(helpers.toSatoshi(2));\n server.getMainAddresses({}, function(err, addresses) {\n should.not.exist(err);\n var addresses = _.uniq(_.pluck(addresses, 'address'));\n _.intersection(addresses, _.pluck(balance.byAddress, 'address')).length.should.equal(2);\n done();\n });\n });\n });\n });\n it('should get balance when there are no addresses', function(done) {\n server.getBalance({}, function(err, balance) {\n should.not.exist(err);\n should.exist(balance);\n balance.totalAmount.should.equal(0);\n balance.lockedAmount.should.equal(0);\n balance.availableAmount.should.equal(0);\n balance.totalBytesToSendMax.should.equal(0);\n should.exist(balance.byAddress);\n balance.byAddress.length.should.equal(0);\n done();\n });\n });\n it('should get balance when there are no funds', function(done) {\n blockchainExplorer.getUnspentUtxos = sinon.stub().callsArgWith(1, null, []);\n server.createAddress({}, function(err, address) {\n should.not.exist(err);\n server.getBalance({}, function(err, balance) {\n should.not.exist(err);\n should.exist(balance);\n balance.totalAmount.should.equal(0);\n balance.lockedAmount.should.equal(0);\n balance.availableAmount.should.equal(0);\n balance.totalBytesToSendMax.should.equal(0);\n should.exist(balance.byAddress);\n balance.byAddress.length.should.equal(0);\n done();\n });\n });\n });\n it('should only include addresses with balance', function(done) {\n helpers.stubUtxos(server, wallet, 1, function(utxos) {\n server.createAddress({}, function(err, address) {\n should.not.exist(err);\n server.getBalance({}, function(err, balance) {\n should.not.exist(err);\n balance.byAddress.length.should.equal(1);\n balance.byAddress[0].amount.should.equal(helpers.toSatoshi(1));\n balance.byAddress[0].address.should.equal(utxos[0].address);\n done();\n });\n });\n });\n });\n it('should return correct kb to send max', function(done) {\n helpers.stubUtxos(server, wallet, _.range(1, 10, 0), function() {\n server.getBalance({}, function(err, balance) {\n should.not.exist(err);\n should.exist(balance);\n balance.totalAmount.should.equal(helpers.toSatoshi(9));\n balance.lockedAmount.should.equal(0);\n balance.totalBytesToSendMax.should.equal(1535);\n done();\n });\n });\n });\n it('should fail gracefully when blockchain is unreachable', function(done) {\n blockchainExplorer.getUnspentUtxos = sinon.stub().callsArgWith(1, 'dummy error');\n server.createAddress({}, function(err, address) {\n should.not.exist(err);\n server.getBalance({}, function(err, balance) {\n should.exist(err);\n err.toString().should.equal('dummy error');\n done();\n });\n });\n });\n });\n\n describe('#getFeeLevels', function() {\n var server, wallet;\n beforeEach(function(done) {\n helpers.createAndJoinWallet(1, 1, function(s, w) {\n server = s;\n wallet = w;\n done();\n });\n });\n\n it('should get current fee levels', function(done) {\n helpers.stubFeeLevels({\n 1: 40000,\n 2: 20000,\n 6: 18000,\n });\n server.getFeeLevels({}, function(err, fees) {\n should.not.exist(err);\n fees = _.zipObject(_.map(fees, function(item) {\n return [item.level, item];\n }));\n fees.priority.feePerKb.should.equal(40000);\n fees.priority.nbBlocks.should.equal(1);\n\n fees.normal.feePerKb.should.equal(20000);\n fees.normal.nbBlocks.should.equal(2);\n\n fees.economy.feePerKb.should.equal(18000);\n fees.economy.nbBlocks.should.equal(6);\n done();\n });\n });\n it('should get default fees if network cannot be accessed', function(done) {\n blockchainExplorer.estimateFee = sinon.stub().yields('dummy error');\n server.getFeeLevels({}, function(err, fees) {\n should.not.exist(err);\n fees = _.zipObject(_.map(fees, function(item) {\n return [item.level, item.feePerKb];\n }));\n fees.priority.should.equal(50000);\n fees.normal.should.equal(20000);\n fees.economy.should.equal(10000);\n done();\n });\n });\n it('should get default fees if network cannot estimate (returns -1)', function(done) {\n helpers.stubFeeLevels({\n 1: -1,\n 2: 18000,\n 6: 0,\n });\n server.getFeeLevels({}, function(err, fees) {\n should.not.exist(err);\n fees = _.zipObject(_.map(fees, function(item) {\n return [item.level, item];\n }));\n fees.priority.feePerKb.should.equal(50000);\n should.not.exist(fees.priority.nbBlocks);\n\n fees.normal.feePerKb.should.equal(18000);\n fees.normal.nbBlocks.should.equal(2);\n\n fees.economy.feePerKb.should.equal(0);\n fees.economy.nbBlocks.should.equal(6);\n done();\n });\n });\n });\n\n describe('Wallet not complete tests', function() {\n it('should fail to create address when wallet is not complete', function(done) {\n var server = new WalletService();\n var walletOpts = {\n name: 'my wallet',\n m: 2,\n n: 3,\n pubKey: TestData.keyPair.pub,\n };\n server.createWallet(walletOpts, function(err, walletId) {\n should.not.exist(err);\n var copayerOpts = helpers.getSignedCopayerOpts({\n walletId: walletId,\n name: 'me',\n xPubKey: TestData.copayers[0].xPubKey_45H,\n requestPubKey: TestData.copayers[0].pubKey_1H_0,\n });\n server.joinWallet(copayerOpts, function(err, result) {\n should.not.exist(err);\n helpers.getAuthServer(result.copayerId, function(server) {\n server.createAddress({}, function(err, address) {\n should.not.exist(address);\n should.exist(err);\n err.code.should.equal('WALLET_NOT_COMPLETE');\n err.message.should.equal('Wallet is not complete');\n done();\n });\n });\n });\n });\n });\n\n it('should fail to create tx when wallet is not complete', function(done) {\n var server = new WalletService();\n var walletOpts = {\n name: 'my wallet',\n m: 2,\n n: 3,\n pubKey: TestData.keyPair.pub,\n };\n server.createWallet(walletOpts, function(err, walletId) {\n should.not.exist(err);\n var copayerOpts = helpers.getSignedCopayerOpts({\n walletId: walletId,\n name: 'me',\n xPubKey: TestData.copayers[0].xPubKey_45H,\n requestPubKey: TestData.copayers[0].pubKey_1H_0,\n });\n server.joinWallet(copayerOpts, function(err, result) {\n should.not.exist(err);\n helpers.getAuthServer(result.copayerId, function(server, wallet) {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 80, TestData.copayers[0].privKey);\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(tx);\n should.exist(err);\n err.code.should.equal('WALLET_NOT_COMPLETE');\n done();\n });\n });\n });\n });\n });\n });\n\n describe('#createTx', function() {\n var server, wallet;\n beforeEach(function(done) {\n helpers.createAndJoinWallet(2, 3, function(s, w) {\n server = s;\n wallet = w;\n done();\n });\n });\n\n it('should create a tx', function(done) {\n helpers.stubUtxos(server, wallet, [100, 200], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 80, TestData.copayers[0].privKey_1H_0, {\n message: 'some message',\n customData: 'some custom data'\n });\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n should.exist(tx);\n tx.walletId.should.equal(wallet.id);\n tx.network.should.equal('livenet');\n tx.creatorId.should.equal(wallet.copayers[0].id);\n tx.message.should.equal('some message');\n tx.customData.should.equal('some custom data');\n tx.isAccepted().should.equal.false;\n tx.isRejected().should.equal.false;\n tx.amount.should.equal(helpers.toSatoshi(80));\n var estimatedFee = WalletUtils.DEFAULT_FEE_PER_KB * 400 / 1000; // fully signed tx should have about 400 bytes\n tx.fee.should.be.within(0.9 * estimatedFee, 1.1 * estimatedFee);\n server.getPendingTxs({}, function(err, txs) {\n should.not.exist(err);\n txs.length.should.equal(1);\n // creator\n txs[0].deleteLockTime.should.equal(0);\n server.getBalance({}, function(err, balance) {\n should.not.exist(err);\n balance.totalAmount.should.equal(helpers.toSatoshi(300));\n balance.lockedAmount.should.equal(tx.inputs[0].satoshis);\n balance.lockedAmount.should.be.below(balance.totalAmount);\n balance.availableAmount.should.equal(balance.totalAmount - balance.lockedAmount);\n server.storage.fetchAddresses(wallet.id, function(err, addresses) {\n should.not.exist(err);\n var change = _.filter(addresses, {\n isChange: true\n });\n change.length.should.equal(1);\n done();\n });\n });\n });\n });\n });\n });\n\n it('should create a tx with legacy signature', function(done) {\n helpers.stubUtxos(server, wallet, [100, 200], function() {\n var txOpts = helpers.createProposalOptsLegacy('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 80, 'some message', TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n should.exist(tx);\n done();\n });\n });\n });\n\n it('should create a tx using confirmed utxos first', function(done) {\n helpers.stubUtxos(server, wallet, [1.3, 'u0.5', 'u0.1', 1.2], function(utxos) {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 1.5, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n should.exist(tx);\n tx.inputs.length.should.equal(2);\n _.difference(_.pluck(tx.inputs, 'txid'), [utxos[0].txid, utxos[3].txid]).length.should.equal(0);\n done();\n });\n });\n });\n\n it('should use unconfirmed utxos only when no more confirmed utxos are available', function(done) {\n helpers.stubUtxos(server, wallet, [1.3, 'u0.5', 'u0.1', 1.2], function(utxos) {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 2.55, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n should.exist(tx);\n tx.inputs.length.should.equal(3);\n var txids = _.pluck(tx.inputs, 'txid');\n txids.should.contain(utxos[0].txid);\n txids.should.contain(utxos[3].txid);\n done();\n });\n });\n });\n\n it('should exclude unconfirmed utxos if specified', function(done) {\n helpers.stubUtxos(server, wallet, [1.3, 'u2', 'u0.1', 1.2], function(utxos) {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 3, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n txOpts.excludeUnconfirmedUtxos = true;\n server.createTx(txOpts, function(err, tx) {\n should.exist(err);\n err.code.should.equal('INSUFFICIENT_FUNDS');\n err.message.should.equal('Insufficient funds');\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 2.5, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n txOpts.excludeUnconfirmedUtxos = true;\n server.createTx(txOpts, function(err, tx) {\n should.exist(err);\n err.code.should.equal('INSUFFICIENT_FUNDS_FOR_FEE');\n err.message.should.equal('Insufficient funds for fee');\n done();\n });\n });\n });\n });\n\n it('should use non-locked confirmed utxos when specified', function(done) {\n helpers.stubUtxos(server, wallet, [1.3, 'u2', 'u0.1', 1.2], function(utxos) {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 1.4, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n txOpts.excludeUnconfirmedUtxos = true;\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n should.exist(tx);\n tx.inputs.length.should.equal(2);\n server.getBalance({}, function(err, balance) {\n should.not.exist(err);\n balance.lockedConfirmedAmount.should.equal(helpers.toSatoshi(2.5));\n balance.availableConfirmedAmount.should.equal(0);\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 0.01, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n txOpts.excludeUnconfirmedUtxos = true;\n server.createTx(txOpts, function(err, tx) {\n should.exist(err);\n err.code.should.equal('LOCKED_FUNDS');\n done();\n });\n });\n });\n });\n });\n\n it('should fail gracefully if unable to reach the blockchain', function(done) {\n blockchainExplorer.getUnspentUtxos = sinon.stub().callsArgWith(1, 'dummy error');\n server.createAddress({}, function(err, address) {\n should.not.exist(err);\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 80, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n server.createTx(txOpts, function(err, tx) {\n should.exist(err);\n err.toString().should.equal('dummy error');\n done();\n });\n });\n });\n\n it('should fail to create tx with invalid proposal signature', function(done) {\n helpers.stubUtxos(server, wallet, [100, 200], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 80, 'dummy');\n\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(tx);\n should.exist(err);\n err.message.should.equal('Invalid proposal signature');\n done();\n });\n });\n });\n\n it('should fail to create tx with proposal signed by another copayer', function(done) {\n helpers.stubUtxos(server, wallet, [100, 200], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 80, TestData.copayers[1].privKey_1H_0);\n\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(tx);\n should.exist(err);\n err.message.should.equal('Invalid proposal signature');\n done();\n });\n });\n });\n\n it('should fail to create tx for invalid address', function(done) {\n helpers.stubUtxos(server, wallet, [100, 200], function() {\n var txOpts = helpers.createSimpleProposalOpts('invalid address', 80, TestData.copayers[0].privKey_1H_0);\n\n server.createTx(txOpts, function(err, tx) {\n should.exist(err);\n should.not.exist(tx);\n // may fail due to Non-base58 character, or Checksum mismatch, or other\n done();\n });\n });\n });\n\n it('should fail to create tx for address of different network', function(done) {\n helpers.stubUtxos(server, wallet, [100, 200], function() {\n var txOpts = helpers.createSimpleProposalOpts('myE38JHdxmQcTJGP1ZiX4BiGhDxMJDvLJD', 80, TestData.copayers[0].privKey_1H_0);\n\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(tx);\n should.exist(err);\n err.code.should.equal('INCORRECT_ADDRESS_NETWORK');\n err.message.should.equal('Incorrect address network');\n done();\n });\n });\n });\n\n it('should fail to create tx for invalid amount', function(done) {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 0, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(tx);\n should.exist(err);\n err.message.should.equal('Invalid amount');\n done();\n });\n });\n\n it('should fail to create tx when insufficient funds', function(done) {\n helpers.stubUtxos(server, wallet, [100], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 120, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n should.exist(err);\n err.code.should.equal('INSUFFICIENT_FUNDS');\n err.message.should.equal('Insufficient funds');\n server.getPendingTxs({}, function(err, txs) {\n should.not.exist(err);\n txs.length.should.equal(0);\n server.getBalance({}, function(err, balance) {\n should.not.exist(err);\n balance.lockedAmount.should.equal(0);\n balance.totalAmount.should.equal(10000000000);\n done();\n });\n });\n });\n });\n });\n\n it('should fail to create tx when insufficient funds for fee', function(done) {\n helpers.stubUtxos(server, wallet, 0.048222, function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 0.048200, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n should.exist(err);\n err.code.should.equal('INSUFFICIENT_FUNDS_FOR_FEE');\n err.message.should.equal('Insufficient funds for fee');\n done();\n });\n });\n });\n\n it('should scale fees according to tx size', function(done) {\n helpers.stubUtxos(server, wallet, [1, 1, 1, 1], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 3.5, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n var estimatedFee = WalletUtils.DEFAULT_FEE_PER_KB * 1300 / 1000; // fully signed tx should have about 1300 bytes\n tx.fee.should.be.within(0.9 * estimatedFee, 1.1 * estimatedFee);\n done();\n });\n });\n });\n\n it('should be possible to use a smaller fee', function(done) {\n helpers.stubUtxos(server, wallet, 1, function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 0.99995, TestData.copayers[0].privKey_1H_0, {\n feePerKb: 80000\n });\n server.createTx(txOpts, function(err, tx) {\n should.exist(err);\n err.code.should.equal('INSUFFICIENT_FUNDS_FOR_FEE');\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 0.99995, TestData.copayers[0].privKey_1H_0, {\n feePerKb: 5000\n });\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n var estimatedFee = 5000 * 400 / 1000; // fully signed tx should have about 400 bytes\n tx.fee.should.be.within(0.9 * estimatedFee, 1.1 * estimatedFee);\n\n // Sign it to make sure Bitcore doesn't complain about the fees\n var signatures = helpers.clientSign(tx, TestData.copayers[0].xPrivKey);\n server.signTx({\n txProposalId: tx.id,\n signatures: signatures,\n }, function(err) {\n should.not.exist(err);\n done();\n });\n });\n });\n });\n });\n\n it('should fail to create tx for dust amount', function(done) {\n helpers.stubUtxos(server, wallet, [1], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 0.00000001, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n should.exist(err);\n err.code.should.equal('DUST_AMOUNT');\n err.message.should.equal('Amount below dust threshold');\n done();\n });\n });\n });\n\n it('should fail to create tx that would return change for dust amount', function(done) {\n helpers.stubUtxos(server, wallet, [1], function() {\n var fee = 4095 / 1e8; // The exact fee of the resulting tx\n var change = 100 / 1e8; // Below dust\n var amount = 1 - fee - change;\n\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', amount, TestData.copayers[0].privKey_1H_0, {\n feePerKb: 10000\n });\n server.createTx(txOpts, function(err, tx) {\n should.exist(err);\n err.code.should.equal('DUST_AMOUNT');\n err.message.should.equal('Amount below dust threshold');\n done();\n });\n });\n });\n\n it('should fail with different error for insufficient funds and locked funds', function(done) {\n helpers.stubUtxos(server, wallet, [10, 10], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 11, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n server.getBalance({}, function(err, balance) {\n should.not.exist(err);\n balance.totalAmount.should.equal(helpers.toSatoshi(20));\n balance.lockedAmount.should.equal(helpers.toSatoshi(20));\n txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 8, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n should.exist(err);\n err.code.should.equal('LOCKED_FUNDS');\n err.message.should.equal('Funds are locked by pending transaction proposals');\n done();\n });\n });\n });\n });\n });\n\n it('should create tx with 0 change output', function(done) {\n helpers.stubUtxos(server, wallet, [1], function() {\n var fee = 4100 / 1e8; // The exact fee of the resulting tx\n var amount = 1 - fee;\n\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', amount, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n should.exist(tx);\n var bitcoreTx = tx.getBitcoreTx();\n bitcoreTx.outputs.length.should.equal(1);\n bitcoreTx.outputs[0].satoshis.should.equal(tx.amount);\n done();\n });\n });\n });\n\n it('should fail gracefully when bitcore throws exception on raw tx creation', function(done) {\n helpers.stubUtxos(server, wallet, [10], function() {\n var bitcoreStub = sinon.stub(Bitcore, 'Transaction');\n bitcoreStub.throws({\n name: 'dummy',\n message: 'dummy exception'\n });\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 2, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n should.exist(err);\n err.message.should.equal('dummy exception');\n bitcoreStub.restore();\n done();\n });\n });\n });\n\n it('should create tx when there is a pending tx and enough UTXOs', function(done) {\n helpers.stubUtxos(server, wallet, [10.1, 10.2, 10.3], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 12, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n should.exist(tx);\n var txOpts2 = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 8, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts2, function(err, tx) {\n should.not.exist(err);\n should.exist(tx);\n server.getPendingTxs({}, function(err, txs) {\n should.not.exist(err);\n txs.length.should.equal(2);\n server.getBalance({}, function(err, balance) {\n should.not.exist(err);\n balance.totalAmount.should.equal(3060000000);\n balance.lockedAmount.should.equal(3060000000);\n done();\n });\n });\n });\n });\n });\n });\n\n it('should fail to create tx when there is a pending tx and not enough UTXOs', function(done) {\n helpers.stubUtxos(server, wallet, [10.1, 10.2, 10.3], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 12, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n should.exist(tx);\n var txOpts2 = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 24, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts2, function(err, tx) {\n err.code.should.equal('LOCKED_FUNDS');\n should.not.exist(tx);\n server.getPendingTxs({}, function(err, txs) {\n should.not.exist(err);\n txs.length.should.equal(1);\n server.getBalance({}, function(err, balance) {\n should.not.exist(err);\n balance.totalAmount.should.equal(helpers.toSatoshi(30.6));\n var amountInputs = _.sum(txs[0].inputs, 'satoshis');\n balance.lockedAmount.should.equal(amountInputs);\n balance.lockedAmount.should.be.below(balance.totalAmount);\n balance.availableAmount.should.equal(balance.totalAmount - balance.lockedAmount);\n done();\n });\n });\n });\n });\n });\n });\n\n it('should create tx using different UTXOs for simultaneous requests', function(done) {\n var N = 5;\n helpers.stubUtxos(server, wallet, _.range(100, 100 + N, 0), function(utxos) {\n server.getBalance({}, function(err, balance) {\n should.not.exist(err);\n balance.totalAmount.should.equal(helpers.toSatoshi(N * 100));\n balance.lockedAmount.should.equal(0);\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 80, TestData.copayers[0].privKey_1H_0);\n async.map(_.range(N), function(i, cb) {\n server.createTx(txOpts, function(err, tx) {\n cb(err, tx);\n });\n }, function(err) {\n server.getPendingTxs({}, function(err, txs) {\n should.not.exist(err);\n txs.length.should.equal(N);\n _.uniq(_.pluck(txs, 'changeAddress')).length.should.equal(N);\n server.getBalance({}, function(err, balance) {\n should.not.exist(err);\n balance.totalAmount.should.equal(helpers.toSatoshi(N * 100));\n balance.lockedAmount.should.equal(balance.totalAmount);\n done();\n });\n });\n });\n });\n });\n });\n\n it('should create tx for type multiple_outputs', function(done) {\n helpers.stubUtxos(server, wallet, [100, 200], function() {\n var outputs = [{\n toAddress: '18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7',\n amount: 75,\n message: 'message #1'\n }, {\n toAddress: '18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7',\n amount: 75,\n message: 'message #2'\n }];\n var txOpts = helpers.createProposalOpts(Model.TxProposal.Types.MULTIPLEOUTPUTS, outputs, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n should.exist(tx);\n done();\n });\n });\n });\n\n it('should fail to create tx for type multiple_outputs with missing output argument', function(done) {\n helpers.stubUtxos(server, wallet, [100, 200], function() {\n var outputs = [{\n amount: 80,\n message: 'message #1',\n }, {\n toAddress: '18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7',\n amount: 90,\n message: 'message #2'\n }];\n var txOpts = helpers.createProposalOpts(Model.TxProposal.Types.MULTIPLEOUTPUTS, outputs, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n server.createTx(txOpts, function(err, tx) {\n should.exist(err);\n err.message.should.contain('outputs argument missing');\n done();\n });\n });\n });\n\n it('should fail to create tx for unsupported proposal type', function(done) {\n helpers.stubUtxos(server, wallet, [100, 200], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 80, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n txOpts.type = 'bogus';\n server.createTx(txOpts, function(err, tx) {\n should.exist(err);\n err.message.should.contain('Invalid proposal type');\n done();\n });\n });\n });\n\n it('should be able to send max amount', function(done) {\n helpers.stubUtxos(server, wallet, _.range(1, 10, 0), function() {\n server.getBalance({}, function(err, balance) {\n should.not.exist(err);\n balance.totalAmount.should.equal(helpers.toSatoshi(9));\n balance.lockedAmount.should.equal(0);\n balance.availableAmount.should.equal(helpers.toSatoshi(9));\n balance.totalBytesToSendMax.should.equal(2896);\n var fee = parseInt((balance.totalBytesToSendMax * 10000 / 1000).toFixed(0));\n var max = balance.availableAmount - fee;\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', max / 1e8, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n should.exist(tx);\n tx.amount.should.equal(max);\n var estimatedFee = 2896 * 10000 / 1000;\n tx.fee.should.be.within(0.9 * estimatedFee, 1.1 * estimatedFee);\n server.getBalance({}, function(err, balance) {\n should.not.exist(err);\n balance.lockedAmount.should.equal(helpers.toSatoshi(9));\n balance.availableAmount.should.equal(0);\n done();\n });\n });\n });\n });\n });\n it('should be able to send max non-locked amount', function(done) {\n helpers.stubUtxos(server, wallet, _.range(1, 10, 0), function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 3.5, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n server.getBalance({}, function(err, balance) {\n should.not.exist(err);\n balance.totalAmount.should.equal(helpers.toSatoshi(9));\n balance.lockedAmount.should.equal(helpers.toSatoshi(4));\n balance.availableAmount.should.equal(helpers.toSatoshi(5));\n balance.totalBytesToSendMax.should.equal(1653);\n var fee = parseInt((balance.totalBytesToSendMax * 2000 / 1000).toFixed(0));\n var max = balance.availableAmount - fee;\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', max / 1e8, TestData.copayers[0].privKey_1H_0, {\n feePerKb: 2000\n });\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n should.exist(tx);\n tx.amount.should.equal(max);\n var estimatedFee = 1653 * 2000 / 1000;\n tx.fee.should.be.within(0.9 * estimatedFee, 1.1 * estimatedFee);\n server.getBalance({}, function(err, balance) {\n should.not.exist(err);\n balance.lockedAmount.should.equal(helpers.toSatoshi(9));\n done();\n });\n });\n });\n });\n });\n });\n it('should not use UTXO provided in utxosToExclude option', function(done) {\n helpers.stubUtxos(server, wallet, [1, 2, 3], function(utxos) {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 4.5, TestData.copayers[0].privKey_1H_0);\n txOpts.utxosToExclude = [utxos[1].txid + ':' + utxos[1].vout];\n server.createTx(txOpts, function(err, tx) {\n should.exist(err);\n err.code.should.equal('INSUFFICIENT_FUNDS');\n err.message.should.equal('Insufficient funds');\n done();\n });\n });\n });\n it('should use non-excluded UTXOs', function(done) {\n helpers.stubUtxos(server, wallet, [1, 2], function(utxos) {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 0.5, TestData.copayers[0].privKey_1H_0);\n txOpts.utxosToExclude = [utxos[0].txid + ':' + utxos[0].vout];\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n tx.inputs.length.should.equal(1);\n tx.inputs[0].txid.should.equal(utxos[1].txid);\n tx.inputs[0].vout.should.equal(utxos[1].vout);\n done();\n });\n });\n });\n });\n\n describe('#createTx backoff time', function(done) {\n var server, wallet, txid;\n\n beforeEach(function(done) {\n helpers.createAndJoinWallet(2, 2, function(s, w) {\n server = s;\n wallet = w;\n helpers.stubUtxos(server, wallet, _.range(2, 6), function() {\n done();\n });\n });\n });\n\n it('should follow backoff time after consecutive rejections', function(done) {\n async.series([\n\n function(next) {\n async.each(_.range(3), function(i, next) {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 1, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n server.rejectTx({\n txProposalId: tx.id,\n reason: 'some reason',\n }, next);\n });\n },\n next);\n },\n function(next) {\n // Allow a 4th tx\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 1, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n server.rejectTx({\n txProposalId: tx.id,\n reason: 'some reason',\n }, next);\n });\n },\n function(next) {\n // Do not allow before backoff time\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 1, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n should.exist(err);\n err.code.should.equal('TX_CANNOT_CREATE');\n next();\n });\n },\n function(next) {\n var clock = sinon.useFakeTimers(Date.now() + (WalletService.BACKOFF_TIME + 2) * 60 * 1000, 'Date');\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 1, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n clock.restore();\n server.rejectTx({\n txProposalId: tx.id,\n reason: 'some reason',\n }, next);\n });\n },\n function(next) {\n // Do not allow a 5th tx before backoff time\n var clock = sinon.useFakeTimers(Date.now() + (WalletService.BACKOFF_TIME + 2) * 60 * 1000 + 1, 'Date');\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 1, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n clock.restore();\n should.exist(err);\n err.code.should.equal('TX_CANNOT_CREATE');\n next();\n });\n },\n ], function(err) {\n should.not.exist(err);\n done();\n });\n });\n });\n\n describe('#rejectTx', function() {\n var server, wallet, txid;\n\n beforeEach(function(done) {\n helpers.createAndJoinWallet(2, 2, function(s, w) {\n server = s;\n wallet = w;\n helpers.stubUtxos(server, wallet, _.range(1, 9), function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 10, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n should.exist(tx);\n txid = tx.id;\n done();\n });\n });\n });\n });\n\n it('should reject a TX', function(done) {\n server.getPendingTxs({}, function(err, txs) {\n var tx = txs[0];\n tx.id.should.equal(txid);\n\n server.rejectTx({\n txProposalId: txid,\n reason: 'some reason',\n }, function(err) {\n should.not.exist(err);\n server.getPendingTxs({}, function(err, txs) {\n should.not.exist(err);\n txs.should.be.empty;\n server.getTx({\n txProposalId: txid\n }, function(err, tx) {\n var actors = tx.getActors();\n actors.length.should.equal(1);\n actors[0].should.equal(wallet.copayers[0].id);\n var action = tx.getActionBy(wallet.copayers[0].id);\n action.type.should.equal('reject');\n action.comment.should.equal('some reason');\n done();\n });\n });\n });\n });\n });\n\n it('should fail to reject non-pending TX', function(done) {\n async.waterfall([\n\n function(next) {\n server.getPendingTxs({}, function(err, txs) {\n var tx = txs[0];\n tx.id.should.equal(txid);\n next();\n });\n },\n function(next) {\n server.rejectTx({\n txProposalId: txid,\n reason: 'some reason',\n }, function(err) {\n should.not.exist(err);\n next();\n });\n },\n function(next) {\n server.getPendingTxs({}, function(err, txs) {\n should.not.exist(err);\n txs.should.be.empty;\n next();\n });\n },\n function(next) {\n helpers.getAuthServer(wallet.copayers[1].id, function(server) {\n server.rejectTx({\n txProposalId: txid,\n reason: 'some other reason',\n }, function(err) {\n should.exist(err);\n err.code.should.equal('TX_NOT_PENDING');\n done();\n });\n });\n },\n ]);\n });\n });\n\n describe('#signTx', function() {\n describe('1-of-1 (BIP44 & P2PKH)', function() {\n var server, wallet, txid;\n\n beforeEach(function(done) {\n helpers.createAndJoinWallet(1, 1, function(s, w) {\n server = s;\n wallet = w;\n helpers.stubUtxos(server, wallet, [1, 2], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 2.5, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n should.exist(tx);\n tx.derivationStrategy.should.equal('BIP44');\n tx.addressType.should.equal('P2PKH');\n txid = tx.id;\n done();\n });\n });\n });\n });\n\n it('should sign a TX with multiple inputs, different paths, and return raw', function(done) {\n blockchainExplorer.getTransaction = sinon.stub().callsArgWith(1, null, null);\n server.getPendingTxs({}, function(err, txs) {\n var tx = txs[0];\n tx.id.should.equal(txid);\n var signatures = helpers.clientSign(tx, TestData.copayers[0].xPrivKey);\n should.not.exist(tx.raw);\n server.signTx({\n txProposalId: txid,\n signatures: signatures,\n }, function(err, txp) {\n should.not.exist(err);\n txp.status.should.equal('accepted');\n // The raw Tx should contain the Signatures.\n txp.raw.should.contain(signatures[0]);\n\n // Get pending should also contains the raw TX\n server.getPendingTxs({}, function(err, txs) {\n var tx = txs[0];\n should.not.exist(err);\n tx.status.should.equal('accepted');\n tx.raw.should.contain(signatures[0]);\n done();\n });\n });\n });\n });\n });\n\n describe('Multisig', function() {\n var server, wallet, txid;\n\n beforeEach(function(done) {\n helpers.createAndJoinWallet(2, 3, function(s, w) {\n server = s;\n wallet = w;\n helpers.stubUtxos(server, wallet, _.range(1, 9), function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 20, TestData.copayers[0].privKey_1H_0);\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n should.exist(tx);\n txid = tx.id;\n done();\n });\n });\n });\n });\n\n it('should sign a TX with multiple inputs, different paths', function(done) {\n server.getPendingTxs({}, function(err, txs) {\n var tx = txs[0];\n tx.id.should.equal(txid);\n\n var signatures = helpers.clientSign(tx, TestData.copayers[0].xPrivKey);\n server.signTx({\n txProposalId: txid,\n signatures: signatures,\n }, function(err, txp) {\n should.not.exist(err);\n should.not.exist(tx.raw);\n server.getPendingTxs({}, function(err, txs) {\n should.not.exist(err);\n var tx = txs[0];\n tx.id.should.equal(txid);\n\n var actors = tx.getActors();\n actors.length.should.equal(1);\n actors[0].should.equal(wallet.copayers[0].id);\n tx.getActionBy(wallet.copayers[0].id).type.should.equal('accept');\n\n done();\n });\n });\n });\n });\n\n it('should fail to sign with a xpriv from other copayer', function(done) {\n server.getPendingTxs({}, function(err, txs) {\n var tx = txs[0];\n tx.id.should.equal(txid);\n var signatures = helpers.clientSign(tx, TestData.copayers[1].xPrivKey);\n server.signTx({\n txProposalId: txid,\n signatures: signatures,\n }, function(err) {\n err.code.should.equal('BAD_SIGNATURES');\n done();\n });\n });\n });\n\n it('should fail if one signature is broken', function(done) {\n server.getPendingTxs({}, function(err, txs) {\n var tx = txs[0];\n tx.id.should.equal(txid);\n\n var signatures = helpers.clientSign(tx, TestData.copayers[0].xPrivKey);\n signatures[0] = 1;\n\n server.signTx({\n txProposalId: txid,\n signatures: signatures,\n }, function(err) {\n err.message.should.contain('signatures');\n done();\n });\n });\n });\n\n it('should fail on invalid signature', function(done) {\n server.getPendingTxs({}, function(err, txs) {\n var tx = txs[0];\n tx.id.should.equal(txid);\n\n var signatures = ['11', '22', '33', '44', '55'];\n server.signTx({\n txProposalId: txid,\n signatures: signatures,\n }, function(err) {\n should.exist(err);\n err.message.should.contain('Bad signatures');\n done();\n });\n });\n });\n\n it('should fail on wrong number of invalid signatures', function(done) {\n server.getPendingTxs({}, function(err, txs) {\n var tx = txs[0];\n tx.id.should.equal(txid);\n\n var signatures = _.take(helpers.clientSign(tx, TestData.copayers[0].xPrivKey), tx.inputs.length - 1);\n server.signTx({\n txProposalId: txid,\n signatures: signatures,\n }, function(err) {\n should.exist(err);\n err.message.should.contain('Bad signatures');\n done();\n });\n });\n });\n\n it('should fail when signing a TX previously rejected', function(done) {\n server.getPendingTxs({}, function(err, txs) {\n var tx = txs[0];\n tx.id.should.equal(txid);\n\n var signatures = helpers.clientSign(tx, TestData.copayers[0].xPrivKey);\n server.signTx({\n txProposalId: txid,\n signatures: signatures,\n }, function(err) {\n server.rejectTx({\n txProposalId: txid,\n }, function(err) {\n err.code.should.contain('COPAYER_VOTED');\n done();\n });\n });\n });\n });\n\n it('should fail when rejected a previously signed TX', function(done) {\n server.getPendingTxs({}, function(err, txs) {\n var tx = txs[0];\n tx.id.should.equal(txid);\n\n server.rejectTx({\n txProposalId: txid,\n }, function(err) {\n var signatures = helpers.clientSign(tx, TestData.copayers[0].xPrivKey);\n server.signTx({\n txProposalId: txid,\n signatures: signatures,\n }, function(err) {\n err.code.should.contain('COPAYER_VOTED');\n done();\n });\n });\n });\n });\n\n it('should fail to sign a non-pending TX', function(done) {\n async.waterfall([\n\n function(next) {\n server.rejectTx({\n txProposalId: txid,\n reason: 'some reason',\n }, function(err) {\n should.not.exist(err);\n next();\n });\n },\n function(next) {\n helpers.getAuthServer(wallet.copayers[1].id, function(server) {\n server.rejectTx({\n txProposalId: txid,\n reason: 'some reason',\n }, function(err) {\n should.not.exist(err);\n next();\n });\n });\n },\n function(next) {\n server.getPendingTxs({}, function(err, txs) {\n should.not.exist(err);\n txs.should.be.empty;\n next();\n });\n },\n function(next) {\n helpers.getAuthServer(wallet.copayers[2].id, function(server) {\n server.getTx({\n txProposalId: txid\n }, function(err, tx) {\n should.not.exist(err);\n var signatures = helpers.clientSign(tx, TestData.copayers[2].xPrivKey);\n server.signTx({\n txProposalId: txid,\n signatures: signatures,\n }, function(err) {\n should.exist(err);\n err.code.should.equal('TX_NOT_PENDING');\n done();\n });\n });\n });\n },\n ]);\n });\n });\n });\n\n describe('#broadcastTx & #broadcastRawTx', function() {\n var server, wallet, txpid, txid;\n beforeEach(function(done) {\n helpers.createAndJoinWallet(1, 1, function(s, w) {\n server = s;\n wallet = w;\n helpers.stubUtxos(server, wallet, [10, 10], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 9, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n server.createTx(txOpts, function(err, txp) {\n should.not.exist(err);\n should.exist(txp);\n var signatures = helpers.clientSign(txp, TestData.copayers[0].xPrivKey);\n server.signTx({\n txProposalId: txp.id,\n signatures: signatures,\n }, function(err, txp) {\n should.not.exist(err);\n should.exist(txp);\n txp.isAccepted().should.be.true;\n txp.isBroadcasted().should.be.false;\n txid = txp.txid;\n txpid = txp.id;\n done();\n });\n });\n });\n });\n });\n\n it('should broadcast a tx', function(done) {\n var clock = sinon.useFakeTimers(1234000, 'Date');\n helpers.stubBroadcast();\n server.broadcastTx({\n txProposalId: txpid\n }, function(err) {\n should.not.exist(err);\n server.getTx({\n txProposalId: txpid\n }, function(err, txp) {\n should.not.exist(err);\n should.not.exist(txp.raw);\n txp.txid.should.equal(txid);\n txp.isBroadcasted().should.be.true;\n txp.broadcastedOn.should.equal(1234);\n clock.restore();\n done();\n });\n });\n });\n\n it('should broadcast a raw tx', function(done) {\n helpers.stubBroadcast();\n server.broadcastRawTx({\n network: 'testnet',\n rawTx: 'raw tx',\n }, function(err, txid) {\n should.not.exist(err);\n should.exist(txid);\n done();\n });\n });\n\n it('should fail to brodcast a tx already marked as broadcasted', function(done) {\n helpers.stubBroadcast();\n server.broadcastTx({\n txProposalId: txpid\n }, function(err) {\n should.not.exist(err);\n server.broadcastTx({\n txProposalId: txpid\n }, function(err) {\n should.exist(err);\n err.code.should.equal('TX_ALREADY_BROADCASTED');\n done();\n });\n });\n });\n\n it('should auto process already broadcasted txs', function(done) {\n helpers.stubBroadcast();\n server.getPendingTxs({}, function(err, txs) {\n should.not.exist(err);\n txs.length.should.equal(1);\n blockchainExplorer.getTransaction = sinon.stub().callsArgWith(1, null, {\n txid: 999\n });\n server.getPendingTxs({}, function(err, txs) {\n should.not.exist(err);\n txs.length.should.equal(0);\n done();\n });\n });\n });\n\n it('should process only broadcasted txs', function(done) {\n helpers.stubBroadcast();\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 9, TestData.copayers[0].privKey_1H_0, {\n message: 'some message 2'\n });\n server.createTx(txOpts, function(err, txp) {\n should.not.exist(err);\n server.getPendingTxs({}, function(err, txs) {\n should.not.exist(err);\n txs.length.should.equal(2);\n blockchainExplorer.getTransaction = sinon.stub().callsArgWith(1, null, {\n txid: 999\n });\n server.getPendingTxs({}, function(err, txs) {\n should.not.exist(err);\n txs.length.should.equal(1);\n txs[0].status.should.equal('pending');\n should.not.exist(txs[0].txid);\n done();\n });\n });\n });\n });\n\n\n\n\n\n it('should fail to brodcast a not yet accepted tx', function(done) {\n helpers.stubBroadcast();\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 9, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n server.createTx(txOpts, function(err, txp) {\n should.not.exist(err);\n should.exist(txp);\n server.broadcastTx({\n txProposalId: txp.id\n }, function(err) {\n should.exist(err);\n err.code.should.equal('TX_NOT_ACCEPTED');\n done();\n });\n });\n });\n\n it('should keep tx as accepted if unable to broadcast it', function(done) {\n blockchainExplorer.broadcast = sinon.stub().callsArgWith(1, 'broadcast error');\n blockchainExplorer.getTransaction = sinon.stub().callsArgWith(1, null, null);\n server.broadcastTx({\n txProposalId: txpid\n }, function(err) {\n should.exist(err);\n err.toString().should.equal('broadcast error');\n server.getTx({\n txProposalId: txpid\n }, function(err, txp) {\n should.not.exist(err);\n should.exist(txp.txid);\n txp.isBroadcasted().should.be.false;\n should.not.exist(txp.broadcastedOn);\n txp.isAccepted().should.be.true;\n done();\n });\n });\n });\n\n it('should mark tx as broadcasted if accepted but already in blockchain', function(done) {\n blockchainExplorer.broadcast = sinon.stub().callsArgWith(1, 'broadcast error');\n blockchainExplorer.getTransaction = sinon.stub().callsArgWith(1, null, {\n txid: '999'\n });\n server.broadcastTx({\n txProposalId: txpid\n }, function(err) {\n should.not.exist(err);\n server.getTx({\n txProposalId: txpid\n }, function(err, txp) {\n should.not.exist(err);\n should.exist(txp.txid);\n txp.isBroadcasted().should.be.true;\n should.exist(txp.broadcastedOn);\n done();\n });\n });\n });\n\n it('should keep tx as accepted if broadcast fails and cannot check tx in blockchain', function(done) {\n blockchainExplorer.broadcast = sinon.stub().callsArgWith(1, 'broadcast error');\n blockchainExplorer.getTransaction = sinon.stub().callsArgWith(1, 'bc check error');\n server.broadcastTx({\n txProposalId: txpid\n }, function(err) {\n should.exist(err);\n err.toString().should.equal('bc check error');\n server.getTx({\n txProposalId: txpid\n }, function(err, txp) {\n should.not.exist(err);\n should.exist(txp.txid);\n txp.isBroadcasted().should.be.false;\n should.not.exist(txp.broadcastedOn);\n txp.isAccepted().should.be.true;\n done();\n });\n });\n });\n });\n\n describe('Tx proposal workflow', function() {\n var server, wallet;\n beforeEach(function(done) {\n helpers.createAndJoinWallet(2, 3, function(s, w) {\n server = s;\n wallet = w;\n helpers.stubUtxos(server, wallet, _.range(1, 9), function() {\n helpers.stubBroadcast();\n done();\n });\n });\n });\n\n it('other copayers should see pending proposal created by one copayer', function(done) {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 10, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n server.createTx(txOpts, function(err, txp) {\n should.not.exist(err);\n should.exist(txp);\n helpers.getAuthServer(wallet.copayers[1].id, function(server2, wallet) {\n server2.getPendingTxs({}, function(err, txps) {\n should.not.exist(err);\n txps.length.should.equal(1);\n txps[0].id.should.equal(txp.id);\n txps[0].message.should.equal('some message');\n done();\n });\n });\n });\n });\n\n it('tx proposals should not be finally accepted until quorum is reached', function(done) {\n var txpId;\n async.waterfall([\n\n function(next) {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 10, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n server.createTx(txOpts, function(err, txp) {\n txpId = txp.id;\n should.not.exist(err);\n should.exist(txp);\n next();\n });\n },\n function(next) {\n server.getPendingTxs({}, function(err, txps) {\n should.not.exist(err);\n txps.length.should.equal(1);\n var txp = txps[0];\n txp.actions.should.be.empty;\n next(null, txp);\n });\n },\n function(txp, next) {\n var signatures = helpers.clientSign(txp, TestData.copayers[0].xPrivKey);\n server.signTx({\n txProposalId: txpId,\n signatures: signatures,\n }, function(err) {\n should.not.exist(err);\n next();\n });\n },\n function(next) {\n server.getPendingTxs({}, function(err, txps) {\n should.not.exist(err);\n txps.length.should.equal(1);\n var txp = txps[0];\n txp.isPending().should.be.true;\n txp.isAccepted().should.be.false;\n txp.isRejected().should.be.false;\n txp.isBroadcasted().should.be.false;\n txp.actions.length.should.equal(1);\n var action = txp.getActionBy(wallet.copayers[0].id);\n action.type.should.equal('accept');\n server.getNotifications({}, function(err, notifications) {\n should.not.exist(err);\n var last = _.last(notifications);\n last.type.should.not.equal('TxProposalFinallyAccepted');\n next(null, txp);\n });\n });\n },\n function(txp, next) {\n helpers.getAuthServer(wallet.copayers[1].id, function(server, wallet) {\n var signatures = helpers.clientSign(txp, TestData.copayers[1].xPrivKey);\n server.signTx({\n txProposalId: txpId,\n signatures: signatures,\n }, function(err) {\n should.not.exist(err);\n next();\n });\n });\n },\n function(next) {\n server.getPendingTxs({}, function(err, txps) {\n should.not.exist(err);\n txps.length.should.equal(1);\n var txp = txps[0];\n txp.isPending().should.be.true;\n txp.isAccepted().should.be.true;\n txp.isBroadcasted().should.be.false;\n should.exist(txp.txid);\n txp.actions.length.should.equal(2);\n server.getNotifications({}, function(err, notifications) {\n should.not.exist(err);\n var last = _.last(notifications);\n last.type.should.equal('TxProposalFinallyAccepted');\n last.walletId.should.equal(wallet.id);\n last.creatorId.should.equal(wallet.copayers[1].id);\n last.data.txProposalId.should.equal(txp.id);\n done();\n });\n });\n },\n ]);\n });\n\n it('tx proposals should accept as many rejections as possible without finally rejecting', function(done) {\n var txpId;\n async.waterfall([\n\n function(next) {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 10, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n server.createTx(txOpts, function(err, txp) {\n txpId = txp.id;\n should.not.exist(err);\n should.exist(txp);\n next();\n });\n },\n function(next) {\n server.getPendingTxs({}, function(err, txps) {\n should.not.exist(err);\n txps.length.should.equal(1);\n var txp = txps[0];\n txp.actions.should.be.empty;\n next();\n });\n },\n function(next) {\n server.rejectTx({\n txProposalId: txpId,\n reason: 'just because'\n }, function(err) {\n should.not.exist(err);\n next();\n });\n },\n function(next) {\n server.getPendingTxs({}, function(err, txps) {\n should.not.exist(err);\n txps.length.should.equal(1);\n var txp = txps[0];\n txp.isPending().should.be.true;\n txp.isRejected().should.be.false;\n txp.isAccepted().should.be.false;\n txp.actions.length.should.equal(1);\n var action = txp.getActionBy(wallet.copayers[0].id);\n action.type.should.equal('reject');\n action.comment.should.equal('just because');\n next();\n });\n },\n function(next) {\n helpers.getAuthServer(wallet.copayers[1].id, function(server, wallet) {\n server.rejectTx({\n txProposalId: txpId,\n reason: 'some other reason'\n }, function(err) {\n should.not.exist(err);\n next();\n });\n });\n },\n function(next) {\n server.getPendingTxs({}, function(err, txps) {\n should.not.exist(err);\n txps.length.should.equal(0);\n next();\n });\n },\n function(next) {\n server.getTx({\n txProposalId: txpId\n }, function(err, txp) {\n should.not.exist(err);\n txp.isPending().should.be.false;\n txp.isRejected().should.be.true;\n txp.isAccepted().should.be.false;\n txp.actions.length.should.equal(2);\n done();\n });\n },\n ]);\n });\n });\n\n describe('#getTx', function() {\n var server, wallet, txpid;\n beforeEach(function(done) {\n helpers.createAndJoinWallet(2, 3, function(s, w) {\n server = s;\n wallet = w;\n helpers.stubUtxos(server, wallet, 10, function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 9, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n server.createTx(txOpts, function(err, txp) {\n should.not.exist(err);\n should.exist(txp);\n txpid = txp.id;\n done();\n });\n });\n });\n });\n\n it('should get own transaction proposal', function(done) {\n server.getTx({\n txProposalId: txpid\n }, function(err, txp) {\n should.not.exist(err);\n should.exist(txp);\n txp.id.should.equal(txpid);\n done();\n });\n });\n it('should get someone elses transaction proposal', function(done) {\n helpers.getAuthServer(wallet.copayers[1].id, function(server2, wallet) {\n server2.getTx({\n txProposalId: txpid\n }, function(err, res) {\n should.not.exist(err);\n res.id.should.equal(txpid);\n done();\n });\n });\n\n });\n it('should fail to get non-existent transaction proposal', function(done) {\n server.getTx({\n txProposalId: 'dummy'\n }, function(err, txp) {\n should.exist(err);\n should.not.exist(txp);\n err.code.should.equal('TX_NOT_FOUND')\n err.message.should.equal('Transaction proposal not found');\n done();\n });\n });\n it.skip('should get accepted/rejected transaction proposal', function(done) {});\n it.skip('should get broadcasted transaction proposal', function(done) {});\n });\n\n describe('#getTxs', function() {\n var server, wallet, clock;\n\n beforeEach(function(done) {\n this.timeout(5000);\n clock = sinon.useFakeTimers('Date');\n helpers.createAndJoinWallet(1, 1, function(s, w) {\n server = s;\n wallet = w;\n helpers.stubUtxos(server, wallet, _.range(1, 11), function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 0.1, TestData.copayers[0].privKey_1H_0);\n async.eachSeries(_.range(10), function(i, next) {\n clock.tick(10 * 1000);\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n next();\n });\n }, function(err) {\n clock.restore();\n return done(err);\n });\n });\n });\n });\n afterEach(function() {\n clock.restore();\n });\n\n it('should pull 4 txs, down to to time 60', function(done) {\n server.getTxs({\n minTs: 60,\n limit: 8\n }, function(err, txps) {\n should.not.exist(err);\n var times = _.pluck(txps, 'createdOn');\n times.should.deep.equal([100, 90, 80, 70, 60]);\n done();\n });\n });\n\n it('should pull the first 5 txs', function(done) {\n server.getTxs({\n maxTs: 50,\n limit: 5\n }, function(err, txps) {\n should.not.exist(err);\n var times = _.pluck(txps, 'createdOn');\n times.should.deep.equal([50, 40, 30, 20, 10]);\n done();\n });\n });\n\n it('should pull the last 4 txs', function(done) {\n server.getTxs({\n limit: 4\n }, function(err, txps) {\n should.not.exist(err);\n var times = _.pluck(txps, 'createdOn');\n times.should.deep.equal([100, 90, 80, 70]);\n done();\n });\n });\n\n it('should pull all txs', function(done) {\n server.getTxs({}, function(err, txps) {\n should.not.exist(err);\n var times = _.pluck(txps, 'createdOn');\n times.should.deep.equal([100, 90, 80, 70, 60, 50, 40, 30, 20, 10]);\n done();\n });\n });\n\n\n it('should txs from times 50 to 70',\n function(done) {\n server.getTxs({\n minTs: 50,\n maxTs: 70,\n }, function(err, txps) {\n should.not.exist(err);\n var times = _.pluck(txps, 'createdOn');\n times.should.deep.equal([70, 60, 50]);\n done();\n });\n });\n });\n\n describe('#getNotifications', function() {\n var clock;\n var server, wallet;\n\n beforeEach(function(done) {\n clock = sinon.useFakeTimers(10 * 1000, 'Date');\n helpers.createAndJoinWallet(1, 1, function(s, w) {\n server = s;\n wallet = w;\n helpers.stubUtxos(server, wallet, _.range(4), function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 0.01, TestData.copayers[0].privKey_1H_0);\n async.eachSeries(_.range(3), function(i, next) {\n clock.tick(25 * 1000);\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n next();\n });\n }, function(err) {\n clock.tick(20 * 1000);\n return done(err);\n });\n });\n });\n });\n afterEach(function() {\n clock.restore();\n });\n\n it('should pull all notifications', function(done) {\n server.getNotifications({}, function(err, notifications) {\n should.not.exist(err);\n var types = _.pluck(notifications, 'type');\n types.should.deep.equal(['NewCopayer', 'NewAddress', 'NewAddress', 'NewTxProposal', 'NewTxProposal', 'NewTxProposal']);\n var walletIds = _.uniq(_.pluck(notifications, 'walletId'));\n walletIds.length.should.equal(1);\n walletIds[0].should.equal(wallet.id);\n var creators = _.uniq(_.compact(_.pluck(notifications, 'creatorId')));\n creators.length.should.equal(1);\n creators[0].should.equal(wallet.copayers[0].id);\n done();\n });\n });\n\n it('should pull new block notifications along with wallet notifications in the last 60 seconds', function(done) {\n // Simulate new block notification\n server.walletId = 'livenet';\n server._notify('NewBlock', {\n hash: 'dummy hash',\n }, {\n isGlobal: true\n }, function(err) {\n should.not.exist(err);\n server.walletId = 'testnet';\n server._notify('NewBlock', {\n hash: 'dummy hash',\n }, {\n isGlobal: true\n }, function(err) {\n should.not.exist(err);\n server.walletId = wallet.id;\n server.getNotifications({\n minTs: +Date.now() - (60 * 1000),\n }, function(err, notifications) {\n should.not.exist(err);\n var types = _.pluck(notifications, 'type');\n types.should.deep.equal(['NewTxProposal', 'NewTxProposal', 'NewBlock']);\n var walletIds = _.uniq(_.pluck(notifications, 'walletId'));\n walletIds.length.should.equal(1);\n walletIds[0].should.equal(wallet.id);\n done();\n });\n });\n });\n });\n\n it('should pull notifications in the last 60 seconds', function(done) {\n server.getNotifications({\n minTs: +Date.now() - (60 * 1000),\n }, function(err, notifications) {\n should.not.exist(err);\n var types = _.pluck(notifications, 'type');\n types.should.deep.equal(['NewTxProposal', 'NewTxProposal']);\n done();\n });\n });\n\n it('should pull notifications after a given notification id', function(done) {\n server.getNotifications({}, function(err, notifications) {\n should.not.exist(err);\n var from = _.first(_.takeRight(notifications, 2)).id; // second to last\n server.getNotifications({\n notificationId: from,\n minTs: +Date.now() - (60 * 1000),\n }, function(err, res) {\n should.not.exist(err);\n res.length.should.equal(1);\n res[0].id.should.equal(_.first(_.takeRight(notifications)).id);\n done();\n });\n });\n });\n\n it('should return empty if no notifications found after a given id', function(done) {\n server.getNotifications({}, function(err, notifications) {\n should.not.exist(err);\n var from = _.first(_.takeRight(notifications)).id; // last one\n server.getNotifications({\n notificationId: from,\n }, function(err, res) {\n should.not.exist(err);\n res.length.should.equal(0);\n done();\n });\n });\n });\n\n it('should return empty if no notifications exist in the given timespan', function(done) {\n clock.tick(100 * 1000);\n server.getNotifications({\n minTs: +Date.now() - (60 * 1000),\n }, function(err, res) {\n should.not.exist(err);\n res.length.should.equal(0);\n done();\n });\n });\n\n it('should contain walletId & creatorId on NewCopayer', function(done) {\n server.getNotifications({}, function(err, notifications) {\n should.not.exist(err);\n var newCopayer = notifications[0];\n newCopayer.type.should.equal('NewCopayer');\n newCopayer.walletId.should.equal(wallet.id);\n newCopayer.creatorId.should.equal(wallet.copayers[0].id);\n done();\n });\n });\n\n it('should notify sign and acceptance', function(done) {\n server.getPendingTxs({}, function(err, txs) {\n blockchainExplorer.broadcast = sinon.stub().callsArgWith(1, 'broadcast error');\n var tx = txs[0];\n var signatures = helpers.clientSign(tx, TestData.copayers[0].xPrivKey);\n server.signTx({\n txProposalId: tx.id,\n signatures: signatures,\n }, function(err) {\n server.getNotifications({\n minTs: Date.now(),\n }, function(err, notifications) {\n should.not.exist(err);\n notifications.length.should.equal(2);\n var types = _.pluck(notifications, 'type');\n types.should.deep.equal(['TxProposalAcceptedBy', 'TxProposalFinallyAccepted']);\n done();\n });\n });\n });\n });\n\n it('should notify rejection', function(done) {\n server.getPendingTxs({}, function(err, txs) {\n var tx = txs[1];\n server.rejectTx({\n txProposalId: tx.id,\n }, function(err) {\n should.not.exist(err);\n server.getNotifications({\n minTs: Date.now(),\n }, function(err, notifications) {\n should.not.exist(err);\n notifications.length.should.equal(2);\n var types = _.pluck(notifications, 'type');\n types.should.deep.equal(['TxProposalRejectedBy', 'TxProposalFinallyRejected']);\n done();\n });\n });\n });\n });\n\n\n it('should notify sign, acceptance, and broadcast, and emit', function(done) {\n server.getPendingTxs({}, function(err, txs) {\n var tx = txs[2];\n var signatures = helpers.clientSign(tx, TestData.copayers[0].xPrivKey);\n server.signTx({\n txProposalId: tx.id,\n signatures: signatures,\n }, function(err) {\n should.not.exist(err);\n helpers.stubBroadcast();\n server.broadcastTx({\n txProposalId: tx.id\n }, function(err, txp) {\n should.not.exist(err);\n server.getNotifications({\n minTs: Date.now(),\n }, function(err, notifications) {\n should.not.exist(err);\n notifications.length.should.equal(3);\n var types = _.pluck(notifications, 'type');\n types.should.deep.equal(['TxProposalAcceptedBy', 'TxProposalFinallyAccepted', 'NewOutgoingTx']);\n done();\n });\n });\n });\n });\n });\n\n\n it('should notify sign, acceptance, and broadcast, and emit (with 3rd party broadcast', function(done) {\n server.getPendingTxs({}, function(err, txs) {\n var tx = txs[2];\n var signatures = helpers.clientSign(tx, TestData.copayers[0].xPrivKey);\n server.signTx({\n txProposalId: tx.id,\n signatures: signatures,\n }, function(err) {\n should.not.exist(err);\n blockchainExplorer.broadcast = sinon.stub().callsArgWith(1, 'err');\n blockchainExplorer.getTransaction = sinon.stub().callsArgWith(1, null, {\n txid: 11\n });\n server.broadcastTx({\n txProposalId: tx.id\n }, function(err, txp) {\n should.not.exist(err);\n server.getNotifications({\n minTs: Date.now(),\n }, function(err, notifications) {\n should.not.exist(err);\n notifications.length.should.equal(3);\n var types = _.pluck(notifications, 'type');\n types.should.deep.equal(['TxProposalAcceptedBy', 'TxProposalFinallyAccepted', 'NewOutgoingTxByThirdParty']);\n done();\n });\n });\n });\n });\n });\n });\n\n describe('#removeWallet', function() {\n var server, wallet, clock;\n\n beforeEach(function(done) {\n helpers.createAndJoinWallet(1, 1, function(s, w) {\n server = s;\n wallet = w;\n\n helpers.stubUtxos(server, wallet, _.range(2), function() {\n var txOpts = {\n toAddress: '18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7',\n amount: helpers.toSatoshi(0.1),\n };\n async.eachSeries(_.range(2), function(i, next) {\n server.createTx(txOpts, function(err, tx) {\n next();\n });\n }, done);\n });\n });\n });\n\n it('should delete a wallet', function(done) {\n server.removeWallet({}, function(err) {\n should.not.exist(err);\n server.getWallet({}, function(err, w) {\n should.exist(err);\n err.code.should.equal('WALLET_NOT_FOUND');\n should.not.exist(w);\n async.parallel([\n\n function(next) {\n server.storage.fetchAddresses(wallet.id, function(err, items) {\n items.length.should.equal(0);\n next();\n });\n },\n function(next) {\n server.storage.fetchTxs(wallet.id, {}, function(err, items) {\n items.length.should.equal(0);\n next();\n });\n },\n function(next) {\n server.storage.fetchNotifications(wallet.id, null, 0, function(err, items) {\n items.length.should.equal(0);\n next();\n });\n },\n ], function(err) {\n should.not.exist(err);\n done();\n });\n });\n });\n });\n\n // creates 2 wallet, and deletes only 1.\n it('should delete a wallet, and only that wallet', function(done) {\n var server2, wallet2;\n async.series([\n\n function(next) {\n helpers.createAndJoinWallet(1, 1, {\n offset: 1\n }, function(s, w) {\n server2 = s;\n wallet2 = w;\n\n helpers.stubUtxos(server2, wallet2, _.range(1, 3), function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 0.1, TestData.copayers[1].privKey_1H_0, {\n message: 'some message'\n });\n async.eachSeries(_.range(2), function(i, next) {\n server2.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n next(err);\n });\n }, next);\n });\n });\n },\n function(next) {\n server.removeWallet({}, next);\n },\n function(next) {\n server.getWallet({}, function(err, wallet) {\n should.exist(err);\n err.code.should.equal('WALLET_NOT_FOUND');\n next();\n });\n },\n function(next) {\n server2.getWallet({}, function(err, wallet) {\n should.not.exist(err);\n should.exist(wallet);\n wallet.id.should.equal(wallet2.id);\n next();\n });\n },\n function(next) {\n server2.getMainAddresses({}, function(err, addresses) {\n should.not.exist(err);\n should.exist(addresses);\n addresses.length.should.above(0);\n next();\n });\n },\n function(next) {\n server2.getTxs({}, function(err, txs) {\n should.not.exist(err);\n should.exist(txs);\n txs.length.should.equal(2);\n next();\n });\n },\n function(next) {\n server2.getNotifications({}, function(err, notifications) {\n should.not.exist(err);\n should.exist(notifications);\n notifications.length.should.above(0);\n next();\n });\n },\n ], function(err) {\n should.not.exist(err);\n done();\n });\n });\n });\n\n describe('#removePendingTx', function() {\n var server, wallet, txp;\n beforeEach(function(done) {\n helpers.createAndJoinWallet(2, 3, function(s, w) {\n server = s;\n wallet = w;\n helpers.stubUtxos(server, wallet, [100, 200], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 80, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n server.createTx(txOpts, function(err, tx) {\n server.getPendingTxs({}, function(err, txs) {\n txp = txs[0];\n done();\n });\n });\n });\n });\n });\n\n\n it('should allow creator to remove an unsigned TX', function(done) {\n server.removePendingTx({\n txProposalId: txp.id\n }, function(err) {\n should.not.exist(err);\n server.getPendingTxs({}, function(err, txs) {\n txs.length.should.equal(0);\n done();\n });\n });\n });\n\n it('should allow creator to remove a signed TX by himself', function(done) {\n var signatures = helpers.clientSign(txp, TestData.copayers[0].xPrivKey);\n server.signTx({\n txProposalId: txp.id,\n signatures: signatures,\n }, function(err) {\n should.not.exist(err);\n server.removePendingTx({\n txProposalId: txp.id\n }, function(err) {\n should.not.exist(err);\n server.getPendingTxs({}, function(err, txs) {\n txs.length.should.equal(0);\n done();\n });\n });\n });\n });\n\n it('should fail to remove non-pending TX', function(done) {\n async.waterfall([\n\n function(next) {\n var signatures = helpers.clientSign(txp, TestData.copayers[0].xPrivKey);\n server.signTx({\n txProposalId: txp.id,\n signatures: signatures,\n }, function(err) {\n should.not.exist(err);\n next();\n });\n },\n function(next) {\n helpers.getAuthServer(wallet.copayers[1].id, function(server) {\n server.rejectTx({\n txProposalId: txp.id,\n }, function(err) {\n should.not.exist(err);\n next();\n });\n });\n },\n function(next) {\n helpers.getAuthServer(wallet.copayers[2].id, function(server) {\n server.rejectTx({\n txProposalId: txp.id,\n }, function(err) {\n should.not.exist(err);\n next();\n });\n });\n },\n function(next) {\n server.getPendingTxs({}, function(err, txs) {\n should.not.exist(err);\n txs.should.be.empty;\n next();\n });\n },\n function(next) {\n server.removePendingTx({\n txProposalId: txp.id\n }, function(err) {\n should.exist(err);\n err.code.should.equal('TX_NOT_PENDING');\n done();\n });\n },\n ]);\n });\n\n it('should not allow non-creator copayer to remove an unsigned TX ', function(done) {\n helpers.getAuthServer(wallet.copayers[1].id, function(server2) {\n server2.removePendingTx({\n txProposalId: txp.id\n }, function(err) {\n should.exist(err);\n err.code.should.contain('TX_CANNOT_REMOVE');\n server2.getPendingTxs({}, function(err, txs) {\n txs.length.should.equal(1);\n done();\n });\n });\n });\n });\n\n it('should not allow creator copayer to remove a TX signed by other copayer, in less than 24hrs', function(done) {\n helpers.getAuthServer(wallet.copayers[1].id, function(server2) {\n var signatures = helpers.clientSign(txp, TestData.copayers[1].xPrivKey);\n server2.signTx({\n txProposalId: txp.id,\n signatures: signatures,\n }, function(err) {\n should.not.exist(err);\n server.removePendingTx({\n txProposalId: txp.id\n }, function(err) {\n err.code.should.equal('TX_CANNOT_REMOVE');\n err.message.should.contain('Cannot remove');\n done();\n });\n });\n });\n });\n\n it('should allow creator copayer to remove a TX rejected by other copayer, in less than 24hrs', function(done) {\n helpers.getAuthServer(wallet.copayers[1].id, function(server2) {\n var signatures = helpers.clientSign(txp, TestData.copayers[1].xPrivKey);\n server2.rejectTx({\n txProposalId: txp.id,\n signatures: signatures,\n }, function(err) {\n should.not.exist(err);\n server.removePendingTx({\n txProposalId: txp.id\n }, function(err) {\n should.not.exist(err);\n done();\n });\n });\n });\n });\n\n\n\n it('should allow creator copayer to remove a TX signed by other copayer, after 24hrs', function(done) {\n helpers.getAuthServer(wallet.copayers[1].id, function(server2) {\n var signatures = helpers.clientSign(txp, TestData.copayers[1].xPrivKey);\n server2.signTx({\n txProposalId: txp.id,\n signatures: signatures,\n }, function(err) {\n should.not.exist(err);\n\n server.getPendingTxs({}, function(err, txs) {\n should.not.exist(err);\n txs[0].deleteLockTime.should.be.above(WalletService.DELETE_LOCKTIME - 10);\n\n var clock = sinon.useFakeTimers(Date.now() + 1 + 24 * 3600 * 1000, 'Date');\n server.removePendingTx({\n txProposalId: txp.id\n }, function(err) {\n should.not.exist(err);\n clock.restore();\n done();\n });\n });\n });\n });\n });\n\n\n it('should allow other copayer to remove a TX signed, after 24hrs', function(done) {\n helpers.getAuthServer(wallet.copayers[1].id, function(server2) {\n var signatures = helpers.clientSign(txp, TestData.copayers[1].xPrivKey);\n server2.signTx({\n txProposalId: txp.id,\n signatures: signatures,\n }, function(err) {\n should.not.exist(err);\n\n var clock = sinon.useFakeTimers(Date.now() + 2000 + WalletService.DELETE_LOCKTIME * 1000, 'Date');\n server2.removePendingTx({\n txProposalId: txp.id\n }, function(err) {\n should.not.exist(err);\n clock.restore();\n done();\n });\n });\n });\n });\n });\n\n describe('#getTxHistory', function() {\n var server, wallet, mainAddresses, changeAddresses;\n beforeEach(function(done) {\n helpers.createAndJoinWallet(1, 1, function(s, w) {\n server = s;\n wallet = w;\n helpers.createAddresses(server, wallet, 1, 1, function(main, change) {\n mainAddresses = main;\n changeAddresses = change;\n done();\n });\n });\n });\n\n it('should get tx history from insight', function(done) {\n helpers.stubHistory(TestData.history);\n server.getTxHistory({}, function(err, txs) {\n should.not.exist(err);\n should.exist(txs);\n txs.length.should.equal(2);\n done();\n });\n });\n it('should get tx history for incoming txs', function(done) {\n server._normalizeTxHistory = sinon.stub().returnsArg(0);\n var txs = [{\n txid: '1',\n confirmations: 1,\n fees: 100,\n time: 20,\n inputs: [{\n address: 'external',\n amount: 500,\n }],\n outputs: [{\n address: mainAddresses[0].address,\n amount: 200,\n }],\n }];\n helpers.stubHistory(txs);\n server.getTxHistory({}, function(err, txs) {\n should.not.exist(err);\n should.exist(txs);\n txs.length.should.equal(1);\n var tx = txs[0];\n tx.action.should.equal('received');\n tx.amount.should.equal(200);\n tx.fees.should.equal(100);\n tx.time.should.equal(20);\n done();\n });\n });\n it('should get tx history for outgoing txs', function(done) {\n server._normalizeTxHistory = sinon.stub().returnsArg(0);\n var txs = [{\n txid: '1',\n confirmations: 1,\n fees: 100,\n time: 1,\n inputs: [{\n address: mainAddresses[0].address,\n amount: 500,\n }],\n outputs: [{\n address: 'external',\n amount: 400,\n }],\n }];\n helpers.stubHistory(txs);\n server.getTxHistory({}, function(err, txs) {\n should.not.exist(err);\n should.exist(txs);\n txs.length.should.equal(1);\n var tx = txs[0];\n tx.action.should.equal('sent');\n tx.amount.should.equal(400);\n tx.fees.should.equal(100);\n tx.time.should.equal(1);\n done();\n });\n });\n it('should get tx history for outgoing txs + change', function(done) {\n server._normalizeTxHistory = sinon.stub().returnsArg(0);\n var txs = [{\n txid: '1',\n confirmations: 1,\n fees: 100,\n time: 1,\n inputs: [{\n address: mainAddresses[0].address,\n amount: 500,\n }],\n outputs: [{\n address: 'external',\n amount: 300,\n }, {\n address: changeAddresses[0].address,\n amount: 100,\n }],\n }];\n helpers.stubHistory(txs);\n server.getTxHistory({}, function(err, txs) {\n should.not.exist(err);\n should.exist(txs);\n txs.length.should.equal(1);\n var tx = txs[0];\n tx.action.should.equal('sent');\n tx.amount.should.equal(300);\n tx.fees.should.equal(100);\n tx.outputs[0].address.should.equal('external');\n tx.outputs[0].amount.should.equal(300);\n done();\n });\n });\n it('should get tx history with accepted proposal', function(done) {\n server._normalizeTxHistory = sinon.stub().returnsArg(0);\n var external = '18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7';\n\n helpers.stubUtxos(server, wallet, [100, 200], function(utxos) {\n var outputs = [{\n toAddress: external,\n amount: 50,\n message: undefined // no message\n }, {\n toAddress: external,\n amount: 30,\n message: 'message #2'\n }];\n var txOpts = helpers.createProposalOpts(Model.TxProposal.Types.MULTIPLEOUTPUTS, outputs, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n should.exist(tx);\n\n var signatures = helpers.clientSign(tx, TestData.copayers[0].xPrivKey);\n server.signTx({\n txProposalId: tx.id,\n signatures: signatures,\n }, function(err, tx) {\n should.not.exist(err);\n\n helpers.stubBroadcast();\n server.broadcastTx({\n txProposalId: tx.id\n }, function(err, txp) {\n should.not.exist(err);\n var txs = [{\n txid: txp.txid,\n confirmations: 1,\n fees: 5460,\n time: 1,\n inputs: [{\n address: tx.inputs[0].address,\n amount: utxos[0].satoshis,\n }],\n outputs: [{\n address: changeAddresses[0].address,\n amount: helpers.toSatoshi(20) - 5460,\n }, {\n address: external,\n amount: helpers.toSatoshi(50)\n }, {\n address: external,\n amount: helpers.toSatoshi(30)\n }]\n }];\n helpers.stubHistory(txs);\n\n server.getTxHistory({}, function(err, txs) {\n should.not.exist(err);\n should.exist(txs);\n txs.length.should.equal(1);\n var tx = txs[0];\n tx.action.should.equal('sent');\n tx.amount.should.equal(helpers.toSatoshi(80));\n tx.message.should.equal('some message');\n tx.addressTo.should.equal(external);\n tx.actions.length.should.equal(1);\n tx.actions[0].type.should.equal('accept');\n tx.actions[0].copayerName.should.equal('copayer 1');\n tx.proposalType.should.equal(Model.TxProposal.Types.MULTIPLEOUTPUTS);\n tx.outputs[0].address.should.equal(external);\n tx.outputs[0].amount.should.equal(helpers.toSatoshi(50));\n should.not.exist(tx.outputs[0].message);\n should.not.exist(tx.outputs[0]['isMine']);\n should.not.exist(tx.outputs[0]['isChange']);\n tx.outputs[1].address.should.equal(external);\n tx.outputs[1].amount.should.equal(helpers.toSatoshi(30));\n should.exist(tx.outputs[1].message);\n tx.outputs[1].message.should.equal('message #2');\n done();\n });\n });\n });\n });\n });\n });\n it('should get various paginated tx history', function(done) {\n var testCases = [{\n opts: {},\n expected: [50, 40, 30, 20, 10],\n }, {\n opts: {\n skip: 1,\n limit: 3,\n },\n expected: [40, 30, 20],\n }, {\n opts: {\n skip: 1,\n limit: 2,\n },\n expected: [40, 30],\n }, {\n opts: {\n skip: 2,\n },\n expected: [30, 20, 10],\n }, {\n opts: {\n limit: 4,\n },\n expected: [50, 40, 30, 20],\n }, {\n opts: {\n skip: 0,\n limit: 3,\n },\n expected: [50, 40, 30],\n }, {\n opts: {\n skip: 0,\n limit: 0,\n },\n expected: [],\n }, {\n opts: {\n skip: 4,\n limit: 20,\n },\n expected: [10],\n }, {\n opts: {\n skip: 20,\n limit: 1,\n },\n expected: [],\n }];\n\n server._normalizeTxHistory = sinon.stub().returnsArg(0);\n var timestamps = [50, 40, 30, 20, 10];\n var txs = _.map(timestamps, function(ts, idx) {\n return {\n txid: (idx + 1).toString(),\n confirmations: ts / 10,\n fees: 100,\n time: ts,\n inputs: [{\n address: 'external',\n amount: 500,\n }],\n outputs: [{\n address: mainAddresses[0].address,\n amount: 200,\n }],\n };\n });\n helpers.stubHistory(txs);\n\n async.each(testCases, function(testCase, next) {\n server.getTxHistory(testCase.opts, function(err, txs) {\n should.not.exist(err);\n should.exist(txs);\n _.pluck(txs, 'time').should.deep.equal(testCase.expected);\n next();\n });\n }, done);\n });\n it('should fail gracefully if unable to reach the blockchain', function(done) {\n blockchainExplorer.getTransactions = sinon.stub().callsArgWith(3, 'dummy error');\n server.getTxHistory({}, function(err, txs) {\n should.exist(err);\n err.toString().should.equal('dummy error');\n done();\n });\n });\n it('should handle invalid tx in history ', function(done) {\n var h = _.clone(TestData.history);\n h.push({\n txid: 'xx'\n })\n helpers.stubHistory(h);\n\n server.getTxHistory({}, function(err, txs) {\n should.not.exist(err);\n should.exist(txs);\n txs.length.should.equal(3);\n txs[2].action.should.equal('invalid');\n done();\n });\n });\n });\n\n describe('#scan', function() {\n var server, wallet;\n var scanConfigOld = WalletService.SCAN_CONFIG;\n\n describe('1-of-1 wallet (BIP44 & P2PKH)', function() {\n beforeEach(function(done) {\n this.timeout(5000);\n WalletService.SCAN_CONFIG.maxGap = 2;\n\n helpers.createAndJoinWallet(1, 1, function(s, w) {\n server = s;\n wallet = w;\n done();\n });\n });\n afterEach(function() {\n WalletService.SCAN_CONFIG = scanConfigOld;\n });\n\n it('should scan main addresses', function(done) {\n helpers.stubAddressActivity(\n ['1L3z9LPd861FWQhf3vDn89Fnc9dkdBo2CG', // m/0/0\n '1GdXraZ1gtoVAvBh49D4hK9xLm6SKgesoE', // m/0/2\n '1FUzgKcyPJsYwDLUEVJYeE2N3KVaoxTjGS', // m/1/0\n ]);\n var expectedPaths = [\n 'm/0/0',\n 'm/0/1',\n 'm/0/2',\n 'm/1/0',\n ];\n server.scan({}, function(err) {\n should.not.exist(err);\n server.getWallet({}, function(err, wallet) {\n should.not.exist(err);\n wallet.scanStatus.should.equal('success');\n server.storage.fetchAddresses(wallet.id, function(err, addresses) {\n should.exist(addresses);\n addresses.length.should.equal(expectedPaths.length);\n var paths = _.pluck(addresses, 'path');\n _.difference(paths, expectedPaths).length.should.equal(0);\n server.createAddress({}, function(err, address) {\n should.not.exist(err);\n address.path.should.equal('m/0/3');\n done();\n });\n });\n });\n });\n });\n\n it('should not go beyond max gap', function(done) {\n helpers.stubAddressActivity(\n ['1L3z9LPd861FWQhf3vDn89Fnc9dkdBo2CG', // m/0/0\n '1GdXraZ1gtoVAvBh49D4hK9xLm6SKgesoE', // m/0/2\n '1DY9exavapgnCUWDnSTJe1BPzXcpgwAQC4', // m/0/5\n '1LD7Cr68LvBPTUeXrr6YXfGrogR7TVj3WQ', // m/1/3\n ]);\n var expectedPaths = [\n 'm/0/0',\n 'm/0/1',\n 'm/0/2',\n ];\n server.scan({}, function(err) {\n should.not.exist(err);\n server.getWallet({}, function(err, wallet) {\n should.not.exist(err);\n wallet.scanStatus.should.equal('success');\n server.storage.fetchAddresses(wallet.id, function(err, addresses) {\n should.exist(addresses);\n addresses.length.should.equal(expectedPaths.length);\n var paths = _.pluck(addresses, 'path');\n _.difference(paths, expectedPaths).length.should.equal(0);\n server.createAddress({}, function(err, address) {\n should.not.exist(err);\n address.path.should.equal('m/0/3');\n // A rescan should see the m/0/5 address initially beyond the gap\n server.scan({}, function(err) {\n server.createAddress({}, function(err, address) {\n should.not.exist(err);\n address.path.should.equal('m/0/6');\n done();\n });\n });\n });\n });\n });\n });\n });\n\n it('should not affect indexes on new wallet', function(done) {\n helpers.stubAddressActivity([]);\n server.scan({}, function(err) {\n should.not.exist(err);\n server.getWallet({}, function(err, wallet) {\n should.not.exist(err);\n wallet.scanStatus.should.equal('success');\n server.storage.fetchAddresses(wallet.id, function(err, addresses) {\n should.not.exist(err);\n addresses.length.should.equal(0);\n server.createAddress({}, function(err, address) {\n should.not.exist(err);\n address.path.should.equal('m/0/0');\n done();\n });\n });\n });\n });\n });\n\n it('should restore wallet balance', function(done) {\n async.waterfall([\n\n function(next) {\n helpers.stubUtxos(server, wallet, [1, 2, 3], function(utxos) {\n should.exist(utxos);\n helpers.stubAddressActivity(_.pluck(utxos, 'address'));\n server.getBalance({}, function(err, balance) {\n balance.totalAmount.should.equal(helpers.toSatoshi(6));\n next(null, server, wallet);\n });\n });\n },\n function(server, wallet, next) {\n server.removeWallet({}, function(err) {\n next(err);\n });\n },\n function(next) {\n // NOTE: this works because it creates the exact same wallet!\n helpers.createAndJoinWallet(1, 1, function(server, wallet) {\n server.getBalance({}, function(err, balance) {\n balance.totalAmount.should.equal(0);\n next(null, server, wallet);\n });\n });\n },\n function(server, wallet, next) {\n server.scan({}, function(err) {\n should.not.exist(err);\n server.getBalance(wallet.id, function(err, balance) {\n balance.totalAmount.should.equal(helpers.toSatoshi(6));\n next();\n })\n });\n },\n ], function(err) {\n should.not.exist(err);\n done();\n });\n });\n\n it('should abort scan if there is an error checking address activity', function(done) {\n blockchainExplorer.getAddressActivity = sinon.stub().callsArgWith(1, 'dummy error');\n server.scan({}, function(err) {\n should.exist(err);\n err.toString().should.equal('dummy error');\n server.getWallet({}, function(err, wallet) {\n should.not.exist(err);\n wallet.scanStatus.should.equal('error');\n wallet.addressManager.receiveAddressIndex.should.equal(0);\n wallet.addressManager.changeAddressIndex.should.equal(0);\n server.storage.fetchAddresses(wallet.id, function(err, addresses) {\n should.not.exist(err);\n addresses.should.be.empty;\n done();\n });\n });\n });\n });\n });\n\n describe('shared wallet (BIP45)', function() {\n\n beforeEach(function(done) {\n this.timeout(5000);\n WalletService.SCAN_CONFIG.maxGap = 2;\n\n helpers.createAndJoinWallet(1, 2, {\n supportBIP44AndP2PKH: false\n }, function(s, w) {\n server = s;\n wallet = w;\n done();\n });\n });\n afterEach(function() {\n WalletService.SCAN_CONFIG = scanConfigOld;\n });\n\n it('should scan main addresses', function(done) {\n helpers.stubAddressActivity(\n ['39AA1Y2VvPJhV3RFbc7cKbUax1WgkPwweR', // m/2147483647/0/0\n '3QX2MNSijnhCALBmUVnDo5UGPj3SEGASWx', // m/2147483647/0/2\n '3MzGaz4KKX66w8ShKaR536ZqzVvREBqqYu', // m/2147483647/1/0\n ]);\n var expectedPaths = [\n 'm/2147483647/0/0',\n 'm/2147483647/0/1',\n 'm/2147483647/0/2',\n 'm/2147483647/1/0',\n ];\n server.scan({}, function(err) {\n should.not.exist(err);\n server.getWallet({}, function(err, wallet) {\n should.not.exist(err);\n wallet.scanStatus.should.equal('success');\n server.storage.fetchAddresses(wallet.id, function(err, addresses) {\n should.exist(addresses);\n addresses.length.should.equal(expectedPaths.length);\n var paths = _.pluck(addresses, 'path');\n _.difference(paths, expectedPaths).length.should.equal(0);\n server.createAddress({}, function(err, address) {\n should.not.exist(err);\n address.path.should.equal('m/2147483647/0/3');\n done();\n });\n });\n });\n });\n });\n it('should scan main addresses & copayer addresses', function(done) {\n helpers.stubAddressActivity(\n ['39AA1Y2VvPJhV3RFbc7cKbUax1WgkPwweR', // m/2147483647/0/0\n '3MzGaz4KKX66w8ShKaR536ZqzVvREBqqYu', // m/2147483647/1/0\n '3BYoynejwBH9q4Jhr9m9P5YTnLTu57US6g', // m/0/0/1\n '37Pb8c32hzm16tCZaVHj4Dtjva45L2a3A3', // m/1/1/0\n '32TB2n283YsXdseMqUm9zHSRcfS5JxTWxx', // m/1/0/0\n ]);\n var expectedPaths = [\n 'm/2147483647/0/0',\n 'm/2147483647/1/0',\n 'm/0/0/0',\n 'm/0/0/1',\n 'm/1/0/0',\n 'm/1/1/0',\n ];\n server.scan({\n includeCopayerBranches: true\n }, function(err) {\n should.not.exist(err);\n server.storage.fetchAddresses(wallet.id, function(err, addresses) {\n should.exist(addresses);\n addresses.length.should.equal(expectedPaths.length);\n var paths = _.pluck(addresses, 'path');\n _.difference(paths, expectedPaths).length.should.equal(0);\n done();\n })\n });\n });\n });\n });\n\n describe('#startScan', function() {\n var server, wallet;\n var scanConfigOld = WalletService.SCAN_CONFIG;\n beforeEach(function(done) {\n this.timeout(5000);\n WalletService.SCAN_CONFIG.maxGap = 2;\n\n helpers.createAndJoinWallet(1, 1, {\n supportBIP44AndP2PKH: false\n }, function(s, w) {\n server = s;\n wallet = w;\n done();\n });\n });\n afterEach(function() {\n WalletService.SCAN_CONFIG = scanConfigOld;\n server.messageBroker.removeAllListeners();\n });\n\n it('should start an asynchronous scan', function(done) {\n helpers.stubAddressActivity(\n ['3GvvHimEMk2GBZnPxTF89GHZL6QhZjUZVs', // m/2147483647/0/0\n '37pd1jjTUiGBh8JL2hKLDgsyrhBoiz5vsi', // m/2147483647/0/2\n '3C3tBn8Sr1wHTp2brMgYsj9ncB7R7paYuB', // m/2147483647/1/0\n ]);\n var expectedPaths = [\n 'm/2147483647/0/0',\n 'm/2147483647/0/1',\n 'm/2147483647/0/2',\n 'm/2147483647/1/0',\n ];\n server.messageBroker.onMessage(function(n) {\n if (n.type == 'ScanFinished') {\n server.getWallet({}, function(err, wallet) {\n should.exist(wallet.scanStatus);\n wallet.scanStatus.should.equal('success');\n should.not.exist(n.creatorId);\n server.storage.fetchAddresses(wallet.id, function(err, addresses) {\n should.exist(addresses);\n addresses.length.should.equal(expectedPaths.length);\n var paths = _.pluck(addresses, 'path');\n _.difference(paths, expectedPaths).length.should.equal(0);\n server.createAddress({}, function(err, address) {\n should.not.exist(err);\n address.path.should.equal('m/2147483647/0/3');\n done();\n });\n })\n });\n }\n });\n server.startScan({}, function(err) {\n should.not.exist(err);\n });\n });\n it('should set scan status error when unable to reach blockchain', function(done) {\n blockchainExplorer.getAddressActivity = sinon.stub().yields('dummy error');\n server.messageBroker.onMessage(function(n) {\n if (n.type == 'ScanFinished') {\n should.exist(n.data.error);\n server.getWallet({}, function(err, wallet) {\n should.exist(wallet.scanStatus);\n wallet.scanStatus.should.equal('error');\n done();\n });\n }\n });\n server.startScan({}, function(err) {\n should.not.exist(err);\n });\n });\n it('should start multiple asynchronous scans for different wallets', function(done) {\n helpers.stubAddressActivity(['3K2VWMXheGZ4qG35DyGjA2dLeKfaSr534A']);\n WalletService.SCAN_CONFIG.scanWindow = 1;\n\n var scans = 0;\n server.messageBroker.onMessage(function(n) {\n if (n.type == 'ScanFinished') {\n scans++;\n if (scans == 2) done();\n }\n });\n\n // Create a second wallet\n var server2 = new WalletService();\n var opts = {\n name: 'second wallet',\n m: 1,\n n: 1,\n pubKey: TestData.keyPair.pub,\n };\n server2.createWallet(opts, function(err, walletId) {\n should.not.exist(err);\n var copayerOpts = helpers.getSignedCopayerOpts({\n walletId: walletId,\n name: 'copayer 1',\n xPubKey: TestData.copayers[3].xPubKey_45H,\n requestPubKey: TestData.copayers[3].pubKey_1H_0,\n });\n server.joinWallet(copayerOpts, function(err, result) {\n should.not.exist(err);\n helpers.getAuthServer(result.copayerId, function(server2) {\n server.startScan({}, function(err) {\n should.not.exist(err);\n scans.should.equal(0);\n });\n server2.startScan({}, function(err) {\n should.not.exist(err);\n scans.should.equal(0);\n });\n scans.should.equal(0);\n });\n });\n });\n });\n });\n\n describe('Legacy', function() {\n describe('Fees', function() {\n var server, wallet;\n beforeEach(function(done) {\n helpers.createAndJoinWallet(2, 3, function(s, w) {\n server = s;\n wallet = w;\n done();\n });\n });\n\n it('should create a tx from legacy (bwc-0.0.*) client', function(done) {\n helpers.stubUtxos(server, wallet, [100, 200], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 80, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n\n var verifyStub = sinon.stub(WalletService.prototype, '_verifySignature');\n verifyStub.returns(true);\n WalletService.getInstanceWithAuth({\n copayerId: wallet.copayers[0].id,\n message: 'dummy',\n signature: 'dummy',\n clientVersion: 'bwc-0.0.40',\n }, function(err, server) {\n should.not.exist(err);\n should.exist(server);\n verifyStub.restore();\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n should.exist(tx);\n tx.amount.should.equal(helpers.toSatoshi(80));\n tx.fee.should.equal(WalletUtils.DEFAULT_FEE_PER_KB);\n done();\n });\n });\n });\n });\n\n it('should not return error when fetching new txps from legacy (bwc-0.0.*) client', function(done) {\n helpers.stubUtxos(server, wallet, [100, 200], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 80, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n should.exist(tx);\n\n var verifyStub = sinon.stub(WalletService.prototype, '_verifySignature');\n verifyStub.returns(true);\n WalletService.getInstanceWithAuth({\n copayerId: wallet.copayers[0].id,\n message: 'dummy',\n signature: 'dummy',\n clientVersion: 'bwc-0.0.40',\n }, function(err, server) {\n verifyStub.restore();\n should.not.exist(err);\n should.exist(server);\n server.getPendingTxs({}, function(err, txps) {\n should.not.exist(err);\n should.exist(txps);\n done();\n });\n });\n });\n });\n });\n it('should fail to sign tx from legacy (bwc-0.0.*) client', function(done) {\n helpers.stubUtxos(server, wallet, [100, 200], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 80, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n should.exist(tx);\n _.startsWith(tx.version, '1.').should.be.false;\n\n var verifyStub = sinon.stub(WalletService.prototype, '_verifySignature');\n verifyStub.returns(true);\n WalletService.getInstanceWithAuth({\n copayerId: wallet.copayers[0].id,\n message: 'dummy',\n signature: 'dummy',\n clientVersion: 'bwc-0.0.40',\n }, function(err, server) {\n var signatures = helpers.clientSign(tx, TestData.copayers[0].xPrivKey);\n server.signTx({\n txProposalId: tx.id,\n signatures: signatures,\n }, function(err) {\n verifyStub.restore();\n should.exist(err);\n err.code.should.equal('UPGRADE_NEEDED');\n err.message.should.contain('sign this spend proposal');\n done();\n });\n });\n });\n });\n });\n it('should create a tx from legacy (bwc-0.0.*) client and sign it from newer client', function(done) {\n helpers.stubUtxos(server, wallet, [100, 200], function() {\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 80, TestData.copayers[0].privKey_1H_0, {\n message: 'some message'\n });\n\n var verifyStub = sinon.stub(WalletService.prototype, '_verifySignature');\n verifyStub.returns(true);\n WalletService.getInstanceWithAuth({\n copayerId: wallet.copayers[0].id,\n message: 'dummy',\n signature: 'dummy',\n clientVersion: 'bwc-0.0.40',\n }, function(err, server) {\n should.not.exist(err);\n should.exist(server);\n verifyStub.restore();\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n should.exist(tx);\n tx.amount.should.equal(helpers.toSatoshi(80));\n tx.fee.should.equal(WalletUtils.DEFAULT_FEE_PER_KB);\n helpers.getAuthServer(wallet.copayers[0].id, function(server) {\n var signatures = helpers.clientSign(tx, TestData.copayers[0].xPrivKey);\n server.signTx({\n txProposalId: tx.id,\n signatures: signatures,\n }, function(err) {\n should.not.exist(err);\n done();\n });\n });\n });\n });\n });\n });\n it('should fail with insufficient fee when invoked from legacy (bwc-0.0.*) client', function(done) {\n helpers.stubUtxos(server, wallet, 1, function() {\n var verifyStub = sinon.stub(WalletService.prototype, '_verifySignature');\n verifyStub.returns(true);\n WalletService.getInstanceWithAuth({\n copayerId: wallet.copayers[0].id,\n message: 'dummy',\n signature: 'dummy',\n clientVersion: 'bwc-0.0.40',\n }, function(err, server) {\n should.not.exist(err);\n should.exist(server);\n verifyStub.restore();\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 0.99995, TestData.copayers[0].privKey_1H_0);\n\n server.createTx(txOpts, function(err, tx) {\n should.exist(err);\n err.code.should.equal('INSUFFICIENT_FUNDS_FOR_FEE');\n var txOpts = helpers.createSimpleProposalOpts('18PzpUFkFZE8zKWUPvfykkTxmB9oMR8qP7', 0.99995, TestData.copayers[0].privKey_1H_0, {\n feePerKb: 5000\n });\n server.createTx(txOpts, function(err, tx) {\n should.not.exist(err);\n tx.fee.should.equal(5000);\n\n // Sign it to make sure Bitcore doesn't complain about the fees\n var signatures = helpers.clientSign(tx, TestData.copayers[0].xPrivKey);\n server.signTx({\n txProposalId: tx.id,\n signatures: signatures,\n }, function(err) {\n should.not.exist(err);\n done();\n });\n });\n });\n });\n });\n });\n });\n });\n});\n"},"message":{"kind":"string","value":"test existing addresses do not get rewinded on scan error\n"},"old_file":{"kind":"string","value":"test/integration/server.js"},"subject":{"kind":"string","value":"test existing addresses do not get rewinded on scan error"},"git_diff":{"kind":"string","value":"est/integration/server.js\n });\n });\n \n it('should not rewind already generated addresses on error', function(done) {\n server.createAddress({}, function(err, address) {\n should.not.exist(err);\n address.path.should.equal('m/0/0');\n blockchainExplorer.getAddressActivity = sinon.stub().callsArgWith(1, 'dummy error');\n server.scan({}, function(err) {\n should.exist(err);\n err.toString().should.equal('dummy error');\n server.getWallet({}, function(err, wallet) {\n should.not.exist(err);\n wallet.scanStatus.should.equal('error');\n wallet.addressManager.receiveAddressIndex.should.equal(1);\n wallet.addressManager.changeAddressIndex.should.equal(0);\n server.createAddress({}, function(err, address) {\n should.not.exist(err);\n address.path.should.equal('m/0/1');\n done();\n });\n });\n });\n });\n });\n\n it('should restore wallet balance', function(done) {\n async.waterfall([\n "}}},{"rowIdx":846,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"3e7bf0fa20312acd476bfdfba45d4f828c5a1353"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"qwerty4030/elasticsearch,elancom/elasticsearch,anti-social/elasticsearch,Fsero/elasticsearch,fekaputra/elasticsearch,mbrukman/elasticsearch,fubuki/elasticsearch,libosu/elasticsearch,wittyameta/elasticsearch,mrorii/elasticsearch,milodky/elasticsearch,rmuir/elasticsearch,apepper/elasticsearch,Liziyao/elasticsearch,vrkansagara/elasticsearch,lightslife/elasticsearch,mkis-/elasticsearch,bestwpw/elasticsearch,gfyoung/elasticsearch,coding0011/elasticsearch,zhaocloud/elasticsearch,kcompher/elasticsearch,overcome/elasticsearch,djschny/elasticsearch,socialrank/elasticsearch,MichaelLiZhou/elasticsearch,kalburgimanjunath/elasticsearch,njlawton/elasticsearch,huypx1292/elasticsearch,springning/elasticsearch,hanst/elasticsearch,yongminxia/elasticsearch,Uiho/elasticsearch,s1monw/elasticsearch,onegambler/elasticsearch,petabytedata/elasticsearch,jeteve/elasticsearch,pritishppai/elasticsearch,geidies/elasticsearch,diendt/elasticsearch,NBSW/elasticsearch,alexbrasetvik/elasticsearch,glefloch/elasticsearch,spiegela/elasticsearch,martinstuga/elasticsearch,tkssharma/elasticsearch,lchennup/elasticsearch,lmenezes/elasticsearch,likaiwalkman/elasticsearch,EasonYi/elasticsearch,overcome/elasticsearch,girirajsharma/elasticsearch,drewr/elasticsearch,mikemccand/elasticsearch,Asimov4/elasticsearch,combinatorist/elasticsearch,girirajsharma/elasticsearch,jw0201/elastic,jpountz/elasticsearch,sreeramjayan/elasticsearch,opendatasoft/elasticsearch,aparo/elasticsearch,LeoYao/elasticsearch,henakamaMSFT/elasticsearch,ajhalani/elasticsearch,wimvds/elasticsearch,ricardocerq/elasticsearch,Charlesdong/elasticsearch,khiraiwa/elasticsearch,dongjoon-hyun/elasticsearch,jchampion/elasticsearch,huanzhong/elasticsearch,ajhalani/elasticsearch,strapdata/elassandra5-rc,brandonkearby/elasticsearch,liweinan0423/elasticsearch,szroland/elasticsearch,lks21c/elasticsearch,opendatasoft/elasticsearch,mcku/elasticsearch,sscarduzio/elasticsearch,kubum/elasticsearch,kcompher/elasticsearch,sposam/elasticsearch,kunallimaye/elasticsearch,ydsakyclguozi/elasticsearch,hydro2k/elasticsearch,sauravmondallive/elasticsearch,sdauletau/elasticsearch,lzo/elasticsearch-1,lchennup/elasticsearch,njlawton/elasticsearch,gmarz/elasticsearch,palecur/elasticsearch,djschny/elasticsearch,aglne/elasticsearch,Rygbee/elasticsearch,strapdata/elassandra5-rc,boliza/elasticsearch,davidvgalbraith/elasticsearch,uschindler/elasticsearch,mnylen/elasticsearch,dongjoon-hyun/elasticsearch,dataduke/elasticsearch,ulkas/elasticsearch,onegambler/elasticsearch,javachengwc/elasticsearch,zkidkid/elasticsearch,spiegela/elasticsearch,GlenRSmith/elasticsearch,rlugojr/elasticsearch,MaineC/elasticsearch,tkssharma/elasticsearch,MichaelLiZhou/elasticsearch,mute/elasticsearch,fred84/elasticsearch,mbrukman/elasticsearch,iantruslove/elasticsearch,ThalaivaStars/OrgRepo1,mjhennig/elasticsearch,socialrank/elasticsearch,hafkensite/elasticsearch,franklanganke/elasticsearch,fubuki/elasticsearch,polyfractal/elasticsearch,knight1128/elasticsearch,JackyMai/elasticsearch,djschny/elasticsearch,ouyangkongtong/elasticsearch,abhijitiitr/es,Helen-Zhao/elasticsearch,JervyShi/elasticsearch,ZTE-PaaS/elasticsearch,MisterAndersen/elasticsearch,acchen97/elasticsearch,AshishThakur/elasticsearch,markllama/elasticsearch,ajhalani/elasticsearch,lchennup/elasticsearch,F0lha/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,F0lha/elasticsearch,Collaborne/elasticsearch,18098924759/elasticsearch,Clairebi/ElasticsearchClone,golubev/elasticsearch,knight1128/elasticsearch,Microsoft/elasticsearch,beiske/elasticsearch,davidvgalbraith/elasticsearch,hirdesh2008/elasticsearch,myelin/elasticsearch,jimczi/elasticsearch,brandonkearby/elasticsearch,petabytedata/elasticsearch,nomoa/elasticsearch,feiqitian/elasticsearch,robin13/elasticsearch,maddin2016/elasticsearch,andrestc/elasticsearch,Flipkart/elasticsearch,gingerwizard/elasticsearch,opendatasoft/elasticsearch,rento19962/elasticsearch,dpursehouse/elasticsearch,Uiho/elasticsearch,Clairebi/ElasticsearchClone,PhaedrusTheGreek/elasticsearch,jaynblue/elasticsearch,markllama/elasticsearch,ivansun1010/elasticsearch,MetSystem/elasticsearch,zhiqinghuang/elasticsearch,knight1128/elasticsearch,zhiqinghuang/elasticsearch,Clairebi/ElasticsearchClone,Charlesdong/elasticsearch,s1monw/elasticsearch,PhaedrusTheGreek/elasticsearch,trangvh/elasticsearch,wittyameta/elasticsearch,dataduke/elasticsearch,strapdata/elassandra,jbertouch/elasticsearch,myelin/elasticsearch,jeteve/elasticsearch,hechunwen/elasticsearch,nezirus/elasticsearch,jbertouch/elasticsearch,rhoml/elasticsearch,karthikjaps/elasticsearch,ricardocerq/elasticsearch,tsohil/elasticsearch,Liziyao/elasticsearch,mcku/elasticsearch,sneivandt/elasticsearch,kunallimaye/elasticsearch,sjohnr/elasticsearch,awislowski/elasticsearch,golubev/elasticsearch,chirilo/elasticsearch,MaineC/elasticsearch,ckclark/elasticsearch,adrianbk/elasticsearch,kingaj/elasticsearch,Fsero/elasticsearch,scottsom/elasticsearch,s1monw/elasticsearch,tkssharma/elasticsearch,szroland/elasticsearch,Shekharrajak/elasticsearch,alexbrasetvik/elasticsearch,feiqitian/elasticsearch,martinstuga/elasticsearch,avikurapati/elasticsearch,LewayneNaidoo/elasticsearch,lmtwga/elasticsearch,kalburgimanjunath/elasticsearch,milodky/elasticsearch,KimTaehee/elasticsearch,NBSW/elasticsearch,markllama/elasticsearch,luiseduardohdbackup/elasticsearch,humandb/elasticsearch,zkidkid/elasticsearch,dylan8902/elasticsearch,Charlesdong/elasticsearch,Uiho/elasticsearch,mohsinh/elasticsearch,vorce/es-metrics,yuy168/elasticsearch,caengcjd/elasticsearch,F0lha/elasticsearch,amaliujia/elasticsearch,marcuswr/elasticsearch-dateline,hafkensite/elasticsearch,episerver/elasticsearch,amit-shar/elasticsearch,coding0011/elasticsearch,scottsom/elasticsearch,kenshin233/elasticsearch,kubum/elasticsearch,rento19962/elasticsearch,amaliujia/elasticsearch,lchennup/elasticsearch,sjohnr/elasticsearch,VukDukic/elasticsearch,naveenhooda2000/elasticsearch,overcome/elasticsearch,golubev/elasticsearch,wimvds/elasticsearch,kimchy/elasticsearch,Chhunlong/elasticsearch,luiseduardohdbackup/elasticsearch,codebunt/elasticsearch,kimchy/elasticsearch,marcuswr/elasticsearch-dateline,Brijeshrpatel9/elasticsearch,Shekharrajak/elasticsearch,wayeast/elasticsearch,i-am-Nathan/elasticsearch,khiraiwa/elasticsearch,hafkensite/elasticsearch,micpalmia/elasticsearch,lks21c/elasticsearch,schonfeld/elasticsearch,andrewvc/elasticsearch,AshishThakur/elasticsearch,Rygbee/elasticsearch,pritishppai/elasticsearch,masaruh/elasticsearch,NBSW/elasticsearch,sarwarbhuiyan/elasticsearch,acchen97/elasticsearch,JackyMai/elasticsearch,wimvds/elasticsearch,sarwarbhuiyan/elasticsearch,petabytedata/elasticsearch,slavau/elasticsearch,yynil/elasticsearch,sposam/elasticsearch,kcompher/elasticsearch,lydonchandra/elasticsearch,yanjunh/elasticsearch,kevinkluge/elasticsearch,mgalushka/elasticsearch,AshishThakur/elasticsearch,knight1128/elasticsearch,anti-social/elasticsearch,ouyangkongtong/elasticsearch,abhijitiitr/es,StefanGor/elasticsearch,jimhooker2002/elasticsearch,camilojd/elasticsearch,salyh/elasticsearch,strapdata/elassandra-test,zhaocloud/elasticsearch,rajanm/elasticsearch,vvcephei/elasticsearch,mgalushka/elasticsearch,masaruh/elasticsearch,camilojd/elasticsearch,aparo/elasticsearch,sdauletau/elasticsearch,PhaedrusTheGreek/elasticsearch,phani546/elasticsearch,cnfire/elasticsearch-1,overcome/elasticsearch,camilojd/elasticsearch,i-am-Nathan/elasticsearch,StefanGor/elasticsearch,jchampion/elasticsearch,loconsolutions/elasticsearch,vroyer/elasticassandra,Liziyao/elasticsearch,davidvgalbraith/elasticsearch,rlugojr/elasticsearch,truemped/elasticsearch,jbertouch/elasticsearch,huanzhong/elasticsearch,Fsero/elasticsearch,easonC/elasticsearch,iacdingping/elasticsearch,markharwood/elasticsearch,18098924759/elasticsearch,codebunt/elasticsearch,mbrukman/elasticsearch,wuranbo/elasticsearch,sneivandt/elasticsearch,kubum/elasticsearch,diendt/elasticsearch,avikurapati/elasticsearch,vrkansagara/elasticsearch,wittyameta/elasticsearch,HarishAtGitHub/elasticsearch,ThiagoGarciaAlves/elasticsearch,fernandozhu/elasticsearch,aglne/elasticsearch,schonfeld/elasticsearch,masterweb121/elasticsearch,wbowling/elasticsearch,wenpos/elasticsearch,ThiagoGarciaAlves/elasticsearch,wangtuo/elasticsearch,fooljohnny/elasticsearch,vorce/es-metrics,Charlesdong/elasticsearch,iamjakob/elasticsearch,apepper/elasticsearch,jpountz/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,Kakakakakku/elasticsearch,avikurapati/elasticsearch,henakamaMSFT/elasticsearch,rhoml/elasticsearch,drewr/elasticsearch,Brijeshrpatel9/elasticsearch,vrkansagara/elasticsearch,KimTaehee/elasticsearch,scorpionvicky/elasticsearch,rajanm/elasticsearch,sscarduzio/elasticsearch,jaynblue/elasticsearch,vinsonlou/elasticsearch,yuy168/elasticsearch,Ansh90/elasticsearch,qwerty4030/elasticsearch,truemped/elasticsearch,nrkkalyan/elasticsearch,loconsolutions/elasticsearch,MaineC/elasticsearch,jbertouch/elasticsearch,mnylen/elasticsearch,clintongormley/elasticsearch,MjAbuz/elasticsearch,hydro2k/elasticsearch,micpalmia/elasticsearch,himanshuag/elasticsearch,lightslife/elasticsearch,jchampion/elasticsearch,JervyShi/elasticsearch,zhaocloud/elasticsearch,rhoml/elasticsearch,zhiqinghuang/elasticsearch,mnylen/elasticsearch,andrestc/elasticsearch,avikurapati/elasticsearch,snikch/elasticsearch,iamjakob/elasticsearch,jprante/elasticsearch,andrejserafim/elasticsearch,sarwarbhuiyan/elasticsearch,zhiqinghuang/elasticsearch,C-Bish/elasticsearch,anti-social/elasticsearch,martinstuga/elasticsearch,MisterAndersen/elasticsearch,maddin2016/elasticsearch,ajhalani/elasticsearch,caengcjd/elasticsearch,mikemccand/elasticsearch,phani546/elasticsearch,fernandozhu/elasticsearch,cnfire/elasticsearch-1,thecocce/elasticsearch,chirilo/elasticsearch,vingupta3/elasticsearch,sscarduzio/elasticsearch,winstonewert/elasticsearch,wangtuo/elasticsearch,mjason3/elasticsearch,ThalaivaStars/OrgRepo1,rmuir/elasticsearch,yongminxia/elasticsearch,smflorentino/elasticsearch,YosuaMichael/elasticsearch,snikch/elasticsearch,xingguang2013/elasticsearch,elancom/elasticsearch,Brijeshrpatel9/elasticsearch,socialrank/elasticsearch,mjhennig/elasticsearch,nrkkalyan/elasticsearch,AndreKR/elasticsearch,mnylen/elasticsearch,micpalmia/elasticsearch,Kakakakakku/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,gingerwizard/elasticsearch,jeteve/elasticsearch,mcku/elasticsearch,ckclark/elasticsearch,sneivandt/elasticsearch,ricardocerq/elasticsearch,liweinan0423/elasticsearch,kimimj/elasticsearch,scorpionvicky/elasticsearch,feiqitian/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,skearns64/elasticsearch,humandb/elasticsearch,mohsinh/elasticsearch,sjohnr/elasticsearch,kalimatas/elasticsearch,Rygbee/elasticsearch,masterweb121/elasticsearch,nrkkalyan/elasticsearch,mgalushka/elasticsearch,markharwood/elasticsearch,javachengwc/elasticsearch,lightslife/elasticsearch,umeshdangat/elasticsearch,masterweb121/elasticsearch,boliza/elasticsearch,caengcjd/elasticsearch,Shekharrajak/elasticsearch,jango2015/elasticsearch,raishiv/elasticsearch,knight1128/elasticsearch,huypx1292/elasticsearch,mgalushka/elasticsearch,pritishppai/elasticsearch,wangtuo/elasticsearch,Chhunlong/elasticsearch,markharwood/elasticsearch,combinatorist/elasticsearch,lzo/elasticsearch-1,LeoYao/elasticsearch,lks21c/elasticsearch,salyh/elasticsearch,ESamir/elasticsearch,henakamaMSFT/elasticsearch,kubum/elasticsearch,opendatasoft/elasticsearch,socialrank/elasticsearch,areek/elasticsearch,AleksKochev/elasticsearch,fekaputra/elasticsearch,linglaiyao1314/elasticsearch,apepper/elasticsearch,ulkas/elasticsearch,MichaelLiZhou/elasticsearch,tkssharma/elasticsearch,Collaborne/elasticsearch,Charlesdong/elasticsearch,Widen/elasticsearch,ImpressTV/elasticsearch,Microsoft/elasticsearch,amit-shar/elasticsearch,Brijeshrpatel9/elasticsearch,polyfractal/elasticsearch,mortonsykes/elasticsearch,shreejay/elasticsearch,peschlowp/elasticsearch,nknize/elasticsearch,overcome/elasticsearch,ThiagoGarciaAlves/elasticsearch,pablocastro/elasticsearch,schonfeld/elasticsearch,dpursehouse/elasticsearch,Chhunlong/elasticsearch,Brijeshrpatel9/elasticsearch,skearns64/elasticsearch,rento19962/elasticsearch,khiraiwa/elasticsearch,xpandan/elasticsearch,xpandan/elasticsearch,zhaocloud/elasticsearch,aparo/elasticsearch,tebriel/elasticsearch,strapdata/elassandra-test,Siddartha07/elasticsearch,ThiagoGarciaAlves/elasticsearch,weipinghe/elasticsearch,petmit/elasticsearch,jimczi/elasticsearch,andrejserafim/elasticsearch,aglne/elasticsearch,wayeast/elasticsearch,alexshadow007/elasticsearch,sauravmondallive/elasticsearch,diendt/elasticsearch,kubum/elasticsearch,Asimov4/elasticsearch,obourgain/elasticsearch,Uiho/elasticsearch,iantruslove/elasticsearch,dataduke/elasticsearch,clintongormley/elasticsearch,coding0011/elasticsearch,hanst/elasticsearch,MjAbuz/elasticsearch,andrestc/elasticsearch,overcome/elasticsearch,lmtwga/elasticsearch,wimvds/elasticsearch,mrorii/elasticsearch,IanvsPoplicola/elasticsearch,tcucchietti/elasticsearch,ckclark/elasticsearch,ydsakyclguozi/elasticsearch,abhijitiitr/es,Collaborne/elasticsearch,mbrukman/elasticsearch,F0lha/elasticsearch,sauravmondallive/elasticsearch,jpountz/elasticsearch,andrestc/elasticsearch,alexbrasetvik/elasticsearch,IanvsPoplicola/elasticsearch,kkirsche/elasticsearch,codebunt/elasticsearch,nrkkalyan/elasticsearch,elancom/elasticsearch,GlenRSmith/elasticsearch,khiraiwa/elasticsearch,qwerty4030/elasticsearch,fforbeck/elasticsearch,ESamir/elasticsearch,nilabhsagar/elasticsearch,abibell/elasticsearch,markllama/elasticsearch,MjAbuz/elasticsearch,jimhooker2002/elasticsearch,ouyangkongtong/elasticsearch,C-Bish/elasticsearch,vietlq/elasticsearch,vorce/es-metrics,SaiprasadKrishnamurthy/elasticsearch,mm0/elasticsearch,hydro2k/elasticsearch,lmtwga/elasticsearch,ivansun1010/elasticsearch,elasticdog/elasticsearch,loconsolutions/elasticsearch,F0lha/elasticsearch,kenshin233/elasticsearch,luiseduardohdbackup/elasticsearch,pritishppai/elasticsearch,kalburgimanjunath/elasticsearch,martinstuga/elasticsearch,likaiwalkman/elasticsearch,alexshadow007/elasticsearch,mgalushka/elasticsearch,mjhennig/elasticsearch,gingerwizard/elasticsearch,springning/elasticsearch,glefloch/elasticsearch,humandb/elasticsearch,cwurm/elasticsearch,ckclark/elasticsearch,nomoa/elasticsearch,Fsero/elasticsearch,Shekharrajak/elasticsearch,sdauletau/elasticsearch,mmaracic/elasticsearch,thecocce/elasticsearch,beiske/elasticsearch,ZTE-PaaS/elasticsearch,Liziyao/elasticsearch,tahaemin/elasticsearch,AndreKR/elasticsearch,kingaj/elasticsearch,heng4fun/elasticsearch,ydsakyclguozi/elasticsearch,hechunwen/elasticsearch,iacdingping/elasticsearch,JackyMai/elasticsearch,humandb/elasticsearch,Rygbee/elasticsearch,apepper/elasticsearch,hirdesh2008/elasticsearch,pozhidaevak/elasticsearch,masterweb121/elasticsearch,Asimov4/elasticsearch,pozhidaevak/elasticsearch,KimTaehee/elasticsearch,aparo/elasticsearch,HonzaKral/elasticsearch,mkis-/elasticsearch,obourgain/elasticsearch,fekaputra/elasticsearch,ESamir/elasticsearch,fekaputra/elasticsearch,lydonchandra/elasticsearch,kkirsche/elasticsearch,robin13/elasticsearch,socialrank/elasticsearch,mjason3/elasticsearch,dpursehouse/elasticsearch,dongjoon-hyun/elasticsearch,JackyMai/elasticsearch,fernandozhu/elasticsearch,ThalaivaStars/OrgRepo1,infusionsoft/elasticsearch,himanshuag/elasticsearch,hechunwen/elasticsearch,jeteve/elasticsearch,kkirsche/elasticsearch,vietlq/elasticsearch,dylan8902/elasticsearch,likaiwalkman/elasticsearch,wimvds/elasticsearch,btiernay/elasticsearch,onegambler/elasticsearch,aparo/elasticsearch,jsgao0/elasticsearch,jeteve/elasticsearch,jango2015/elasticsearch,pozhidaevak/elasticsearch,fred84/elasticsearch,jango2015/elasticsearch,wangyuxue/elasticsearch,opendatasoft/elasticsearch,sdauletau/elasticsearch,wenpos/elasticsearch,clintongormley/elasticsearch,achow/elasticsearch,andrejserafim/elasticsearch,markharwood/elasticsearch,fekaputra/elasticsearch,camilojd/elasticsearch,Siddartha07/elasticsearch,JSCooke/elasticsearch,alexksikes/elasticsearch,HarishAtGitHub/elasticsearch,acchen97/elasticsearch,mbrukman/elasticsearch,kevinkluge/elasticsearch,clintongormley/elasticsearch,hechunwen/elasticsearch,mute/elasticsearch,dylan8902/elasticsearch,kingaj/elasticsearch,tebriel/elasticsearch,mohit/elasticsearch,HonzaKral/elasticsearch,karthikjaps/elasticsearch,hechunwen/elasticsearch,robin13/elasticsearch,mikemccand/elasticsearch,winstonewert/elasticsearch,uschindler/elasticsearch,rajanm/elasticsearch,markharwood/elasticsearch,zeroctu/elasticsearch,achow/elasticsearch,jsgao0/elasticsearch,a2lin/elasticsearch,mkis-/elasticsearch,Stacey-Gammon/elasticsearch,kevinkluge/elasticsearch,heng4fun/elasticsearch,luiseduardohdbackup/elasticsearch,dylan8902/elasticsearch,vingupta3/elasticsearch,winstonewert/elasticsearch,petabytedata/elasticsearch,milodky/elasticsearch,palecur/elasticsearch,nazarewk/elasticsearch,strapdata/elassandra,mgalushka/elasticsearch,henakamaMSFT/elasticsearch,lchennup/elasticsearch,18098924759/elasticsearch,mohsinh/elasticsearch,anti-social/elasticsearch,anti-social/elasticsearch,scorpionvicky/elasticsearch,HarishAtGitHub/elasticsearch,golubev/elasticsearch,codebunt/elasticsearch,Ansh90/elasticsearch,libosu/elasticsearch,fernandozhu/elasticsearch,yynil/elasticsearch,glefloch/elasticsearch,mikemccand/elasticsearch,kalimatas/elasticsearch,nellicus/elasticsearch,dantuffery/elasticsearch,phani546/elasticsearch,chirilo/elasticsearch,maddin2016/elasticsearch,cwurm/elasticsearch,linglaiyao1314/elasticsearch,areek/elasticsearch,truemped/elasticsearch,himanshuag/elasticsearch,slavau/elasticsearch,polyfractal/elasticsearch,zeroctu/elasticsearch,vorce/es-metrics,salyh/elasticsearch,obourgain/elasticsearch,geidies/elasticsearch,zhaocloud/elasticsearch,AleksKochev/elasticsearch,amaliujia/elasticsearch,aglne/elasticsearch,mcku/elasticsearch,tsohil/elasticsearch,umeshdangat/elasticsearch,TonyChai24/ESSource,nellicus/elasticsearch,markwalkom/elasticsearch,queirozfcom/elasticsearch,hydro2k/elasticsearch,bawse/elasticsearch,SergVro/elasticsearch,schonfeld/elasticsearch,YosuaMichael/elasticsearch,njlawton/elasticsearch,JSCooke/elasticsearch,girirajsharma/elasticsearch,bawse/elasticsearch,dantuffery/elasticsearch,Flipkart/elasticsearch,Clairebi/ElasticsearchClone,iacdingping/elasticsearch,kcompher/elasticsearch,petabytedata/elasticsearch,scottsom/elasticsearch,alexkuk/elasticsearch,JervyShi/elasticsearch,raishiv/elasticsearch,lmtwga/elasticsearch,libosu/elasticsearch,raishiv/elasticsearch,zeroctu/elasticsearch,jimhooker2002/elasticsearch,fred84/elasticsearch,snikch/elasticsearch,myelin/elasticsearch,vrkansagara/elasticsearch,jango2015/elasticsearch,liweinan0423/elasticsearch,onegambler/elasticsearch,iacdingping/elasticsearch,jpountz/elasticsearch,Clairebi/ElasticsearchClone,jw0201/elastic,AndreKR/elasticsearch,tkssharma/elasticsearch,cnfire/elasticsearch-1,aparo/elasticsearch,pablocastro/elasticsearch,vietlq/elasticsearch,ImpressTV/elasticsearch,a2lin/elasticsearch,ulkas/elasticsearch,mapr/elasticsearch,IanvsPoplicola/elasticsearch,C-Bish/elasticsearch,JervyShi/elasticsearch,LewayneNaidoo/elasticsearch,AshishThakur/elasticsearch,bawse/elasticsearch,zkidkid/elasticsearch,onegambler/elasticsearch,kingaj/elasticsearch,humandb/elasticsearch,nazarewk/elasticsearch,humandb/elasticsearch,truemped/elasticsearch,dongaihua/highlight-elasticsearch,wangtuo/elasticsearch,kcompher/elasticsearch,szroland/elasticsearch,pritishppai/elasticsearch,javachengwc/elasticsearch,glefloch/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,amit-shar/elasticsearch,brandonkearby/elasticsearch,Chhunlong/elasticsearch,btiernay/elasticsearch,Shekharrajak/elasticsearch,himanshuag/elasticsearch,Collaborne/elasticsearch,iacdingping/elasticsearch,knight1128/elasticsearch,zhiqinghuang/elasticsearch,geidies/elasticsearch,ESamir/elasticsearch,uschindler/elasticsearch,Rygbee/elasticsearch,abibell/elasticsearch,Uiho/elasticsearch,yuy168/elasticsearch,knight1128/elasticsearch,sc0ttkclark/elasticsearch,StefanGor/elasticsearch,easonC/elasticsearch,ThiagoGarciaAlves/elasticsearch,ajhalani/elasticsearch,nezirus/elasticsearch,umeshdangat/elasticsearch,truemped/elasticsearch,nellicus/elasticsearch,jpountz/elasticsearch,mute/elasticsearch,micpalmia/elasticsearch,tahaemin/elasticsearch,dataduke/elasticsearch,bestwpw/elasticsearch,artnowo/elasticsearch,vietlq/elasticsearch,easonC/elasticsearch,fforbeck/elasticsearch,polyfractal/elasticsearch,xuzha/elasticsearch,truemped/elasticsearch,MjAbuz/elasticsearch,masterweb121/elasticsearch,apepper/elasticsearch,dantuffery/elasticsearch,springning/elasticsearch,mm0/elasticsearch,kubum/elasticsearch,vrkansagara/elasticsearch,infusionsoft/elasticsearch,vrkansagara/elasticsearch,beiske/elasticsearch,adrianbk/elasticsearch,janmejay/elasticsearch,raishiv/elasticsearch,cnfire/elasticsearch-1,fforbeck/elasticsearch,artnowo/elasticsearch,shreejay/elasticsearch,naveenhooda2000/elasticsearch,tcucchietti/elasticsearch,rajanm/elasticsearch,jimczi/elasticsearch,linglaiyao1314/elasticsearch,mbrukman/elasticsearch,vinsonlou/elasticsearch,coding0011/elasticsearch,episerver/elasticsearch,mcku/elasticsearch,andrestc/elasticsearch,Microsoft/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,Widen/elasticsearch,btiernay/elasticsearch,pozhidaevak/elasticsearch,tahaemin/elasticsearch,weipinghe/elasticsearch,sreeramjayan/elasticsearch,MichaelLiZhou/elasticsearch,SergVro/elasticsearch,i-am-Nathan/elasticsearch,schonfeld/elasticsearch,polyfractal/elasticsearch,sjohnr/elasticsearch,sjohnr/elasticsearch,caengcjd/elasticsearch,elancom/elasticsearch,tebriel/elasticsearch,adrianbk/elasticsearch,jprante/elasticsearch,huanzhong/elasticsearch,kimimj/elasticsearch,mohit/elasticsearch,brandonkearby/elasticsearch,HarishAtGitHub/elasticsearch,markharwood/elasticsearch,kalburgimanjunath/elasticsearch,huanzhong/elasticsearch,winstonewert/elasticsearch,sposam/elasticsearch,MichaelLiZhou/elasticsearch,obourgain/elasticsearch,MjAbuz/elasticsearch,alexkuk/elasticsearch,jchampion/elasticsearch,jimhooker2002/elasticsearch,MisterAndersen/elasticsearch,Chhunlong/elasticsearch,abibell/elasticsearch,jango2015/elasticsearch,rmuir/elasticsearch,tcucchietti/elasticsearch,yongminxia/elasticsearch,vietlq/elasticsearch,sneivandt/elasticsearch,tsohil/elasticsearch,adrianbk/elasticsearch,uboness/elasticsearch,palecur/elasticsearch,avikurapati/elasticsearch,masaruh/elasticsearch,Kakakakakku/elasticsearch,mm0/elasticsearch,JackyMai/elasticsearch,bestwpw/elasticsearch,rlugojr/elasticsearch,mapr/elasticsearch,mm0/elasticsearch,mnylen/elasticsearch,Siddartha07/elasticsearch,koxa29/elasticsearch,SergVro/elasticsearch,hirdesh2008/elasticsearch,MjAbuz/elasticsearch,trangvh/elasticsearch,HonzaKral/elasticsearch,koxa29/elasticsearch,yanjunh/elasticsearch,clintongormley/elasticsearch,18098924759/elasticsearch,ulkas/elasticsearch,hechunwen/elasticsearch,hanst/elasticsearch,nknize/elasticsearch,wayeast/elasticsearch,Shepard1212/elasticsearch,naveenhooda2000/elasticsearch,alexksikes/elasticsearch,Kakakakakku/elasticsearch,Uiho/elasticsearch,djschny/elasticsearch,wittyameta/elasticsearch,pranavraman/elasticsearch,palecur/elasticsearch,peschlowp/elasticsearch,Kakakakakku/elasticsearch,mortonsykes/elasticsearch,xingguang2013/elasticsearch,NBSW/elasticsearch,LewayneNaidoo/elasticsearch,LewayneNaidoo/elasticsearch,episerver/elasticsearch,vingupta3/elasticsearch,hydro2k/elasticsearch,strapdata/elassandra5-rc,queirozfcom/elasticsearch,Liziyao/elasticsearch,martinstuga/elasticsearch,mrorii/elasticsearch,ydsakyclguozi/elasticsearch,cwurm/elasticsearch,AleksKochev/elasticsearch,F0lha/elasticsearch,myelin/elasticsearch,gfyoung/elasticsearch,Siddartha07/elasticsearch,peschlowp/elasticsearch,JSCooke/elasticsearch,alexshadow007/elasticsearch,uboness/elasticsearch,dylan8902/elasticsearch,tahaemin/elasticsearch,hydro2k/elasticsearch,truemped/elasticsearch,ouyangkongtong/elasticsearch,brwe/elasticsearch,AndreKR/elasticsearch,LeoYao/elasticsearch,sposam/elasticsearch,mrorii/elasticsearch,markwalkom/elasticsearch,mmaracic/elasticsearch,episerver/elasticsearch,sauravmondallive/elasticsearch,kaneshin/elasticsearch,MaineC/elasticsearch,marcuswr/elasticsearch-dateline,maddin2016/elasticsearch,uschindler/elasticsearch,xingguang2013/elasticsearch,diendt/elasticsearch,yanjunh/elasticsearch,fooljohnny/elasticsearch,jw0201/elastic,koxa29/elasticsearch,socialrank/elasticsearch,KimTaehee/elasticsearch,iantruslove/elasticsearch,queirozfcom/elasticsearch,kalimatas/elasticsearch,sneivandt/elasticsearch,springning/elasticsearch,kingaj/elasticsearch,chirilo/elasticsearch,linglaiyao1314/elasticsearch,wbowling/elasticsearch,Chhunlong/elasticsearch,likaiwalkman/elasticsearch,nellicus/elasticsearch,jaynblue/elasticsearch,davidvgalbraith/elasticsearch,uboness/elasticsearch,bawse/elasticsearch,skearns64/elasticsearch,strapdata/elassandra-test,jw0201/elastic,abibell/elasticsearch,petabytedata/elasticsearch,linglaiyao1314/elasticsearch,chrismwendt/elasticsearch,skearns64/elasticsearch,dantuffery/elasticsearch,drewr/elasticsearch,nezirus/elasticsearch,iantruslove/elasticsearch,wayeast/elasticsearch,javachengwc/elasticsearch,kcompher/elasticsearch,ouyangkongtong/elasticsearch,wayeast/elasticsearch,yuy168/elasticsearch,djschny/elasticsearch,opendatasoft/elasticsearch,kubum/elasticsearch,diendt/elasticsearch,mapr/elasticsearch,smflorentino/elasticsearch,lightslife/elasticsearch,mmaracic/elasticsearch,sjohnr/elasticsearch,iacdingping/elasticsearch,ImpressTV/elasticsearch,HarishAtGitHub/elasticsearch,NBSW/elasticsearch,elasticdog/elasticsearch,lks21c/elasticsearch,PhaedrusTheGreek/elasticsearch,njlawton/elasticsearch,liweinan0423/elasticsearch,hydro2k/elasticsearch,petmit/elasticsearch,Charlesdong/elasticsearch,alexkuk/elasticsearch,lightslife/elasticsearch,achow/elasticsearch,huanzhong/elasticsearch,sscarduzio/elasticsearch,hanst/elasticsearch,pozhidaevak/elasticsearch,mjhennig/elasticsearch,fred84/elasticsearch,rmuir/elasticsearch,springning/elasticsearch,Flipkart/elasticsearch,nknize/elasticsearch,nazarewk/elasticsearch,dataduke/elasticsearch,ckclark/elasticsearch,achow/elasticsearch,Siddartha07/elasticsearch,cnfire/elasticsearch-1,easonC/elasticsearch,iamjakob/elasticsearch,andrewvc/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,Shepard1212/elasticsearch,brwe/elasticsearch,xpandan/elasticsearch,elancom/elasticsearch,rlugojr/elasticsearch,khiraiwa/elasticsearch,franklanganke/elasticsearch,karthikjaps/elasticsearch,sdauletau/elasticsearch,mmaracic/elasticsearch,feiqitian/elasticsearch,vingupta3/elasticsearch,andrestc/elasticsearch,TonyChai24/ESSource,hanswang/elasticsearch,EasonYi/elasticsearch,Helen-Zhao/elasticsearch,kunallimaye/elasticsearch,drewr/elasticsearch,snikch/elasticsearch,strapdata/elassandra-test,mcku/elasticsearch,snikch/elasticsearch,lmenezes/elasticsearch,Chhunlong/elasticsearch,vroyer/elasticassandra,xingguang2013/elasticsearch,vvcephei/elasticsearch,brandonkearby/elasticsearch,szroland/elasticsearch,a2lin/elasticsearch,LeoYao/elasticsearch,kimimj/elasticsearch,fforbeck/elasticsearch,rento19962/elasticsearch,huypx1292/elasticsearch,VukDukic/elasticsearch,xingguang2013/elasticsearch,heng4fun/elasticsearch,kunallimaye/elasticsearch,btiernay/elasticsearch,strapdata/elassandra-test,ImpressTV/elasticsearch,beiske/elasticsearch,mapr/elasticsearch,sarwarbhuiyan/elasticsearch,lydonchandra/elasticsearch,amaliujia/elasticsearch,infusionsoft/elasticsearch,xpandan/elasticsearch,hafkensite/elasticsearch,Shekharrajak/elasticsearch,weipinghe/elasticsearch,schonfeld/elasticsearch,Widen/elasticsearch,jsgao0/elasticsearch,adrianbk/elasticsearch,abhijitiitr/es,huypx1292/elasticsearch,alexbrasetvik/elasticsearch,kimimj/elasticsearch,trangvh/elasticsearch,vvcephei/elasticsearch,petmit/elasticsearch,18098924759/elasticsearch,karthikjaps/elasticsearch,hanswang/elasticsearch,thecocce/elasticsearch,AleksKochev/elasticsearch,mcku/elasticsearch,pranavraman/elasticsearch,ThalaivaStars/OrgRepo1,dataduke/elasticsearch,salyh/elasticsearch,MjAbuz/elasticsearch,jsgao0/elasticsearch,hirdesh2008/elasticsearch,caengcjd/elasticsearch,huypx1292/elasticsearch,queirozfcom/elasticsearch,Asimov4/elasticsearch,scorpionvicky/elasticsearch,ouyangkongtong/elasticsearch,AshishThakur/elasticsearch,ThalaivaStars/OrgRepo1,areek/elasticsearch,ulkas/elasticsearch,GlenRSmith/elasticsearch,lzo/elasticsearch-1,ivansun1010/elasticsearch,s1monw/elasticsearch,franklanganke/elasticsearch,davidvgalbraith/elasticsearch,weipinghe/elasticsearch,ImpressTV/elasticsearch,sreeramjayan/elasticsearch,umeshdangat/elasticsearch,aglne/elasticsearch,jpountz/elasticsearch,Ansh90/elasticsearch,loconsolutions/elasticsearch,wangyuxue/elasticsearch,geidies/elasticsearch,vroyer/elassandra,jw0201/elastic,mnylen/elasticsearch,strapdata/elassandra-test,dantuffery/elasticsearch,lmtwga/elasticsearch,btiernay/elasticsearch,strapdata/elassandra,kenshin233/elasticsearch,alexshadow007/elasticsearch,scottsom/elasticsearch,rento19962/elasticsearch,sreeramjayan/elasticsearch,pritishppai/elasticsearch,jimhooker2002/elasticsearch,rmuir/elasticsearch,petabytedata/elasticsearch,strapdata/elassandra,MetSystem/elasticsearch,lks21c/elasticsearch,sarwarbhuiyan/elasticsearch,strapdata/elassandra5-rc,sauravmondallive/elasticsearch,gingerwizard/elasticsearch,apepper/elasticsearch,dongjoon-hyun/elasticsearch,slavau/elasticsearch,smflorentino/elasticsearch,libosu/elasticsearch,mjason3/elasticsearch,cnfire/elasticsearch-1,wenpos/elasticsearch,lightslife/elasticsearch,easonC/elasticsearch,gmarz/elasticsearch,pritishppai/elasticsearch,libosu/elasticsearch,artnowo/elasticsearch,Asimov4/elasticsearch,maddin2016/elasticsearch,pranavraman/elasticsearch,tahaemin/elasticsearch,Ansh90/elasticsearch,scorpionvicky/elasticsearch,onegambler/elasticsearch,sposam/elasticsearch,lydonchandra/elasticsearch,queirozfcom/elasticsearch,geidies/elasticsearch,elasticdog/elasticsearch,bestwpw/elasticsearch,sposam/elasticsearch,vvcephei/elasticsearch,combinatorist/elasticsearch,YosuaMichael/elasticsearch,nilabhsagar/elasticsearch,hafkensite/elasticsearch,zhiqinghuang/elasticsearch,lzo/elasticsearch-1,likaiwalkman/elasticsearch,zeroctu/elasticsearch,thecocce/elasticsearch,hafkensite/elasticsearch,caengcjd/elasticsearch,wuranbo/elasticsearch,markllama/elasticsearch,markwalkom/elasticsearch,jprante/elasticsearch,iantruslove/elasticsearch,Widen/elasticsearch,mrorii/elasticsearch,pranavraman/elasticsearch,franklanganke/elasticsearch,Rygbee/elasticsearch,alexshadow007/elasticsearch,nrkkalyan/elasticsearch,Stacey-Gammon/elasticsearch,achow/elasticsearch,kkirsche/elasticsearch,jprante/elasticsearch,wuranbo/elasticsearch,tahaemin/elasticsearch,infusionsoft/elasticsearch,jsgao0/elasticsearch,salyh/elasticsearch,Shepard1212/elasticsearch,jango2015/elasticsearch,jchampion/elasticsearch,ivansun1010/elasticsearch,btiernay/elasticsearch,mkis-/elasticsearch,sscarduzio/elasticsearch,jw0201/elastic,s1monw/elasticsearch,elancom/elasticsearch,aglne/elasticsearch,springning/elasticsearch,chrismwendt/elasticsearch,kunallimaye/elasticsearch,mortonsykes/elasticsearch,iantruslove/elasticsearch,strapdata/elassandra-test,YosuaMichael/elasticsearch,nomoa/elasticsearch,markwalkom/elasticsearch,vorce/es-metrics,sdauletau/elasticsearch,hanswang/elasticsearch,ivansun1010/elasticsearch,areek/elasticsearch,uschindler/elasticsearch,karthikjaps/elasticsearch,SergVro/elasticsearch,TonyChai24/ESSource,robin13/elasticsearch,xingguang2013/elasticsearch,infusionsoft/elasticsearch,mmaracic/elasticsearch,wittyameta/elasticsearch,zkidkid/elasticsearch,camilojd/elasticsearch,tebriel/elasticsearch,ckclark/elasticsearch,dpursehouse/elasticsearch,btiernay/elasticsearch,combinatorist/elasticsearch,kkirsche/elasticsearch,bestwpw/elasticsearch,synhershko/elasticsearch,Shepard1212/elasticsearch,fubuki/elasticsearch,wittyameta/elasticsearch,huypx1292/elasticsearch,franklanganke/elasticsearch,markwalkom/elasticsearch,acchen97/elasticsearch,milodky/elasticsearch,rajanm/elasticsearch,yuy168/elasticsearch,kenshin233/elasticsearch,yuy168/elasticsearch,schonfeld/elasticsearch,tsohil/elasticsearch,hafkensite/elasticsearch,lzo/elasticsearch-1,iacdingping/elasticsearch,fforbeck/elasticsearch,PhaedrusTheGreek/elasticsearch,janmejay/elasticsearch,golubev/elasticsearch,gfyoung/elasticsearch,pablocastro/elasticsearch,EasonYi/elasticsearch,yynil/elasticsearch,wbowling/elasticsearch,karthikjaps/elasticsearch,rento19962/elasticsearch,StefanGor/elasticsearch,GlenRSmith/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,JervyShi/elasticsearch,mute/elasticsearch,girirajsharma/elasticsearch,masaruh/elasticsearch,milodky/elasticsearch,camilojd/elasticsearch,xuzha/elasticsearch,sarwarbhuiyan/elasticsearch,nellicus/elasticsearch,njlawton/elasticsearch,skearns64/elasticsearch,hanswang/elasticsearch,kaneshin/elasticsearch,ulkas/elasticsearch,lmtwga/elasticsearch,SergVro/elasticsearch,thecocce/elasticsearch,ThalaivaStars/OrgRepo1,strapdata/elassandra5-rc,szroland/elasticsearch,drewr/elasticsearch,jimczi/elasticsearch,vingupta3/elasticsearch,girirajsharma/elasticsearch,acchen97/elasticsearch,Liziyao/elasticsearch,nezirus/elasticsearch,kalburgimanjunath/elasticsearch,pablocastro/elasticsearch,yynil/elasticsearch,gingerwizard/elasticsearch,andrewvc/elasticsearch,andrejserafim/elasticsearch,kevinkluge/elasticsearch,awislowski/elasticsearch,gmarz/elasticsearch,janmejay/elasticsearch,jango2015/elasticsearch,uboness/elasticsearch,phani546/elasticsearch,wbowling/elasticsearch,javachengwc/elasticsearch,Shepard1212/elasticsearch,alexkuk/elasticsearch,masterweb121/elasticsearch,kenshin233/elasticsearch,lightslife/elasticsearch,sreeramjayan/elasticsearch,nomoa/elasticsearch,hirdesh2008/elasticsearch,kkirsche/elasticsearch,feiqitian/elasticsearch,nomoa/elasticsearch,tcucchietti/elasticsearch,slavau/elasticsearch,Stacey-Gammon/elasticsearch,easonC/elasticsearch,mkis-/elasticsearch,coding0011/elasticsearch,Microsoft/elasticsearch,andrejserafim/elasticsearch,linglaiyao1314/elasticsearch,abhijitiitr/es,elasticdog/elasticsearch,AndreKR/elasticsearch,YosuaMichael/elasticsearch,TonyChai24/ESSource,zeroctu/elasticsearch,trangvh/elasticsearch,Rygbee/elasticsearch,kevinkluge/elasticsearch,kenshin233/elasticsearch,JSCooke/elasticsearch,mapr/elasticsearch,TonyChai24/ESSource,StefanGor/elasticsearch,iamjakob/elasticsearch,winstonewert/elasticsearch,a2lin/elasticsearch,areek/elasticsearch,hanswang/elasticsearch,Siddartha07/elasticsearch,mm0/elasticsearch,MisterAndersen/elasticsearch,andrejserafim/elasticsearch,janmejay/elasticsearch,ivansun1010/elasticsearch,xuzha/elasticsearch,nknize/elasticsearch,jaynblue/elasticsearch,rento19962/elasticsearch,LeoYao/elasticsearch,mjhennig/elasticsearch,tahaemin/elasticsearch,himanshuag/elasticsearch,drewr/elasticsearch,beiske/elasticsearch,kalburgimanjunath/elasticsearch,phani546/elasticsearch,abibell/elasticsearch,markllama/elasticsearch,LewayneNaidoo/elasticsearch,linglaiyao1314/elasticsearch,pranavraman/elasticsearch,gingerwizard/elasticsearch,Clairebi/ElasticsearchClone,areek/elasticsearch,C-Bish/elasticsearch,iamjakob/elasticsearch,mnylen/elasticsearch,szroland/elasticsearch,Ansh90/elasticsearch,kingaj/elasticsearch,sarwarbhuiyan/elasticsearch,pablocastro/elasticsearch,rajanm/elasticsearch,apepper/elasticsearch,sc0ttkclark/elasticsearch,jimhooker2002/elasticsearch,mapr/elasticsearch,Fsero/elasticsearch,lmtwga/elasticsearch,kunallimaye/elasticsearch,marcuswr/elasticsearch-dateline,vvcephei/elasticsearch,rhoml/elasticsearch,mm0/elasticsearch,rhoml/elasticsearch,IanvsPoplicola/elasticsearch,wuranbo/elasticsearch,golubev/elasticsearch,mohsinh/elasticsearch,qwerty4030/elasticsearch,huanzhong/elasticsearch,yongminxia/elasticsearch,kingaj/elasticsearch,amit-shar/elasticsearch,ESamir/elasticsearch,zkidkid/elasticsearch,khiraiwa/elasticsearch,JervyShi/elasticsearch,milodky/elasticsearch,girirajsharma/elasticsearch,martinstuga/elasticsearch,mohit/elasticsearch,infusionsoft/elasticsearch,ricardocerq/elasticsearch,ulkas/elasticsearch,Flipkart/elasticsearch,wangtuo/elasticsearch,18098924759/elasticsearch,petmit/elasticsearch,smflorentino/elasticsearch,pablocastro/elasticsearch,rhoml/elasticsearch,peschlowp/elasticsearch,spiegela/elasticsearch,tkssharma/elasticsearch,MetSystem/elasticsearch,yanjunh/elasticsearch,pablocastro/elasticsearch,henakamaMSFT/elasticsearch,ThiagoGarciaAlves/elasticsearch,cwurm/elasticsearch,tsohil/elasticsearch,HarishAtGitHub/elasticsearch,Charlesdong/elasticsearch,loconsolutions/elasticsearch,shreejay/elasticsearch,amit-shar/elasticsearch,mohit/elasticsearch,Flipkart/elasticsearch,Microsoft/elasticsearch,Stacey-Gammon/elasticsearch,shreejay/elasticsearch,kenshin233/elasticsearch,xpandan/elasticsearch,loconsolutions/elasticsearch,fekaputra/elasticsearch,kevinkluge/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,Brijeshrpatel9/elasticsearch,ESamir/elasticsearch,mortonsykes/elasticsearch,luiseduardohdbackup/elasticsearch,vingupta3/elasticsearch,raishiv/elasticsearch,heng4fun/elasticsearch,ydsakyclguozi/elasticsearch,onegambler/elasticsearch,shreejay/elasticsearch,nazarewk/elasticsearch,KimTaehee/elasticsearch,AshishThakur/elasticsearch,Ansh90/elasticsearch,fooljohnny/elasticsearch,socialrank/elasticsearch,bestwpw/elasticsearch,MaineC/elasticsearch,PhaedrusTheGreek/elasticsearch,hirdesh2008/elasticsearch,geidies/elasticsearch,masterweb121/elasticsearch,kalimatas/elasticsearch,franklanganke/elasticsearch,abibell/elasticsearch,mute/elasticsearch,i-am-Nathan/elasticsearch,kaneshin/elasticsearch,polyfractal/elasticsearch,lydonchandra/elasticsearch,nezirus/elasticsearch,zhaocloud/elasticsearch,achow/elasticsearch,hanswang/elasticsearch,springning/elasticsearch,AleksKochev/elasticsearch,Fsero/elasticsearch,GlenRSmith/elasticsearch,queirozfcom/elasticsearch,Helen-Zhao/elasticsearch,fernandozhu/elasticsearch,mgalushka/elasticsearch,sc0ttkclark/elasticsearch,vroyer/elassandra,Kakakakakku/elasticsearch,C-Bish/elasticsearch,himanshuag/elasticsearch,VukDukic/elasticsearch,koxa29/elasticsearch,jeteve/elasticsearch,nellicus/elasticsearch,KimTaehee/elasticsearch,Fsero/elasticsearch,diendt/elasticsearch,qwerty4030/elasticsearch,robin13/elasticsearch,kaneshin/elasticsearch,Collaborne/elasticsearch,alexkuk/elasticsearch,mjason3/elasticsearch,gfyoung/elasticsearch,djschny/elasticsearch,wimvds/elasticsearch,naveenhooda2000/elasticsearch,sc0ttkclark/elasticsearch,jchampion/elasticsearch,koxa29/elasticsearch,yongminxia/elasticsearch,fooljohnny/elasticsearch,yuy168/elasticsearch,heng4fun/elasticsearch,humandb/elasticsearch,ydsakyclguozi/elasticsearch,trangvh/elasticsearch,wayeast/elasticsearch,mjason3/elasticsearch,JSCooke/elasticsearch,spiegela/elasticsearch,jprante/elasticsearch,bestwpw/elasticsearch,vingupta3/elasticsearch,ZTE-PaaS/elasticsearch,IanvsPoplicola/elasticsearch,tcucchietti/elasticsearch,TonyChai24/ESSource,SaiprasadKrishnamurthy/elasticsearch,obourgain/elasticsearch,liweinan0423/elasticsearch,dataduke/elasticsearch,dylan8902/elasticsearch,lchennup/elasticsearch,amit-shar/elasticsearch,kunallimaye/elasticsearch,nilabhsagar/elasticsearch,myelin/elasticsearch,alexbrasetvik/elasticsearch,alexkuk/elasticsearch,chrismwendt/elasticsearch,umeshdangat/elasticsearch,ZTE-PaaS/elasticsearch,synhershko/elasticsearch,mkis-/elasticsearch,palecur/elasticsearch,fred84/elasticsearch,slavau/elasticsearch,feiqitian/elasticsearch,KimTaehee/elasticsearch,zeroctu/elasticsearch,VukDukic/elasticsearch,chirilo/elasticsearch,djschny/elasticsearch,mjhennig/elasticsearch,pranavraman/elasticsearch,EasonYi/elasticsearch,YosuaMichael/elasticsearch,awislowski/elasticsearch,Uiho/elasticsearch,yynil/elasticsearch,yanjunh/elasticsearch,boliza/elasticsearch,mute/elasticsearch,wbowling/elasticsearch,sauravmondallive/elasticsearch,tkssharma/elasticsearch,lydonchandra/elasticsearch,javachengwc/elasticsearch,davidvgalbraith/elasticsearch,skearns64/elasticsearch,snikch/elasticsearch,libosu/elasticsearch,nrkkalyan/elasticsearch,dylan8902/elasticsearch,yongminxia/elasticsearch,wuranbo/elasticsearch,naveenhooda2000/elasticsearch,TonyChai24/ESSource,alexbrasetvik/elasticsearch,vietlq/elasticsearch,markwalkom/elasticsearch,episerver/elasticsearch,glefloch/elasticsearch,artnowo/elasticsearch,achow/elasticsearch,AndreKR/elasticsearch,jaynblue/elasticsearch,wenpos/elasticsearch,amaliujia/elasticsearch,adrianbk/elasticsearch,MetSystem/elasticsearch,brwe/elasticsearch,EasonYi/elasticsearch,i-am-Nathan/elasticsearch,alexksikes/elasticsearch,smflorentino/elasticsearch,himanshuag/elasticsearch,anti-social/elasticsearch,weipinghe/elasticsearch,peschlowp/elasticsearch,MetSystem/elasticsearch,MichaelLiZhou/elasticsearch,caengcjd/elasticsearch,weipinghe/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,mute/elasticsearch,dongjoon-hyun/elasticsearch,SergVro/elasticsearch,elasticdog/elasticsearch,LeoYao/elasticsearch,sc0ttkclark/elasticsearch,mohsinh/elasticsearch,sc0ttkclark/elasticsearch,mikemccand/elasticsearch,luiseduardohdbackup/elasticsearch,Brijeshrpatel9/elasticsearch,kaneshin/elasticsearch,ouyangkongtong/elasticsearch,petmit/elasticsearch,tebriel/elasticsearch,fekaputra/elasticsearch,spiegela/elasticsearch,kaneshin/elasticsearch,koxa29/elasticsearch,a2lin/elasticsearch,rmuir/elasticsearch,chirilo/elasticsearch,chrismwendt/elasticsearch,YosuaMichael/elasticsearch,VukDukic/elasticsearch,clintongormley/elasticsearch,Widen/elasticsearch,Widen/elasticsearch,ckclark/elasticsearch,mm0/elasticsearch,markllama/elasticsearch,nellicus/elasticsearch,fooljohnny/elasticsearch,likaiwalkman/elasticsearch,drewr/elasticsearch,ImpressTV/elasticsearch,andrestc/elasticsearch,PhaedrusTheGreek/elasticsearch,gfyoung/elasticsearch,iamjakob/elasticsearch,kimimj/elasticsearch,cnfire/elasticsearch-1,alexksikes/elasticsearch,xuzha/elasticsearch,kevinkluge/elasticsearch,jaynblue/elasticsearch,kimimj/elasticsearch,infusionsoft/elasticsearch,mjhennig/elasticsearch,elancom/elasticsearch,huanzhong/elasticsearch,beiske/elasticsearch,hanswang/elasticsearch,lchennup/elasticsearch,Shekharrajak/elasticsearch,acchen97/elasticsearch,adrianbk/elasticsearch,mrorii/elasticsearch,kimimj/elasticsearch,xpandan/elasticsearch,nrkkalyan/elasticsearch,vietlq/elasticsearch,hanst/elasticsearch,sdauletau/elasticsearch,fubuki/elasticsearch,phani546/elasticsearch,xuzha/elasticsearch,amit-shar/elasticsearch,artnowo/elasticsearch,cwurm/elasticsearch,awislowski/elasticsearch,smflorentino/elasticsearch,ImpressTV/elasticsearch,Siddartha07/elasticsearch,vroyer/elasticassandra,nilabhsagar/elasticsearch,weipinghe/elasticsearch,MetSystem/elasticsearch,boliza/elasticsearch,franklanganke/elasticsearch,Stacey-Gammon/elasticsearch,jbertouch/elasticsearch,codebunt/elasticsearch,strapdata/elassandra,lzo/elasticsearch-1,nazarewk/elasticsearch,Widen/elasticsearch,codebunt/elasticsearch,nknize/elasticsearch,janmejay/elasticsearch,mohit/elasticsearch,NBSW/elasticsearch,pranavraman/elasticsearch,HarishAtGitHub/elasticsearch,Asimov4/elasticsearch,ricardocerq/elasticsearch,mortonsykes/elasticsearch,sreeramjayan/elasticsearch,jimhooker2002/elasticsearch,nilabhsagar/elasticsearch,lzo/elasticsearch-1,abibell/elasticsearch,bawse/elasticsearch,brwe/elasticsearch,kalimatas/elasticsearch,zhiqinghuang/elasticsearch,Helen-Zhao/elasticsearch,EasonYi/elasticsearch,luiseduardohdbackup/elasticsearch,tsohil/elasticsearch,vroyer/elassandra,boliza/elasticsearch,Flipkart/elasticsearch,kcompher/elasticsearch,Collaborne/elasticsearch,jbertouch/elasticsearch,iantruslove/elasticsearch,wenpos/elasticsearch,fubuki/elasticsearch,Collaborne/elasticsearch,jsgao0/elasticsearch,wayeast/elasticsearch,gingerwizard/elasticsearch,wittyameta/elasticsearch,jimczi/elasticsearch,HonzaKral/elasticsearch,beiske/elasticsearch,18098924759/elasticsearch,jeteve/elasticsearch,awislowski/elasticsearch,wimvds/elasticsearch,hirdesh2008/elasticsearch,fooljohnny/elasticsearch,yongminxia/elasticsearch,gmarz/elasticsearch,wangyuxue/elasticsearch,rlugojr/elasticsearch,wbowling/elasticsearch,mmaracic/elasticsearch,scottsom/elasticsearch,tebriel/elasticsearch,alexksikes/elasticsearch,thecocce/elasticsearch,MichaelLiZhou/elasticsearch,mbrukman/elasticsearch,slavau/elasticsearch,Helen-Zhao/elasticsearch,xingguang2013/elasticsearch,yynil/elasticsearch,zeroctu/elasticsearch,Ansh90/elasticsearch,combinatorist/elasticsearch,fubuki/elasticsearch,areek/elasticsearch,tsohil/elasticsearch,NBSW/elasticsearch,MisterAndersen/elasticsearch,iamjakob/elasticsearch,micpalmia/elasticsearch,wbowling/elasticsearch,likaiwalkman/elasticsearch,xuzha/elasticsearch,amaliujia/elasticsearch,Liziyao/elasticsearch,lydonchandra/elasticsearch,sc0ttkclark/elasticsearch,slavau/elasticsearch,chrismwendt/elasticsearch,kalburgimanjunath/elasticsearch,dongaihua/highlight-elasticsearch,brwe/elasticsearch,ZTE-PaaS/elasticsearch,karthikjaps/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,marcuswr/elasticsearch-dateline,acchen97/elasticsearch,EasonYi/elasticsearch,hanst/elasticsearch,sposam/elasticsearch,LeoYao/elasticsearch,masaruh/elasticsearch,MetSystem/elasticsearch,janmejay/elasticsearch,queirozfcom/elasticsearch,dpursehouse/elasticsearch,vvcephei/elasticsearch,gmarz/elasticsearch,kimchy/elasticsearch"},"new_contents":{"kind":"string","value":"/*\n * Licensed to Elastic Search and Shay Banon under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. Elastic Search licenses this\n * file 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 */\n\npackage org.elasticsearch.rest.action.search;\n\nimport com.google.inject.Inject;\nimport org.elasticsearch.action.ActionListener;\nimport org.elasticsearch.action.search.SearchOperationThreading;\nimport org.elasticsearch.action.search.SearchResponse;\nimport org.elasticsearch.action.search.SearchScrollRequest;\nimport org.elasticsearch.client.Client;\nimport org.elasticsearch.rest.*;\nimport org.elasticsearch.search.Scroll;\nimport org.elasticsearch.util.json.JsonBuilder;\nimport org.elasticsearch.util.settings.Settings;\n\nimport java.io.IOException;\n\nimport static org.elasticsearch.rest.RestRequest.Method.*;\nimport static org.elasticsearch.rest.RestResponse.Status.*;\nimport static org.elasticsearch.rest.action.support.RestJsonBuilder.*;\nimport static org.elasticsearch.util.TimeValue.*;\n\n/**\n * @author kimchy (shay.banon)\n */\npublic class RestSearchScrollAction extends BaseRestHandler {\n\n @Inject public RestSearchScrollAction(Settings settings, Client client, RestController controller) {\n super(settings, client);\n\n controller.registerHandler(GET, \"/_search/scroll\", this);\n controller.registerHandler(POST, \"/_search/scroll\", this);\n controller.registerHandler(GET, \"/_search/scroll/{scrollId}\", this);\n controller.registerHandler(POST, \"/_search/scroll/{scrollId}\", this);\n }\n\n @Override public void handleRequest(final RestRequest request, final RestChannel channel) {\n SearchScrollRequest searchScrollRequest = new SearchScrollRequest(request.param(\"scrollId\"));\n try {\n String scroll = request.param(\"scroll\");\n if (scroll != null) {\n searchScrollRequest.scroll(new Scroll(parseTimeValue(scroll, null)));\n }\n searchScrollRequest.listenerThreaded(false);\n SearchOperationThreading operationThreading = SearchOperationThreading.fromString(request.param(\"operationThreading\"), SearchOperationThreading.SINGLE_THREAD);\n if (operationThreading == SearchOperationThreading.NO_THREADS) {\n // since we don't spawn, don't allow no_threads, but change it to a single thread\n operationThreading = SearchOperationThreading.SINGLE_THREAD;\n }\n searchScrollRequest.operationThreading(operationThreading);\n } catch (Exception e) {\n try {\n JsonBuilder builder = restJsonBuilder(request);\n channel.sendResponse(new JsonRestResponse(request, BAD_REQUEST, builder.startObject().field(\"error\", e.getMessage()).endObject()));\n } catch (IOException e1) {\n logger.error(\"Failed to send failure response\", e1);\n }\n return;\n }\n\n client.searchScroll(searchScrollRequest, new ActionListener() {\n @Override public void onResponse(SearchResponse response) {\n try {\n JsonBuilder builder = restJsonBuilder(request);\n builder.startObject();\n response.toJson(builder, request);\n builder.endObject();\n channel.sendResponse(new JsonRestResponse(request, OK, builder));\n } catch (Exception e) {\n onFailure(e);\n }\n }\n\n @Override public void onFailure(Throwable e) {\n try {\n channel.sendResponse(new JsonThrowableRestResponse(request, e));\n } catch (IOException e1) {\n logger.error(\"Failed to send failure response\", e1);\n }\n }\n });\n }\n}\n"},"new_file":{"kind":"string","value":"modules/elasticsearch/src/main/java/org/elasticsearch/rest/action/search/RestSearchScrollAction.java"},"old_contents":{"kind":"string","value":"/*\n * Licensed to Elastic Search and Shay Banon under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. Elastic Search licenses this\n * file 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 */\n\npackage org.elasticsearch.rest.action.search;\n\nimport com.google.inject.Inject;\nimport org.elasticsearch.action.ActionListener;\nimport org.elasticsearch.action.search.SearchOperationThreading;\nimport org.elasticsearch.action.search.SearchResponse;\nimport org.elasticsearch.action.search.SearchScrollRequest;\nimport org.elasticsearch.client.Client;\nimport org.elasticsearch.rest.*;\nimport org.elasticsearch.search.Scroll;\nimport org.elasticsearch.util.json.JsonBuilder;\nimport org.elasticsearch.util.settings.Settings;\n\nimport java.io.IOException;\n\nimport static org.elasticsearch.rest.RestRequest.Method.*;\nimport static org.elasticsearch.rest.RestResponse.Status.*;\nimport static org.elasticsearch.rest.action.support.RestJsonBuilder.*;\nimport static org.elasticsearch.util.TimeValue.*;\n\n/**\n * @author kimchy (shay.banon)\n */\npublic class RestSearchScrollAction extends BaseRestHandler {\n\n @Inject public RestSearchScrollAction(Settings settings, Client client, RestController controller) {\n super(settings, client);\n\n controller.registerHandler(GET, \"/_searchScroll\", this);\n controller.registerHandler(POST, \"/_searchScroll\", this);\n controller.registerHandler(GET, \"/_searchScroll/{scrollId}\", this);\n controller.registerHandler(POST, \"/_searchScroll/{scrollId}\", this);\n }\n\n @Override public void handleRequest(final RestRequest request, final RestChannel channel) {\n SearchScrollRequest searchScrollRequest = new SearchScrollRequest(request.param(\"scrollId\"));\n try {\n String scroll = request.param(\"scroll\");\n if (scroll != null) {\n searchScrollRequest.scroll(new Scroll(parseTimeValue(scroll, null)));\n }\n searchScrollRequest.listenerThreaded(false);\n SearchOperationThreading operationThreading = SearchOperationThreading.fromString(request.param(\"operationThreading\"), SearchOperationThreading.SINGLE_THREAD);\n if (operationThreading == SearchOperationThreading.NO_THREADS) {\n // since we don't spawn, don't allow no_threads, but change it to a single thread\n operationThreading = SearchOperationThreading.SINGLE_THREAD;\n }\n searchScrollRequest.operationThreading(operationThreading);\n } catch (Exception e) {\n try {\n JsonBuilder builder = restJsonBuilder(request);\n channel.sendResponse(new JsonRestResponse(request, BAD_REQUEST, builder.startObject().field(\"error\", e.getMessage()).endObject()));\n } catch (IOException e1) {\n logger.error(\"Failed to send failure response\", e1);\n }\n return;\n }\n\n client.searchScroll(searchScrollRequest, new ActionListener() {\n @Override public void onResponse(SearchResponse response) {\n try {\n JsonBuilder builder = restJsonBuilder(request);\n builder.startObject();\n response.toJson(builder, request);\n builder.endObject();\n channel.sendResponse(new JsonRestResponse(request, OK, builder));\n } catch (Exception e) {\n onFailure(e);\n }\n }\n\n @Override public void onFailure(Throwable e) {\n try {\n channel.sendResponse(new JsonThrowableRestResponse(request, e));\n } catch (IOException e1) {\n logger.error(\"Failed to send failure response\", e1);\n }\n }\n });\n }\n}\n"},"message":{"kind":"string","value":"check search scroll URI to /_search/scroll from /_searchScroll\n"},"old_file":{"kind":"string","value":"modules/elasticsearch/src/main/java/org/elasticsearch/rest/action/search/RestSearchScrollAction.java"},"subject":{"kind":"string","value":"check search scroll URI to /_search/scroll from /_searchScroll"},"git_diff":{"kind":"string","value":"odules/elasticsearch/src/main/java/org/elasticsearch/rest/action/search/RestSearchScrollAction.java\n @Inject public RestSearchScrollAction(Settings settings, Client client, RestController controller) {\n super(settings, client);\n \n controller.registerHandler(GET, \"/_searchScroll\", this);\n controller.registerHandler(POST, \"/_searchScroll\", this);\n controller.registerHandler(GET, \"/_searchScroll/{scrollId}\", this);\n controller.registerHandler(POST, \"/_searchScroll/{scrollId}\", this);\n controller.registerHandler(GET, \"/_search/scroll\", this);\n controller.registerHandler(POST, \"/_search/scroll\", this);\n controller.registerHandler(GET, \"/_search/scroll/{scrollId}\", this);\n controller.registerHandler(POST, \"/_search/scroll/{scrollId}\", this);\n }\n \n @Override public void handleRequest(final RestRequest request, final RestChannel channel) {"}}},{"rowIdx":847,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"5d381410e48b83baa500704e1f71548e47f447a3"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"sosy-lab/java-smt,sosy-lab/java-smt,sosy-lab/java-smt,sosy-lab/java-smt,sosy-lab/java-smt"},"new_contents":{"kind":"string","value":"/*\n * JavaSMT is an API wrapper for a collection of SMT solvers.\n * This file is part of JavaSMT.\n *\n * Copyright (C) 2007-2016 Dirk Beyer\n * All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.sosy_lab.java_smt.solvers.mathsat5;\n\nimport static org.sosy_lab.java_smt.solvers.mathsat5.Mathsat5NativeApi.msat_assert_formula;\nimport static org.sosy_lab.java_smt.solvers.mathsat5.Mathsat5NativeApi.msat_create_itp_group;\nimport static org.sosy_lab.java_smt.solvers.mathsat5.Mathsat5NativeApi.msat_get_interpolant;\nimport static org.sosy_lab.java_smt.solvers.mathsat5.Mathsat5NativeApi.msat_push_backtrack_point;\nimport static org.sosy_lab.java_smt.solvers.mathsat5.Mathsat5NativeApi.msat_set_itp_group;\n\nimport com.google.common.base.Preconditions;\nimport com.google.common.base.Strings;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Lists;\nimport com.google.common.primitives.Ints;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport org.sosy_lab.common.ShutdownNotifier;\nimport org.sosy_lab.java_smt.api.BooleanFormula;\nimport org.sosy_lab.java_smt.api.InterpolatingProverEnvironment;\nimport org.sosy_lab.java_smt.api.SolverContext.ProverOptions;\nimport org.sosy_lab.java_smt.api.SolverException;\n\nclass Mathsat5InterpolatingProver extends Mathsat5AbstractProver\n implements InterpolatingProverEnvironment {\n\n private static final ImmutableSet ALLOWED_FAILURE_MESSAGES =\n ImmutableSet.of(\n \"impossible to build a suitable congruence graph!\",\n \"can't build ie-local interpolant\",\n \"set_raised on an already-raised proof\",\n \"splitting of AB-mixed terms not supported\",\n \"Hypothesis belongs neither to A nor to B\",\n \"FP<->BV combination unsupported by the current configuration\",\n \"cur_eq unknown to the classifier\",\n \"unknown constraint in the ItpMapper\",\n \"AB-mixed term not found in eq_itp map\",\n \"uncolored atom found in Array proof\",\n \"uncolorable Array proof\",\n \"arr: proof splitting not supported\");\n private static final ImmutableSet ALLOWED_FAILURE_MESSAGE_PREFIXES =\n ImmutableSet.of(\"uncolorable NA lemma\");\n\n Mathsat5InterpolatingProver(\n Mathsat5SolverContext pMgr,\n ShutdownNotifier pShutdownNotifier,\n Mathsat5FormulaCreator creator,\n Set options) {\n super(pMgr, options, creator, pShutdownNotifier);\n }\n\n @Override\n protected void createConfig(Map pConfig) {\n pConfig.put(\"interpolation\", \"true\");\n pConfig.put(\"model_generation\", \"true\");\n pConfig.put(\"theory.bv.eager\", \"false\");\n }\n\n @Override\n public Integer addConstraint(BooleanFormula f) {\n Preconditions.checkState(!closed);\n int group = msat_create_itp_group(curEnv);\n msat_set_itp_group(curEnv, group);\n long t = creator.extractInfo(f);\n msat_assert_formula(curEnv, t);\n return group;\n }\n\n @Override\n public void push() {\n Preconditions.checkState(!closed);\n msat_push_backtrack_point(curEnv);\n }\n\n @Override\n protected long getMsatModel() throws SolverException {\n // Interpolation in MathSAT is buggy at least for UFs+Ints and sometimes returns a wrong \"SAT\".\n // In this case, model generation fails and users should try again without interpolation.\n // Example failures: \"Invalid model\", \"non-integer model value\"\n // As this is a bug in MathSAT and not in our code, we throw a SolverException.\n // We do it only in InterpolatingProver because without interpolation this is not expected.\n try {\n return super.getMsatModel();\n } catch (IllegalArgumentException e) {\n String msg = Strings.emptyToNull(e.getMessage());\n throw new SolverException(\n \"msat_get_model failed\"\n + (msg != null ? \" with \\\"\" + msg + \"\\\"\" : \"\")\n + \", probably the actual problem is interpolation\",\n e);\n }\n }\n\n @Override\n public BooleanFormula getInterpolant(Collection formulasOfA) throws SolverException {\n Preconditions.checkState(!closed);\n\n int[] groupsOfA = Ints.toArray(formulasOfA);\n long itp;\n try {\n itp = msat_get_interpolant(curEnv, groupsOfA);\n } catch (IllegalArgumentException e) {\n final String message = e.getMessage();\n if (!Strings.isNullOrEmpty(message)\n && (ALLOWED_FAILURE_MESSAGES.contains(message)\n || ALLOWED_FAILURE_MESSAGE_PREFIXES.stream().anyMatch(message::startsWith))) {\n // This is not a bug in our code,\n // but a problem of MathSAT which happens during interpolation\n throw new SolverException(message, e);\n }\n throw e;\n }\n return creator.encapsulateBoolean(itp);\n }\n\n @Override\n public List getSeqInterpolants(\n List> partitionedFormulas) throws SolverException {\n // the fallback to a loop is sound and returns an inductive sequence of interpolants\n final List itps = new ArrayList<>();\n for (int i = 1; i < partitionedFormulas.size(); i++) {\n itps.add(\n getInterpolant(Lists.newArrayList(Iterables.concat(partitionedFormulas.subList(0, i)))));\n }\n return itps;\n }\n\n @Override\n public List getTreeInterpolants(\n List> partitionedFormulas, int[] startOfSubTree) {\n throw new UnsupportedOperationException(\n \"directly receiving tree interpolants is not supported.\"\n + \"Use another solver or another strategy for interpolants.\");\n }\n\n @Override\n public T allSat(AllSatCallback callback, List important) {\n // TODO how can we support allsat in MathSat5-interpolation-prover?\n // error: \"allsat is not compatible wwith proof generation\"\n throw new UnsupportedOperationException(\n \"allsat computation is not possible with interpolation prover.\");\n }\n}\n"},"new_file":{"kind":"string","value":"src/org/sosy_lab/java_smt/solvers/mathsat5/Mathsat5InterpolatingProver.java"},"old_contents":{"kind":"string","value":"/*\n * JavaSMT is an API wrapper for a collection of SMT solvers.\n * This file is part of JavaSMT.\n *\n * Copyright (C) 2007-2016 Dirk Beyer\n * All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.sosy_lab.java_smt.solvers.mathsat5;\n\nimport static org.sosy_lab.java_smt.solvers.mathsat5.Mathsat5NativeApi.msat_assert_formula;\nimport static org.sosy_lab.java_smt.solvers.mathsat5.Mathsat5NativeApi.msat_create_itp_group;\nimport static org.sosy_lab.java_smt.solvers.mathsat5.Mathsat5NativeApi.msat_get_interpolant;\nimport static org.sosy_lab.java_smt.solvers.mathsat5.Mathsat5NativeApi.msat_push_backtrack_point;\nimport static org.sosy_lab.java_smt.solvers.mathsat5.Mathsat5NativeApi.msat_set_itp_group;\n\nimport com.google.common.base.Preconditions;\nimport com.google.common.base.Strings;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Lists;\nimport com.google.common.primitives.Ints;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport org.sosy_lab.common.ShutdownNotifier;\nimport org.sosy_lab.java_smt.api.BooleanFormula;\nimport org.sosy_lab.java_smt.api.InterpolatingProverEnvironment;\nimport org.sosy_lab.java_smt.api.SolverContext.ProverOptions;\nimport org.sosy_lab.java_smt.api.SolverException;\n\nclass Mathsat5InterpolatingProver extends Mathsat5AbstractProver\n implements InterpolatingProverEnvironment {\n\n private static final ImmutableSet ALLOWED_FAILURE_MESSAGES =\n ImmutableSet.of(\n \"impossible to build a suitable congruence graph!\",\n \"can't build ie-local interpolant\",\n \"set_raised on an already-raised proof\",\n \"splitting of AB-mixed terms not supported\",\n \"Hypothesis belongs neither to A nor to B\",\n \"FP<->BV combination unsupported by the current configuration\",\n \"cur_eq unknown to the classifier\",\n \"unknown constraint in the ItpMapper\",\n \"AB-mixed term not found in eq_itp map\",\n \"uncolored atom found in Array proof\",\n \"uncolorable Array proof\",\n \"arr: proof splitting not supported\");\n private static final ImmutableSet ALLOWED_FAILURE_MESSAGE_PREFIXES =\n ImmutableSet.of(\"uncolorable NA lemma\");\n\n Mathsat5InterpolatingProver(\n Mathsat5SolverContext pMgr,\n ShutdownNotifier pShutdownNotifier,\n Mathsat5FormulaCreator creator,\n Set options) {\n super(pMgr, options, creator, pShutdownNotifier);\n }\n\n @Override\n protected void createConfig(Map pConfig) {\n pConfig.put(\"interpolation\", \"true\");\n pConfig.put(\"model_generation\", \"true\");\n pConfig.put(\"theory.bv.eager\", \"false\");\n }\n\n @Override\n public Integer addConstraint(BooleanFormula f) {\n Preconditions.checkState(!closed);\n int group = msat_create_itp_group(curEnv);\n msat_set_itp_group(curEnv, group);\n long t = creator.extractInfo(f);\n msat_assert_formula(curEnv, t);\n return group;\n }\n\n @Override\n public void push() {\n Preconditions.checkState(!closed);\n msat_push_backtrack_point(curEnv);\n }\n\n @Override\n protected long getMsatModel() throws SolverException {\n // Interpolation in MathSAT is buggy at least for UFs+Ints and sometimes returns a wrong \"SAT\".\n // In this case, model generation fails and users should try again without interpolation.\n // Example failures: \"Invalid model\", \"non-integer model value\"\n // As this is a bug in MathSAT and not in our code, we throw a SolverException.\n // We do it only in InterpolatingProver because without interpolation this is not expected.\n try {\n return super.getMsatModel();\n } catch (IllegalArgumentException e) {\n String msg = Strings.emptyToNull(e.getMessage());\n throw new SolverException(\n \"msat_get_model failed\"\n + (msg != null ? \" with \\\"\" + msg + \"\\\"\" : \"\")\n + \", probably the actual problem is interpolation\",\n e);\n }\n }\n\n @Override\n public BooleanFormula getInterpolant(Collection formulasOfA) throws SolverException {\n Preconditions.checkState(!closed);\n\n int[] groupsOfA = Ints.toArray(formulasOfA);\n long itp;\n try {\n itp = msat_get_interpolant(curEnv, groupsOfA);\n } catch (IllegalArgumentException e) {\n final String message = e.getMessage();\n if (!Strings.isNullOrEmpty(message)\n && (ALLOWED_FAILURE_MESSAGES.contains(message)\n || ALLOWED_FAILURE_MESSAGE_PREFIXES.stream().anyMatch(message::startsWith))) {\n // This is not a bug in our code,\n // but a problem of MathSAT which happens during interpolation\n throw new SolverException(message, e);\n }\n throw e;\n }\n return creator.encapsulateBoolean(itp);\n }\n\n @Override\n public List getSeqInterpolants(\n List> partitionedFormulas) throws SolverException {\n // the fallback to a loop is sound and returns an inductive sequence of interpolants\n final List itps = new ArrayList<>();\n for (int i = 0; i < partitionedFormulas.size(); i++) {\n itps.add(\n getInterpolant(Lists.newArrayList(Iterables.concat(partitionedFormulas.subList(0, i)))));\n }\n return itps;\n }\n\n @Override\n public List getTreeInterpolants(\n List> partitionedFormulas, int[] startOfSubTree) {\n throw new UnsupportedOperationException(\n \"directly receiving tree interpolants is not supported.\"\n + \"Use another solver or another strategy for interpolants.\");\n }\n\n @Override\n public T allSat(AllSatCallback callback, List important) {\n // TODO how can we support allsat in MathSat5-interpolation-prover?\n // error: \"allsat is not compatible wwith proof generation\"\n throw new UnsupportedOperationException(\n \"allsat computation is not possible with interpolation prover.\");\n }\n}\n"},"message":{"kind":"string","value":"bugfix for sequential interpolation loop in Mathsat5-wrapper.\n"},"old_file":{"kind":"string","value":"src/org/sosy_lab/java_smt/solvers/mathsat5/Mathsat5InterpolatingProver.java"},"subject":{"kind":"string","value":"bugfix for sequential interpolation loop in Mathsat5-wrapper."},"git_diff":{"kind":"string","value":"rc/org/sosy_lab/java_smt/solvers/mathsat5/Mathsat5InterpolatingProver.java\n List> partitionedFormulas) throws SolverException {\n // the fallback to a loop is sound and returns an inductive sequence of interpolants\n final List itps = new ArrayList<>();\n for (int i = 0; i < partitionedFormulas.size(); i++) {\n for (int i = 1; i < partitionedFormulas.size(); i++) {\n itps.add(\n getInterpolant(Lists.newArrayList(Iterables.concat(partitionedFormulas.subList(0, i)))));\n }"}}},{"rowIdx":848,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"fd694bedb1586c076ce15c5ae9d99760e2ed5776"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"npatarino/apk-methods-analyzer,itcayman/dex-method-counts,marcoaros/dex-method-counts,liufuxin/dex-method-counts,MaTriXy/dex-method-counts,cncomer/dex-method-counts,luoxiaobin88/dex-method-counts,liqiuzuo/dex-method-counts,Rowandjj/dex-method-counts,itcayman/dex-method-counts,laiqurufeng/dex-method-counts,mihaip/dex-method-counts,Rowandjj/dex-method-counts,liufuxin/dex-method-counts,luoxiaobin88/dex-method-counts,MaTriXy/dex-method-counts,cncomer/dex-method-counts,cpinan/dex-method-counts,npatarino/apk-methods-analyzer,mihaip/dex-method-counts,dambrisco/dex-method-counts,dambrisco/dex-method-counts,liqiuzuo/dex-method-counts,cpinan/dex-method-counts,marcoaros/dex-method-counts,npatarino/apk-methods-analyzer,laiqurufeng/dex-method-counts"},"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 */\n\npackage info.persistent.dex;\n\nimport com.android.dexdeps.DexData;\nimport com.android.dexdeps.DexDataException;\n\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.RandomAccessFile;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.zip.ZipEntry;\nimport java.util.zip.ZipException;\nimport java.util.zip.ZipFile;\n\npublic class Main {\n private static final String CLASSES_DEX = \"classes.dex\";\n\n private boolean includeClasses;\n private String packageFilter;\n private int maxDepth = Integer.MAX_VALUE;\n private DexMethodCounts.Filter filter = DexMethodCounts.Filter.ALL;\n private String[] inputFileNames;\n\n /**\n * Entry point.\n */\n public static void main(String[] args) {\n Main main = new Main();\n main.run(args);\n }\n\n /**\n * Start things up.\n */\n void run(String[] args) {\n try {\n parseArgs(args);\n\n List fileNames = new ArrayList();\n for (String inputFileName : inputFileNames) {\n File file = new File(inputFileName);\n if (file.isDirectory()) {\n String dirPath = file.getAbsolutePath();\n for (String fileInDir: file.list()){\n fileNames.add(dirPath + File.separator + fileInDir);\n }\n } else {\n fileNames.add(inputFileName);\n }\n }\n\n for (String fileName : fileNames) {\n System.out.println(\"Processing \" + fileName);\n RandomAccessFile raf = openInputFile(fileName);\n DexData dexData = new DexData(raf);\n dexData.load();\n DexMethodCounts.generate(\n dexData, includeClasses, packageFilter, maxDepth, filter);\n raf.close();\n }\n System.out.println(\"Overall method count: \" + DexMethodCounts.overallCount);\n } catch (UsageException ue) {\n usage();\n System.exit(2);\n } catch (IOException ioe) {\n if (ioe.getMessage() != null) {\n System.err.println(\"Failed: \" + ioe);\n }\n System.exit(1);\n } catch (DexDataException dde) {\n /* a message was already reported, just bail quietly */\n System.exit(1);\n }\n }\n\n /**\n * Opens an input file, which could be a .dex or a .jar/.apk with a\n * classes.dex inside. If the latter, we extract the contents to a\n * temporary file.\n *\n * @param fileName the name of the file to open\n */\n RandomAccessFile openInputFile(String fileName) throws IOException {\n RandomAccessFile raf;\n\n raf = openInputFileAsZip(fileName);\n if (raf == null) {\n File inputFile = new File(fileName);\n raf = new RandomAccessFile(inputFile, \"r\");\n }\n\n return raf;\n }\n\n /**\n * Tries to open an input file as a Zip archive (jar/apk) with a\n * \"classes.dex\" inside.\n *\n * @param fileName the name of the file to open\n * @return a RandomAccessFile for classes.dex, or null if the input file\n * is not a zip archive\n * @throws IOException if the file isn't found, or it's a zip and\n * classes.dex isn't found inside\n */\n RandomAccessFile openInputFileAsZip(String fileName) throws IOException {\n ZipFile zipFile;\n\n /*\n * Try it as a zip file.\n */\n try {\n zipFile = new ZipFile(fileName);\n } catch (FileNotFoundException fnfe) {\n /* not found, no point in retrying as non-zip */\n System.err.println(\"Unable to open '\" + fileName + \"': \" +\n fnfe.getMessage());\n throw fnfe;\n } catch (ZipException ze) {\n /* not a zip */\n return null;\n }\n\n /*\n * We know it's a zip; see if there's anything useful inside. A\n * failure here results in some type of IOException (of which\n * ZipException is a subclass).\n */\n ZipEntry entry = zipFile.getEntry(CLASSES_DEX);\n if (entry == null) {\n System.err.println(\"Unable to find '\" + CLASSES_DEX +\n \"' in '\" + fileName + \"'\");\n zipFile.close();\n throw new ZipException();\n }\n\n InputStream zis = zipFile.getInputStream(entry);\n\n /*\n * Create a temp file to hold the DEX data, open it, and delete it\n * to ensure it doesn't hang around if we fail.\n */\n File tempFile = File.createTempFile(\"dexdeps\", \".dex\");\n //System.out.println(\"+++ using temp \" + tempFile);\n RandomAccessFile raf = new RandomAccessFile(tempFile, \"rw\");\n tempFile.delete();\n\n /*\n * Copy all data from input stream to output file.\n */\n byte copyBuf[] = new byte[32768];\n int actual;\n\n while (true) {\n actual = zis.read(copyBuf);\n if (actual == -1)\n break;\n\n raf.write(copyBuf, 0, actual);\n }\n\n zis.close();\n raf.seek(0);\n\n return raf;\n }\n\n void parseArgs(String[] args) {\n int idx;\n\n for (idx = 0; idx < args.length; idx++) {\n String arg = args[idx];\n\n if (arg.equals(\"--\") || !arg.startsWith(\"--\")) {\n break;\n } else if (arg.equals(\"--include-classes\")) {\n includeClasses = true;\n } else if (arg.startsWith(\"--package-filter=\")) {\n packageFilter = arg.substring(arg.indexOf('=') + 1);\n } else if (arg.startsWith(\"--max-depth=\")) {\n maxDepth =\n Integer.parseInt(arg.substring(arg.indexOf('=') + 1));\n } else if (arg.startsWith(\"--filter=\")) {\n filter = Enum.valueOf(\n DexMethodCounts.Filter.class,\n arg.substring(arg.indexOf('=') + 1).toUpperCase());\n } else {\n System.err.println(\"Unknown option '\" + arg + \"'\");\n throw new UsageException();\n }\n }\n\n // We expect at least one more argument (file name).\n int fileCount = args.length - idx;\n if (fileCount == 0) {\n throw new UsageException();\n }\n inputFileNames = new String[fileCount];\n System.arraycopy(args, idx, inputFileNames, 0, fileCount);\n }\n\n void usage() {\n System.err.print(\n \"DEX per-package/class method counts v1.0\\n\" +\n \"Usage: dex-method-counts [options] ...\\n\" +\n \"Options:\\n\" +\n \" --include-classes\\n\" +\n \" --package-filter=com.foo.bar\\n\" +\n \" --max-depth=N\\n\"\n );\n }\n\n private static class UsageException extends RuntimeException {}\n}\n"},"new_file":{"kind":"string","value":"src/info/persistent/dex/Main.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 */\n\npackage info.persistent.dex;\n\nimport com.android.dexdeps.DexData;\nimport com.android.dexdeps.DexDataException;\n\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.RandomAccessFile;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.zip.ZipEntry;\nimport java.util.zip.ZipException;\nimport java.util.zip.ZipFile;\n\npublic class Main {\n private static final String CLASSES_DEX = \"classes.dex\";\n\n private boolean includeClasses;\n private String packageFilter;\n private int maxDepth = Integer.MAX_VALUE;\n private DexMethodCounts.Filter filter = DexMethodCounts.Filter.ALL;\n private String[] inputFileNames;\n\n /**\n * Entry point.\n */\n public static void main(String[] args) {\n Main main = new Main();\n main.run(args);\n }\n\n /**\n * Start things up.\n */\n void run(String[] args) {\n try {\n parseArgs(args);\n\n List fileNames = new ArrayList();\n for (String inputFileName : inputFileNames) {\n File file = new File(inputFileName);\n if (file.isDirectory()) {\n String dirPath = file.getAbsolutePath();\n for (String fileInDir: file.list()){\n fileNames.add(dirPath + File.separator + fileInDir);\n }\n } else {\n fileNames.add(inputFileName);\n }\n }\n\n for (String fileName : fileNames) {\n System.out.println(\"Processing \" + fileName);\n RandomAccessFile raf = openInputFile(fileName);\n DexData dexData = new DexData(raf);\n dexData.load();\n DexMethodCounts.generate(\n dexData, includeClasses, packageFilter, maxDepth, filter);\n raf.close();\n }\n System.out.println(\"Overall method count: \" + DexMethodCounts.overallCount);\n } catch (UsageException ue) {\n usage();\n System.exit(2);\n } catch (IOException ioe) {\n if (ioe.getMessage() != null) {\n System.err.println(\"Failed: \" + ioe);\n }\n System.exit(1);\n } catch (DexDataException dde) {\n /* a message was already reported, just bail quietly */\n System.exit(1);\n }\n }\n\n /**\n * Opens an input file, which could be a .dex or a .jar/.apk with a\n * classes.dex inside. If the latter, we extract the contents to a\n * temporary file.\n *\n * @param fileName the name of the file to open\n */\n RandomAccessFile openInputFile(String fileName) throws IOException {\n RandomAccessFile raf;\n\n raf = openInputFileAsZip(fileName);\n if (raf == null) {\n File inputFile = new File(fileName);\n raf = new RandomAccessFile(inputFile, \"r\");\n }\n\n return raf;\n }\n\n /**\n * Tries to open an input file as a Zip archive (jar/apk) with a\n * \"classes.dex\" inside.\n *\n * @param fileName the name of the file to open\n * @return a RandomAccessFile for classes.dex, or null if the input file\n * is not a zip archive\n * @throws IOException if the file isn't found, or it's a zip and\n * classes.dex isn't found inside\n */\n RandomAccessFile openInputFileAsZip(String fileName) throws IOException {\n ZipFile zipFile;\n\n /*\n * Try it as a zip file.\n */\n try {\n zipFile = new ZipFile(fileName);\n } catch (FileNotFoundException fnfe) {\n /* not found, no point in retrying as non-zip */\n System.err.println(\"Unable to open '\" + fileName + \"': \" +\n fnfe.getMessage());\n throw fnfe;\n } catch (ZipException ze) {\n /* not a zip */\n return null;\n }\n\n /*\n * We know it's a zip; see if there's anything useful inside. A\n * failure here results in some type of IOException (of which\n * ZipException is a subclass).\n */\n ZipEntry entry = zipFile.getEntry(CLASSES_DEX);\n if (entry == null) {\n System.err.println(\"Unable to find '\" + CLASSES_DEX +\n \"' in '\" + fileName + \"'\");\n zipFile.close();\n throw new ZipException();\n }\n\n InputStream zis = zipFile.getInputStream(entry);\n\n /*\n * Create a temp file to hold the DEX data, open it, and delete it\n * to ensure it doesn't hang around if we fail.\n */\n File tempFile = File.createTempFile(\"dexdeps\", \".dex\");\n //System.out.println(\"+++ using temp \" + tempFile);\n RandomAccessFile raf = new RandomAccessFile(tempFile, \"rw\");\n tempFile.delete();\n\n /*\n * Copy all data from input stream to output file.\n */\n byte copyBuf[] = new byte[32768];\n int actual;\n\n while (true) {\n actual = zis.read(copyBuf);\n if (actual == -1)\n break;\n\n raf.write(copyBuf, 0, actual);\n }\n\n zis.close();\n raf.seek(0);\n\n return raf;\n }\n\n void parseArgs(String[] args) {\n int idx;\n\n for (idx = 0; idx < args.length; idx++) {\n String arg = args[idx];\n\n if (arg.equals(\"--\") || !arg.startsWith(\"--\")) {\n break;\n } else if (arg.equals(\"--include-classes\")) {\n includeClasses = true;\n } else if (arg.startsWith(\"--package-filter=\")) {\n packageFilter = arg.substring(arg.indexOf('=') + 1);\n } else if (arg.startsWith(\"--max-depth=\")) {\n maxDepth =\n Integer.parseInt(arg.substring(arg.indexOf('=') + 1));\n } else if (arg.startsWith(\"--filter=\")) {\n filter = Enum.valueOf(\n DexMethodCounts.Filter.class,\n arg.substring(arg.indexOf('=') + 1).toUpperCase());\n } else {\n System.err.println(\"Unknown option '\" + arg + \"'\");\n throw new UsageException();\n }\n }\n\n // We expect at least one more argument (file name).\n int fileCount = args.length - idx;\n if (fileCount == 0) {\n throw new UsageException();\n }\n inputFileNames = new String[fileCount];\n System.arraycopy(args, idx, inputFileNames, 0, fileCount);\n }\n\n void usage() {\n System.err.print(\n \"DEX per-package/class method counts v1.0\\n\" +\n \"Usage: dex-method-counts [options] ...\\n\" +\n \"Options:\\n\" +\n \" --include-classes\\n\" +\n \" --package-filter=com.foo.bar\\n\" +\n \" --max-depth=N\\n\"\n );\n }\n\n private static class UsageException extends RuntimeException {}\n}\n"},"message":{"kind":"string","value":"whitespaces returned to original state\n"},"old_file":{"kind":"string","value":"src/info/persistent/dex/Main.java"},"subject":{"kind":"string","value":"whitespaces returned to original state"},"git_diff":{"kind":"string","value":"rc/info/persistent/dex/Main.java\n *\n * @param fileName the name of the file to open\n * @return a RandomAccessFile for classes.dex, or null if the input file\n * is not a zip archive\n * is not a zip archive\n * @throws IOException if the file isn't found, or it's a zip and\n * classes.dex isn't found inside\n */\n \n void usage() {\n System.err.print(\n \"DEX per-package/class method counts v1.0\\n\" +\n \"Usage: dex-method-counts [options] ...\\n\" +\n \"Options:\\n\" +\n \" --include-classes\\n\" +\n \" --package-filter=com.foo.bar\\n\" +\n \" --max-depth=N\\n\"\n \"DEX per-package/class method counts v1.0\\n\" +\n \"Usage: dex-method-counts [options] ...\\n\" +\n \"Options:\\n\" +\n \" --include-classes\\n\" +\n \" --package-filter=com.foo.bar\\n\" +\n \" --max-depth=N\\n\"\n );\n }\n "}}},{"rowIdx":849,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"9ab9e89ebd3ed5083d0a83a870ea9038060ef287"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"keepacom/api_backend"},"new_contents":{"kind":"string","value":"package com.keepa.api.backend.helper;\n\nimport static com.keepa.api.backend.structs.Product.CsvType;\n\n/**\n * Provides methods to work on the Keepa price history CSV format.\n */\nclass ProductAnalyzer {\n\n\t/**\n\t * finds the extreme point in the specified interval\n\t *\n\t * @param csv value/price history csv\n\t * @param start start of the interval (keepa time minutes), can be 0.\n\t * @param end end of the interval (keepa time minutes), can be in the future (Integer.MAX_VALUE).\n\t * @param isMinimum whether to find the minimum or maximum\n\t * @return extremePoint (value/price) in the given interval or -1 if no extreme point was found.\n\t * @deprecated use {@link ProductAnalyzer#getExtremePointInInterval(int[], int, int, boolean, CsvType)} instead.\n\t */\n\tpublic static int getExtremePointInInterval(int[] csv, int start, int end, boolean isMinimum) {\n\t\tif (csv == null || csv.length < 4 || csv[csv.length - 1] == -1 || csv[csv.length - 3] == -1)\n\t\t\treturn -1;\n\n\t\tint extremeValue = -1;\n\t\tif (isMinimum)\n\t\t\textremeValue = Integer.MAX_VALUE;\n\n\t\tfor (int i = 0; i < csv.length; i += 2) {\n\t\t\tint date = csv[i];\n\n\t\t\tif (date <= start) continue;\n\t\t\tif (date >= end) break;\n\t\t\tif (csv[i + 1] == -1) continue;\n\n\t\t\tif (isMinimum)\n\t\t\t\textremeValue = Math.min(extremeValue, csv[i + 1]);\n\t\t\telse\n\t\t\t\textremeValue = Math.max(extremeValue, csv[i + 1]);\n\t\t}\n\n\t\tif (extremeValue == Integer.MAX_VALUE) return -1;\n\t\treturn extremeValue;\n\t}\n\n\t/**\n\t * finds the extreme point in the specified interval\n\t *\n\t * @param csv value/price history csv\n\t * @param start start of the interval (keepa time minutes), can be 0.\n\t * @param end end of the interval (keepa time minutes), can be in the future (Integer.MAX_VALUE).\n\t * @param isMinimum whether to find the minimum or maximum\n\t * @param type the type of the csv data. If the csv includes shipping costs the extreme point will be the landing price (price + shipping).\n\t * @return extremePoint (value/price)) in the given interval or -1 if no extreme point was found. If the csv includes shipping costs it will be the landing price (price + shipping).\n\t * @deprecated use {@link ProductAnalyzer#getExtremePointsInIntervalWithTime(int[], int, int, CsvType)} instead.\n\t */\n\tpublic static int getExtremePointInInterval(int[] csv, int start, int end, boolean isMinimum, CsvType type) {\n\t\tint[] minMax = getExtremePointsInIntervalWithTime(csv, start, end, type);\n\t\treturn minMax[isMinimum ? 1 : 3];\n\t}\n\n\t/**\n\t * finds the extreme point in the specified interval\n\t *\n\t * @param csv value/price history csv\n\t * @param start start of the interval (keepa time minutes), can be 0.\n\t * @param end end of the interval (keepa time minutes), can be in the future (Integer.MAX_VALUE).\n\t * @param type the type of the csv data. If the csv includes shipping costs the extreme point will be the landing price (price + shipping).\n\t * @return extremePoints (time, lowest value/price, time, highest value/price) in the given interval or -1 if no extreme point was found. If the csv includes shipping costs it will be the landing price (price + shipping).\n\t */\n\tpublic static int[] getExtremePointsInIntervalWithTime(int[] csv, int start, int end, CsvType type) {\n\t\tif (csv == null || start >= end || csv.length < (type.isWithShipping ? 6 : 4))\n\t\t\treturn new int[]{-1, -1, -1, -1};\n\n\t\tint[] extremeValue = new int[]{-1, Integer.MAX_VALUE, -1, -1};\n\n\t\tint lastTime = getLastTime(csv, type);\n\t\tint firstTime = csv[0];\n\t\tif (lastTime == -1 || firstTime == -1 || firstTime > end) return new int[]{-1, -1, -1, -1};\n\n\t\tif (firstTime > start)\n\t\t\tstart = firstTime;\n\n\t\tint loopIncrement = (type.isWithShipping ? 3 : 2);\n\t\tint adjustedIndex = type.isWithShipping ? 2 : 1;\n\n\t\tfor (int i = 1, j = csv.length; i < j; i += loopIncrement) {\n\t\t\tint c = csv[i];\n\t\t\tint date = csv[i - 1];\n\t\t\tif (date >= end)\n\t\t\t\tbreak;\n\n\t\t\tif (c != -1) {\n\t\t\t\tif (type.isWithShipping) {\n\t\t\t\t\tint s = csv[i + 1];\n\t\t\t\t\tc += s < 0 ? 0 : s;\n\t\t\t\t}\n\n\t\t\t\tif (date >= start) {\n\t\t\t\t\tif (c < extremeValue[1]) {\n\t\t\t\t\t\textremeValue[1] = c;\n\t\t\t\t\t\textremeValue[0] = csv[i - 1];\n\t\t\t\t\t}\n\n\t\t\t\t\tif (c > extremeValue[3]) {\n\t\t\t\t\t\textremeValue[3] = c;\n\t\t\t\t\t\textremeValue[2] = csv[i - 1];\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tboolean isValid = false;\n\t\t\t\t\tif (i == j - adjustedIndex) {\n\t\t\t\t\t\tisValid = true;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tint nextDate = csv[i + adjustedIndex];\n\t\t\t\t\t\tif (nextDate >= end || (nextDate >= start))\n\t\t\t\t\t\t\tisValid = true;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (isValid) {\n\t\t\t\t\t\tif (c < extremeValue[1]) {\n\t\t\t\t\t\t\textremeValue[1] = c;\n\t\t\t\t\t\t\textremeValue[0] = start;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (c > extremeValue[3]) {\n\t\t\t\t\t\t\textremeValue[3] = c;\n\t\t\t\t\t\t\textremeValue[2] = start;\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\n\t\tif (extremeValue[1] == Integer.MAX_VALUE) return new int[]{-1, -1, -1, -1};\n\t\treturn extremeValue;\n\t}\n\n\t/**\n\t * Get the last value/price change.\n\t *\n\t * @param csv value/price history csv\n\t * @return the last value/price change delta\n\t * @deprecated use {@link ProductAnalyzer#getDeltaLast(int[], CsvType)} instead.\n\t */\n\tpublic static int getDeltaLast(int[] csv) {\n\t\tif (csv == null || csv.length < 4 || csv[csv.length - 1] == -1 || csv[csv.length - 3] == -1)\n\t\t\treturn 0;\n\n\t\treturn csv[csv.length - 1] - csv[csv.length - 3];\n\t}\n\n\t/**\n\t * Get the last value/price change.\n\t *\n\t * @param csv value/price history csv\n\t * @param type the type of the csv data. If the csv includes shipping costs the extreme point will be the landing price (price + shipping).\n\t * @return the last value/price change delta. If the csv includes shipping costs it will be the delta of the the landing prices (price + shipping).\n\t */\n\tprivate static int getDeltaLast(int[] csv, CsvType type) {\n\t\tif (type.isWithShipping) {\n\t\t\tif (csv == null || csv.length < 6 || csv[csv.length - 1] == -1 || csv[csv.length - 5] == -1)\n\t\t\t\treturn 0;\n\n\t\t\tint v = csv[csv.length - 5];\n\t\t\tint s = csv[csv.length - 4];\n\t\t\tint totalLast = v < 0 ? v : v + (s < 0 ? 0 : s);\n\n\t\t\tv = csv[csv.length - 2];\n\t\t\ts = csv[csv.length - 1];\n\t\t\tint totalCurrent = v < 0 ? v : v + (s < 0 ? 0 : s);\n\n\t\t\treturn totalCurrent - totalLast;\n\t\t} else {\n\t\t\tif (csv == null || csv.length < 4 || csv[csv.length - 1] == -1 || csv[csv.length - 3] == -1)\n\t\t\t\treturn 0;\n\n\t\t\treturn csv[csv.length - 1] - csv[csv.length - 3];\n\t\t}\n\t}\n\n\t/**\n\t * Get the last value/price.\n\t *\n\t * @param csv value/price history csv\n\t * @return the last value/price\n\t * @deprecated use {@link ProductAnalyzer#getLast(int[], CsvType)} instead.\n\t */\n\tprivate static int getLast(int[] csv) {\n\t\treturn csv == null || csv.length == 0 ? -1 : csv[csv.length - 1];\n\t}\n\n\n\t/**\n\t * Get the last value/price.\n\t *\n\t * @param csv value/price history csv\n\t * @param type the type of the csv data.\n\t * @return the last value/price. If the csv includes shipping costs it will be the landing price (price + shipping).\n\t */\n\tpublic static int getLast(int[] csv, CsvType type) {\n\t\tif (csv == null || csv.length == 0) return -1;\n\n\t\tif (type.isWithShipping) {\n\t\t\tint s = csv[csv.length - 1];\n\t\t\tint v = csv[csv.length - 2];\n\t\t\treturn v < 0 ? v : v + (s < 0 ? 0 : s);\n\t\t}\n\n\t\treturn csv[csv.length - 1];\n\t}\n\n\t/**\n\t * Get the time (keepa time minutes) of the last entry. This does not correspond to the last update time, but to the last time we registered a price/value change.\n\t *\n\t * @param csv value/price history csv\n\t * @param type the type of the csv data.\n\t * @return keepa time minutes of the last entry\n\t */\n\tpublic static int getLastTime(int[] csv, CsvType type) {\n\t\treturn csv == null || csv.length == 0 ? -1 : csv[csv.length - (type.isWithShipping ? 3 : 2)];\n\t}\n\n\t/**\n\t * Get the value/price at the specified time\n\t *\n\t * @param csv value/price history csv\n\t * @param time value/price lookup time (keepa time minutes)\n\t * @return the price/value of the product at the specified time. -1 if no value was found or if the product was out of stock.\n\t * @deprecated use {@link ProductAnalyzer#getValueAtTime(int[], int, CsvType)} instead.\n\t */\n\tpublic static int getValueAtTime(int[] csv, int time) {\n\t\tif (csv == null || csv.length == 0) return -1;\n\t\tint i = 0;\n\t\tfor (; i < csv.length; i += 2) {\n\t\t\tif (csv[i] > time) break;\n\t\t}\n\n\t\tif (i > csv.length) return getLast(csv);\n\t\tif (i < 2) return -1;\n\n\t\treturn csv[i - 1];\n\t}\n\n\t/**\n\t * Get the value/price at the specified time\n\t *\n\t * @param csv value/price history csv\n\t * @param time value/price lookup time (keepa time minutes)\n\t * @param type the type of the csv data.\n\t * @return the price or value of the product at the specified time. -1 if no value was found or if the product was out of stock. If the csv includes shipping costs it will be the landing price (price + shipping).\n\t */\n\tpublic static int getValueAtTime(int[] csv, int time, CsvType type) {\n\t\tif (csv == null || csv.length == 0) return -1;\n\t\tint i = 0;\n\n\t\tint loopIncrement = (type.isWithShipping ? 3 : 2);\n\t\tfor (; i < csv.length; i += loopIncrement)\n\t\t\tif (csv[i] > time) break;\n\n\t\tif (i > csv.length) return getLast(csv, type);\n\t\tif (i < loopIncrement) return -1;\n\n\t\tif (type.isWithShipping) {\n\t\t\tint v = csv[i - 2];\n\t\t\tint s = csv[i - 1];\n\t\t\treturn v < 0 ? v : v + (s < 0 ? 0 : s);\n\t\t}\n\n\t\treturn csv[i - 1];\n\t}\n\n\t/**\n\t * Get the price and shipping cost at the specified time\n\t *\n\t * @param csv price with shipping history csv\n\t * @param time price lookup time (keepa time minutes)\n\t * @return int[price, shipping] - the price and shipping cost of the product at the specified time. [-1, -1] if no price was found or if the product was out of stock.\n\t */\n\tpublic static int[] getPriceAndShippingAtTime(int[] csv, int time) {\n\t\tif (csv == null || csv.length == 0) return new int[]{-1, -1};\n\t\tint i = 0;\n\n\t\tfor (; i < csv.length; i += 3) {\n\t\t\tif (csv[i] > time) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (i > csv.length) return getLastPriceAndShipping(csv);\n\t\tif (i < 3) return new int[]{-1, -1};\n\n\t\treturn new int[]{csv[i - 2], csv[i - 1]};\n\t}\n\n\n\t/**\n\t * Get the last price and shipping cost.\n\t *\n\t * @param csv price with shipping history csv\n\t * @return int[price, shipping] - the last price and shipping cost.\n\t */\n\tpublic static int[] getLastPriceAndShipping(int[] csv) {\n\t\tif (csv == null || csv.length < 3) return new int[]{-1, -1};\n\t\treturn new int[]{csv[csv.length - 2], csv[csv.length - 1]};\n\t}\n\n\n\t/**\n\t * @param csv value/price history csv\n\t * @param time time to begin the search\n\t * @return the closest value/price found to the specified time. If the csv includes shipping costs it will be the landing price (price + shipping).\n\t * @deprecated use {@link ProductAnalyzer#getClosestValueAtTime(int[], int, CsvType)} instead.\n\t */\n\tpublic static int getClosestValueAtTime(int[] csv, int time) {\n\t\tif (csv == null || csv.length == 0) return -1;\n\t\tint i = 0;\n\t\tfor (; i < csv.length; i += 2) {\n\t\t\tif (csv[i] > time) break;\n\t\t}\n\n\t\tif (i > csv.length) return getLast(csv);\n\t\tif (i < 2) {\n\t\t\tif (csv.length < 3)\n\t\t\t\treturn csv[1];\n\t\t\telse\n\t\t\t\ti += 2;\n\t\t}\n\n\t\tif (csv[i - 1] != -1)\n\t\t\treturn csv[i - 1];\n\t\telse {\n\t\t\tfor (; i < csv.length; i += 2) {\n\t\t\t\tif (csv[i - 1] != -1) break;\n\t\t\t}\n\t\t\tif (i > csv.length) return getLast(csv);\n\t\t\tif (i < 2) return -1;\n\t\t\treturn csv[i - 1];\n\t\t}\n\t}\n\n\t/**\n\t * @param csv value/price history csv\n\t * @param time time to begin the search\n\t * @param type the type of the csv data.\n\t * @return the closest value/price found to the specified time. If the csv includes shipping costs it will be the landing price (price + shipping).\n\t */\n\tpublic static int getClosestValueAtTime(int[] csv, int time, CsvType type) {\n\t\tif (csv == null || csv.length == 0) return -1;\n\t\tint i = 0;\n\t\tint loopIncrement = (type.isWithShipping ? 3 : 2);\n\t\tfor (; i < csv.length; i += loopIncrement)\n\t\t\tif (csv[i] > time) break;\n\n\t\tif (i > csv.length) return getLast(csv, type);\n\t\tif (i < loopIncrement) {\n\t\t\tif (type.isWithShipping) {\n\t\t\t\tif (csv.length < 4) {\n\t\t\t\t\tint v = csv[2];\n\t\t\t\t\tint s = csv[1];\n\t\t\t\t\treturn v < 0 ? v : v + (s < 0 ? 0 : s);\n\t\t\t\t} else\n\t\t\t\t\ti += 3;\n\t\t\t} else {\n\t\t\t\tif (csv.length < 3)\n\t\t\t\t\treturn csv[1];\n\t\t\t\telse\n\t\t\t\t\ti += 2;\n\t\t\t}\n\t\t}\n\n\t\tif (type.isWithShipping) {\n\t\t\tif (csv[i - 2] != -1) {\n\t\t\t\tint v = csv[i - 2];\n\t\t\t\tint s = csv[i - 1];\n\t\t\t\treturn v < 0 ? v : v + (s < 0 ? 0 : s);\n\t\t\t} else {\n\t\t\t\tfor (; i < csv.length; i += loopIncrement) {\n\t\t\t\t\tif (csv[i - 2] != -1) break;\n\t\t\t\t}\n\t\t\t\tif (i > csv.length) return getLast(csv, type);\n\t\t\t\tif (i < 3) return -1;\n\t\t\t\tint v = csv[i - 2];\n\t\t\t\tint s = csv[i - 1];\n\t\t\t\treturn v < 0 ? v : v + (s < 0 ? 0 : s);\n\t\t\t}\n\t\t} else {\n\t\t\tif (csv[i - 1] != -1)\n\t\t\t\treturn csv[i - 1];\n\t\t\telse {\n\t\t\t\tfor (; i < csv.length; i += 2) {\n\t\t\t\t\tif (csv[i - 1] != -1) break;\n\t\t\t\t}\n\t\t\t\tif (i > csv.length) return getLast(csv, type);\n\t\t\t\tif (i < 2) return -1;\n\t\t\t\treturn csv[i - 1];\n\t\t\t}\n\t\t}\n\t}\n\n\n\t/**\n\t * finds the lowest and highest value/price of the csv history\n\t *\n\t * @param csv value/price history csv\n\t * @return [0] = low, [1] = high\n\t * @deprecated use {@link ProductAnalyzer#getLowestAndHighest(int[], CsvType)} instead.\n\t */\n\tpublic static int[] getLowestAndHighest(int[] csv) {\n\t\tif (csv == null || csv.length < 6) {\n\t\t\treturn new int[]{-1, -1};\n\t\t}\n\n\t\tint[] lowHigh = new int[]{Integer.MAX_VALUE, -1};\n\n\t\tfor (int i = 0, k = csv.length; i < k; i = i + 2) {\n\t\t\tint v = csv[i + 1];\n\t\t\tif (v == -1) continue;\n\n\t\t\tif (v < lowHigh[0])\n\t\t\t\tlowHigh[0] = v;\n\t\t\tif (v > lowHigh[1])\n\t\t\t\tlowHigh[1] = v;\n\t\t}\n\n\t\tif (lowHigh[0] == Integer.MAX_VALUE)\n\t\t\tlowHigh[0] = -1;\n\t\treturn lowHigh;\n\t}\n\n\t/**\n\t * finds the lowest and highest value/price of the csv history\n\t *\n\t * @param csv value/price history csv\n\t * @param type the type of the csv data.\n\t * @return [0] = low, [1] = high. If the csv includes shipping costs the extreme point will be the landing price (price + shipping). [-1, -1] if insufficient data.\n\t */\n\tpublic static int[] getLowestAndHighest(int[] csv, CsvType type) {\n\t\tint[] minMax = getExtremePointsInIntervalWithTime(csv, 0, Integer.MAX_VALUE, type);\n\t\treturn new int[]{minMax[1], minMax[3]};\n\t}\n\n\t/**\n\t * finds the lowest and highest value/price of the csv history including the dates of the occurrences (in keepa time minutes).\n\t *\n\t * @param csv value/price history csv\n\t * @param type the type of the csv data.\n\t * @return [0] = low time, [1] = low, [2] = high time, [3] = high. If the csv includes shipping costs the extreme point will be the landing price (price + shipping). [-1, -1, -1, -1] if insufficient data.\n\t */\n\tpublic static int[] getLowestAndHighestWithTime(int[] csv, CsvType type) {\n\t\treturn getExtremePointsInIntervalWithTime(csv, 0, Integer.MAX_VALUE, type);\n\t}\n\n\t/**\n\t * Returns a weighted mean of the products csv history in the last X days\n\t *\n\t * @param csv value/price history csv\n\t * @param days number of days the weighted mean will be calculated for (e.g. 90 days, 60 days, 30 days)\n\t * @return the weighted mean or -1 if insufficient history csv length (less than a day)\n\t * @deprecated use {@link ProductAnalyzer#calcWeightedMean(int[], int, double, CsvType)} instead.\n\t */\n\tpublic static int calcWeightedMean(int[] csv, double days) {\n\t\tint avg = -1;\n\n\t\tint now = KeepaTime.nowMinutes();\n\t\tif (csv == null || csv.length == 0) {\n\t\t\treturn avg;\n\t\t}\n\n\t\tint size = csv.length;\n\n\t\tint duration = (csv[size - 2] - csv[0]) / 60;\n\t\tdouble count = 0;\n\n\t\tif (size < 4 || duration < 24)\n\t\t\treturn avg;\n\n\t\tif (duration < 24 * days)\n\t\t\tdays = Math.floor(duration / 24.0);\n\n\t\tfor (int i = 1; i < size; i = i + 2) {\n\t\t\tint c = csv[i];\n\t\t\tif (c != -1) {\n\t\t\t\tif (now - csv[i - 1] < days * 24 * 60) {\n\t\t\t\t\tif (i == 1) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (avg == -1) {\n\t\t\t\t\t\tif (csv[i - 2] == -1) {\n\t\t\t\t\t\t\tavg = 0;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tdouble tmpCount = (days * 24 * 60 - (now - csv[i - 1])) / (24 * 60.0);\n\t\t\t\t\t\t\tcount = tmpCount;\n\t\t\t\t\t\t\tavg = (int) Math.floor(csv[i - 2] * tmpCount);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (i + 1 == size) {\n\t\t\t\t\t\tif (csv[i - 2] == -1) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdouble tmpCount = ((now - csv[size - 2]) / (24.0 * 60.0));\n\t\t\t\t\t\tcount += tmpCount;\n\t\t\t\t\t\tavg += c * tmpCount;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdouble tmpCount = ((csv[i + 1] - csv[i - 1]) / (24.0 * 60.0));\n\t\t\t\t\t\tcount += tmpCount;\n\t\t\t\t\t\tavg += c * tmpCount;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif (i == size - 1 && csv[i] != -1) {\n\t\t\t\t\t\tcount = 1;\n\t\t\t\t\t\tavg = csv[i];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (avg != -1) {\n\t\t\tavg = (int) Math.floor(avg / count);\n\t\t}\n\n\t\treturn avg;\n\t}\n\n\n\t/**\n\t * Returns a weighted mean of the products csv history in the last X days\n\t *\n\t * @param csv value/price history csv\n\t * @param now current keepa time minutes\n\t * @param days number of days the weighted mean will be calculated for (e.g. 90 days, 60 days, 30 days)\n\t * @param type the type of the csv data.\n\t * @return the weighted mean or -1 if insufficient history csv length (less than a day). If the csv includes shipping costs it will be the wieghted mean of the landing price (price + shipping).\n\t */\n\tpublic static int calcWeightedMean(int[] csv, int now, double days, CsvType type) {\n\t\tint avg = -1;\n\n\t\tif (csv == null || csv.length == 0)\n\t\t\treturn avg;\n\n\t\tint size = csv.length;\n\t\tint loopIncrement = (type.isWithShipping ? 3 : 2);\n\n\t\tint duration = (csv[size - loopIncrement] - csv[0]) / 60;\n\t\tdouble count = 0;\n\n\t\tif (size < 4 || duration < 24 * 7)\n\t\t\treturn avg;\n\n\t\tif (duration < 24 * days)\n\t\t\tdays = Math.floor(duration / 24.0);\n\n\t\tint adjustedIndex = type.isWithShipping ? 2 : 1;\n\n\t\tfor (int i = 1, j = size; i < j; i = i + loopIncrement) {\n\t\t\tint c = csv[i];\n\t\t\tif (c != -1) {\n\t\t\t\tif (type.isWithShipping) {\n\t\t\t\t\tint s = csv[i + 1];\n\t\t\t\t\tc += s < 0 ? 0 : s;\n\t\t\t\t}\n\n\t\t\t\tif (now - csv[i - 1] < days * 24 * 60) {\n\t\t\t\t\tif (i == 1) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (avg == -1) {\n\t\t\t\t\t\tif (csv[i - loopIncrement] == -1) {\n\t\t\t\t\t\t\tavg = 0;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tdouble tmpCount = (days * 24 * 60 - (now - csv[i - 1])) / (24 * 60.0);\n\t\t\t\t\t\t\tcount = tmpCount;\n\t\t\t\t\t\t\tint price = csv[i - loopIncrement];\n\t\t\t\t\t\t\tif (type.isWithShipping) {\n\t\t\t\t\t\t\t\tint s = csv[i - 2];\n\t\t\t\t\t\t\t\tprice += s < 0 ? 0 : s;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tavg = (int) Math.floor(price * tmpCount);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (i + adjustedIndex == j) {\n\t\t\t\t\t\tif (csv[i - loopIncrement] == -1) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdouble tmpCount = ((now - csv[j - loopIncrement]) / (24.0 * 60.0));\n\t\t\t\t\t\tcount += tmpCount;\n\t\t\t\t\t\tavg += c * tmpCount;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdouble tmpCount = ((csv[i + adjustedIndex] - csv[i - 1]) / (24.0 * 60.0));\n\t\t\t\t\t\tcount += tmpCount;\n\t\t\t\t\t\tavg += c * tmpCount;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif (i == j - adjustedIndex && csv[i] != -1) {\n\t\t\t\t\t\tcount = 1;\n\t\t\t\t\t\tavg = c;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (avg != -1) {\n\t\t\tif (count != 0)\n\t\t\t\tavg = (int) Math.floor(avg / count);\n\t\t\telse\n\t\t\t\tavg = -1;\n\t\t}\n\n\t\treturn avg;\n\t}\n\n\t/**\n\t * Returns true if the CSV was out of stock in the given period.\n\t *\n\t * @param csv value/price history csv\n\t * @param start start of the interval (keepa time minutes), can be 0.\n\t * @param end end of the interval (keepa time minutes), can be in the future (Integer.MAX_VALUE).\n\t * @param type the type of the csv data.\n\t * @return was out of stock in interval, null if the csv is too short to tell.\n\t */\n\tpublic static Boolean getOutOfStockInInterval(int[] csv, int start, int end, CsvType type) {\n\t\tif (type.isWithShipping) {\n\t\t\tif (csv == null || csv.length < 6)\n\t\t\t\treturn null;\n\t\t} else if (start >= end || csv == null || csv.length < 4)\n\t\t\treturn null;\n\n\t\tint loopIncrement = (type.isWithShipping ? 3 : 2);\n\t\tfor (int i = 0; i < csv.length; i += loopIncrement) {\n\t\t\tint date = csv[i];\n\t\t\tif (date <= start) continue;\n\t\t\tif (date >= end) break;\n\t\t\tif (csv[i + 1] == -1) return true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns a the percentage of time in the given interval the price type was out of stock\n\t *\n\t * @param csv value/price history csv\n\t * @param now current keepa time minutes\n\t * @param start start of the interval (keepa time minutes), can be 0.\n\t * @param end end of the interval (keepa time minutes), can be in the future (Integer.MAX_VALUE).\n\t * @param type the type of the csv data.\n\t * @param trackingSince the product object's trackingSince value\n\t * @return percentage between 0 and 100 or -1 if insufficient data. 100 = 100% out of stock in the interval.\n\t */\n\tpublic static int getOutOfStockPercentageInInterval(int[] csv, int now, int start, int end, CsvType type, int trackingSince) {\n\t\tif (!type.isPrice) return -1;\n\t\tif (start >= end) return -1;\n\t\tif (csv == null || csv.length == 0)\n\t\t\treturn -1;\n\n\t\tint size = csv.length;\n\t\tint loopIncrement = (type.isWithShipping ? 3 : 2);\n\n\t\tint lastTime = getLastTime(csv, type);\n\t\tint firstTime = csv[0];\n\n\t\tif (lastTime == -1 || firstTime == -1 || firstTime > end || trackingSince > end) return -1;\n\n\t\tlong count = 0;\n\n\t\tif (trackingSince > start)\n\t\t\tstart = trackingSince;\n\n\t\tif (end > now)\n\t\t\tend = now;\n\n\t\tint adjustedIndex = type.isWithShipping ? 2 : 1;\n\n\t\tfor (int i = 1, j = size; i < j; i += loopIncrement) {\n\t\t\tint c = csv[i];\n\t\t\tint date = csv[i - 1];\n\n\t\t\tif (date >= end)\n\t\t\t\tbreak;\n\n\t\t\tif (c != -1) {\n\t\t\t\tif (date >= start) {\n\t\t\t\t\tif (i == 1) {\n\t\t\t\t\t\tif (i + adjustedIndex == j) {\n\t\t\t\t\t\t\treturn 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tint nextDate;\n\t\t\t\t\tif (i + adjustedIndex == j) {\n\t\t\t\t\t\tnextDate = now;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tnextDate = csv[i + adjustedIndex];\n\t\t\t\t\t\tif (nextDate > end)\n\t\t\t\t\t\t\tnextDate = end;\n\t\t\t\t\t}\n\n\t\t\t\t\tlong tmpCount = nextDate - date;\n\n\t\t\t\t\tcount += tmpCount;\n\t\t\t\t} else {\n\t\t\t\t\tif (i == j - adjustedIndex) {\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tint nextDate = csv[i + adjustedIndex];\n\n\t\t\t\t\t\tif (nextDate >= end)\n\t\t\t\t\t\t\treturn 0;\n\n\t\t\t\t\t\tif (nextDate >= start)\n\t\t\t\t\t\t\tcount = nextDate - start;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (count > 0)\n\t\t\tcount = 100 - (int) Math.floor((count * 100) / (end - start));\n\t\telse if (count == 0) {\n\t\t\tcount = 100;\n\t\t}\n\n\t\treturn (int) count;\n\t}\n}\n"},"new_file":{"kind":"string","value":"src/main/java/com/keepa/api/backend/helper/ProductAnalyzer.java"},"old_contents":{"kind":"string","value":"package com.keepa.api.backend.helper;\n\nimport static com.keepa.api.backend.structs.Product.CsvType;\n\n/**\n * Provides methods to work on the Keepa price history CSV format.\n */\nclass ProductAnalyzer {\n\n\t/**\n\t * finds the extreme point in the specified interval\n\t *\n\t * @param csv value/price history csv\n\t * @param start start of the interval (keepa time minutes), can be 0.\n\t * @param end end of the interval (keepa time minutes), can be in the future (Integer.MAX_VALUE).\n\t * @param isMinimum whether to find the minimum or maximum\n\t * @return extremePoint (value/price) in the given interval or -1 if no extreme point was found.\n\t * @deprecated use {@link ProductAnalyzer#getExtremePointInInterval(int[], int, int, boolean, CsvType)} instead.\n\t */\n\tpublic static int getExtremePointInInterval(int[] csv, int start, int end, boolean isMinimum) {\n\t\tif (csv == null || csv.length < 4 || csv[csv.length - 1] == -1 || csv[csv.length - 3] == -1)\n\t\t\treturn -1;\n\n\t\tint extremeValue = -1;\n\t\tif (isMinimum)\n\t\t\textremeValue = Integer.MAX_VALUE;\n\n\t\tfor (int i = 0; i < csv.length; i += 2) {\n\t\t\tint date = csv[i];\n\n\t\t\tif (date <= start) continue;\n\t\t\tif (date >= end) break;\n\t\t\tif (csv[i + 1] == -1) continue;\n\n\t\t\tif (isMinimum)\n\t\t\t\textremeValue = Math.min(extremeValue, csv[i + 1]);\n\t\t\telse\n\t\t\t\textremeValue = Math.max(extremeValue, csv[i + 1]);\n\t\t}\n\n\t\tif (extremeValue == Integer.MAX_VALUE) return -1;\n\t\treturn extremeValue;\n\t}\n\n\t/**\n\t * finds the extreme point in the specified interval\n\t *\n\t * @param csv value/price history csv\n\t * @param start start of the interval (keepa time minutes), can be 0.\n\t * @param end end of the interval (keepa time minutes), can be in the future (Integer.MAX_VALUE).\n\t * @param isMinimum whether to find the minimum or maximum\n\t * @param type the type of the csv data. If the csv includes shipping costs the extreme point will be the landing price (price + shipping).\n\t * @return extremePoint (value/price)) in the given interval or -1 if no extreme point was found. If the csv includes shipping costs it will be the landing price (price + shipping).\n\t * @deprecated use {@link ProductAnalyzer#getExtremePointsInIntervalWithTime(int[], int, int, CsvType)} instead.\n\t */\n\tpublic static int getExtremePointInInterval(int[] csv, int start, int end, boolean isMinimum, CsvType type) {\n\t\tint[] minMax = getExtremePointsInIntervalWithTime(csv, start, end, type);\n\t\treturn minMax[isMinimum ? 1 : 3];\n\t}\n\n\t/**\n\t * finds the extreme point in the specified interval\n\t *\n\t * @param csv value/price history csv\n\t * @param start start of the interval (keepa time minutes), can be 0.\n\t * @param end end of the interval (keepa time minutes), can be in the future (Integer.MAX_VALUE).\n\t * @param type the type of the csv data. If the csv includes shipping costs the extreme point will be the landing price (price + shipping).\n\t * @return extremePoints (time, lowest value/price, time, highest value/price) in the given interval or -1 if no extreme point was found. If the csv includes shipping costs it will be the landing price (price + shipping).\n\t */\n\tpublic static int[] getExtremePointsInIntervalWithTime(int[] csv, int start, int end, CsvType type) {\n\t\tif (csv == null || start >= end || csv.length < (type.isWithShipping ? 6 : 4))\n\t\t\treturn new int[]{-1, -1, -1, -1};\n\n\t\tint[] extremeValue = new int[]{-1, Integer.MAX_VALUE, -1, -1};\n\n\t\tint lastTime = getLastTime(csv, type);\n\t\tint firstTime = csv[0];\n\t\tif (lastTime == -1 || firstTime == -1 || firstTime > end) return new int[]{-1, -1, -1, -1};\n\n\t\tif (firstTime > start)\n\t\t\tstart = firstTime;\n\n\t\tint loopIncrement = (type.isWithShipping ? 3 : 2);\n\t\tint adjustedIndex = type.isWithShipping ? 2 : 1;\n\n\t\tfor (int i = 1, j = csv.length; i < j; i += loopIncrement) {\n\t\t\tint c = csv[i];\n\t\t\tint date = csv[i - 1];\n\t\t\tif (date >= end)\n\t\t\t\tbreak;\n\n\t\t\tif (c != -1) {\n\t\t\t\tif (type.isWithShipping) {\n\t\t\t\t\tint s = csv[i + 1];\n\t\t\t\t\tc += s < 0 ? 0 : s;\n\t\t\t\t}\n\n\t\t\t\tif (date >= start) {\n\t\t\t\t\tif (c < extremeValue[1]) {\n\t\t\t\t\t\textremeValue[1] = c;\n\t\t\t\t\t\textremeValue[0] = csv[i - 1];\n\t\t\t\t\t}\n\n\t\t\t\t\tif (c > extremeValue[3]) {\n\t\t\t\t\t\textremeValue[3] = c;\n\t\t\t\t\t\textremeValue[2] = csv[i - 1];\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tboolean isValid = false;\n\t\t\t\t\tif (i == j - adjustedIndex) {\n\t\t\t\t\t\tisValid = true;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tint nextDate = csv[i + adjustedIndex];\n\t\t\t\t\t\tif (nextDate >= end || (nextDate >= start))\n\t\t\t\t\t\t\tisValid = true;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (isValid) {\n\t\t\t\t\t\tif (c < extremeValue[1]) {\n\t\t\t\t\t\t\textremeValue[1] = c;\n\t\t\t\t\t\t\textremeValue[0] = start;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (c > extremeValue[3]) {\n\t\t\t\t\t\t\textremeValue[3] = c;\n\t\t\t\t\t\t\textremeValue[2] = start;\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\n\t\tif (extremeValue[1] == Integer.MAX_VALUE) return new int[]{-1, -1, -1, -1};\n\t\treturn extremeValue;\n\t}\n\n\t/**\n\t * Get the last value/price change.\n\t *\n\t * @param csv value/price history csv\n\t * @return the last value/price change delta\n\t * @deprecated use {@link ProductAnalyzer#getDeltaLast(int[], CsvType)} instead.\n\t */\n\tpublic static int getDeltaLast(int[] csv) {\n\t\tif (csv == null || csv.length < 4 || csv[csv.length - 1] == -1 || csv[csv.length - 3] == -1)\n\t\t\treturn 0;\n\n\t\treturn csv[csv.length - 1] - csv[csv.length - 3];\n\t}\n\n\t/**\n\t * Get the last value/price change.\n\t *\n\t * @param csv value/price history csv\n\t * @param type the type of the csv data. If the csv includes shipping costs the extreme point will be the landing price (price + shipping).\n\t * @return the last value/price change delta. If the csv includes shipping costs it will be the delta of the the landing prices (price + shipping).\n\t */\n\tprivate static int getDeltaLast(int[] csv, CsvType type) {\n\t\tif (type.isWithShipping) {\n\t\t\tif (csv == null || csv.length < 6 || csv[csv.length - 1] == -1 || csv[csv.length - 5] == -1)\n\t\t\t\treturn 0;\n\n\t\t\tint v = csv[csv.length - 5];\n\t\t\tint s = csv[csv.length - 4];\n\t\t\tint totalLast = v < 0 ? v : v + (s < 0 ? 0 : s);\n\n\t\t\tv = csv[csv.length - 2];\n\t\t\ts = csv[csv.length - 1];\n\t\t\tint totalCurrent = v < 0 ? v : v + (s < 0 ? 0 : s);\n\n\t\t\treturn totalCurrent - totalLast;\n\t\t} else {\n\t\t\tif (csv == null || csv.length < 4 || csv[csv.length - 1] == -1 || csv[csv.length - 3] == -1)\n\t\t\t\treturn 0;\n\n\t\t\treturn csv[csv.length - 1] - csv[csv.length - 3];\n\t\t}\n\t}\n\n\t/**\n\t * Get the last value/price.\n\t *\n\t * @param csv value/price history csv\n\t * @return the last value/price\n\t * @deprecated use {@link ProductAnalyzer#getLast(int[], CsvType)} instead.\n\t */\n\tprivate static int getLast(int[] csv) {\n\t\treturn csv == null || csv.length == 0 ? -1 : csv[csv.length - 1];\n\t}\n\n\n\t/**\n\t * Get the last value/price.\n\t *\n\t * @param csv value/price history csv\n\t * @param type the type of the csv data.\n\t * @return the last value/price. If the csv includes shipping costs it will be the landing price (price + shipping).\n\t */\n\tpublic static int getLast(int[] csv, CsvType type) {\n\t\tif (csv == null || csv.length == 0) return -1;\n\n\t\tif (type.isWithShipping) {\n\t\t\tint s = csv[csv.length - 1];\n\t\t\tint v = csv[csv.length - 2];\n\t\t\treturn v < 0 ? v : v + (s < 0 ? 0 : s);\n\t\t}\n\n\t\treturn csv[csv.length - 1];\n\t}\n\n\t/**\n\t * Get the time (keepa time minutes) of the last entry. This does not correspond to the last update time, but to the last time we registered a price/value change.\n\t *\n\t * @param csv value/price history csv\n\t * @param type the type of the csv data.\n\t * @return keepa time minutes of the last entry\n\t */\n\tpublic static int getLastTime(int[] csv, CsvType type) {\n\t\treturn csv == null || csv.length == 0 ? -1 : csv[csv.length - (type.isWithShipping ? 3 : 2)];\n\t}\n\n\t/**\n\t * Get the value/price at the specified time\n\t *\n\t * @param csv value/price history csv\n\t * @param time value/price lookup time (keepa time minutes)\n\t * @return the price/value of the product at the specified time. -1 if no value was found or if the product was out of stock.\n\t * @deprecated use {@link ProductAnalyzer#getValueAtTime(int[], int, CsvType)} instead.\n\t */\n\tpublic static int getValueAtTime(int[] csv, int time) {\n\t\tif (csv == null || csv.length == 0) return -1;\n\t\tint i = 0;\n\t\tfor (; i < csv.length; i += 2) {\n\t\t\tif (csv[i] > time) break;\n\t\t}\n\n\t\tif (i > csv.length) return getLast(csv);\n\t\tif (i < 2) return -1;\n\n\t\treturn csv[i - 1];\n\t}\n\n\t/**\n\t * Get the value/price at the specified time\n\t *\n\t * @param csv value/price history csv\n\t * @param time value/price lookup time (keepa time minutes)\n\t * @param type the type of the csv data.\n\t * @return the price or value of the product at the specified time. -1 if no value was found or if the product was out of stock. If the csv includes shipping costs it will be the landing price (price + shipping).\n\t */\n\tpublic static int getValueAtTime(int[] csv, int time, CsvType type) {\n\t\tif (csv == null || csv.length == 0) return -1;\n\t\tint i = 0;\n\n\t\tint loopIncrement = (type.isWithShipping ? 3 : 2);\n\t\tfor (; i < csv.length; i += loopIncrement)\n\t\t\tif (csv[i] > time) break;\n\n\t\tif (i > csv.length) return getLast(csv, type);\n\t\tif (i < loopIncrement) return -1;\n\n\t\tif (type.isWithShipping) {\n\t\t\tint v = csv[i - 2];\n\t\t\tint s = csv[i - 1];\n\t\t\treturn v < 0 ? v : v + (s < 0 ? 0 : s);\n\t\t}\n\n\t\treturn csv[i - 1];\n\t}\n\n\t/**\n\t * Get the price and shipping cost at the specified time\n\t *\n\t * @param csv price with shipping history csv\n\t * @param time price lookup time (keepa time minutes)\n\t * @return int[price, shipping] - the price and shipping cost of the product at the specified time. [-1, -1] if no price was found or if the product was out of stock.\n\t */\n\tpublic static int[] getPriceAndShippingAtTime(int[] csv, int time) {\n\t\tif (csv == null || csv.length == 0) return new int[]{-1, -1};\n\t\tint i = 0;\n\n\t\tfor (; i < csv.length; i += 3) {\n\t\t\tif (csv[i] > time) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (i > csv.length) return getLastPriceAndShipping(csv);\n\t\tif (i < 3) return new int[]{-1, -1};\n\n\t\treturn new int[]{csv[i - 2], csv[i - 1]};\n\t}\n\n\n\t/**\n\t * Get the last price and shipping cost.\n\t *\n\t * @param csv price with shipping history csv\n\t * @return int[price, shipping] - the last price and shipping cost.\n\t */\n\tpublic static int[] getLastPriceAndShipping(int[] csv) {\n\t\tif (csv == null || csv.length < 3) return new int[]{-1, -1};\n\t\treturn new int[]{csv[csv.length - 2], csv[csv.length - 1]};\n\t}\n\n\n\t/**\n\t * @param csv value/price history csv\n\t * @param time time to begin the search\n\t * @return the closest value/price found to the specified time. If the csv includes shipping costs it will be the landing price (price + shipping).\n\t * @deprecated use {@link ProductAnalyzer#getClosestValueAtTime(int[], int, CsvType)} instead.\n\t */\n\tpublic static int getClosestValueAtTime(int[] csv, int time) {\n\t\tif (csv == null || csv.length == 0) return -1;\n\t\tint i = 0;\n\t\tfor (; i < csv.length; i += 2) {\n\t\t\tif (csv[i] > time) break;\n\t\t}\n\n\t\tif (i > csv.length) return getLast(csv);\n\t\tif (i < 2) {\n\t\t\tif (csv.length < 3)\n\t\t\t\treturn csv[1];\n\t\t\telse\n\t\t\t\ti += 2;\n\t\t}\n\n\t\tif (csv[i - 1] != -1)\n\t\t\treturn csv[i - 1];\n\t\telse {\n\t\t\tfor (; i < csv.length; i += 2) {\n\t\t\t\tif (csv[i - 1] != -1) break;\n\t\t\t}\n\t\t\tif (i > csv.length) return getLast(csv);\n\t\t\tif (i < 2) return -1;\n\t\t\treturn csv[i - 1];\n\t\t}\n\t}\n\n\t/**\n\t * @param csv value/price history csv\n\t * @param time time to begin the search\n\t * @param type the type of the csv data.\n\t * @return the closest value/price found to the specified time. If the csv includes shipping costs it will be the landing price (price + shipping).\n\t */\n\tpublic static int getClosestValueAtTime(int[] csv, int time, CsvType type) {\n\t\tif (csv == null || csv.length == 0) return -1;\n\t\tint i = 0;\n\t\tint loopIncrement = (type.isWithShipping ? 3 : 2);\n\t\tfor (; i < csv.length; i += loopIncrement)\n\t\t\tif (csv[i] > time) break;\n\n\t\tif (i > csv.length) return getLast(csv, type);\n\t\tif (i < loopIncrement) {\n\t\t\tif (type.isWithShipping) {\n\t\t\t\tif (csv.length < 4) {\n\t\t\t\t\tint v = csv[2];\n\t\t\t\t\tint s = csv[1];\n\t\t\t\t\treturn v < 0 ? v : v + (s < 0 ? 0 : s);\n\t\t\t\t} else\n\t\t\t\t\ti += 3;\n\t\t\t} else {\n\t\t\t\tif (csv.length < 3)\n\t\t\t\t\treturn csv[1];\n\t\t\t\telse\n\t\t\t\t\ti += 2;\n\t\t\t}\n\t\t}\n\n\t\tif (type.isWithShipping) {\n\t\t\tif (csv[i - 2] != -1) {\n\t\t\t\tint v = csv[i - 2];\n\t\t\t\tint s = csv[i - 1];\n\t\t\t\treturn v < 0 ? v : v + (s < 0 ? 0 : s);\n\t\t\t} else {\n\t\t\t\tfor (; i < csv.length; i += loopIncrement) {\n\t\t\t\t\tif (csv[i - 2] != -1) break;\n\t\t\t\t}\n\t\t\t\tif (i > csv.length) return getLast(csv, type);\n\t\t\t\tif (i < 3) return -1;\n\t\t\t\tint v = csv[i - 2];\n\t\t\t\tint s = csv[i - 1];\n\t\t\t\treturn v < 0 ? v : v + (s < 0 ? 0 : s);\n\t\t\t}\n\t\t} else {\n\t\t\tif (csv[i - 1] != -1)\n\t\t\t\treturn csv[i - 1];\n\t\t\telse {\n\t\t\t\tfor (; i < csv.length; i += 2) {\n\t\t\t\t\tif (csv[i - 1] != -1) break;\n\t\t\t\t}\n\t\t\t\tif (i > csv.length) return getLast(csv, type);\n\t\t\t\tif (i < 2) return -1;\n\t\t\t\treturn csv[i - 1];\n\t\t\t}\n\t\t}\n\t}\n\n\n\t/**\n\t * finds the lowest and highest value/price of the csv history\n\t *\n\t * @param csv value/price history csv\n\t * @return [0] = low, [1] = high\n\t * @deprecated use {@link ProductAnalyzer#getLowestAndHighest(int[], CsvType)} instead.\n\t */\n\tpublic static int[] getLowestAndHighest(int[] csv) {\n\t\tif (csv == null || csv.length < 6) {\n\t\t\treturn new int[]{-1, -1};\n\t\t}\n\n\t\tint[] lowHigh = new int[]{Integer.MAX_VALUE, -1};\n\n\t\tfor (int i = 0, k = csv.length; i < k; i = i + 2) {\n\t\t\tint v = csv[i + 1];\n\t\t\tif (v == -1) continue;\n\n\t\t\tif (v < lowHigh[0])\n\t\t\t\tlowHigh[0] = v;\n\t\t\tif (v > lowHigh[1])\n\t\t\t\tlowHigh[1] = v;\n\t\t}\n\n\t\tif (lowHigh[0] == Integer.MAX_VALUE)\n\t\t\tlowHigh[0] = -1;\n\t\treturn lowHigh;\n\t}\n\n\t/**\n\t * finds the lowest and highest value/price of the csv history\n\t *\n\t * @param csv value/price history csv\n\t * @param type the type of the csv data.\n\t * @return [0] = low, [1] = high. If the csv includes shipping costs the extreme point will be the landing price (price + shipping). [-1, -1] if insufficient data.\n\t */\n\tpublic static int[] getLowestAndHighest(int[] csv, CsvType type) {\n\t\tint[] minMax = getExtremePointsInIntervalWithTime(csv, 0, Integer.MAX_VALUE, type);\n\t\treturn new int[]{minMax[1], minMax[3]};\n\t}\n\n\t/**\n\t * finds the lowest and highest value/price of the csv history including the dates of the occurrences (in keepa time minutes).\n\t *\n\t * @param csv value/price history csv\n\t * @param type the type of the csv data.\n\t * @return [0] = low time, [1] = low, [2] = high time, [3] = high. If the csv includes shipping costs the extreme point will be the landing price (price + shipping). [-1, -1, -1, -1] if insufficient data.\n\t */\n\tpublic static int[] getLowestAndHighestWithTime(int[] csv, CsvType type) {\n\t\treturn getExtremePointsInIntervalWithTime(csv, 0, Integer.MAX_VALUE, type);\n\t}\n\n\t/**\n\t * Returns a weighted mean of the products csv history in the last X days\n\t *\n\t * @param csv value/price history csv\n\t * @param days number of days the weighted mean will be calculated for (e.g. 90 days, 60 days, 30 days)\n\t * @return the weighted mean or -1 if insufficient history csv length (less than a day)\n\t * @deprecated use {@link ProductAnalyzer#calcWeightedMean(int[], int, double, CsvType)} instead.\n\t */\n\tpublic static int calcWeightedMean(int[] csv, double days) {\n\t\tint avg = -1;\n\n\t\tint now = KeepaTime.nowMinutes();\n\t\tif (csv == null || csv.length == 0) {\n\t\t\treturn avg;\n\t\t}\n\n\t\tint size = csv.length;\n\n\t\tint duration = (csv[size - 2] - csv[0]) / 60;\n\t\tdouble count = 0;\n\n\t\tif (size < 4 || duration < 24)\n\t\t\treturn avg;\n\n\t\tif (duration < 24 * days)\n\t\t\tdays = Math.floor(duration / 24.0);\n\n\t\tfor (int i = 1; i < size; i = i + 2) {\n\t\t\tint c = csv[i];\n\t\t\tif (c != -1) {\n\t\t\t\tif (now - csv[i - 1] < days * 24 * 60) {\n\t\t\t\t\tif (i == 1) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (avg == -1) {\n\t\t\t\t\t\tif (csv[i - 2] == -1) {\n\t\t\t\t\t\t\tavg = 0;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tdouble tmpCount = (days * 24 * 60 - (now - csv[i - 1])) / (24 * 60.0);\n\t\t\t\t\t\t\tcount = tmpCount;\n\t\t\t\t\t\t\tavg = (int) Math.floor(csv[i - 2] * tmpCount);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (i + 1 == size) {\n\t\t\t\t\t\tif (csv[i - 2] == -1) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdouble tmpCount = ((now - csv[size - 2]) / (24.0 * 60.0));\n\t\t\t\t\t\tcount += tmpCount;\n\t\t\t\t\t\tavg += c * tmpCount;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdouble tmpCount = ((csv[i + 1] - csv[i - 1]) / (24.0 * 60.0));\n\t\t\t\t\t\tcount += tmpCount;\n\t\t\t\t\t\tavg += c * tmpCount;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif (i == size - 1 && csv[i] != -1) {\n\t\t\t\t\t\tcount = 1;\n\t\t\t\t\t\tavg = csv[i];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (avg != -1) {\n\t\t\tavg = (int) Math.floor(avg / count);\n\t\t}\n\n\t\treturn avg;\n\t}\n\n\n\t/**\n\t * Returns a weighted mean of the products csv history in the last X days\n\t *\n\t * @param csv value/price history csv\n\t * @param days number of days the weighted mean will be calculated for (e.g. 90 days, 60 days, 30 days)\n\t * @return the weighted mean or -1 if insufficient history csv length (less than a day). If the csv includes shipping costs it will be the wieghted mean of the landing price (price + shipping).\n\t */\n\tpublic static int calcWeightedMean(int[] csv, int now, double days, CsvType type) {\n\t\tint avg = -1;\n\n\t\tif (csv == null || csv.length == 0)\n\t\t\treturn avg;\n\n\t\tint size = csv.length;\n\t\tint loopIncrement = (type.isWithShipping ? 3 : 2);\n\n\t\tint duration = (csv[size - loopIncrement] - csv[0]) / 60;\n\t\tdouble count = 0;\n\n\t\tif (size < 4 || duration < 24 * 7)\n\t\t\treturn avg;\n\n\t\tif (duration < 24 * days)\n\t\t\tdays = Math.floor(duration / 24.0);\n\n\t\tint adjustedIndex = type.isWithShipping ? 2 : 1;\n\n\t\tfor (int i = 1, j = size; i < j; i = i + loopIncrement) {\n\t\t\tint c = csv[i];\n\t\t\tif (c != -1) {\n\t\t\t\tif (type.isWithShipping) {\n\t\t\t\t\tint s = csv[i + 1];\n\t\t\t\t\tc += s < 0 ? 0 : s;\n\t\t\t\t}\n\n\t\t\t\tif (now - csv[i - 1] < days * 24 * 60) {\n\t\t\t\t\tif (i == 1) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (avg == -1) {\n\t\t\t\t\t\tif (csv[i - loopIncrement] == -1) {\n\t\t\t\t\t\t\tavg = 0;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tdouble tmpCount = (days * 24 * 60 - (now - csv[i - 1])) / (24 * 60.0);\n\t\t\t\t\t\t\tcount = tmpCount;\n\t\t\t\t\t\t\tint price = csv[i - loopIncrement];\n\t\t\t\t\t\t\tif (type.isWithShipping) {\n\t\t\t\t\t\t\t\tint s = csv[i - 2];\n\t\t\t\t\t\t\t\tprice += s < 0 ? 0 : s;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tavg = (int) Math.floor(price * tmpCount);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (i + adjustedIndex == j) {\n\t\t\t\t\t\tif (csv[i - loopIncrement] == -1) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdouble tmpCount = ((now - csv[j - loopIncrement]) / (24.0 * 60.0));\n\t\t\t\t\t\tcount += tmpCount;\n\t\t\t\t\t\tavg += c * tmpCount;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdouble tmpCount = ((csv[i + adjustedIndex] - csv[i - 1]) / (24.0 * 60.0));\n\t\t\t\t\t\tcount += tmpCount;\n\t\t\t\t\t\tavg += c * tmpCount;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif (i == j - adjustedIndex && csv[i] != -1) {\n\t\t\t\t\t\tcount = 1;\n\t\t\t\t\t\tavg = c;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (avg != -1) {\n\t\t\tif (count != 0)\n\t\t\t\tavg = (int) Math.floor(avg / count);\n\t\t\telse\n\t\t\t\tavg = -1;\n\t\t}\n\n\t\treturn avg;\n\t}\n\n\t/**\n\t * Returns true if the CSV was out of stock in the given period.\n\t *\n\t * @param csv value/price history csv\n\t * @param start start of the interval (keepa time minutes), can be 0.\n\t * @param end end of the interval (keepa time minutes), can be in the future (Integer.MAX_VALUE).\n\t * @param type the type of the csv data.\n\t * @return was out of stock in interval, null if the csv is too short to tell.\n\t */\n\tpublic static Boolean getOutOfStockInInterval(int[] csv, int start, int end, CsvType type) {\n\t\tif (type.isWithShipping) {\n\t\t\tif (csv == null || csv.length < 6)\n\t\t\t\treturn null;\n\t\t} else if (start >= end || csv == null || csv.length < 4)\n\t\t\treturn null;\n\n\t\tint loopIncrement = (type.isWithShipping ? 3 : 2);\n\t\tfor (int i = 0; i < csv.length; i += loopIncrement) {\n\t\t\tint date = csv[i];\n\t\t\tif (date <= start) continue;\n\t\t\tif (date >= end) break;\n\t\t\tif (csv[i + 1] == -1) return true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tpublic static int getOutOfStockPercentageInInterval(int[] v, int now, int start, int end, CsvType type, int trackingSince) {\n\t\tif (!type.isPrice) return -1;\n\t\tif (start >= end) return -1;\n\t\tif (v == null || v.length == 0)\n\t\t\treturn -1;\n\n\t\tint size = v.length;\n\t\tint loopIncrement = (type.isWithShipping ? 3 : 2);\n\n\t\tint lastTime = getLastTime(v, type);\n\t\tint firstTime = v[0];\n\n\t\tif (lastTime == -1 || firstTime == -1 || firstTime > end || trackingSince > end) return -1;\n\n\t\tlong count = 0;\n\n\t\tif (trackingSince > start)\n\t\t\tstart = trackingSince;\n\n\t\tif (end > now)\n\t\t\tend = now;\n\n\t\tint adjustedIndex = type.isWithShipping ? 2 : 1;\n\n\t\tfor (int i = 1, j = size; i < j; i += loopIncrement) {\n\t\t\tint c = v[i];\n\t\t\tint date = v[i - 1];\n\n\t\t\tif (date >= end)\n\t\t\t\tbreak;\n\n\t\t\tif (c != -1) {\n\t\t\t\tif (date >= start) {\n\t\t\t\t\tif (i == 1) {\n\t\t\t\t\t\tif (i + adjustedIndex == j) {\n\t\t\t\t\t\t\treturn 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tint nextDate;\n\t\t\t\t\tif (i + adjustedIndex == j) {\n\t\t\t\t\t\tnextDate = now;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tnextDate = v[i + adjustedIndex];\n\t\t\t\t\t\tif (nextDate > end)\n\t\t\t\t\t\t\tnextDate = end;\n\t\t\t\t\t}\n\n\t\t\t\t\tlong tmpCount = nextDate - date;\n\n\t\t\t\t\tcount += tmpCount;\n\t\t\t\t} else {\n\t\t\t\t\tif (i == j - adjustedIndex) {\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tint nextDate = v[i + adjustedIndex];\n\n\t\t\t\t\t\tif (nextDate >= end)\n\t\t\t\t\t\t\treturn 0;\n\n\t\t\t\t\t\tif (nextDate >= start)\n\t\t\t\t\t\t\tcount = nextDate - start;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (count > 0)\n\t\t\tcount = 100 - (int) Math.floor((count * 100) / (end - start));\n\t\telse if (count == 0) {\n\t\t\tcount = 100;\n\t\t}\n\n\t\treturn (int) count;\n\t}\n}\n"},"message":{"kind":"string","value":"added missing java doc\n"},"old_file":{"kind":"string","value":"src/main/java/com/keepa/api/backend/helper/ProductAnalyzer.java"},"subject":{"kind":"string","value":"added missing java doc"},"git_diff":{"kind":"string","value":"rc/main/java/com/keepa/api/backend/helper/ProductAnalyzer.java\n \t * Returns a weighted mean of the products csv history in the last X days\n \t *\n \t * @param csv value/price history csv\n\t * @param now current keepa time minutes\n \t * @param days number of days the weighted mean will be calculated for (e.g. 90 days, 60 days, 30 days)\n\t * @param type the type of the csv data.\n \t * @return the weighted mean or -1 if insufficient history csv length (less than a day). If the csv includes shipping costs it will be the wieghted mean of the landing price (price + shipping).\n \t */\n \tpublic static int calcWeightedMean(int[] csv, int now, double days, CsvType type) {\n \t\treturn false;\n \t}\n \n\tpublic static int getOutOfStockPercentageInInterval(int[] v, int now, int start, int end, CsvType type, int trackingSince) {\n\t/**\n\t * Returns a the percentage of time in the given interval the price type was out of stock\n\t *\n\t * @param csv value/price history csv\n\t * @param now current keepa time minutes\n\t * @param start start of the interval (keepa time minutes), can be 0.\n\t * @param end end of the interval (keepa time minutes), can be in the future (Integer.MAX_VALUE).\n\t * @param type the type of the csv data.\n\t * @param trackingSince the product object's trackingSince value\n\t * @return percentage between 0 and 100 or -1 if insufficient data. 100 = 100% out of stock in the interval.\n\t */\n\tpublic static int getOutOfStockPercentageInInterval(int[] csv, int now, int start, int end, CsvType type, int trackingSince) {\n \t\tif (!type.isPrice) return -1;\n \t\tif (start >= end) return -1;\n\t\tif (v == null || v.length == 0)\n\t\tif (csv == null || csv.length == 0)\n \t\t\treturn -1;\n \n\t\tint size = v.length;\n\t\tint size = csv.length;\n \t\tint loopIncrement = (type.isWithShipping ? 3 : 2);\n \n\t\tint lastTime = getLastTime(v, type);\n\t\tint firstTime = v[0];\n\t\tint lastTime = getLastTime(csv, type);\n\t\tint firstTime = csv[0];\n \n \t\tif (lastTime == -1 || firstTime == -1 || firstTime > end || trackingSince > end) return -1;\n \n \t\tint adjustedIndex = type.isWithShipping ? 2 : 1;\n \n \t\tfor (int i = 1, j = size; i < j; i += loopIncrement) {\n\t\t\tint c = v[i];\n\t\t\tint date = v[i - 1];\n\t\t\tint c = csv[i];\n\t\t\tint date = csv[i - 1];\n \n \t\t\tif (date >= end)\n \t\t\t\tbreak;\n \t\t\t\t\tif (i + adjustedIndex == j) {\n \t\t\t\t\t\tnextDate = now;\n \t\t\t\t\t} else {\n\t\t\t\t\t\tnextDate = v[i + adjustedIndex];\n\t\t\t\t\t\tnextDate = csv[i + adjustedIndex];\n \t\t\t\t\t\tif (nextDate > end)\n \t\t\t\t\t\t\tnextDate = end;\n \t\t\t\t\t}\n \t\t\t\t\tif (i == j - adjustedIndex) {\n \t\t\t\t\t\treturn 0;\n \t\t\t\t\t} else {\n\t\t\t\t\t\tint nextDate = v[i + adjustedIndex];\n\t\t\t\t\t\tint nextDate = csv[i + adjustedIndex];\n \n \t\t\t\t\t\tif (nextDate >= end)\n \t\t\t\t\t\t\treturn 0;"}}},{"rowIdx":850,"cells":{"lang":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"b01a5f3acc3ae6a83449d2393d2f5580259ba312"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"filamentgroup/auto-complete,filamentgroup/component,filamentgroup/auto-complete,filamentgroup/auto-complete"},"new_contents":{"kind":"string","value":"/*\n * simple auto-enhance-able component skeleton\n * Copyright (c) 2013 Filament Group, Inc.\n * Licensed under MIT\n */\n\n(function( $ ){\n\n\tvar componentName = \"component-name-here\",\n\t\tenhancedAttr = \"data-enhanced\",\n\t\tinitSelector = \".\" + componentName + \":not([\" + enhancedAttr + \"])\";\n\n\t$.fn[ componentName ] = function(){\n\t\treturn this.each( function(){\n\t\t\t// make enhancements here\n\t\t});\n\t};\n\n\t// auto-init on enhance (which is called on domready)\n\t$( document ).bind( \"enhance\", function( e ){\n\t\tvar $sel = $( e.target ).is( initSelector ) ? $( e.target ) : $( initSelector, e.target );\n\t\t$sel[ componentName ]().attr( enhancedAttr, \"true\" );\n\t});\n\n}( jQuery ));\n"},"new_file":{"kind":"string","value":"component.js"},"old_contents":{"kind":"string","value":"/*\n * simple auto-enhance-able component skeleton\n * Copyright (c) 2013 Filament Group, Inc.\n * Licensed under MIT\n */\n\n(function( $ ){\n\n\tvar componentName = \"component-name-here\",\n\t\tenhancedAttr = \"data-enhanced\",\n\t\tinitSelector = \".\" + componentName + \":not([\" + enhancedAttr + \"])\";\n\n\t$.fn[ componentName ] = function(){\n\t\treturn this.each( function(){\n\t\t\t// make enhancements here\n\t\t});\n\t};\n\n\t// auto-init on enhance (which is called on domready)\n\t$( document ).bind( \"enhance\", function( e ){\n\t\t$( initSelector, e.target )[ componentName ]().attr( enhancedAttr, true );\n\t});\n\n}( jQuery ));\n"},"message":{"kind":"string","value":"make sure children are selected as well\n"},"old_file":{"kind":"string","value":"component.js"},"subject":{"kind":"string","value":"make sure children are selected as well"},"git_diff":{"kind":"string","value":"omponent.js\n \n \t// auto-init on enhance (which is called on domready)\n \t$( document ).bind( \"enhance\", function( e ){\n\t\t$( initSelector, e.target )[ componentName ]().attr( enhancedAttr, true );\n\t\tvar $sel = $( e.target ).is( initSelector ) ? $( e.target ) : $( initSelector, e.target );\n\t\t$sel[ componentName ]().attr( enhancedAttr, \"true\" );\n \t});\n \n }( jQuery ));"}}},{"rowIdx":851,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"53b631670500f9b138fa6294751441b7d2310f0c"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"joansmith/dmix,jcnoir/dmix,0359xiaodong/dmix,abarisain/dmix,hurzl/dmix,0359xiaodong/dmix,abarisain/dmix,jcnoir/dmix,hurzl/dmix,joansmith/dmix"},"new_contents":{"kind":"string","value":"/*\n * Copyright (C) 2010-2014 The MPDroid 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 */\n\npackage com.namelessdev.mpdroid;\n\nimport org.a0z.mpd.MPDStatus;\nimport org.a0z.mpd.event.StatusChangeListener;\nimport org.a0z.mpd.exception.MPDServerException;\n\nimport android.app.Service;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.media.AudioManager;\nimport android.media.AudioManager.OnAudioFocusChangeListener;\nimport android.media.MediaPlayer;\nimport android.media.MediaPlayer.OnCompletionListener;\nimport android.media.MediaPlayer.OnErrorListener;\nimport android.media.MediaPlayer.OnPreparedListener;\nimport android.os.Handler;\nimport android.os.IBinder;\nimport android.os.Message;\nimport android.os.PowerManager;\nimport android.os.StrictMode;\nimport android.telephony.PhoneStateListener;\nimport android.telephony.TelephonyManager;\nimport android.util.Log;\n\nimport java.io.IOException;\n\n/**\n * StreamingService hooks Android's audio framework to the\n * user's MPD streaming server to allow local audio playback.\n *\n * @author Arnaud Barisain Monrose (Dream_Team)\n * @version $Id: $\n */\nfinal public class StreamingService extends Service implements\n /**\n * OnInfoListener is not used because it is broken (never gets called, ever)..\n * OnBufferingUpdateListener is not used because it depends on a stream completion time.\n */\n OnAudioFocusChangeListener,\n OnCompletionListener,\n OnErrorListener,\n OnPreparedListener,\n StatusChangeListener {\n\n private static final String TAG = \"StreamingService\";\n\n private static final String FULLY_QUALIFIED_NAME = \"com.namelessdev.mpdroid.\" + TAG + \".\";\n\n /** Kills (or hides) the notification if StreamingService started it. */\n public static final String ACTION_NOTIFICATION_STOP = FULLY_QUALIFIED_NAME\n + \"NOTIFICATION_STOP\";\n\n public static final String ACTION_START = FULLY_QUALIFIED_NAME + \"START_STREAMING\";\n\n /** Keeps the notification alive, but puts it in non-streaming status. */\n public static final String ACTION_STREAMING_STOP = FULLY_QUALIFIED_NAME + \"STOP_STREAMING\";\n\n public static final String ACTION_BUFFERING_BEGIN = FULLY_QUALIFIED_NAME + \"BUFFERING_BEGIN\";\n\n public static final String ACTION_BUFFERING_END = FULLY_QUALIFIED_NAME + \"BUFFERING_END\";\n\n private static boolean serviceWoundDown = false;\n\n final private Handler delayedStopHandler = new Handler() {\n @Override\n public void handleMessage(Message msg) {\n Log.d(TAG, \"Stopping self by handler delay.\");\n stopSelf();\n }\n };\n\n final private Handler delayedPlayHandler = new Handler() {\n @Override\n public void handleMessage(Message msg) {\n mediaPlayer.prepareAsync();\n }\n };\n\n private boolean serviceControlHandlersActive = false;\n\n private TelephonyManager mTelephonyManager = null;\n\n private MPDApplication app = null;\n\n private MediaPlayer mediaPlayer = null;\n\n private AudioManager audioManager = null;\n\n private boolean streamingStoppedForCall = false;\n\n private PowerManager.WakeLock mWakeLock = null;\n\n /** Is MPD playing? */\n private boolean isPlaying = false;\n\n public static boolean isWoundDown() {\n return serviceWoundDown;\n }\n\n private static void serviceWoundDown(boolean value) {\n serviceWoundDown = value;\n }\n\n /**\n * Setup for the method which allows MPDroid to override behavior during\n * phone events.\n */\n final private PhoneStateListener phoneStateListener = new PhoneStateListener() {\n @Override\n public void onCallStateChanged(int state, String incomingNumber) {\n switch (state) {\n case TelephonyManager.CALL_STATE_RINGING:\n final int ringVolume = audioManager.getStreamVolume(AudioManager.STREAM_RING);\n if (ringVolume == 0) {\n break;\n } /** Otherwise, continue */\n case TelephonyManager.CALL_STATE_OFFHOOK:\n if (isPlaying) {\n streamingStoppedForCall = true;\n windDownResources(ACTION_STREAMING_STOP);\n }\n break;\n case TelephonyManager.CALL_STATE_IDLE:\n // Resume playback only if music was playing when the call was answered\n if (streamingStoppedForCall) {\n tryToStream();\n streamingStoppedForCall = false;\n }\n break;\n }\n }\n };\n\n /** Keep track of the number of errors encountered. */\n private int errorIterator = 0;\n\n /** Keep track when mediaPlayer is preparing a stream */\n private boolean preparingStreaming = false;\n\n /**\n * getState is a convenience method to safely retrieve a state object.\n *\n * @return A current state object.\n */\n private String getState() {\n Log.d(TAG, \"getState()\");\n String state = null;\n\n try {\n state = app.oMPDAsyncHelper.oMPD.getStatus().getState();\n } catch (MPDServerException e) {\n Log.w(TAG, \"Failed to get the current MPD state.\", e);\n }\n\n return state;\n }\n\n /**\n * If streaming mode is activated this will setup the Android mediaPlayer\n * framework, register the media button events, register the remote control\n * client then setup and the framework streaming.\n */\n private void tryToStream() {\n if (preparingStreaming) {\n Log.d(TAG, \"A stream is already being prepared.\");\n } else if (!isPlaying) {\n Log.d(TAG, \"MPD is not currently playing, can't stream.\");\n } else if (!app.getApplicationState().streamingMode) {\n Log.d(TAG, \"streamingMode is not currently active, won't stream.\");\n } else {\n beginStreaming();\n }\n }\n\n private void beginStreaming() {\n Log.d(TAG, \"StreamingService.beginStreaming()\");\n if (mediaPlayer == null) {\n windUpResources();\n }\n\n final String streamSource = getStreamSource();\n final int ASYNC_IDLE = 1500;\n preparingStreaming = true;\n stopControlHandlers();\n\n sendIntent(ACTION_BUFFERING_BEGIN, NotificationService.class);\n\n /**\n * With MediaPlayer, there is a racy bug which affects, minimally, Android KitKat and lower.\n * If mediaPlayer.prepareAsync() is called too soon after mediaPlayer.setDataSource(), and\n * after the initial mediaPlayer.play(), general and non-specific errors are usually emitted\n * for the first few 100 milliseconds.\n *\n * Sometimes, these errors result in nagging Log errors, sometimes these errors result in\n * unrecoverable errors. This handler sets up a 1.5 second delay between\n * mediaPlayer.setDataSource() and mediaPlayer.AsyncPrepare() whether first play after\n * service start or not.\n *\n * The magic number here can be adjusted if there are any more problems. I have witnessed\n * these errors occur at 750ms, but never higher. It's worth doubling, even in optimal\n * conditions, stream buffering is pretty slow anyhow. Adjust if necessary.\n *\n * This order is very specific and if interrupted can cause big problems.\n */\n try {\n mediaPlayer.reset();\n mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);\n mediaPlayer.setDataSource(streamSource);\n Message msg = delayedPlayHandler.obtainMessage();\n delayedPlayHandler.sendMessageDelayed(msg, ASYNC_IDLE); /** Go to onPrepared() */\n } catch (IOException e) {\n Log.e(TAG, \"IO failure while trying to stream from: \" + streamSource, e);\n windDownResources(ACTION_STREAMING_STOP);\n } catch (IllegalStateException e) {\n Log.e(TAG,\n \"This is typically caused by a change in the server state during stream preparation.\",\n e);\n windDownResources(ACTION_STREAMING_STOP);\n } finally {\n delayedPlayHandler.removeCallbacksAndMessages(delayedPlayHandler);\n }\n }\n\n @Override\n public void connectionStateChanged(boolean connected, boolean connectionLost) {\n }\n\n /** A method to send a quick message to another class. */\n private void sendIntent(String msg, Class destination) {\n Log.d(TAG, \"Sending intent \" + msg + \" to \" + destination + \".\");\n Intent i = new Intent(this, destination);\n i.setAction(msg);\n this.startService(i);\n }\n\n /**\n * A JMPDComm callback to be invoked during library state changes.\n *\n * @param updating true when updating, false when not updating.\n */\n @Override\n public void libraryStateChanged(boolean updating) {\n }\n\n /**\n * Handle the change of volume if a notification, or any other kind of\n * interrupting audio event.\n *\n * @param focusChange The type of focus change.\n */\n @Override\n final public void onAudioFocusChange(int focusChange) {\n Log.d(TAG, \"StreamingService.onAudioFocusChange()\");\n if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {\n mediaPlayer.setVolume(0.2f, 0.2f);\n } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {\n mediaPlayer.setVolume(1f, 1f);\n } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {\n sendIntent(NotificationService.ACTION_PAUSE, NotificationService.class);\n }\n }\n\n @Override\n final public IBinder onBind(Intent intent) {\n return null;\n }\n\n /**\n * A MediaPlayer callback to be invoked when playback of a media source has completed.\n *\n * @param mp The MediaPlayer object that reached the end of the stream.\n */\n @Override\n final public void onCompletion(MediaPlayer mp) {\n Log.d(TAG, \"StreamingService.onCompletion()\");\n\n /**\n * If MPD is restarted during streaming, onCompletion() will be called.\n * onStateChange() won't be called. If we still detect playing, restart the stream.\n */\n if (isPlaying) {\n tryToStream();\n } else {\n /** The only way we make it here is with an empty playlist. */\n windDownResources(ACTION_NOTIFICATION_STOP);\n }\n }\n\n final public void onCreate() {\n Log.d(TAG, \"StreamingService.onCreate()\");\n\n app = (MPDApplication) getApplication();\n\n if (app == null || !app.getApplicationState().streamingMode) {\n stopSelf();\n }\n\n audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);\n\n StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();\n StrictMode.setThreadPolicy(policy);\n\n app.oMPDAsyncHelper.addStatusChangeListener(this);\n app.addConnectionLock(this);\n\n isPlaying = MPDStatus.MPD_STATE_PLAYING.equals(getState());\n }\n\n private String getStreamSource() {\n return \"http://\"\n + app.oMPDAsyncHelper.getConnectionSettings().getConnectionStreamingServer() + \":\"\n + app.oMPDAsyncHelper.getConnectionSettings().iPortStreaming + \"/\"\n + app.oMPDAsyncHelper.getConnectionSettings().sSuffixStreaming;\n }\n\n /**\n * This happens at the beginning of beginStreaming() to populate all\n * necessary resources for handling the MediaPlayer stream.\n */\n private void windUpResources() {\n Log.d(TAG, \"Winding up resources.\");\n\n serviceWoundDown(false);\n\n if (mWakeLock == null) {\n final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);\n mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);\n mWakeLock.setReferenceCounted(false);\n }\n\n mWakeLock.acquire();\n\n mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);\n mTelephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);\n\n mediaPlayer = new MediaPlayer();\n mediaPlayer.setOnCompletionListener(this);\n mediaPlayer.setOnPreparedListener(this);\n mediaPlayer.setOnErrorListener(this);\n }\n\n /**\n * windDownResources occurs after a delay or during stopSelf() to\n * clean up resources and give up focus to the phone and sound.\n */\n private void windDownResources(String action) {\n Log.d(TAG, \"Winding down resources.\");\n\n serviceWoundDown(true);\n\n if (ACTION_STREAMING_STOP.equals(action)) {\n setupServiceControlHandlers();\n }\n\n if (action != null) {\n sendIntent(action, NotificationService.class);\n }\n\n /**\n * Make sure that the first thing we do is releasing the wake lock\n */\n if (mWakeLock != null) {\n mWakeLock.release();\n }\n\n if (mTelephonyManager != null) {\n mTelephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);\n }\n\n if (audioManager != null) {\n audioManager.abandonAudioFocus(this);\n }\n\n if (mediaPlayer != null) {\n if (mediaPlayer.isPlaying()) {\n mediaPlayer.stop();\n }\n mediaPlayer.reset();\n mediaPlayer.release();\n mediaPlayer = null;\n }\n\n /**\n * If we got here due to an exception, try to stream\n * again until the error iterator runs out.\n */\n if (preparingStreaming) {\n Log.d(TAG,\n \"Stream had an error, trying to re-initiate streaming, try: \" + errorIterator);\n errorIterator += 1;\n preparingStreaming = false;\n tryToStream();\n }\n }\n\n @Override\n final public void onDestroy() {\n Log.d(TAG, \"StreamingService.onDestroy()\");\n\n stopControlHandlers();\n\n /** Remove the current MPD listeners */\n app.oMPDAsyncHelper.removeStatusChangeListener(this);\n\n windDownResources(ACTION_NOTIFICATION_STOP);\n\n app.removeConnectionLock(this);\n app.getApplicationState().streamingMode = false;\n }\n\n\n /**\n * A MediaPlayer callback to be invoked when there has been an error during an asynchronous\n * operation (other errors will throw exceptions at method call time).\n *\n * @param mp The current mediaPlayer.\n * @param what The type of error that has occurred.\n * @param extra An extra code, specific to the error. Typically implementation dependent.\n * @return True if the method handled the error, false if it didn't. Returning false, or not\n * having an OnErrorListener at all, will cause the OnCompletionListener to be called.\n */\n @Override\n final public boolean onError(MediaPlayer mp, int what, int extra) {\n Log.d(TAG, \"StreamingService.onError()\");\n final int MAX_ERROR = 4;\n\n if (errorIterator > 0) {\n Log.d(TAG, \"Error occurred while streaming, this is try #\" + errorIterator\n + \", will attempt up to \" + MAX_ERROR + \" times.\");\n }\n\n /** This keeps from continuous errors and battery draining. */\n if (errorIterator > MAX_ERROR) {\n stopSelf();\n }\n\n /** beginStreaming() will never start otherwise. */\n preparingStreaming = false;\n\n /** Either way we need to stop streaming. */\n windDownResources(ACTION_STREAMING_STOP);\n\n errorIterator += 1;\n return true;\n }\n\n /**\n * A MediaPlayer callback used when the media file is ready for playback.\n *\n * @param mp The MediaPlayer that is ready for playback.\n */\n @Override\n final public void onPrepared(MediaPlayer mp) {\n Log.d(TAG, \"StreamingService.onPrepared()\");\n final int focusResult = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC,\n AudioManager.AUDIOFOCUS_GAIN);\n\n /**\n * Not to be playing here is unlikely but it's a race we need to avoid.\n */\n if (isPlaying && focusResult == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {\n sendIntent(ACTION_BUFFERING_END, NotificationService.class);\n mediaPlayer.start();\n } else {\n /** Because preparingStreaming is still set, this will reset the stream. */\n windDownResources(ACTION_STREAMING_STOP);\n }\n\n preparingStreaming = false;\n errorIterator = 0; /** Reset the error iterator. */\n }\n\n /**\n * Called by the system every time a client explicitly\n * starts the service by calling startService(Intent).\n */\n @Override\n final public int onStartCommand(Intent intent, int flags, int startId) {\n Log.d(TAG, \"StreamingService.onStartCommand()\");\n if (!app.getApplicationState().streamingMode) {\n stopSelf();\n }\n\n switch (intent.getAction()) {\n case ACTION_START:\n tryToStream();\n break;\n case ACTION_STREAMING_STOP:\n windDownResources(ACTION_STREAMING_STOP);\n break;\n }\n\n /**\n * We want this service to continue running until it is explicitly\n * stopped, so return sticky.\n */\n return START_STICKY;\n }\n\n @Override\n public void playlistChanged(MPDStatus mpdStatus, int oldPlaylistVersion) {\n }\n\n @Override\n public void randomChanged(boolean random) {\n }\n\n @Override\n public void repeatChanged(boolean repeating) {\n }\n\n /**\n * A JMPDComm callback which is invoked on MPD status change.\n *\n * @param mpdStatus MPDStatus after event.\n * @param oldState Previous state.\n */\n @Override\n final public void stateChanged(MPDStatus mpdStatus, String oldState) {\n Log.d(TAG, \"StreamingService.stateChanged()\");\n\n final String state = mpdStatus.getState();\n\n if (state != null) {\n switch (state) {\n case MPDStatus.MPD_STATE_PLAYING:\n stopControlHandlers();\n isPlaying = true;\n tryToStream();\n break;\n case MPDStatus.MPD_STATE_STOPPED:\n case MPDStatus.MPD_STATE_PAUSED:\n /**\n * If in the middle of stream preparation, \"Buffering…\" notification message\n * is likely.\n */\n if (preparingStreaming) {\n sendIntent(ACTION_BUFFERING_END, NotificationService.class);\n }\n\n /** If the playlistLength is == 0, let onCompletion handle it. */\n if (mpdStatus.getPlaylistLength() != 0) {\n windDownResources(ACTION_STREAMING_STOP);\n }\n isPlaying = false;\n break;\n }\n }\n }\n\n private void stopControlHandlers() {\n if (serviceControlHandlersActive) {\n Log.d(TAG, \"Removing control handlers\");\n delayedStopHandler.removeCallbacksAndMessages(null);\n serviceControlHandlersActive = false;\n }\n }\n\n private void setupServiceControlHandlers() {\n if (!serviceControlHandlersActive) {\n Log.d(TAG, \"Setting up control handlers\");\n final int STOP_IDLE_DELAY = 600000; /** 10 minutes */\n /**\n * Stop handler so we don't annoy the user when they forget to turn streamingMode off.\n */\n final Message msg = delayedStopHandler.obtainMessage();\n delayedStopHandler.sendMessageDelayed(msg, STOP_IDLE_DELAY);\n serviceControlHandlersActive = true;\n }\n }\n\n @Override\n public void trackChanged(MPDStatus mpdStatus, int oldTrack) {\n }\n\n @Override\n public void volumeChanged(MPDStatus mpdStatus, int oldVolume) {\n }\n}\n"},"new_file":{"kind":"string","value":"MPDroid/src/com/namelessdev/mpdroid/StreamingService.java"},"old_contents":{"kind":"string","value":"/*\n * Copyright (C) 2010-2014 The MPDroid 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 */\n\npackage com.namelessdev.mpdroid;\n\nimport org.a0z.mpd.MPDStatus;\nimport org.a0z.mpd.event.StatusChangeListener;\nimport org.a0z.mpd.exception.MPDServerException;\n\nimport android.app.Service;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.media.AudioManager;\nimport android.media.AudioManager.OnAudioFocusChangeListener;\nimport android.media.MediaPlayer;\nimport android.media.MediaPlayer.OnCompletionListener;\nimport android.media.MediaPlayer.OnErrorListener;\nimport android.media.MediaPlayer.OnPreparedListener;\nimport android.os.Handler;\nimport android.os.IBinder;\nimport android.os.Message;\nimport android.os.PowerManager;\nimport android.os.StrictMode;\nimport android.telephony.PhoneStateListener;\nimport android.telephony.TelephonyManager;\nimport android.util.Log;\n\nimport java.io.IOException;\n\n/**\n * StreamingService hooks Android's audio framework to the\n * user's MPD streaming server to allow local audio playback.\n *\n * @author Arnaud Barisain Monrose (Dream_Team)\n * @version $Id: $\n */\nfinal public class StreamingService extends Service implements\n /**\n * OnInfoListener is not used because it is broken (never gets called, ever)..\n * OnBufferingUpdateListener is not used because it depends on a stream completion time.\n */\n OnAudioFocusChangeListener,\n OnCompletionListener,\n OnErrorListener,\n OnPreparedListener,\n StatusChangeListener {\n\n private static final String TAG = \"StreamingService\";\n\n private static final String FULLY_QUALIFIED_NAME = \"com.namelessdev.mpdroid.\" + TAG + \".\";\n\n /** Kills (or hides) the notification if StreamingService started it. */\n public static final String ACTION_NOTIFICATION_STOP = FULLY_QUALIFIED_NAME\n + \"NOTIFICATION_STOP\";\n\n public static final String ACTION_START = FULLY_QUALIFIED_NAME + \"START_STREAMING\";\n\n /** Keeps the notification alive, but puts it in non-streaming status. */\n public static final String ACTION_STREAMING_STOP = FULLY_QUALIFIED_NAME + \"STOP_STREAMING\";\n\n public static final String ACTION_BUFFERING_BEGIN = FULLY_QUALIFIED_NAME + \"BUFFERING_BEGIN\";\n\n public static final String ACTION_BUFFERING_END = FULLY_QUALIFIED_NAME + \"BUFFERING_END\";\n\n private static boolean serviceWoundDown = false;\n\n final private Handler delayedStopHandler = new Handler() {\n @Override\n public void handleMessage(Message msg) {\n Log.d(TAG, \"Stopping self by handler delay.\");\n stopSelf();\n }\n };\n\n final private Handler delayedPlayHandler = new Handler() {\n @Override\n public void handleMessage(Message msg) {\n mediaPlayer.prepareAsync();\n }\n };\n\n private boolean serviceControlHandlersActive = false;\n\n private TelephonyManager mTelephonyManager = null;\n\n private MPDApplication app = null;\n\n private MediaPlayer mediaPlayer = null;\n\n private AudioManager audioManager = null;\n\n private boolean streamingStoppedForCall = false;\n\n private PowerManager.WakeLock mWakeLock = null;\n\n /** Is MPD playing? */\n private boolean isPlaying = false;\n\n public static boolean isWoundDown() {\n return serviceWoundDown;\n }\n\n private static void serviceWoundDown(boolean value) {\n serviceWoundDown = value;\n }\n\n /**\n * Setup for the method which allows MPDroid to override behavior during\n * phone events.\n */\n final private PhoneStateListener phoneStateListener = new PhoneStateListener() {\n @Override\n public void onCallStateChanged(int state, String incomingNumber) {\n switch (state) {\n case TelephonyManager.CALL_STATE_RINGING:\n final int ringVolume = audioManager.getStreamVolume(AudioManager.STREAM_RING);\n if (ringVolume == 0) {\n break;\n } /** Otherwise, continue */\n case TelephonyManager.CALL_STATE_OFFHOOK:\n if (isPlaying) {\n streamingStoppedForCall = true;\n windDownResources(ACTION_STREAMING_STOP);\n }\n break;\n case TelephonyManager.CALL_STATE_IDLE:\n // Resume playback only if music was playing when the call was answered\n if (streamingStoppedForCall) {\n tryToStream();\n streamingStoppedForCall = false;\n }\n break;\n }\n }\n };\n\n /** Keep track of the number of errors encountered. */\n private int errorIterator = 0;\n\n /** Keep track when mediaPlayer is preparing a stream */\n private boolean preparingStreaming = false;\n\n /**\n * getState is a convenience method to safely retrieve a state object.\n *\n * @return A current state object.\n */\n private String getState() {\n Log.d(TAG, \"getState()\");\n String state = null;\n\n try {\n state = app.oMPDAsyncHelper.oMPD.getStatus().getState();\n } catch (MPDServerException e) {\n Log.w(TAG, \"Failed to get the current MPD state.\", e);\n }\n\n return state;\n }\n\n /**\n * If streaming mode is activated this will setup the Android mediaPlayer\n * framework, register the media button events, register the remote control\n * client then setup and the framework streaming.\n */\n private void tryToStream() {\n if (preparingStreaming) {\n Log.d(TAG, \"A stream is already being prepared.\");\n } else if (!isPlaying) {\n Log.d(TAG, \"MPD is not currently playing, can't stream.\");\n } else if (!app.getApplicationState().streamingMode) {\n Log.d(TAG, \"streamingMode is not currently active, won't stream.\");\n } else {\n beginStreaming();\n }\n }\n\n private void beginStreaming() {\n Log.d(TAG, \"StreamingService.beginStreaming()\");\n if (mediaPlayer == null) {\n windUpResources();\n }\n\n final String streamSource = getStreamSource();\n final int ASYNC_IDLE = 1500;\n preparingStreaming = true;\n stopControlHandlers();\n\n sendIntent(ACTION_BUFFERING_BEGIN, NotificationService.class);\n\n /**\n * With MediaPlayer, there is a racy bug which affects, minimally, Android KitKat and lower.\n * If mediaPlayer.prepareAsync() is called too soon after mediaPlayer.setDataSource(), and\n * after the initial mediaPlayer.play(), general and non-specific errors are usually emitted\n * for the first few 100 milliseconds.\n *\n * Sometimes, these errors result in nagging Log errors, sometimes these errors result in\n * unrecoverable errors. This handler sets up a 1.5 second delay between\n * mediaPlayer.setDataSource() and mediaPlayer.AsyncPrepare() whether first play after\n * service start or not.\n *\n * The magic number here can be adjusted if there are any more problems. I have witnessed\n * these errors occur at 750ms, but never higher. It's worth doubling, even in optimal\n * conditions, stream buffering is pretty slow anyhow. Adjust if necessary.\n *\n * This order is very specific and if interrupted can cause big problems.\n */\n try {\n mediaPlayer.reset();\n mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);\n mediaPlayer.setDataSource(streamSource);\n Message msg = delayedPlayHandler.obtainMessage();\n delayedPlayHandler.sendMessageDelayed(msg, ASYNC_IDLE); /** Go to onPrepared() */\n } catch (IOException e) {\n Log.e(TAG, \"IO failure while trying to stream from: \" + streamSource, e);\n windDownResources(ACTION_STREAMING_STOP);\n } catch (IllegalStateException e) {\n Log.e(TAG,\n \"This is typically caused by a change in the server state during stream preparation.\",\n e);\n windDownResources(ACTION_STREAMING_STOP);\n } finally {\n delayedPlayHandler.removeCallbacksAndMessages(delayedPlayHandler);\n }\n }\n\n @Override\n public void connectionStateChanged(boolean connected, boolean connectionLost) {\n }\n\n /** A method to send a quick message to another class. */\n private void sendIntent(String msg, Class destination) {\n Log.d(TAG, \"Sending intent \" + msg + \" to \" + destination + \".\");\n Intent i = new Intent(this, destination);\n i.setAction(msg);\n this.startService(i);\n }\n\n /**\n * A JMPDComm callback to be invoked during library state changes.\n *\n * @param updating true when updating, false when not updating.\n */\n @Override\n public void libraryStateChanged(boolean updating) {\n }\n\n /**\n * Handle the change of volume if a notification, or any other kind of\n * interrupting audio event.\n *\n * @param focusChange The type of focus change.\n */\n @Override\n final public void onAudioFocusChange(int focusChange) {\n Log.d(TAG, \"StreamingService.onAudioFocusChange()\");\n if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {\n mediaPlayer.setVolume(0.2f, 0.2f);\n } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {\n mediaPlayer.setVolume(1f, 1f);\n } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {\n sendIntent(NotificationService.ACTION_PAUSE, NotificationService.class);\n }\n }\n\n @Override\n final public IBinder onBind(Intent intent) {\n return null;\n }\n\n /**\n * A MediaPlayer callback to be invoked when playback of a media source has completed.\n *\n * @param mp The MediaPlayer object that reached the end of the stream.\n */\n @Override\n final public void onCompletion(MediaPlayer mp) {\n Log.d(TAG, \"StreamingService.onCompletion()\");\n\n /**\n * If MPD is restarted during streaming, onCompletion() will be called.\n * onStateChange() won't be called. If we still detect playing, restart the stream.\n */\n if (isPlaying) {\n tryToStream();\n } else {\n /** The only way we make it here is with an empty playlist. */\n windDownResources(ACTION_NOTIFICATION_STOP);\n }\n }\n\n final public void onCreate() {\n Log.d(TAG, \"StreamingService.onCreate()\");\n\n app = (MPDApplication) getApplication();\n\n if (app == null || !app.getApplicationState().streamingMode) {\n stopSelf();\n }\n\n audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);\n\n StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();\n StrictMode.setThreadPolicy(policy);\n\n app.oMPDAsyncHelper.addStatusChangeListener(this);\n app.addConnectionLock(this);\n\n isPlaying = MPDStatus.MPD_STATE_PLAYING.equals(getState());\n }\n\n private String getStreamSource() {\n return \"http://\"\n + app.oMPDAsyncHelper.getConnectionSettings().getConnectionStreamingServer() + \":\"\n + app.oMPDAsyncHelper.getConnectionSettings().iPortStreaming + \"/\"\n + app.oMPDAsyncHelper.getConnectionSettings().sSuffixStreaming;\n }\n\n /**\n * This happens at the beginning of beginStreaming() to populate all\n * necessary resources for handling the MediaPlayer stream.\n */\n private void windUpResources() {\n Log.d(TAG, \"Winding up resources.\");\n\n serviceWoundDown(false);\n\n if (mWakeLock == null) {\n final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);\n mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);\n mWakeLock.setReferenceCounted(false);\n }\n\n mWakeLock.acquire();\n\n mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);\n mTelephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);\n\n mediaPlayer = new MediaPlayer();\n mediaPlayer.setOnCompletionListener(this);\n mediaPlayer.setOnPreparedListener(this);\n mediaPlayer.setOnErrorListener(this);\n }\n\n /**\n * windDownResources occurs after a delay or during stopSelf() to\n * clean up resources and give up focus to the phone and sound.\n */\n private void windDownResources(String action) {\n Log.d(TAG, \"Winding down resources.\");\n\n serviceWoundDown(true);\n\n if (ACTION_STREAMING_STOP.equals(action)) {\n setupServiceControlHandlers();\n }\n\n if (action != null) {\n sendIntent(action, NotificationService.class);\n }\n\n /**\n * Make sure that the first thing we do is releasing the wake lock\n */\n if (mWakeLock != null) {\n mWakeLock.release();\n }\n\n if (mTelephonyManager != null) {\n mTelephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);\n }\n\n if (mediaPlayer != null) {\n if (mediaPlayer.isPlaying()) {\n mediaPlayer.stop();\n }\n mediaPlayer.reset();\n mediaPlayer.release();\n mediaPlayer = null;\n }\n\n /**\n * If we got here due to an exception, try to stream\n * again until the error iterator runs out.\n */\n if (preparingStreaming) {\n Log.d(TAG,\n \"Stream had an error, trying to re-initiate streaming, try: \" + errorIterator);\n errorIterator += 1;\n preparingStreaming = false;\n tryToStream();\n }\n }\n\n @Override\n final public void onDestroy() {\n Log.d(TAG, \"StreamingService.onDestroy()\");\n\n stopControlHandlers();\n\n if (audioManager != null) {\n audioManager.abandonAudioFocus(this);\n }\n\n /** Remove the current MPD listeners */\n app.oMPDAsyncHelper.removeStatusChangeListener(this);\n\n windDownResources(ACTION_NOTIFICATION_STOP);\n\n app.removeConnectionLock(this);\n app.getApplicationState().streamingMode = false;\n }\n\n\n /**\n * A MediaPlayer callback to be invoked when there has been an error during an asynchronous\n * operation (other errors will throw exceptions at method call time).\n *\n * @param mp The current mediaPlayer.\n * @param what The type of error that has occurred.\n * @param extra An extra code, specific to the error. Typically implementation dependent.\n * @return True if the method handled the error, false if it didn't. Returning false, or not\n * having an OnErrorListener at all, will cause the OnCompletionListener to be called.\n */\n @Override\n final public boolean onError(MediaPlayer mp, int what, int extra) {\n Log.d(TAG, \"StreamingService.onError()\");\n final int MAX_ERROR = 4;\n\n if (errorIterator > 0) {\n Log.d(TAG, \"Error occurred while streaming, this is try #\" + errorIterator\n + \", will attempt up to \" + MAX_ERROR + \" times.\");\n }\n\n /** This keeps from continuous errors and battery draining. */\n if (errorIterator > MAX_ERROR) {\n stopSelf();\n }\n\n /** beginStreaming() will never start otherwise. */\n preparingStreaming = false;\n\n /** Either way we need to stop streaming. */\n windDownResources(ACTION_STREAMING_STOP);\n\n errorIterator += 1;\n return true;\n }\n\n /**\n * A MediaPlayer callback used when the media file is ready for playback.\n *\n * @param mp The MediaPlayer that is ready for playback.\n */\n @Override\n final public void onPrepared(MediaPlayer mp) {\n Log.d(TAG, \"StreamingService.onPrepared()\");\n final int focusResult = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC,\n AudioManager.AUDIOFOCUS_GAIN);\n\n /**\n * Not to be playing here is unlikely but it's a race we need to avoid.\n */\n if (isPlaying && focusResult == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {\n sendIntent(ACTION_BUFFERING_END, NotificationService.class);\n mediaPlayer.start();\n } else {\n /** Because preparingStreaming is still set, this will reset the stream. */\n windDownResources(ACTION_STREAMING_STOP);\n }\n\n preparingStreaming = false;\n errorIterator = 0; /** Reset the error iterator. */\n }\n\n /**\n * Called by the system every time a client explicitly\n * starts the service by calling startService(Intent).\n */\n @Override\n final public int onStartCommand(Intent intent, int flags, int startId) {\n Log.d(TAG, \"StreamingService.onStartCommand()\");\n if (!app.getApplicationState().streamingMode) {\n stopSelf();\n }\n\n switch (intent.getAction()) {\n case ACTION_START:\n tryToStream();\n break;\n case ACTION_STREAMING_STOP:\n windDownResources(ACTION_STREAMING_STOP);\n break;\n }\n\n /**\n * We want this service to continue running until it is explicitly\n * stopped, so return sticky.\n */\n return START_STICKY;\n }\n\n @Override\n public void playlistChanged(MPDStatus mpdStatus, int oldPlaylistVersion) {\n }\n\n @Override\n public void randomChanged(boolean random) {\n }\n\n @Override\n public void repeatChanged(boolean repeating) {\n }\n\n /**\n * A JMPDComm callback which is invoked on MPD status change.\n *\n * @param mpdStatus MPDStatus after event.\n * @param oldState Previous state.\n */\n @Override\n final public void stateChanged(MPDStatus mpdStatus, String oldState) {\n Log.d(TAG, \"StreamingService.stateChanged()\");\n\n final String state = mpdStatus.getState();\n\n if (state != null) {\n switch (state) {\n case MPDStatus.MPD_STATE_PLAYING:\n stopControlHandlers();\n isPlaying = true;\n tryToStream();\n break;\n case MPDStatus.MPD_STATE_STOPPED:\n case MPDStatus.MPD_STATE_PAUSED:\n /**\n * If in the middle of stream preparation, \"Buffering…\" notification message\n * is likely.\n */\n if (preparingStreaming) {\n sendIntent(ACTION_BUFFERING_END, NotificationService.class);\n }\n\n /** If the playlistLength is == 0, let onCompletion handle it. */\n if (mpdStatus.getPlaylistLength() != 0) {\n windDownResources(ACTION_STREAMING_STOP);\n }\n isPlaying = false;\n break;\n }\n }\n }\n\n private void stopControlHandlers() {\n if (serviceControlHandlersActive) {\n Log.d(TAG, \"Removing control handlers\");\n delayedStopHandler.removeCallbacksAndMessages(null);\n serviceControlHandlersActive = false;\n }\n }\n\n private void setupServiceControlHandlers() {\n if (!serviceControlHandlersActive) {\n Log.d(TAG, \"Setting up control handlers\");\n final int STOP_IDLE_DELAY = 600000; /** 10 minutes */\n /**\n * Stop handler so we don't annoy the user when they forget to turn streamingMode off.\n */\n final Message msg = delayedStopHandler.obtainMessage();\n delayedStopHandler.sendMessageDelayed(msg, STOP_IDLE_DELAY);\n serviceControlHandlersActive = true;\n }\n }\n\n @Override\n public void trackChanged(MPDStatus mpdStatus, int oldTrack) {\n }\n\n @Override\n public void volumeChanged(MPDStatus mpdStatus, int oldVolume) {\n }\n}\n"},"message":{"kind":"string","value":"StreamingService: Abandon audio focus when winding down resources.\n"},"old_file":{"kind":"string","value":"MPDroid/src/com/namelessdev/mpdroid/StreamingService.java"},"subject":{"kind":"string","value":"StreamingService: Abandon audio focus when winding down resources."},"git_diff":{"kind":"string","value":"PDroid/src/com/namelessdev/mpdroid/StreamingService.java\n mTelephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);\n }\n \n if (audioManager != null) {\n audioManager.abandonAudioFocus(this);\n }\n\n if (mediaPlayer != null) {\n if (mediaPlayer.isPlaying()) {\n mediaPlayer.stop();\n Log.d(TAG, \"StreamingService.onDestroy()\");\n \n stopControlHandlers();\n\n if (audioManager != null) {\n audioManager.abandonAudioFocus(this);\n }\n \n /** Remove the current MPD listeners */\n app.oMPDAsyncHelper.removeStatusChangeListener(this);"}}},{"rowIdx":852,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"4b5bc7517a4501fd13d4dd70b766804b2d4fd07b"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"Armandorev/url-shortener,Armandorev/url-shortener,Armandorev/url-shortener,Armandorev/url-shortener"},"new_contents":{"kind":"string","value":"package benjamin.groehbiel.ch.shortener.redis;\n\nimport benjamin.groehbiel.ch.JsonHelper;\nimport benjamin.groehbiel.ch.shortener.ShortenerHandle;\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport org.springframework.stereotype.Service;\nimport redis.clients.jedis.Jedis;\nimport redis.clients.jedis.JedisPool;\nimport redis.clients.jedis.JedisPoolConfig;\n\nimport java.io.IOException;\nimport java.net.URI;\nimport java.util.Set;\n\n@Service\npublic class RedisManager {\n\n public static final String HASH_PREFIX = \"hash:\";\n public static final String COUNT_FIELD = \"$count\";\n\n private JedisPool pool;\n\n public RedisManager() {\n JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();\n jedisPoolConfig.setMaxTotal(16);\n\n if (System.getProperty(\"redis.password\").isEmpty()) {\n pool = createJedisPoolForTestEnv(jedisPoolConfig);\n } else {\n pool = createJedisPoolForProdEnv(jedisPoolConfig);\n }\n }\n\n public String getHashFor(String key) {\n try (Jedis jedis = pool.getResource()) {\n return jedis.get(key);\n } catch (Exception ex) {\n ex.printStackTrace();\n return null;\n }\n }\n\n public void setUrlAndHash(String key, String value) {\n try (Jedis jedis = pool.getResource()) {\n jedis.set(key, value);\n }\n }\n\n public ShortenerHandle getHandleFor(String hash) throws IOException {\n hash = hash.replace(HASH_PREFIX, \"\");\n\n try (Jedis jedis = pool.getResource()) {\n String json = jedis.get(HASH_PREFIX + hash);\n return JsonHelper.unserialize(json);\n }\n\n }\n\n public void storeHash(ShortenerHandle shortenerHandle) throws JsonProcessingException {\n URI url = shortenerHandle.getOriginalURI();\n setHashAndHandle(shortenerHandle.getHash(), shortenerHandle);\n setUrlAndHash(url.toString(), shortenerHandle.getHash());\n incrementByOne(COUNT_FIELD);\n }\n\n public void setHashAndHandle(String hash, ShortenerHandle value) throws JsonProcessingException {\n try (Jedis jedis = pool.getResource()) {\n jedis.set(HASH_PREFIX + hash, JsonHelper.serialize(value));\n }\n }\n\n public Set getHashes() {\n return getValuesFor(HASH_PREFIX + \"*\");\n }\n\n public Long incrementByOne(String key) {\n try (Jedis jedis = pool.getResource()) {\n return jedis.incrBy(key, 1);\n }\n }\n\n public Long getHashCount() {\n try (Jedis jedis = pool.getResource()) {\n String shortenedSoFar = jedis.get(COUNT_FIELD);\n\n if (shortenedSoFar == null) {\n return 0L;\n } else {\n return Long.parseLong(shortenedSoFar);\n }\n }\n }\n\n private Set getValuesFor(String regex) {\n try (Jedis jedis = pool.getResource()) {\n return jedis.keys(regex);\n }\n }\n\n public void clear() {\n try (Jedis jedis = pool.getResource()) {\n jedis.flushAll();\n }\n }\n\n public void removeHash(String hashToDelete) throws IOException {\n ShortenerHandle hashHandle = getHandleFor(hashToDelete);\n URI originalURI = hashHandle.getOriginalURI();\n\n try (Jedis jedis = pool.getResource()) {\n jedis.del(HASH_PREFIX + hashToDelete);\n jedis.del(originalURI.toString());\n jedis.decrBy(COUNT_FIELD, 1);\n }\n }\n\n private JedisPool createJedisPoolForProdEnv(JedisPoolConfig jedisPoolConfig) {\n return new JedisPool(jedisPoolConfig, System.getProperty(\"redis.host\"), Integer.parseInt(System.getProperty(\"redis.port\")), 2000, System.getProperty(\"redis.password\"));\n }\n\n private JedisPool createJedisPoolForTestEnv(JedisPoolConfig jedisPoolConfig) {\n return new JedisPool(jedisPoolConfig, System.getProperty(\"redis.host\"), Integer.parseInt(System.getProperty(\"redis.port\")));\n }\n\n}\n"},"new_file":{"kind":"string","value":"src/main/java/benjamin/groehbiel/ch/shortener/redis/RedisManager.java"},"old_contents":{"kind":"string","value":"package benjamin.groehbiel.ch.shortener.redis;\n\nimport benjamin.groehbiel.ch.JsonHelper;\nimport benjamin.groehbiel.ch.shortener.ShortenerHandle;\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport org.springframework.stereotype.Service;\nimport redis.clients.jedis.Jedis;\nimport redis.clients.jedis.JedisPool;\nimport redis.clients.jedis.JedisPoolConfig;\n\nimport java.io.IOException;\nimport java.net.URI;\nimport java.util.Set;\n\n@Service\npublic class RedisManager {\n\n public static final String HASH_PREFIX = \"hash:\";\n public static final String COUNT_FIELD = \"$count\";\n\n private JedisPool pool;\n\n public RedisManager() {\n JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();\n jedisPoolConfig.setMaxTotal(16);\n pool = new JedisPool(jedisPoolConfig, System.getProperty(\"redis.host\"), Integer.parseInt(System.getProperty(\"redis.port\")));\n }\n\n public String getHashFor(String key) {\n try (Jedis jedis = pool.getResource()) {\n return jedis.get(key);\n } catch (Exception ex) {\n ex.printStackTrace();\n return null;\n }\n }\n\n public void setUrlAndHash(String key, String value) {\n try (Jedis jedis = pool.getResource()) {\n jedis.set(key, value);\n }\n }\n\n public ShortenerHandle getHandleFor(String hash) throws IOException {\n hash = hash.replace(HASH_PREFIX, \"\");\n\n try (Jedis jedis = pool.getResource()) {\n String json = jedis.get(HASH_PREFIX + hash);\n return JsonHelper.unserialize(json);\n }\n\n }\n\n public void storeHash(ShortenerHandle shortenerHandle) throws JsonProcessingException {\n URI url = shortenerHandle.getOriginalURI();\n setHashAndHandle(shortenerHandle.getHash(), shortenerHandle);\n setUrlAndHash(url.toString(), shortenerHandle.getHash());\n incrementByOne(COUNT_FIELD);\n }\n\n public void setHashAndHandle(String hash, ShortenerHandle value) throws JsonProcessingException {\n try (Jedis jedis = pool.getResource()) {\n jedis.set(HASH_PREFIX + hash, JsonHelper.serialize(value));\n }\n }\n\n public Set getHashes() {\n return getValuesFor(HASH_PREFIX + \"*\");\n }\n\n public Long incrementByOne(String key) {\n try (Jedis jedis = pool.getResource()) {\n return jedis.incrBy(key, 1);\n }\n }\n\n public Long getHashCount() {\n try (Jedis jedis = pool.getResource()) {\n String shortenedSoFar = jedis.get(COUNT_FIELD);\n\n if (shortenedSoFar == null) {\n return 0L;\n } else {\n return Long.parseLong(shortenedSoFar);\n }\n }\n }\n\n private Set getValuesFor(String regex) {\n try (Jedis jedis = pool.getResource()) {\n return jedis.keys(regex);\n }\n }\n\n public void clear() {\n try (Jedis jedis = pool.getResource()) {\n jedis.flushAll();\n }\n }\n\n public void close() {\n pool.destroy();\n }\n\n public void removeHash(String hashToDelete) throws IOException {\n ShortenerHandle hashHandle = getHandleFor(hashToDelete);\n URI originalURI = hashHandle.getOriginalURI();\n\n try (Jedis jedis = pool.getResource()) {\n jedis.del(HASH_PREFIX + hashToDelete);\n jedis.del(originalURI.toString());\n jedis.decrBy(COUNT_FIELD, 1);\n }\n }\n}\n"},"message":{"kind":"string","value":"Fix redis authentication issue in prod\n"},"old_file":{"kind":"string","value":"src/main/java/benjamin/groehbiel/ch/shortener/redis/RedisManager.java"},"subject":{"kind":"string","value":"Fix redis authentication issue in prod"},"git_diff":{"kind":"string","value":"rc/main/java/benjamin/groehbiel/ch/shortener/redis/RedisManager.java\n public RedisManager() {\n JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();\n jedisPoolConfig.setMaxTotal(16);\n pool = new JedisPool(jedisPoolConfig, System.getProperty(\"redis.host\"), Integer.parseInt(System.getProperty(\"redis.port\")));\n\n if (System.getProperty(\"redis.password\").isEmpty()) {\n pool = createJedisPoolForTestEnv(jedisPoolConfig);\n } else {\n pool = createJedisPoolForProdEnv(jedisPoolConfig);\n }\n }\n \n public String getHashFor(String key) {\n }\n }\n \n public void close() {\n pool.destroy();\n }\n\n public void removeHash(String hashToDelete) throws IOException {\n ShortenerHandle hashHandle = getHandleFor(hashToDelete);\n URI originalURI = hashHandle.getOriginalURI();\n jedis.decrBy(COUNT_FIELD, 1);\n }\n }\n\n private JedisPool createJedisPoolForProdEnv(JedisPoolConfig jedisPoolConfig) {\n return new JedisPool(jedisPoolConfig, System.getProperty(\"redis.host\"), Integer.parseInt(System.getProperty(\"redis.port\")), 2000, System.getProperty(\"redis.password\"));\n }\n\n private JedisPool createJedisPoolForTestEnv(JedisPoolConfig jedisPoolConfig) {\n return new JedisPool(jedisPoolConfig, System.getProperty(\"redis.host\"), Integer.parseInt(System.getProperty(\"redis.port\")));\n }\n\n }"}}},{"rowIdx":853,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"bsd-2-clause"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"1f99df1e7fb5c0b94a87503d67f27afefbffc3ea"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"stapler/stapler,stapler/stapler,stapler/stapler,stapler/stapler,stapler/stapler"},"new_contents":{"kind":"string","value":"package org.kohsuke.stapler.lang;\n\nimport org.kohsuke.stapler.Function;\n\nimport java.net.URL;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\n\n/**\n * Abstraction of class-like object, agnostic to languages.\n *\n *

\n * To support other JVM languages that use their own specific types to represent a class\n * (such as JRuby and Jython), we now use this object instead of {@link Class}. This allows\n * us to reuse much of the logic of class traversal/resource lookup across different languages.\n * \n * This is a convenient tuple so that we can pass around a single argument instead of two.\n *\n * @param \n * Variable that represents the type of {@code Class} like object in this language.\n *\n * @author Kohsuke Kawaguchi\n */\npublic final class Klass {\n public final C clazz;\n public final KlassNavigator navigator;\n\n public Klass(C clazz, KlassNavigator navigator) {\n this.clazz = clazz;\n this.navigator = navigator;\n }\n\n public URL getResource(String resourceName) {\n return navigator.getResource(clazz,resourceName);\n }\n\n public Iterable> getAncestors() {\n return navigator.getAncestors(clazz);\n }\n \n public Klass getSuperClass() {\n return navigator.getSuperClass(clazz);\n }\n\n public Class toJavaClass() {\n return navigator.toJavaClass(clazz);\n }\n\n /**\n * @since 1.220\n */\n public List getDeclaredMethods() {\n return navigator.getDeclaredMethods(clazz);\n }\n\n public List getDeclaredFields() {\n try {\n return navigator.getDeclaredFields(clazz);\n } catch (AbstractMethodError err) {\n // A plugin uses obsolete version of Stapler-dependent library (e.g. JRuby), which does not offer the method (JENKINS-39414)\n // TODO: what to do with Logging? The error must be VERY visible, but it will totally pollute system logs\n return Collections.emptyList();\n }\n }\n\n /**\n * Gets all the public fields defined in this type, including super types.\n *\n * @see Class#getFields()\n */\n public List getFields() {\n Map fields = new LinkedHashMap();\n for (Klass k = this; k!=null; k=k.getSuperClass()) {\n for (FieldRef f : k.getDeclaredFields()) {\n String name = f.getName();\n if (!fields.containsKey(name) && f.isRoutable()) {\n fields.put(name,f);\n }\n }\n }\n\n return new ArrayList(fields.values());\n }\n\n public List getFunctions() {\n return navigator.getFunctions(clazz);\n }\n\n public boolean isArray() {\n return navigator.isArray(clazz);\n }\n\n public Object getArrayElement(Object o, int index) throws IndexOutOfBoundsException {\n return navigator.getArrayElement(o,index);\n }\n\n public boolean isMap() {\n return navigator.isMap(clazz);\n }\n\n public Object getMapElement(Object o, String key) {\n return navigator.getMapElement(o,key);\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 Klass that = (Klass) o;\n return clazz.equals(that.clazz) && navigator.equals(that.navigator);\n\n }\n\n @Override\n public int hashCode() {\n return 31 * clazz.hashCode() + navigator.hashCode();\n }\n\n @Override\n public String toString() {\n return clazz.toString();\n }\n\n /**\n * Creates {@link Klass} from a Java {@link Class}.\n */\n public static Klass java(Class c) {\n return c == null ? null : new Klass(c, KlassNavigator.JAVA);\n }\n}\n"},"new_file":{"kind":"string","value":"core/src/main/java/org/kohsuke/stapler/lang/Klass.java"},"old_contents":{"kind":"string","value":"package org.kohsuke.stapler.lang;\n\nimport org.kohsuke.stapler.Function;\n\nimport java.net.URL;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\n\n/**\n * Abstraction of class-like object, agnostic to languages.\n *\n *

\n * To support other JVM languages that use their own specific types to represent a class\n * (such as JRuby and Jython), we now use this object instead of {@link Class}. This allows\n * us to reuse much of the logic of class traversal/resource lookup across different languages.\n * \n * This is a convenient tuple so that we can pass around a single argument instead of two.\n *\n * @param \n * Variable that represents the type of {@code Class} like object in this language.\n *\n * @author Kohsuke Kawaguchi\n */\npublic final class Klass {\n public final C clazz;\n public final KlassNavigator navigator;\n\n public Klass(C clazz, KlassNavigator navigator) {\n this.clazz = clazz;\n this.navigator = navigator;\n }\n\n public URL getResource(String resourceName) {\n return navigator.getResource(clazz,resourceName);\n }\n\n public Iterable> getAncestors() {\n return navigator.getAncestors(clazz);\n }\n \n public Klass getSuperClass() {\n return navigator.getSuperClass(clazz);\n }\n\n public Class toJavaClass() {\n return navigator.toJavaClass(clazz);\n }\n\n /**\n * @since 1.220\n */\n public List getDeclaredMethods() {\n return navigator.getDeclaredMethods(clazz);\n }\n\n public List getDeclaredFields() {\n return navigator.getDeclaredFields(clazz);\n }\n\n /**\n * Gets all the public fields defined in this type, including super types.\n *\n * @see Class#getFields()\n */\n public List getFields() {\n Map fields = new LinkedHashMap();\n for (Klass k = this; k!=null; k=k.getSuperClass()) {\n for (FieldRef f : k.getDeclaredFields()) {\n String name = f.getName();\n if (!fields.containsKey(name) && f.isRoutable()) {\n fields.put(name,f);\n }\n }\n }\n\n return new ArrayList(fields.values());\n }\n\n public List getFunctions() {\n return navigator.getFunctions(clazz);\n }\n\n public boolean isArray() {\n return navigator.isArray(clazz);\n }\n\n public Object getArrayElement(Object o, int index) throws IndexOutOfBoundsException {\n return navigator.getArrayElement(o,index);\n }\n\n public boolean isMap() {\n return navigator.isMap(clazz);\n }\n\n public Object getMapElement(Object o, String key) {\n return navigator.getMapElement(o,key);\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 Klass that = (Klass) o;\n return clazz.equals(that.clazz) && navigator.equals(that.navigator);\n\n }\n\n @Override\n public int hashCode() {\n return 31 * clazz.hashCode() + navigator.hashCode();\n }\n\n @Override\n public String toString() {\n return clazz.toString();\n }\n\n /**\n * Creates {@link Klass} from a Java {@link Class}.\n */\n public static Klass java(Class c) {\n return c == null ? null : new Klass(c, KlassNavigator.JAVA);\n }\n}\n"},"message":{"kind":"string","value":"[JENKINS-39414] - Prevent compatibility breakage in Klass#getDeclaredFields() when a Jenkins plugin uses obsolete Stapler lib\n"},"old_file":{"kind":"string","value":"core/src/main/java/org/kohsuke/stapler/lang/Klass.java"},"subject":{"kind":"string","value":"[JENKINS-39414] - Prevent compatibility breakage in Klass#getDeclaredFields() when a Jenkins plugin uses obsolete Stapler lib"},"git_diff":{"kind":"string","value":"ore/src/main/java/org/kohsuke/stapler/lang/Klass.java\n \n import java.net.URL;\n import java.util.ArrayList;\nimport java.util.Collections;\n import java.util.LinkedHashMap;\n import java.util.List;\n import java.util.Map;\n }\n \n public List getDeclaredFields() {\n return navigator.getDeclaredFields(clazz);\n try {\n return navigator.getDeclaredFields(clazz);\n } catch (AbstractMethodError err) {\n // A plugin uses obsolete version of Stapler-dependent library (e.g. JRuby), which does not offer the method (JENKINS-39414)\n // TODO: what to do with Logging? The error must be VERY visible, but it will totally pollute system logs\n return Collections.emptyList();\n }\n }\n \n /**"}}},{"rowIdx":854,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"76cc898413295857db977af9e974b67f851dd6ef"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"buckett/sakai-gitflow,bzhouduke123/sakai,OpenCollabZA/sakai,surya-janani/sakai,lorenamgUMU/sakai,ouit0408/sakai,joserabal/sakai,zqian/sakai,hackbuteer59/sakai,tl-its-umich-edu/sakai,kingmook/sakai,joserabal/sakai,Fudan-University/sakai,rodriguezdevera/sakai,noondaysun/sakai,rodriguezdevera/sakai,puramshetty/sakai,kwedoff1/sakai,puramshetty/sakai,clhedrick/sakai,wfuedu/sakai,buckett/sakai-gitflow,duke-compsci290-spring2016/sakai,duke-compsci290-spring2016/sakai,zqian/sakai,kingmook/sakai,ktakacs/sakai,kwedoff1/sakai,rodriguezdevera/sakai,kingmook/sakai,ktakacs/sakai,rodriguezdevera/sakai,frasese/sakai,hackbuteer59/sakai,liubo404/sakai,tl-its-umich-edu/sakai,conder/sakai,frasese/sakai,liubo404/sakai,udayg/sakai,conder/sakai,colczr/sakai,conder/sakai,surya-janani/sakai,conder/sakai,zqian/sakai,kwedoff1/sakai,udayg/sakai,wfuedu/sakai,kwedoff1/sakai,frasese/sakai,bzhouduke123/sakai,surya-janani/sakai,OpenCollabZA/sakai,surya-janani/sakai,conder/sakai,whumph/sakai,Fudan-University/sakai,hackbuteer59/sakai,OpenCollabZA/sakai,colczr/sakai,willkara/sakai,whumph/sakai,wfuedu/sakai,udayg/sakai,buckett/sakai-gitflow,pushyamig/sakai,noondaysun/sakai,OpenCollabZA/sakai,liubo404/sakai,wfuedu/sakai,puramshetty/sakai,pushyamig/sakai,puramshetty/sakai,buckett/sakai-gitflow,joserabal/sakai,puramshetty/sakai,bkirschn/sakai,noondaysun/sakai,OpenCollabZA/sakai,whumph/sakai,bzhouduke123/sakai,introp-software/sakai,bkirschn/sakai,rodriguezdevera/sakai,joserabal/sakai,noondaysun/sakai,tl-its-umich-edu/sakai,frasese/sakai,buckett/sakai-gitflow,liubo404/sakai,frasese/sakai,bzhouduke123/sakai,udayg/sakai,ouit0408/sakai,lorenamgUMU/sakai,willkara/sakai,willkara/sakai,frasese/sakai,conder/sakai,pushyamig/sakai,liubo404/sakai,tl-its-umich-edu/sakai,puramshetty/sakai,clhedrick/sakai,puramshetty/sakai,ktakacs/sakai,rodriguezdevera/sakai,ouit0408/sakai,frasese/sakai,bzhouduke123/sakai,kwedoff1/sakai,duke-compsci290-spring2016/sakai,frasese/sakai,clhedrick/sakai,introp-software/sakai,introp-software/sakai,bkirschn/sakai,duke-compsci290-spring2016/sakai,introp-software/sakai,willkara/sakai,willkara/sakai,Fudan-University/sakai,bzhouduke123/sakai,liubo404/sakai,kwedoff1/sakai,Fudan-University/sakai,noondaysun/sakai,tl-its-umich-edu/sakai,OpenCollabZA/sakai,colczr/sakai,surya-janani/sakai,introp-software/sakai,OpenCollabZA/sakai,bkirschn/sakai,clhedrick/sakai,hackbuteer59/sakai,liubo404/sakai,clhedrick/sakai,introp-software/sakai,kingmook/sakai,hackbuteer59/sakai,hackbuteer59/sakai,joserabal/sakai,noondaysun/sakai,udayg/sakai,kingmook/sakai,clhedrick/sakai,colczr/sakai,OpenCollabZA/sakai,whumph/sakai,introp-software/sakai,colczr/sakai,kingmook/sakai,zqian/sakai,buckett/sakai-gitflow,lorenamgUMU/sakai,zqian/sakai,kwedoff1/sakai,udayg/sakai,bkirschn/sakai,duke-compsci290-spring2016/sakai,duke-compsci290-spring2016/sakai,hackbuteer59/sakai,pushyamig/sakai,pushyamig/sakai,surya-janani/sakai,wfuedu/sakai,buckett/sakai-gitflow,Fudan-University/sakai,ktakacs/sakai,kingmook/sakai,zqian/sakai,rodriguezdevera/sakai,lorenamgUMU/sakai,willkara/sakai,puramshetty/sakai,noondaysun/sakai,clhedrick/sakai,bkirschn/sakai,kwedoff1/sakai,udayg/sakai,bkirschn/sakai,lorenamgUMU/sakai,introp-software/sakai,ktakacs/sakai,colczr/sakai,colczr/sakai,zqian/sakai,ktakacs/sakai,joserabal/sakai,whumph/sakai,bkirschn/sakai,lorenamgUMU/sakai,whumph/sakai,lorenamgUMU/sakai,duke-compsci290-spring2016/sakai,tl-its-umich-edu/sakai,liubo404/sakai,ktakacs/sakai,conder/sakai,tl-its-umich-edu/sakai,hackbuteer59/sakai,surya-janani/sakai,pushyamig/sakai,wfuedu/sakai,Fudan-University/sakai,Fudan-University/sakai,udayg/sakai,ktakacs/sakai,ouit0408/sakai,buckett/sakai-gitflow,rodriguezdevera/sakai,Fudan-University/sakai,noondaysun/sakai,whumph/sakai,whumph/sakai,ouit0408/sakai,pushyamig/sakai,ouit0408/sakai,duke-compsci290-spring2016/sakai,wfuedu/sakai,surya-janani/sakai,bzhouduke123/sakai,kingmook/sakai,ouit0408/sakai,ouit0408/sakai,tl-its-umich-edu/sakai,joserabal/sakai,lorenamgUMU/sakai,wfuedu/sakai,willkara/sakai,zqian/sakai,bzhouduke123/sakai,joserabal/sakai,pushyamig/sakai,clhedrick/sakai,conder/sakai,willkara/sakai,colczr/sakai"},"new_contents":{"kind":"string","value":"/**********************************************************************************\r\n * $URL$\r\n * $Id$\r\n ***********************************************************************************\r\n *\r\n * Copyright (c) 2005 The Regents of the University of Michigan, Trustees of Indiana University,\r\n * Board of Trustees of the Leland Stanford, Jr., University, and The MIT Corporation\r\n * \r\n * Licensed under the Educational Community License Version 1.0 (the \"License\");\r\n * By obtaining, using and/or copying this Original Work, you agree that you have read,\r\n * understand, and will comply with the terms and conditions of the Educational Community License.\r\n * You may obtain a copy of the License at:\r\n * \r\n * http://cvs.sakaiproject.org/licenses/license_1_0.html\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\r\n * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE\r\n * AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\r\n * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING \r\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n *\r\n **********************************************************************************/\r\n\r\npackage org.sakaiproject.component.app.messageforums;\r\n\r\nimport org.apache.commons.logging.Log;\r\nimport org.apache.commons.logging.LogFactory;\r\nimport org.sakaiproject.api.app.messageforums.Area;\r\n\r\n\r\npublic class MessageForumsAreaManagerImpl {//implements MessageForumsAreaManager {\r\n \r\n private static final Log LOG = LogFactory.getLog(MessageForumsAreaManagerImpl.class); \r\n\r\n public boolean isPrivateAreaEnabled() {\r\n return false;\r\n }\r\n\r\n public Area getPrivateArea() {\r\n return null;\r\n }\r\n\r\n public Area getDiscussionForumArea() {\r\n return null;\r\n }\r\n\r\n}\r\n"},"new_file":{"kind":"string","value":"msgcntr/messageforums-component-shared/src/java/org/sakaiproject/component/app/messageforums/MessageForumsAreaManagerImpl.java"},"old_contents":{"kind":"string","value":"/**********************************************************************************\r\n * $URL$\r\n * $Id$\r\n ***********************************************************************************\r\n *\r\n * Copyright (c) 2005 The Regents of the University of Michigan, Trustees of Indiana University,\r\n * Board of Trustees of the Leland Stanford, Jr., University, and The MIT Corporation\r\n * \r\n * Licensed under the Educational Community License Version 1.0 (the \"License\");\r\n * By obtaining, using and/or copying this Original Work, you agree that you have read,\r\n * understand, and will comply with the terms and conditions of the Educational Community License.\r\n * You may obtain a copy of the License at:\r\n * \r\n * http://cvs.sakaiproject.org/licenses/license_1_0.html\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\r\n * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE\r\n * AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\r\n * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING \r\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n *\r\n **********************************************************************************/\r\n\r\npackage org.sakaiproject.component.app.messageforums;\r\n\r\nimport org.apache.commons.logging.Log;\r\nimport org.apache.commons.logging.LogFactory;\r\nimport org.sakaiproject.api.app.messageforums.Area;\r\nimport org.sakaiproject.api.app.messageforums.MessageForumsAreaManager;\r\n\r\npublic class MessageForumsAreaManagerImpl implements MessageForumsAreaManager {\r\n \r\n private static final Log LOG = LogFactory.getLog(MessageForumsAreaManagerImpl.class); \r\n\r\n public boolean isPrivateAreaEnabled() {\r\n return false;\r\n }\r\n\r\n public Area getPrivateArea() {\r\n return null;\r\n }\r\n\r\n public Area getDiscussionForumArea() {\r\n return null;\r\n }\r\n\r\n}\r\n"},"message":{"kind":"string","value":"New managers \nclean up\nremove type etc\n\ngit-svn-id: c7b2716e7381eb8d90b7fc9f797026a6a3c5b5ba@3459 66ffb92e-73f9-0310-93c1-f5514f145a0a\n"},"old_file":{"kind":"string","value":"msgcntr/messageforums-component-shared/src/java/org/sakaiproject/component/app/messageforums/MessageForumsAreaManagerImpl.java"},"subject":{"kind":"string","value":"New managers clean up remove type etc"},"git_diff":{"kind":"string","value":"sgcntr/messageforums-component-shared/src/java/org/sakaiproject/component/app/messageforums/MessageForumsAreaManagerImpl.java\n import org.apache.commons.logging.Log;\n import org.apache.commons.logging.LogFactory;\n import org.sakaiproject.api.app.messageforums.Area;\nimport org.sakaiproject.api.app.messageforums.MessageForumsAreaManager;\n \npublic class MessageForumsAreaManagerImpl implements MessageForumsAreaManager {\n\npublic class MessageForumsAreaManagerImpl {//implements MessageForumsAreaManager {\n \n private static final Log LOG = LogFactory.getLog(MessageForumsAreaManagerImpl.class); \n "}}},{"rowIdx":855,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"8fff1c2a111edd2f3caabbeb852ce29afc222cd0"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"project-recoin/PybossaTwitterController,project-recoin/PybossaTwitterController"},"new_contents":{"kind":"string","value":"package sociam.pybossa.twitter;\n\nimport java.util.List;\n\nimport sociam.pybossa.util.TwitterAccount;\nimport twitter4j.Paging;\nimport twitter4j.Status;\nimport twitter4j.Twitter;\nimport twitter4j.TwitterException;\n\npublic class DeleteTweets {\n\n\tpublic static void main(String[] args) throws InterruptedException {\n\n\t\tBoolean res = removeTweets();\n\t\tif (res == false) {\n\t\t\tremoveTweets();\n\t\t} else if (res == true) {\n\t\t\tSystem.out.println(\"All tweets are deleted\");\n\t\t} else {\n\t\t\tSystem.err.println(\"Error, exiting the script!!\");\n\t\t}\n\n\t}\n\n\tpublic static Boolean removeTweets() {\n\t\tTwitter twitter = TwitterAccount.setTwitterAccount(2);\n\t\ttry {\n\t\t\tPaging p = new Paging();\n\t\t\tp.setCount(200);\n\t\t\tList statuses = twitter.getUserTimeline(p);\n\n\t\t\twhile (statuses != null) {\n\t\t\t\tfor (Status status : statuses) {\n\t\t\t\t\tlong id = status.getId();\n\t\t\t\t\ttwitter.destroyStatus(id);\n\t\t\t\t\tSystem.out.println(\"deleted\");\n\t\t\t\t\tThread.sleep(5000);\n\t\t\t\t}\n\t\t\t\tSystem.out.println(\"Waiting 15 minutes before getting 200 responses\");\n\t\t\t\tstatuses = twitter.getHomeTimeline();\n\t\t\t\tThread.sleep(900000);\n\t\t\t}\n\n\t\t\treturn true;\n\t\t} catch (TwitterException e) {\n\t\t\te.printStackTrace();\n\t\t\tif (e.exceededRateLimitation()) {\n\t\t\t\ttry {\n\t\t\t\t\tSystem.err.println(\"Twitter rate limit is exceeded!\");\n\t\t\t\t\tint waitfor = e.getRateLimitStatus().getSecondsUntilReset();\n\t\t\t\t\tSystem.err.println(\"Waiting for \" + (waitfor + 100) + \" seconds\");\n\t\t\t\t\tThread.sleep((waitfor * 1000) + 100000);\n\t\t\t\t\tremoveTweets();\n\t\t\t\t} catch (InterruptedException e2) {\n\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\te2.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn null;\n\t\t} catch (InterruptedException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t\treturn null;\n\t\t}\n\t}\n}\n"},"new_file":{"kind":"string","value":"src/main/java/sociam/pybossa/twitter/DeleteTweets.java"},"old_contents":{"kind":"string","value":"package sociam.pybossa.twitter;\n\nimport java.util.List;\n\nimport sociam.pybossa.util.TwitterAccount;\nimport twitter4j.Paging;\nimport twitter4j.Status;\nimport twitter4j.Twitter;\nimport twitter4j.TwitterException;\n\npublic class DeleteTweets {\n\n\tpublic static void main(String[] args) throws InterruptedException {\n\n\t\tBoolean res = removeTweets();\n\t\tif (res == false) {\n\t\t\tremoveTweets();\n\t\t} else if (res == true) {\n\t\t\tSystem.out.println(\"All tweets are deleted\");\n\t\t} else {\n\t\t\tSystem.err.println(\"Error, exiting the script!!\");\n\t\t}\n\n\t}\n\n\tpublic static Boolean removeTweets() {\n\t\tTwitter twitter = TwitterAccount.setTwitterAccount(2);\n\t\ttry {\n\t\t\tPaging p = new Paging();\n\t\t\tp.setCount(200);\n\t\t\tList statuses = twitter.getHomeTimeline(p);\n\n\t\t\twhile (statuses != null) {\n\t\t\t\tfor (Status status : statuses) {\n\t\t\t\t\tlong id = status.getId();\n\t\t\t\t\ttwitter.destroyStatus(id);\n\t\t\t\t\tSystem.out.println(\"deleted\");\n\t\t\t\t\tThread.sleep(5000);\n\t\t\t\t}\n\t\t\t\tSystem.out.println(\"Waiting 15 minutes before getting 200 responses\");\n\t\t\t\tstatuses = twitter.getHomeTimeline();\n\t\t\t\tThread.sleep(900000);\n\t\t\t}\n\n\t\t\treturn true;\n\t\t} catch (TwitterException e) {\n\t\t\te.printStackTrace();\n\t\t\tif (e.exceededRateLimitation()) {\n\t\t\t\ttry {\n\t\t\t\t\tSystem.err.println(\"Twitter rate limit is exceeded!\");\n\t\t\t\t\tint waitfor = e.getRateLimitStatus().getSecondsUntilReset();\n\t\t\t\t\tSystem.err.println(\"Waiting for \" + (waitfor + 100) + \" seconds\");\n\t\t\t\t\tThread.sleep((waitfor * 1000) + 100000);\n\t\t\t\t\tremoveTweets();\n\t\t\t\t} catch (InterruptedException e2) {\n\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\te2.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn null;\n\t\t} catch (InterruptedException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t\treturn null;\n\t\t}\n\t}\n}\n"},"message":{"kind":"string","value":"no message\n"},"old_file":{"kind":"string","value":"src/main/java/sociam/pybossa/twitter/DeleteTweets.java"},"subject":{"kind":"string","value":"no message"},"git_diff":{"kind":"string","value":"rc/main/java/sociam/pybossa/twitter/DeleteTweets.java\n \t\ttry {\n \t\t\tPaging p = new Paging();\n \t\t\tp.setCount(200);\n\t\t\tList statuses = twitter.getHomeTimeline(p);\n\t\t\tList statuses = twitter.getUserTimeline(p);\n \n \t\t\twhile (statuses != null) {\n \t\t\t\tfor (Status status : statuses) {"}}},{"rowIdx":856,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"b97ae495e4c8c6ac50ff686c050c7f9cd3abaf05"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"gunnarmorling/aerogear-unifiedpush-server,baiwyc119/aerogear-unifiedpush-server,lfryc/aerogear-unifiedpush-server,diogoalbuquerque/aerogear-unifiedpush-server,danielpassos/aerogear-unifiedpush-server,matzew/aerogear-unifiedpush-server,sinarz/aerogear-unifiedpush-server,qmx/aerogear-unifiedpush-server,fheng/aerogear-unifiedpush-server,aerogear/aerogear-unifiedpush-server,lholmquist/aerogear-unified-push-server,baiwyc119/aerogear-unifiedpush-server,lholmquist/aerogear-unified-push-server,yvnicolas/aerogear-unifiedpush-server,yvnicolas/aerogear-unifiedpush-server,andresgalante/aerogear-unifiedpush-server,matzew/aerogear-unifiedpush-server,matzew/aerogear-unifiedpush-server,IvanGurtler/aerogear-unifiedpush-server,andresgalante/aerogear-unifiedpush-server,danielpassos/aerogear-unifiedpush-server,abstractj/aerogear-unifiedpush-server,edewit/aerogear-unifiedpush-server,yvnicolas/aerogear-unifiedpush-server,thradec/aerogear-unifiedpush-server,fheng/aerogear-unifiedpush-server,lfryc/aerogear-unifiedpush-server,lholmquist/aerogear-unified-push-server,andresgalante/aerogear-unifiedpush-server,julioa/aerogear-unifiedpush-server,baiwyc119/aerogear-unifiedpush-server,abstractj/aerogear-unifiedpush-server,baiwyc119/aerogear-unifiedpush-server,lfryc/aerogear-unifiedpush-server,diogoalbuquerque/aerogear-unifiedpush-server,aerobase/unifiedpush-server,aerobase/unifiedpush-server,lfryc/aerogear-unifiedpush-server,abstractj/aerogear-unifiedpush-server,fheng/aerogear-unifiedpush-server,sinarz/aerogear-unifiedpush-server,andresgalante/aerogear-unifiedpush-server,abstractj/aerogear-unifiedpush-server,sinarz/aerogear-unifiedpush-server,C-B4/unifiedpush-server,qmx/aerogear-unifiedpush-server,aerobase/unifiedpush-server,julioa/aerogear-unifiedpush-server,gunnarmorling/aerogear-unifiedpush-server,lholmquist/aerogear-unified-push-server,matzew/aerogear-unifiedpush-server,edewit/aerogear-unifiedpush-server,secondsun/aerogear-unifiedpush-server,secondsun/aerogear-unifiedpush-server,lholmquist/aerogear-unified-push-server,abstractj/aerogear-unifiedpush-server,julioa/aerogear-unifiedpush-server,C-B4/unifiedpush-server,idelpivnitskiy/aerogear-unifiedpush-server,secondsun/aerogear-unifiedpush-server,yvnicolas/aerogear-unifiedpush-server,edewit/aerogear-unifiedpush-server,aerogear/aerogear-unifiedpush-server,julioa/aerogear-unifiedpush-server,andresgalante/aerogear-unifiedpush-server,idelpivnitskiy/aerogear-unifiedpush-server,thradec/aerogear-unifiedpush-server,fheng/aerogear-unifiedpush-server,IvanGurtler/aerogear-unifiedpush-server,matzew/aerogear-unifiedpush-server,sinarz/aerogear-unifiedpush-server,thradec/aerogear-unifiedpush-server,thradec/aerogear-unifiedpush-server,idelpivnitskiy/aerogear-unifiedpush-server,abstractj/aerogear-unifiedpush-server,lfryc/aerogear-unifiedpush-server,lfryc/aerogear-unifiedpush-server,edewit/aerogear-unifiedpush-server,andresgalante/aerogear-unifiedpush-server,danielpassos/aerogear-unifiedpush-server,aerogear/aerogear-unifiedpush-server,julioa/aerogear-unifiedpush-server,IvanGurtler/aerogear-unifiedpush-server,sinarz/aerogear-unifiedpush-server,matzew/aerogear-unifiedpush-server,julioa/aerogear-unifiedpush-server,edewit/aerogear-unifiedpush-server,danielpassos/aerogear-unifiedpush-server,sinarz/aerogear-unifiedpush-server,C-B4/unifiedpush-server,edewit/aerogear-unifiedpush-server,danielpassos/aerogear-unifiedpush-server,idelpivnitskiy/aerogear-unifiedpush-server,gunnarmorling/aerogear-unifiedpush-server,danielpassos/aerogear-unifiedpush-server,yvnicolas/aerogear-unifiedpush-server,baiwyc119/aerogear-unifiedpush-server,lholmquist/aerogear-unified-push-server,C-B4/unifiedpush-server,fheng/aerogear-unifiedpush-server,thradec/aerogear-unifiedpush-server,yvnicolas/aerogear-unifiedpush-server,thradec/aerogear-unifiedpush-server,idelpivnitskiy/aerogear-unifiedpush-server,idelpivnitskiy/aerogear-unifiedpush-server,baiwyc119/aerogear-unifiedpush-server,fheng/aerogear-unifiedpush-server,diogoalbuquerque/aerogear-unifiedpush-server"},"new_contents":{"kind":"string","value":"/**\n * JBoss, Home of Professional Open Source\n * Copyright Red Hat, Inc., and individual contributors.\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 * \thttp://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jboss.aerogear.unifiedpush.rest.security;\n\nimport org.jboss.aerogear.unifiedpush.users.Developer;\nimport org.jboss.aerogear.security.auth.AuthenticationManager;\nimport org.jboss.aerogear.security.authz.IdentityManagement;\nimport org.jboss.aerogear.security.exception.AeroGearSecurityException;\nimport org.jboss.aerogear.security.picketlink.auth.CredentialMatcher;\nimport org.picketlink.idm.model.basic.Agent;\nimport org.picketlink.idm.model.basic.User;\n\nimport javax.ejb.Stateless;\nimport javax.inject.Inject;\nimport javax.ws.rs.Consumes;\nimport javax.ws.rs.POST;\nimport javax.ws.rs.PUT;\nimport javax.ws.rs.Path;\nimport javax.ws.rs.Produces;\nimport javax.ws.rs.core.MediaType;\nimport javax.ws.rs.core.Response;\nimport javax.ws.rs.core.Response.Status;\n\n@Stateless\n@Path(\"/auth\")\npublic class AuthenticationEndpoint {\n\n @Inject\n private AuthenticationManager authenticationManager;\n\n @Inject\n private CredentialMatcher credential;\n @Inject\n private IdentityManagement configuration;\n\n @POST\n @Path(\"/login\")\n @Consumes(MediaType.APPLICATION_JSON)\n @Produces(MediaType.APPLICATION_JSON)\n public Response login(final Developer developer) {\n\n authenticationManager.login(developer, developer.getPassword());\n\n return Response.ok().build();\n }\n\n @POST\n @Path(\"/logout\")\n public Response logout() {\n try {\n authenticationManager.logout();\n } catch (AeroGearSecurityException agse) {\n return Response.status(Status.UNAUTHORIZED).build();\n }\n return Response.ok().build();\n }\n\n @PUT\n @Path(\"/update\")\n public Response updateUserPasswordAndRole(final Developer developer) {\n\n User simpleUser = (User) configuration.findByUsername(developer.getLoginName());\n configuration.reset(simpleUser, developer.getPassword(), developer.getNewPassword());\n\n return Response.ok().build();\n }\n}\n"},"new_file":{"kind":"string","value":"src/main/java/org/jboss/aerogear/unifiedpush/rest/security/AuthenticationEndpoint.java"},"old_contents":{"kind":"string","value":"/**\n * JBoss, Home of Professional Open Source\n * Copyright Red Hat, Inc., and individual contributors.\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 * \thttp://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jboss.aerogear.unifiedpush.rest.security;\n\nimport org.jboss.aerogear.unifiedpush.users.Developer;\nimport org.jboss.aerogear.security.auth.AuthenticationManager;\nimport org.jboss.aerogear.security.authz.IdentityManagement;\nimport org.jboss.aerogear.security.exception.AeroGearSecurityException;\nimport org.jboss.aerogear.security.picketlink.auth.CredentialMatcher;\nimport org.picketlink.idm.model.basic.User;\n\nimport javax.ejb.Stateless;\nimport javax.inject.Inject;\nimport javax.ws.rs.Consumes;\nimport javax.ws.rs.POST;\nimport javax.ws.rs.PUT;\nimport javax.ws.rs.Path;\nimport javax.ws.rs.Produces;\nimport javax.ws.rs.core.MediaType;\nimport javax.ws.rs.core.Response;\nimport javax.ws.rs.core.Response.Status;\n\n@Stateless\n@Path(\"/auth\")\npublic class AuthenticationEndpoint {\n\n @Inject\n private AuthenticationManager authenticationManager;\n @Inject\n private CredentialMatcher credential;\n @Inject\n private IdentityManagement configuration;\n\n @POST\n @Path(\"/login\")\n @Consumes(MediaType.APPLICATION_JSON)\n @Produces(MediaType.APPLICATION_JSON)\n public Response login(final Developer developer) {\n\n authenticationManager.login(developer, developer.getPassword());\n\n return Response.ok().build();\n }\n\n @POST\n @Path(\"/logout\")\n public Response logout() {\n try {\n authenticationManager.logout();\n } catch (AeroGearSecurityException agse) {\n return Response.status(Status.UNAUTHORIZED).build();\n }\n return Response.ok().build();\n }\n\n @PUT\n @Path(\"/update\")\n public Response updateUserPasswordAndRole(final Developer developer) {\n\n User simpleUser = (User) configuration.findByUsername(developer.getLoginName());\n configuration.reset(simpleUser, developer.getPassword(), developer.getNewPassword());\n\n return Response.ok().build();\n }\n}\n"},"message":{"kind":"string","value":"Using Agent as parameterized type for the AuthenticationManager injection point\n"},"old_file":{"kind":"string","value":"src/main/java/org/jboss/aerogear/unifiedpush/rest/security/AuthenticationEndpoint.java"},"subject":{"kind":"string","value":"Using Agent as parameterized type for the AuthenticationManager injection point"},"git_diff":{"kind":"string","value":"rc/main/java/org/jboss/aerogear/unifiedpush/rest/security/AuthenticationEndpoint.java\n import org.jboss.aerogear.security.authz.IdentityManagement;\n import org.jboss.aerogear.security.exception.AeroGearSecurityException;\n import org.jboss.aerogear.security.picketlink.auth.CredentialMatcher;\nimport org.picketlink.idm.model.basic.Agent;\n import org.picketlink.idm.model.basic.User;\n \n import javax.ejb.Stateless;\n public class AuthenticationEndpoint {\n \n @Inject\n private AuthenticationManager authenticationManager;\n private AuthenticationManager authenticationManager;\n\n @Inject\n private CredentialMatcher credential;\n @Inject"}}},{"rowIdx":857,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"bf5963598702bad563b346005012b2f4788f9be4"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"innovateme/ICampGeoFence"},"new_contents":{"kind":"string","value":"package com.example.icampgeofence;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport android.app.Activity;\nimport android.app.PendingIntent;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.IntentSender;\nimport android.location.Location;\nimport android.location.LocationManager;\nimport android.location.LocationProvider;\nimport android.os.Bundle;\nimport android.util.Log;\nimport android.widget.Toast;\n\nimport com.google.android.gms.common.ConnectionResult;\nimport com.google.android.gms.common.GooglePlayServicesClient;\nimport com.google.android.gms.common.GooglePlayServicesUtil;\nimport com.google.android.gms.location.Geofence;\nimport com.google.android.gms.location.LocationClient;\nimport com.google.android.gms.location.LocationClient.OnAddGeofencesResultListener;\nimport com.google.android.gms.location.LocationClient.OnRemoveGeofencesResultListener;\nimport com.google.android.gms.location.LocationStatusCodes;\n\npublic class LocationMgr implements\n\tGooglePlayServicesClient.ConnectionCallbacks,\n\tGooglePlayServicesClient.OnConnectionFailedListener {\n\n\tpublic static final String TRANSITION_INTENT_ACTION = \"geofence_transition\";\n\n\t/*\n\t * Define a request code to send to Google Play services\n\t * This code is returned in Activity.onActivityResult\n\t */\n\tprivate final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;\n\tprivate final static int REQUEST_CODE_RECOVER_PLAY_SERVICES = 1001;\n\n\tprivate final Activity parentActivity;\n\tprivate LocationClient locationClient = null;\n\n // Stores the PendingIntent used to request geofence monitoring\n private PendingIntent geofenceRequestIntent;\n\n // Flag that indicates if a request is underway.\n private boolean inProgress = false;\n\n public interface OnDeleteFenceListener {\n \tvoid onDeleteFence(String id);\n }\n\t\n public LocationMgr(Activity parent) {\n\t\tparentActivity = parent;\n\n\t\t/*\n\t\t * Create a new location client, using the enclosing class to\n\t\t * handle callbacks.\n\t\t */\n\t\tlocationClient = new LocationClient(parentActivity, this, this);\n\t}\n\n\tpublic LocationClient getClient() {\n\t\treturn locationClient;\n\t}\n\n\tprotected void connect() {\n\t\t// Connect the client.\n\t\ttry {\n\t\t\tlocationClient.connect();\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\tLog.e(\"LocationMgr could not connect.\", e.getMessage(), e);\n\t\t}\n\t}\n\n\tprotected void disconnect() {\n\t\t// Disconnecting the client invalidates it.\n\t\tlocationClient.disconnect();\n\t}\n\n\tpublic void setMockLocation(double latitude, double longitude, float accuracy) {\n\t LocationManager lm = (LocationManager) parentActivity.getSystemService(Context.LOCATION_SERVICE);\n\t lm.addTestProvider(LocationManager.GPS_PROVIDER,\n\t \"requiresNetwork\" == \"\",\n\t \"requiresSatellite\" == \"\",\n\t \"requiresCell\" == \"\",\n\t \"hasMonetaryCost\" == \"\",\n\t \"supportsAltitude\" == \"\",\n\t \"supportsSpeed\" == \"\",\n\t \"supportsBearing\" == \"\",\n\t android.location.Criteria.NO_REQUIREMENT,\n\t android.location.Criteria.ACCURACY_FINE);\n\n\t Location newLocation = new Location(LocationManager.GPS_PROVIDER);\n\n\t newLocation.setLatitude(latitude);\n\t newLocation.setLongitude(longitude);\n\t newLocation.setAccuracy(accuracy);\n\n\t lm.setTestProviderEnabled(LocationManager.GPS_PROVIDER, true);\n\n\t lm.setTestProviderStatus(LocationManager.GPS_PROVIDER,\n\t LocationProvider.AVAILABLE,\n\t null,System.currentTimeMillis());\n\n\t lm.setTestProviderLocation(LocationManager.GPS_PROVIDER, newLocation);\n\t}\n\n\n\t/*\n\t * Called by Location Services when the request to connect the\n\t * client finishes successfully. At this point, you can\n\t * request the current location or start periodic updates\n\t */\n\t@Override\n\tpublic void onConnected(Bundle dataBundle) {\n\t\t// Display the connection status\n\t\tToast.makeText(parentActivity, \"Connected\", Toast.LENGTH_SHORT).show();\n\n\t}\n\n\t/*\n\t * Called by Location Services if the connection to the\n\t * location client drops because of an error.\n\t */\n\t@Override\n\tpublic void onDisconnected() {\n\t\t// Display the connection status\n\t\tToast.makeText(parentActivity, \"Disconnected. Please re-connect.\", Toast.LENGTH_SHORT).show();\n\t}\n\n\t/*\n\t * Called by Location Services if the attempt to\n\t * Location Services fails.\n\t */\n\t@Override\n\tpublic void onConnectionFailed(ConnectionResult connectionResult) {\n\t\t/*\n\t\t * Google Play services can resolve some errors it detects.\n\t\t * If the error has a resolution, try sending an Intent to\n\t\t * start a Google Play services activity that can resolve\n\t\t * error.\n\t\t */\n\t\tif (connectionResult.hasResolution()) {\n\t\t\ttry {\n\t\t\t\t// Start an Activity that tries to resolve the error\n\t\t\t\tconnectionResult.startResolutionForResult(\n\t\t\t\t\t\tparentActivity,\n\t\t\t\t\t\tCONNECTION_FAILURE_RESOLUTION_REQUEST);\n\t\t\t\t/*\n\t\t\t\t * Thrown if Google Play services canceled the original\n\t\t\t\t * PendingIntent\n\t\t\t\t */\n\t\t\t}\n\t\t\tcatch (IntentSender.SendIntentException e) {\n\t\t\t\t// Log the error\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t/*\n\t\t\t * If no resolution is available, display a dialog to the\n\t\t\t * user with the error.\n\t\t\t */\n\t\t\tshowErrorDialog(connectionResult.getErrorCode());\n\t\t}\n\t} \n\n\tvoid showErrorDialog(int code) {\n\t\tGooglePlayServicesUtil.getErrorDialog(code, parentActivity, REQUEST_CODE_RECOVER_PLAY_SERVICES).show();\n\t}\n\n /*\n * Create a PendingIntent that triggers an IntentService in your\n * app when a geofence transition occurs.\n */\n private PendingIntent getTransitionPendingIntent() {\n // Create an explicit Intent\n Intent intent = new Intent(parentActivity, ReceiveTransitionsIntentService.class);\n intent.setAction(TRANSITION_INTENT_ACTION);\n /*\n * Return the PendingIntent\n */\n return PendingIntent.getService(\n parentActivity,\n 0,\n intent,\n PendingIntent.FLAG_UPDATE_CURRENT);\n }\n \n public void addGeofences(final List fenceList, final OnAddGeofencesResultListener listener) {\n \tList gfList = new ArrayList();\n \t// create a Geofence from each Fence\n \tfor (Fence f : fenceList) {\n \t\tgfList.add(f.asGeofence());\n \t}\n\t\t// get pending intent for geofence transitions\n\t\tgeofenceRequestIntent = getTransitionPendingIntent();\n\t\t// Send a request to add the current geofences\n locationClient.addGeofences(gfList, geofenceRequestIntent, new OnAddGeofencesResultListener() {\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void onAddGeofencesResult(int statusCode, String[] geofenceRequestIds) {\n\t\t\t\t// if successful, persist the new Fence\n\t\t if (LocationStatusCodes.SUCCESS == statusCode) {\n\t\t \t\tFenceMgr.getDefault().add(fenceList);\n\t\t \t\tlistener.onAddGeofencesResult(statusCode, geofenceRequestIds);\n\t\t \t\tToast.makeText(parentActivity, \"Added \" + fenceList.size() + \" new geofences.\", Toast.LENGTH_SHORT).show();\n\t\t }\n\t\t else {\n\t\t\t // If adding the geofences failed\n\t\t /*\n\t\t * Report errors here.\n\t\t * You can log the error using Log.e() or update\n\t\t * the UI.\n\t\t */\n\t\t }\n\t\t // Turn off the in progress flag\n\t\t inProgress = false;\n\t\t\t}\n\t\t});\n }\n \n \n public void removeAllGeofences(final OnRemoveGeofencesResultListener listener) {\n \tif (!FenceMgr.getDefault().getFences().isEmpty()) {\n \t\tremoveGeofences(FenceMgr.getDefault().getFences(), listener);\n \t}\n }\n\n \n public void removeGeofences(final List fenceList, final OnRemoveGeofencesResultListener listener) {\n \tList gfList = new ArrayList();\n \tfor (Fence f : fenceList) {\n \t\tgfList.add(f.getId());\n \t}\n locationClient.removeGeofences(gfList, new OnRemoveGeofencesResultListener() {\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void onRemoveGeofencesByRequestIdsResult(int statusCode, String[] geofenceRequestIds) {\n\t\t\t\t// if successful, persist the change\n\t\t if (LocationStatusCodes.SUCCESS == statusCode) {\n\t\t \t\tFenceMgr.getDefault().delete(fenceList);\n\t\t \t\tlistener.onRemoveGeofencesByRequestIdsResult(statusCode, geofenceRequestIds);\n\t\t \t\tToast.makeText(parentActivity, \"Removed \" + geofenceRequestIds.length + \" geofences.\", Toast.LENGTH_SHORT).show();\n\t\t }\n\t\t else {\n\t\t\t // If adding the geofences failed\n\t\t /*\n\t\t * Report errors here.\n\t\t * You can log the error using Log.e() or update\n\t\t * the UI.\n\t\t */\n\t\t }\n\t\t // Turn off the in progress flag\n\t\t inProgress = false;\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void onRemoveGeofencesByPendingIntentResult(int arg0, PendingIntent arg1) {\n\t\t\t\t// TODO Auto-generated method stub\n\t\t\t}\n\t\t});\n }\n\n public void addGeofence(final Fence fence) {\n\t\t// get pending intent for geofence transitions\n\t\tgeofenceRequestIntent = getTransitionPendingIntent();\n // create new Geofence from Fence and add to play services\n\t\tGeofence gf = fence.asGeofence();\n\t\tList gfList = new ArrayList();\n\t\tgfList.add(gf);\n\t\t// Send a request to add the current geofences\n locationClient.addGeofences(gfList, geofenceRequestIntent, new OnAddGeofencesResultListener() {\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void onAddGeofencesResult(int statusCode, String[] geofenceRequestIds) {\n\t\t\t\t// if successful, persist the new Fence\n\t\t if (LocationStatusCodes.SUCCESS == statusCode) {\n\t\t \t\tFenceMgr.getDefault().add(fence);\n\t\t \t\tToast.makeText(parentActivity, \"Added new geofence named \" + fence.getName(), Toast.LENGTH_SHORT).show();\n\t\t }\n\t\t else if (LocationStatusCodes.GEOFENCE_NOT_AVAILABLE == statusCode) {\n\t\t\t // If adding the geofences failed\n\t\t \tToast.makeText(parentActivity, \"Error: Location Access turned off in Settings\", Toast.LENGTH_SHORT).show();\n\t\t }\n\t\t else if (LocationStatusCodes.GEOFENCE_TOO_MANY_GEOFENCES == statusCode) {\n\t\t\t // If adding the geofences failed\n\t\t \tToast.makeText(parentActivity, \"Error: Geofence limit exceeded\" + fence.getName() + \", Code:\" + statusCode, Toast.LENGTH_SHORT).show();\t\t \t\n\t\t }\n\t\t else {\n\t\t\t // If adding the geofences failed\n\t\t \tToast.makeText(parentActivity, \"Error: Geofence not added\", Toast.LENGTH_SHORT).show();\n\t\t }\n\t\t // Turn off the in progress flag\n\t\t inProgress = false;\n\t\t\t}\n\t\t});\n\t}\n \n public void removeGeofence(final Fence fence, final OnDeleteFenceListener listener) {\n\t\tList gfList = new ArrayList();\n\t\tgfList.add(fence.getId());\n locationClient.removeGeofences(gfList, new OnRemoveGeofencesResultListener() {\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void onRemoveGeofencesByRequestIdsResult(int statusCode, String[] geofenceRequestIds) {\n\t\t\t\t// if successful, persist the change\n\t\t if (LocationStatusCodes.SUCCESS == statusCode) {\n\t\t \t\tFenceMgr.getDefault().delete(fence);\n\t\t \t\tlistener.onDeleteFence(fence.getId());\n\t\t \t\tToast.makeText(parentActivity, \"Removed geofence named \" + fence.getName(), Toast.LENGTH_SHORT).show();\n\t\t }\n\t\t else if (LocationStatusCodes.GEOFENCE_NOT_AVAILABLE == statusCode) {\n\t\t\t // If adding the geofences failed\n\t\t \tToast.makeText(parentActivity, \"Error: Location Access turned off in Settings\", Toast.LENGTH_SHORT).show();\n\t\t }\n\t\t else {\n\t\t\t // If adding the geofences failed\n\t\t \tToast.makeText(parentActivity, \"Error: Geofence not removed\", Toast.LENGTH_SHORT).show();\n\t\t }\n\t\t // Turn off the in progress flag\n\t\t inProgress = false;\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void onRemoveGeofencesByPendingIntentResult(int arg0, PendingIntent arg1) {\n\t\t\t\t// TODO Auto-generated method stub\n\t\t\t}\n\t\t});\n }\n}\n"},"new_file":{"kind":"string","value":"src/com/example/icampgeofence/LocationMgr.java"},"old_contents":{"kind":"string","value":"package com.example.icampgeofence;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport android.app.Activity;\nimport android.app.PendingIntent;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.IntentSender;\nimport android.location.Location;\nimport android.location.LocationManager;\nimport android.location.LocationProvider;\nimport android.os.Bundle;\nimport android.util.Log;\nimport android.widget.Toast;\n\nimport com.google.android.gms.common.ConnectionResult;\nimport com.google.android.gms.common.GooglePlayServicesClient;\nimport com.google.android.gms.common.GooglePlayServicesUtil;\nimport com.google.android.gms.location.Geofence;\nimport com.google.android.gms.location.LocationClient;\nimport com.google.android.gms.location.LocationClient.OnAddGeofencesResultListener;\nimport com.google.android.gms.location.LocationClient.OnRemoveGeofencesResultListener;\nimport com.google.android.gms.location.LocationStatusCodes;\n\npublic class LocationMgr implements\n\tGooglePlayServicesClient.ConnectionCallbacks,\n\tGooglePlayServicesClient.OnConnectionFailedListener {\n\n\tpublic static final String TRANSITION_INTENT_ACTION = \"geofence_transition\";\n\n\t/*\n\t * Define a request code to send to Google Play services\n\t * This code is returned in Activity.onActivityResult\n\t */\n\tprivate final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;\n\tprivate final static int REQUEST_CODE_RECOVER_PLAY_SERVICES = 1001;\n\n\tprivate final Activity parentActivity;\n\tprivate LocationClient locationClient = null;\n\n // Stores the PendingIntent used to request geofence monitoring\n private PendingIntent geofenceRequestIntent;\n\n // Flag that indicates if a request is underway.\n private boolean inProgress = false;\n\n public interface OnDeleteFenceListener {\n \tvoid onDeleteFence(String id);\n }\n\t\n public LocationMgr(Activity parent) {\n\t\tparentActivity = parent;\n\n\t\t/*\n\t\t * Create a new location client, using the enclosing class to\n\t\t * handle callbacks.\n\t\t */\n\t\tlocationClient = new LocationClient(parentActivity, this, this);\n\t}\n\n\tpublic LocationClient getClient() {\n\t\treturn locationClient;\n\t}\n\n\tprotected void connect() {\n\t\t// Connect the client.\n\t\ttry {\n\t\t\tlocationClient.connect();\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\tLog.e(\"LocationMgr could not connect.\", e.getMessage(), e);\n\t\t}\n\t}\n\n\tprotected void disconnect() {\n\t\t// Disconnecting the client invalidates it.\n\t\tlocationClient.disconnect();\n\t}\n\n\tpublic void setMockLocation(double latitude, double longitude, float accuracy) {\n\t LocationManager lm = (LocationManager) parentActivity.getSystemService(Context.LOCATION_SERVICE);\n\t lm.addTestProvider(LocationManager.GPS_PROVIDER,\n\t \"requiresNetwork\" == \"\",\n\t \"requiresSatellite\" == \"\",\n\t \"requiresCell\" == \"\",\n\t \"hasMonetaryCost\" == \"\",\n\t \"supportsAltitude\" == \"\",\n\t \"supportsSpeed\" == \"\",\n\t \"supportsBearing\" == \"\",\n\t android.location.Criteria.NO_REQUIREMENT,\n\t android.location.Criteria.ACCURACY_FINE);\n\n\t Location newLocation = new Location(LocationManager.GPS_PROVIDER);\n\n\t newLocation.setLatitude(latitude);\n\t newLocation.setLongitude(longitude);\n\t newLocation.setAccuracy(accuracy);\n\n\t lm.setTestProviderEnabled(LocationManager.GPS_PROVIDER, true);\n\n\t lm.setTestProviderStatus(LocationManager.GPS_PROVIDER,\n\t LocationProvider.AVAILABLE,\n\t null,System.currentTimeMillis());\n\n\t lm.setTestProviderLocation(LocationManager.GPS_PROVIDER, newLocation);\n\t}\n\n\n\t/*\n\t * Called by Location Services when the request to connect the\n\t * client finishes successfully. At this point, you can\n\t * request the current location or start periodic updates\n\t */\n\t@Override\n\tpublic void onConnected(Bundle dataBundle) {\n\t\t// Display the connection status\n\t\tToast.makeText(parentActivity, \"Connected\", Toast.LENGTH_SHORT).show();\n\n\t}\n\n\t/*\n\t * Called by Location Services if the connection to the\n\t * location client drops because of an error.\n\t */\n\t@Override\n\tpublic void onDisconnected() {\n\t\t// Display the connection status\n\t\tToast.makeText(parentActivity, \"Disconnected. Please re-connect.\", Toast.LENGTH_SHORT).show();\n\t}\n\n\t/*\n\t * Called by Location Services if the attempt to\n\t * Location Services fails.\n\t */\n\t@Override\n\tpublic void onConnectionFailed(ConnectionResult connectionResult) {\n\t\t/*\n\t\t * Google Play services can resolve some errors it detects.\n\t\t * If the error has a resolution, try sending an Intent to\n\t\t * start a Google Play services activity that can resolve\n\t\t * error.\n\t\t */\n\t\tif (connectionResult.hasResolution()) {\n\t\t\ttry {\n\t\t\t\t// Start an Activity that tries to resolve the error\n\t\t\t\tconnectionResult.startResolutionForResult(\n\t\t\t\t\t\tparentActivity,\n\t\t\t\t\t\tCONNECTION_FAILURE_RESOLUTION_REQUEST);\n\t\t\t\t/*\n\t\t\t\t * Thrown if Google Play services canceled the original\n\t\t\t\t * PendingIntent\n\t\t\t\t */\n\t\t\t}\n\t\t\tcatch (IntentSender.SendIntentException e) {\n\t\t\t\t// Log the error\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t/*\n\t\t\t * If no resolution is available, display a dialog to the\n\t\t\t * user with the error.\n\t\t\t */\n\t\t\tshowErrorDialog(connectionResult.getErrorCode());\n\t\t}\n\t} \n\n\tvoid showErrorDialog(int code) {\n\t\tGooglePlayServicesUtil.getErrorDialog(code, parentActivity, REQUEST_CODE_RECOVER_PLAY_SERVICES).show();\n\t}\n\n /*\n * Create a PendingIntent that triggers an IntentService in your\n * app when a geofence transition occurs.\n */\n private PendingIntent getTransitionPendingIntent() {\n // Create an explicit Intent\n Intent intent = new Intent(parentActivity, ReceiveTransitionsIntentService.class);\n intent.setAction(TRANSITION_INTENT_ACTION);\n /*\n * Return the PendingIntent\n */\n return PendingIntent.getService(\n parentActivity,\n 0,\n intent,\n PendingIntent.FLAG_UPDATE_CURRENT);\n }\n \n public void addGeofences(final List fenceList, final OnAddGeofencesResultListener listener) {\n \tList gfList = new ArrayList();\n \t// create a Geofence from each Fence\n \tfor (Fence f : fenceList) {\n \t\tgfList.add(f.asGeofence());\n \t}\n\t\t// get pending intent for geofence transitions\n\t\tgeofenceRequestIntent = getTransitionPendingIntent();\n\t\t// Send a request to add the current geofences\n locationClient.addGeofences(gfList, geofenceRequestIntent, new OnAddGeofencesResultListener() {\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void onAddGeofencesResult(int statusCode, String[] geofenceRequestIds) {\n\t\t\t\t// if successful, persist the new Fence\n\t\t if (LocationStatusCodes.SUCCESS == statusCode) {\n\t\t \t\tFenceMgr.getDefault().add(fenceList);\n\t\t \t\tlistener.onAddGeofencesResult(statusCode, geofenceRequestIds);\n\t\t \t\tToast.makeText(parentActivity, \"Added \" + fenceList.size() + \" new geofences.\", Toast.LENGTH_SHORT).show();\n\t\t }\n\t\t else {\n\t\t\t // If adding the geofences failed\n\t\t /*\n\t\t * Report errors here.\n\t\t * You can log the error using Log.e() or update\n\t\t * the UI.\n\t\t */\n\t\t }\n\t\t // Turn off the in progress flag\n\t\t inProgress = false;\n\t\t\t}\n\t\t});\n }\n \n \n public void removeAllGeofences(final OnRemoveGeofencesResultListener listener) {\n \tif (!FenceMgr.getDefault().getFences().isEmpty()) {\n \t\tremoveGeofences(FenceMgr.getDefault().getFences(), listener);\n \t}\n }\n\n \n public void removeGeofences(final List fenceList, final OnRemoveGeofencesResultListener listener) {\n \tList gfList = new ArrayList();\n \tfor (Fence f : fenceList) {\n \t\tgfList.add(f.getId());\n \t}\n locationClient.removeGeofences(gfList, new OnRemoveGeofencesResultListener() {\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void onRemoveGeofencesByRequestIdsResult(int statusCode, String[] geofenceRequestIds) {\n\t\t\t\t// if successful, persist the change\n\t\t if (LocationStatusCodes.SUCCESS == statusCode) {\n\t\t \t\tFenceMgr.getDefault().delete(fenceList);\n\t\t \t\tlistener.onRemoveGeofencesByRequestIdsResult(statusCode, geofenceRequestIds);\n\t\t \t\tToast.makeText(parentActivity, \"Removed \" + geofenceRequestIds.length + \" geofences.\", Toast.LENGTH_SHORT).show();\n\t\t }\n\t\t else {\n\t\t\t // If adding the geofences failed\n\t\t /*\n\t\t * Report errors here.\n\t\t * You can log the error using Log.e() or update\n\t\t * the UI.\n\t\t */\n\t\t }\n\t\t // Turn off the in progress flag\n\t\t inProgress = false;\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void onRemoveGeofencesByPendingIntentResult(int arg0, PendingIntent arg1) {\n\t\t\t\t// TODO Auto-generated method stub\n\t\t\t}\n\t\t});\n }\n\n public void addGeofence(final Fence fence) {\n\t\t// get pending intent for geofence transitions\n\t\tgeofenceRequestIntent = getTransitionPendingIntent();\n // create new Geofence from Fence and add to play services\n\t\tGeofence gf = fence.asGeofence();\n\t\tList gfList = new ArrayList();\n\t\tgfList.add(gf);\n\t\t// Send a request to add the current geofences\n locationClient.addGeofences(gfList, geofenceRequestIntent, new OnAddGeofencesResultListener() {\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void onAddGeofencesResult(int statusCode, String[] geofenceRequestIds) {\n\t\t\t\t// if successful, persist the new Fence\n\t\t if (LocationStatusCodes.SUCCESS == statusCode) {\n\t\t \t\tFenceMgr.getDefault().add(fence);\n\t\t \t\tToast.makeText(parentActivity, \"Added new geofence named \" + fence.getName(), Toast.LENGTH_SHORT).show();\n\t\t }\n\t\t else {\n\t\t\t // If adding the geofences failed\n\t\t /*\n\t\t * Report errors here.\n\t\t * You can log the error using Log.e() or update\n\t\t * the UI.\n\t\t */\n\t\t }\n\t\t // Turn off the in progress flag\n\t\t inProgress = false;\n\t\t\t}\n\t\t});\n\t}\n \n public void removeGeofence(final Fence fence, final OnDeleteFenceListener listener) {\n\t\tList gfList = new ArrayList();\n\t\tgfList.add(fence.getId());\n locationClient.removeGeofences(gfList, new OnRemoveGeofencesResultListener() {\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void onRemoveGeofencesByRequestIdsResult(int statusCode, String[] geofenceRequestIds) {\n\t\t\t\t// if successful, persist the change\n\t\t if (LocationStatusCodes.SUCCESS == statusCode) {\n\t\t \t\tFenceMgr.getDefault().delete(fence);\n\t\t \t\tlistener.onDeleteFence(fence.getId());\n\t\t \t\tToast.makeText(parentActivity, \"Removed geofence named \" + fence.getName(), Toast.LENGTH_SHORT).show();\n\t\t }\n\t\t else {\n\t\t\t // If adding the geofences failed\n\t\t /*\n\t\t * Report errors here.\n\t\t * You can log the error using Log.e() or update\n\t\t * the UI.\n\t\t */\n\t\t }\n\t\t // Turn off the in progress flag\n\t\t inProgress = false;\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void onRemoveGeofencesByPendingIntentResult(int arg0, PendingIntent arg1) {\n\t\t\t\t// TODO Auto-generated method stub\n\t\t\t}\n\t\t});\n }\n}\n"},"message":{"kind":"string","value":"Added error messages when location services is turned off"},"old_file":{"kind":"string","value":"src/com/example/icampgeofence/LocationMgr.java"},"subject":{"kind":"string","value":"Added error messages when location services is turned off"},"git_diff":{"kind":"string","value":"rc/com/example/icampgeofence/LocationMgr.java\n \t\t \t\tFenceMgr.getDefault().add(fence);\n \t\t \t\tToast.makeText(parentActivity, \"Added new geofence named \" + fence.getName(), Toast.LENGTH_SHORT).show();\n \t\t }\n\t\t else if (LocationStatusCodes.GEOFENCE_NOT_AVAILABLE == statusCode) {\n\t\t\t // If adding the geofences failed\n\t\t \tToast.makeText(parentActivity, \"Error: Location Access turned off in Settings\", Toast.LENGTH_SHORT).show();\n\t\t }\n\t\t else if (LocationStatusCodes.GEOFENCE_TOO_MANY_GEOFENCES == statusCode) {\n\t\t\t // If adding the geofences failed\n\t\t \tToast.makeText(parentActivity, \"Error: Geofence limit exceeded\" + fence.getName() + \", Code:\" + statusCode, Toast.LENGTH_SHORT).show();\t\t \t\n\t\t }\n \t\t else {\n \t\t\t // If adding the geofences failed\n\t\t /*\n\t\t * Report errors here.\n\t\t * You can log the error using Log.e() or update\n\t\t * the UI.\n\t\t */\n\t\t \tToast.makeText(parentActivity, \"Error: Geofence not added\", Toast.LENGTH_SHORT).show();\n \t\t }\n \t\t // Turn off the in progress flag\n \t\t inProgress = false;\n \t\t \t\tlistener.onDeleteFence(fence.getId());\n \t\t \t\tToast.makeText(parentActivity, \"Removed geofence named \" + fence.getName(), Toast.LENGTH_SHORT).show();\n \t\t }\n\t\t else if (LocationStatusCodes.GEOFENCE_NOT_AVAILABLE == statusCode) {\n\t\t\t // If adding the geofences failed\n\t\t \tToast.makeText(parentActivity, \"Error: Location Access turned off in Settings\", Toast.LENGTH_SHORT).show();\n\t\t }\n \t\t else {\n \t\t\t // If adding the geofences failed\n\t\t /*\n\t\t * Report errors here.\n\t\t * You can log the error using Log.e() or update\n\t\t * the UI.\n\t\t */\n\t\t \tToast.makeText(parentActivity, \"Error: Geofence not removed\", Toast.LENGTH_SHORT).show();\n \t\t }\n \t\t // Turn off the in progress flag\n \t\t inProgress = false;"}}},{"rowIdx":858,"cells":{"lang":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"ecbb1d2367cdd7a42f4271197c3a321bd7e3c2ef"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"uplne/vivamusica2014"},"new_contents":{"kind":"string","value":"\ndb.program.insert({\n \"datenum\" : 21,\n \"datemonth\" : \"jún\",\n \"datemonth_en\": \"June\",\n \"datetime\" : \"20:30
Entrance free\",\n \"place\" : \"Hlavné námestie\",\n \"place_en\": \"Main Square\",\n \"title\" : \"Sen noci svätojánskej\",\n \"title_en\": \"A Midsummer Night’s Dream\",\n \"intro\" : \"Otvárací koncert 10. ročníka Viva Musica! festivalu a Kultúrneho leta a Hradných slávností Bratislava 2014\",\n \"intro_en\": \"Opening concert in the 10th annual Viva Musica! Festival and Bratislava Cultural Summer and Castle Festival 2014\",\n \"text\" : \"Viva Musica! festival v roku 2014 oslavuje okrúhle 10. narodeniny a svojim návštevníkom opäť ponúkne niekoľko exkluzívnych hudobných zážitkov. V rámci otváracieho koncertu uvedieme v spolupráci s medzinárodným festivalom Letné shakespearovské slávnosti a Kultúrne leto a hradné slávnosti Bratislava 2014 Shakespearovu romantickú komédiu Sen noci svätojánskej s rovnomennou scénickou hudbou nemeckého hudobného skladateľa Felixa Mendelssohna-Bartholdyho (1809-1847). Shakespearov text ožije v podaní Sabiny Laurinovej, Oldřicha Víznera a Csongora Kassaia v sprievode Mendelssohnovej hudby interpretovanej Slovenskou filharmóniou pod vedením Leoša Svárovského. Viva Shakespeare!

Realizačný tím:

Preklad: Martin Hilský, Ľubomír Feldek
Dramaturgia a réžia: Róbert Mankovecký
Producent za LSS: Janka Zednikovičová

Účinkujú:

Oberon – Oldřich Vízner
Titania – Sabina Laurinová
Puk – Csongor Kassai
Klbko – Peter Kadlečík
Väzba – Jakub Rybárik

Petronela Drobná – soprán
Katarína Kubovičová-Sroková – alt
Ženský spevácky zbor
Jozef Chabroň – zbormajster

Slovenská filharmónia
Leoš Svárovský – dirigent\",\n \"text_en\": \"In 2014 the Viva Musica! Festival celebrates its 10th birthday and again offers its visitors some exquisite musical delights. In collaboration with the international Summer Shakespeare Festival, Bratislava Cultural Summer and Castle Festival 2014, our opening concert presents Shakespeare’s romantic comedy A Midsummer Night’s Dream with the identically-named music by the German composer Felix Mendelssohn-Bartholdy (1809-1847). Shakespeare’s text is vividly rendered by Sabina Laurinová, Oldřich Vízner and Csongor Kassai, accompanied by Mendelssohn’s music performed by the Slovak Philharmonic and members of the Slovak Philharmonic Choir conducted by Leoš Svárovský. Viva Shakespeare!

Production team:

Translators: Martin Hilský, Ľubomír Feldek
Dramaturge and director: Róbert Mankovecký
Producer for SSF: Janka Zednikovičová

Performers:

Oberon – Oldřich Vízner
Titania – Sabina Laurinová
Puck – Csongor Kassai
Bottom – Peter Kadlečík
Quince – Jakub Rybárik

Petronela Drobná – soprano
Katarína Kubovičová-Sroková – alto
Members of the Slovak Philharmonic Choir
Jozef Chabroň – choirmaster

Slovak Philharmonic
Leoš Svárovský – conductor\",\n \"img\" : \"sen.jpg\",\n \"path\" : \"sen-noci-svatojanskej\",\n \"tickets\" : \"\",\n \"price\" : \"Vstup voľný\",\n \"price_en\": \"Entrance free\"\n})\ndb.program.insert({\n \"datenum\" : 22,\n \"datemonth\" : \"jún\",\n \"datemonth_en\" : \"June\",\n \"datetime\" : \"17:00\",\n \"place\" : \"Nádvorie Primaciálneho paláca\",\n \"place_en\": \"Primatial Palace Forecourt\",\n \"title\" : \"Čarovná flauta\",\n \"title_en\": \"The Magic Flute\",\n \"intro\" : \"Detský deň v rámci Viva Musica! festivalu na obľúbenom Hlavnom námestí a na Nádvorí Primaciálneho paláca prinesie okrem iného aj netradičné spracovanie opernej klasiky pre deti.\",\n \"intro_en\": \"The famous Mozart opera as you’ve never known it!\",\n \"text\" : \"Mozartova opera Čarovná flauta rozpráva príbeh princa Tamina, ktorý bojuje o priazeň pôvabnej princeznej Paminy, dcéry Kráľovnej noci, a vtáčkara Papagena túžiaceho po krásnej Papagene. Silou lásky a pravdy hrdinovia prekonávajú nástrahy Kráľovnej noci, jej troch dvorných dám a sluhu Monostata. Mozartova opera v podaní pražského Národného bábkového divadla je určená predovšetkým deťom a ich rodičom a prinesie okrem stretnutia s operou a hudbou rakúskeho génia aj nevšedný zážitok z vizuálneho stvárnenia diela v podaní bábok so živými hercami.

Národné bábkové divadlo Praha:
Tamino – Ivan Čermák
Papageno – Michal Džula
Sarastro – Roman Havelka
Papagena – Taťana Zemanová
Pamina – Linda Bláhová Lahnerová
Kráľovná noci / Dáma – Vlastimila Žaludová

Martin Vanek – rozprávač

Realizačný tím:
Réžia: Karel Brožek
Vedúci techniky: Karel Vacek
Technika: David Hron, Kateřina Hronová
Producent: Petr Vodička\",\n \"text_en\": \"Mozart’s opera The Magic Flute tells the story of prince Tamino, who is fighting for the favour of the charming princess Pamina, daughter of the Queen of the Night, and the bird-catcher Papageno who is full of desire for the beautiful Papagena. By the power of love and truth the heroes overcome the snares of the Queen of the Night, her three court ladies and her servant Monostato. Mozart’s opera, as rendered by the Prague National Marionette Theatre, is designed principally for children and their parents, and apart from the encounter with the work and music of the Austrian genius, offers an unusual treat in the visual presentation of the work as rendered by puppets with live actors. Martin Vanek will be the accompanist during the performance.

Prague National Marionette Theatre:
Tamino – Ivan Čermák
Papageno – Michal Džula
Sarastro – Roman Havelka
Papagena – Taťana Zemanová
Pamina – Linda Bláhová Lahnerová
Queen of the Night / Court lady – Vlastimila Žaludová

Martin Vanek – narrator

Production team:
Director: Karel Brožek
Head of technics: Karel Vacek
Technics: David Hron, Kateřina
Producer: Petr Vodička\",\n \"img\" : \"babkova.jpg\",\n \"path\" : \"carovna-flauta\",\n \"tickets\" : \"http://www.ticketportal.sk/event.aspx?id=19643&idpartner=57\",\n \"price\" : \"\"\n})\ndb.program.insert({\n \"datenum\" : 22,\n \"datemonth\" : \"jún\",\n \"datemonth_en\" : \"June\",\n \"datetime\" : \"20:00
Entrance free\",\n \"place\" : \"Hlavné námestie\",\n \"place_en\": \"Main Square\",\n \"title\" : \"Virtuoso\",\n \"title_en\" : \"Virtuoso\",\n \"intro\" : \"Predstavte si obrovský orchester zložený z talentovaných detí z celého Slovenska – detí, ktoré by sa za normálnych okolností možno nikdy nestretli...\",\n \"intro_en\": \"Imagine an enormous orchestra composed of talented children from the whole of Slovakia – children you would never meet under normal circumstances...\",\n \"text\" : \"Predstavte si obrovský orchester zložený z talentovaných detí z celého Slovenska – detí, ktoré by sa za normálnych okoSpojila ich však láska k hudbe, hodiny cvičenia na hudobnom nástroji a možno aj v kútiku duše schovaný sen stať sa niekým, kto sa zapíše do hudobných dejín. Unikátny hudobný projekt VIRTUOSO túto predstavu premieňa na realitu prostredníctvom zapojenia detských a mládežníckych talentov zo základných umeleckých škôl z celého Slovenska do jedného veľkého národného orchestra. Šéfdirigentom orchestra je Igor Dohovič, rodák z Prešova, pod ktorého vedením už národný mládežnícky orchester úspešne absolvoval niekoľko koncertov po celom Slovensku. V orchestri platí pravidlo: „Jeden za všetkých – všetci za lásku ku klasickej hudbe!“ A tá je prudko nákazlivá aj pre všetkých ostatných.

Program:

Henry Purcell (1659-1695): Rondeau zo suity Abdelazer
Antonio Vivaldi (1678-1741): Štyri ročné obdobia – Jar
Antonio Vivaldi: Sinfonia h mol „Al santo sepolcro“, RV 169
Wolfgang Amadeus Mozart (1756-1791): Non più andrai, ária Figara z opery Figarova svadba
Joseph Haydn (1732-1809): Detská symfónia (1. a 3. časť)
Peter Martin: Sovetto
Dmitrij Šostakovič (1906-1975): Valčík zo Suity č. 2
Hubert Giraud (1920): Sous le ciel de Paris
Lucio Dalla (1943-2012): Caruso
Karl William Pamp Jenkins (1944): Palladio
Ennio Morricone (1928): Vtedy na západe
Klaus Badelt (1967): Piráti z Karibiku
Astor Piazzolla (1921-1992): Tango

Národný mládežnícky orchester Virtuoso
Filip Tůma – barytón
Igor Dohovič – dirigent\",\n \"text_en\": \"But what all of them had in common was a love of music, hours of practice on a musical instrument, and maybe in some corner of their minds a dream of becoming someone whose name would be recorded in musical history. The unique musical project VIRTUOSO makes this idea a reality by bringing together talented children and youth from the primary art schools of all Slovakia into one big national orchestra. The chief conductor is Igor Dohovič, a native of Prešov, under whose direction the orchestra has already successfully completed a number of concerts throughout Slovakia. In this orchestra the rule applies: “One for all, and all for the love of classical music!” And that is highly infectious for everyone else.

Program:

Henry Purcell (1659-1695): Rondeau from Abdelazer suite
Antonio Vivaldi (1678-1741): The Four Seasons – Spring
Antonio Vivaldi: Sinfonia b minor „Al santo sepolcro“, RV 169
Wolfgang Amadeus Mozart (1756-1791): Non più andrai, aria of Figaro from The Marriage of Figaro
Joseph Haydn (1732-1809): Children’s Symphony (1st and 3rd mov.)
Peter Martin: Sovetto
Dmitrij Šostakovič (1906-1975): Waltz from Suite No. 2
Hubert Giraud (1920): Sous le ciel de Paris
Lucio Dalla (1943-2012): Caruso
Karl William Pamp Jenkins (1944): Palladio
Ennio Morricone (1928): Once Upon a Time in the West
Klaus Badelt (1967): Pirates of the Caribbean
Astor Piazzolla (1921-1992): Tango

National Youth Orchestra Virtuoso
Filip Tůma – baritone
Igor Dohovič – conductor\",\n \"img\" : \"virtuoso.jpg\",\n \"path\" : \"virtuoso\",\n \"tickets\" : \"\",\n \"price\" : \"Vstup voľný\",\n \"price_en\": \"Entrance free\"\n})\ndb.program.insert({\n \"datenum\" : 24,\n \"datemonth\" : \"jún\",\n \"datemonth\": \"June\",\n \"datetime\" : \"20:00\",\n \"place\" : \"Stará tržnica\",\n \"place_en\": \"Old City Market Hall\",\n \"title\" : \"Quasars Ensemble & Dalibor Karvay\",\n \"title_en\": \"Quasars Ensemble & Dalibor Karvay\",\n \"intro\" : \"Jedinečné spojenie hviezd súčasnej klasiky a husľového virtuóza Dalibora Karvaya.\",\n \"intro_en\": \"A unique alliance of stars of contemporary classical music with the violin virtuoso Dalibor Karvay.\",\n \"text\" : \"Komorné zoskupenie Quasars Ensemble pôsobí na slovenskej hudobnej scéne od roku 2008 a počas šiestich rokov sa vyprovilovalo na medzinárodne uznávaný súbor súčasnej klasickej hudby. Quasars Ensemble založil hudobný skladateľ, klavirista a dirigent Ivan Buffa a výnimočnosťou súboru je okrem iného aj fakt, že popri súčasnej klasickej hudbe sa v rovnakej miere venuje aj hudbe starších epoch. Súbor je pravidelným hosťom významných domácich i zahraničných hudobných festivalov, organizuje vlastné projekty v regiónoch Slovenska, má na konte šesť profilových CD albumov a je držiteľom ocenenia Krištáľové krídlo v kategórii „Hudba“ za rok 2013. Špeciálnym hosťom koncertu bude vynikajúci slovenský huslista Dalibor Karvay, ktorý v sprievode Quasars Ensemble pod taktovkou Ivana Buffu uvedie Waxmanovu verziu melódií z Bizetovej opery Carmen a Ravelovu virtuóznu skladbu Tzigane, ktoré v programe doplní Septet francúzskeho skladateľa s poľskými koreňmi Alexandra Tansmana a Komorná hudba č. 1, op. 24 nemeckého autora Paula Hindemitha.

Program:

Alexandre Tansman (1897-1986): Septet
Maurice Ravel (1875-1937): Tzigane (arr. I. Buffa)
Franz Waxman (1906-1967): Fantázia Carmen (arr. I. Buffa)

* * *

Alexander Moyzes (1906-1984): Divertimento op. 11 (arr. I. Buffa)
Paul Hindemith (1895-1963): Komorná hudba č. 1, op. 24

Dalibor Karvay – husle

Quasars Ensemble:
Andrea Bošková – flauta
Júlia Csíziková – hoboj
Martin Mosorjak – klarinet
Attila Jankó – fagot
István Siket – trúbka
András Kovalcsik – lesný roh
Diana Buffa – klavír
Tamás Schlanger – bicie
Maroš Potokár – 1. husle
Peter Mosorjak – 2. husle
Peter Zwiebel – viola
Andrej Gál – violončelo
Marián Bujňák – kontrabas
Milan Osadský – akordeón

Ivan Buffa – dirigent\",\n \"text_en\": \"The chamber formation Quasars Ensemble has been active on the Slovak music scene since 2008, and in the course of six years has established its profile as an internationally respected formation in contemporary classical music. Quasars Ensemble was founded by the composer, pianist and conductor Ivan Buffa, and one of its exceptional features is that alongside contemporary classical music it also devotes itself in equal measure to the music of earlier epochs. The ensemble is a regular guest at leading music festivals at home and abroad, organises projects of its own in the regions of Slovakia, has six profile CD albums to its credit, and is the holder of the 2013 Crystal Wing Prize in the “Music” category. The concert’s special guest will be the outstanding Slovak violinist Dalibor Karvay, who, accompanied by Quasars Ensemble, will present the Waxman version of melodies from Bizet’s opera Carmen and Ravel’s virtuoso work Tzigane. These will be complemented in the programme by Septet, a work by the French composer (with Polish roots) Alexander Tansman, Divertimento Op. 11 by the Slovak composer Alexander Moyzes, and Chamber Music No. 1, Op. 24 by the German composer Paul Hindemith.

Program:

Alexandre Tansman (1897-1986): Septet
Maurice Ravel (1875-1937): Tzigane (arr. I. Buffa)
Franz Waxman (1906-1967): Carmen Fantasie (arr. I. Buffa)

* * *

Alexander Moyzes (1906-1984): Divertimento Op. 11 (arr. I. Buffa)
Paul Hindemith (1895-1963): Chamber Music No. 1, Op. 24

Dalibor Karvay – violin

Quasars Ensemble:

Andrea Bošková – flute
Júlia Csíziková – oboe
Martin Mosorjak – clarinet
Attila Jankó – bassoon
István Siket – trumpet
András Kovalcsik – French horn
Diana Buffa – piano
Tamás Schlanger – percussions
Maroš Potokár – 1st violin
Peter Mosorjak – 2nd violin
Peter Zwiebel – viola
Andrej Gál – violoncello
Marián Bujňák – double bass
Milan Osadský – accordion

Ivan Buffa – conductor\",\n \"img\" : \"karvay.jpg\",\n \"path\" : \"quasars-ensemble-dalibor-karvay\",\n \"tickets\" : \"http://www.ticketportal.sk/event.aspx?id=19624&idpartner=57\",\n \"price\" : \"\"\n})\ndb.program.insert({\n \"datenum\" : 25,\n \"datemonth\" : \"jún\",\n \"datemonth_en\" : \"June\",\n \"datetime\" : \"20:00\",\n \"place\" : \"Stará tržnica\",\n \"place_en\": \"Old City Market Hall\",\n \"title\" : \"Xavier Sabata & Il Pomo D’Oro\",\n \"title_en\" : \"Xavier Sabata & Il Pomo D’Oro\",\n \"intro\" : \"„Tento projekt patrí k tomu najinteligentnejšiemu a najpozoruhodnejšiemu, čo sa v hudobnom svete zrodilo za posledné roky.“ (Guardian)\",\n \"intro_en\": \"“This project is one of the most intelligent and noteworthy that the music world has produced in recent years.” (Guardian)\",\n \"text\" : \"Španielsky kontratenorista Xavier Sabata vo svojom projekte Händel: Bad Guys odhaľuje svet záporných postáv v Händlových operách a presviedča nás o tom, že baroková opera nemusí byť len o vznešených antických ideáloch. Vďaka svojmu výnimočnému hlasu stvárňuje postavy bezočivých pokrytcov, zlomyseľných tyranov či dokonca obyčajných hlupákov s absolútnym nadhľadom a ľahkosťou. Xavier Sabata pochádza z Barcelony a má za sebou hosťovania na tých najprestížnejších svetových operných a koncertných pódiách. Do Bratislavy príde po prvýkrát so súborom Il pomo d’oro pod vedením huslistu a dirigenta Riccarda Minasiho, ktorý sa špecializuje na tzv. historicky poučenú interpretáciu starej hudby na dobových nástrojoch.

Program:

Georg Friedrich Händel (1685-1759):
Sinfonia B dur, HWV 339, 1. časť
Vo‘ dar pace a un’alma altiera (Tamerlano)
Nella terra, in ciel, nell‘onda (Faramondo)
Concerto grosso G dur, HWV 314
Bel labbro formato (Ottone, re di Germania)
Dover, giustizia, amor (Ariodante)

* * *

Domerò la tua fierezza (Giulio Cesare)
Serenatevi, o luci belle (Teseo)
Se l’inganno sortisce felice (Ariodante)
Sonáta G dur op. 5, č. 4, HWV 399
Così suole a rio vicina (Faramondo)
Voglio stragi, e voglio morte (Teseo)

Xavier Sabata – kontratenor

Il pomo d’oro:
Alfia Bakieva – husle
Boris Begelman – husle
Ester Crazzolara – husle
Anna Fuskova – husle
Daniela Nuzzoli – husle, viola
Enrico Parizzi – viola
Federico Toffano – violoncello
Davide Nava – kontrabas
Maxim Emelyanychev – cembalo

Riccardo Minasi – husle, umelecké vedenie

\",\n \"text_en\": \"In his project Händel: Bad Guys the Spanish countertenor Xavier Sabata uncovers the world of the negative characters in Händel’s operas and persuades us of the fact that baroque opera need not only be about the sublime ideals of antiquity. Making use of his exceptional voice, he creates the characters of ruthless hypocrites, malignant tyrants, and pure-and-simple stupid asses, with absolute clarity and ease. Xavier Sabata comes from Barcelona and has a history of guest appearances on the world’s most prestigious opera and concert stages. He is coming to Bratislava for the first time with Il pomo d’oro ensemble, led by violinist and conductor Riccardo Minasi, who specialises in the so-called historically informed performance of early music on period instruments.

Program:

Georg Friedrich Händel (1685-1759):

Sinfonia B flat major, HWV 339, 1st mov.
Vo‘ dar pace a un’alma altiera (Tamerlano)
Nella terra, in ciel, nell‘onda (Faramondo)
Concerto Grosso G major, HWV 314
Bel labbro formato (Ottone, re di Germania)
Dover, giustizia, amor (Ariodante)

* * *

Domerò la tua fierezza (Giulio Cesare)
Serenatevi, o luci belle (Teseo)
Se l’inganno sortisce felice (Ariodante)
Sonate G major Op. 5, No. 4, HWV 399
Così suole a rio vicina (Faramondo)
Voglio stragi, e voglio morte (Teseo)

Xavier Sabata – countertenor

Il pomo d’oro:

Alfia Bakieva – violin
Boris Begelman – violin
Ester Crazzolara – violin
Anna Fuskova – violin
Daniela Nuzzoli – violin, viola
Enrico Parizzi – viola
Federico Toffano – violoncello
Davide Nava – double bass
Maxim Emelyanychev – cembalo

Riccardo Minasi – violin, conductor

\",\n \"img\" : \"sabata.jpg\",\n \"path\" : \"handel-bad-guys\",\n \"tickets\" : \"http://www.ticketportal.sk/event.aspx?id=19543&idpartner=57\",\n \"price\" : \"\"\n})\ndb.program.insert({\n \"datenum\" : 26,\n \"datemonth\" : \"jún\",\n \"datemonth_en\": \"June\",\n \"datetime\" : \"20:00\",\n \"place\" : \"Stará tržnica\",\n \"place_en\": \"Old City Market Hall\",\n \"title\" : \"Korben Dallas Symphony\",\n \"title_en\" : \"Korben Dallas Symphony\",\n \"intro\" : \"Výnimočný objav slovenskej hudobnej scény v sprievode orchestra na Viva Musica! festivale.\",\n \"intro_en\": \"Underground goes classic!\",\n \"text\" : \"Korben Dallas minulý rok pokrstil svoj druhý album Karnevalová vrana. V éteri bodujú hity Otec, Zlatý jeleň a Beh a po rokoch v hudobnom podzemí sa Korben Dallas stáva mienkotvornou kapelou. Skupinu založili spevák a gitarista Juraj Benetin a basgitarista Lukáš Fila po rozpade skupiny Appendix, v ktorej spolu hrali trinásť rokov. Bubeníkom sa po dlhom hľadaní stal Ozo Guttler zo skupiny Tu v Dome. Kapela debutovala živým albumom Pekné cesty v roku 2011 a má za sebou okrem hrania v rámci niekoľkých hudobných festivalov aj spoločné koncerty s americkou pesničkárkou Jess Klein, spoluprácu s Ľubom Petruškom z Chiki liki tu-a či s Andrejom Šebanom. S orchestrom však Korben Dallas ešte nikdy nehral – v exkluzívnej premiére po prvýkrát na Viva Musica! festivale!

Korben Dallas
Juraj Benetin – spev, gitara
Lukáš Fila – basgitara
Ozo Guttler – bicie

Špeciálny hosť:
Ľubo Petruška – gitara (Chiki liki tu-a)

Sinfonietta Bratislava
Braňo Kostka – dirigent

Slavomír Solovic – aranžmány\",\n \"text_en\": \"Last year Korben Dallas named his second album Carnival Raven. The hit tunes Father, Golden Deer and Run have won favour on the ether, and after years in the musical underground Korben Dallas has become a trend-setting band. The group was founded by singer and guitarist Juraj Benetin and bass guitarist Lukáš Fila after the break-up of Appendix, where they had played together for thirteen years. After much searching, Ozo Guttler from the Here at Home group became the drummer. The band made its debut with the live album Fine Roads in 2011, and apart from playing in a number of music festivals it has also performed concerts together with the American singer Jess Klein and collaborated with Ľuboš Petruška of Chiki liki tu-a and Andrej Šeban. However, up to now Korben Dallas has never played with an orchestra – here it is in an exclusive premiere, first time in the Viva Musica! Festival, under the baton of Braňo Kostka!

Korben Dallas
Juraj Benetin – vocals, guitar
Lukáš Fila – bassguitar
Ozo Guttler – drums

Special guest:
Ľubo Petruška – guitar (Chiki liki tu-a)

Sinfonietta Bratislava
Braňo Kostka – conductor

Slavomír Solovic – arranger\",\n \"img\" : \"korben.jpg\",\n \"path\" : \"korben-dallas-symphony\",\n \"tickets\" : \"http://www.ticketportal.sk/event.aspx?id=19545&idpartner=57\",\n \"price\" : \"\"\n})\ndb.program.insert({\n \"datenum\" : 27,\n \"datemonth\" : \"jún\",\n \"datemonth_en\": \"June\",\n \"datetime\" : \"22:00

24:00 hororová noc v Gorila.sk Urban Space\",\n \"place\" : \"Stará tržnica\",\n \"place_en\": \"Old City Market Hall\",\n \"title\" : \"Upír Nosferatu\",\n \"title_en\": \"Nosferatu\",\n \"intro\" : \"„Keď sa za Hutterom samé od seba zavreli dvere hradu, jeho osud bol spečatený. Mal sa stať prvou svetoznámou obeťou prvého svetoznámeho upíra a ako mu povedal Dr. Sievers: Svojmu osudu neutečiete.“ (www.kinema.sk)\",\n \"intro_en\": \"The legendary silent film with orchestral accompaniment.

24:00 a night of horror in Gorila.sk Urban Space\",\n \"text\" : \"Každý ho pozná, ale málokto ho v súčasnosti naozaj videl. Reč je o klasickom nemeckom nemom filme Upír Nosferatu (Nosferatu, eine Symphonie des Grauens; r. F. W. Murnau, 1922), ktorý už takmer storočie desí obecenstvo na celom svete. Keď sa nemecký expresionista Friedrich Wilhelm Murnau rozhodol natočiť adaptáciu slávneho románu Brama Stokera Dracula netušil, že vytvorí nadčasové dielo, ktoré budú filmoví vedci študovať ešte dlho po jeho smrti, a ktoré položí základy filmového hororu. Mladý úradník realitnej kancelárie Hutter prichádza do Transylvánie na hrad bohatého kupca, grófa Orloka, avšak po jeho návrate už nič nie je tak ako predtým... V rámci Viva Musica! festivalu uvedieme Murnauov film s autorskou hudbou slovenského skladateľa Vladislava Šarišského, laureáta prestížnej Medzinárodnej súťaže Sergeja Prokofieva v Petrohrade a držiteľa Ceny pre mladého tvorcu udeľovanej Nadáciou Tatra banky.

Vladislav „Slnko“ Šarišský – autor hudby, hudobné naštudovanie, theremin

Adam Novák – 1. husle
Ján Kružliak, ml. – 2. husle
Martin Mierny – viola
Boris Bohó – violončelo
Milan Osadský – akordeón
Štefan Bugala – tympany, perkusie

Po koncerte v Starej tržnici pokračujeme hororovou nocou v Gorila.sk Urban Space!

Príďte sa báť po kultovom Draculovi do Gorila.sk Urban Space. 27. júna o 24:00 na Nám. SNP začína hororová noc. Prinesieme vám tri hororové filmy, ktoré vybrali fanúšikovia tohto žánru. Úplne vážne: návštevu odporúčame len tým, ktorí sa neboja!


PROGRAM

Sinister (2012, USA)
V zajatí démonov (2013, USA)
Tucker a Dale vs. Zlo (2010, USA)\",\n \"text_en\": \"Everyone knows of it, but at the present day few have actually seen it. We are referring to the classical German silent film Nosferatu (Nosferatu, eine Symphonie des Grauens; dir. F. W. Murnau, 1922), which for almost a century has been frightening audiences throughout the world. When the German expressionist Friedrich Wilhelm Murnau decided to film an adaptation of Bram Stoker’s famous novel Dracula, he had no idea he was about to create a timeless work which would lay the foundations of film horror and would be studied by scholars of film long after his death. A young clerk of the Hutter estate agency comes to Transylvania to the castle of Count Orlok, a wealthy merchant, but after his return nothing is as it was before... As part of the Viva Musica! Festival we are presenting Murnau’s film with music written by the Slovak composer Vladislav “Sun” Šarišský, laureate of the prestigious international Sergej Prokofiev Competition in St. Petersburg and holder of the Young Artist’s Prize awarded by the Tatra Bank Foundation.

Vladislav „Slnko“ Šarišský – composer, theremin

Adam Novák – 1st violin
Ján Kružliak, ml. – 2nd violin
Martin Mierny – viola
Boris Bohó – violoncello
Milan Osadský – accordion
Štefan Bugala – timpani, percussions

After the concert in the Old City Market Hall, we continue with the night of horror in Gorila.sk Urban Space! At 24:00, June 27, the night of horror begins at SNP Square. We are bringing you three horror films which fans of this genre have selected. Quite seriously: we recommend a visit only to those who aren’t scared!

Programme of the night of horror:

Sinister (2012, USA)
The Conjuring (2013, USA)
Tucker & Dale vs. Evil (2010, USA)\",\n \"img\" : \"nosferatu.jpg\",\n \"path\" : \"upir-nosferatu\",\n \"tickets\" : \"http://www.ticketportal.sk/event.aspx?ID=19546&idpartner=57\",\n \"price\" : \"\"\n})\ndb.program.insert({\n \"datenum\" : 28,\n \"datemonth\" : \"jún\",\n \"datemonth_en\" : \"June\",\n \"datetime\" : \"20:00\",\n \"place\" : \"Bratislavský hrad\",\n \"place_en\": \"Bratislava Castle\",\n \"title\" : \"Viva Opera!\",\n \"title_en\" : \"Viva Opera!\",\n \"intro\" : \"Svetoznáme slovenské operné hviezdy po prvýkrát spolu na jednom pódiu!\",\n \"intro_en\": \"World-famous opera stars together on one stage for the first time!\",\n \"text\" : \"Záverečný koncert 10. ročníka medzinárodného festivalu Viva Musica! bude oslavou opery. Na jednom pódiu sa po prvýkrát spolu stretnú najlepší slovenskí operní sólisti – Adriana Kučerová, Jana Kurucová, Miroslav Dvorský, Dalibor Jenis a Štefan Kocán, ktorí v sprievode Orchestra Viva Musica! pod taktovkou Martina Leginusa, súčasného hudobného riaditeľa a šéfdirigenta pražskej Štátnej opery, uvedú známe i menej známe operné lahôdky z pera takých operných majstrov, akými boli Giuseppe Verdi, Georges Bizet, Gioacchino Rossini či Giacomo Puccini. Viva Opera!

Program:

Gioacchino Rossini (1792-1868):
Barbier zo Sevilly, predohra
Largo al factotum, ária z opery Barbier zo Sevilly
Oh patria!... Di tanti palpiti, ária z opery Tancredi
La calunnia é un venticello, ária z opery Barbier zo Sevilly

Gaetano Donizetti (1797-1848):
Quel guardo il cavaliere, ária z opery Don Pasquale

Giuseppe Verdi (1813-1901):
Lunge da lei... De‘ miei bollenti spiriti, ária z opery La traviata
Propizio ei giunge... Vieni a me, ti benedico, duet z opery Simon Boccanegra
Vanne la tua meta gia vedo... Credo, in un dio crudel, ária z opery Otello
E lui!... desso... l’Infante!... Dio che nell’alma infondere, duet z opery Don Carlos

Arrigo Boito (1842-1918):
Son lo spirito che nega, ária z opery Mefistofeles

Giuseppe Verdi:
Bella figlia dell'amore, kvartet z opery Rigoletto

* * *

Georges Bizet (1838-1875):
Carmen, predohra
Les tringles des sistres tintaient, ária z opery Carmen
Votre toast, je peux vous le rendre, ária z opery Carmen
La fleur que tu m'avais jetée, ária z opery Carmen

Léo Delibes (1836-1891):
Viens, Mallika, les lianes en fleurs... Dôme épais, le jasmin, duet z opery Lakmé

Jacques-François-Fromental-Élie Halévy (1799-1862):
Si la rigueur et la vengeance, ária z opery Židovka

Léo Delibes:
Les filles de Cadix

Adriana Kučerová – soprán
Jana Kurucová – mezzosoprán
Miroslav Dvorský – tenor
Dalibor Jenis – barytón
Štefan Kocán – bas

Orchester Viva Musica!

Martin Leginus – dirigent\",\n \"text_en\": \" The concluding concert of the 10th annual international Viva Musica! Festival will be a celebration of opera. For the first time the finest Slovak opera soloists will meet on the same stage. Adriana Kučerová, Jana Kurucová, Miroslav Dvorský, Dalibor Jenis and Štefan Kocán, accompanied by the Orchestra Viva Musica! under the baton of Martin Leginus, musical director and chief conductor of the Prague State Opera, will perform well-known and less well-known delights of opera, composed by such masters as Giuseppe Verdi, Georges Bizet, Gioacchino Rossini, and Giacomo Puccini. Viva opera!.

Program:

Gioacchino Rossini (1792-1868):
The Barber of Seville, overture
Largo al factotum, aria from The Barber of Seville
Oh patria!... Di tanti palpiti, aria from Tancredi
La calunnia é un venticello, aria from The Barber of Seville

Gaetano Donizetti (1797-1848):
Quel guardo il cavaliere, aria from Don Pasquale

Giuseppe Verdi (1813-1901):
Lunge da lei... De‘ miei bollenti spiriti, aria from La traviata
Propizio ei giunge... Vieni a me, ti benedico, duet from Simon Boccanegra
Vanne la tua meta gia vedo... Credo, in un dio crudel, aria from Otello
E lui!... desso... l’Infante!... Dio che nell’alma infondere, duet from Don Carlos

Arrigo Boito (1842-1918):
Son lo spirito che nega, aria from Mefistofele

Giuseppe Verdi:
Bella figlia dell'amore, quartet from Rigoletto

* * *

Georges Bizet (1838-1875):
Carmen, overture
Les tringles des sistres tintaient, aria from Carmen
Votre toast, je peux vous le rendre, aria from Carmen
La fleur que tu m'avais jetée, aria from Carmen

Léo Delibes (1836-1891):
Viens, Mallika, les lianes en fleurs... Dôme épais, le jasmin, duet from Lakmé

Jacques-François-Fromental-Élie Halévy (1799-1862):
Si la rigueur et la vengeance, aria from La Juive

Léo Delibes:
Les filles de Cadix

Adriana Kučerová – soprano
Jana Kurucová – mezzosoprano
Miroslav Dvorský – tenor
Dalibor Jenis – baritone
Štefan Kocán – bass

Viva Musica! orchestra
Martin Leginus – conductor\",\n \"img\" : \"opera.jpg\",\n \"path\" : \"viva-opera\",\n \"tickets\" : \"http://www.ticketportal.sk/event.aspx?id=19471&idpartner=57\",\n \"price\" : \"\"\n})\n"},"new_file":{"kind":"string","value":"mongosave.js"},"old_contents":{"kind":"string","value":"\ndb.program.insert({\n \"datenum\" : 21,\n \"datemonth\" : \"jún\",\n \"datemonth_en\": \"June\",\n \"datetime\" : \"20:30
Entrance free\",\n \"place\" : \"Hlavné námestie\",\n \"place_en\": \"Main Square\",\n \"title\" : \"Sen noci svätojánskej\",\n \"title_en\": \"A Midsummer Night’s Dream\",\n \"intro\" : \"Otvárací koncert 10. ročníka Viva Musica! festivalu a Kultúrneho leta a Hradných slávností Bratislava 2014\",\n \"intro_en\": \"Opening concert in the 10th annual Viva Musica! Festival and Bratislava Cultural Summer and Castle Festival 2014\",\n \"text\" : \"Viva Musica! festival v roku 2014 oslavuje okrúhle 10. narodeniny a svojim návštevníkom opäť ponúkne niekoľko exkluzívnych hudobných zážitkov. V rámci otváracieho koncertu uvedieme v spolupráci s medzinárodným festivalom Letné shakespearovské slávnosti a Kultúrne leto a hradné slávnosti Bratislava 2014 Shakespearovu romantickú komédiu Sen noci svätojánskej s rovnomennou scénickou hudbou nemeckého hudobného skladateľa Felixa Mendelssohna-Bartholdyho (1809-1847). Shakespearov text ožije v podaní Sabiny Laurinovej, Oldřicha Víznera a Csongora Kassaia v sprievode Mendelssohnovej hudby interpretovanej Slovenskou filharmóniou pod vedením Leoša Svárovského. Viva Shakespeare!

Realizačný tím:

Preklad: Martin Hilský, Ľubomír Feldek
Dramaturgia a réžia: Róbert Mankovecký
Producent za LSS: Janka Zednikovičová

Účinkujú:

Oberon – Oldřich Vízner
Titania – Sabina Laurinová
Puk – Csongor Kassai
Klbko – Peter Kadlečík
Väzba – Jakub Rybárik

Petronela Drobná – soprán
Katarína Kubovičová-Sroková – alt
Ženský spevácky zbor
Jozef Chabroň – zbormajster

Slovenská filharmónia
Leoš Svárovský – dirigent\",\n \"text_en\": \"In 2014 the Viva Musica! Festival celebrates its 10th birthday and again offers its visitors some exquisite musical delights. In collaboration with the international Summer Shakespeare Festival, Bratislava Cultural Summer and Castle Festival 2014, our opening concert presents Shakespeare’s romantic comedy A Midsummer Night’s Dream with the identically-named music by the German composer Felix Mendelssohn-Bartholdy (1809-1847). Shakespeare’s text is vividly rendered by Sabina Laurinová, Oldřich Vízner and Csongor Kassai, accompanied by Mendelssohn’s music performed by the Slovak Philharmonic and members of the Slovak Philharmonic Choir conducted by Leoš Svárovský. Viva Shakespeare!

Production team:

Translators: Martin Hilský, Ľubomír Feldek
Dramaturge and director: Róbert Mankovecký
Producer for SSF: Janka Zednikovičová

Performers:

Oberon – Oldřich Vízner
Titania – Sabina Laurinová
Puck – Csongor Kassai
Bottom – Peter Kadlečík
Quince – Jakub Rybárik

Petronela Drobná – soprano
Katarína Kubovičová-Sroková – alto
Members of the Slovak Philharmonic Choir
Jozef Chabroň –choirmaster

Slovak Philharmonic
Leoš Svárovský – conductor\",\n \"img\" : \"sen.jpg\",\n \"path\" : \"sen-noci-svatojanskej\",\n \"tickets\" : \"\",\n \"price\" : \"Vstup voľný\",\n \"price_en\": \"Entrance free\"\n})\ndb.program.insert({\n \"datenum\" : 22,\n \"datemonth\" : \"jún\",\n \"datemonth_en\" : \"June\",\n \"datetime\" : \"17:00\",\n \"place\" : \"Nádvorie Primaciálneho paláca\",\n \"place_en\": \"Primatial Palace Forecourt\",\n \"title\" : \"Čarovná flauta\",\n \"title_en\": \"The Magic Flute\",\n \"intro\" : \"Detský deň v rámci Viva Musica! festivalu na obľúbenom Hlavnom námestí a na Nádvorí Primaciálneho paláca prinesie okrem iného aj netradičné spracovanie opernej klasiky pre deti.\",\n \"intro_en\": \"The famous Mozart opera as you’ve never known it!\",\n \"text\" : \"Mozartova opera Čarovná flauta rozpráva príbeh princa Tamina, ktorý bojuje o priazeň pôvabnej princeznej Paminy, dcéry Kráľovnej noci, a vtáčkara Papagena túžiaceho po krásnej Papagene. Silou lásky a pravdy hrdinovia prekonávajú nástrahy Kráľovnej noci, jej troch dvorných dám a sluhu Monostata. Mozartova opera v podaní pražského Národného bábkového divadla je určená predovšetkým deťom a ich rodičom a prinesie okrem stretnutia s operou a hudbou rakúskeho génia aj nevšedný zážitok z vizuálneho stvárnenia diela v podaní bábok so živými hercami.

Národné bábkové divadlo Praha:
Tamino – Ivan Čermák
Papageno – Michal Džula
Sarastro – Roman Havelka
Papagena – Taťana Zemanová
Pamina – Linda Bláhová Lahnerová
Kráľovná noci / Dáma – Vlastimila Žaludová

Martin Vanek – rozprávač

Realizačný tím:
Réžia: Karel Brožek
Vedúci techniky: Karel Vacek
Technika: David Hron, Kateřina Hronová
Producent: Petr Vodička\",\n \"text_en\": \"Mozart’s opera The Magic Flute tells the story of prince Tamino, who is fighting for the favour of the charming princess Pamina, daughter of the Queen of the Night, and the bird-catcher Papageno who is full of desire for the beautiful Papagena. By the power of love and truth the heroes overcome the snares of the Queen of the Night, her three court ladies and her servant Monostato. Mozart’s opera, as rendered by the Prague National Marionette Theatre, is designed principally for children and their parents, and apart from the encounter with the work and music of the Austrian genius, offers an unusual treat in the visual presentation of the work as rendered by puppets with live actors. Martin Vanek will be the accompanist during the performance.

Prague National Marionette Theatre:
Tamino – Ivan Čermák
Papageno – Michal Džula
Sarastro – Roman Havelka
Papagena – Taťana Zemanová
Pamina – Linda Bláhová Lahnerová
Queen of the Night / Court lady – Vlastimila Žaludová

Martin Vanek – narrator

Production team:
Director: Karel Brožek
Head of technics: Karel Vacek
Technics: David Hron, Kateřina
Producer: Petr Vodička\",\n \"img\" : \"babkova.jpg\",\n \"path\" : \"carovna-flauta\",\n \"tickets\" : \"http://www.ticketportal.sk/event.aspx?id=19643&idpartner=57\",\n \"price\" : \"\"\n})\ndb.program.insert({\n \"datenum\" : 22,\n \"datemonth\" : \"jún\",\n \"datemonth_en\" : \"June\",\n \"datetime\" : \"20:00
Entrance free\",\n \"place\" : \"Hlavné námestie\",\n \"place_en\": \"Main Square\",\n \"title\" : \"Virtuoso\",\n \"title_en\" : \"Virtuoso\",\n \"intro\" : \"Predstavte si obrovský orchester zložený z talentovaných detí z celého Slovenska – detí, ktoré by sa za normálnych okolností možno nikdy nestretli...\",\n \"intro_en\": \"Imagine an enormous orchestra composed of talented children from the whole of Slovakia – children you would never meet under normal circumstances...\",\n \"text\" : \"Predstavte si obrovský orchester zložený z talentovaných detí z celého Slovenska – detí, ktoré by sa za normálnych okoSpojila ich však láska k hudbe, hodiny cvičenia na hudobnom nástroji a možno aj v kútiku duše schovaný sen stať sa niekým, kto sa zapíše do hudobných dejín. Unikátny hudobný projekt VIRTUOSO túto predstavu premieňa na realitu prostredníctvom zapojenia detských a mládežníckych talentov zo základných umeleckých škôl z celého Slovenska do jedného veľkého národného orchestra. Šéfdirigentom orchestra je Igor Dohovič, rodák z Prešova, pod ktorého vedením už národný mládežnícky orchester úspešne absolvoval niekoľko koncertov po celom Slovensku. V orchestri platí pravidlo: „Jeden za všetkých – všetci za lásku ku klasickej hudbe!“ A tá je prudko nákazlivá aj pre všetkých ostatných.

Program:

Henry Purcell (1659-1695): Rondeau zo suity Abdelazer
Antonio Vivaldi (1678-1741): Štyri ročné obdobia – Jar
Antonio Vivaldi: Sinfonia h mol „Al santo sepolcro“, RV 169
Wolfgang Amadeus Mozart (1756-1791): Non più andrai, ária Figara z opery Figarova svadba
Joseph Haydn (1732-1809): Detská symfónia (1. a 3. časť)
Peter Martin: Sovetto
Dmitrij Šostakovič (1906-1975): Valčík zo Suity č. 2
Hubert Giraud (1920): Sous le ciel de Paris
Lucio Dalla (1943-2012): Caruso
Karl William Pamp Jenkins (1944): Palladio
Ennio Morricone (1928): Vtedy na západe
Klaus Badelt (1967): Piráti z Karibiku
Astor Piazzolla (1921-1992): Tango

Národný mládežnícky orchester Virtuoso
Filip Tůma – barytón
Igor Dohovič – dirigent\",\n \"text_en\": \"But what all of them had in common was a love of music, hours of practice on a musical instrument, and maybe in some corner of their minds a dream of becoming someone whose name would be recorded in musical history. The unique musical project VIRTUOSO makes this idea a reality by bringing together talented children and youth from the primary art schools of all Slovakia into one big national orchestra. The chief conductor is Igor Dohovič, a native of Prešov, under whose direction the orchestra has already successfully completed a number of concerts throughout Slovakia. In this orchestra the rule applies: “One for all, and all for the love of classical music!” And that is highly infectious for everyone else.

Program:

Henry Purcell (1659-1695): Rondeau from Abdelazer suite
Antonio Vivaldi (1678-1741): The Four Seasons – Spring
Antonio Vivaldi: Sinfonia b minor „Al santo sepolcro“, RV 169
Wolfgang Amadeus Mozart (1756-1791): Non più andrai, aria of Figaro from The Marriage of Figaro
Joseph Haydn (1732-1809): Children’s Symphony (1st and 3rd mov.)
Peter Martin: Sovetto
Dmitrij Šostakovič (1906-1975): Waltz from Suite No. 2
Hubert Giraud (1920): Sous le ciel de Paris
Lucio Dalla (1943-2012): Caruso
Karl William Pamp Jenkins (1944): Palladio
Ennio Morricone (1928): Once Upon a Time in the West
Klaus Badelt (1967): Pirates of the Caribbean
Astor Piazzolla (1921-1992): Tango

National Youth Orchestra Virtuoso
Filip Tůma – baritone
Igor Dohovič – conductor\",\n \"img\" : \"virtuoso.jpg\",\n \"path\" : \"virtuoso\",\n \"tickets\" : \"\",\n \"price\" : \"Vstup voľný\",\n \"price_en\": \"Entrance free\"\n})\ndb.program.insert({\n \"datenum\" : 24,\n \"datemonth\" : \"jún\",\n \"datemonth\": \"June\",\n \"datetime\" : \"20:00\",\n \"place\" : \"Stará tržnica\",\n \"place_en\": \"Old City Market Hall\",\n \"title\" : \"Quasars Ensemble & Dalibor Karvay\",\n \"title_en\": \"Quasars Ensemble & Dalibor Karvay\",\n \"intro\" : \"Jedinečné spojenie hviezd súčasnej klasiky a husľového virtuóza Dalibora Karvaya.\",\n \"intro_en\": \"A unique alliance of stars of contemporary classical music with the violin virtuoso Dalibor Karvay.\",\n \"text\" : \"Komorné zoskupenie Quasars Ensemble pôsobí na slovenskej hudobnej scéne od roku 2008 a počas šiestich rokov sa vyprovilovalo na medzinárodne uznávaný súbor súčasnej klasickej hudby. Quasars Ensemble založil hudobný skladateľ, klavirista a dirigent Ivan Buffa a výnimočnosťou súboru je okrem iného aj fakt, že popri súčasnej klasickej hudbe sa v rovnakej miere venuje aj hudbe starších epoch. Súbor je pravidelným hosťom významných domácich i zahraničných hudobných festivalov, organizuje vlastné projekty v regiónoch Slovenska, má na konte šesť profilových CD albumov a je držiteľom ocenenia Krištáľové krídlo v kategórii „Hudba“ za rok 2013. Špeciálnym hosťom koncertu bude vynikajúci slovenský huslista Dalibor Karvay, ktorý v sprievode Quasars Ensemble pod taktovkou Ivana Buffu uvedie Waxmanovu verziu melódií z Bizetovej opery Carmen a Ravelovu virtuóznu skladbu Tzigane, ktoré v programe doplní Septet francúzskeho skladateľa s poľskými koreňmi Alexandra Tansmana a Komorná hudba č. 1, op. 24 nemeckého autora Paula Hindemitha.

Program:

Alexandre Tansman (1897-1986): Septet
Maurice Ravel (1875-1937): Tzigane (arr. I. Buffa)
Franz Waxman (1906-1967): Fantázia Carmen (arr. I. Buffa)

* * *

Alexander Moyzes (1906-1984): Divertimento op. 11 (arr. I. Buffa)
Paul Hindemith (1895-1963): Komorná hudba č. 1, op. 24

Dalibor Karvay – husle

Quasars Ensemble:
Andrea Bošková – flauta
Júlia Csíziková – hoboj
Martin Mosorjak – klarinet
Attila Jankó – fagot
István Siket – trúbka
András Kovalcsik – lesný roh
Diana Buffa – klavír
Tamás Schlanger – bicie
Maroš Potokár – 1. husle
Peter Mosorjak – 2. husle
Peter Zwiebel – viola
Andrej Gál – violončelo
Marián Bujňák – kontrabas
Milan Osadský – akordeón

Ivan Buffa – dirigent\",\n \"text_en\": \"The chamber formation Quasars Ensemble has been active on the Slovak music scene since 2008, and in the course of six years has established its profile as an internationally respected formation in contemporary classical music. Quasars Ensemble was founded by the composer, pianist and conductor Ivan Buffa, and one of its exceptional features is that alongside contemporary classical music it also devotes itself in equal measure to the music of earlier epochs. The ensemble is a regular guest at leading music festivals at home and abroad, organises projects of its own in the regions of Slovakia, has six profile CD albums to its credit, and is the holder of the 2013 Crystal Wing Prize in the “Music” category. The concert’s special guest will be the outstanding Slovak violinist Dalibor Karvay, who, accompanied by Quasars Ensemble, will present the Waxman version of melodies from Bizet’s opera Carmen and Ravel’s virtuoso work Tzigane. These will be complemented in the programme by Septet, a work by the French composer (with Polish roots) Alexander Tansman, Divertimento Op. 11 by the Slovak composer Alexander Moyzes, and Chamber Music No. 1, Op. 24 by the German composer Paul Hindemith.

Program:

Alexandre Tansman (1897-1986): Septet
Maurice Ravel (1875-1937): Tzigane (arr. I. Buffa)
Franz Waxman (1906-1967): Carmen Fantasie (arr. I. Buffa)

* * *

Alexander Moyzes (1906-1984): Divertimento Op. 11 (arr. I. Buffa)
Paul Hindemith (1895-1963): Chamber Music No. 1, Op. 24

Dalibor Karvay – violin

Quasars Ensemble:

Andrea Bošková – flute
Júlia Csíziková – oboe
Martin Mosorjak – clarinet
Attila Jankó – bassoon
István Siket – trumpet
András Kovalcsik – French horn
Diana Buffa – piano
Tamás Schlanger – percussions
Maroš Potokár – 1st violin
Peter Mosorjak – 2nd violin
Peter Zwiebel – viola
Andrej Gál – violoncello
Marián Bujňák – double bass
Milan Osadský – accordion

Ivan Buffa – conductor\",\n \"img\" : \"karvay.jpg\",\n \"path\" : \"quasars-ensemble-dalibor-karvay\",\n \"tickets\" : \"http://www.ticketportal.sk/event.aspx?id=19624&idpartner=57\",\n \"price\" : \"\"\n})\ndb.program.insert({\n \"datenum\" : 25,\n \"datemonth\" : \"jún\",\n \"datemonth_en\" : \"June\",\n \"datetime\" : \"20:00\",\n \"place\" : \"Stará tržnica\",\n \"place_en\": \"Old City Market Hall\",\n \"title\" : \"Xavier Sabata & Il Pomo D’Oro\",\n \"title_en\" : \"Xavier Sabata & Il Pomo D’Oro\",\n \"intro\" : \"„Tento projekt patrí k tomu najinteligentnejšiemu a najpozoruhodnejšiemu, čo sa v hudobnom svete zrodilo za posledné roky.“ (Guardian)\",\n \"intro_en\": \"“This project is one of the most intelligent and noteworthy that the music world has produced in recent years.” (Guardian)\",\n \"text\" : \"Španielsky kontratenorista Xavier Sabata vo svojom projekte Händel: Bad Guys odhaľuje svet záporných postáv v Händlových operách a presviedča nás o tom, že baroková opera nemusí byť len o vznešených antických ideáloch. Vďaka svojmu výnimočnému hlasu stvárňuje postavy bezočivých pokrytcov, zlomyseľných tyranov či dokonca obyčajných hlupákov s absolútnym nadhľadom a ľahkosťou. Xavier Sabata pochádza z Barcelony a má za sebou hosťovania na tých najprestížnejších svetových operných a koncertných pódiách. Do Bratislavy príde po prvýkrát so súborom Il pomo d’oro pod vedením huslistu a dirigenta Riccarda Minasiho, ktorý sa špecializuje na tzv. historicky poučenú interpretáciu starej hudby na dobových nástrojoch.

Program:

Georg Friedrich Händel (1685-1759):
Sinfonia B dur, HWV 339, 1. časť
Vo‘ dar pace a un’alma altiera (Tamerlano)
Nella terra, in ciel, nell‘onda (Faramondo)
Concerto grosso G dur, HWV 314
Bel labbro formato (Ottone, re di Germania)
Dover, giustizia, amor (Ariodante)

* * *

Domerò la tua fierezza (Giulio Cesare)
Serenatevi, o luci belle (Teseo)
Se l’inganno sortisce felice (Ariodante)
Sonáta G dur op. 5, č. 4, HWV 399
Così suole a rio vicina (Faramondo)
Voglio stragi, e voglio morte (Teseo)

Xavier Sabata – kontratenor

Il pomo d’oro:
Alfia Bakieva – husle
Boris Begelman – husle
Ester Crazzolara – husle
Anna Fuskova – husle
Daniela Nuzzoli – husle, viola
Enrico Parizzi – viola
Federico Toffano – violoncello
Davide Nava – kontrabas
Maxim Emelyanychev – cembalo

Riccardo Minasi – husle, umelecké vedenie

\",\n \"text_en\": \"In his project Händel: Bad Guys the Spanish countertenor Xavier Sabata uncovers the world of the negative characters in Händel’s operas and persuades us of the fact that baroque opera need not only be about the sublime ideals of antiquity. Making use of his exceptional voice, he creates the characters of ruthless hypocrites, malignant tyrants, and pure-and-simple stupid asses, with absolute clarity and ease. Xavier Sabata comes from Barcelona and has a history of guest appearances on the world’s most prestigious opera and concert stages. He is coming to Bratislava for the first time with Il pomo d’oro ensemble, led by violinist and conductor Riccardo Minasi, who specialises in the so-called historically informed performance of early music on period instruments.

Program:

Georg Friedrich Händel (1685-1759):

Sinfonia B flat major, HWV 339, 1st mov.
Vo‘ dar pace a un’alma altiera (Tamerlano)
Nella terra, in ciel, nell‘onda (Faramondo)
Concerto Grosso G major, HWV 314
Bel labbro formato (Ottone, re di Germania)
Dover, giustizia, amor (Ariodante)

* * *

Domerò la tua fierezza (Giulio Cesare)
Serenatevi, o luci belle (Teseo)
Se l’inganno sortisce felice (Ariodante)
Sonate G major Op. 5, No. 4, HWV 399
Così suole a rio vicina (Faramondo)
Voglio stragi, e voglio morte (Teseo)

Xavier Sabata – countertenor

Il pomo d’oro:

Alfia Bakieva – violin
Boris Begelman – violin
Ester Crazzolara – violin
Anna Fuskova – violin
Daniela Nuzzoli – violin, viola
Enrico Parizzi – viola
Federico Toffano – violoncello
Davide Nava – double bass
Maxim Emelyanychev – cembalo

Riccardo Minasi – violin, conductor

\",\n \"img\" : \"sabata.jpg\",\n \"path\" : \"handel-bad-guys\",\n \"tickets\" : \"http://www.ticketportal.sk/event.aspx?id=19543&idpartner=57\",\n \"price\" : \"\"\n})\ndb.program.insert({\n \"datenum\" : 26,\n \"datemonth\" : \"jún\",\n \"datemonth_en\": \"June\",\n \"datetime\" : \"20:00\",\n \"place\" : \"Stará tržnica\",\n \"place_en\": \"Old City Market Hall\",\n \"title\" : \"Korben Dallas Symphony\",\n \"title_en\" : \"Korben Dallas Symphony\",\n \"intro\" : \"Výnimočný objav slovenskej hudobnej scény v sprievode orchestra na Viva Musica! festivale.\",\n \"intro_en\": \"Underground goes classic!\",\n \"text\" : \"Korben Dallas minulý rok pokrstil svoj druhý album Karnevalová vrana. V éteri bodujú hity Otec, Zlatý jeleň a Beh a po rokoch v hudobnom podzemí sa Korben Dallas stáva mienkotvornou kapelou. Skupinu založili spevák a gitarista Juraj Benetin a basgitarista Lukáš Fila po rozpade skupiny Appendix, v ktorej spolu hrali trinásť rokov. Bubeníkom sa po dlhom hľadaní stal Ozo Guttler zo skupiny Tu v Dome. Kapela debutovala živým albumom Pekné cesty v roku 2011 a má za sebou okrem hrania v rámci niekoľkých hudobných festivalov aj spoločné koncerty s americkou pesničkárkou Jess Klein, spoluprácu s Ľubom Petruškom z Chiki liki tu-a či s Andrejom Šebanom. S orchestrom však Korben Dallas ešte nikdy nehral – v exkluzívnej premiére po prvýkrát na Viva Musica! festivale!

Korben Dallas
Juraj Benetin – spev, gitara
Lukáš Fila – basgitara
Ozo Guttler – bicie

Špeciálny hosť:
Ľubo Petruška – gitara (Chiki liki tu-a)

Sinfonietta Bratislava
Braňo Kostka – dirigent

Slavomír Solovic – aranžmány\",\n \"text_en\": \"Last year Korben Dallas named his second album Carnival Raven. The hit tunes Father, Golden Deer and Run have won favour on the ether, and after years in the musical underground Korben Dallas has become a trend-setting band. The group was founded by singer and guitarist Juraj Benetin and bass guitarist Lukáš Fila after the break-up of Appendix, where they had played together for thirteen years. After much searching, Ozo Guttler from the Here at Home group became the drummer. The band made its debut with the live album Fine Roads in 2011, and apart from playing in a number of music festivals it has also performed concerts together with the American singer Jess Klein and collaborated with Ľuboš Petruška of Chiki liki tu-a and Andrej Šeban. However, up to now Korben Dallas has never played with an orchestra – here it is in an exclusive premiere, first time in the Viva Musica! Festival, under the baton of Braňo Kostka!

Korben Dallas
Juraj Benetin – vocals, guitar
Lukáš Fila – bassguitar
Ozo Guttler – drums

Special guest:
Ľubo Petruška – guitar (Chiki liki tu-a)

Sinfonietta Bratislava
Braňo Kostka – conductor

Slavomír Solovic – arranger\",\n \"img\" : \"korben.jpg\",\n \"path\" : \"korben-dallas-symphony\",\n \"tickets\" : \"http://www.ticketportal.sk/event.aspx?id=19545&idpartner=57\",\n \"price\" : \"\"\n})\ndb.program.insert({\n \"datenum\" : 27,\n \"datemonth\" : \"jún\",\n \"datemonth_en\": \"June\",\n \"datetime\" : \"22:00

24:00 hororová noc v Gorila.sk Urban Space\",\n \"place\" : \"Stará tržnica\",\n \"place_en\": \"Old City Market Hall\",\n \"title\" : \"Upír Nosferatu\",\n \"title_en\": \"Nosferatu\",\n \"intro\" : \"„Keď sa za Hutterom samé od seba zavreli dvere hradu, jeho osud bol spečatený. Mal sa stať prvou svetoznámou obeťou prvého svetoznámeho upíra a ako mu povedal Dr. Sievers: Svojmu osudu neutečiete.“ (www.kinema.sk)\",\n \"intro_en\": \"The legendary silent film with orchestral accompaniment.

24:00 a night of horror in Gorila.sk Urban Space\",\n \"text\" : \"Každý ho pozná, ale málokto ho v súčasnosti naozaj videl. Reč je o klasickom nemeckom nemom filme Upír Nosferatu (Nosferatu, eine Symphonie des Grauens; r. F. W. Murnau, 1922), ktorý už takmer storočie desí obecenstvo na celom svete. Keď sa nemecký expresionista Friedrich Wilhelm Murnau rozhodol natočiť adaptáciu slávneho románu Brama Stokera Dracula netušil, že vytvorí nadčasové dielo, ktoré budú filmoví vedci študovať ešte dlho po jeho smrti, a ktoré položí základy filmového hororu. Mladý úradník realitnej kancelárie Hutter prichádza do Transylvánie na hrad bohatého kupca, grófa Orloka, avšak po jeho návrate už nič nie je tak ako predtým... V rámci Viva Musica! festivalu uvedieme Murnauov film s autorskou hudbou slovenského skladateľa Vladislava Šarišského, laureáta prestížnej Medzinárodnej súťaže Sergeja Prokofieva v Petrohrade a držiteľa Ceny pre mladého tvorcu udeľovanej Nadáciou Tatra banky.

Vladislav „Slnko“ Šarišský – autor hudby, hudobné naštudovanie, theremin

Adam Novák – 1. husle
Ján Kružliak, ml. – 2. husle
Martin Mierny – viola
Boris Bohó – violončelo
Milan Osadský – akordeón
Štefan Bugala – tympany, perkusie

Po koncerte v Starej tržnici pokračujeme hororovou nocou v Gorila.sk Urban Space!

Príďte sa báť po kultovom Draculovi do Gorila.sk Urban Space. 27. júna o 24:00 na Nám. SNP začína hororová noc. Prinesieme vám tri hororové filmy, ktoré vybrali fanúšikovia tohto žánru. Úplne vážne: návštevu odporúčame len tým, ktorí sa neboja!


PROGRAM

Sinister (2012, USA)
V zajatí démonov (2013, USA)
Tucker a Dale vs. Zlo (2010, USA)\",\n \"text_en\": \"Everyone knows of it, but at the present day few have actually seen it. We are referring to the classical German silent film Nosferatu (Nosferatu, eine Symphonie des Grauens; dir. F. W. Murnau, 1922), which for almost a century has been frightening audiences throughout the world. When the German expressionist Friedrich Wilhelm Murnau decided to film an adaptation of Bram Stoker’s famous novel Dracula, he had no idea he was about to create a timeless work which would lay the foundations of film horror and would be studied by scholars of film long after his death. A young clerk of the Hutter estate agency comes to Transylvania to the castle of Count Orlok, a wealthy merchant, but after his return nothing is as it was before... As part of the Viva Musica! Festival we are presenting Murnau’s film with music written by the Slovak composer Vladislav “Sun” Šarišský, laureate of the prestigious international Sergej Prokofiev Competition in St. Petersburg and holder of the Young Artist’s Prize awarded by the Tatra Bank Foundation.

Vladislav „Slnko“ Šarišský – composer, theremin

Adam Novák – 1st violin
Ján Kružliak, ml. – 2nd violin
Martin Mierny – viola
Boris Bohó – violoncello
Milan Osadský – accordion
Štefan Bugala – timpani, percussions

After the concert in the Old City Market Hall, we continue with the night of horror in Gorila.sk Urban Space! At 24:00, June 27, the night of horror begins at SNP Square. We are bringing you three horror films which fans of this genre have selected. Quite seriously: we recommend a visit only to those who aren’t scared!

Programme of the night of horror:

Sinister (2012, USA)
The Conjuring (2013, USA)
Tucker & Dale vs. Evil (2010, USA)\",\n \"img\" : \"nosferatu.jpg\",\n \"path\" : \"upir-nosferatu\",\n \"tickets\" : \"http://www.ticketportal.sk/event.aspx?ID=19546&idpartner=57\",\n \"price\" : \"\"\n})\ndb.program.insert({\n \"datenum\" : 28,\n \"datemonth\" : \"jún\",\n \"datemonth_en\" : \"June\",\n \"datetime\" : \"20:00\",\n \"place\" : \"Bratislavský hrad\",\n \"place_en\": \"Bratislava Castle\",\n \"title\" : \"Viva Opera!\",\n \"title_en\" : \"Viva Opera!\",\n \"intro\" : \"Svetoznáme slovenské operné hviezdy po prvýkrát spolu na jednom pódiu!\",\n \"intro_en\": \"World-famous opera stars together on one stage for the first time!\",\n \"text\" : \"Záverečný koncert 10. ročníka medzinárodného festivalu Viva Musica! bude oslavou opery. Na jednom pódiu sa po prvýkrát spolu stretnú najlepší slovenskí operní sólisti – Adriana Kučerová, Jana Kurucová, Miroslav Dvorský, Dalibor Jenis a Štefan Kocán, ktorí v sprievode Orchestra Viva Musica! pod taktovkou Martina Leginusa, súčasného hudobného riaditeľa a šéfdirigenta pražskej Štátnej opery, uvedú známe i menej známe operné lahôdky z pera takých operných majstrov, akými boli Giuseppe Verdi, Georges Bizet, Gioacchino Rossini či Giacomo Puccini. Viva Opera!

Program:

Gioacchino Rossini (1792-1868):
Barbier zo Sevilly, predohra
Largo al factotum, ária z opery Barbier zo Sevilly
Oh patria!... Di tanti palpiti, ária z opery Tancredi
La calunnia é un venticello, ária z opery Barbier zo Sevilly

Gaetano Donizetti (1797-1848):
Quel guardo il cavaliere, ária z opery Don Pasquale

Giuseppe Verdi (1813-1901):
Lunge da lei... De‘ miei bollenti spiriti, ária z opery La traviata
Propizio ei giunge... Vieni a me, ti benedico, duet z opery Simon Boccanegra
Vanne la tua meta gia vedo... Credo, in un dio crudel, ária z opery Otello
E lui!... desso... l’Infante!... Dio che nell’alma infondere, duet z opery Don Carlos

Arrigo Boito (1842-1918):
Son lo spirito che nega, ária z opery Mefistofeles

Giuseppe Verdi:
Bella figlia dell'amore, kvartet z opery Rigoletto

* * *

Georges Bizet (1838-1875):
Carmen, predohra
Les tringles des sistres tintaient, ária z opery Carmen
Votre toast, je peux vous le rendre, ária z opery Carmen
La fleur que tu m'avais jetée, ária z opery Carmen

Léo Delibes (1836-1891):
Viens, Mallika, les lianes en fleurs... Dôme épais, le jasmin, duet z opery Lakmé

Jacques-François-Fromental-Élie Halévy (1799-1862):
Si la rigueur et la vengeance, ária z opery Židovka

Léo Delibes:
Les filles de Cadix

Adriana Kučerová – soprán
Jana Kurucová – mezzosoprán
Miroslav Dvorský – tenor
Dalibor Jenis – barytón
Štefan Kocán – bas

Orchester Viva Musica!

Martin Leginus – dirigent\",\n \"text_en\": \" The concluding concert of the 10th annual international Viva Musica! Festival will be a celebration of opera. For the first time the finest Slovak opera soloists will meet on the same stage. Adriana Kučerová, Jana Kurucová, Miroslav Dvorský, Dalibor Jenis and Štefan Kocán, accompanied by the Orchestra Viva Musica! under the baton of Martin Leginus, musical director and chief conductor of the Prague State Opera, will perform well-known and less well-known delights of opera, composed by such masters as Giuseppe Verdi, Georges Bizet, Gioacchino Rossini, and Giacomo Puccini. Viva opera!.

Program:

Gioacchino Rossini (1792-1868):
The Barber of Seville, overture
Largo al factotum, aria from The Barber of Seville
Oh patria!... Di tanti palpiti, aria from Tancredi
La calunnia é un venticello, aria from The Barber of Seville

Gaetano Donizetti (1797-1848):
Quel guardo il cavaliere, aria from Don Pasquale

Giuseppe Verdi (1813-1901):
Lunge da lei... De‘ miei bollenti spiriti, aria from La traviata
Propizio ei giunge... Vieni a me, ti benedico, duet from Simon Boccanegra
Vanne la tua meta gia vedo... Credo, in un dio crudel, aria from Otello
E lui!... desso... l’Infante!... Dio che nell’alma infondere, duet from Don Carlos

Arrigo Boito (1842-1918):
Son lo spirito che nega, aria from Mefistofele

Giuseppe Verdi:
Bella figlia dell'amore, quartet from Rigoletto

* * *

Georges Bizet (1838-1875):
Carmen, overture
Les tringles des sistres tintaient, aria from Carmen
Votre toast, je peux vous le rendre, aria from Carmen
La fleur que tu m'avais jetée, aria from Carmen

Léo Delibes (1836-1891):
Viens, Mallika, les lianes en fleurs... Dôme épais, le jasmin, duet from Lakmé

Jacques-François-Fromental-Élie Halévy (1799-1862):
Si la rigueur et la vengeance, aria from La Juive

Léo Delibes:
Les filles de Cadix

Adriana Kučerová – soprano
Jana Kurucová – mezzosoprano
Miroslav Dvorský – tenor
Dalibor Jenis – baritone
Štefan Kocán – bass

Viva Musica! orchestra
Martin Leginus – conductor\",\n \"img\" : \"opera.jpg\",\n \"path\" : \"viva-opera\",\n \"tickets\" : \"http://www.ticketportal.sk/event.aspx?id=19471&idpartner=57\",\n \"price\" : \"\"\n})\n"},"message":{"kind":"string","value":"DB update\n"},"old_file":{"kind":"string","value":"mongosave.js"},"subject":{"kind":"string","value":"DB update"},"git_diff":{"kind":"string","value":"ongosave.js\n \"title_en\": \"A Midsummer Night’s Dream\",\n \"intro\" : \"Otvárací koncert 10. ročníka Viva Musica! festivalu a Kultúrneho leta a Hradných slávností Bratislava 2014\",\n \"intro_en\": \"Opening concert in the 10th annual Viva Musica! Festival and Bratislava Cultural Summer and Castle Festival 2014\",\n \"text\" : \"Viva Musica! festival v roku 2014 oslavuje okrúhle 10. narodeniny a svojim návštevníkom opäť ponúkne niekoľko exkluzívnych hudobných zážitkov. V rámci otváracieho koncertu uvedieme v spolupráci s medzinárodným festivalom Letné shakespearovské slávnosti a Kultúrne leto a hradné slávnosti Bratislava 2014 Shakespearovu romantickú komédiu Sen noci svätojánskej s rovnomennou scénickou hudbou nemeckého hudobného skladateľa Felixa Mendelssohna-Bartholdyho (1809-1847). Shakespearov text ožije v podaní Sabiny Laurinovej, Oldřicha Víznera a Csongora Kassaia v sprievode Mendelssohnovej hudby interpretovanej Slovenskou filharmóniou pod vedením Leoša Svárovského. Viva Shakespeare!

Realizačný tím:

Preklad: Martin Hilský, Ľubomír Feldek
Dramaturgia a réžia: Róbert Mankovecký
Producent za LSS: Janka Zednikovičová

Účinkujú:

Oberon – Oldřich Vízner
Titania – Sabina Laurinová
Puk – Csongor Kassai
Klbko – Peter Kadlečík
Väzba – Jakub Rybárik

Petronela Drobná – soprán
Katarína Kubovičová-Sroková – alt
Ženský spevácky zbor
Jozef Chabroň – zbormajster

Slovenská filharmónia
Leoš Svárovský – dirigent\",\n \"text_en\": \"In 2014 the Viva Musica! Festival celebrates its 10th birthday and again offers its visitors some exquisite musical delights. In collaboration with the international Summer Shakespeare Festival, Bratislava Cultural Summer and Castle Festival 2014, our opening concert presents Shakespeare’s romantic comedy A Midsummer Night’s Dream with the identically-named music by the German composer Felix Mendelssohn-Bartholdy (1809-1847). Shakespeare’s text is vividly rendered by Sabina Laurinová, Oldřich Vízner and Csongor Kassai, accompanied by Mendelssohn’s music performed by the Slovak Philharmonic and members of the Slovak Philharmonic Choir conducted by Leoš Svárovský. Viva Shakespeare!

Production team:

Translators: Martin Hilský, Ľubomír Feldek
Dramaturge and director: Róbert Mankovecký
Producer for SSF: Janka Zednikovičová

Performers:

Oberon – Oldřich Vízner
Titania – Sabina Laurinová
Puck – Csongor Kassai
Bottom – Peter Kadlečík
Quince – Jakub Rybárik

Petronela Drobná – soprano
Katarína Kubovičová-Sroková – alto
Members of the Slovak Philharmonic Choir
Jozef Chabroň –choirmaster

Slovak Philharmonic
Leoš Svárovský – conductor\",\n \"text\" : \"Viva Musica! festival v roku 2014 oslavuje okrúhle 10. narodeniny a svojim návštevníkom opäť ponúkne niekoľko exkluzívnych hudobných zážitkov. V rámci otváracieho koncertu uvedieme v spolupráci s medzinárodným festivalom Letné shakespearovské slávnosti a Kultúrne leto a hradné slávnosti Bratislava 2014 Shakespearovu romantickú komédiu Sen noci svätojánskej s rovnomennou scénickou hudbou nemeckého hudobného skladateľa Felixa Mendelssohna-Bartholdyho (1809-1847). Shakespearov text ožije v podaní Sabiny Laurinovej, Oldřicha Víznera a Csongora Kassaia v sprievode Mendelssohnovej hudby interpretovanej Slovenskou filharmóniou pod vedením Leoša Svárovského. Viva Shakespeare!

Realizačný tím:

Preklad: Martin Hilský, Ľubomír Feldek
Dramaturgia a réžia: Róbert Mankovecký
Producent za LSS: Janka Zednikovičová

Účinkujú:

Oberon – Oldřich Vízner
Titania – Sabina Laurinová
Puk – Csongor Kassai
Klbko – Peter Kadlečík
Väzba – Jakub Rybárik

Petronela Drobná – soprán
Katarína Kubovičová-Sroková – alt
Ženský spevácky zbor
Jozef Chabroň – zbormajster

Slovenská filharmónia
Leoš Svárovský – dirigent\",\n \"text_en\": \"In 2014 the Viva Musica! Festival celebrates its 10th birthday and again offers its visitors some exquisite musical delights. In collaboration with the international Summer Shakespeare Festival, Bratislava Cultural Summer and Castle Festival 2014, our opening concert presents Shakespeare’s romantic comedy A Midsummer Night’s Dream with the identically-named music by the German composer Felix Mendelssohn-Bartholdy (1809-1847). Shakespeare’s text is vividly rendered by Sabina Laurinová, Oldřich Vízner and Csongor Kassai, accompanied by Mendelssohn’s music performed by the Slovak Philharmonic and members of the Slovak Philharmonic Choir conducted by Leoš Svárovský. Viva Shakespeare!

Production team:

Translators: Martin Hilský, Ľubomír Feldek
Dramaturge and director: Róbert Mankovecký
Producer for SSF: Janka Zednikovičová

Performers:

Oberon – Oldřich Vízner
Titania – Sabina Laurinová
Puck – Csongor Kassai
Bottom – Peter Kadlečík
Quince – Jakub Rybárik

Petronela Drobná – soprano
Katarína Kubovičová-Sroková – alto
Members of the Slovak Philharmonic Choir
Jozef Chabroň – choirmaster

Slovak Philharmonic
Leoš Svárovský – conductor\",\n \"img\" : \"sen.jpg\",\n \"path\" : \"sen-noci-svatojanskej\",\n \"tickets\" : \"\","}}},{"rowIdx":859,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"0c75a95e67e6ea5662ebc6a6472895f0b1ee699c"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"TechCavern/WaveTact"},"new_contents":{"kind":"string","value":"package com.techcavern.wavetact.utils;\n\nimport com.google.common.io.Files;\nimport com.techcavern.wavetact.annot.ConCMD;\nimport com.techcavern.wavetact.objects.NetProperty;\nimport org.jooq.Record;\nimport org.pircbotx.Colors;\nimport com.techcavern.wavetact.annot.IRCCMD;\nimport com.techcavern.wavetact.objects.ConsoleCommand;\nimport com.techcavern.wavetact.objects.IRCCommand;\nimport org.flywaydb.core.Flyway;\nimport org.jooq.DSLContext;\nimport org.jooq.SQLDialect;\nimport org.jooq.impl.DSL;\nimport org.pircbotx.PircBotX;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.lang.reflect.Field;\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.util.Scanner;\nimport java.util.Set;\nimport java.util.concurrent.TimeUnit;\n\nimport static com.techcavern.wavetactdb.Tables.BANS;\n\npublic class LoadUtils {\n\n public static void initiateDatabaseConnection() throws Exception {\n Flyway flyway = new Flyway();\n flyway.setDataSource(\"jdbc:sqlite:./db.sqlite\", null, null);\n flyway.migrate();\n System.err.println(\"Getting connection...\");\n Class.forName(\"org.sqlite.JDBC\");\n Connection conn = DriverManager.getConnection(\"jdbc:sqlite:./db.sqlite\");\n System.err.println(\"Creating DSLContext...\");\n Registry.WaveTactDB = DSL.using(conn, SQLDialect.SQLITE);\n Registry.wundergroundapikey = DatabaseUtils.getConfig(\"wundergroundapikey\");\n Registry.wolframalphaapikey = DatabaseUtils.getConfig(\"wolframalphaapikey\");\n Registry.wordnikapikey = DatabaseUtils.getConfig(\"wordnikapikey\");\n Registry.googleapikey = DatabaseUtils.getConfig(\"googleapikey\");\n }\n\n public static void registerIRCCommands() {\n Set> classes = Registry.wavetactreflection.getTypesAnnotatedWith(IRCCMD.class);\n for (Class clss : classes) {\n try {\n Registry.IRCCommands.add(((IRCCommand) clss.newInstance()));\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n }\n\n public static void registerConsoleCommands() {\n Set> classes = Registry.wavetactreflection.getTypesAnnotatedWith(ConCMD.class);\n for (Class clss : classes) {\n try {\n Registry.ConsoleCommands.add(((ConsoleCommand) clss.newInstance()));\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n }\n\n public static void registerAttacks() {\n Registry.Attacks.add(\"sends a 53 inch monitor flying at $*\");\n Registry.Attacks.add(\"shoots a rocket at $*\");\n Registry.Attacks.add(\"punches $* right in the crotch\");\n Registry.Attacks.add(\"packs $* up and ships it off to another galaxy\");\n Registry.Attacks.add(\"eats $* up for breakfast\");\n Registry.Attacks.add(\"sends a flying desk at $*\");\n Registry.Attacks.add(\"swallows $* whole\");\n Registry.Attacks.add(\"ties $* up and feeds it to a shark\");\n Registry.Attacks.add(\"runs over $* with a car\");\n Registry.Attacks.add(\"throws a racket at $*\");\n Registry.Attacks.add(\"gobbles up $*\");\n Registry.Attacks.add(\"throws a 2000 pound object at $*\");\n Registry.Attacks.add(\"starts throwing punches at $*\");\n Registry.Attacks.add(\"sends a flying dragon at $*\");\n Registry.Attacks.add(\"takes over $*'s computers and blasts porn at full volume\");\n Registry.Attacks.add(\"packs $* up and ships them off to Apple\");\n Registry.Attacks.add(\"hands $* off to Lord Voldemort\");\n Registry.Attacks.add(\"hands $* off to a pack of a wolves\");\n Registry.Attacks.add(\"hands $* off to a herd of centaurs\");\n Registry.Attacks.add(\"drops $* off to a 2000 kilometer cliff\");\n Registry.Attacks.add(\"flies $* out into the middle of nowhere\");\n Registry.Attacks.add(\"hunts $* down with a gun\");\n Registry.Attacks.add(\"slaps $* around with a large trout\");\n Registry.Attacks.add(\"throws iphones at $*\");\n Registry.Attacks.add(\"fires missile at $*\");\n Registry.Attacks.add(\"puts $* in a rocket and sends them off to pluto\");\n Registry.Attacks.add(\"forcefeeds $* a plate of poisoned beef\");\n Registry.Attacks.add(\"mind controls $* to marry Dolores Umbridge\");\n Registry.Attacks.add(\"throws poorly written code at $*\");\n Registry.Attacks.add(\"throws knives at $*\");\n Registry.Attacks.add(\"throws various objects at $*\");\n Registry.Attacks.add(\"throws rocks at $*\");\n Registry.Attacks.add(\"throws grenades at $*\");\n Registry.Attacks.add(\"throws IE6 at $*\");\n Registry.Attacks.add(\"throws axes at $*\");\n Registry.Attacks.add(\"throws evil things at $*\");\n Registry.Attacks.add(\"throws netsplits at $*\");\n Registry.Attacks.add(\"throws hammers at $*\");\n Registry.Attacks.add(\"throws spears at $*\");\n Registry.Attacks.add(\"throws spikes at $*\");\n Registry.Attacks.add(\"throws $* into a burning building\");\n Registry.Attacks.add(\"throws sharp things at $*\");\n Registry.Attacks.add(\"throws moldy bread at $*\");\n Registry.Attacks.add(\"throws mojibake at $*\");\n Registry.Attacks.add(\"throws floppy disks at $*\");\n Registry.Attacks.add(\"throws nails at $*\");\n Registry.Attacks.add(\"throws burning planets at $*\");\n Registry.Attacks.add(\"throws thorns at $*\");\n Registry.Attacks.add(\"throws skulls at $*\");\n Registry.Attacks.add(\"throws a fresh, unboxed copy of Windows Me at $*\");\n Registry.Attacks.add(\"casts fire at $*\");\n Registry.Attacks.add(\"casts ice at $*\");\n Registry.Attacks.add(\"casts death at $*\");\n Registry.Attacks.add(\"casts \" + Colors.BOLD + \"DEATH\" + Colors.BOLD + \" at $*\");\n Registry.Attacks.add(\"casts poison at $*\");\n Registry.Attacks.add(\"casts stupid at $*\");\n Registry.Attacks.add(\"attacks $* with knives\");\n Registry.Attacks.add(\"attacks $* with idiots from #freenode\");\n Registry.Attacks.add(\"attacks $* with an army of trolls\");\n Registry.Attacks.add(\"attacks $* with oper abuse\");\n Registry.Attacks.add(\"attacks $* with confusingly bad english\");\n Registry.Attacks.add(\"attacks $* with Windows Me\");\n Registry.Attacks.add(\"attacks $* with Quicktime for Windows\");\n Registry.Attacks.add(\"attacks $* with ???\");\n Registry.Attacks.add(\"attacks $* with segmentation faults\");\n Registry.Attacks.add(\"attacks $* with relentless spyware\");\n Registry.Attacks.add(\"attacks $* with NSA spies\");\n Registry.Attacks.add(\"attacks $* with tracking devices\");\n Registry.Attacks.add(\"attacks $* with a botnet\");\n }\n\n public static void registerEightball() {\n Registry.Eightball.add(\"Hmm.. not today\");\n Registry.Eightball.add(\"YES!\");\n Registry.Eightball.add(\"Maybe\");\n Registry.Eightball.add(\"Nope.\");\n Registry.Eightball.add(\"Sources say no.\");\n Registry.Eightball.add(\"Definitely\");\n Registry.Eightball.add(\"I have my doubts\");\n Registry.Eightball.add(\"Signs say yes\");\n Registry.Eightball.add(\"Cannot predict now\");\n Registry.Eightball.add(\"It is certain\");\n Registry.Eightball.add(\"Sure\");\n Registry.Eightball.add(\"Outlook decent\");\n Registry.Eightball.add(\"Very doubtful\");\n Registry.Eightball.add(\"Perhaps now is not a good time to tell you\");\n Registry.Eightball.add(\"Concentrate and ask again\");\n Registry.Eightball.add(\"Forget about it\");\n Registry.Eightball.add(\"Don't count on it\");\n }\n\n public static void addDir(String s) throws IOException {\n try {\n Field field = ClassLoader.class.getDeclaredField(\"usr_paths\");\n field.setAccessible(true);\n String[] paths = (String[]) field.get(null);\n for (String path : paths) {\n if (s.equals(path)) {\n return;\n }\n }\n String[] tmp = new String[paths.length + 1];\n System.arraycopy(paths, 0, tmp, 0, paths.length);\n tmp[paths.length] = s;\n field.set(null, tmp);\n System.setProperty(\"java.library.path\", System.getProperty(\"java.library.path\") + File.pathSeparator + s);\n } catch (IllegalAccessException e) {\n throw new IOException(\"Failed to get permissions to set library path\");\n } catch (NoSuchFieldException e) {\n throw new IOException(\"Failed to get field handle to set library path\");\n }\n }\n public static void initializeMessageQueue(){\n for(NetProperty network:Registry.NetworkName) {\n class MessageQueue implements Runnable {\n @Override\n public void run() {\n try {\n TimeUnit.SECONDS.sleep(30);\n } catch (InterruptedException c) {\n }\n while (true) {\n try {\n if (Registry.MessageQueue.size() > 0 && network.getNetwork().equals(Registry.MessageQueue.get(0).getNetwork())) {\n Registry.MessageQueue.get(0).getNetwork().sendRaw().rawLine(Registry.MessageQueue.get(0).getProperty());\n Registry.MessageQueue.remove(0);\n TimeUnit.MILLISECONDS.sleep(900);\n }\n TimeUnit.MILLISECONDS.sleep(100);\n } catch (Exception e) {\n }\n }\n }\n\n }\n Registry.threadPool.execute(new MessageQueue());\n }\n\n }\n public static void initalizeBanQueue() {\n class BanQueue implements Runnable {\n\n @Override\n public void run() {\n try {\n TimeUnit.SECONDS.sleep(120);\n } catch (InterruptedException c) {\n // ignored\n }\n while (true) {\n try {\n for (Record banRecord : DatabaseUtils.getBans()) {\n try {\n if (System.currentTimeMillis() >= banRecord.getValue(BANS.TIME) + banRecord.getValue(BANS.INIT)) {\n PircBotX networkObject = IRCUtils.getBotByNetworkName(banRecord.getValue(BANS.NETWORK));\n IRCUtils.setMode(IRCUtils.getChannelbyName(networkObject, banRecord.getValue(BANS.CHANNEL)), networkObject, \"-\" + banRecord.getValue(BANS.PROPERTY), banRecord.getValue(BANS.HOSTMASK));\n DatabaseUtils.removeBan(banRecord.getValue(BANS.NETWORK), banRecord.getValue(BANS.CHANNEL), banRecord.getValue(BANS.HOSTMASK), banRecord.getValue(BANS.ISMUTE));\n }\n } catch (IllegalArgumentException | NullPointerException e) {\n // ignored\n }\n }\n TimeUnit.SECONDS.sleep(120);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n }\n }\n Registry.threadPool.execute(new BanQueue());\n }\n}\n"},"new_file":{"kind":"string","value":"src/main/java/com/techcavern/wavetact/utils/LoadUtils.java"},"old_contents":{"kind":"string","value":"package com.techcavern.wavetact.utils;\n\nimport com.google.common.io.Files;\nimport com.techcavern.wavetact.annot.ConCMD;\nimport com.techcavern.wavetact.objects.NetProperty;\nimport org.jooq.Record;\nimport org.pircbotx.Colors;\nimport com.techcavern.wavetact.annot.IRCCMD;\nimport com.techcavern.wavetact.objects.ConsoleCommand;\nimport com.techcavern.wavetact.objects.IRCCommand;\nimport org.flywaydb.core.Flyway;\nimport org.jooq.DSLContext;\nimport org.jooq.SQLDialect;\nimport org.jooq.impl.DSL;\nimport org.pircbotx.PircBotX;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.lang.reflect.Field;\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.util.Scanner;\nimport java.util.Set;\nimport java.util.concurrent.TimeUnit;\n\nimport static com.techcavern.wavetactdb.Tables.BANS;\n\npublic class LoadUtils {\n\n public static void initiateDatabaseConnection() throws Exception {\n Flyway flyway = new Flyway();\n flyway.setDataSource(\"jdbc:sqlite:./db.sqlite\", null, null);\n flyway.migrate();\n System.err.println(\"Getting connection...\");\n Class.forName(\"org.sqlite.JDBC\");\n Connection conn = DriverManager.getConnection(\"jdbc:sqlite:./db.sqlite\");\n System.err.println(\"Creating DSLContext...\");\n Registry.WaveTactDB = DSL.using(conn, SQLDialect.SQLITE);\n Registry.wundergroundapikey = DatabaseUtils.getConfig(\"wundergroundapikey\");\n Registry.wolframalphaapikey = DatabaseUtils.getConfig(\"wolframalphaapikey\");\n Registry.wordnikapikey = DatabaseUtils.getConfig(\"wordnikapikey\");\n Registry.googleapikey = DatabaseUtils.getConfig(\"googleapikey\");\n }\n\n public static void registerIRCCommands() {\n Set> classes = Registry.wavetactreflection.getTypesAnnotatedWith(IRCCMD.class);\n for (Class clss : classes) {\n try {\n Registry.IRCCommands.add(((IRCCommand) clss.newInstance()));\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n }\n\n public static void registerConsoleCommands() {\n Set> classes = Registry.wavetactreflection.getTypesAnnotatedWith(ConCMD.class);\n for (Class clss : classes) {\n try {\n Registry.ConsoleCommands.add(((ConsoleCommand) clss.newInstance()));\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n }\n\n public static void registerAttacks() {\n Registry.Attacks.add(\"sends a 53 inch monitor flying at $*\");\n Registry.Attacks.add(\"shoots a rocket at $*\");\n Registry.Attacks.add(\"punches $* right in the crotch\");\n Registry.Attacks.add(\"packs $* up and ships it off to another galaxy\");\n Registry.Attacks.add(\"eats $* up for breakfast\");\n Registry.Attacks.add(\"sends a flying desk at $*\");\n Registry.Attacks.add(\"swallows $* whole\");\n Registry.Attacks.add(\"ties $* up and feeds it to a shark\");\n Registry.Attacks.add(\"runs over $* with a car\");\n Registry.Attacks.add(\"throws a racket at $*\");\n Registry.Attacks.add(\"gobbles up $*\");\n Registry.Attacks.add(\"throws a 2000 pound object at $*\");\n Registry.Attacks.add(\"starts throwing punches at $*\");\n Registry.Attacks.add(\"sends a flying dragon at $*\");\n Registry.Attacks.add(\"takes over $*'s computers and blasts porn at full volume\");\n Registry.Attacks.add(\"packs $* up and ships them off to Apple\");\n Registry.Attacks.add(\"hands $* off to Lord Voldemort\");\n Registry.Attacks.add(\"hands $* off to a pack of a wolves\");\n Registry.Attacks.add(\"hands $* off to a herd of centaurs\");\n Registry.Attacks.add(\"drops $* off to a 2000 kilometer cliff\");\n Registry.Attacks.add(\"flies $* out into the middle of nowhere\");\n Registry.Attacks.add(\"hunts $* down with a gun\");\n Registry.Attacks.add(\"slaps $* around with a large trout\");\n Registry.Attacks.add(\"throws iphones at $*\");\n Registry.Attacks.add(\"fires missile at $*\");\n Registry.Attacks.add(\"puts $* in a rocket and sends them off to pluto\");\n Registry.Attacks.add(\"forcefeeds $* a plate of poisoned beef\");\n Registry.Attacks.add(\"mind controls $* to marry Dolores Umbridge\");\n Registry.Attacks.add(\"throws poorly written code at $*\");\n Registry.Attacks.add(\"throws knives at $*\");\n Registry.Attacks.add(\"throws various objects at $*\");\n Registry.Attacks.add(\"throws rocks at $*\");\n Registry.Attacks.add(\"throws grenades at $*\");\n Registry.Attacks.add(\"throws IE6 at $*\");\n Registry.Attacks.add(\"throws axes at $*\");\n Registry.Attacks.add(\"throws evil things at $*\");\n Registry.Attacks.add(\"throws netsplits at $*\");\n Registry.Attacks.add(\"throws hammers at $*\");\n Registry.Attacks.add(\"throws spears at $*\");\n Registry.Attacks.add(\"throws spikes at $*\");\n Registry.Attacks.add(\"throws sharp things at $*\");\n Registry.Attacks.add(\"throws moldy bread at $*\");\n Registry.Attacks.add(\"throws mojibake at $*\");\n Registry.Attacks.add(\"throws floppy disks at $*\");\n Registry.Attacks.add(\"throws nails at $*\");\n Registry.Attacks.add(\"throws burning planets at $*\");\n Registry.Attacks.add(\"throws thorns at $*\");\n Registry.Attacks.add(\"throws skulls at $*\");\n Registry.Attacks.add(\"throws a fresh, unboxed copy of Windows Me at $*\");\n Registry.Attacks.add(\"casts fire at $*\");\n Registry.Attacks.add(\"casts ice at $*\");\n Registry.Attacks.add(\"casts death at $*\");\n Registry.Attacks.add(\"casts \" + Colors.BOLD + \"DEATH\" + Colors.BOLD + \" at $*\");\n Registry.Attacks.add(\"casts poison at $*\");\n Registry.Attacks.add(\"casts stupid at $*\");\n Registry.Attacks.add(\"attacks $* with knives\");\n Registry.Attacks.add(\"attacks $* with idiots from #freenode\");\n Registry.Attacks.add(\"attacks $* with an army of trolls\");\n Registry.Attacks.add(\"attacks $* with oper abuse\");\n Registry.Attacks.add(\"attacks $* with confusingly bad english\");\n Registry.Attacks.add(\"attacks $* with Windows Me\");\n Registry.Attacks.add(\"attacks $* with Quicktime for Windows\");\n Registry.Attacks.add(\"attacks $* with ???\");\n Registry.Attacks.add(\"attacks $* with segmentation faults\");\n Registry.Attacks.add(\"attacks $* with relentless spyware\");\n Registry.Attacks.add(\"attacks $* with NSA spies\");\n Registry.Attacks.add(\"attacks $* with tracking devices\");\n Registry.Attacks.add(\"attacks $* with a botnet\");\n }\n\n public static void registerEightball() {\n Registry.Eightball.add(\"Hmm.. not today\");\n Registry.Eightball.add(\"YES!\");\n Registry.Eightball.add(\"Maybe\");\n Registry.Eightball.add(\"Nope.\");\n Registry.Eightball.add(\"Sources say no.\");\n Registry.Eightball.add(\"Definitely\");\n Registry.Eightball.add(\"I have my doubts\");\n Registry.Eightball.add(\"Signs say yes\");\n Registry.Eightball.add(\"Cannot predict now\");\n Registry.Eightball.add(\"It is certain\");\n Registry.Eightball.add(\"Sure\");\n Registry.Eightball.add(\"Outlook decent\");\n Registry.Eightball.add(\"Very doubtful\");\n Registry.Eightball.add(\"Perhaps now is not a good time to tell you\");\n Registry.Eightball.add(\"Concentrate and ask again\");\n Registry.Eightball.add(\"Forget about it\");\n Registry.Eightball.add(\"Don't count on it\");\n }\n\n public static void addDir(String s) throws IOException {\n try {\n Field field = ClassLoader.class.getDeclaredField(\"usr_paths\");\n field.setAccessible(true);\n String[] paths = (String[]) field.get(null);\n for (String path : paths) {\n if (s.equals(path)) {\n return;\n }\n }\n String[] tmp = new String[paths.length + 1];\n System.arraycopy(paths, 0, tmp, 0, paths.length);\n tmp[paths.length] = s;\n field.set(null, tmp);\n System.setProperty(\"java.library.path\", System.getProperty(\"java.library.path\") + File.pathSeparator + s);\n } catch (IllegalAccessException e) {\n throw new IOException(\"Failed to get permissions to set library path\");\n } catch (NoSuchFieldException e) {\n throw new IOException(\"Failed to get field handle to set library path\");\n }\n }\n public static void initializeMessageQueue(){\n for(NetProperty network:Registry.NetworkName) {\n class MessageQueue implements Runnable {\n @Override\n public void run() {\n try {\n TimeUnit.SECONDS.sleep(30);\n } catch (InterruptedException c) {\n }\n while (true) {\n try {\n if (Registry.MessageQueue.size() > 0 && network.getNetwork().equals(Registry.MessageQueue.get(0).getNetwork())) {\n Registry.MessageQueue.get(0).getNetwork().sendRaw().rawLine(Registry.MessageQueue.get(0).getProperty());\n Registry.MessageQueue.remove(0);\n TimeUnit.MILLISECONDS.sleep(900);\n }\n TimeUnit.MILLISECONDS.sleep(100);\n } catch (Exception e) {\n }\n }\n }\n\n }\n Registry.threadPool.execute(new MessageQueue());\n }\n\n }\n public static void initalizeBanQueue() {\n class BanQueue implements Runnable {\n\n @Override\n public void run() {\n try {\n TimeUnit.SECONDS.sleep(120);\n } catch (InterruptedException c) {\n // ignored\n }\n while (true) {\n try {\n for (Record banRecord : DatabaseUtils.getBans()) {\n try {\n if (System.currentTimeMillis() >= banRecord.getValue(BANS.TIME) + banRecord.getValue(BANS.INIT)) {\n PircBotX networkObject = IRCUtils.getBotByNetworkName(banRecord.getValue(BANS.NETWORK));\n IRCUtils.setMode(IRCUtils.getChannelbyName(networkObject, banRecord.getValue(BANS.CHANNEL)), networkObject, \"-\" + banRecord.getValue(BANS.PROPERTY), banRecord.getValue(BANS.HOSTMASK));\n DatabaseUtils.removeBan(banRecord.getValue(BANS.NETWORK), banRecord.getValue(BANS.CHANNEL), banRecord.getValue(BANS.HOSTMASK), banRecord.getValue(BANS.ISMUTE));\n }\n } catch (IllegalArgumentException | NullPointerException e) {\n // ignored\n }\n }\n TimeUnit.SECONDS.sleep(120);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n }\n }\n Registry.threadPool.execute(new BanQueue());\n }\n}\n"},"message":{"kind":"string","value":"Adds an attack (Resolves #63)\n"},"old_file":{"kind":"string","value":"src/main/java/com/techcavern/wavetact/utils/LoadUtils.java"},"subject":{"kind":"string","value":"Adds an attack (Resolves #63)"},"git_diff":{"kind":"string","value":"rc/main/java/com/techcavern/wavetact/utils/LoadUtils.java\n Registry.Attacks.add(\"throws hammers at $*\");\n Registry.Attacks.add(\"throws spears at $*\");\n Registry.Attacks.add(\"throws spikes at $*\");\n Registry.Attacks.add(\"throws $* into a burning building\");\n Registry.Attacks.add(\"throws sharp things at $*\");\n Registry.Attacks.add(\"throws moldy bread at $*\");\n Registry.Attacks.add(\"throws mojibake at $*\");"}}},{"rowIdx":860,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"9ba9524bb45e527da91d074d1d9209797f292009"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"apache/syncope,ilgrosso/syncope,ilgrosso/syncope,ilgrosso/syncope,apache/syncope,apache/syncope,apache/syncope,ilgrosso/syncope"},"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.syncope.client.console.rest;\n\nimport java.util.List;\nimport java.util.Optional;\nimport org.apache.syncope.common.lib.to.PagedResult;\nimport org.apache.syncope.common.lib.to.UserRequest;\nimport org.apache.syncope.common.lib.to.UserRequestForm;\nimport org.apache.syncope.common.rest.api.beans.UserRequestFormQuery;\nimport org.apache.syncope.common.rest.api.beans.UserRequestQuery;\nimport org.apache.wicket.extensions.markup.html.repeater.util.SortParam;\nimport org.apache.syncope.common.rest.api.service.UserRequestService;\n\npublic class UserRequestRestClient extends BaseRestClient {\n\n private static final long serialVersionUID = -4785231164900813921L;\n\n public static int countUserRequests() {\n return getService(UserRequestService.class).\n list(new UserRequestQuery.Builder().page(1).size(0).build()).\n getTotalCount();\n }\n\n public static List getUserRequests(final int page, final int size, final SortParam sort) {\n return getService(UserRequestService.class).\n list(new UserRequestQuery.Builder().page(page).size(size).orderBy(toOrderBy(sort)).build()).\n getResult();\n }\n\n public static void cancelRequest(final String executionId, final String reason) {\n getService(UserRequestService.class).cancel(executionId, reason);\n }\n\n public static int countForms() {\n return getService(UserRequestService.class).\n getForms(new UserRequestFormQuery.Builder().page(1).size(0).build()).\n getTotalCount();\n }\n\n public static List getForms(final int page, final int size, final SortParam sort) {\n return getService(UserRequestService.class).\n getForms(new UserRequestFormQuery.Builder().page(page).size(size).orderBy(toOrderBy(sort)).build()).\n getResult();\n }\n\n public static Optional getForm(final String userKey) {\n PagedResult forms = getService(UserRequestService.class).\n getForms(new UserRequestFormQuery.Builder().user(userKey).page(1).size(1).build());\n UserRequestForm form = forms.getResult().isEmpty()\n ? null\n : forms.getResult().get(0);\n return Optional.ofNullable(form);\n }\n\n public static UserRequestForm claimForm(final String taskKey) {\n return getService(UserRequestService.class).claimForm(taskKey);\n }\n\n public static UserRequestForm unclaimForm(final String taskKey) {\n return getService(UserRequestService.class).unclaimForm(taskKey);\n }\n\n public static void submitForm(final UserRequestForm form) {\n getService(UserRequestService.class).submitForm(form);\n }\n}\n"},"new_file":{"kind":"string","value":"ext/flowable/client-console/src/main/java/org/apache/syncope/client/console/rest/UserRequestRestClient.java"},"old_contents":{"kind":"string","value":"/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\npackage org.apache.syncope.client.console.rest;\n\nimport java.util.List;\nimport java.util.Optional;\nimport org.apache.syncope.common.lib.to.PagedResult;\nimport org.apache.syncope.common.lib.to.UserRequest;\nimport org.apache.syncope.common.lib.to.UserRequestForm;\nimport org.apache.syncope.common.rest.api.beans.UserRequestFormQuery;\nimport org.apache.syncope.common.rest.api.beans.UserRequestQuery;\nimport org.apache.wicket.extensions.markup.html.repeater.util.SortParam;\nimport org.apache.syncope.common.rest.api.service.UserRequestService;\n\npublic class UserRequestRestClient extends BaseRestClient {\n\n private static final long serialVersionUID = -4785231164900813921L;\n\n public static int countUserRequests() {\n return getService(UserRequestService.class).\n list(new UserRequestQuery.Builder().page(1).size(0).build()).\n getTotalCount();\n }\n\n public static List getUserRequests(final int page, final int size, final SortParam sort) {\n return getService(UserRequestService.class).\n list(new UserRequestQuery.Builder().page(page).size(size).orderBy(toOrderBy(sort)).build()).\n getResult();\n }\n\n public static void cancelRequest(final String executionId, final String reason) {\n getService(UserRequestService.class).cancel(executionId, reason);\n }\n\n public static int countForms() {\n return getService(UserRequestService.class).\n getForms(new UserRequestFormQuery.Builder().page(1).size(0).build()).\n getTotalCount();\n }\n\n public static List getForms(final int page, final int size, final SortParam sort) {\n return getService(UserRequestService.class).\n getForms(new UserRequestFormQuery.Builder().page(page).size(size).orderBy(toOrderBy(sort)).build()).\n getResult();\n }\n\n public static Optional getForm(final String userKey) {\n PagedResult forms = getService(UserRequestService.class).\n getForms(new UserRequestFormQuery.Builder().user(userKey).page(1).size(0).build());\n UserRequestForm form = forms.getResult().isEmpty()\n ? null\n : forms.getResult().get(0);\n return Optional.ofNullable(form);\n }\n\n public static UserRequestForm claimForm(final String taskKey) {\n return getService(UserRequestService.class).claimForm(taskKey);\n }\n\n public static UserRequestForm unclaimForm(final String taskKey) {\n return getService(UserRequestService.class).unclaimForm(taskKey);\n }\n\n public static void submitForm(final UserRequestForm form) {\n getService(UserRequestService.class).submitForm(form);\n }\n}\n"},"message":{"kind":"string","value":"fixed query on console rest client to retrieve form for a given user\n"},"old_file":{"kind":"string","value":"ext/flowable/client-console/src/main/java/org/apache/syncope/client/console/rest/UserRequestRestClient.java"},"subject":{"kind":"string","value":"fixed query on console rest client to retrieve form for a given user"},"git_diff":{"kind":"string","value":"xt/flowable/client-console/src/main/java/org/apache/syncope/client/console/rest/UserRequestRestClient.java\n \n public static Optional getForm(final String userKey) {\n PagedResult forms = getService(UserRequestService.class).\n getForms(new UserRequestFormQuery.Builder().user(userKey).page(1).size(0).build());\n getForms(new UserRequestFormQuery.Builder().user(userKey).page(1).size(1).build());\n UserRequestForm form = forms.getResult().isEmpty()\n ? null\n : forms.getResult().get(0);"}}},{"rowIdx":861,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"db555b7c3d151653b613dc807680b9bad0c750d8"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"java110/MicroCommunity,java110/MicroCommunity,java110/MicroCommunity,java110/MicroCommunity"},"new_contents":{"kind":"string","value":"package com.java110.api.listener.fee;\n\nimport com.alibaba.fastjson.JSONArray;\nimport com.alibaba.fastjson.JSONObject;\nimport com.java110.api.listener.AbstractServiceApiDataFlowListener;\nimport com.java110.core.annotation.Java110Listener;\nimport com.java110.core.context.DataFlowContext;\nimport com.java110.core.smo.fee.IFeeConfigInnerServiceSMO;\nimport com.java110.core.smo.fee.IFeeInnerServiceSMO;\nimport com.java110.core.smo.hardwareAdapation.ICarInoutInnerServiceSMO;\nimport com.java110.core.smo.room.IRoomInnerServiceSMO;\nimport com.java110.dto.FeeConfigDto;\nimport com.java110.dto.FeeDto;\nimport com.java110.dto.RoomDto;\nimport com.java110.dto.hardwareAdapation.CarInoutDto;\nimport com.java110.entity.center.AppService;\nimport com.java110.entity.order.Orders;\nimport com.java110.event.service.api.ServiceDataFlowEvent;\nimport com.java110.utils.constant.BusinessTypeConstant;\nimport com.java110.utils.constant.CommonConstant;\nimport com.java110.utils.constant.FeeTypeConstant;\nimport com.java110.utils.constant.ResponseConstant;\nimport com.java110.utils.constant.ServiceCodeConstant;\nimport com.java110.utils.exception.ListenerExecuteException;\nimport com.java110.utils.util.Assert;\nimport com.java110.utils.util.BeanConvertUtil;\nimport com.java110.utils.util.DateUtil;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.http.HttpHeaders;\nimport org.springframework.http.HttpMethod;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.http.ResponseEntity;\n\nimport java.util.Calendar;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Map;\n\n/**\n * @ClassName PayFeeListener\n * @Description TODO 预交费(临时停车费)侦听\n * @Author wuxw\n * @Date 2019/6/3 13:46\n * @Version 1.0\n * add by wuxw 2019/6/3\n **/\n@Java110Listener(\"payFeePreTempCarInoutListener\")\npublic class PayFeePreTempCarInoutListener extends AbstractServiceApiDataFlowListener {\n\n private static Logger logger = LoggerFactory.getLogger(PayFeePreTempCarInoutListener.class);\n\n\n @Autowired\n private IFeeInnerServiceSMO feeInnerServiceSMOImpl;\n\n @Autowired\n private IRoomInnerServiceSMO roomInnerServiceSMOImpl;\n\n @Autowired\n private ICarInoutInnerServiceSMO carInoutInnerServiceSMOImpl;\n\n @Autowired\n private IFeeConfigInnerServiceSMO feeConfigInnerServiceSMOImpl;\n\n\n @Override\n public String getServiceCode() {\n return ServiceCodeConstant.SERVICE_CODE_PAY_FEE_PRE_TEMP_CAR_INOUT;\n }\n\n @Override\n public HttpMethod getHttpMethod() {\n return HttpMethod.POST;\n }\n\n @Override\n public void soService(ServiceDataFlowEvent event) {\n\n logger.debug(\"ServiceDataFlowEvent : {}\", event);\n\n DataFlowContext dataFlowContext = event.getDataFlowContext();\n AppService service = event.getAppService();\n\n String paramIn = dataFlowContext.getReqData();\n\n //校验数据\n validate(paramIn);\n JSONObject paramObj = JSONObject.parseObject(paramIn);\n\n HttpHeaders header = new HttpHeaders();\n dataFlowContext.getRequestCurrentHeaders().put(CommonConstant.HTTP_ORDER_TYPE_CD, \"D\");\n JSONArray businesses = new JSONArray();\n paramObj.put(\"cycles\", 1);\n //添加单元信息\n businesses.add(addFeeDetail(paramObj, dataFlowContext));\n businesses.add(modifyFee(paramObj, dataFlowContext));\n businesses.add(modifyCarInout(paramObj, dataFlowContext));\n\n JSONObject paramInObj = super.restToCenterProtocol(businesses, dataFlowContext.getRequestCurrentHeaders());\n\n //将 rest header 信息传递到下层服务中去\n super.freshHttpHeader(header, dataFlowContext.getRequestCurrentHeaders());\n\n ResponseEntity responseEntity = this.callService(dataFlowContext, service.getServiceCode(), paramInObj);\n if (responseEntity.getStatusCode() != HttpStatus.OK) {\n dataFlowContext.setResponseEntity(responseEntity);\n return;\n }\n\n JSONObject paramOut = JSONObject.parseObject(responseEntity.getBody());\n paramOut.put(\"receivableAmount\", paramObj.getString(\"receivableAmount\"));\n\n responseEntity = new ResponseEntity<>(paramOut.toJSONString(), HttpStatus.OK);\n dataFlowContext.setResponseEntity(responseEntity);\n }\n\n private JSONObject modifyCarInout(JSONObject reqJson, DataFlowContext context) {\n\n FeeDto feeDto = (FeeDto) reqJson.get(\"feeInfo\");\n CarInoutDto tempCarInoutDto = new CarInoutDto();\n tempCarInoutDto.setCommunityId(reqJson.getString(\"communityId\"));\n tempCarInoutDto.setInoutId(feeDto.getPayerObjId());\n List carInoutDtos = carInoutInnerServiceSMOImpl.queryCarInouts(tempCarInoutDto);\n\n Assert.listOnlyOne(carInoutDtos, \"根据费用信息反差车辆进场记录未查到 或查到多条\");\n\n CarInoutDto carInoutDto = carInoutDtos.get(0);\n JSONObject business = JSONObject.parseObject(\"{\\\"datas\\\":{}}\");\n business.put(CommonConstant.HTTP_BUSINESS_TYPE_CD, BusinessTypeConstant.BUSINESS_TYPE_UPDATE_CAR_INOUT);\n business.put(CommonConstant.HTTP_SEQ, DEFAULT_SEQ);\n business.put(CommonConstant.HTTP_INVOKE_MODEL, CommonConstant.HTTP_INVOKE_MODEL_S);\n JSONObject businessCarInout = new JSONObject();\n businessCarInout.putAll(BeanConvertUtil.beanCovertMap(carInoutDto));\n businessCarInout.put(\"state\", \"100400\");\n //计算 应收金额\n business.getJSONObject(CommonConstant.HTTP_BUSINESS_DATAS).put(\"businessCarInout\", businessCarInout);\n return business;\n }\n\n /**\n * 刷入order信息\n *\n * @param orders 订单信息\n * @param headers 头部信息\n */\n protected void freshOrderProtocol(JSONObject orders, Map headers) {\n super.freshOrderProtocol(orders, headers);\n orders.put(\"orderProcess\", Orders.ORDER_PROCESS_ORDER_PRE_SUBMIT);\n\n }\n\n /**\n * 添加费用明细信息\n *\n * @param paramInJson 接口调用放传入入参\n * @param dataFlowContext 数据上下文\n * @return 订单服务能够接受的报文\n */\n private JSONObject addFeeDetail(JSONObject paramInJson, DataFlowContext dataFlowContext) {\n\n\n JSONObject business = JSONObject.parseObject(\"{\\\"datas\\\":{}}\");\n business.put(CommonConstant.HTTP_BUSINESS_TYPE_CD, BusinessTypeConstant.BUSINESS_TYPE_SAVE_FEE_DETAIL);\n business.put(CommonConstant.HTTP_SEQ, DEFAULT_SEQ);\n business.put(CommonConstant.HTTP_INVOKE_MODEL, CommonConstant.HTTP_INVOKE_MODEL_S);\n JSONObject businessFeeDetail = new JSONObject();\n businessFeeDetail.putAll(paramInJson);\n businessFeeDetail.put(\"detailId\", \"-1\");\n businessFeeDetail.put(\"primeRate\", \"1.00\");\n //计算 应收金额\n FeeDto feeDto = new FeeDto();\n feeDto.setFeeId(paramInJson.getString(\"feeId\"));\n feeDto.setCommunityId(paramInJson.getString(\"communityId\"));\n List feeDtos = feeInnerServiceSMOImpl.queryFees(feeDto);\n if (feeDtos == null || feeDtos.size() != 1) {\n throw new ListenerExecuteException(ResponseConstant.RESULT_CODE_ERROR, \"查询费用信息失败,未查到数据或查到多条数据\");\n }\n feeDto = feeDtos.get(0);\n paramInJson.put(\"feeInfo\", feeDto);\n FeeConfigDto feeConfigDto = new FeeConfigDto();\n feeConfigDto.setFeeTypeCd(feeDto.getFeeTypeCd());\n feeConfigDto.setCommunityId(feeDto.getCommunityId());\n List feeConfigDtos = feeConfigInnerServiceSMOImpl.queryFeeConfigs(feeConfigDto);\n if (feeConfigDtos == null || feeConfigDtos.size() != 1) {\n throw new ListenerExecuteException(ResponseConstant.RESULT_CODE_ERROR, \"未查到费用配置信息,查询多条数据\");\n }\n feeConfigDto = feeConfigDtos.get(0);\n Date nowTime = new Date();\n\n long diff = nowTime.getTime() - feeDto.getStartTime().getTime();\n long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数\n long nh = 1000 * 60 * 60;// 一小时的毫秒数\n long nm = 1000 * 60;// 一分钟的毫秒数\n double day = 0;\n double hour = 0;\n double min = 0;\n day = diff / nd;// 计算差多少天\n hour = diff % nd / nh + day * 24;// 计算差多少小时\n min = diff % nd % nh / nm + day * 24 * 60;// 计算差多少分钟\n double money = 0.00;\n double newHour = hour;\n if (min > 0) { //一小时超过\n newHour += 1;\n }\n if (newHour <= 2) {\n money = Double.parseDouble(feeConfigDto.getAdditionalAmount());\n } else {\n double lastHour = newHour - 2;\n money = lastHour * Double.parseDouble(feeConfigDto.getSquarePrice()) + Double.parseDouble(feeConfigDto.getAdditionalAmount());\n }\n\n double receivableAmount = money;\n\n businessFeeDetail.put(\"receivableAmount\", receivableAmount);\n business.getJSONObject(CommonConstant.HTTP_BUSINESS_DATAS).put(\"businessFeeDetail\", businessFeeDetail);\n paramInJson.put(\"receivableAmount\", receivableAmount);\n return business;\n }\n\n\n /**\n * 修改费用信息\n *\n * @param paramInJson 接口调用放传入入参\n * @param dataFlowContext 数据上下文\n * @return 订单服务能够接受的报文\n */\n private JSONObject modifyFee(JSONObject paramInJson, DataFlowContext dataFlowContext) {\n\n\n JSONObject business = JSONObject.parseObject(\"{\\\"datas\\\":{}}\");\n business.put(CommonConstant.HTTP_BUSINESS_TYPE_CD, BusinessTypeConstant.BUSINESS_TYPE_UPDATE_FEE_INFO);\n business.put(CommonConstant.HTTP_SEQ, DEFAULT_SEQ + 1);\n business.put(CommonConstant.HTTP_INVOKE_MODEL, CommonConstant.HTTP_INVOKE_MODEL_S);\n JSONObject businessFee = new JSONObject();\n FeeDto feeInfo = (FeeDto) paramInJson.get(\"feeInfo\");\n Map feeMap = BeanConvertUtil.beanCovertMap(feeInfo);\n feeMap.put(\"startTime\", DateUtil.getFormatTimeString(feeInfo.getStartTime(), DateUtil.DATE_FORMATE_STRING_A));\n feeMap.put(\"endTime\", DateUtil.getFormatTimeString(new Date(), DateUtil.DATE_FORMATE_STRING_A));\n feeMap.put(\"total\", paramInJson.getString(\"receivableAmount\"));\n businessFee.putAll(feeMap);\n business.getJSONObject(CommonConstant.HTTP_BUSINESS_DATAS).put(\"businessFee\", businessFee);\n\n return business;\n }\n\n /**\n * 数据校验\n *\n * @param paramIn \"communityId\": \"7020181217000001\",\n * \"memberId\": \"3456789\",\n * \"memberTypeCd\": \"390001200001\"\n */\n private void validate(String paramIn) {\n Assert.jsonObjectHaveKey(paramIn, \"communityId\", \"请求报文中未包含communityId节点\");\n Assert.jsonObjectHaveKey(paramIn, \"receivedAmount\", \"请求报文中未包含receivedAmount节点\");\n Assert.jsonObjectHaveKey(paramIn, \"feeId\", \"请求报文中未包含feeId节点\");\n\n JSONObject paramInObj = JSONObject.parseObject(paramIn);\n Assert.hasLength(paramInObj.getString(\"communityId\"), \"小区ID不能为空\");\n Assert.hasLength(paramInObj.getString(\"receivedAmount\"), \"实收金额不能为空\");\n Assert.hasLength(paramInObj.getString(\"feeId\"), \"费用ID不能为空\");\n\n }\n\n @Override\n public int getOrder() {\n return DEFAULT_ORDER;\n }\n\n\n public IFeeInnerServiceSMO getFeeInnerServiceSMOImpl() {\n return feeInnerServiceSMOImpl;\n }\n\n public void setFeeInnerServiceSMOImpl(IFeeInnerServiceSMO feeInnerServiceSMOImpl) {\n this.feeInnerServiceSMOImpl = feeInnerServiceSMOImpl;\n }\n\n public IFeeConfigInnerServiceSMO getFeeConfigInnerServiceSMOImpl() {\n return feeConfigInnerServiceSMOImpl;\n }\n\n public void setFeeConfigInnerServiceSMOImpl(IFeeConfigInnerServiceSMO feeConfigInnerServiceSMOImpl) {\n this.feeConfigInnerServiceSMOImpl = feeConfigInnerServiceSMOImpl;\n }\n\n public IRoomInnerServiceSMO getRoomInnerServiceSMOImpl() {\n return roomInnerServiceSMOImpl;\n }\n\n public void setRoomInnerServiceSMOImpl(IRoomInnerServiceSMO roomInnerServiceSMOImpl) {\n this.roomInnerServiceSMOImpl = roomInnerServiceSMOImpl;\n }\n}\n"},"new_file":{"kind":"string","value":"Api/src/main/java/com/java110/api/listener/fee/PayFeePreTempCarInoutListener.java"},"old_contents":{"kind":"string","value":"package com.java110.api.listener.fee;\n\nimport com.alibaba.fastjson.JSONArray;\nimport com.alibaba.fastjson.JSONObject;\nimport com.java110.api.listener.AbstractServiceApiDataFlowListener;\nimport com.java110.core.annotation.Java110Listener;\nimport com.java110.core.context.DataFlowContext;\nimport com.java110.core.smo.fee.IFeeConfigInnerServiceSMO;\nimport com.java110.core.smo.fee.IFeeInnerServiceSMO;\nimport com.java110.core.smo.hardwareAdapation.ICarInoutInnerServiceSMO;\nimport com.java110.core.smo.room.IRoomInnerServiceSMO;\nimport com.java110.dto.FeeConfigDto;\nimport com.java110.dto.FeeDto;\nimport com.java110.dto.RoomDto;\nimport com.java110.dto.hardwareAdapation.CarInoutDto;\nimport com.java110.entity.center.AppService;\nimport com.java110.entity.order.Orders;\nimport com.java110.event.service.api.ServiceDataFlowEvent;\nimport com.java110.utils.constant.BusinessTypeConstant;\nimport com.java110.utils.constant.CommonConstant;\nimport com.java110.utils.constant.FeeTypeConstant;\nimport com.java110.utils.constant.ResponseConstant;\nimport com.java110.utils.constant.ServiceCodeConstant;\nimport com.java110.utils.exception.ListenerExecuteException;\nimport com.java110.utils.util.Assert;\nimport com.java110.utils.util.BeanConvertUtil;\nimport com.java110.utils.util.DateUtil;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.http.HttpHeaders;\nimport org.springframework.http.HttpMethod;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.http.ResponseEntity;\n\nimport java.util.Calendar;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Map;\n\n/**\n * @ClassName PayFeeListener\n * @Description TODO 预交费(临时停车费)侦听\n * @Author wuxw\n * @Date 2019/6/3 13:46\n * @Version 1.0\n * add by wuxw 2019/6/3\n **/\n@Java110Listener(\"payFeePreTempCarInoutListener\")\npublic class PayFeePreTempCarInoutListener extends AbstractServiceApiDataFlowListener {\n\n private static Logger logger = LoggerFactory.getLogger(PayFeePreTempCarInoutListener.class);\n\n\n @Autowired\n private IFeeInnerServiceSMO feeInnerServiceSMOImpl;\n\n @Autowired\n private IRoomInnerServiceSMO roomInnerServiceSMOImpl;\n\n @Autowired\n private ICarInoutInnerServiceSMO carInoutInnerServiceSMOImpl;\n\n @Autowired\n private IFeeConfigInnerServiceSMO feeConfigInnerServiceSMOImpl;\n\n\n @Override\n public String getServiceCode() {\n return ServiceCodeConstant.SERVICE_CODE_PAY_FEE_PRE_TEMP_CAR_INOUT;\n }\n\n @Override\n public HttpMethod getHttpMethod() {\n return HttpMethod.POST;\n }\n\n @Override\n public void soService(ServiceDataFlowEvent event) {\n\n logger.debug(\"ServiceDataFlowEvent : {}\", event);\n\n DataFlowContext dataFlowContext = event.getDataFlowContext();\n AppService service = event.getAppService();\n\n String paramIn = dataFlowContext.getReqData();\n\n //校验数据\n validate(paramIn);\n JSONObject paramObj = JSONObject.parseObject(paramIn);\n\n HttpHeaders header = new HttpHeaders();\n dataFlowContext.getRequestCurrentHeaders().put(CommonConstant.HTTP_ORDER_TYPE_CD, \"D\");\n JSONArray businesses = new JSONArray();\n\n //添加单元信息\n businesses.add(addFeeDetail(paramObj, dataFlowContext));\n businesses.add(modifyFee(paramObj, dataFlowContext));\n businesses.add(modifyCarInout(paramObj, dataFlowContext));\n\n JSONObject paramInObj = super.restToCenterProtocol(businesses, dataFlowContext.getRequestCurrentHeaders());\n\n //将 rest header 信息传递到下层服务中去\n super.freshHttpHeader(header, dataFlowContext.getRequestCurrentHeaders());\n\n ResponseEntity responseEntity = this.callService(dataFlowContext, service.getServiceCode(), paramInObj);\n if (responseEntity.getStatusCode() != HttpStatus.OK) {\n dataFlowContext.setResponseEntity(responseEntity);\n return;\n }\n\n JSONObject paramOut = JSONObject.parseObject(responseEntity.getBody());\n paramOut.put(\"receivableAmount\", paramObj.getString(\"receivableAmount\"));\n\n responseEntity = new ResponseEntity<>(paramOut.toJSONString(), HttpStatus.OK);\n dataFlowContext.setResponseEntity(responseEntity);\n }\n\n private JSONObject modifyCarInout(JSONObject reqJson, DataFlowContext context) {\n\n FeeDto feeDto = (FeeDto) reqJson.get(\"feeInfo\");\n CarInoutDto tempCarInoutDto = new CarInoutDto();\n tempCarInoutDto.setCommunityId(reqJson.getString(\"communityId\"));\n tempCarInoutDto.setInoutId(feeDto.getPayerObjId());\n List carInoutDtos = carInoutInnerServiceSMOImpl.queryCarInouts(tempCarInoutDto);\n\n Assert.listOnlyOne(carInoutDtos, \"根据费用信息反差车辆进场记录未查到 或查到多条\");\n\n CarInoutDto carInoutDto = carInoutDtos.get(0);\n JSONObject business = JSONObject.parseObject(\"{\\\"datas\\\":{}}\");\n business.put(CommonConstant.HTTP_BUSINESS_TYPE_CD, BusinessTypeConstant.BUSINESS_TYPE_UPDATE_CAR_INOUT);\n business.put(CommonConstant.HTTP_SEQ, DEFAULT_SEQ);\n business.put(CommonConstant.HTTP_INVOKE_MODEL, CommonConstant.HTTP_INVOKE_MODEL_S);\n JSONObject businessCarInout = new JSONObject();\n businessCarInout.putAll(BeanConvertUtil.beanCovertMap(carInoutDto));\n businessCarInout.put(\"state\", \"100400\");\n //计算 应收金额\n business.getJSONObject(CommonConstant.HTTP_BUSINESS_DATAS).put(\"businessCarInout\", businessCarInout);\n return business;\n }\n\n /**\n * 刷入order信息\n *\n * @param orders 订单信息\n * @param headers 头部信息\n */\n protected void freshOrderProtocol(JSONObject orders, Map headers) {\n super.freshOrderProtocol(orders, headers);\n orders.put(\"orderProcess\", Orders.ORDER_PROCESS_ORDER_PRE_SUBMIT);\n\n }\n\n /**\n * 添加费用明细信息\n *\n * @param paramInJson 接口调用放传入入参\n * @param dataFlowContext 数据上下文\n * @return 订单服务能够接受的报文\n */\n private JSONObject addFeeDetail(JSONObject paramInJson, DataFlowContext dataFlowContext) {\n\n\n JSONObject business = JSONObject.parseObject(\"{\\\"datas\\\":{}}\");\n business.put(CommonConstant.HTTP_BUSINESS_TYPE_CD, BusinessTypeConstant.BUSINESS_TYPE_SAVE_FEE_DETAIL);\n business.put(CommonConstant.HTTP_SEQ, DEFAULT_SEQ);\n business.put(CommonConstant.HTTP_INVOKE_MODEL, CommonConstant.HTTP_INVOKE_MODEL_S);\n JSONObject businessFeeDetail = new JSONObject();\n businessFeeDetail.putAll(paramInJson);\n businessFeeDetail.put(\"detailId\", \"-1\");\n businessFeeDetail.put(\"primeRate\", \"1.00\");\n //计算 应收金额\n FeeDto feeDto = new FeeDto();\n feeDto.setFeeId(paramInJson.getString(\"feeId\"));\n feeDto.setCommunityId(paramInJson.getString(\"communityId\"));\n List feeDtos = feeInnerServiceSMOImpl.queryFees(feeDto);\n if (feeDtos == null || feeDtos.size() != 1) {\n throw new ListenerExecuteException(ResponseConstant.RESULT_CODE_ERROR, \"查询费用信息失败,未查到数据或查到多条数据\");\n }\n feeDto = feeDtos.get(0);\n paramInJson.put(\"feeInfo\", feeDto);\n FeeConfigDto feeConfigDto = new FeeConfigDto();\n feeConfigDto.setFeeTypeCd(feeDto.getFeeTypeCd());\n feeConfigDto.setCommunityId(feeDto.getCommunityId());\n List feeConfigDtos = feeConfigInnerServiceSMOImpl.queryFeeConfigs(feeConfigDto);\n if (feeConfigDtos == null || feeConfigDtos.size() != 1) {\n throw new ListenerExecuteException(ResponseConstant.RESULT_CODE_ERROR, \"未查到费用配置信息,查询多条数据\");\n }\n feeConfigDto = feeConfigDtos.get(0);\n Date nowTime = new Date();\n\n long diff = nowTime.getTime() - feeDto.getStartTime().getTime();\n long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数\n long nh = 1000 * 60 * 60;// 一小时的毫秒数\n long nm = 1000 * 60;// 一分钟的毫秒数\n double day = 0;\n double hour = 0;\n double min = 0;\n day = diff / nd;// 计算差多少天\n hour = diff % nd / nh + day * 24;// 计算差多少小时\n min = diff % nd % nh / nm + day * 24 * 60;// 计算差多少分钟\n double money = 0.00;\n double newHour = hour;\n if (min > 0) { //一小时超过\n newHour += 1;\n }\n if (newHour <= 2) {\n money = Double.parseDouble(feeConfigDto.getAdditionalAmount());\n } else {\n double lastHour = newHour - 2;\n money = lastHour * Double.parseDouble(feeConfigDto.getSquarePrice()) + Double.parseDouble(feeConfigDto.getAdditionalAmount());\n }\n\n double receivableAmount = money;\n\n businessFeeDetail.put(\"receivableAmount\", receivableAmount);\n business.getJSONObject(CommonConstant.HTTP_BUSINESS_DATAS).put(\"businessFeeDetail\", businessFeeDetail);\n paramInJson.put(\"receivableAmount\", receivableAmount);\n return business;\n }\n\n\n /**\n * 修改费用信息\n *\n * @param paramInJson 接口调用放传入入参\n * @param dataFlowContext 数据上下文\n * @return 订单服务能够接受的报文\n */\n private JSONObject modifyFee(JSONObject paramInJson, DataFlowContext dataFlowContext) {\n\n\n JSONObject business = JSONObject.parseObject(\"{\\\"datas\\\":{}}\");\n business.put(CommonConstant.HTTP_BUSINESS_TYPE_CD, BusinessTypeConstant.BUSINESS_TYPE_UPDATE_FEE_INFO);\n business.put(CommonConstant.HTTP_SEQ, DEFAULT_SEQ + 1);\n business.put(CommonConstant.HTTP_INVOKE_MODEL, CommonConstant.HTTP_INVOKE_MODEL_S);\n JSONObject businessFee = new JSONObject();\n FeeDto feeInfo = (FeeDto) paramInJson.get(\"feeInfo\");\n Map feeMap = BeanConvertUtil.beanCovertMap(feeInfo);\n feeMap.put(\"startTime\", DateUtil.getFormatTimeString(feeInfo.getStartTime(), DateUtil.DATE_FORMATE_STRING_A));\n feeMap.put(\"endTime\", DateUtil.getFormatTimeString(new Date(), DateUtil.DATE_FORMATE_STRING_A));\n feeMap.put(\"total\", paramInJson.getString(\"receivableAmount\"));\n businessFee.putAll(feeMap);\n business.getJSONObject(CommonConstant.HTTP_BUSINESS_DATAS).put(\"businessFee\", businessFee);\n\n return business;\n }\n\n /**\n * 数据校验\n *\n * @param paramIn \"communityId\": \"7020181217000001\",\n * \"memberId\": \"3456789\",\n * \"memberTypeCd\": \"390001200001\"\n */\n private void validate(String paramIn) {\n Assert.jsonObjectHaveKey(paramIn, \"communityId\", \"请求报文中未包含communityId节点\");\n Assert.jsonObjectHaveKey(paramIn, \"receivedAmount\", \"请求报文中未包含receivedAmount节点\");\n Assert.jsonObjectHaveKey(paramIn, \"feeId\", \"请求报文中未包含feeId节点\");\n\n JSONObject paramInObj = JSONObject.parseObject(paramIn);\n Assert.hasLength(paramInObj.getString(\"communityId\"), \"小区ID不能为空\");\n Assert.hasLength(paramInObj.getString(\"receivedAmount\"), \"实收金额不能为空\");\n Assert.hasLength(paramInObj.getString(\"feeId\"), \"费用ID不能为空\");\n\n }\n\n @Override\n public int getOrder() {\n return DEFAULT_ORDER;\n }\n\n\n public IFeeInnerServiceSMO getFeeInnerServiceSMOImpl() {\n return feeInnerServiceSMOImpl;\n }\n\n public void setFeeInnerServiceSMOImpl(IFeeInnerServiceSMO feeInnerServiceSMOImpl) {\n this.feeInnerServiceSMOImpl = feeInnerServiceSMOImpl;\n }\n\n public IFeeConfigInnerServiceSMO getFeeConfigInnerServiceSMOImpl() {\n return feeConfigInnerServiceSMOImpl;\n }\n\n public void setFeeConfigInnerServiceSMOImpl(IFeeConfigInnerServiceSMO feeConfigInnerServiceSMOImpl) {\n this.feeConfigInnerServiceSMOImpl = feeConfigInnerServiceSMOImpl;\n }\n\n public IRoomInnerServiceSMO getRoomInnerServiceSMOImpl() {\n return roomInnerServiceSMOImpl;\n }\n\n public void setRoomInnerServiceSMOImpl(IRoomInnerServiceSMO roomInnerServiceSMOImpl) {\n this.roomInnerServiceSMOImpl = roomInnerServiceSMOImpl;\n }\n}\n"},"message":{"kind":"string","value":"加入 cycles 写死为1期\n"},"old_file":{"kind":"string","value":"Api/src/main/java/com/java110/api/listener/fee/PayFeePreTempCarInoutListener.java"},"subject":{"kind":"string","value":"加入 cycles 写死为1期"},"git_diff":{"kind":"string","value":"pi/src/main/java/com/java110/api/listener/fee/PayFeePreTempCarInoutListener.java\n HttpHeaders header = new HttpHeaders();\n dataFlowContext.getRequestCurrentHeaders().put(CommonConstant.HTTP_ORDER_TYPE_CD, \"D\");\n JSONArray businesses = new JSONArray();\n\n paramObj.put(\"cycles\", 1);\n //添加单元信息\n businesses.add(addFeeDetail(paramObj, dataFlowContext));\n businesses.add(modifyFee(paramObj, dataFlowContext));"}}},{"rowIdx":862,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"ababd55cdcb6ee2592f8218fc0b74664b38152a5"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"genedelisa/rockymusic"},"new_contents":{"kind":"string","value":"package com.rockhoppertech.music.fx.cmn;\n\n/*\n * #%L\n * rockymusic-fx\n * %%\n * Copyright (C) 1996 - 2013 Rockhopper Technologies\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 javafx.application.Application;\nimport javafx.beans.value.ChangeListener;\nimport javafx.beans.value.ObservableValue;\nimport javafx.geometry.Insets;\nimport javafx.scene.Scene;\nimport javafx.scene.SceneBuilder;\nimport javafx.scene.control.Button;\nimport javafx.scene.control.ButtonBuilder;\nimport javafx.scene.control.ComboBox;\nimport javafx.scene.control.ScrollPane;\nimport javafx.scene.control.TextArea;\nimport javafx.scene.control.TextAreaBuilder;\nimport javafx.scene.control.TextField;\nimport javafx.scene.control.TextFieldBuilder;\nimport javafx.scene.layout.AnchorPane;\nimport javafx.scene.layout.AnchorPaneBuilder;\nimport javafx.scene.layout.BorderPane;\nimport javafx.scene.layout.BorderPaneBuilder;\nimport javafx.scene.layout.HBox;\nimport javafx.scene.layout.HBoxBuilder;\nimport javafx.scene.layout.Pane;\nimport javafx.scene.layout.VBox;\nimport javafx.scene.layout.VBoxBuilder;\nimport javafx.scene.paint.Color;\nimport javafx.stage.Screen;\nimport javafx.stage.Stage;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.rockhoppertech.music.fx.cmn.model.StaffModel;\nimport com.rockhoppertech.music.midi.js.MIDITrack;\nimport com.rockhoppertech.music.midi.js.MIDITrackBuilder;\n\n/**\n * @author Gene De Lisa\n * \n */\npublic class NotationApp extends Application {\n\n private static final Logger logger = LoggerFactory\n .getLogger(NotationApp.class);\n Stage stage;\n Scene scene;\n Pane root;\n\n private NotationController controller;\n private StaffModel staffModel;\n // private NotationView view;\n // private NotationCanvas view;\n private StaffRegion view;\n\n // private StaffControl view;\n\n // private static ObservableList tableDataList;\n\n public static void main(String[] args) throws Exception {\n launch(args);\n }\n\n @Override\n public void start(Stage stage) throws Exception {\n this.stage = stage;\n\n this.staffModel = new StaffModel();\n MIDITrack track = MIDITrackBuilder\n .create()\n .noteString(\n \"E5 F G Ab G# A B C C6 D Eb F# G A B C7 B4 Bf4 A4 Af4\")\n .durations(1, 1.5, .5, .75, .25, .25)\n .sequential()\n .build();\n System.out.println(track);\n this.staffModel.setTrack(track);\n // this.view = new NotationCanvas(this.staffModel);\n this.view = new StaffRegion(this.staffModel);\n this.controller = new NotationController(staffModel, view);\n this.view.drawShapes();\n\n this.configureScene();\n this.configureStage();\n logger.debug(\"started\");\n }\n\n private void configureStage() {\n stage.setTitle(\"Music Notation\");\n\n // fullScreen();\n\n stage.setScene(this.scene);\n controller.setStage(this.stage);\n stage.show();\n }\n\n private void fullScreen() {\n // make it full screen\n stage.setX(0);\n stage.setY(0);\n stage.setWidth(Screen.getPrimary().getVisualBounds().getWidth());\n stage.setHeight(Screen.getPrimary().getVisualBounds().getHeight());\n }\n\n private void configureScene() {\n // TextField text = new TextField();\n // text.setId(\"noteStringText\");\n // text.setEditable(true);\n // text.setPromptText(\"Enter a note string\");\n // controller.setTextField(text);\n\n TextArea textArea = new TextArea();\n textArea.setId(\"noteStringText\");\n textArea.setEditable(true);\n textArea.setPromptText(\"Enter a note string\");\n textArea.setWrapText(true);\n// textArea.setText(MIDITrack\n //.getPitchesAsString(this.staffModel.getTrackProperty().get()));\n \n textArea.setText(this.staffModel.getTrackProperty().get().toBriefMIDIString(\"\\n\"));\n controller.setTextArea(textArea);\n \n Button b = ButtonBuilder.create()\n .id(\"noteStringButton\")\n .style(\"-fx-font: 22 arial; -fx-base: #1055FF;\")\n .text(\"Evaluate note string\")\n .build();\n controller.setNoteStringButton(b);\n Button pb = ButtonBuilder.create()\n .id(\"playButton\")\n .style(\"-fx-font: 22 arial; -fx-base: #1055FF;\")\n .text(\"Play\")\n .build();\n controller.setPlayButton(pb);\n\n final ComboBox clefComboBox = new ComboBox<>();\n clefComboBox.getItems().addAll(\n \"Treble\",\n \"Bass\",\n \"Alto\"\n );\n clefComboBox.getSelectionModel().selectFirst();\n clefComboBox.getSelectionModel().selectedItemProperty()\n .addListener(new ChangeListener() {\n @Override\n public void changed(\n ObservableValue observable,\n String oldValue, String newValue) {\n\n }\n });\n ;\n controller.setClefCombBox(clefComboBox);\n\n final ComboBox fontSizeComboBox = new ComboBox<>();\n fontSizeComboBox.getItems().addAll(12d, 24d, 36d, 48d, 72d, 96d);\n fontSizeComboBox.getSelectionModel().select(3);\n controller.setFontSizeComboBox(fontSizeComboBox);\n\n FXTextAreaReceiver receiver = new FXTextAreaReceiver();\n controller.addReceiver(receiver);\n\n HBox hbox = HBoxBuilder.create()\n .padding(new Insets(20))\n .children(clefComboBox, fontSizeComboBox)\n .build();\n HBox buttonbox = HBoxBuilder.create()\n .padding(new Insets(20))\n .children(b, pb)\n .build();\n\n VBox vbox = VBoxBuilder.create()\n .padding(new Insets(20))\n .children(textArea, buttonbox, hbox, receiver)\n .build();\n\n ScrollPane sp = new ScrollPane();\n // sp.setContent(view.getCanvas());\n sp.setContent(view);\n sp.setPrefSize(1300, 300);\n\n BorderPane bp = BorderPaneBuilder.create()\n .id(\"rootpane\")\n // .padding(new Insets(20))\n .style(\"-fx-padding: 30\")\n .top(sp)\n .center(vbox)\n .build();\n AnchorPane.setTopAnchor(bp, 10.0);\n AnchorPane.setBottomAnchor(bp, 10.0);\n AnchorPane.setLeftAnchor(bp, 10.0);\n AnchorPane.setRightAnchor(bp, 65.0);\n\n root = AnchorPaneBuilder.create()\n .children(bp)\n .build();\n\n this.scene = SceneBuilder.create()\n .root(root)\n .fill(Color.web(\"#1030F0\"))\n // .stylesheets(\"/styles/app2styles.css\")\n .build();\n }\n\n // private void configureSceneold() {\n //\n // // double fontSize = 24d;\n // // double fontSize = 36d;\n // double fontSize = 48d;\n // // double fontSize = 96d;\n // Font font = Font.loadFont(\n // FontApp.class.getResource(\"/fonts/Bravura.otf\")\n // .toExternalForm(),\n // fontSize);\n // // FontMetrics fm;\n //\n // // Font font = new Font(\"Bravura\", fontSize);\n //\n // Canvas canvas = new Canvas(1300, 250);\n // canvas.setOpacity(100);\n //\n // GraphicsContext gc = canvas.getGraphicsContext2D();\n // gc.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());\n // gc.setFill(Color.WHITE);\n // gc.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());\n // gc.setFill(Color.BLACK);\n // gc.setTextBaseline(VPos.CENTER);\n // gc.setFont(font);\n //\n // double x = 50d;\n // double y = 125d;\n // // double yinc = fontSize / 10d + 1.2; // magic number since we lack\n // // font\n // // metrics. works for 48. too much\n // // for 24 or 36\n //\n // this.yspacing = fontSize / 8d;\n //\n // gc.fillText(getGlyph(\"gClef\"), x, y - (this.yspacing * 2d));\n // // gc.fillText(getGlyph(\"fClef\"), x, y - (this.yspacing * 6d));\n //\n // this.trebleStaffBottom = y;\n // String staff = getGlyph(\"staff5Lines\");\n // for (double xx = x; xx < 1250; xx += fontSize / 2d) {\n // gc.fillText(staff, xx, y);\n // }\n //\n // gc.fillText(getGlyph(\"noteQuarterUp\"), x += fontSize, y);\n // gc.fillText(getGlyph(\"accidentalFlat\"), x += fontSize, y);\n // gc.fillText(getGlyph(\"noteQuarterDown\"), x += fontSize / 3d, y);\n // gc.fillText(getGlyph(\"noteHalfUp\"), x += fontSize, y);\n //\n // double yy = y;\n // // ascending scale\n // for (int i = 0; i < 12; i++, yy -= this.yspacing) {\n // gc.fillText(SymbolFactory.noteQuarterUp(), x += fontSize, yy);\n // }\n //\n // setupStaff();\n //\n // yy = this.trebleFlatYpositions[Pitch.D5];\n // gc.fillText(SymbolFactory.noteQuarterDownFlat(), x += fontSize, yy);\n //\n // yy = this.trebleFlatYpositions[Pitch.E5];\n // gc.fillText(SymbolFactory.noteQuarterDownFlat(), x += fontSize, yy);\n //\n // yy = this.trebleFlatYpositions[Pitch.F5];\n // gc.fillText(SymbolFactory.noteQuarterDownFlat(), x += fontSize, yy);\n //\n // yy = this.trebleFlatYpositions[Pitch.G5];\n // gc.fillText(SymbolFactory.noteQuarterDownFlat(), x += fontSize, yy);\n //\n // yy = this.trebleFlatYpositions[Pitch.A5];\n // gc.fillText(SymbolFactory.noteQuarterDownFlat(), x += fontSize, yy);\n //\n // yy = this.trebleFlatYpositions[Pitch.B5];\n // gc.fillText(SymbolFactory.noteQuarterDownFlat(), x += fontSize, yy);\n //\n // yy = this.trebleFlatYpositions[Pitch.C6];\n // gc.fillText(SymbolFactory.noteQuarterDownFlat(), x += fontSize, yy);\n //\n // int pitch = Pitch.EF6;\n // if (needFlats(pitch)) {\n // String ns = SymbolFactory.noteQuarterDownFlat();\n // yy = this.trebleFlatYpositions[pitch];\n // gc.fillText(ns, x += fontSize, yy);\n // }\n // // ledger? \"staff1Line\"\n //\n // /*\n // * \"noteheadBlack\": { \"stemDownNW\": [ 0.0, -0.184 ], \"stemUpSE\": [\n // * 1.328, 0.184 ] },\n // */\n //\n // // gc.fillText(\"abcedfghijklmnopqrstuvwxyz\", 50d, 150d);\n //\n // /*\n // * \"gClef\": { \"alternateCodepoint\": \"U+1D11E\", \"codepoint\": \"U+E050\" },\n // */\n //\n // // Image bgimage = new Image(getClass().getResourceAsStream(\n // // \"/images/background.jpg\"));\n // // ImageView imageView = ImageViewBuilder.create()\n // // .image(bgimage)\n // // .build();\n //\n // Button b = ButtonBuilder.create()\n // .id(\"someButton\")\n // .text(\"Button\")\n // .style(\"-fx-font: 22 arial; -fx-base: #b6e7c9;\")\n // // .onAction(new EventHandler() {\n // // @Override\n // // public void handle(ActionEvent e) {\n // // logger.debug(\"local button pressed {}\", e);\n // // }\n // // })\n // .build();\n //\n // // not a singleton: logger.debug(\"button builder {}\",\n // // ButtonBuilder.create());\n //\n // // the controller has the action handler\n // //this.controller.setButton(b);\n // //BorderPane.setAlignment(b, Pos.CENTER);\n //\n // BorderPane borderPane = new BorderPane();\n // // borderPane.setTop(toolbar);\n // // borderPane.setLeft(actionPane);\n // // borderPane.setRight(colorPane);\n //\n // borderPane.setCenter(view.getCanvasPane());\n //\n // // borderPane.setBottom(statusBar);\n //\n // Group group = new Group();\n // group.getChildren().add(canvas);\n // // group.getChildren().add(b);\n //\n // root =\n // BorderPaneBuilder\n // .create()\n // .id(\"rootpane\")\n // .padding(new Insets(20))\n // // .style(\"-fx-padding: 30\")\n // .center(group)\n // .build();\n //\n // this.scene = SceneBuilder.create()\n // // .root(root)\n // .root(borderPane)\n // .fill(Color.web(\"#103000\"))\n // // .stylesheets(\"/styles/app2styles.css\")\n // .build();\n //\n // // MIDITrack track = MIDITrackBuilder.create()\n // // .noteString(\"C D E\")\n // // .build();\n // // track.sequential();\n //\n // }\n\n}\n"},"new_file":{"kind":"string","value":"rockymusic-fx/src/main/java/com/rockhoppertech/music/fx/cmn/NotationApp.java"},"old_contents":{"kind":"string","value":"package com.rockhoppertech.music.fx.cmn;\n\n/*\n * #%L\n * rockymusic-fx\n * %%\n * Copyright (C) 1996 - 2013 Rockhopper Technologies\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 javafx.application.Application;\nimport javafx.beans.value.ChangeListener;\nimport javafx.beans.value.ObservableValue;\nimport javafx.geometry.Insets;\nimport javafx.scene.Scene;\nimport javafx.scene.SceneBuilder;\nimport javafx.scene.control.Button;\nimport javafx.scene.control.ButtonBuilder;\nimport javafx.scene.control.ComboBox;\nimport javafx.scene.control.ScrollPane;\nimport javafx.scene.control.TextArea;\nimport javafx.scene.control.TextAreaBuilder;\nimport javafx.scene.control.TextField;\nimport javafx.scene.control.TextFieldBuilder;\nimport javafx.scene.layout.AnchorPane;\nimport javafx.scene.layout.AnchorPaneBuilder;\nimport javafx.scene.layout.BorderPane;\nimport javafx.scene.layout.BorderPaneBuilder;\nimport javafx.scene.layout.HBox;\nimport javafx.scene.layout.HBoxBuilder;\nimport javafx.scene.layout.Pane;\nimport javafx.scene.layout.VBox;\nimport javafx.scene.layout.VBoxBuilder;\nimport javafx.scene.paint.Color;\nimport javafx.stage.Screen;\nimport javafx.stage.Stage;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.rockhoppertech.music.fx.cmn.model.StaffModel;\nimport com.rockhoppertech.music.midi.js.MIDITrack;\nimport com.rockhoppertech.music.midi.js.MIDITrackBuilder;\n\n/**\n * @author Gene De Lisa\n * \n */\npublic class NotationApp extends Application {\n\n private static final Logger logger = LoggerFactory\n .getLogger(NotationApp.class);\n Stage stage;\n Scene scene;\n Pane root;\n\n private NotationController controller;\n private StaffModel staffModel;\n // private NotationView view;\n // private NotationCanvas view;\n private StaffRegion view;\n\n // private StaffControl view;\n\n // private static ObservableList tableDataList;\n\n public static void main(String[] args) throws Exception {\n launch(args);\n }\n\n @Override\n public void start(Stage stage) throws Exception {\n this.stage = stage;\n\n this.staffModel = new StaffModel();\n MIDITrack track = MIDITrackBuilder\n .create()\n .noteString(\n \"E5 F G Ab G# A B C C6 D Eb F# G A B C7 B4 Bf4 A4 Af4\")\n .durations(1, 1.5, .5, .75, .25, .25)\n .sequential()\n .build();\n System.out.println(track);\n this.staffModel.setTrack(track);\n // this.view = new NotationCanvas(this.staffModel);\n this.view = new StaffRegion(this.staffModel);\n this.controller = new NotationController(staffModel, view);\n this.view.drawShapes();\n\n this.configureScene();\n this.configureStage();\n logger.debug(\"started\");\n }\n\n private void configureStage() {\n stage.setTitle(\"Music Notation\");\n\n // fullScreen();\n\n stage.setScene(this.scene);\n controller.setStage(this.stage);\n stage.show();\n }\n\n private void fullScreen() {\n // make it full screen\n stage.setX(0);\n stage.setY(0);\n stage.setWidth(Screen.getPrimary().getVisualBounds().getWidth());\n stage.setHeight(Screen.getPrimary().getVisualBounds().getHeight());\n }\n\n private void configureScene() {\n // TextField text = new TextField();\n // text.setId(\"noteStringText\");\n // text.setEditable(true);\n // text.setPromptText(\"Enter a note string\");\n // controller.setTextField(text);\n\n TextArea textArea = new TextArea();\n textArea.setId(\"noteStringText\");\n textArea.setEditable(true);\n textArea.setPromptText(\"Enter a note string\");\n textArea.setWrapText(true);\n textArea.setText(MIDITrack\n .getPitchesAsString(this.staffModel.getTrackProperty().get()));\n controller.setTextArea(textArea);\n \n Button b = ButtonBuilder.create()\n .id(\"noteStringButton\")\n .style(\"-fx-font: 22 arial; -fx-base: #1055FF;\")\n .text(\"Evaluate note string\")\n .build();\n controller.setNoteStringButton(b);\n Button pb = ButtonBuilder.create()\n .id(\"playButton\")\n .style(\"-fx-font: 22 arial; -fx-base: #1055FF;\")\n .text(\"Play\")\n .build();\n controller.setPlayButton(pb);\n\n final ComboBox clefComboBox = new ComboBox<>();\n clefComboBox.getItems().addAll(\n \"Treble\",\n \"Bass\",\n \"Alto\"\n );\n clefComboBox.getSelectionModel().selectFirst();\n clefComboBox.getSelectionModel().selectedItemProperty()\n .addListener(new ChangeListener() {\n @Override\n public void changed(\n ObservableValue observable,\n String oldValue, String newValue) {\n\n }\n });\n ;\n controller.setClefCombBox(clefComboBox);\n\n final ComboBox fontSizeComboBox = new ComboBox<>();\n fontSizeComboBox.getItems().addAll(12d, 24d, 36d, 48d, 72d, 96d);\n fontSizeComboBox.getSelectionModel().select(3);\n controller.setFontSizeComboBox(fontSizeComboBox);\n\n FXTextAreaReceiver receiver = new FXTextAreaReceiver();\n controller.addReceiver(receiver);\n\n HBox hbox = HBoxBuilder.create()\n .padding(new Insets(20))\n .children(clefComboBox, fontSizeComboBox)\n .build();\n HBox buttonbox = HBoxBuilder.create()\n .padding(new Insets(20))\n .children(b, pb)\n .build();\n\n VBox vbox = VBoxBuilder.create()\n .padding(new Insets(20))\n .children(textArea, buttonbox, hbox, receiver)\n .build();\n\n ScrollPane sp = new ScrollPane();\n // sp.setContent(view.getCanvas());\n sp.setContent(view);\n sp.setPrefSize(1300, 300);\n\n BorderPane bp = BorderPaneBuilder.create()\n .id(\"rootpane\")\n // .padding(new Insets(20))\n .style(\"-fx-padding: 30\")\n .top(sp)\n .center(vbox)\n .build();\n AnchorPane.setTopAnchor(bp, 10.0);\n AnchorPane.setBottomAnchor(bp, 10.0);\n AnchorPane.setLeftAnchor(bp, 10.0);\n AnchorPane.setRightAnchor(bp, 65.0);\n\n root = AnchorPaneBuilder.create()\n .children(bp)\n .build();\n\n this.scene = SceneBuilder.create()\n .root(root)\n .fill(Color.web(\"#1030F0\"))\n // .stylesheets(\"/styles/app2styles.css\")\n .build();\n }\n\n // private void configureSceneold() {\n //\n // // double fontSize = 24d;\n // // double fontSize = 36d;\n // double fontSize = 48d;\n // // double fontSize = 96d;\n // Font font = Font.loadFont(\n // FontApp.class.getResource(\"/fonts/Bravura.otf\")\n // .toExternalForm(),\n // fontSize);\n // // FontMetrics fm;\n //\n // // Font font = new Font(\"Bravura\", fontSize);\n //\n // Canvas canvas = new Canvas(1300, 250);\n // canvas.setOpacity(100);\n //\n // GraphicsContext gc = canvas.getGraphicsContext2D();\n // gc.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());\n // gc.setFill(Color.WHITE);\n // gc.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());\n // gc.setFill(Color.BLACK);\n // gc.setTextBaseline(VPos.CENTER);\n // gc.setFont(font);\n //\n // double x = 50d;\n // double y = 125d;\n // // double yinc = fontSize / 10d + 1.2; // magic number since we lack\n // // font\n // // metrics. works for 48. too much\n // // for 24 or 36\n //\n // this.yspacing = fontSize / 8d;\n //\n // gc.fillText(getGlyph(\"gClef\"), x, y - (this.yspacing * 2d));\n // // gc.fillText(getGlyph(\"fClef\"), x, y - (this.yspacing * 6d));\n //\n // this.trebleStaffBottom = y;\n // String staff = getGlyph(\"staff5Lines\");\n // for (double xx = x; xx < 1250; xx += fontSize / 2d) {\n // gc.fillText(staff, xx, y);\n // }\n //\n // gc.fillText(getGlyph(\"noteQuarterUp\"), x += fontSize, y);\n // gc.fillText(getGlyph(\"accidentalFlat\"), x += fontSize, y);\n // gc.fillText(getGlyph(\"noteQuarterDown\"), x += fontSize / 3d, y);\n // gc.fillText(getGlyph(\"noteHalfUp\"), x += fontSize, y);\n //\n // double yy = y;\n // // ascending scale\n // for (int i = 0; i < 12; i++, yy -= this.yspacing) {\n // gc.fillText(SymbolFactory.noteQuarterUp(), x += fontSize, yy);\n // }\n //\n // setupStaff();\n //\n // yy = this.trebleFlatYpositions[Pitch.D5];\n // gc.fillText(SymbolFactory.noteQuarterDownFlat(), x += fontSize, yy);\n //\n // yy = this.trebleFlatYpositions[Pitch.E5];\n // gc.fillText(SymbolFactory.noteQuarterDownFlat(), x += fontSize, yy);\n //\n // yy = this.trebleFlatYpositions[Pitch.F5];\n // gc.fillText(SymbolFactory.noteQuarterDownFlat(), x += fontSize, yy);\n //\n // yy = this.trebleFlatYpositions[Pitch.G5];\n // gc.fillText(SymbolFactory.noteQuarterDownFlat(), x += fontSize, yy);\n //\n // yy = this.trebleFlatYpositions[Pitch.A5];\n // gc.fillText(SymbolFactory.noteQuarterDownFlat(), x += fontSize, yy);\n //\n // yy = this.trebleFlatYpositions[Pitch.B5];\n // gc.fillText(SymbolFactory.noteQuarterDownFlat(), x += fontSize, yy);\n //\n // yy = this.trebleFlatYpositions[Pitch.C6];\n // gc.fillText(SymbolFactory.noteQuarterDownFlat(), x += fontSize, yy);\n //\n // int pitch = Pitch.EF6;\n // if (needFlats(pitch)) {\n // String ns = SymbolFactory.noteQuarterDownFlat();\n // yy = this.trebleFlatYpositions[pitch];\n // gc.fillText(ns, x += fontSize, yy);\n // }\n // // ledger? \"staff1Line\"\n //\n // /*\n // * \"noteheadBlack\": { \"stemDownNW\": [ 0.0, -0.184 ], \"stemUpSE\": [\n // * 1.328, 0.184 ] },\n // */\n //\n // // gc.fillText(\"abcedfghijklmnopqrstuvwxyz\", 50d, 150d);\n //\n // /*\n // * \"gClef\": { \"alternateCodepoint\": \"U+1D11E\", \"codepoint\": \"U+E050\" },\n // */\n //\n // // Image bgimage = new Image(getClass().getResourceAsStream(\n // // \"/images/background.jpg\"));\n // // ImageView imageView = ImageViewBuilder.create()\n // // .image(bgimage)\n // // .build();\n //\n // Button b = ButtonBuilder.create()\n // .id(\"someButton\")\n // .text(\"Button\")\n // .style(\"-fx-font: 22 arial; -fx-base: #b6e7c9;\")\n // // .onAction(new EventHandler() {\n // // @Override\n // // public void handle(ActionEvent e) {\n // // logger.debug(\"local button pressed {}\", e);\n // // }\n // // })\n // .build();\n //\n // // not a singleton: logger.debug(\"button builder {}\",\n // // ButtonBuilder.create());\n //\n // // the controller has the action handler\n // //this.controller.setButton(b);\n // //BorderPane.setAlignment(b, Pos.CENTER);\n //\n // BorderPane borderPane = new BorderPane();\n // // borderPane.setTop(toolbar);\n // // borderPane.setLeft(actionPane);\n // // borderPane.setRight(colorPane);\n //\n // borderPane.setCenter(view.getCanvasPane());\n //\n // // borderPane.setBottom(statusBar);\n //\n // Group group = new Group();\n // group.getChildren().add(canvas);\n // // group.getChildren().add(b);\n //\n // root =\n // BorderPaneBuilder\n // .create()\n // .id(\"rootpane\")\n // .padding(new Insets(20))\n // // .style(\"-fx-padding: 30\")\n // .center(group)\n // .build();\n //\n // this.scene = SceneBuilder.create()\n // // .root(root)\n // .root(borderPane)\n // .fill(Color.web(\"#103000\"))\n // // .stylesheets(\"/styles/app2styles.css\")\n // .build();\n //\n // // MIDITrack track = MIDITrackBuilder.create()\n // // .noteString(\"C D E\")\n // // .build();\n // // track.sequential();\n //\n // }\n\n}\n"},"message":{"kind":"string","value":"Removing builders"},"old_file":{"kind":"string","value":"rockymusic-fx/src/main/java/com/rockhoppertech/music/fx/cmn/NotationApp.java"},"subject":{"kind":"string","value":"Removing builders"},"git_diff":{"kind":"string","value":"ockymusic-fx/src/main/java/com/rockhoppertech/music/fx/cmn/NotationApp.java\n textArea.setEditable(true);\n textArea.setPromptText(\"Enter a note string\");\n textArea.setWrapText(true);\n textArea.setText(MIDITrack\n .getPitchesAsString(this.staffModel.getTrackProperty().get()));\n// textArea.setText(MIDITrack\n //.getPitchesAsString(this.staffModel.getTrackProperty().get()));\n \n textArea.setText(this.staffModel.getTrackProperty().get().toBriefMIDIString(\"\\n\"));\n controller.setTextArea(textArea);\n \n Button b = ButtonBuilder.create()"}}},{"rowIdx":863,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"dd28a84ccc917300a505f2ae4b3b7074803b83e2"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"lucko/helper"},"new_contents":{"kind":"string","value":"/*\n * Copyright (c) 2017 Lucko (Luck) \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\npackage me.lucko.helper.serialize;\n\nimport com.google.common.base.Preconditions;\nimport com.google.gson.JsonElement;\nimport com.google.gson.JsonObject;\n\nimport org.bukkit.Bukkit;\nimport org.bukkit.Location;\nimport org.bukkit.block.Block;\nimport org.bukkit.block.BlockFace;\n\n/**\n * An immutable and serializable location object\n */\npublic final class BlockPosition {\n public static BlockPosition deserialize(JsonElement element) {\n Preconditions.checkArgument(element.isJsonObject());\n JsonObject object = element.getAsJsonObject();\n\n Preconditions.checkArgument(object.has(\"x\"));\n Preconditions.checkArgument(object.has(\"y\"));\n Preconditions.checkArgument(object.has(\"z\"));\n Preconditions.checkArgument(object.has(\"world\"));\n\n int x = object.get(\"x\").getAsInt();\n int y = object.get(\"y\").getAsInt();\n int z = object.get(\"z\").getAsInt();\n String world = object.get(\"world\").getAsString();\n\n return of(x, y, z, world);\n }\n\n public static BlockPosition of(int x, int y, int z, String world) {\n return new BlockPosition(x, y, z, world);\n }\n\n public static BlockPosition of(Location location) {\n return of(location.getBlockX(), location.getBlockY(), location.getBlockZ(), location.getWorld().getName());\n }\n\n public static BlockPosition of(Block block) {\n return of(block.getLocation());\n }\n\n private final int x;\n private final int y;\n private final int z;\n private final String world;\n\n private Location bukkitLocation = null;\n\n private BlockPosition(int x, int y, int z, String world) {\n this.x = x;\n this.y = y;\n this.z = z;\n this.world = world;\n }\n\n public int getX() {\n return this.x;\n }\n\n public int getY() {\n return this.y;\n }\n\n public int getZ() {\n return this.z;\n }\n\n public String getWorld() {\n return this.world;\n }\n\n public synchronized Location toLocation() {\n if (bukkitLocation == null) {\n bukkitLocation = new Location(Bukkit.getWorld(world), x, y, z);\n }\n\n return bukkitLocation.clone();\n }\n\n public Block toBlock() {\n return toLocation().getBlock();\n }\n\n public BlockPosition getRelative(BlockFace face) {\n return BlockPosition.of(x + face.getModX(), y + face.getModY(), z + face.getModZ(), world);\n }\n\n public BlockPosition getRelative(BlockFace face, int distance) {\n return BlockPosition.of(x + (face.getModX() * distance), y + (face.getModY() * distance), z + (face.getModZ() * distance), world);\n }\n\n public BlockPosition add(int x, int y, int z) {\n return BlockPosition.of(this.x + x, this.y + y, this.z + z, world);\n }\n\n public BlockPosition subtract(int x, int y, int z) {\n return add(-x, -y, -z);\n }\n\n public JsonObject serialize() {\n JsonObject object = new JsonObject();\n object.addProperty(\"x\", x);\n object.addProperty(\"y\", y);\n object.addProperty(\"z\", z);\n object.addProperty(\"world\", world);\n return object;\n }\n\n @Override\n public boolean equals(Object o) {\n if (o == this) return true;\n if (!(o instanceof BlockPosition)) return false;\n final BlockPosition other = (BlockPosition) o;\n return this.getX() == other.getX() &&\n this.getY() == other.getY() &&\n this.getZ() == other.getZ() &&\n (this.getWorld() == null ? other.getWorld() == null : this.getWorld().equals(other.getWorld()));\n }\n\n @Override\n public int hashCode() {\n final int PRIME = 59;\n int result = 1;\n result = result * PRIME + this.getX();\n result = result * PRIME + this.getY();\n result = result * PRIME + this.getZ();\n result = result * PRIME + (this.getWorld() == null ? 43 : this.getWorld().hashCode());\n return result;\n }\n\n @Override\n public String toString() {\n return \"BlockPosition(x=\" + this.getX() + \", y=\" + this.getY() + \", z=\" + this.getZ() + \", world=\" + this.getWorld() + \")\";\n }\n\n}"},"new_file":{"kind":"string","value":"src/main/java/me/lucko/helper/serialize/BlockPosition.java"},"old_contents":{"kind":"string","value":"/*\n * Copyright (c) 2017 Lucko (Luck) \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\npackage me.lucko.helper.serialize;\n\nimport com.google.common.base.Preconditions;\nimport com.google.gson.JsonElement;\nimport com.google.gson.JsonObject;\n\nimport org.bukkit.Bukkit;\nimport org.bukkit.Location;\nimport org.bukkit.block.Block;\nimport org.bukkit.block.BlockFace;\n\n/**\n * An immutable and serializable location object\n */\npublic final class BlockPosition {\n public static BlockPosition deserialize(JsonElement element) {\n Preconditions.checkArgument(element.isJsonObject());\n JsonObject object = element.getAsJsonObject();\n\n Preconditions.checkArgument(object.has(\"x\"));\n Preconditions.checkArgument(object.has(\"y\"));\n Preconditions.checkArgument(object.has(\"z\"));\n Preconditions.checkArgument(object.has(\"world\"));\n\n int x = object.get(\"x\").getAsInt();\n int y = object.get(\"y\").getAsInt();\n int z = object.get(\"z\").getAsInt();\n String world = object.get(\"world\").getAsString();\n\n return of(x, y, z, world);\n }\n\n public static BlockPosition of(int x, int y, int z, String world) {\n return new BlockPosition(x, y, z, world, null);\n }\n\n public static BlockPosition of(Location location) {\n return of(location.getBlockX(), location.getBlockY(), location.getBlockZ(), location.getWorld().getName()).setBukkitLocation(location);\n }\n\n public static BlockPosition of(Block block) {\n return of(block.getLocation());\n }\n\n private final int x;\n private final int y;\n private final int z;\n private final String world;\n\n private Location bukkitLocation;\n\n private BlockPosition(int x, int y, int z, String world, Location bukkitLocation) {\n this.x = x;\n this.y = y;\n this.z = z;\n this.world = world;\n this.bukkitLocation = bukkitLocation;\n }\n\n public int getX() {\n return this.x;\n }\n\n public int getY() {\n return this.y;\n }\n\n public int getZ() {\n return this.z;\n }\n\n public String getWorld() {\n return this.world;\n }\n\n public synchronized Location toLocation() {\n if (bukkitLocation == null) {\n bukkitLocation = new Location(Bukkit.getWorld(world), x, y, z);\n }\n\n return bukkitLocation;\n }\n\n public Block toBlock() {\n return toLocation().getBlock();\n }\n\n private BlockPosition setBukkitLocation(Location bukkitLocation) {\n this.bukkitLocation = bukkitLocation;\n return this;\n }\n\n public BlockPosition getRelative(BlockFace face) {\n return BlockPosition.of(x + face.getModX(), y + face.getModY(), z + face.getModZ(), world);\n }\n\n public BlockPosition getRelative(BlockFace face, int distance) {\n return BlockPosition.of(x + (face.getModX() * distance), y + (face.getModY() * distance), z + (face.getModZ() * distance), world);\n }\n\n public BlockPosition add(int x, int y, int z) {\n return BlockPosition.of(this.x + x, this.y + y, this.z + z, world);\n }\n\n public BlockPosition subtract(int x, int y, int z) {\n return add(-x, -y, -z);\n }\n\n public JsonObject serialize() {\n JsonObject object = new JsonObject();\n object.addProperty(\"x\", x);\n object.addProperty(\"y\", y);\n object.addProperty(\"z\", z);\n object.addProperty(\"world\", world);\n return object;\n }\n\n @Override\n public boolean equals(Object o) {\n if (o == this) return true;\n if (!(o instanceof BlockPosition)) return false;\n final BlockPosition other = (BlockPosition) o;\n return this.getX() == other.getX() &&\n this.getY() == other.getY() &&\n this.getZ() == other.getZ() &&\n (this.getWorld() == null ? other.getWorld() == null : this.getWorld().equals(other.getWorld()));\n }\n\n @Override\n public int hashCode() {\n final int PRIME = 59;\n int result = 1;\n result = result * PRIME + this.getX();\n result = result * PRIME + this.getY();\n result = result * PRIME + this.getZ();\n result = result * PRIME + (this.getWorld() == null ? 43 : this.getWorld().hashCode());\n return result;\n }\n\n @Override\n public String toString() {\n return \"BlockPosition(x=\" + this.getX() + \", y=\" + this.getY() + \", z=\" + this.getZ() + \", world=\" + this.getWorld() + \")\";\n }\n\n}"},"message":{"kind":"string","value":"fix potential issue with cloned locations\n"},"old_file":{"kind":"string","value":"src/main/java/me/lucko/helper/serialize/BlockPosition.java"},"subject":{"kind":"string","value":"fix potential issue with cloned locations"},"git_diff":{"kind":"string","value":"rc/main/java/me/lucko/helper/serialize/BlockPosition.java\n }\n \n public static BlockPosition of(int x, int y, int z, String world) {\n return new BlockPosition(x, y, z, world, null);\n return new BlockPosition(x, y, z, world);\n }\n \n public static BlockPosition of(Location location) {\n return of(location.getBlockX(), location.getBlockY(), location.getBlockZ(), location.getWorld().getName()).setBukkitLocation(location);\n return of(location.getBlockX(), location.getBlockY(), location.getBlockZ(), location.getWorld().getName());\n }\n \n public static BlockPosition of(Block block) {\n private final int z;\n private final String world;\n \n private Location bukkitLocation;\n private Location bukkitLocation = null;\n \n private BlockPosition(int x, int y, int z, String world, Location bukkitLocation) {\n private BlockPosition(int x, int y, int z, String world) {\n this.x = x;\n this.y = y;\n this.z = z;\n this.world = world;\n this.bukkitLocation = bukkitLocation;\n }\n \n public int getX() {\n bukkitLocation = new Location(Bukkit.getWorld(world), x, y, z);\n }\n \n return bukkitLocation;\n return bukkitLocation.clone();\n }\n \n public Block toBlock() {\n return toLocation().getBlock();\n }\n\n private BlockPosition setBukkitLocation(Location bukkitLocation) {\n this.bukkitLocation = bukkitLocation;\n return this;\n }\n \n public BlockPosition getRelative(BlockFace face) {"}}},{"rowIdx":864,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"1306364a2fbd381a338402dc7963451d30e1fc8e"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"dschadow/ApplicationIntrusionDetection,dschadow/ApplicationIntrusionDetection"},"new_contents":{"kind":"string","value":"/*\n * Copyright (C) 2017 Dominik Schadow, dominikschadow@gmail.com\n *\n * This file is part of the Application Intrusion Detection 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 de.dominikschadow.dukeencounters.confirmation;\n\nimport de.dominikschadow.dukeencounters.encounter.EncounterService;\nimport de.dominikschadow.dukeencounters.user.UserService;\nimport org.junit.Before;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.rules.ExpectedException;\nimport org.mockito.Mock;\nimport org.mockito.MockitoAnnotations;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.mockito.BDDMockito.given;\n\n/**\n * Tests the [@link ConfirmationService} class.\n *\n * @author Dominik Schadow\n */\npublic class ConfirmationServiceTest {\n @Rule\n public ExpectedException thrown = ExpectedException.none();\n\n @Mock\n private ConfirmationRepository repository;\n @Mock\n private UserService userService;\n @Mock\n private EncounterService encounterService;\n\n private ConfirmationService service;\n\n private Confirmation testConfirmation;\n\n @Before\n public void setup() {\n MockitoAnnotations.initMocks(this);\n service = new ConfirmationService(repository, userService, encounterService);\n\n testConfirmation = new Confirmation();\n testConfirmation.setId(1);\n }\n\n @Test\n public void getConfirmationsByUsernameWhenUsernameIsNullShouldThrowException() throws Exception {\n thrown.expect(NullPointerException.class);\n thrown.expectMessage(\"username\");\n service.getConfirmationsByUsername(null);\n }\n\n @Test\n public void getConfirmationByUsernameAndEncounterIdWhenUsernameAndIdAreValidReturnsConfirmation() throws Exception {\n given(repository.findByUsernameAndEncounterId(\"test\", 1)).willReturn(testConfirmation);\n Confirmation confirmation = service.getConfirmationByUsernameAndEncounterId(\"test\", 1);\n\n assertThat(confirmation.getId()).isEqualTo(1);\n }\n\n\n\n}"},"new_file":{"kind":"string","value":"duke-encounters/src/test/java/de/dominikschadow/dukeencounters/confirmation/ConfirmationServiceTest.java"},"old_contents":{"kind":"string","value":"/*\n * Copyright (C) 2017 Dominik Schadow, dominikschadow@gmail.com\n *\n * This file is part of the Application Intrusion Detection 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 de.dominikschadow.dukeencounters.confirmation;\n\nimport de.dominikschadow.dukeencounters.encounter.EncounterService;\nimport de.dominikschadow.dukeencounters.user.UserService;\nimport org.junit.Before;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.rules.ExpectedException;\nimport org.mockito.Mock;\nimport org.mockito.MockitoAnnotations;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.mockito.BDDMockito.given;\n\n/**\n * Tests the [@link ConfirmationService} class.\n *\n * @author Dominik Schadow\n */\npublic class ConfirmationServiceTest {\n @Rule\n public ExpectedException thrown = ExpectedException.none();\n\n @Mock\n private ConfirmationRepository repository;\n @Mock\n private UserService userService;\n @Mock\n private EncounterService encounterService;\n\n private ConfirmationService service;\n\n private Confirmation testConfirmation;\n\n @Before\n public void setup() {\n MockitoAnnotations.initMocks(this);\n service = new ConfirmationService(repository, userService, encounterService);\n\n testConfirmation = new Confirmation();\n testConfirmation.setId(1);\n }\n\n @Test\n public void getConfirmationsByUsernameWhenUsernameIsNullShouldThrowException() throws Exception {\n thrown.expect(NullPointerException.class);\n thrown.expectMessage(\"username\");\n service.getConfirmationsByUsername(null);\n }\n\n @Test\n public void getConfirmationByUsernameAndEncounterId() throws Exception {\n given(repository.findByUsernameAndEncounterId(\"test\", 1)).willReturn(testConfirmation);\n Confirmation confirmation = service.getConfirmationByUsernameAndEncounterId(\"test\", 1);\n\n assertThat(confirmation.getId()).isEqualTo(1);\n }\n\n\n\n}"},"message":{"kind":"string","value":"Renamed test\n"},"old_file":{"kind":"string","value":"duke-encounters/src/test/java/de/dominikschadow/dukeencounters/confirmation/ConfirmationServiceTest.java"},"subject":{"kind":"string","value":"Renamed test"},"git_diff":{"kind":"string","value":"uke-encounters/src/test/java/de/dominikschadow/dukeencounters/confirmation/ConfirmationServiceTest.java\n }\n \n @Test\n public void getConfirmationByUsernameAndEncounterId() throws Exception {\n public void getConfirmationByUsernameAndEncounterIdWhenUsernameAndIdAreValidReturnsConfirmation() throws Exception {\n given(repository.findByUsernameAndEncounterId(\"test\", 1)).willReturn(testConfirmation);\n Confirmation confirmation = service.getConfirmationByUsernameAndEncounterId(\"test\", 1);\n "}}},{"rowIdx":865,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"943b6ed12cbe9528936070a8b6d7995f79a410f6"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"andy256/druid,Kleagleguo/druid,taochaoqiang/druid,fjy/druid,Fokko/druid,praveev/druid,Deebs21/druid,calliope7/druid,skyportsystems/druid,rasahner/druid,dclim/druid,Fokko/druid,yaochitc/druid-dev,andy256/druid,noddi/druid,anupkumardixit/druid,monetate/druid,druid-io/druid,pjain1/druid,metamx/druid,wenjixin/druid,cocosli/druid,leventov/druid,optimizely/druid,rasahner/druid,tubemogul/druid,metamx/druid,Fokko/druid,Kleagleguo/druid,implydata/druid,zhiqinghuang/druid,authbox-lib/druid,pombredanne/druid,mangeshpardeshiyahoo/druid,elijah513/druid,dclim/druid,fjy/druid,zhaown/druid,amikey/druid,leventov/druid,qix/druid,anupkumardixit/druid,implydata/druid,friedhardware/druid,noddi/druid,Deebs21/druid,metamx/druid,gianm/druid,mghosh4/druid,mrijke/druid,dkhwangbo/druid,nvoron23/druid,nvoron23/druid,druid-io/druid,guobingkun/druid,authbox-lib/druid,leventov/druid,wenjixin/druid,andy256/druid,potto007/druid-avro,redBorder/druid,haoch/druid,gianm/druid,michaelschiff/druid,premc/druid,jon-wei/druid,se7entyse7en/druid,penuel-leo/druid,knoguchi/druid,haoch/druid,b-slim/druid,pombredanne/druid,friedhardware/druid,authbox-lib/druid,authbox-lib/druid,erikdubbelboer/druid,implydata/druid,zhihuij/druid,himanshug/druid,nishantmonu51/druid,b-slim/druid,minewhat/druid,monetate/druid,KurtYoung/druid,haoch/druid,zxs/druid,qix/druid,767326791/druid,deltaprojects/druid,authbox-lib/druid,zhiqinghuang/druid,Deebs21/druid,zengzhihai110/druid,elijah513/druid,KurtYoung/druid,lcp0578/druid,fjy/druid,liquidm/druid,premc/druid,nvoron23/druid,mghosh4/druid,erikdubbelboer/druid,nvoron23/druid,praveev/druid,yaochitc/druid-dev,premc/druid,zengzhihai110/druid,skyportsystems/druid,rasahner/druid,deltaprojects/druid,himanshug/druid,cocosli/druid,gianm/druid,minewhat/druid,pjain1/druid,zhihuij/druid,se7entyse7en/druid,redBorder/druid,zxs/druid,zxs/druid,nishantmonu51/druid,lcp0578/druid,minewhat/druid,767326791/druid,pombredanne/druid,himanshug/druid,pdeva/druid,guobingkun/druid,eshen1991/druid,guobingkun/druid,monetate/druid,zhaown/druid,eshen1991/druid,milimetric/druid,anupkumardixit/druid,milimetric/druid,skyportsystems/druid,du00cs/druid,lcp0578/druid,767326791/druid,praveev/druid,mrijke/druid,jon-wei/druid,mrijke/druid,andy256/druid,deltaprojects/druid,andy256/druid,winval/druid,druid-io/druid,calliope7/druid,Deebs21/druid,tubemogul/druid,solimant/druid,du00cs/druid,noddi/druid,tubemogul/druid,zengzhihai110/druid,mrijke/druid,michaelschiff/druid,friedhardware/druid,optimizely/druid,minewhat/druid,fjy/druid,himanshug/druid,zhaown/druid,redBorder/druid,deltaprojects/druid,pombredanne/druid,potto007/druid-avro,wenjixin/druid,liquidm/druid,pjain1/druid,deltaprojects/druid,zhiqinghuang/druid,skyportsystems/druid,premc/druid,jon-wei/druid,Deebs21/druid,lizhanhui/data_druid,milimetric/druid,potto007/druid-avro,mghosh4/druid,guobingkun/druid,zhihuij/druid,Kleagleguo/druid,OttoOps/druid,metamx/druid,767326791/druid,dclim/druid,knoguchi/druid,dkhwangbo/druid,praveev/druid,Fokko/druid,smartpcr/druid,eshen1991/druid,du00cs/druid,premc/druid,lcp0578/druid,himanshug/druid,druid-io/druid,amikey/druid,se7entyse7en/druid,Fokko/druid,penuel-leo/druid,qix/druid,tubemogul/druid,anupkumardixit/druid,mrijke/druid,taochaoqiang/druid,penuel-leo/druid,zhihuij/druid,milimetric/druid,minewhat/druid,OttoOps/druid,nishantmonu51/druid,dclim/druid,noddi/druid,KurtYoung/druid,michaelschiff/druid,monetate/druid,redBorder/druid,kevintvh/druid,anupkumardixit/druid,zengzhihai110/druid,winval/druid,dkhwangbo/druid,pjain1/druid,pjain1/druid,calliope7/druid,zhihuij/druid,leventov/druid,dclim/druid,se7entyse7en/druid,pdeva/druid,liquidm/druid,yaochitc/druid-dev,mangeshpardeshiyahoo/druid,redBorder/druid,smartpcr/druid,lizhanhui/data_druid,dkhwangbo/druid,calliope7/druid,michaelschiff/druid,KurtYoung/druid,optimizely/druid,smartpcr/druid,potto007/druid-avro,leventov/druid,zhiqinghuang/druid,skyportsystems/druid,zhaown/druid,eshen1991/druid,zhaown/druid,guobingkun/druid,deltaprojects/druid,cocosli/druid,tubemogul/druid,solimant/druid,du00cs/druid,solimant/druid,yaochitc/druid-dev,friedhardware/druid,liquidm/druid,Kleagleguo/druid,winval/druid,metamx/druid,mangeshpardeshiyahoo/druid,haoch/druid,lizhanhui/data_druid,pjain1/druid,rasahner/druid,jon-wei/druid,mangeshpardeshiyahoo/druid,Fokko/druid,zxs/druid,liquidm/druid,zxs/druid,nishantmonu51/druid,KurtYoung/druid,mghosh4/druid,pdeva/druid,elijah513/druid,amikey/druid,praveev/druid,eshen1991/druid,pdeva/druid,nishantmonu51/druid,zengzhihai110/druid,wenjixin/druid,taochaoqiang/druid,erikdubbelboer/druid,noddi/druid,erikdubbelboer/druid,gianm/druid,amikey/druid,implydata/druid,optimizely/druid,b-slim/druid,michaelschiff/druid,yaochitc/druid-dev,knoguchi/druid,knoguchi/druid,kevintvh/druid,knoguchi/druid,amikey/druid,calliope7/druid,taochaoqiang/druid,kevintvh/druid,monetate/druid,friedhardware/druid,implydata/druid,winval/druid,optimizely/druid,lizhanhui/data_druid,liquidm/druid,mangeshpardeshiyahoo/druid,fjy/druid,winval/druid,lcp0578/druid,nishantmonu51/druid,solimant/druid,nvoron23/druid,nishantmonu51/druid,penuel-leo/druid,gianm/druid,haoch/druid,qix/druid,wenjixin/druid,erikdubbelboer/druid,pombredanne/druid,milimetric/druid,OttoOps/druid,rasahner/druid,pdeva/druid,elijah513/druid,mghosh4/druid,gianm/druid,cocosli/druid,pjain1/druid,jon-wei/druid,smartpcr/druid,b-slim/druid,se7entyse7en/druid,kevintvh/druid,deltaprojects/druid,jon-wei/druid,solimant/druid,taochaoqiang/druid,kevintvh/druid,qix/druid,potto007/druid-avro,monetate/druid,smartpcr/druid,Kleagleguo/druid,penuel-leo/druid,implydata/druid,OttoOps/druid,elijah513/druid,mghosh4/druid,767326791/druid,lizhanhui/data_druid,dkhwangbo/druid,zhiqinghuang/druid,jon-wei/druid,druid-io/druid,cocosli/druid,gianm/druid,michaelschiff/druid,michaelschiff/druid,OttoOps/druid,b-slim/druid,mghosh4/druid,monetate/druid,Fokko/druid,du00cs/druid"},"new_contents":{"kind":"string","value":"/*\n * Druid - a distributed column store.\n * Copyright (C) 2012, 2013 Metamarkets Group Inc.\n *\n * This program is free software; you can redistribute it and/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 2\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\npackage io.druid;\n\nimport com.google.common.collect.Lists;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.inject.Binder;\nimport com.google.inject.Inject;\nimport com.google.inject.Injector;\nimport com.google.inject.Module;\nimport com.google.inject.servlet.GuiceFilter;\nimport com.metamx.common.lifecycle.Lifecycle;\nimport com.metamx.http.client.HttpClient;\nimport com.metamx.http.client.response.StatusResponseHandler;\nimport com.metamx.http.client.response.StatusResponseHolder;\nimport io.druid.guice.Jerseys;\nimport io.druid.guice.LazySingleton;\nimport io.druid.guice.annotations.Global;\nimport io.druid.initialization.Initialization;\nimport io.druid.server.initialization.JettyServerInitializer;\nimport org.eclipse.jetty.server.Handler;\nimport org.eclipse.jetty.server.Server;\nimport org.eclipse.jetty.server.handler.DefaultHandler;\nimport org.eclipse.jetty.server.handler.HandlerList;\nimport org.eclipse.jetty.servlet.DefaultServlet;\nimport org.eclipse.jetty.servlet.ServletContextHandler;\nimport org.eclipse.jetty.servlet.ServletHolder;\nimport org.eclipse.jetty.servlets.GzipFilter;\nimport org.junit.Ignore;\nimport org.junit.Test;\n\nimport javax.ws.rs.GET;\nimport javax.ws.rs.Path;\nimport javax.ws.rs.Produces;\nimport javax.ws.rs.core.Response;\nimport java.net.URL;\nimport java.nio.charset.Charset;\nimport java.util.Random;\nimport java.util.concurrent.CountDownLatch;\nimport java.util.concurrent.Executor;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicLong;\n\npublic class JettyTest\n{\n public static void setProperties()\n {\n System.setProperty(\"druid.host\", \"localhost:9999\");\n System.setProperty(\"druid.port\", \"9999\");\n System.setProperty(\"druid.server.http.numThreads\", \"20\");\n System.setProperty(\"druid.service\", \"test\");\n System.setProperty(\"druid.server.http.maxIdleTime\", \"PT1S\");\n System.setProperty(\"druid.global.http.readTimeout\", \"PT1S\");\n }\n\n @Test @Ignore // this test will deadlock if it hits an issue, so ignored by default\n public void testTimeouts() throws Exception\n {\n // test for request timeouts properly not locking up all threads\n\n setProperties();\n Injector injector = Initialization.makeInjectorWithModules(\n Initialization.makeStartupInjector(), Lists.newArrayList(\n new Module()\n {\n @Override\n public void configure(Binder binder)\n {\n binder.bind(JettyServerInitializer.class).to(JettyServerInit.class).in(LazySingleton.class);\n Jerseys.addResource(binder, SlowResource.class);\n\n }\n }\n )\n );\n Lifecycle lifecycle = injector.getInstance(Lifecycle.class);\n // Jetty is Lazy Initialized do a getInstance\n injector.getInstance(Server.class);\n lifecycle.start();\n ClientHolder holder = injector.getInstance(ClientHolder.class);\n final HttpClient client = holder.getClient();\n final Executor executor = Executors.newFixedThreadPool(100);\n final AtomicLong count = new AtomicLong(0);\n final CountDownLatch latch = new CountDownLatch(1000);\n for (int i = 0; i < 10000; i++) {\n executor.execute(\n new Runnable()\n {\n @Override\n public void run()\n {\n executor.execute(\n new Runnable()\n {\n @Override\n public void run()\n {\n long startTime = System.currentTimeMillis();\n long startTime2 = 0;\n try {\n ListenableFuture go = client.get(\n new URL(\n \"http://localhost:9999/slow/hello\"\n )\n )\n .go(new StatusResponseHandler(Charset.defaultCharset()));\n startTime2 = System.currentTimeMillis();\n go.get();\n }\n catch (Exception e) {\n e.printStackTrace();\n }\n finally {\n System.out\n .println(\n \"Response time client\"\n + (System.currentTimeMillis() - startTime)\n + \"time taken for getting future\"\n + (System.currentTimeMillis() - startTime2)\n + \"Counter \" + count.incrementAndGet()\n );\n latch.countDown();\n\n }\n }\n }\n );\n }\n }\n );\n }\n\n latch.await();\n lifecycle.stop();\n\n }\n\n public static class ClientHolder\n {\n HttpClient client;\n\n @Inject\n ClientHolder(@Global HttpClient client)\n {\n this.client = client;\n }\n\n public HttpClient getClient()\n {\n return client;\n }\n }\n\n public static class JettyServerInit implements JettyServerInitializer\n {\n\n @Override\n public void initialize(Server server, Injector injector)\n {\n final ServletContextHandler root = new ServletContextHandler(ServletContextHandler.SESSIONS);\n root.addServlet(new ServletHolder(new DefaultServlet()), \"/*\");\n root.addFilter(GzipFilter.class, \"/*\", null);\n root.addFilter(GuiceFilter.class, \"/*\", null);\n\n final HandlerList handlerList = new HandlerList();\n handlerList.setHandlers(new Handler[]{root, new DefaultHandler()});\n server.setHandler(handlerList);\n }\n }\n\n @Path(\"/slow\")\n public static class SlowResource\n {\n\n public static Random random = new Random();\n\n @GET\n @Path(\"/hello\")\n @Produces(\"application/json\")\n public Response hello()\n {\n try {\n TimeUnit.MILLISECONDS.sleep(100 + random.nextInt(2000));\n }\n catch (InterruptedException e) {\n //\n }\n return Response.ok(\"hello\").build();\n }\n }\n}\n"},"new_file":{"kind":"string","value":"server/src/test/java/io/druid/server/initialization/JettyTest.java"},"old_contents":{"kind":"string","value":"/*\n * Druid - a distributed column store.\n * Copyright (C) 2012, 2013 Metamarkets Group Inc.\n *\n * This program is free software; you can redistribute it and/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 2\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\npackage io.druid;\n\nimport com.google.common.collect.Lists;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.inject.Binder;\nimport com.google.inject.Inject;\nimport com.google.inject.Injector;\nimport com.google.inject.Module;\nimport com.google.inject.servlet.GuiceFilter;\nimport com.metamx.common.lifecycle.Lifecycle;\nimport com.metamx.http.client.HttpClient;\nimport com.metamx.http.client.response.StatusResponseHandler;\nimport com.metamx.http.client.response.StatusResponseHolder;\nimport io.druid.guice.Jerseys;\nimport io.druid.guice.LazySingleton;\nimport io.druid.guice.annotations.Global;\nimport io.druid.initialization.Initialization;\nimport io.druid.server.initialization.JettyServerInitializer;\nimport org.eclipse.jetty.server.Handler;\nimport org.eclipse.jetty.server.Server;\nimport org.eclipse.jetty.server.handler.DefaultHandler;\nimport org.eclipse.jetty.server.handler.HandlerList;\nimport org.eclipse.jetty.servlet.DefaultServlet;\nimport org.eclipse.jetty.servlet.ServletContextHandler;\nimport org.eclipse.jetty.servlet.ServletHolder;\nimport org.eclipse.jetty.servlets.GzipFilter;\nimport org.junit.Ignore;\nimport org.junit.Test;\n\nimport javax.ws.rs.GET;\nimport javax.ws.rs.Path;\nimport javax.ws.rs.Produces;\nimport javax.ws.rs.core.Response;\nimport java.net.URL;\nimport java.nio.charset.Charset;\nimport java.util.Random;\nimport java.util.concurrent.CountDownLatch;\nimport java.util.concurrent.Executor;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicLong;\n\npublic class JettyTest\n{\n public static void setProperties()\n {\n System.setProperty(\"druid.host\", \"localhost:9999\");\n System.setProperty(\"druid.port\", \"9999\");\n System.setProperty(\"druid.server.http.numThreads\", \"20\");\n System.setProperty(\"druid.service\", \"test\");\n System.setProperty(\"druid.server.http.maxIdleTime\", \"PT1S\");\n System.setProperty(\"druid.global.http.readTimeout\", \"PT1S\");\n }\n\n @Test\n @Ignore\n public void testTimeouts() throws Exception\n {\n setProperties();\n Injector injector = Initialization.makeInjectorWithModules(\n Initialization.makeStartupInjector(), Lists.newArrayList(\n new Module()\n {\n @Override\n public void configure(Binder binder)\n {\n binder.bind(JettyServerInitializer.class).to(JettyServerInit.class).in(LazySingleton.class);\n Jerseys.addResource(binder, SlowResource.class);\n\n }\n }\n )\n );\n Lifecycle lifecycle = injector.getInstance(Lifecycle.class);\n // Jetty is Lazy Initialized do a getInstance\n injector.getInstance(Server.class);\n lifecycle.start();\n ClientHolder holder = injector.getInstance(ClientHolder.class);\n final HttpClient client = holder.getClient();\n final Executor executor = Executors.newFixedThreadPool(100);\n final AtomicLong count = new AtomicLong(0);\n final CountDownLatch latch = new CountDownLatch(1000);\n for (int i = 0; i < 10000; i++) {\n executor.execute(\n new Runnable()\n {\n @Override\n public void run()\n {\n executor.execute(\n new Runnable()\n {\n @Override\n public void run()\n {\n long startTime = System.currentTimeMillis();\n long startTime2 = 0;\n try {\n ListenableFuture go = client.get(\n new URL(\n \"http://localhost:9999/slow/hello\"\n )\n )\n .go(new StatusResponseHandler(Charset.defaultCharset()));\n startTime2 = System.currentTimeMillis();\n go.get();\n }\n catch (Exception e) {\n e.printStackTrace();\n }\n finally {\n System.out\n .println(\n \"Response time client\"\n + (System.currentTimeMillis() - startTime)\n + \"time taken for getting future\"\n + (System.currentTimeMillis() - startTime2)\n + \"Counter \" + count.incrementAndGet()\n );\n latch.countDown();\n\n }\n }\n }\n );\n }\n }\n );\n }\n\n latch.await();\n lifecycle.stop();\n\n }\n\n public static class ClientHolder\n {\n HttpClient client;\n\n @Inject\n ClientHolder(@Global HttpClient client)\n {\n this.client = client;\n }\n\n public HttpClient getClient()\n {\n return client;\n }\n }\n\n public static class JettyServerInit implements JettyServerInitializer\n {\n\n @Override\n public void initialize(Server server, Injector injector)\n {\n final ServletContextHandler root = new ServletContextHandler(ServletContextHandler.SESSIONS);\n root.addServlet(new ServletHolder(new DefaultServlet()), \"/*\");\n root.addFilter(GzipFilter.class, \"/*\", null);\n root.addFilter(GuiceFilter.class, \"/*\", null);\n\n final HandlerList handlerList = new HandlerList();\n handlerList.setHandlers(new Handler[]{root, new DefaultHandler()});\n server.setHandler(handlerList);\n }\n }\n\n @Path(\"/slow\")\n public static class SlowResource\n {\n\n public static Random random = new Random();\n\n @GET\n @Path(\"/hello\")\n @Produces(\"application/json\")\n public Response hello()\n {\n try {\n TimeUnit.MILLISECONDS.sleep(100 + random.nextInt(2000));\n }\n catch (InterruptedException e) {\n //\n }\n return Response.ok(\"hello\").build();\n }\n }\n}\n"},"message":{"kind":"string","value":"add comments\n"},"old_file":{"kind":"string","value":"server/src/test/java/io/druid/server/initialization/JettyTest.java"},"subject":{"kind":"string","value":"add comments"},"git_diff":{"kind":"string","value":"erver/src/test/java/io/druid/server/initialization/JettyTest.java\n System.setProperty(\"druid.global.http.readTimeout\", \"PT1S\");\n }\n \n @Test\n @Ignore\n @Test @Ignore // this test will deadlock if it hits an issue, so ignored by default\n public void testTimeouts() throws Exception\n {\n // test for request timeouts properly not locking up all threads\n\n setProperties();\n Injector injector = Initialization.makeInjectorWithModules(\n Initialization.makeStartupInjector(), Lists.newArrayList("}}},{"rowIdx":866,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"11ff4a94f5768ffdf526d89bfb030a053fa64304"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"j-fuentes/cas,zhoffice/cas,kalatestimine/cas,fogbeam/fogbeam_cas,fengbaicanhe/cas,jacklotusho/cas,mduszyk/cas,zhangwei5095/jasig-cas-server,rallportctr/cas,DICE-UNC/cas,creamer/cas,rallportctr/cas,zawn/cas,zhangjianTFTC/cas,fengbaicanhe/cas,austgl/cas,joansmith/cas,icereval/cas,zhangwei5095/jasig-cas-server,Kevin2030/cas,zhangjianTFTC/cas,thomasdarimont/cas,mduszyk/cas,thomasdarimont/cas,PetrGasparik/cas,PetrGasparik/cas,ssmyka/cas,yisiqi/cas,mduszyk/cas,thomasdarimont/cas,eBaoTech/cas,luneo7/cas,j-fuentes/cas,zhaorui1/cas,ssmyka/cas,creamer/cas,nader93k/cas,j-fuentes/cas,j-fuentes/cas,creamer/cas,PetrGasparik/cas,fogbeam/fogbeam_cas,fannyfinal/cas,HuangWeiWei1919/cas,battags/cas,rallportctr/cas,luneo7/cas,austgl/cas,Kuohong/cas,Kuohong/cas,zhangwei5095/jasig-cas-server,fannyfinal/cas,Kuohong/cas,austgl/cas,austgl/cas,moghaddam/cas,yisiqi/cas,vbonamy/cas,DICE-UNC/cas,vbonamy/cas,jasonchw/cas,kalatestimine/cas,zhangjianTFTC/cas,icereval/cas,Kuohong/cas,yisiqi/cas,Kevin2030/cas,nestle1998/cas,thomasdarimont/cas,lijihuai/cas,jasonchw/cas,joansmith/cas,rallportctr/cas,joansmith/cas,zhangjianTFTC/cas,icereval/cas,eBaoTech/cas,moghaddam/cas,youjava/cas,nestle1998/cas,joansmith/cas,Kevin2030/cas,jacklotusho/cas,jacklotusho/cas,fogbeam/fogbeam_cas,moghaddam/cas,yisiqi/cas,vbonamy/cas,battags/cas,icereval/cas,nestle1998/cas,ssmyka/cas,zawn/cas,jasonchw/cas,zhaorui1/cas,Kevin2030/cas,ssmyka/cas,battags/cas,nader93k/cas,eBaoTech/cas,zhoffice/cas,fengbaicanhe/cas,jasonchw/cas,zhangwei5095/jasig-cas-server,youjava/cas,fengbaicanhe/cas,DICE-UNC/cas,kalatestimine/cas,mduszyk/cas,zhoffice/cas,youjava/cas,nader93k/cas,HuangWeiWei1919/cas,jacklotusho/cas,fannyfinal/cas,luneo7/cas,kalatestimine/cas,zhaorui1/cas,nader93k/cas,lijihuai/cas,zhoffice/cas,lijihuai/cas,fannyfinal/cas,fogbeam/fogbeam_cas,HuangWeiWei1919/cas,DICE-UNC/cas,eBaoTech/cas,lijihuai/cas,zhaorui1/cas,youjava/cas,battags/cas,HuangWeiWei1919/cas,zawn/cas,PetrGasparik/cas,nestle1998/cas,luneo7/cas,zawn/cas,vbonamy/cas,moghaddam/cas,creamer/cas"},"new_contents":{"kind":"string","value":"/*\n * Licensed to Apereo under one or more contributor license\n * agreements. See the NOTICE file distributed with this work\n * for additional information regarding copyright ownership.\n * Apereo licenses this file to you under the Apache License,\n * Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a\n * copy of the License at the following location:\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.jasig.cas.adaptors.x509.authentication.handler.support;\n\nimport java.security.GeneralSecurityException;\nimport java.security.cert.X509CRL;\nimport java.security.cert.X509CRLEntry;\nimport java.security.cert.X509Certificate;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Iterator;\nimport java.util.List;\n\nimport javax.validation.constraints.NotNull;\n\nimport org.jasig.cas.adaptors.x509.util.CertUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * Base class for all CRL-based revocation checkers.\n *\n * @author Marvin S. Addison\n * @since 3.4.6\n *\n */\npublic abstract class AbstractCRLRevocationChecker implements RevocationChecker {\n /** Logger instance. **/\n protected final Logger logger = LoggerFactory.getLogger(getClass());\n\n /**\n * Flag to indicate whether all\n * crls should be checked for the cert resource.\n * Defaults to false.\n **/\n protected boolean checkAll;\n\n /** Policy to apply when CRL data is unavailable. */\n @NotNull\n private RevocationPolicy unavailableCRLPolicy = new DenyRevocationPolicy();\n\n /** Policy to apply when CRL data has expired. */\n @NotNull\n private RevocationPolicy expiredCRLPolicy = new ThresholdExpiredCRLRevocationPolicy();\n\n /**\n * {@inheritDoc}\n **/\n @Override\n public void check(final X509Certificate cert) throws GeneralSecurityException {\n if (cert == null) {\n throw new IllegalArgumentException(\"Certificate cannot be null.\");\n }\n logger.debug(\"Evaluating certificate revocation status for {}\", CertUtils.toString(cert));\n final Collection crls = getCRLs(cert);\n\n if (crls == null || crls.isEmpty()) {\n logger.warn(\"CRL data is not available for {}\", CertUtils.toString(cert));\n this.unavailableCRLPolicy.apply(null);\n return;\n }\n\n final List expiredCrls = new ArrayList<>();\n final List revokedCrls = new ArrayList<>();\n\n final Iterator it = crls.iterator();\n while (it.hasNext()) {\n final X509CRL crl = it.next();\n if (CertUtils.isExpired(crl)) {\n logger.warn(\"CRL data expired on {}\", crl.getNextUpdate());\n expiredCrls.add(crl);\n }\n }\n\n if (crls.size() == expiredCrls.size()) {\n logger.warn(\"All CRLs retrieved have expired. Applying CRL expiration policy...\");\n for (final X509CRL crl : expiredCrls) {\n this.expiredCRLPolicy.apply(crl);\n }\n } else {\n crls.removeAll(expiredCrls);\n logger.debug(\"Valid CRLs [{}] found that are not expired yet\", crls);\n\n for (final X509CRL crl : crls) {\n final X509CRLEntry entry = crl.getRevokedCertificate(cert);\n if (entry != null) {\n revokedCrls.add(entry);\n }\n }\n\n if (revokedCrls.size() == crls.size()) {\n final X509CRLEntry entry = revokedCrls.get(0);\n logger.warn(\"All CRL entries have been revoked. Rejecting the first entry [{}]\", entry);\n throw new RevokedCertificateException(entry);\n }\n }\n }\n\n /**\n * Sets the policy to apply when CRL data is unavailable.\n *\n * @param policy Revocation policy.\n */\n public void setUnavailableCRLPolicy(final RevocationPolicy policy) {\n this.unavailableCRLPolicy = policy;\n }\n\n /**\n * Sets the policy to apply when CRL data is expired.\n *\n * @param policy Revocation policy.\n */\n public void setExpiredCRLPolicy(final RevocationPolicy policy) {\n this.expiredCRLPolicy = policy;\n }\n\n\n /**\n * Indicates whether all resources should be checked,\n * or revocation should stop at the first resource\n * that produces the cert.\n *\n * @param checkAll the check all\n */\n public final void setCheckAll(final boolean checkAll) {\n this.checkAll = checkAll;\n }\n\n /**\n * Gets the first fetched CRL for the given certificate.\n *\n * @param cert Certificate for which the CRL of the issuing CA should be retrieved.\n *\n * @return CRL for given cert, or null\n */\n public final X509CRL getCRL(final X509Certificate cert) {\n final Collection list = getCRLs(cert);\n if (list != null && !list.isEmpty()) {\n return list.iterator().next();\n }\n logger.debug(\"No CRL could be found for {}\", CertUtils.toString(cert));\n return null;\n }\n\n /**\n * Records the addition of a new CRL entry.\n * @param id the id of the entry to keep track of\n * @param crl new CRL entry\n * @return true if the entry was added successfully.\n * @since 4.1\n */\n protected abstract boolean addCRL(final Object id, final X509CRL crl);\n\n /**\n * Gets the collection of CRLs for the given certificate.\n *\n * @param cert Certificate for which the CRL of the issuing CA should be retrieved.\n * @return CRLs for given cert.\n */\n protected abstract Collection getCRLs(final X509Certificate cert);\n}\n"},"new_file":{"kind":"string","value":"cas-server-support-x509/src/main/java/org/jasig/cas/adaptors/x509/authentication/handler/support/AbstractCRLRevocationChecker.java"},"old_contents":{"kind":"string","value":"/*\n * Licensed to Apereo under one or more contributor license\n * agreements. See the NOTICE file distributed with this work\n * for additional information regarding copyright ownership.\n * Apereo licenses this file to you under the Apache License,\n * Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a\n * copy of the License at the following location:\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.jasig.cas.adaptors.x509.authentication.handler.support;\n\nimport java.security.GeneralSecurityException;\nimport java.security.cert.X509CRL;\nimport java.security.cert.X509CRLEntry;\nimport java.security.cert.X509Certificate;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Iterator;\nimport java.util.List;\n\nimport javax.validation.constraints.NotNull;\n\nimport org.jasig.cas.adaptors.x509.util.CertUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * Base class for all CRL-based revocation checkers.\n *\n * @author Marvin S. Addison\n * @since 3.4.6\n *\n */\npublic abstract class AbstractCRLRevocationChecker implements RevocationChecker {\n /** Logger instance. **/\n protected final Logger logger = LoggerFactory.getLogger(getClass());\n\n /**\n * Flag to indicate whether all\n * crls should be checked for the cert resource.\n * Defaults to false.\n **/\n protected boolean checkAll;\n\n /** Policy to apply when CRL data is unavailable. */\n @NotNull\n private RevocationPolicy unavailableCRLPolicy = new DenyRevocationPolicy();\n\n /** Policy to apply when CRL data has expired. */\n @NotNull\n private RevocationPolicy expiredCRLPolicy = new ThresholdExpiredCRLRevocationPolicy();\n\n /**\n * {@inheritDoc}\n **/\n @Override\n public void check(final X509Certificate cert) throws GeneralSecurityException {\n if (cert == null) {\n throw new IllegalArgumentException(\"Certificate cannot be null.\");\n }\n logger.debug(\"Evaluating certificate revocation status for {}\", CertUtils.toString(cert));\n final Collection crls = getCRLs(cert);\n\n if (crls == null || crls.isEmpty()) {\n logger.warn(\"CRL data is not available for {}\", CertUtils.toString(cert));\n this.unavailableCRLPolicy.apply(null);\n return;\n }\n\n final List expiredCrls = new ArrayList<>();\n final List revokedCrls = new ArrayList<>();\n\n final Iterator it = crls.iterator();\n while (it.hasNext()) {\n final X509CRL crl = it.next();\n if (CertUtils.isExpired(crl)) {\n logger.warn(\"CRL data expired on {}\", crl.getNextUpdate());\n expiredCrls.add(crl);\n }\n }\n\n if (crls.size() == expiredCrls.size()) {\n logger.warn(\"All CRLs retrieved have expired. Applying CRL expiration policy...\");\n for (final X509CRL crl : expiredCrls) {\n this.expiredCRLPolicy.apply(crl);\n }\n } else {\n crls.removeAll(expiredCrls);\n logger.debug(\"Valid CRLs [{}] found that are not expired yet\", crls);\n\n for (final X509CRL crl : crls) {\n final X509CRLEntry entry = crl.getRevokedCertificate(cert);\n if (entry != null) {\n revokedCrls.add(entry);\n }\n }\n\n if (revokedCrls.size() == crls.size() && !revokedCrls.isEmpty()) {\n final X509CRLEntry entry = revokedCrls.get(0);\n logger.warn(\"All CRL entries have been revoked. Rejecting the first entry [{}]\", entry);\n throw new RevokedCertificateException(entry);\n }\n }\n }\n\n /**\n * Sets the policy to apply when CRL data is unavailable.\n *\n * @param policy Revocation policy.\n */\n public void setUnavailableCRLPolicy(final RevocationPolicy policy) {\n this.unavailableCRLPolicy = policy;\n }\n\n /**\n * Sets the policy to apply when CRL data is expired.\n *\n * @param policy Revocation policy.\n */\n public void setExpiredCRLPolicy(final RevocationPolicy policy) {\n this.expiredCRLPolicy = policy;\n }\n\n\n /**\n * Indicates whether all resources should be checked,\n * or revocation should stop at the first resource\n * that produces the cert.\n *\n * @param checkAll the check all\n */\n public final void setCheckAll(final boolean checkAll) {\n this.checkAll = checkAll;\n }\n\n /**\n * Gets the first fetched CRL for the given certificate.\n *\n * @param cert Certificate for which the CRL of the issuing CA should be retrieved.\n *\n * @return CRL for given cert, or null\n */\n public final X509CRL getCRL(final X509Certificate cert) {\n final Collection list = getCRLs(cert);\n if (list != null && !list.isEmpty()) {\n return list.iterator().next();\n }\n logger.debug(\"No CRL could be found for {}\", CertUtils.toString(cert));\n return null;\n }\n\n /**\n * Records the addition of a new CRL entry.\n * @param id the id of the entry to keep track of\n * @param crl new CRL entry\n * @return true if the entry was added successfully.\n * @since 4.1\n */\n protected abstract boolean addCRL(final Object id, final X509CRL crl);\n\n /**\n * Gets the collection of CRLs for the given certificate.\n *\n * @param cert Certificate for which the CRL of the issuing CA should be retrieved.\n * @return CRLs for given cert.\n */\n protected abstract Collection getCRLs(final X509Certificate cert);\n}\n"},"message":{"kind":"string","value":"removed useless check\n"},"old_file":{"kind":"string","value":"cas-server-support-x509/src/main/java/org/jasig/cas/adaptors/x509/authentication/handler/support/AbstractCRLRevocationChecker.java"},"subject":{"kind":"string","value":"removed useless check"},"git_diff":{"kind":"string","value":"as-server-support-x509/src/main/java/org/jasig/cas/adaptors/x509/authentication/handler/support/AbstractCRLRevocationChecker.java\n }\n }\n \n if (revokedCrls.size() == crls.size() && !revokedCrls.isEmpty()) {\n if (revokedCrls.size() == crls.size()) {\n final X509CRLEntry entry = revokedCrls.get(0);\n logger.warn(\"All CRL entries have been revoked. Rejecting the first entry [{}]\", entry);\n throw new RevokedCertificateException(entry);"}}},{"rowIdx":867,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"30a11ddb653d2e63714a1b1544b83cb3314ecb98"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"skmedix/JFoenix,jfoenixadmin/JFoenix"},"new_contents":{"kind":"string","value":"/*\r\n * Licensed to the Apache Software Foundation (ASF) under one\r\n * or more contributor license agreements. See the NOTICE file\r\n * distributed with this work for additional information\r\n * regarding copyright ownership. The ASF licenses this file\r\n * to you under the Apache License, Version 2.0 (the\r\n * \"License\"); you may not use this file except in compliance\r\n * 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,\r\n * software distributed under the License is distributed on an\r\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\r\n * KIND, either express or implied. See the License for the\r\n * specific language governing permissions and limitations\r\n * under the License.\r\n */\r\npackage com.jfoenix.controls;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.Collections;\r\nimport java.util.List;\r\n\r\nimport javafx.animation.Interpolator;\r\nimport javafx.animation.KeyFrame;\r\nimport javafx.animation.KeyValue;\r\nimport javafx.animation.Timeline;\r\nimport javafx.animation.Transition;\r\nimport javafx.beans.DefaultProperty;\r\nimport javafx.beans.property.BooleanProperty;\r\nimport javafx.beans.property.ObjectProperty;\r\nimport javafx.beans.property.SimpleBooleanProperty;\r\nimport javafx.beans.property.SimpleObjectProperty;\r\nimport javafx.css.CssMetaData;\r\nimport javafx.css.SimpleStyleableObjectProperty;\r\nimport javafx.css.Styleable;\r\nimport javafx.css.StyleableObjectProperty;\r\nimport javafx.css.StyleableProperty;\r\nimport javafx.event.EventHandler;\r\nimport javafx.geometry.Pos;\r\nimport javafx.scene.Parent;\r\nimport javafx.scene.input.MouseEvent;\r\nimport javafx.scene.layout.Background;\r\nimport javafx.scene.layout.BackgroundFill;\r\nimport javafx.scene.layout.CornerRadii;\r\nimport javafx.scene.layout.Pane;\r\nimport javafx.scene.layout.Region;\r\nimport javafx.scene.layout.StackPane;\r\nimport javafx.scene.paint.Color;\r\nimport javafx.util.Duration;\r\n\r\nimport com.jfoenix.controls.events.JFXDialogEvent;\r\nimport com.jfoenix.converters.DialogTransitionConverter;\r\nimport com.jfoenix.effects.JFXDepthManager;\r\nimport com.jfoenix.transitions.CachedTransition;\r\n\r\n/**\r\n * @author Shadi Shaheen\r\n * note that for JFXDialog to work properly the root node should\r\n * be of type {@link StackPane}\r\n */\r\n@DefaultProperty(value=\"content\")\r\npublic class JFXDialog extends StackPane {\r\n\r\n\t//\tpublic static enum JFXDialogLayout{PLAIN, HEADING, ACTIONS, BACKDROP};\r\n\tpublic static enum DialogTransition{CENTER, TOP, RIGHT, BOTTOM, LEFT};\r\n\r\n\tprivate StackPane contentHolder;\r\n\tprivate StackPane overlayPane;\r\n\r\n\tprivate double offsetX = 0;\r\n\tprivate double offsetY = 0;\r\n\r\n\tprivate Pane dialogContainer;\r\n\tprivate Region content;\r\n\tprivate Transition animation;\r\n\r\n\tprivate BooleanProperty overlayClose = new SimpleBooleanProperty(true);\r\n\tEventHandler closeHandler = (e)->close();\r\n\t\r\n\tpublic JFXDialog(){\r\n\t\tthis(null,null,DialogTransition.CENTER);\r\n\t}\r\n\r\n\t/**\r\n\t * creates JFX Dialog control\r\n\t * @param dialogContainer\r\n\t * @param content\r\n\t * @param transitionType\r\n\t */\r\n\t\r\n\tpublic JFXDialog(Pane dialogContainer, Region content, DialogTransition transitionType) {\t\t\r\n\t\tinitialize();\r\n\t\tsetContent(content);\r\n\t\tsetDialogContainer(dialogContainer);\r\n\t\tthis.transitionType.set(transitionType);\r\n\t\t// init change listeners\r\n\t\tinitChangeListeners();\r\n\t}\r\n\t\r\n\t/**\r\n\t * creates JFX Dialog control\r\n\t * @param dialogContainer\r\n\t * @param content\r\n\t * @param transitionType\r\n\t * @param overlayClose\r\n\t */\r\n\tpublic JFXDialog(Pane dialogContainer, Region content, DialogTransition transitionType, boolean overlayClose) {\t\t\r\n\t\tinitialize();\r\n\t\tsetOverlayClose(overlayClose);\r\n\t\tsetContent(content);\r\n\t\tsetDialogContainer(dialogContainer);\r\n\t\tthis.transitionType.set(transitionType);\r\n\t\t// init change listeners\r\n\t\tinitChangeListeners();\r\n\t}\r\n\r\n\tprivate void initChangeListeners(){\r\n\t\toverlayCloseProperty().addListener((o,oldVal,newVal)->{\r\n\t\t\tif(overlayPane!=null){\r\n\t\t\t\tif(newVal) overlayPane.addEventHandler(MouseEvent.MOUSE_PRESSED, closeHandler);\r\n\t\t\t\telse overlayPane.removeEventHandler(MouseEvent.MOUSE_PRESSED, closeHandler);\t\t\r\n\t\t\t}\r\n\t\t});\r\n\t}\r\n\t\r\n\tprivate void initialize() {\r\n\t\tthis.setVisible(false);\r\n\t\tthis.getStyleClass().add(DEFAULT_STYLE_CLASS); \r\n\t\t\r\n\t\tcontentHolder = new StackPane();\r\n\t\tcontentHolder.setBackground(new Background(new BackgroundFill(Color.WHITE, new CornerRadii(2), null)));\r\n\t\tJFXDepthManager.setDepth(contentHolder, 4);\r\n\t\tcontentHolder.setPickOnBounds(false);\r\n\t\t// ensure stackpane is never resized beyond it's preferred size\r\n\t\tcontentHolder.setMaxSize(Region.USE_PREF_SIZE, Region.USE_PREF_SIZE);\r\n\t\toverlayPane = new StackPane();\r\n\t\toverlayPane.getChildren().add(contentHolder);\r\n\t\toverlayPane.getStyleClass().add(\"jfx-dialog-overlay-pane\");\r\n\t\tStackPane.setAlignment(contentHolder, Pos.CENTER);\r\n\t\toverlayPane.setVisible(false);\r\n\t\toverlayPane.setBackground(new Background(new BackgroundFill(Color.rgb(0, 0, 0, 0.1), null, null)));\r\n\t\t// close the dialog if clicked on the overlay pane\r\n\t\tif(overlayClose.get()) overlayPane.addEventHandler(MouseEvent.MOUSE_PRESSED, closeHandler);\r\n\t\t// prevent propagating the events to overlay pane\r\n\t\tcontentHolder.addEventHandler(MouseEvent.ANY, (e)->e.consume());\r\n\t}\r\n\r\n\t/***************************************************************************\r\n\t * *\r\n\t * Setters / Getters *\r\n\t * *\r\n\t **************************************************************************/\r\n\r\n\tpublic Pane getDialogContainer() {\r\n\t\treturn dialogContainer;\r\n\t}\r\n\r\n\tpublic void setDialogContainer(Pane dialogContainer) {\r\n\t\tif(dialogContainer!=null){\r\n\t\t\tthis.dialogContainer = dialogContainer;\r\n\t\t\tif(this.getChildren().indexOf(overlayPane)==-1)this.getChildren().setAll(overlayPane);\r\n\t\t\tthis.visibleProperty().unbind();\r\n\t\t\tthis.visibleProperty().bind(overlayPane.visibleProperty());\r\n\t\t\tif(this.dialogContainer.getChildren().indexOf(this)==-1 || this.dialogContainer.getChildren().indexOf(this)!=this.dialogContainer.getChildren().size()-1){\r\n\t\t\t\tthis.dialogContainer.getChildren().remove(this);\r\n\t\t\t\tthis.dialogContainer.getChildren().add(this);\r\n\t\t\t}\r\n\t\t\t// FIXME: need to be improved to consider only the parent boundary\r\n\t\t\toffsetX = (this.getParent().getBoundsInLocal().getWidth());\r\n\t\t\toffsetY = (this.getParent().getBoundsInLocal().getHeight());\r\n\t\t\tanimation = getShowAnimation(transitionType.get());\r\n\t\t}\r\n\t}\r\n\r\n\tpublic Region getContent() {\r\n\t\treturn content;\r\n\t}\r\n\r\n\tpublic void setContent(Region content) {\r\n\t\tif(content!=null){\r\n\t\t\tthis.content = content;\t\t\t\t\r\n\t\t\tcontentHolder.getChildren().add(content);\t\t\t\r\n\t\t}\r\n\t}\r\n\r\n\t\r\n\tpublic final BooleanProperty overlayCloseProperty() {\r\n\t\treturn this.overlayClose;\r\n\t}\r\n\r\n\tpublic final boolean isOverlayClose() {\r\n\t\treturn this.overlayCloseProperty().get();\r\n\t}\r\n\r\n\tpublic final void setOverlayClose(final boolean overlayClose) {\r\n\t\tthis.overlayCloseProperty().set(overlayClose);\r\n\t}\r\n\t\r\n\t/***************************************************************************\r\n\t * *\r\n\t * Public API *\r\n\t * *\r\n\t **************************************************************************/\r\n\r\n\tpublic void show(Pane dialogContainer){\r\n\t\tthis.setDialogContainer(dialogContainer);\r\n\t\tanimation.play();\r\n\t}\r\n\r\n\tpublic void show(){\r\n\t\tthis.setDialogContainer(dialogContainer);\r\n//\t\tanimation = getShowAnimation(transitionType.get());\r\n\t\tanimation.play();\t\t\r\n\t}\r\n\r\n\tpublic void close(){\r\n\t\tanimation.setRate(-1);\r\n\t\tanimation.play();\r\n\t\tanimation.setOnFinished((e)->{\r\n\t\t\tresetProperties();\r\n\t\t});\r\n\t\tonDialogClosedProperty.get().handle(new JFXDialogEvent(JFXDialogEvent.CLOSED));\r\n\t}\r\n\r\n\t/***************************************************************************\r\n\t * *\r\n\t * Transitions *\r\n\t * *\r\n\t **************************************************************************/\r\n\r\n\tprivate Transition getShowAnimation(DialogTransition transitionType){\r\n\t\tTransition animation = null;\r\n\t\tif(contentHolder!=null){\r\n\t\t\tswitch (transitionType) {\t\t\r\n\t\t\tcase LEFT:\t\r\n\t\t\t\tcontentHolder.setTranslateX(-offsetX);\r\n\t\t\t\tanimation = new LeftTransition();\r\n\t\t\t\tbreak;\r\n\t\t\tcase RIGHT:\t\t\t\r\n\t\t\t\tcontentHolder.setTranslateX(offsetX);\r\n\t\t\t\tanimation = new RightTransition();\r\n\t\t\t\tbreak;\r\n\t\t\tcase TOP:\t\r\n\t\t\t\tcontentHolder.setTranslateY(-offsetY);\r\n\t\t\t\tanimation = new TopTransition();\r\n\t\t\t\tbreak;\r\n\t\t\tcase BOTTOM:\t\t\t\r\n\t\t\t\tcontentHolder.setTranslateY(offsetY);\r\n\t\t\t\tanimation = new BottomTransition();\r\n\t\t\t\tbreak;\r\n\t\t\tdefault:\r\n\t\t\t\tcontentHolder.setScaleX(0);\r\n\t\t\t\tcontentHolder.setScaleY(0);\r\n\t\t\t\tanimation = new CenterTransition();\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif(animation!=null)animation.setOnFinished((finish)->onDialogOpenedProperty.get().handle(new JFXDialogEvent(JFXDialogEvent.OPENED)));\r\n\t\treturn animation;\r\n\t}\r\n\r\n\tprivate void resetProperties(){\r\n\t\toverlayPane.setVisible(false);\t\r\n\t\tcontentHolder.setTranslateX(0);\r\n\t\tcontentHolder.setTranslateY(0);\r\n\t\tcontentHolder.setScaleX(1);\r\n\t\tcontentHolder.setScaleY(1);\r\n\t}\r\n\r\n\tprivate class LeftTransition extends CachedTransition {\r\n\t\tpublic LeftTransition() {\r\n\t\t\tsuper(contentHolder, new Timeline(\r\n\t\t\t\t\tnew KeyFrame(Duration.ZERO, \r\n\t\t\t\t\t\t\tnew KeyValue(contentHolder.translateXProperty(), -offsetX ,Interpolator.EASE_BOTH),\r\n\t\t\t\t\t\t\tnew KeyValue(overlayPane.visibleProperty(), false ,Interpolator.EASE_BOTH)\r\n\t\t\t\t\t\t\t),\r\n\t\t\t\t\t\t\tnew KeyFrame(Duration.millis(10), \r\n\t\t\t\t\t\t\t\t\tnew KeyValue(overlayPane.visibleProperty(), true ,Interpolator.EASE_BOTH),\r\n\t\t\t\t\t\t\t\t\tnew KeyValue(overlayPane.opacityProperty(), 0,Interpolator.EASE_BOTH)\r\n\t\t\t\t\t\t\t\t\t),\r\n\t\t\t\t\t\t\t\t\tnew KeyFrame(Duration.millis(1000), \r\n\t\t\t\t\t\t\t\t\t\t\tnew KeyValue(contentHolder.translateXProperty(), 0,Interpolator.EASE_BOTH),\r\n\t\t\t\t\t\t\t\t\t\t\tnew KeyValue(overlayPane.opacityProperty(), 1,Interpolator.EASE_BOTH)\r\n\t\t\t\t\t\t\t\t\t\t\t))\r\n\t\t\t\t\t);\r\n\t\t\t// reduce the number to increase the shifting , increase number to reduce shifting\r\n\t\t\tsetCycleDuration(Duration.seconds(0.4));\r\n\t\t\tsetDelay(Duration.seconds(0));\r\n\t\t}\r\n\t}\r\n\r\n\tprivate class RightTransition extends CachedTransition {\r\n\t\tpublic RightTransition() {\r\n\t\t\tsuper(contentHolder, new Timeline(\r\n\t\t\t\t\tnew KeyFrame(Duration.ZERO, \r\n\t\t\t\t\t\t\tnew KeyValue(contentHolder.translateXProperty(), offsetX ,Interpolator.EASE_BOTH),\r\n\t\t\t\t\t\t\tnew KeyValue(overlayPane.visibleProperty(), false ,Interpolator.EASE_BOTH)\r\n\t\t\t\t\t\t\t),\r\n\t\t\t\t\t\t\tnew KeyFrame(Duration.millis(10), \r\n\t\t\t\t\t\t\t\t\tnew KeyValue(overlayPane.visibleProperty(), true ,Interpolator.EASE_BOTH),\r\n\t\t\t\t\t\t\t\t\tnew KeyValue(overlayPane.opacityProperty(), 0, Interpolator.EASE_BOTH)\r\n\t\t\t\t\t\t\t\t\t),\r\n\t\t\t\t\t\t\t\t\tnew KeyFrame(Duration.millis(1000), \r\n\t\t\t\t\t\t\t\t\t\t\tnew KeyValue(contentHolder.translateXProperty(), 0,Interpolator.EASE_BOTH),\r\n\t\t\t\t\t\t\t\t\t\t\tnew KeyValue(overlayPane.opacityProperty(), 1, Interpolator.EASE_BOTH)))\r\n\t\t\t\t\t);\r\n\t\t\t// reduce the number to increase the shifting , increase number to reduce shifting\r\n\t\t\tsetCycleDuration(Duration.seconds(0.4));\r\n\t\t\tsetDelay(Duration.seconds(0));\r\n\t\t}\r\n\t}\r\n\r\n\tprivate class TopTransition extends CachedTransition {\r\n\t\tpublic TopTransition() {\r\n\t\t\tsuper(contentHolder, new Timeline(\r\n\t\t\t\t\tnew KeyFrame(Duration.ZERO, \r\n\t\t\t\t\t\t\tnew KeyValue(contentHolder.translateYProperty(), -offsetY ,Interpolator.EASE_BOTH),\r\n\t\t\t\t\t\t\tnew KeyValue(overlayPane.visibleProperty(), false ,Interpolator.EASE_BOTH)\r\n\t\t\t\t\t\t\t),\r\n\t\t\t\t\t\t\tnew KeyFrame(Duration.millis(10), \r\n\t\t\t\t\t\t\t\t\tnew KeyValue(overlayPane.visibleProperty(), true ,Interpolator.EASE_BOTH),\r\n\t\t\t\t\t\t\t\t\tnew KeyValue(overlayPane.opacityProperty(), 0, Interpolator.EASE_BOTH)\r\n\t\t\t\t\t\t\t\t\t),\r\n\t\t\t\t\t\t\t\t\tnew KeyFrame(Duration.millis(1000),\r\n\t\t\t\t\t\t\t\t\t\t\tnew KeyValue(contentHolder.translateYProperty(), 0,Interpolator.EASE_BOTH),\r\n\t\t\t\t\t\t\t\t\t\t\tnew KeyValue(overlayPane.opacityProperty(), 1, Interpolator.EASE_BOTH)))\r\n\t\t\t\t\t);\r\n\t\t\t// reduce the number to increase the shifting , increase number to reduce shifting\r\n\t\t\tsetCycleDuration(Duration.seconds(0.4));\r\n\t\t\tsetDelay(Duration.seconds(0));\r\n\t\t}\r\n\t}\r\n\r\n\tprivate class BottomTransition extends CachedTransition {\r\n\t\tpublic BottomTransition() {\r\n\t\t\tsuper(contentHolder, new Timeline(\r\n\t\t\t\t\tnew KeyFrame(Duration.ZERO, \r\n\t\t\t\t\t\t\tnew KeyValue(contentHolder.translateYProperty(), offsetY ,Interpolator.EASE_BOTH),\r\n\t\t\t\t\t\t\tnew KeyValue(overlayPane.visibleProperty(), false ,Interpolator.EASE_BOTH)\r\n\t\t\t\t\t\t\t),\r\n\t\t\t\t\t\t\tnew KeyFrame(Duration.millis(10), \r\n\t\t\t\t\t\t\t\t\tnew KeyValue(overlayPane.visibleProperty(), true ,Interpolator.EASE_BOTH),\r\n\t\t\t\t\t\t\t\t\tnew KeyValue(overlayPane.opacityProperty(), 0, Interpolator.EASE_BOTH)\r\n\t\t\t\t\t\t\t\t\t),\r\n\t\t\t\t\t\t\t\t\tnew KeyFrame(Duration.millis(1000), \r\n\t\t\t\t\t\t\t\t\t\t\tnew KeyValue(contentHolder.translateYProperty(), 0,Interpolator.EASE_BOTH),\r\n\t\t\t\t\t\t\t\t\t\t\tnew KeyValue(overlayPane.opacityProperty(), 1, Interpolator.EASE_BOTH)))\r\n\t\t\t\t\t);\r\n\t\t\t// reduce the number to increase the shifting , increase number to reduce shifting\r\n\t\t\tsetCycleDuration(Duration.seconds(0.4));\r\n\t\t\tsetDelay(Duration.seconds(0));\r\n\t\t}\r\n\t}\r\n\r\n\tprivate class CenterTransition extends CachedTransition {\r\n\t\tpublic CenterTransition() {\r\n\t\t\tsuper(contentHolder, new Timeline(\r\n\t\t\t\t\tnew KeyFrame(Duration.ZERO, \r\n\t\t\t\t\t\t\tnew KeyValue(contentHolder.scaleXProperty(), 0 ,Interpolator.EASE_BOTH),\r\n\t\t\t\t\t\t\tnew KeyValue(contentHolder.scaleYProperty(), 0 ,Interpolator.EASE_BOTH),\r\n\t\t\t\t\t\t\tnew KeyValue(overlayPane.visibleProperty(), false ,Interpolator.EASE_BOTH)\r\n\t\t\t\t\t\t\t),\r\n\t\t\t\t\t\t\tnew KeyFrame(Duration.millis(10), \r\n\t\t\t\t\t\t\t\t\tnew KeyValue(overlayPane.visibleProperty(), true ,Interpolator.EASE_BOTH),\r\n\t\t\t\t\t\t\t\t\tnew KeyValue(overlayPane.opacityProperty(), 0,Interpolator.EASE_BOTH)\r\n\t\t\t\t\t\t\t\t\t),\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\tnew KeyFrame(Duration.millis(1000), \t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\tnew KeyValue(contentHolder.scaleXProperty(), 1 ,Interpolator.EASE_BOTH),\r\n\t\t\t\t\t\t\t\t\t\t\tnew KeyValue(contentHolder.scaleYProperty(), 1 ,Interpolator.EASE_BOTH),\r\n\t\t\t\t\t\t\t\t\t\t\tnew KeyValue(overlayPane.opacityProperty(), 1, Interpolator.EASE_BOTH)\r\n\t\t\t\t\t\t\t\t\t\t\t))\r\n\t\t\t\t\t);\r\n\t\t\t// reduce the number to increase the shifting , increase number to reduce shifting\r\n\t\t\tsetCycleDuration(Duration.seconds(0.4));\r\n\t\t\tsetDelay(Duration.seconds(0));\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t/***************************************************************************\r\n\t * *\r\n\t * Stylesheet Handling *\r\n\t * *\r\n\t **************************************************************************/\r\n\r\n\tprivate static final String DEFAULT_STYLE_CLASS = \"jfx-dialog\";\r\n\r\n\r\n\tprivate StyleableObjectProperty transitionType = new SimpleStyleableObjectProperty(StyleableProperties.DIALOG_TRANSITION, JFXDialog.this, \"dialogTransition\", DialogTransition.CENTER );\r\n\r\n\tpublic DialogTransition getTransitionType(){\r\n\t\treturn transitionType == null ? DialogTransition.CENTER : transitionType.get();\r\n\t}\r\n\tpublic StyleableObjectProperty transitionTypeProperty(){\t\t\r\n\t\treturn this.transitionType;\r\n\t}\r\n\tpublic void setTransitionType(DialogTransition transition){\r\n\t\tthis.transitionType.set(transition);\r\n\t}\r\n\r\n\r\n\tprivate static class StyleableProperties {\r\n\t\tprivate static final CssMetaData< JFXDialog, DialogTransition> DIALOG_TRANSITION =\r\n\t\t\t\tnew CssMetaData< JFXDialog, DialogTransition>(\"-fx-dialog-transition\",\r\n\t\t\t\t\t\tDialogTransitionConverter.getInstance(), DialogTransition.CENTER) {\r\n\t\t\t@Override\r\n\t\t\tpublic boolean isSettable(JFXDialog control) {\r\n\t\t\t\treturn control.transitionType == null || !control.transitionType.isBound();\r\n\t\t\t}\r\n\t\t\t@Override\r\n\t\t\tpublic StyleableProperty getStyleableProperty(JFXDialog control) {\r\n\t\t\t\treturn control.transitionTypeProperty();\r\n\t\t\t}\r\n\t\t};\r\n\r\n\t\tprivate static final List> CHILD_STYLEABLES;\r\n\t\tstatic {\r\n\t\t\tfinal List> styleables =\r\n\t\t\t\t\tnew ArrayList>(Parent.getClassCssMetaData());\r\n\t\t\tCollections.addAll(styleables,\r\n\t\t\t\t\tDIALOG_TRANSITION\r\n\t\t\t\t\t);\r\n\t\t\tCHILD_STYLEABLES = Collections.unmodifiableList(styleables);\r\n\t\t}\r\n\t}\r\n\r\n\t// inherit the styleable properties from parent\r\n\tprivate List> STYLEABLES;\r\n\r\n\t@Override\r\n\tpublic List> getCssMetaData() {\r\n\t\tif(STYLEABLES == null){\r\n\t\t\tfinal List> styleables =\r\n\t\t\t\t\tnew ArrayList>(Parent.getClassCssMetaData());\r\n\t\t\tstyleables.addAll(getClassCssMetaData());\r\n\t\t\tstyleables.addAll(super.getClassCssMetaData());\r\n\t\t\tSTYLEABLES = Collections.unmodifiableList(styleables);\r\n\t\t}\r\n\t\treturn STYLEABLES;\r\n\t}\r\n\tpublic static List> getClassCssMetaData() {\r\n\t\treturn StyleableProperties.CHILD_STYLEABLES;\r\n\t}\r\n\r\n\r\n\r\n\t/***************************************************************************\r\n\t * *\r\n\t * Custom Events *\r\n\t * *\r\n\t **************************************************************************/\r\n\t\r\n\tprivate ObjectProperty> onDialogClosedProperty = new SimpleObjectProperty<>((closed)->{});\r\n\r\n\tpublic void setOnDialogClosed(EventHandler handler){\r\n\t\tonDialogClosedProperty.set(handler);\r\n\t}\r\n\r\n\tpublic void getOnDialogClosed(EventHandler handler){\r\n\t\tonDialogClosedProperty.get();\r\n\t}\r\n\r\n\r\n\tprivate ObjectProperty> onDialogOpenedProperty = new SimpleObjectProperty<>((opened)->{});\r\n\t\r\n\tpublic void setOnDialogOpened(EventHandler handler){\r\n\t\tonDialogOpenedProperty.set(handler);\r\n\t}\r\n\r\n\tpublic void getOnDialogOpened(EventHandler handler){\r\n\t\tonDialogOpenedProperty.get();\r\n\t}\r\n\r\n\r\n\r\n\t\r\n\t\r\n}\r\n\r\n"},"new_file":{"kind":"string","value":"src/com/jfoenix/controls/JFXDialog.java"},"old_contents":{"kind":"string","value":"/*\r\n * Licensed to the Apache Software Foundation (ASF) under one\r\n * or more contributor license agreements. See the NOTICE file\r\n * distributed with this work for additional information\r\n * regarding copyright ownership. The ASF licenses this file\r\n * to you under the Apache License, Version 2.0 (the\r\n * \"License\"); you may not use this file except in compliance\r\n * 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,\r\n * software distributed under the License is distributed on an\r\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\r\n * KIND, either express or implied. See the License for the\r\n * specific language governing permissions and limitations\r\n * under the License.\r\n */\r\npackage com.jfoenix.controls;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.Collections;\r\nimport java.util.List;\r\n\r\nimport javafx.animation.Interpolator;\r\nimport javafx.animation.KeyFrame;\r\nimport javafx.animation.KeyValue;\r\nimport javafx.animation.Timeline;\r\nimport javafx.animation.Transition;\r\nimport javafx.beans.DefaultProperty;\r\nimport javafx.beans.property.BooleanProperty;\r\nimport javafx.beans.property.ObjectProperty;\r\nimport javafx.beans.property.SimpleBooleanProperty;\r\nimport javafx.beans.property.SimpleObjectProperty;\r\nimport javafx.css.CssMetaData;\r\nimport javafx.css.SimpleStyleableObjectProperty;\r\nimport javafx.css.Styleable;\r\nimport javafx.css.StyleableObjectProperty;\r\nimport javafx.css.StyleableProperty;\r\nimport javafx.event.EventHandler;\r\nimport javafx.geometry.Pos;\r\nimport javafx.scene.Parent;\r\nimport javafx.scene.input.MouseEvent;\r\nimport javafx.scene.layout.Background;\r\nimport javafx.scene.layout.BackgroundFill;\r\nimport javafx.scene.layout.CornerRadii;\r\nimport javafx.scene.layout.Pane;\r\nimport javafx.scene.layout.Region;\r\nimport javafx.scene.layout.StackPane;\r\nimport javafx.scene.paint.Color;\r\nimport javafx.util.Duration;\r\n\r\nimport com.jfoenix.controls.events.JFXDialogEvent;\r\nimport com.jfoenix.converters.DialogTransitionConverter;\r\nimport com.jfoenix.effects.JFXDepthManager;\r\nimport com.jfoenix.transitions.CachedTransition;\r\n\r\n/**\r\n * @author Shadi Shaheen\r\n *\r\n */\r\n@DefaultProperty(value=\"content\")\r\npublic class JFXDialog extends StackPane {\r\n\r\n\t//\tpublic static enum JFXDialogLayout{PLAIN, HEADING, ACTIONS, BACKDROP};\r\n\tpublic static enum DialogTransition{CENTER, TOP, RIGHT, BOTTOM, LEFT};\r\n\r\n\tprivate StackPane contentHolder;\r\n\tprivate StackPane overlayPane;\r\n\r\n\tprivate double offsetX = 0;\r\n\tprivate double offsetY = 0;\r\n\r\n\tprivate Pane dialogContainer;\r\n\tprivate Region content;\r\n\tprivate Transition animation;\r\n\r\n\tprivate BooleanProperty overlayClose = new SimpleBooleanProperty(true);\r\n\tEventHandler closeHandler = (e)->close();\r\n\t\r\n\tpublic JFXDialog(){\r\n\t\tthis(null,null,DialogTransition.CENTER);\r\n\t}\r\n\r\n\t/**\r\n\t * creates JFX Dialog control\r\n\t * @param dialogContainer\r\n\t * @param content\r\n\t * @param transitionType\r\n\t */\r\n\t\r\n\tpublic JFXDialog(Pane dialogContainer, Region content, DialogTransition transitionType) {\t\t\r\n\t\tinitialize();\r\n\t\tsetContent(content);\r\n\t\tsetDialogContainer(dialogContainer);\r\n\t\tthis.transitionType.set(transitionType);\r\n\t\t// init change listeners\r\n\t\tinitChangeListeners();\r\n\t}\r\n\t\r\n\t/**\r\n\t * creates JFX Dialog control\r\n\t * @param dialogContainer\r\n\t * @param content\r\n\t * @param transitionType\r\n\t * @param overlayClose\r\n\t */\r\n\tpublic JFXDialog(Pane dialogContainer, Region content, DialogTransition transitionType, boolean overlayClose) {\t\t\r\n\t\tinitialize();\r\n\t\tsetOverlayClose(overlayClose);\r\n\t\tsetContent(content);\r\n\t\tsetDialogContainer(dialogContainer);\r\n\t\tthis.transitionType.set(transitionType);\r\n\t\t// init change listeners\r\n\t\tinitChangeListeners();\r\n\t}\r\n\r\n\tprivate void initChangeListeners(){\r\n\t\toverlayCloseProperty().addListener((o,oldVal,newVal)->{\r\n\t\t\tif(overlayPane!=null){\r\n\t\t\t\tif(newVal) overlayPane.addEventHandler(MouseEvent.MOUSE_PRESSED, closeHandler);\r\n\t\t\t\telse overlayPane.removeEventHandler(MouseEvent.MOUSE_PRESSED, closeHandler);\t\t\r\n\t\t\t}\r\n\t\t});\r\n\t}\r\n\t\r\n\tprivate void initialize() {\r\n\t\tthis.setVisible(false);\r\n\t\tthis.getStyleClass().add(DEFAULT_STYLE_CLASS); \r\n\t\t\r\n\t\tcontentHolder = new StackPane();\r\n\t\tcontentHolder.setBackground(new Background(new BackgroundFill(Color.WHITE, new CornerRadii(2), null)));\r\n\t\tJFXDepthManager.setDepth(contentHolder, 4);\r\n\t\tcontentHolder.setPickOnBounds(false);\r\n\t\t// ensure stackpane is never resized beyond it's preferred size\r\n\t\tcontentHolder.setMaxSize(Region.USE_PREF_SIZE, Region.USE_PREF_SIZE);\r\n\t\toverlayPane = new StackPane();\r\n\t\toverlayPane.getChildren().add(contentHolder);\r\n\t\toverlayPane.getStyleClass().add(\"jfx-dialog-overlay-pane\");\r\n\t\tStackPane.setAlignment(contentHolder, Pos.CENTER);\r\n\t\toverlayPane.setVisible(false);\r\n\t\toverlayPane.setBackground(new Background(new BackgroundFill(Color.rgb(0, 0, 0, 0.1), null, null)));\r\n\t\t// close the dialog if clicked on the overlay pane\r\n\t\tif(overlayClose.get()) overlayPane.addEventHandler(MouseEvent.MOUSE_PRESSED, closeHandler);\r\n\t\t// prevent propagating the events to overlay pane\r\n\t\tcontentHolder.addEventHandler(MouseEvent.ANY, (e)->e.consume());\r\n\t}\r\n\r\n\t/***************************************************************************\r\n\t * *\r\n\t * Setters / Getters *\r\n\t * *\r\n\t **************************************************************************/\r\n\r\n\tpublic Pane getDialogContainer() {\r\n\t\treturn dialogContainer;\r\n\t}\r\n\r\n\tpublic void setDialogContainer(Pane dialogContainer) {\r\n\t\tif(dialogContainer!=null){\r\n\t\t\tthis.dialogContainer = dialogContainer;\r\n\t\t\tif(this.getChildren().indexOf(overlayPane)==-1)this.getChildren().setAll(overlayPane);\r\n\t\t\tthis.visibleProperty().unbind();\r\n\t\t\tthis.visibleProperty().bind(overlayPane.visibleProperty());\r\n\t\t\tif(this.dialogContainer.getChildren().indexOf(this)==-1 || this.dialogContainer.getChildren().indexOf(this)!=this.dialogContainer.getChildren().size()-1){\r\n\t\t\t\tthis.dialogContainer.getChildren().remove(this);\r\n\t\t\t\tthis.dialogContainer.getChildren().add(this);\r\n\t\t\t}\r\n\t\t\t// FIXME: need to be improved to consider only the parent boundary\r\n\t\t\toffsetX = (this.getParent().getBoundsInLocal().getWidth());\r\n\t\t\toffsetY = (this.getParent().getBoundsInLocal().getHeight());\r\n\t\t\tanimation = getShowAnimation(transitionType.get());\r\n\t\t}\r\n\t}\r\n\r\n\tpublic Region getContent() {\r\n\t\treturn content;\r\n\t}\r\n\r\n\tpublic void setContent(Region content) {\r\n\t\tif(content!=null){\r\n\t\t\tthis.content = content;\t\t\t\t\r\n\t\t\tcontentHolder.getChildren().add(content);\t\t\t\r\n\t\t}\r\n\t}\r\n\r\n\t\r\n\tpublic final BooleanProperty overlayCloseProperty() {\r\n\t\treturn this.overlayClose;\r\n\t}\r\n\r\n\tpublic final boolean isOverlayClose() {\r\n\t\treturn this.overlayCloseProperty().get();\r\n\t}\r\n\r\n\tpublic final void setOverlayClose(final boolean overlayClose) {\r\n\t\tthis.overlayCloseProperty().set(overlayClose);\r\n\t}\r\n\t\r\n\t/***************************************************************************\r\n\t * *\r\n\t * Public API *\r\n\t * *\r\n\t **************************************************************************/\r\n\r\n\tpublic void show(Pane dialogContainer){\r\n\t\tthis.setDialogContainer(dialogContainer);\r\n\t\tanimation.play();\r\n\t}\r\n\r\n\tpublic void show(){\r\n\t\tthis.setDialogContainer(dialogContainer);\r\n//\t\tanimation = getShowAnimation(transitionType.get());\r\n\t\tanimation.play();\t\t\r\n\t}\r\n\r\n\tpublic void close(){\r\n\t\tanimation.setRate(-1);\r\n\t\tanimation.play();\r\n\t\tanimation.setOnFinished((e)->{\r\n\t\t\tresetProperties();\r\n\t\t});\r\n\t\tonDialogClosedProperty.get().handle(new JFXDialogEvent(JFXDialogEvent.CLOSED));\r\n\t}\r\n\r\n\t/***************************************************************************\r\n\t * *\r\n\t * Transitions *\r\n\t * *\r\n\t **************************************************************************/\r\n\r\n\tprivate Transition getShowAnimation(DialogTransition transitionType){\r\n\t\tTransition animation = null;\r\n\t\tif(contentHolder!=null){\r\n\t\t\tswitch (transitionType) {\t\t\r\n\t\t\tcase LEFT:\t\r\n\t\t\t\tcontentHolder.setTranslateX(-offsetX);\r\n\t\t\t\tanimation = new LeftTransition();\r\n\t\t\t\tbreak;\r\n\t\t\tcase RIGHT:\t\t\t\r\n\t\t\t\tcontentHolder.setTranslateX(offsetX);\r\n\t\t\t\tanimation = new RightTransition();\r\n\t\t\t\tbreak;\r\n\t\t\tcase TOP:\t\r\n\t\t\t\tcontentHolder.setTranslateY(-offsetY);\r\n\t\t\t\tanimation = new TopTransition();\r\n\t\t\t\tbreak;\r\n\t\t\tcase BOTTOM:\t\t\t\r\n\t\t\t\tcontentHolder.setTranslateY(offsetY);\r\n\t\t\t\tanimation = new BottomTransition();\r\n\t\t\t\tbreak;\r\n\t\t\tdefault:\r\n\t\t\t\tcontentHolder.setScaleX(0);\r\n\t\t\t\tcontentHolder.setScaleY(0);\r\n\t\t\t\tanimation = new CenterTransition();\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif(animation!=null)animation.setOnFinished((finish)->onDialogOpenedProperty.get().handle(new JFXDialogEvent(JFXDialogEvent.OPENED)));\r\n\t\treturn animation;\r\n\t}\r\n\r\n\tprivate void resetProperties(){\r\n\t\toverlayPane.setVisible(false);\t\r\n\t\tcontentHolder.setTranslateX(0);\r\n\t\tcontentHolder.setTranslateY(0);\r\n\t\tcontentHolder.setScaleX(1);\r\n\t\tcontentHolder.setScaleY(1);\r\n\t}\r\n\r\n\tprivate class LeftTransition extends CachedTransition {\r\n\t\tpublic LeftTransition() {\r\n\t\t\tsuper(contentHolder, new Timeline(\r\n\t\t\t\t\tnew KeyFrame(Duration.ZERO, \r\n\t\t\t\t\t\t\tnew KeyValue(contentHolder.translateXProperty(), -offsetX ,Interpolator.EASE_BOTH),\r\n\t\t\t\t\t\t\tnew KeyValue(overlayPane.visibleProperty(), false ,Interpolator.EASE_BOTH)\r\n\t\t\t\t\t\t\t),\r\n\t\t\t\t\t\t\tnew KeyFrame(Duration.millis(10), \r\n\t\t\t\t\t\t\t\t\tnew KeyValue(overlayPane.visibleProperty(), true ,Interpolator.EASE_BOTH),\r\n\t\t\t\t\t\t\t\t\tnew KeyValue(overlayPane.opacityProperty(), 0,Interpolator.EASE_BOTH)\r\n\t\t\t\t\t\t\t\t\t),\r\n\t\t\t\t\t\t\t\t\tnew KeyFrame(Duration.millis(1000), \r\n\t\t\t\t\t\t\t\t\t\t\tnew KeyValue(contentHolder.translateXProperty(), 0,Interpolator.EASE_BOTH),\r\n\t\t\t\t\t\t\t\t\t\t\tnew KeyValue(overlayPane.opacityProperty(), 1,Interpolator.EASE_BOTH)\r\n\t\t\t\t\t\t\t\t\t\t\t))\r\n\t\t\t\t\t);\r\n\t\t\t// reduce the number to increase the shifting , increase number to reduce shifting\r\n\t\t\tsetCycleDuration(Duration.seconds(0.4));\r\n\t\t\tsetDelay(Duration.seconds(0));\r\n\t\t}\r\n\t}\r\n\r\n\tprivate class RightTransition extends CachedTransition {\r\n\t\tpublic RightTransition() {\r\n\t\t\tsuper(contentHolder, new Timeline(\r\n\t\t\t\t\tnew KeyFrame(Duration.ZERO, \r\n\t\t\t\t\t\t\tnew KeyValue(contentHolder.translateXProperty(), offsetX ,Interpolator.EASE_BOTH),\r\n\t\t\t\t\t\t\tnew KeyValue(overlayPane.visibleProperty(), false ,Interpolator.EASE_BOTH)\r\n\t\t\t\t\t\t\t),\r\n\t\t\t\t\t\t\tnew KeyFrame(Duration.millis(10), \r\n\t\t\t\t\t\t\t\t\tnew KeyValue(overlayPane.visibleProperty(), true ,Interpolator.EASE_BOTH),\r\n\t\t\t\t\t\t\t\t\tnew KeyValue(overlayPane.opacityProperty(), 0, Interpolator.EASE_BOTH)\r\n\t\t\t\t\t\t\t\t\t),\r\n\t\t\t\t\t\t\t\t\tnew KeyFrame(Duration.millis(1000), \r\n\t\t\t\t\t\t\t\t\t\t\tnew KeyValue(contentHolder.translateXProperty(), 0,Interpolator.EASE_BOTH),\r\n\t\t\t\t\t\t\t\t\t\t\tnew KeyValue(overlayPane.opacityProperty(), 1, Interpolator.EASE_BOTH)))\r\n\t\t\t\t\t);\r\n\t\t\t// reduce the number to increase the shifting , increase number to reduce shifting\r\n\t\t\tsetCycleDuration(Duration.seconds(0.4));\r\n\t\t\tsetDelay(Duration.seconds(0));\r\n\t\t}\r\n\t}\r\n\r\n\tprivate class TopTransition extends CachedTransition {\r\n\t\tpublic TopTransition() {\r\n\t\t\tsuper(contentHolder, new Timeline(\r\n\t\t\t\t\tnew KeyFrame(Duration.ZERO, \r\n\t\t\t\t\t\t\tnew KeyValue(contentHolder.translateYProperty(), -offsetY ,Interpolator.EASE_BOTH),\r\n\t\t\t\t\t\t\tnew KeyValue(overlayPane.visibleProperty(), false ,Interpolator.EASE_BOTH)\r\n\t\t\t\t\t\t\t),\r\n\t\t\t\t\t\t\tnew KeyFrame(Duration.millis(10), \r\n\t\t\t\t\t\t\t\t\tnew KeyValue(overlayPane.visibleProperty(), true ,Interpolator.EASE_BOTH),\r\n\t\t\t\t\t\t\t\t\tnew KeyValue(overlayPane.opacityProperty(), 0, Interpolator.EASE_BOTH)\r\n\t\t\t\t\t\t\t\t\t),\r\n\t\t\t\t\t\t\t\t\tnew KeyFrame(Duration.millis(1000),\r\n\t\t\t\t\t\t\t\t\t\t\tnew KeyValue(contentHolder.translateYProperty(), 0,Interpolator.EASE_BOTH),\r\n\t\t\t\t\t\t\t\t\t\t\tnew KeyValue(overlayPane.opacityProperty(), 1, Interpolator.EASE_BOTH)))\r\n\t\t\t\t\t);\r\n\t\t\t// reduce the number to increase the shifting , increase number to reduce shifting\r\n\t\t\tsetCycleDuration(Duration.seconds(0.4));\r\n\t\t\tsetDelay(Duration.seconds(0));\r\n\t\t}\r\n\t}\r\n\r\n\tprivate class BottomTransition extends CachedTransition {\r\n\t\tpublic BottomTransition() {\r\n\t\t\tsuper(contentHolder, new Timeline(\r\n\t\t\t\t\tnew KeyFrame(Duration.ZERO, \r\n\t\t\t\t\t\t\tnew KeyValue(contentHolder.translateYProperty(), offsetY ,Interpolator.EASE_BOTH),\r\n\t\t\t\t\t\t\tnew KeyValue(overlayPane.visibleProperty(), false ,Interpolator.EASE_BOTH)\r\n\t\t\t\t\t\t\t),\r\n\t\t\t\t\t\t\tnew KeyFrame(Duration.millis(10), \r\n\t\t\t\t\t\t\t\t\tnew KeyValue(overlayPane.visibleProperty(), true ,Interpolator.EASE_BOTH),\r\n\t\t\t\t\t\t\t\t\tnew KeyValue(overlayPane.opacityProperty(), 0, Interpolator.EASE_BOTH)\r\n\t\t\t\t\t\t\t\t\t),\r\n\t\t\t\t\t\t\t\t\tnew KeyFrame(Duration.millis(1000), \r\n\t\t\t\t\t\t\t\t\t\t\tnew KeyValue(contentHolder.translateYProperty(), 0,Interpolator.EASE_BOTH),\r\n\t\t\t\t\t\t\t\t\t\t\tnew KeyValue(overlayPane.opacityProperty(), 1, Interpolator.EASE_BOTH)))\r\n\t\t\t\t\t);\r\n\t\t\t// reduce the number to increase the shifting , increase number to reduce shifting\r\n\t\t\tsetCycleDuration(Duration.seconds(0.4));\r\n\t\t\tsetDelay(Duration.seconds(0));\r\n\t\t}\r\n\t}\r\n\r\n\tprivate class CenterTransition extends CachedTransition {\r\n\t\tpublic CenterTransition() {\r\n\t\t\tsuper(contentHolder, new Timeline(\r\n\t\t\t\t\tnew KeyFrame(Duration.ZERO, \r\n\t\t\t\t\t\t\tnew KeyValue(contentHolder.scaleXProperty(), 0 ,Interpolator.EASE_BOTH),\r\n\t\t\t\t\t\t\tnew KeyValue(contentHolder.scaleYProperty(), 0 ,Interpolator.EASE_BOTH),\r\n\t\t\t\t\t\t\tnew KeyValue(overlayPane.visibleProperty(), false ,Interpolator.EASE_BOTH)\r\n\t\t\t\t\t\t\t),\r\n\t\t\t\t\t\t\tnew KeyFrame(Duration.millis(10), \r\n\t\t\t\t\t\t\t\t\tnew KeyValue(overlayPane.visibleProperty(), true ,Interpolator.EASE_BOTH),\r\n\t\t\t\t\t\t\t\t\tnew KeyValue(overlayPane.opacityProperty(), 0,Interpolator.EASE_BOTH)\r\n\t\t\t\t\t\t\t\t\t),\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\tnew KeyFrame(Duration.millis(1000), \t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\tnew KeyValue(contentHolder.scaleXProperty(), 1 ,Interpolator.EASE_BOTH),\r\n\t\t\t\t\t\t\t\t\t\t\tnew KeyValue(contentHolder.scaleYProperty(), 1 ,Interpolator.EASE_BOTH),\r\n\t\t\t\t\t\t\t\t\t\t\tnew KeyValue(overlayPane.opacityProperty(), 1, Interpolator.EASE_BOTH)\r\n\t\t\t\t\t\t\t\t\t\t\t))\r\n\t\t\t\t\t);\r\n\t\t\t// reduce the number to increase the shifting , increase number to reduce shifting\r\n\t\t\tsetCycleDuration(Duration.seconds(0.4));\r\n\t\t\tsetDelay(Duration.seconds(0));\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t/***************************************************************************\r\n\t * *\r\n\t * Stylesheet Handling *\r\n\t * *\r\n\t **************************************************************************/\r\n\r\n\tprivate static final String DEFAULT_STYLE_CLASS = \"jfx-dialog\";\r\n\r\n\r\n\tprivate StyleableObjectProperty transitionType = new SimpleStyleableObjectProperty(StyleableProperties.DIALOG_TRANSITION, JFXDialog.this, \"dialogTransition\", DialogTransition.CENTER );\r\n\r\n\tpublic DialogTransition getTransitionType(){\r\n\t\treturn transitionType == null ? DialogTransition.CENTER : transitionType.get();\r\n\t}\r\n\tpublic StyleableObjectProperty transitionTypeProperty(){\t\t\r\n\t\treturn this.transitionType;\r\n\t}\r\n\tpublic void setTransitionType(DialogTransition transition){\r\n\t\tthis.transitionType.set(transition);\r\n\t}\r\n\r\n\r\n\tprivate static class StyleableProperties {\r\n\t\tprivate static final CssMetaData< JFXDialog, DialogTransition> DIALOG_TRANSITION =\r\n\t\t\t\tnew CssMetaData< JFXDialog, DialogTransition>(\"-fx-dialog-transition\",\r\n\t\t\t\t\t\tDialogTransitionConverter.getInstance(), DialogTransition.CENTER) {\r\n\t\t\t@Override\r\n\t\t\tpublic boolean isSettable(JFXDialog control) {\r\n\t\t\t\treturn control.transitionType == null || !control.transitionType.isBound();\r\n\t\t\t}\r\n\t\t\t@Override\r\n\t\t\tpublic StyleableProperty getStyleableProperty(JFXDialog control) {\r\n\t\t\t\treturn control.transitionTypeProperty();\r\n\t\t\t}\r\n\t\t};\r\n\r\n\t\tprivate static final List> CHILD_STYLEABLES;\r\n\t\tstatic {\r\n\t\t\tfinal List> styleables =\r\n\t\t\t\t\tnew ArrayList>(Parent.getClassCssMetaData());\r\n\t\t\tCollections.addAll(styleables,\r\n\t\t\t\t\tDIALOG_TRANSITION\r\n\t\t\t\t\t);\r\n\t\t\tCHILD_STYLEABLES = Collections.unmodifiableList(styleables);\r\n\t\t}\r\n\t}\r\n\r\n\t// inherit the styleable properties from parent\r\n\tprivate List> STYLEABLES;\r\n\r\n\t@Override\r\n\tpublic List> getCssMetaData() {\r\n\t\tif(STYLEABLES == null){\r\n\t\t\tfinal List> styleables =\r\n\t\t\t\t\tnew ArrayList>(Parent.getClassCssMetaData());\r\n\t\t\tstyleables.addAll(getClassCssMetaData());\r\n\t\t\tstyleables.addAll(super.getClassCssMetaData());\r\n\t\t\tSTYLEABLES = Collections.unmodifiableList(styleables);\r\n\t\t}\r\n\t\treturn STYLEABLES;\r\n\t}\r\n\tpublic static List> getClassCssMetaData() {\r\n\t\treturn StyleableProperties.CHILD_STYLEABLES;\r\n\t}\r\n\r\n\r\n\r\n\t/***************************************************************************\r\n\t * *\r\n\t * Custom Events *\r\n\t * *\r\n\t **************************************************************************/\r\n\t\r\n\tprivate ObjectProperty> onDialogClosedProperty = new SimpleObjectProperty<>((closed)->{});\r\n\r\n\tpublic void setOnDialogClosed(EventHandler handler){\r\n\t\tonDialogClosedProperty.set(handler);\r\n\t}\r\n\r\n\tpublic void getOnDialogClosed(EventHandler handler){\r\n\t\tonDialogClosedProperty.get();\r\n\t}\r\n\r\n\r\n\tprivate ObjectProperty> onDialogOpenedProperty = new SimpleObjectProperty<>((opened)->{});\r\n\t\r\n\tpublic void setOnDialogOpened(EventHandler handler){\r\n\t\tonDialogOpenedProperty.set(handler);\r\n\t}\r\n\r\n\tpublic void getOnDialogOpened(EventHandler handler){\r\n\t\tonDialogOpenedProperty.get();\r\n\t}\r\n\r\n\r\n\r\n\t\r\n\t\r\n}\r\n\r\n"},"message":{"kind":"string","value":"Note that JFXDialog requires the root to be stack pane to work properly\n"},"old_file":{"kind":"string","value":"src/com/jfoenix/controls/JFXDialog.java"},"subject":{"kind":"string","value":"Note that JFXDialog requires the root to be stack pane to work properly"},"git_diff":{"kind":"string","value":"rc/com/jfoenix/controls/JFXDialog.java\n \n /**\n * @author Shadi Shaheen\n *\n * note that for JFXDialog to work properly the root node should\n * be of type {@link StackPane}\n */\n @DefaultProperty(value=\"content\")\n public class JFXDialog extends StackPane {"}}},{"rowIdx":868,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"ac3965447d9e9d1c066f89eafb67c558975b7965"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"appaloosa-store/appaloosa-android-tools"},"new_contents":{"kind":"string","value":"package appaloosa_store.com.appaloosa_android_tools.analytics.db;\n\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.sqlite.SQLiteDatabase;\nimport android.database.sqlite.SQLiteOpenHelper;\nimport android.util.Pair;\n\nimport com.google.gson.JsonArray;\nimport com.google.gson.JsonParser;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport appaloosa_store.com.appaloosa_android_tools.analytics.model.Event;\n\npublic class AnalyticsDb extends SQLiteOpenHelper {\n\n private static final int DB_VERSION = 1;\n private static final String DB_NAME = \"analytics\";\n\n private static final String TABLE_EVENT = \"event\";\n private static final String CREATE_TABLE = \"CREATE TABLE \" + TABLE_EVENT +\n \"(\" + DBColumn.ID + \" INTEGER PRIMARY KEY NOT NULL, \" +\n DBColumn.EVENT + \" TEXT);\";\n\n private SQLiteDatabase db;\n private final Object lock = new Object();\n\n public AnalyticsDb(Context context) {\n super(context, DB_NAME, null, DB_VERSION);\n db = getWritableDatabase();\n }\n\n @Override\n public void onCreate(SQLiteDatabase db) {\n db.execSQL(CREATE_TABLE);\n }\n\n @Override\n public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n db.execSQL(\"DROP TABLE IF EXISTS \" + TABLE_EVENT + \";\");\n onCreate(db);\n }\n\n public boolean insertEvent(Event event) {\n ContentValues value = new ContentValues();\n value.put(DBColumn.EVENT.toString(), event.toJson().toString());\n synchronized (lock) {\n return db.insert(TABLE_EVENT, null, value) != -1;\n }\n }\n\n public int countEvents() {\n Cursor c = db.rawQuery(\"SELECT COUNT(*) FROM \" + TABLE_EVENT, null);\n if (c.moveToNext()) {\n return c.getInt(0);\n }\n c.close();\n return 0;\n }\n\n public Pair, JsonArray> getOldestEvents(int batchSize) {\n List eventsIds = new ArrayList<>();\n JsonArray events = new JsonArray();\n JsonParser parser = new JsonParser();\n synchronized (lock) {\n Cursor cursor = db.query(TABLE_EVENT,\n DBColumn.COLUMNS,\n null, null, null, null,\n DBColumn.ID.toString() + \" ASC\",\n batchSize + \"\");\n while (cursor.moveToNext()) {\n events.add(parser.parse(cursor.getString(DBColumn.EVENT.getIndex())));\n eventsIds.add(cursor.getInt(DBColumn.ID.getIndex()));\n }\n cursor.close();\n }\n return new Pair<>(eventsIds, events);\n }\n\n public boolean deleteEvent(int id) {\n synchronized (lock) {\n return db.delete(TABLE_EVENT, DBColumn.ID.toString() + \" = ?\", new String[] {\"\" + id}) > 0;\n }\n }\n\n public boolean deleteEvents(List ids) {\n boolean allDeleted = true;\n for (int id : ids) {\n allDeleted &= deleteEvent(id);\n }\n return allDeleted;\n }\n}"},"new_file":{"kind":"string","value":"app/src/main/java/appaloosa_store/com/appaloosa_android_tools/analytics/db/AnalyticsDb.java"},"old_contents":{"kind":"string","value":"package appaloosa_store.com.appaloosa_android_tools.analytics.db;\n\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.sqlite.SQLiteDatabase;\nimport android.database.sqlite.SQLiteOpenHelper;\nimport android.util.Pair;\n\nimport com.google.gson.JsonArray;\nimport com.google.gson.JsonParser;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport appaloosa_store.com.appaloosa_android_tools.analytics.model.Event;\n\npublic class AnalyticsDb extends SQLiteOpenHelper {\n\n private static final int DB_VERSION = 1;\n private static final String DB_NAME = \"analytics\";\n\n private static final String TABLE_EVENT = \"event\";\n private static final String CREATE_TABLE = \"CREATE TABLE \" + TABLE_EVENT +\n \"(\" + DBColumn.ID + \" INTEGER PRIMARY KEY NOT NULL, \" +\n DBColumn.EVENT + \" TEXT);\";\n\n private SQLiteDatabase db;\n private final Object lock = new Object();\n\n public AnalyticsDb(Context context) {\n super(context, DB_NAME, null, DB_VERSION);\n db = getWritableDatabase();\n }\n\n @Override\n public void onCreate(SQLiteDatabase db) {\n db.execSQL(CREATE_TABLE);\n }\n\n @Override\n public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n db.execSQL(\"DROP TABLE IF EXISTS \" + TABLE_EVENT + \";\");\n onCreate(db);\n }\n\n public boolean insertEvent(Event event) {\n ContentValues value = new ContentValues();\n value.put(DBColumn.EVENT.toString(), event.toJson().toString());\n synchronized (lock) {\n return db.insert(TABLE_EVENT, null, value) != -1;\n }\n }\n\n public int countEvents() {\n Cursor c = db.rawQuery(\"SELECT COUNT(*) FROM \" + TABLE_EVENT, null);\n if (c.moveToNext()) {\n return c.getInt(0);\n }\n return 0;\n }\n\n public Pair, JsonArray> getOldestEvents(int batchSize) {\n List eventsIds = new ArrayList<>();\n JsonArray events = new JsonArray();\n JsonParser parser = new JsonParser();\n synchronized (lock) {\n Cursor cursor = db.query(TABLE_EVENT,\n DBColumn.COLUMNS,\n null, null, null, null,\n DBColumn.ID.toString() + \" ASC\",\n batchSize + \"\");\n while (cursor.moveToNext()) {\n events.add(parser.parse(cursor.getString(DBColumn.EVENT.getIndex())));\n eventsIds.add(cursor.getInt(DBColumn.ID.getIndex()));\n }\n cursor.close();\n }\n return new Pair<>(eventsIds, events);\n }\n\n public boolean deleteEvent(int id) {\n synchronized (lock) {\n return db.delete(TABLE_EVENT, DBColumn.ID.toString() + \" = ?\", new String[] {\"\" + id}) > 0;\n }\n }\n\n public boolean deleteEvents(List ids) {\n boolean allDeleted = true;\n for (int id : ids) {\n allDeleted &= deleteEvent(id);\n }\n return allDeleted;\n }\n}"},"message":{"kind":"string","value":"Quick fix to AnalyticsDb\n"},"old_file":{"kind":"string","value":"app/src/main/java/appaloosa_store/com/appaloosa_android_tools/analytics/db/AnalyticsDb.java"},"subject":{"kind":"string","value":"Quick fix to AnalyticsDb"},"git_diff":{"kind":"string","value":"pp/src/main/java/appaloosa_store/com/appaloosa_android_tools/analytics/db/AnalyticsDb.java\n if (c.moveToNext()) {\n return c.getInt(0);\n }\n c.close();\n return 0;\n }\n "}}},{"rowIdx":869,"cells":{"lang":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"24cbd0eba4521ab8cbe32361321187e447d66a79"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"SavageCore/yadg-pth-userscript,SavageCore/yadg-pth-userscript"},"new_contents":{"kind":"string","value":"// ==UserScript==\n// @id pth-yadg\n// @name PTH YADG\n// @description This script provides integration with online description generator YADG (http://yadg.cc) - Credit to Slack06\n// @license https://github.com/SavageCore/yadg-pth-userscript/blob/master/LICENSE\n// @version 1.3.10\n// @namespace yadg\n// @grant GM_xmlhttpRequest\n// @require https://yadg.cc/static/js/jsandbox.min.js\n// @include http*://*passtheheadphones.me/upload.php*\n// @include http*://*passtheheadphones.me/requests.php*\n// @include http*://*passtheheadphones.me/torrents.php*\n// @include http*://*waffles.ch/upload.php*\n// @include http*://*waffles.ch/requests.php*\n// @downloadURL https://github.com/SavageCore/yadg-pth-userscript/raw/master/pth_yadg.user.js\n// ==/UserScript==\n\n// --------- USER SETTINGS START ---------\n\n/*\n Here you can set site specific default templates.\n You can find a list of available templates at: https://yadg.cc/api/v2/templates/\n*/\nvar defaultPTHFormat = 5,\n defaultWafflesFormat = 9;\n\n// --------- USER SETTINGS END ---------\n\n\n\n// --------- THIRD PARTY CODE AREA START ---------\n\n//\n// Creates an object which gives some helper methods to\n// Save/Load/Remove data to/from the localStorage\n//\n// Source from: https://github.com/gergob/localstoragewrapper\n//\nfunction LocalStorageWrapper (applicationPrefix) {\n \"use strict\";\n\n if(applicationPrefix == undefined) {\n throw new Error('applicationPrefix parameter should be defined');\n }\n\n var delimiter = '_';\n\n //if the passed in value for prefix is not string, it should be converted\n var keyPrefix = typeof(applicationPrefix) === 'string' ? applicationPrefix : JSON.stringify(applicationPrefix);\n\n var localStorage = window.localStorage||unsafeWindow.localStorage;\n\n var isLocalStorageAvailable = function() {\n return typeof(localStorage) != undefined\n };\n\n var getKeyPrefix = function() {\n return keyPrefix;\n };\n\n //\n // validates if there is a prefix defined for the keys\n // and checks if the localStorage functionality is available or not\n //\n var makeChecks = function(key) {\n var prefix = getKeyPrefix();\n if(prefix == undefined) {\n throw new Error('No prefix was defined, data cannot be saved');\n }\n\n if(!isLocalStorageAvailable()) {\n throw new Error('LocalStorage is not supported by your browser, data cannot be saved');\n }\n\n //keys are always strings\n var checkedKey = typeof(key) === 'string' ? key : JSON.stringify(key);\n\n return checkedKey;\n };\n\n //\n // saves the value associated to the key into the localStorage\n //\n var addItem = function(key, value) {\n var that = this;\n try{\n var checkedKey = makeChecks(key);\n var combinedKey = that.getKeyPrefix() + delimiter + checkedKey;\n localStorage.setItem(combinedKey, JSON.stringify(value));\n }\n catch(error) {\n console.log(error);\n throw error;\n }\n };\n\n //\n // gets the value of the object saved to the key passed as parameter\n //\n var getItem = function(key) {\n var that = this;\n var result = undefined;\n try{\n var checkedKey = makeChecks(key);\n var combinedKey = that.getKeyPrefix() + delimiter + checkedKey;\n var resultAsJSON = localStorage.getItem(combinedKey);\n result = JSON.parse(resultAsJSON);\n }\n catch(error) {\n console.log(error);\n throw error;\n }\n return result;\n };\n\n //\n // returns all the keys from the localStorage\n //\n var getAllKeys = function() {\n var prefix = getKeyPrefix();\n var results = [];\n\n if(prefix == undefined) {\n throw new Error('No prefix was defined, data cannot be saved');\n }\n\n if(!isLocalStorageAvailable()) {\n throw new Error('LocalStorage is not supported by your browser, data cannot be saved');\n }\n\n for(var key in localStorage) {\n if(key.indexOf(prefix) == 0) {\n var keyParts = key.split(delimiter);\n results.push(keyParts[1]);\n }\n }\n\n return results;\n };\n\n //\n // removes the value associated to the key from the localStorage\n //\n var removeItem = function(key) {\n var that = this;\n var result = false;\n try{\n var checkedKey = makeChecks(key);\n var combinedKey = that.getKeyPrefix() + delimiter + checkedKey;\n localStorage.removeItem(combinedKey);\n result = true;\n }\n catch(error) {\n console.log(error);\n throw error;\n }\n return result;\n };\n\n //\n // removes all the values from the localStorage\n //\n var removeAll = function() {\n var that = this;\n\n try{\n var allKeys = that.getAllKeys();\n for(var i=0; i < allKeys.length; ++i) {\n var checkedKey = makeChecks(allKeys[i]);\n var combinedKey = that.getKeyPrefix() + delimiter + checkedKey;\n localStorage.removeItem(combinedKey);\n }\n }\n catch(error) {\n console.log(error);\n throw error;\n }\n };\n\n // make some of the functionalities public\n return {\n isLocalStorageAvailable : isLocalStorageAvailable,\n getKeyPrefix : getKeyPrefix,\n addItem : addItem,\n getItem : getItem,\n getAllKeys : getAllKeys,\n removeItem : removeItem,\n removeAll : removeAll\n }\n}\n\n// --------- THIRD PARTY CODE AREA END ---------\n\nvar yadg_util = {\n exec : function exec(fn) {\n var script = document.createElement('script');\n script.setAttribute(\"type\", \"application/javascript\");\n script.textContent = '(' + fn + ')();';\n document.body.appendChild(script); // run the script\n document.body.removeChild(script); // clean up\n },\n\n // handle for updating page css, taken from one of hateradio's scripts\n addCSS : function(style) {\n if(!this.style) {\n this.style = document.createElement('style');\n this.style.type = 'text/css';\n (document.head || document.getElementsByTagName('head')[0]).appendChild(this.style);\n }\n this.style.appendChild(document.createTextNode(style+'\\n'));\n },\n\n setValueIfSet: function(value,input,cond) {\n if (cond) {\n input.value = value;\n } else {\n input.value = '';\n }\n },\n\n // negative count will remove, positive count will add given number of artist boxes\n addRemoveArtistBoxes : function(count) {\n if (count != 0) {\n if (count < 0) {\n for (var i = 0; i < -count; i++) {\n yadg_util.exec(function() {RemoveArtistField()});\n }\n } else {\n for (var i = 0; i < count; i++) {\n yadg_util.exec(function() {AddArtistField()});\n }\n }\n }\n },\n\n getOptionOffsets : function(select) {\n var option_offsets = {};\n for (var j = 0; j < select.options.length; j++) {\n option_offsets[select.options[j].value] = select.options[j].index;\n }\n return option_offsets;\n },\n\n storage : new LocalStorageWrapper(\"yadg\"),\n\n settings : new LocalStorageWrapper(\"yadgSettings\")\n};\n\n// very simple wrapper for XmlHttpRequest\nfunction requester(url, method, callback, data, error_callback) {\n this.data = data;\n this.url = url;\n this.method = method;\n if (!error_callback) {\n error_callback = yadg.failed_callback;\n }\n\n this.send = function() {\n var details = {\n url : this.url,\n method : this.method,\n onload : function(response) {\n if (response.status === 200) {\n callback(JSON.parse(response.responseText));\n } else if (response.status === 401) {\n yadg.failed_authentication_callback();\n } else {\n error_callback();\n }\n },\n onerror : error_callback\n };\n if (method == \"POST\") {\n details.data = JSON.stringify(this.data);\n }\n\n var headers = {\n \"Accept\" : \"application/json\",\n \"Content-Type\" : \"application/json\"\n };\n\n if (yadg_util.settings.getItem(factory.KEY_API_TOKEN)) {\n headers.Authorization = \"Token \" + yadg_util.settings.getItem(factory.KEY_API_TOKEN);\n }\n\n details.headers = headers;\n\n GM_xmlhttpRequest(details);\n };\n}\n\nvar yadg_sandbox = {\n\n KEY_LAST_WARNING : \"templateLastWarning\",\n\n init : function(callback) {\n GM_xmlhttpRequest({\n method: 'GET',\n url: yadg.yadgHost + '/static/js/jsandbox-worker.js',\n onload: function(response) {\n var script, dataURL = null;\n if (response.status === 200) {\n script = response.responseText;\n var blob = new Blob([script], {type: 'application/javascript'});\n var URL = window.URL || window.webkitURL;\n if (!URL || !URL.createObjectURL) {\n throw new Error('No no valid implementation of window.URL.createObjectURL found.');\n }\n dataURL = URL.createObjectURL(blob);\n yadg_sandbox.initCallback(dataURL);\n yadg_sandbox.loadSwig(callback);\n } else {\n yadg_sandbox.initCallbackError();\n }\n },\n onerror: function() {\n yadg_sandbox.initCallbackError();\n }\n });\n\n },\n\n loadSwig : function(callback) {\n // importScripts for the web worker will not work in Firefox with cross-domain requests\n // see: https://bugzilla.mozilla.org/show_bug.cgi?id=756589\n // so download the Swig files manually with GM_xmlhttpRequest\n GM_xmlhttpRequest({\n method: 'GET',\n url: yadg.yadgHost + \"/static/js/swig.min.js\",\n onload: function(response) {\n if (response.status === 200) {\n yadg_sandbox.swig_script = response.responseText;\n\n GM_xmlhttpRequest({\n method: 'GET',\n url: yadg.yadgHost + \"/static/js/swig.custom.js\",\n onload: function(response) {\n if (response.status === 200) {\n yadg_sandbox.swig_custom_script = response.responseText;\n callback();\n }\n }\n });\n }\n }\n });\n },\n\n initializeSwig : function(dependencies) {\n if (!(this.swig_script && this.swig_custom_script)) {\n yadg.failed_callback();\n return\n }\n\n yadg_sandbox.exec({data: this.swig_script, onerror: yadg.failed_callback});\n yadg_sandbox.exec({data: this.swig_custom_script, onerror: yadg.failed_callback});\n yadg_sandbox.exec({data: \"var myswig = new swig.Swig({ loader: swig.loaders.memory(input.templates), autoescape: false }), i=0; yadg_filters.register_filters(myswig);\", input: {templates: dependencies}});\n },\n\n renderTemplate : function(template, data, callback, error) {\n var eval_string = \"myswig.render(input.template, { locals: input.data, filename: 'scratchpad' + (i++) })\";\n this.eval({data: eval_string, callback: function(out) {callback(out);}, input: {template: template, data: data}, onerror: function(err){error(err);}});\n },\n\n initCallback : function(dataUrl) {\n JSandbox.url = dataUrl;\n this.jsandbox = new JSandbox();\n this.initError = false;\n },\n\n resetSandbox : function() {\n this.jsandbox.terminate();\n this.jsandbox = new JSandbox();\n },\n\n load : function(options) {\n this.jsandbox.load(options);\n },\n\n exec : function(options) {\n this.jsandbox.exec(options);\n },\n\n eval : function(options) {\n this.jsandbox.eval(options);\n },\n\n initCallbackError : function() {\n this.initError = true;\n\n var last_warning = yadg_util.storage.getItem(this.KEY_LAST_WARNING),\n now = new Date();\n if (last_warning === null || now.getTime() - (new Date(last_warning)).getTime() > factory.CACHE_TIMEOUT) {\n alert(\"Could not load the necessary script files for executing YADG. If this error persists you might need to update the user script. You will only get this message once a day.\");\n yadg_util.storage.addItem(this.KEY_LAST_WARNING, now);\n }\n }\n};\n\nvar factory = {\n // storage keys for cache\n KEY_LAST_CHECKED : \"lastChecked\",\n KEY_SCRAPER_LIST : \"scraperList\",\n KEY_FORMAT_LIST : \"formatList\",\n\n // storage keys for settings\n KEY_API_TOKEN : \"apiToken\",\n KEY_DEFAULT_TEMPLATE : \"defaultTemplate\",\n KEY_DEFAULT_SCRAPER : \"defaultScraper\",\n KEY_REPLACE_DESCRIPTION : \"replaceDescriptionOn\",\n KEY_SETTINGS_INIT_VER : \"settingsInitializedVer\",\n\n CACHE_TIMEOUT : 1000*60*60*24, // 24 hours\n\n UPDATE_PROGRESS : 0,\n\n locations : new Array(\n {\n name : 'pth_upload',\n regex : /http(s)?\\:\\/\\/(.*\\.)?passtheheadphones\\.me\\/upload\\.php.*/i\n },\n {\n name : 'pth_edit',\n regex : /http(s)?\\:\\/\\/(.*\\.)?passtheheadphones\\.me\\/torrents\\.php\\?action=editgroup&groupid=.*/i\n },\n {\n name : 'pth_request',\n regex : /http(s)?\\:\\/\\/(.*\\.)?passtheheadphones\\.me\\/requests\\.php\\?action=new/i\n },\n {\n name : 'pth_request_edit',\n regex : /http(s)?\\:\\/\\/(.*\\.)?passtheheadphones\\.me\\/requests\\.php\\?action=edit&id=.*/i\n },\n {\n name : 'pth_torrent_overview',\n regex : /http(s)?\\:\\/\\/(.*\\.)?passtheheadphones\\.me\\/torrents\\.php\\?id=.*/i\n },\n {\n name : 'waffles_upload',\n// regex : /http(s)?\\:\\/\\/(.*\\.)?waffles\\.ch\\/upload\\.php\\?legacy=1.*/i\n// },\n// {\n// TODO: reenable support for the new Waffles upload page once it is reactivated\n// name : 'waffles_upload_new',\n regex : /http(s)?\\:\\/\\/(.*\\.)?waffles\\.ch\\/upload\\.php.*/i\n },\n {\n name : 'waffles_request',\n regex : /http(s)?\\:\\/\\/(.*\\.)?waffles\\.ch\\/requests\\.php\\?do=add/i\n }\n ),\n\n determineLocation : function(uri) {\n for (var i = 0; i < this.locations.length; i++) {\n if (this.locations[i].regex.test(uri)) {\n return this.locations[i].name;\n }\n }\n return null;\n },\n\n init : function() {\n this.currentLocation = this.determineLocation(document.URL);\n // only continue with the initialization if we found a valid location\n if (this.currentLocation !== null) {\n this.insertIntoPage(this.getInputElements());\n\n // set the necessary styles\n this.setStyles();\n\n // make sure we initialize the settings to the most recent version\n this.initializeSettings();\n\n // populate settings inputs\n this.populateSettings();\n\n // add the appropriate action for the button\n var button = document.getElementById('yadg_submit');\n button.addEventListener('click', function (e) {\n e.preventDefault();\n yadg.makeRequest();\n }, false);\n\n // add the action for the options toggle\n var toggleLink = document.getElementById('yadg_toggle_options');\n if (toggleLink !== null) {\n toggleLink.addEventListener('click', function (e) {\n e.preventDefault();\n\n var optionsDiv = document.getElementById('yadg_options'),\n display = optionsDiv.style.display;\n\n if (display == 'none' || display == '') {\n optionsDiv.style.display = 'block';\n } else {\n optionsDiv.style.display = 'none';\n }\n });\n }\n\n // add the action for the template select\n var formatSelect = this.getFormatSelect();\n if (formatSelect !== null) {\n formatSelect.addEventListener('change', function (e) {\n if (yadg_renderer.hasCached()) {\n yadg_renderer.renderCached(this.value, factory.setDescriptionBoxValue, factory.setDescriptionBoxValue);\n }\n });\n }\n\n // add the action to the save settings link\n var saveSettingsLink = document.getElementById('yadg_save_settings');\n if (saveSettingsLink !== null) {\n saveSettingsLink.addEventListener('click', function (e) {\n e.preventDefault();\n\n factory.saveSettings();\n\n alert(\"Settings saved successfully.\");\n });\n }\n\n // add the action to the clear cache link\n var clearCacheLink = document.getElementById('yadg_clear_cache');\n if (clearCacheLink !== null) {\n clearCacheLink.addEventListener('click', function (e) {\n e.preventDefault();\n\n yadg_util.storage.removeAll();\n\n alert(\"Cache cleared. Please reload the page for this to take effect.\");\n });\n }\n\n var last_checked = yadg_util.storage.getItem(factory.KEY_LAST_CHECKED);\n if (last_checked === null || (new Date()).getTime() - (new Date(last_checked)).getTime() > factory.CACHE_TIMEOUT) {\n // update the scraper and formats list\n factory.UPDATE_PROGRESS = 1;\n yadg.getScraperList(factory.setScraperSelect);\n yadg.getFormatsList(factory.setFormatSelect);\n } else {\n factory.setScraperSelect(yadg_util.storage.getItem(factory.KEY_SCRAPER_LIST));\n factory.setFormatSelect(yadg_util.storage.getItem(factory.KEY_FORMAT_LIST));\n }\n\n return true;\n } else {\n return false;\n }\n },\n\n getApiTokenInput : function() {\n return document.getElementById('yadg_api_token');\n },\n\n getReplaceDescriptionCheckbox : function() {\n return document.getElementById('yadg_options_replace');\n },\n\n getReplaceDescriptionSettingKey : function() {\n return this.makeReplaceDescriptionSettingsKey(this.currentLocation);\n },\n\n makeReplaceDescriptionSettingsKey : function(subKey) {\n return this.KEY_REPLACE_DESCRIPTION + subKey.replace(/_/g, \"\");\n },\n\n initializeSettings : function() {\n var settings_ver = yadg_util.settings.getItem(factory.KEY_SETTINGS_INIT_VER),\n current_ver = 1;\n\n if (!settings_ver) {\n settings_ver = 0;\n }\n\n if (settings_ver < current_ver) {\n // replace descriptions on upload and new request pages\n var locations = [\n 'pth_upload',\n 'pth_request',\n 'waffles_upload',\n 'waffles_upload_new',\n 'waffles_request'\n ];\n for (var i = 0; i < locations.length; i++) {\n var loc = locations[i],\n replace_desc_setting_key = factory.makeReplaceDescriptionSettingsKey(loc);\n\n yadg_util.settings.addItem(replace_desc_setting_key, true);\n }\n }\n\n yadg_util.settings.addItem(factory.KEY_SETTINGS_INIT_VER, current_ver);\n },\n\n populateSettings : function() {\n var api_token = yadg_util.settings.getItem(factory.KEY_API_TOKEN),\n replace_desc = yadg_util.settings.getItem(factory.getReplaceDescriptionSettingKey());\n\n if (api_token) {\n var api_token_input = factory.getApiTokenInput();\n api_token_input.value = api_token;\n }\n\n if (replace_desc) {\n var replace_desc_checkbox = factory.getReplaceDescriptionCheckbox();\n replace_desc_checkbox.checked = true;\n }\n },\n\n saveSettings : function() {\n var scraper_select = factory.getScraperSelect(),\n template_select = factory.getFormatSelect(),\n api_token_input = factory.getApiTokenInput(),\n replace_desc_checkbox = factory.getReplaceDescriptionCheckbox();\n\n var current_scraper = null,\n current_template = null,\n api_token = api_token_input.value.trim(),\n replace_description = replace_desc_checkbox.checked;\n\n if (scraper_select.options.length > 0) {\n current_scraper = scraper_select.options[scraper_select.selectedIndex].value;\n }\n\n if (template_select.options.length > 0) {\n current_template = template_select.options[template_select.selectedIndex].value;\n }\n\n if (current_scraper !== null) {\n yadg_util.settings.addItem(factory.KEY_DEFAULT_SCRAPER, current_scraper);\n }\n\n if (current_template !== null) {\n yadg_util.settings.addItem(factory.KEY_DEFAULT_TEMPLATE, current_template);\n }\n\n if (api_token !== \"\") {\n yadg_util.settings.addItem(factory.KEY_API_TOKEN, api_token);\n } else {\n yadg_util.settings.removeItem(factory.KEY_API_TOKEN);\n }\n\n var replace_desc_setting_key = factory.getReplaceDescriptionSettingKey();\n if (replace_description) {\n yadg_util.settings.addItem(replace_desc_setting_key, true);\n } else {\n yadg_util.settings.removeItem(replace_desc_setting_key);\n }\n },\n\n setDescriptionBoxValue : function(value) {\n var desc_box = factory.getDescriptionBox(),\n replace_desc_checkbox = factory.getReplaceDescriptionCheckbox(),\n replace_desc = false;\n\n if (replace_desc_checkbox !== null) {\n replace_desc = replace_desc_checkbox.checked;\n }\n\n if (desc_box !== null) {\n if (!replace_desc && /\\S/.test(desc_box.value)) { // check if the current description contains more than whitespace\n desc_box.value += \"\\n\\n\" + value;\n } else {\n desc_box.value = value;\n }\n }\n },\n\n getFormatSelect : function() {\n return document.getElementById('yadg_format');\n },\n\n setDefaultFormat : function() {\n var format_select = factory.getFormatSelect();\n var format_offsets = yadg_util.getOptionOffsets(format_select);\n\n var default_format = yadg_util.settings.getItem(factory.KEY_DEFAULT_TEMPLATE);\n if (default_format !== null && default_format in format_offsets) {\n format_select.selectedIndex = format_offsets[default_format];\n } else {\n // we have no settings so fall back to the hard coded defaults\n switch (this.currentLocation) {\n case \"waffles_upload\":\n case \"waffles_upload_new\":\n case \"waffles_request\":\n format_select.selectedIndex = format_offsets[defaultWafflesFormat];\n break;\n\n default:\n format_select.selectedIndex = format_offsets[defaultPTHFormat];\n break;\n }\n }\n },\n\n getScraperSelect : function() {\n return document.getElementById(\"yadg_scraper\");\n },\n\n setDefaultScraper : function() {\n var default_scraper = yadg_util.settings.getItem(factory.KEY_DEFAULT_SCRAPER);\n if (default_scraper !== null) {\n var scraper_select = factory.getScraperSelect();\n var scraper_offsets = yadg_util.getOptionOffsets(scraper_select);\n\n if (default_scraper in scraper_offsets) {\n scraper_select.selectedIndex = scraper_offsets[default_scraper];\n }\n }\n },\n\n setScraperSelect : function(scrapers) {\n var scraper_select = factory.getScraperSelect();\n\n factory.setSelect(scraper_select, scrapers);\n factory.setDefaultScraper();\n\n if (factory.UPDATE_PROGRESS > 0) {\n yadg_util.storage.addItem(factory.KEY_SCRAPER_LIST, scrapers);\n factory.UPDATE_PROGRESS |= 1<<1;\n\n if (factory.UPDATE_PROGRESS === 7) {\n yadg_util.storage.addItem(factory.KEY_LAST_CHECKED, new Date());\n }\n }\n },\n\n setFormatSelect : function(templates) {\n var format_select = factory.getFormatSelect();\n\n var non_utility = [];\n var save_templates = [];\n for (var i = 0; i < templates.length; i++) {\n if (factory.UPDATE_PROGRESS > 0) {\n yadg_templates.addTemplate(templates[i]);\n\n save_templates.push({\n id : templates[i]['id'],\n url : templates[i]['url'],\n name : templates[i]['name'],\n nameFormatted : templates[i]['nameFormatted'],\n owner : templates[i]['owner'],\n default : templates[i]['default'],\n isUtility : templates[i]['isUtility']\n });\n } else {\n yadg_templates.addTemplateUrl(templates[i]['id'], templates[i]['url']);\n }\n\n if (!templates[i]['isUtility']) {\n non_utility.push(templates[i]);\n }\n }\n\n factory.setSelect(format_select, non_utility);\n factory.setDefaultFormat();\n\n if (factory.UPDATE_PROGRESS > 0) {\n yadg_util.storage.addItem(factory.KEY_FORMAT_LIST, save_templates);\n factory.UPDATE_PROGRESS |= 1<<2;\n\n if (factory.UPDATE_PROGRESS === 7) {\n yadg_util.storage.addItem(factory.KEY_LAST_CHECKED, new Date());\n }\n }\n },\n\n setSelect : function(select, data) {\n select.options.length = data.length;\n\n for (var i = 0; i < data.length; i++) {\n // we are not using the javascript constructor to create an Option instance because this will create an\n // incompatibility with jQuery in Chrome which will make it impossible to add a new artist field on passtheheadphones.me\n var o = document.createElement(\"option\");\n if ('nameFormatted' in data[i]) {\n o.text = data[i]['nameFormatted'];\n } else {\n o.text = data[i]['name'];\n }\n o.value = data[i]['value'] || data[i]['id'];\n o.selected = data[i]['default'];\n select.options[i] = o;\n if (data[i]['default']) {\n select.selectedIndex = i;\n }\n if (data[i]['url']) {\n o.setAttribute('data-url', data[i]['url']);\n }\n }\n },\n\n setStyles : function() {\n // general styles\n yadg_util.addCSS('div#yadg_options{ display:none; margin-top:3px; } input#yadg_input,input#yadg_submit,label#yadg_format_label,a#yadg_scraper_info { margin-right: 5px } div#yadg_response { margin-top:3px; } select#yadg_scraper { margin-right: 2px } #yadg_options_template,#yadg_options_api_token,#yadg_options_replace_div { margin-bottom: 3px; } .add_form[name=\"yadg\"] input,.add_form[name=\"yadg\"] select { width: 90%; margin: 2px 0 !important; } div.box { border:none !important }');\n\n // location specific styles will go here\n switch(this.currentLocation) {\n case \"waffles_upload\":\n yadg_util.addCSS('div#yadg_response ul { margin-left: 0 !important; padding-left: 0 !important; }');\n break;\n\n case \"waffles_request\":\n yadg_util.addCSS('div#yadg_response ul { margin-left: 0 !important; padding-left: 0 !important; }');\n break;\n\n default:\n\n break;\n }\n },\n\n getInputElements : function() {\n var buttonHTML = '',\n scraperSelectHTML = '',\n optionsHTML = '
',\n inputHTML = '',\n responseDivHTML = '
',\n toggleOptionsLinkHTML = 'Toggle options',\n scraperInfoLink = '[?]';\n\n\n switch (this.currentLocation) {\n case \"pth_upload\":\n var tr = document.createElement('tr');\n tr.className = \"yadg_tr\";\n tr.innerHTML = 'YADG:' + inputHTML + scraperSelectHTML + scraperInfoLink + buttonHTML + toggleOptionsLinkHTML + optionsHTML + responseDivHTML + '';\n return tr;\n\n case \"pth_edit\":\n var div = document.createElement('div');\n div.className = \"yadg_div\";\n div.innerHTML = '

YADG:

\\n' + inputHTML + '\\n' + scraperSelectHTML + '\\n' + scraperInfoLink + '\\n' + buttonHTML + '\\n' + toggleOptionsLinkHTML + '\\n' + optionsHTML + '\\n' + responseDivHTML;\n return div;\n\n case \"pth_torrent_overview\":\n var div = document.createElement('div');\n div.id = 'yadg_div'\n div.className = 'box';\n div.innerHTML = '
YADG
\\n
\\n
\\n\\n' + scraperSelectHTML + '\\n' + scraperInfoLink + '\\n' + buttonHTML + '\\n' + toggleOptionsLinkHTML + '\\n' + optionsHTML + '\\n' + responseDivHTML;\n return div;\n\n case \"pth_request\":\n case \"pth_request_edit\":\n var tr = document.createElement('tr');\n tr.className = \"yadg_tr\";\n tr.innerHTML = 'YADG:' + inputHTML + scraperSelectHTML + scraperInfoLink + buttonHTML + toggleOptionsLinkHTML + optionsHTML + responseDivHTML + '';\n return tr;\n\n case \"waffles_upload\":\n var tr = document.createElement('tr');\n tr.className = \"yadg_tr\";\n tr.innerHTML = '' + inputHTML + scraperSelectHTML + scraperInfoLink + buttonHTML + toggleOptionsLinkHTML + optionsHTML + responseDivHTML + '';\n return tr;\n\n case \"waffles_upload_new\":\n var p = document.createElement('p');\n p.className = \"yadg_p\";\n p.innerHTML = '' + inputHTML + scraperSelectHTML + scraperInfoLink + buttonHTML + toggleOptionsLinkHTML + optionsHTML + responseDivHTML;\n return p;\n\n case \"waffles_request\":\n var tr = document.createElement('tr');\n tr.className = \"yadg_tr\";\n tr.innerHTML = 'YADG:' + inputHTML + scraperSelectHTML + scraperInfoLink + buttonHTML + toggleOptionsLinkHTML + optionsHTML + responseDivHTML + '';\n return tr;\n\n default:\n // that should actually never happen\n return document.createElement('div');\n }\n },\n\n insertIntoPage : function(element) {\n switch (this.currentLocation) {\n case \"pth_upload\":\n var year_tr = document.getElementById('year_tr');\n year_tr.parentNode.insertBefore(element,year_tr);\n break;\n\n case \"pth_edit\":\n var summary_input = document.getElementsByName('summary')[0];\n summary_input.parentNode.insertBefore(element,summary_input.nextSibling.nextSibling);\n break;\n\n case \"pth_torrent_overview\":\n var add_artists_box = document.getElementsByClassName(\"box_addartists\")[0];\n add_artists_box.appendChild(element);\n break;\n\n case \"pth_request\":\n case \"pth_request_edit\":\n var artist_tr = document.getElementById('artist_tr');\n artist_tr.parentNode.insertBefore(element,artist_tr);\n break;\n\n case \"waffles_upload\":\n var submit_button = document.getElementsByName('submit')[0];\n submit_button.parentNode.parentNode.parentNode.insertBefore(element,submit_button.parentNode.parentNode);\n break;\n\n case \"waffles_upload_new\":\n var h4s = document.getElementsByTagName('h4');\n var div;\n for (var i=0; i < h4s.length; i++) {\n if (h4s[i].innerHTML.indexOf('read the rules') !== -1) {\n div = h4s[i].parentNode;\n break;\n }\n }\n div.appendChild(element);\n break;\n\n case \"waffles_request\":\n var category_select = document.getElementsByName('category')[0];\n category_select.parentNode.parentNode.parentNode.insertBefore(element,category_select.parentNode.parentNode);\n break;\n\n default:\n break;\n }\n },\n\n getDescriptionBox : function() {\n switch (this.currentLocation) {\n case \"pth_upload\":\n return document.getElementById('album_desc');\n\n case \"pth_edit\":\n return document.getElementsByName('body')[0];\n\n case \"pth_torrent_overview\":\n if (!this.hasOwnProperty(\"dummybox\")) {\n this.dummybox = document.createElement('div');\n }\n return this.dummybox;\n\n case \"pth_request\":\n case \"pth_request_edit\":\n return document.getElementsByName('description')[0];\n\n case \"waffles_upload\":\n return document.getElementById('descr');\n\n case \"waffles_upload_new\":\n return document.getElementById('id_descr');\n\n case \"waffles_request\":\n return document.getElementsByName('information')[0];\n\n default:\n // that should actually never happen\n return document.createElement('div');\n }\n },\n\n getFormFillFunction : function() {\n switch (this.currentLocation) {\n case \"pth_upload\":\n var f = function(rawData) {\n var artist_inputs = document.getElementsByName(\"artists[]\"),\n album_title_input = document.getElementById(\"title\"),\n year_input = document.getElementById(\"year\"),\n label_input = document.getElementById(\"record_label\"),\n catalog_input = document.getElementById(\"catalogue_number\"),\n tags_input = document.getElementById(\"tags\"),\n data = yadg.prepareRawResponse(rawData);\n\n if (data.artists != false) {\n var input_idx = 0;\n\n yadg_util.addRemoveArtistBoxes(data.effective_artist_count - artist_inputs.length);\n\n artist_inputs = document.getElementsByName(\"artists[]\");\n\n for (var i = 0; i < data.artist_keys.length; i++) {\n var artist_key = data.artist_keys[i],\n artist_types = data.artists[artist_key];\n\n for (var j = 0; j < artist_types.length; j++) {\n var artist_type = artist_types[j],\n artist_input = artist_inputs[input_idx],\n type_select = artist_input.nextSibling;\n\n while (type_select.tagName != 'SELECT') {\n type_select = type_select.nextSibling;\n }\n\n artist_input.value = artist_key;\n\n var option_offsets = yadg_util.getOptionOffsets(type_select);\n\n if (artist_type === \"main\") {\n type_select.selectedIndex = option_offsets[1];\n } else if (artist_type === \"guest\") {\n type_select.selectedIndex = option_offsets[2];\n } else if (artist_type === \"remixer\") {\n type_select.selectedIndex = option_offsets[3];\n } else {\n // we don't know this artist type, default to \"main\"\n type_select.selectedIndex = option_offsets[1];\n }\n\n // next artist input\n input_idx += 1;\n }\n }\n } else {\n for (var i = 0; i < artist_inputs.length; i++) {\n artist_inputs[i].value = '';\n }\n }\n\n if (data.tags != false) {\n tags_input.value = data.tag_string.toLowerCase();\n } else {\n tags_input.value = '';\n }\n\n yadg_util.setValueIfSet(data.year,year_input,data.year != false);\n yadg_util.setValueIfSet(data.title,album_title_input,data.title != false);\n yadg_util.setValueIfSet(data.label,label_input,data.label != false);\n yadg_util.setValueIfSet(data.catalog,catalog_input,data.catalog != false);\n };\n return f;\n\n case \"pth_edit\":\n f = function(rawData) {\n var summary_input = document.getElementsByName(\"summary\")[0];\n var data = yadg.prepareRawResponse(rawData);\n\n summary_input.value = 'YADG Update';\n };\n return f;\n\n case \"pth_torrent_overview\":\n f = function(rawData) {\n var artist_inputs = document.getElementsByName(\"aliasname[]\"),\n data = yadg.prepareRawResponse(rawData);\n\n if (data.artists != false) {\n var input_idx = 0;\n\n yadg_util.addRemoveArtistBoxes(data.effective_artist_count - artist_inputs.length);\n\n artist_inputs = document.getElementsByName(\"aliasname[]\");\n\n for (var i = 0; i < data.artist_keys.length; i++) {\n var artist_key = data.artist_keys[i],\n artist_types = data.artists[artist_key];\n\n for (var j = 0; j < artist_types.length; j++) {\n var artist_type = artist_types[j],\n artist_input = artist_inputs[input_idx],\n type_select = artist_input.nextSibling;\n\n while (type_select.tagName != 'SELECT') {\n type_select = type_select.nextSibling;\n }\n\n artist_input.value = artist_key;\n\n var option_offsets = yadg_util.getOptionOffsets(type_select);\n\n if (artist_type === \"main\") {\n type_select.selectedIndex = option_offsets[1];\n } else if (artist_type === \"guest\") {\n type_select.selectedIndex = option_offsets[2];\n } else if (artist_type === \"remixer\") {\n type_select.selectedIndex = option_offsets[3];\n } else {\n // we don't know this artist type, default to \"main\"\n type_select.selectedIndex = option_offsets[1];\n }\n\n // next artist input\n input_idx += 1;\n }\n }\n } else {\n for (var i = 0; i < artist_inputs.length; i++) {\n artist_inputs[i].value = '';\n }\n }\n };\n return f;\n\n case \"pth_request\":\n case \"pth_request_edit\":\n var f = function(rawData) {\n var artist_inputs = document.getElementsByName(\"artists[]\"),\n album_title_input = document.getElementsByName(\"title\")[0],\n year_input = document.getElementsByName(\"year\")[0],\n label_input = document.getElementsByName(\"recordlabel\")[0],\n catalog_input = document.getElementsByName(\"cataloguenumber\")[0],\n tags_input = document.getElementById(\"tags\"),\n data = yadg.prepareRawResponse(rawData);\n\n if (data.artists != false) {\n var input_idx = 0;\n\n yadg_util.addRemoveArtistBoxes(data.effective_artist_count - artist_inputs.length);\n\n artist_inputs = document.getElementsByName(\"artists[]\");\n\n for (var i = 0; i < data.artist_keys.length; i++) {\n var artist_key = data.artist_keys[i],\n artist_types = data.artists[artist_key];\n\n for (var j = 0; j < artist_types.length; j++) {\n var artist_type = artist_types[j],\n artist_input = artist_inputs[input_idx],\n type_select = artist_input.nextSibling;\n\n while (type_select.tagName != 'SELECT') {\n type_select = type_select.nextSibling;\n }\n\n artist_input.value = artist_key;\n\n var option_offsets = yadg_util.getOptionOffsets(type_select);\n\n if (artist_type === \"main\") {\n type_select.selectedIndex = option_offsets[1];\n } else if (artist_type === \"guest\") {\n type_select.selectedIndex = option_offsets[2];\n } else if (artist_type === \"remixer\") {\n type_select.selectedIndex = option_offsets[3];\n } else {\n // we don't know this artist type, default to \"main\"\n type_select.selectedIndex = option_offsets[1];\n }\n\n // next artist input\n input_idx += 1;\n }\n }\n } else {\n for (var i = 0; i < artist_inputs.length; i++) {\n artist_inputs[i].value = '';\n }\n }\n\n if (data.tags != false) {\n tags_input.value = data.tag_string.toLowerCase();\n } else {\n tags_input.value = '';\n }\n\n yadg_util.setValueIfSet(data.year,year_input,data.year != false);\n yadg_util.setValueIfSet(data.title,album_title_input,data.title != false);\n yadg_util.setValueIfSet(data.label,label_input,data.label != false);\n yadg_util.setValueIfSet(data.catalog,catalog_input,data.catalog != false);\n };\n return f;\n\n case \"waffles_upload\":\n var f = function(rawData) {\n var artist_input = document.getElementsByName(\"artist\")[0],\n album_title_input = document.getElementsByName(\"album\")[0],\n year_input = document.getElementsByName(\"year\")[0],\n va_checkbox = document.getElementById(\"va\"),\n tags_input = document.getElementById(\"tags\"),\n data = yadg.prepareRawResponse(rawData);\n\n if (data.artists != false) {\n if (data.is_various) {\n artist_input.value = \"\";\n va_checkbox.checked = true;\n } else {\n artist_input.value = data.flat_artist_string;\n va_checkbox.checked = false;\n }\n } else {\n va_checkbox.checked = false;\n artist_input.value = \"\";\n }\n\n yadg_util.setValueIfSet(data.year,year_input,data.year != false);\n yadg_util.setValueIfSet(data.title,album_title_input,data.title != false);\n\n if (data.tags != false) {\n tags_input.value = data.tag_string_nodots.toLowerCase();\n } else {\n tags_input.value = '';\n }\n\n yadg_util.exec(function() {formatName()});\n };\n return f;\n\n case \"waffles_upload_new\":\n var f = function(rawData) {\n var artist_input = document.getElementById(\"id_artist\"),\n album_title_input = document.getElementById(\"id_album\"),\n year_input = document.getElementById(\"id_year\"),\n va_checkbox = document.getElementById(\"id_va\"),\n tags_input = document.getElementById(\"id_tags\"),\n data = yadg.prepareRawResponse(rawData);\n\n if (data.artists != false) {\n if (data.is_various) {\n if (!va_checkbox.checked) {\n va_checkbox.click();\n }\n } else {\n if (va_checkbox.checked) {\n va_checkbox.click();\n }\n artist_input.value = data.flat_artist_string;\n }\n } else {\n if (va_checkbox.checked) {\n va_checkbox.click();\n }\n artist_input.value = \"\";\n }\n\n yadg_util.setValueIfSet(data.year,year_input,data.year != false);\n yadg_util.setValueIfSet(data.title,album_title_input,data.title != false);\n\n if (data.tags != false) {\n tags_input.value = data.tag_string_nodots.toLowerCase();\n } else {\n tags_input.value = '';\n }\n };\n return f;\n\n case \"waffles_request\":\n var f = function(rawData) {\n var artist_input = document.getElementsByName(\"artist\")[0],\n album_title_input = document.getElementsByName(\"title\")[0],\n year_input = document.getElementsByName(\"year\")[0],\n data = yadg.prepareRawResponse(rawData);\n\n if (data.artists != false) {\n if (data.is_various) {\n artist_input.value = \"Various Artists\";\n } else {\n artist_input.value = data.flat_artist_string;\n }\n } else {\n artist_input.value = \"\";\n }\n\n yadg_util.setValueIfSet(data.year,year_input,data.year != false);\n yadg_util.setValueIfSet(data.title,album_title_input,data.title != false);\n };\n return f;\n\n default:\n // that should actually never happen\n return function(data) {};\n }\n }\n};\n\nvar yadg_templates = {\n _templates : {},\n _template_urls : {},\n\n getTemplate : function(id, callback) {\n if (id in this._templates) {\n callback(this._templates[id]);\n } else if (id in this._template_urls) {\n var request = new requester(this._template_urls[id], 'GET', function(template) {\n yadg_templates.addTemplate(template);\n callback(template);\n }, null, yadg_templates.errorTemplate);\n request.send();\n } else {\n this.errorTemplate();\n }\n },\n\n addTemplate : function(template) {\n this._templates[template.id] = template;\n },\n\n addTemplateUrl : function(id, url) {\n this._template_urls[id] = url;\n },\n\n errorTemplate : function() {\n yadg.printError(\"Could not get template. Please choose another one.\", true);\n }\n};\n\nvar yadg_renderer = {\n _last_data : null,\n _last_template_id : null,\n\n render : function(template_id, data, callback, error_callback) {\n this._last_data = data;\n var new_template = this._last_template_id !== template_id;\n this._last_template_id = template_id;\n\n yadg_templates.getTemplate(template_id, function(template) {\n // the new template might have different dependencies, so initialize Swig with those\n if (new_template) {\n yadg_sandbox.resetSandbox();\n yadg_sandbox.initializeSwig(template.dependencies);\n }\n yadg_sandbox.renderTemplate(template.code, data, callback, error_callback);\n });\n },\n\n renderCached : function(template_id, callback, error_callback) {\n if (this.hasCached()) {\n this.render(template_id, this._last_data, callback, error_callback);\n }\n },\n\n hasCached : function() {\n return this._last_data !== null;\n },\n\n clearCached : function() {\n this._last_data = null;\n }\n};\n\nvar yadg = {\n yadgHost : \"https://yadg.cc\",\n baseURI : \"/api/v2/\",\n\n standardError : \"Sorry, an error occured. Please try again. If this error persists the user script might need updating.\",\n authenticationError : \"Your API token is invalid. Please provide a valid API token or remove the current one.\",\n lastStateError : false,\n\n isBusy : false,\n\n init : function() {\n this.scraperSelect = document.getElementById('yadg_scraper');\n this.formatSelect = document.getElementById('yadg_format');\n this.input = document.getElementById('yadg_input');\n this.responseDiv = document.getElementById('yadg_response');\n this.button = document.getElementById('yadg_submit');\n },\n\n getBaseURL : function() {\n return this.yadgHost + this.baseURI;\n },\n\n getScraperList : function(callback) {\n var url = this.getBaseURL() + \"scrapers/\";\n\n var request = new requester(url, 'GET', callback);\n\n request.send();\n },\n\n getFormatsList : function(callback) {\n var url = this.getBaseURL() + \"templates/\";\n\n this.getTemplates(url, [], callback);\n },\n\n getTemplates : function(url, templates, callback) {\n var request = new requester(url, 'GET', function(data) {\n for (var i = 0; i < data.results.length; i++) {\n templates.push(data.results[i]);\n }\n if (data.next !== null) {\n yadg.getTemplates(data.next, templates, callback);\n } else {\n callback(templates);\n }\n });\n\n request.send();\n },\n\n makeRequest : function(params) {\n if (this.isBusy) return;\n\n var data;\n if (params) {\n data = params;\n } else {\n data = {\n scraper: this.scraperSelect.options[this.scraperSelect.selectedIndex].value,\n input: this.input.value\n };\n }\n var url = this.getBaseURL() + 'query/';\n\n if (data.input !== '') {\n var request = new requester(url, 'POST', function(result) {\n yadg.getResult(result.url);\n }, data);\n this.busyStart();\n request.send();\n }\n },\n\n getResult : function(result_url) {\n var request = new requester(result_url, 'GET', function(response) {\n if (response.status == \"done\") {\n if (response.data.type == 'ReleaseResult') {\n var template_id = yadg.formatSelect.options[yadg.formatSelect.selectedIndex].value;\n yadg_renderer.render(template_id, response, factory.setDescriptionBoxValue, factory.setDescriptionBoxValue);\n\n if (yadg.lastStateError == true) {\n yadg.responseDiv.innerHTML = \"\";\n yadg.lastStateError = false;\n }\n\n var fillFunc = factory.getFormFillFunction();\n fillFunc(response.data);\n } else if (response.data.type == 'ListResult') {\n var ul = document.createElement('ul');\n ul.id = \"yadg_release_list\";\n\n var release_list = response.data.items;\n for (var i = 0; i < release_list.length;i++) {\n var name = release_list[i]['name'],\n info = release_list[i]['info'],\n query_params = release_list[i]['queryParams'],\n release_url = release_list[i]['url'];\n\n var li = document.createElement('li'),\n a = document.createElement('a');\n\n a.textContent = name;\n a.params = query_params;\n a.href = release_url;\n\n a.addEventListener('click',function(e) { e.preventDefault(); yadg.makeRequest(this.params);},false);\n\n li.appendChild(a);\n li.appendChild(document.createElement('br'));\n li.appendChild(document.createTextNode(info));\n\n ul.appendChild(li);\n }\n\n if (ul.childNodes.length != 0) {\n yadg.responseDiv.innerHTML = \"\";\n yadg.responseDiv.appendChild(ul);\n yadg.lastStateError = false;\n\n // we got a ListResult so clear the last ReleaseResult from the render cache\n yadg_renderer.clearCached();\n } else {\n yadg.printError('Sorry, there were no matches.');\n }\n } else if (response.data.type == 'NotFoundResult') {\n yadg.printError('I could not find the release with the given ID. You may want to try again with another one.');\n } else {\n yadg.printError('Something weird happened. Please try again');\n }\n yadg.busyStop();\n } else if (response.status == 'failed') {\n yadg.failed_callback();\n } else {\n var delay = function() { yadg.getResult(response.url); };\n window.setTimeout(delay, 1000);\n }\n });\n request.send();\n },\n\n printError : function(message, template_error) {\n this.responseDiv.innerHTML = \"\";\n this.responseDiv.appendChild(document.createTextNode(message));\n if (!template_error) {\n this.lastStateError = true;\n\n // there was a non template related error, so for consistencies sake clear the last ReleaseResult from the\n // render cache\n yadg_renderer.clearCached();\n }\n },\n\n failed_callback : function() {\n yadg.printError(yadg.standardError);\n yadg.busyStop();\n },\n\n failed_authentication_callback : function() {\n yadg.printError(yadg.authenticationError);\n yadg.busyStop();\n },\n\n busyStart : function() {\n this.isBusy = true;\n this.button.setAttribute('disabled',true);\n this.button.value = \"Please wait...\";\n this.input.setAttribute('disabled',true);\n this.scraperSelect.setAttribute('disabled',true);\n this.formatSelect.setAttribute('disabled',true);\n },\n\n busyStop : function() {\n this.button.removeAttribute('disabled');\n this.button.value = \"Fetch\";\n this.input.removeAttribute('disabled');\n this.scraperSelect.removeAttribute('disabled');\n this.formatSelect.removeAttribute('disabled');\n this.isBusy = false;\n },\n\n prepareRawResponse : function(rawData) {\n var result = {};\n\n result.artists = false;\n result.year = false;\n result.title = false;\n result.label = false;\n result.catalog = false;\n result.genre = false;\n result.style = false;\n result.tags = false;\n result.is_various = false;\n result.flat_artist_string = false;\n\n if (rawData.artists.length > 0) {\n result.artists = {};\n\n for (var i = 0; i < rawData.artists.length; i++) {\n var artist = rawData.artists[i];\n if (!artist[\"isVarious\"]) {\n result.artists[artist[\"name\"]] = artist[\"types\"];\n } else {\n result.is_various = true;\n }\n }\n }\n if (rawData.discs.length > 0) {\n for (var k = 0; k < rawData.discs.length; k++) {\n var disc = rawData.discs[k];\n for (var l = 0; l < disc[\"tracks\"].length; l++) {\n var track = disc[\"tracks\"][l];\n for (var m = 0; m < track[\"artists\"].length; m++) {\n var name = track[\"artists\"][m][\"name\"],\n type = track[\"artists\"][m][\"types\"];\n\n var newTypes = null;\n if (name in result.artists) {\n newTypes = result.artists[name].concat(type);\n // deduplicate new types array\n for(var i = 0; i < newTypes.length; ++i) {\n for(var j = i+1; j < newTypes.length; ++j) {\n if(newTypes[i] === newTypes[j])\n newTypes.splice(j--, 1);\n }\n }\n } else {\n newTypes = type;\n }\n\n result.artists[name] = newTypes;\n }\n }\n }\n }\n for (var i = 0; i < rawData['releaseEvents'].length; i++) {\n var event = rawData['releaseEvents'][i];\n if (event.date) {\n result.year = event.date.match(/\\d{4}/)[0];\n if (result.year.length != 4) {\n result.year = false;\n } else {\n break;\n }\n }\n }\n if (rawData.title) {\n result.title = rawData.title;\n }\n if (rawData.labelIds.length > 0) {\n var labelId = rawData['labelIds'][0];\n if (labelId.label) {\n result.label = labelId.label;\n }\n if (labelId.catalogueNrs.length > 0) {\n result.catalog = labelId.catalogueNrs[0];\n }\n }\n if (rawData.genres.length > 0) {\n result.genre = rawData.genres;\n }\n if (rawData.styles.length > 0) {\n result.style = rawData.styles;\n }\n if (result.genre != false && result.style != false) {\n result.tags = rawData.genres.concat(rawData.styles);\n } else if (result.genre != false) {\n result.tags = rawData.genres;\n } else if (result.style != false) {\n result.tags = rawData.styles;\n }\n\n if (result.tags != false) {\n result.tag_string = \"\";\n result.tag_string_nodots = \"\";\n\n for (var i = 0; i < result.tags.length; i++) {\n result.tag_string = result.tag_string + result.tags[i].replace(/\\s+/g,'.');\n result.tag_string_nodots = result.tag_string_nodots + result.tags[i].replace(/\\s+/g,' ');\n if (i != result.tags.length-1) {\n result.tag_string = result.tag_string + ', ';\n result.tag_string_nodots = result.tag_string_nodots + ', ';\n }\n }\n }\n\n if (result.artists != false) {\n // count the artists\n result.artists_length = 0;\n result.artist_keys = [];\n result.effective_artist_count = 0;\n\n for (var i in result.artists) {\n if (result.artists.hasOwnProperty(i)) {\n result.artists_length++;\n result.artist_keys.push(i);\n result.effective_artist_count += result.artists[i].length;\n }\n }\n }\n\n if (result.artists_length == 0) {\n result.artists = false;\n } else {\n // create a flat string of all the main artists\n var artist_string = \"\";\n\n for (var i = 0; i < result.artists_length; i++) {\n if (result.artists[result.artist_keys[i]].indexOf(\"main\") != -1) {\n if (artist_string != \"\" && i < result.artists_length - 2) {\n artist_string = artist_string + \", \";\n } else if (artist_string != \"\" && i < result.artists_length - 1) {\n artist_string = artist_string + \" & \";\n }\n artist_string = artist_string + result.artist_keys[i];\n }\n }\n\n result.flat_artist_string = artist_string;\n }\n\n return result;\n }\n};\n\nyadg_sandbox.init(function() {\n if (factory.init()) { // returns true if we run on a valid location\n yadg.init();\n }\n});\n"},"new_file":{"kind":"string","value":"pth_yadg.user.js"},"old_contents":{"kind":"string","value":"// ==UserScript==\n// @id pth-yadg\n// @name passtheheadphones.me - YADG\n// @description This script provides integration with online description generator YADG (http://yadg.cc) - Credit to Slack06\n// @license https://github.com/SavageCore/yadg-pth-userscript/blob/master/LICENSE\n// @version 1.3.10\n// @namespace yadg\n// @grant GM_xmlhttpRequest\n// @require https://yadg.cc/static/js/jsandbox.min.js\n// @include http*://*passtheheadphones.me/upload.php*\n// @include http*://*passtheheadphones.me/requests.php*\n// @include http*://*passtheheadphones.me/torrents.php*\n// @include http*://*waffles.ch/upload.php*\n// @include http*://*waffles.ch/requests.php*\n// @downloadURL https://github.com/SavageCore/yadg-pth-userscript/raw/master/pth_yadg.user.js\n// ==/UserScript==\n\n// --------- USER SETTINGS START ---------\n\n/*\n Here you can set site specific default templates.\n You can find a list of available templates at: https://yadg.cc/api/v2/templates/\n*/\nvar defaultPTHFormat = 5,\n defaultWafflesFormat = 9;\n\n// --------- USER SETTINGS END ---------\n\n\n\n// --------- THIRD PARTY CODE AREA START ---------\n\n//\n// Creates an object which gives some helper methods to\n// Save/Load/Remove data to/from the localStorage\n//\n// Source from: https://github.com/gergob/localstoragewrapper\n//\nfunction LocalStorageWrapper (applicationPrefix) {\n \"use strict\";\n\n if(applicationPrefix == undefined) {\n throw new Error('applicationPrefix parameter should be defined');\n }\n\n var delimiter = '_';\n\n //if the passed in value for prefix is not string, it should be converted\n var keyPrefix = typeof(applicationPrefix) === 'string' ? applicationPrefix : JSON.stringify(applicationPrefix);\n\n var localStorage = window.localStorage||unsafeWindow.localStorage;\n\n var isLocalStorageAvailable = function() {\n return typeof(localStorage) != undefined\n };\n\n var getKeyPrefix = function() {\n return keyPrefix;\n };\n\n //\n // validates if there is a prefix defined for the keys\n // and checks if the localStorage functionality is available or not\n //\n var makeChecks = function(key) {\n var prefix = getKeyPrefix();\n if(prefix == undefined) {\n throw new Error('No prefix was defined, data cannot be saved');\n }\n\n if(!isLocalStorageAvailable()) {\n throw new Error('LocalStorage is not supported by your browser, data cannot be saved');\n }\n\n //keys are always strings\n var checkedKey = typeof(key) === 'string' ? key : JSON.stringify(key);\n\n return checkedKey;\n };\n\n //\n // saves the value associated to the key into the localStorage\n //\n var addItem = function(key, value) {\n var that = this;\n try{\n var checkedKey = makeChecks(key);\n var combinedKey = that.getKeyPrefix() + delimiter + checkedKey;\n localStorage.setItem(combinedKey, JSON.stringify(value));\n }\n catch(error) {\n console.log(error);\n throw error;\n }\n };\n\n //\n // gets the value of the object saved to the key passed as parameter\n //\n var getItem = function(key) {\n var that = this;\n var result = undefined;\n try{\n var checkedKey = makeChecks(key);\n var combinedKey = that.getKeyPrefix() + delimiter + checkedKey;\n var resultAsJSON = localStorage.getItem(combinedKey);\n result = JSON.parse(resultAsJSON);\n }\n catch(error) {\n console.log(error);\n throw error;\n }\n return result;\n };\n\n //\n // returns all the keys from the localStorage\n //\n var getAllKeys = function() {\n var prefix = getKeyPrefix();\n var results = [];\n\n if(prefix == undefined) {\n throw new Error('No prefix was defined, data cannot be saved');\n }\n\n if(!isLocalStorageAvailable()) {\n throw new Error('LocalStorage is not supported by your browser, data cannot be saved');\n }\n\n for(var key in localStorage) {\n if(key.indexOf(prefix) == 0) {\n var keyParts = key.split(delimiter);\n results.push(keyParts[1]);\n }\n }\n\n return results;\n };\n\n //\n // removes the value associated to the key from the localStorage\n //\n var removeItem = function(key) {\n var that = this;\n var result = false;\n try{\n var checkedKey = makeChecks(key);\n var combinedKey = that.getKeyPrefix() + delimiter + checkedKey;\n localStorage.removeItem(combinedKey);\n result = true;\n }\n catch(error) {\n console.log(error);\n throw error;\n }\n return result;\n };\n\n //\n // removes all the values from the localStorage\n //\n var removeAll = function() {\n var that = this;\n\n try{\n var allKeys = that.getAllKeys();\n for(var i=0; i < allKeys.length; ++i) {\n var checkedKey = makeChecks(allKeys[i]);\n var combinedKey = that.getKeyPrefix() + delimiter + checkedKey;\n localStorage.removeItem(combinedKey);\n }\n }\n catch(error) {\n console.log(error);\n throw error;\n }\n };\n\n // make some of the functionalities public\n return {\n isLocalStorageAvailable : isLocalStorageAvailable,\n getKeyPrefix : getKeyPrefix,\n addItem : addItem,\n getItem : getItem,\n getAllKeys : getAllKeys,\n removeItem : removeItem,\n removeAll : removeAll\n }\n}\n\n// --------- THIRD PARTY CODE AREA END ---------\n\nvar yadg_util = {\n exec : function exec(fn) {\n var script = document.createElement('script');\n script.setAttribute(\"type\", \"application/javascript\");\n script.textContent = '(' + fn + ')();';\n document.body.appendChild(script); // run the script\n document.body.removeChild(script); // clean up\n },\n\n // handle for updating page css, taken from one of hateradio's scripts\n addCSS : function(style) {\n if(!this.style) {\n this.style = document.createElement('style');\n this.style.type = 'text/css';\n (document.head || document.getElementsByTagName('head')[0]).appendChild(this.style);\n }\n this.style.appendChild(document.createTextNode(style+'\\n'));\n },\n\n setValueIfSet: function(value,input,cond) {\n if (cond) {\n input.value = value;\n } else {\n input.value = '';\n }\n },\n\n // negative count will remove, positive count will add given number of artist boxes\n addRemoveArtistBoxes : function(count) {\n if (count != 0) {\n if (count < 0) {\n for (var i = 0; i < -count; i++) {\n yadg_util.exec(function() {RemoveArtistField()});\n }\n } else {\n for (var i = 0; i < count; i++) {\n yadg_util.exec(function() {AddArtistField()});\n }\n }\n }\n },\n\n getOptionOffsets : function(select) {\n var option_offsets = {};\n for (var j = 0; j < select.options.length; j++) {\n option_offsets[select.options[j].value] = select.options[j].index;\n }\n return option_offsets;\n },\n\n storage : new LocalStorageWrapper(\"yadg\"),\n\n settings : new LocalStorageWrapper(\"yadgSettings\")\n};\n\n// very simple wrapper for XmlHttpRequest\nfunction requester(url, method, callback, data, error_callback) {\n this.data = data;\n this.url = url;\n this.method = method;\n if (!error_callback) {\n error_callback = yadg.failed_callback;\n }\n\n this.send = function() {\n var details = {\n url : this.url,\n method : this.method,\n onload : function(response) {\n if (response.status === 200) {\n callback(JSON.parse(response.responseText));\n } else if (response.status === 401) {\n yadg.failed_authentication_callback();\n } else {\n error_callback();\n }\n },\n onerror : error_callback\n };\n if (method == \"POST\") {\n details.data = JSON.stringify(this.data);\n }\n\n var headers = {\n \"Accept\" : \"application/json\",\n \"Content-Type\" : \"application/json\"\n };\n\n if (yadg_util.settings.getItem(factory.KEY_API_TOKEN)) {\n headers.Authorization = \"Token \" + yadg_util.settings.getItem(factory.KEY_API_TOKEN);\n }\n\n details.headers = headers;\n\n GM_xmlhttpRequest(details);\n };\n}\n\nvar yadg_sandbox = {\n\n KEY_LAST_WARNING : \"templateLastWarning\",\n\n init : function(callback) {\n GM_xmlhttpRequest({\n method: 'GET',\n url: yadg.yadgHost + '/static/js/jsandbox-worker.js',\n onload: function(response) {\n var script, dataURL = null;\n if (response.status === 200) {\n script = response.responseText;\n var blob = new Blob([script], {type: 'application/javascript'});\n var URL = window.URL || window.webkitURL;\n if (!URL || !URL.createObjectURL) {\n throw new Error('No no valid implementation of window.URL.createObjectURL found.');\n }\n dataURL = URL.createObjectURL(blob);\n yadg_sandbox.initCallback(dataURL);\n yadg_sandbox.loadSwig(callback);\n } else {\n yadg_sandbox.initCallbackError();\n }\n },\n onerror: function() {\n yadg_sandbox.initCallbackError();\n }\n });\n\n },\n\n loadSwig : function(callback) {\n // importScripts for the web worker will not work in Firefox with cross-domain requests\n // see: https://bugzilla.mozilla.org/show_bug.cgi?id=756589\n // so download the Swig files manually with GM_xmlhttpRequest\n GM_xmlhttpRequest({\n method: 'GET',\n url: yadg.yadgHost + \"/static/js/swig.min.js\",\n onload: function(response) {\n if (response.status === 200) {\n yadg_sandbox.swig_script = response.responseText;\n\n GM_xmlhttpRequest({\n method: 'GET',\n url: yadg.yadgHost + \"/static/js/swig.custom.js\",\n onload: function(response) {\n if (response.status === 200) {\n yadg_sandbox.swig_custom_script = response.responseText;\n callback();\n }\n }\n });\n }\n }\n });\n },\n\n initializeSwig : function(dependencies) {\n if (!(this.swig_script && this.swig_custom_script)) {\n yadg.failed_callback();\n return\n }\n\n yadg_sandbox.exec({data: this.swig_script, onerror: yadg.failed_callback});\n yadg_sandbox.exec({data: this.swig_custom_script, onerror: yadg.failed_callback});\n yadg_sandbox.exec({data: \"var myswig = new swig.Swig({ loader: swig.loaders.memory(input.templates), autoescape: false }), i=0; yadg_filters.register_filters(myswig);\", input: {templates: dependencies}});\n },\n\n renderTemplate : function(template, data, callback, error) {\n var eval_string = \"myswig.render(input.template, { locals: input.data, filename: 'scratchpad' + (i++) })\";\n this.eval({data: eval_string, callback: function(out) {callback(out);}, input: {template: template, data: data}, onerror: function(err){error(err);}});\n },\n\n initCallback : function(dataUrl) {\n JSandbox.url = dataUrl;\n this.jsandbox = new JSandbox();\n this.initError = false;\n },\n\n resetSandbox : function() {\n this.jsandbox.terminate();\n this.jsandbox = new JSandbox();\n },\n\n load : function(options) {\n this.jsandbox.load(options);\n },\n\n exec : function(options) {\n this.jsandbox.exec(options);\n },\n\n eval : function(options) {\n this.jsandbox.eval(options);\n },\n\n initCallbackError : function() {\n this.initError = true;\n\n var last_warning = yadg_util.storage.getItem(this.KEY_LAST_WARNING),\n now = new Date();\n if (last_warning === null || now.getTime() - (new Date(last_warning)).getTime() > factory.CACHE_TIMEOUT) {\n alert(\"Could not load the necessary script files for executing YADG. If this error persists you might need to update the user script. You will only get this message once a day.\");\n yadg_util.storage.addItem(this.KEY_LAST_WARNING, now);\n }\n }\n};\n\nvar factory = {\n // storage keys for cache\n KEY_LAST_CHECKED : \"lastChecked\",\n KEY_SCRAPER_LIST : \"scraperList\",\n KEY_FORMAT_LIST : \"formatList\",\n\n // storage keys for settings\n KEY_API_TOKEN : \"apiToken\",\n KEY_DEFAULT_TEMPLATE : \"defaultTemplate\",\n KEY_DEFAULT_SCRAPER : \"defaultScraper\",\n KEY_REPLACE_DESCRIPTION : \"replaceDescriptionOn\",\n KEY_SETTINGS_INIT_VER : \"settingsInitializedVer\",\n\n CACHE_TIMEOUT : 1000*60*60*24, // 24 hours\n\n UPDATE_PROGRESS : 0,\n\n locations : new Array(\n {\n name : 'pth_upload',\n regex : /http(s)?\\:\\/\\/(.*\\.)?passtheheadphones\\.me\\/upload\\.php.*/i\n },\n {\n name : 'pth_edit',\n regex : /http(s)?\\:\\/\\/(.*\\.)?passtheheadphones\\.me\\/torrents\\.php\\?action=editgroup&groupid=.*/i\n },\n {\n name : 'pth_request',\n regex : /http(s)?\\:\\/\\/(.*\\.)?passtheheadphones\\.me\\/requests\\.php\\?action=new/i\n },\n {\n name : 'pth_request_edit',\n regex : /http(s)?\\:\\/\\/(.*\\.)?passtheheadphones\\.me\\/requests\\.php\\?action=edit&id=.*/i\n },\n {\n name : 'pth_torrent_overview',\n regex : /http(s)?\\:\\/\\/(.*\\.)?passtheheadphones\\.me\\/torrents\\.php\\?id=.*/i\n },\n {\n name : 'waffles_upload',\n// regex : /http(s)?\\:\\/\\/(.*\\.)?waffles\\.ch\\/upload\\.php\\?legacy=1.*/i\n// },\n// {\n// TODO: reenable support for the new Waffles upload page once it is reactivated\n// name : 'waffles_upload_new',\n regex : /http(s)?\\:\\/\\/(.*\\.)?waffles\\.ch\\/upload\\.php.*/i\n },\n {\n name : 'waffles_request',\n regex : /http(s)?\\:\\/\\/(.*\\.)?waffles\\.ch\\/requests\\.php\\?do=add/i\n }\n ),\n\n determineLocation : function(uri) {\n for (var i = 0; i < this.locations.length; i++) {\n if (this.locations[i].regex.test(uri)) {\n return this.locations[i].name;\n }\n }\n return null;\n },\n\n init : function() {\n this.currentLocation = this.determineLocation(document.URL);\n // only continue with the initialization if we found a valid location\n if (this.currentLocation !== null) {\n this.insertIntoPage(this.getInputElements());\n\n // set the necessary styles\n this.setStyles();\n\n // make sure we initialize the settings to the most recent version\n this.initializeSettings();\n\n // populate settings inputs\n this.populateSettings();\n\n // add the appropriate action for the button\n var button = document.getElementById('yadg_submit');\n button.addEventListener('click', function (e) {\n e.preventDefault();\n yadg.makeRequest();\n }, false);\n\n // add the action for the options toggle\n var toggleLink = document.getElementById('yadg_toggle_options');\n if (toggleLink !== null) {\n toggleLink.addEventListener('click', function (e) {\n e.preventDefault();\n\n var optionsDiv = document.getElementById('yadg_options'),\n display = optionsDiv.style.display;\n\n if (display == 'none' || display == '') {\n optionsDiv.style.display = 'block';\n } else {\n optionsDiv.style.display = 'none';\n }\n });\n }\n\n // add the action for the template select\n var formatSelect = this.getFormatSelect();\n if (formatSelect !== null) {\n formatSelect.addEventListener('change', function (e) {\n if (yadg_renderer.hasCached()) {\n yadg_renderer.renderCached(this.value, factory.setDescriptionBoxValue, factory.setDescriptionBoxValue);\n }\n });\n }\n\n // add the action to the save settings link\n var saveSettingsLink = document.getElementById('yadg_save_settings');\n if (saveSettingsLink !== null) {\n saveSettingsLink.addEventListener('click', function (e) {\n e.preventDefault();\n\n factory.saveSettings();\n\n alert(\"Settings saved successfully.\");\n });\n }\n\n // add the action to the clear cache link\n var clearCacheLink = document.getElementById('yadg_clear_cache');\n if (clearCacheLink !== null) {\n clearCacheLink.addEventListener('click', function (e) {\n e.preventDefault();\n\n yadg_util.storage.removeAll();\n\n alert(\"Cache cleared. Please reload the page for this to take effect.\");\n });\n }\n\n var last_checked = yadg_util.storage.getItem(factory.KEY_LAST_CHECKED);\n if (last_checked === null || (new Date()).getTime() - (new Date(last_checked)).getTime() > factory.CACHE_TIMEOUT) {\n // update the scraper and formats list\n factory.UPDATE_PROGRESS = 1;\n yadg.getScraperList(factory.setScraperSelect);\n yadg.getFormatsList(factory.setFormatSelect);\n } else {\n factory.setScraperSelect(yadg_util.storage.getItem(factory.KEY_SCRAPER_LIST));\n factory.setFormatSelect(yadg_util.storage.getItem(factory.KEY_FORMAT_LIST));\n }\n\n return true;\n } else {\n return false;\n }\n },\n\n getApiTokenInput : function() {\n return document.getElementById('yadg_api_token');\n },\n\n getReplaceDescriptionCheckbox : function() {\n return document.getElementById('yadg_options_replace');\n },\n\n getReplaceDescriptionSettingKey : function() {\n return this.makeReplaceDescriptionSettingsKey(this.currentLocation);\n },\n\n makeReplaceDescriptionSettingsKey : function(subKey) {\n return this.KEY_REPLACE_DESCRIPTION + subKey.replace(/_/g, \"\");\n },\n\n initializeSettings : function() {\n var settings_ver = yadg_util.settings.getItem(factory.KEY_SETTINGS_INIT_VER),\n current_ver = 1;\n\n if (!settings_ver) {\n settings_ver = 0;\n }\n\n if (settings_ver < current_ver) {\n // replace descriptions on upload and new request pages\n var locations = [\n 'pth_upload',\n 'pth_request',\n 'waffles_upload',\n 'waffles_upload_new',\n 'waffles_request'\n ];\n for (var i = 0; i < locations.length; i++) {\n var loc = locations[i],\n replace_desc_setting_key = factory.makeReplaceDescriptionSettingsKey(loc);\n\n yadg_util.settings.addItem(replace_desc_setting_key, true);\n }\n }\n\n yadg_util.settings.addItem(factory.KEY_SETTINGS_INIT_VER, current_ver);\n },\n\n populateSettings : function() {\n var api_token = yadg_util.settings.getItem(factory.KEY_API_TOKEN),\n replace_desc = yadg_util.settings.getItem(factory.getReplaceDescriptionSettingKey());\n\n if (api_token) {\n var api_token_input = factory.getApiTokenInput();\n api_token_input.value = api_token;\n }\n\n if (replace_desc) {\n var replace_desc_checkbox = factory.getReplaceDescriptionCheckbox();\n replace_desc_checkbox.checked = true;\n }\n },\n\n saveSettings : function() {\n var scraper_select = factory.getScraperSelect(),\n template_select = factory.getFormatSelect(),\n api_token_input = factory.getApiTokenInput(),\n replace_desc_checkbox = factory.getReplaceDescriptionCheckbox();\n\n var current_scraper = null,\n current_template = null,\n api_token = api_token_input.value.trim(),\n replace_description = replace_desc_checkbox.checked;\n\n if (scraper_select.options.length > 0) {\n current_scraper = scraper_select.options[scraper_select.selectedIndex].value;\n }\n\n if (template_select.options.length > 0) {\n current_template = template_select.options[template_select.selectedIndex].value;\n }\n\n if (current_scraper !== null) {\n yadg_util.settings.addItem(factory.KEY_DEFAULT_SCRAPER, current_scraper);\n }\n\n if (current_template !== null) {\n yadg_util.settings.addItem(factory.KEY_DEFAULT_TEMPLATE, current_template);\n }\n\n if (api_token !== \"\") {\n yadg_util.settings.addItem(factory.KEY_API_TOKEN, api_token);\n } else {\n yadg_util.settings.removeItem(factory.KEY_API_TOKEN);\n }\n\n var replace_desc_setting_key = factory.getReplaceDescriptionSettingKey();\n if (replace_description) {\n yadg_util.settings.addItem(replace_desc_setting_key, true);\n } else {\n yadg_util.settings.removeItem(replace_desc_setting_key);\n }\n },\n\n setDescriptionBoxValue : function(value) {\n var desc_box = factory.getDescriptionBox(),\n replace_desc_checkbox = factory.getReplaceDescriptionCheckbox(),\n replace_desc = false;\n\n if (replace_desc_checkbox !== null) {\n replace_desc = replace_desc_checkbox.checked;\n }\n\n if (desc_box !== null) {\n if (!replace_desc && /\\S/.test(desc_box.value)) { // check if the current description contains more than whitespace\n desc_box.value += \"\\n\\n\" + value;\n } else {\n desc_box.value = value;\n }\n }\n },\n\n getFormatSelect : function() {\n return document.getElementById('yadg_format');\n },\n\n setDefaultFormat : function() {\n var format_select = factory.getFormatSelect();\n var format_offsets = yadg_util.getOptionOffsets(format_select);\n\n var default_format = yadg_util.settings.getItem(factory.KEY_DEFAULT_TEMPLATE);\n if (default_format !== null && default_format in format_offsets) {\n format_select.selectedIndex = format_offsets[default_format];\n } else {\n // we have no settings so fall back to the hard coded defaults\n switch (this.currentLocation) {\n case \"waffles_upload\":\n case \"waffles_upload_new\":\n case \"waffles_request\":\n format_select.selectedIndex = format_offsets[defaultWafflesFormat];\n break;\n\n default:\n format_select.selectedIndex = format_offsets[defaultPTHFormat];\n break;\n }\n }\n },\n\n getScraperSelect : function() {\n return document.getElementById(\"yadg_scraper\");\n },\n\n setDefaultScraper : function() {\n var default_scraper = yadg_util.settings.getItem(factory.KEY_DEFAULT_SCRAPER);\n if (default_scraper !== null) {\n var scraper_select = factory.getScraperSelect();\n var scraper_offsets = yadg_util.getOptionOffsets(scraper_select);\n\n if (default_scraper in scraper_offsets) {\n scraper_select.selectedIndex = scraper_offsets[default_scraper];\n }\n }\n },\n\n setScraperSelect : function(scrapers) {\n var scraper_select = factory.getScraperSelect();\n\n factory.setSelect(scraper_select, scrapers);\n factory.setDefaultScraper();\n\n if (factory.UPDATE_PROGRESS > 0) {\n yadg_util.storage.addItem(factory.KEY_SCRAPER_LIST, scrapers);\n factory.UPDATE_PROGRESS |= 1<<1;\n\n if (factory.UPDATE_PROGRESS === 7) {\n yadg_util.storage.addItem(factory.KEY_LAST_CHECKED, new Date());\n }\n }\n },\n\n setFormatSelect : function(templates) {\n var format_select = factory.getFormatSelect();\n\n var non_utility = [];\n var save_templates = [];\n for (var i = 0; i < templates.length; i++) {\n if (factory.UPDATE_PROGRESS > 0) {\n yadg_templates.addTemplate(templates[i]);\n\n save_templates.push({\n id : templates[i]['id'],\n url : templates[i]['url'],\n name : templates[i]['name'],\n nameFormatted : templates[i]['nameFormatted'],\n owner : templates[i]['owner'],\n default : templates[i]['default'],\n isUtility : templates[i]['isUtility']\n });\n } else {\n yadg_templates.addTemplateUrl(templates[i]['id'], templates[i]['url']);\n }\n\n if (!templates[i]['isUtility']) {\n non_utility.push(templates[i]);\n }\n }\n\n factory.setSelect(format_select, non_utility);\n factory.setDefaultFormat();\n\n if (factory.UPDATE_PROGRESS > 0) {\n yadg_util.storage.addItem(factory.KEY_FORMAT_LIST, save_templates);\n factory.UPDATE_PROGRESS |= 1<<2;\n\n if (factory.UPDATE_PROGRESS === 7) {\n yadg_util.storage.addItem(factory.KEY_LAST_CHECKED, new Date());\n }\n }\n },\n\n setSelect : function(select, data) {\n select.options.length = data.length;\n\n for (var i = 0; i < data.length; i++) {\n // we are not using the javascript constructor to create an Option instance because this will create an\n // incompatibility with jQuery in Chrome which will make it impossible to add a new artist field on passtheheadphones.me\n var o = document.createElement(\"option\");\n if ('nameFormatted' in data[i]) {\n o.text = data[i]['nameFormatted'];\n } else {\n o.text = data[i]['name'];\n }\n o.value = data[i]['value'] || data[i]['id'];\n o.selected = data[i]['default'];\n select.options[i] = o;\n if (data[i]['default']) {\n select.selectedIndex = i;\n }\n if (data[i]['url']) {\n o.setAttribute('data-url', data[i]['url']);\n }\n }\n },\n\n setStyles : function() {\n // general styles\n yadg_util.addCSS('div#yadg_options{ display:none; margin-top:3px; } input#yadg_input,input#yadg_submit,label#yadg_format_label,a#yadg_scraper_info { margin-right: 5px } div#yadg_response { margin-top:3px; } select#yadg_scraper { margin-right: 2px } #yadg_options_template,#yadg_options_api_token,#yadg_options_replace_div { margin-bottom: 3px; } .add_form[name=\"yadg\"] input,.add_form[name=\"yadg\"] select { width: 90%; margin: 2px 0 !important; } div.box { border:none !important }');\n\n // location specific styles will go here\n switch(this.currentLocation) {\n case \"waffles_upload\":\n yadg_util.addCSS('div#yadg_response ul { margin-left: 0 !important; padding-left: 0 !important; }');\n break;\n\n case \"waffles_request\":\n yadg_util.addCSS('div#yadg_response ul { margin-left: 0 !important; padding-left: 0 !important; }');\n break;\n\n default:\n\n break;\n }\n },\n\n getInputElements : function() {\n var buttonHTML = '',\n scraperSelectHTML = '',\n optionsHTML = '
',\n inputHTML = '',\n responseDivHTML = '
',\n toggleOptionsLinkHTML = 'Toggle options',\n scraperInfoLink = '[?]';\n\n\n switch (this.currentLocation) {\n case \"pth_upload\":\n var tr = document.createElement('tr');\n tr.className = \"yadg_tr\";\n tr.innerHTML = 'YADG:' + inputHTML + scraperSelectHTML + scraperInfoLink + buttonHTML + toggleOptionsLinkHTML + optionsHTML + responseDivHTML + '';\n return tr;\n\n case \"pth_edit\":\n var div = document.createElement('div');\n div.className = \"yadg_div\";\n div.innerHTML = '

YADG:

\\n' + inputHTML + '\\n' + scraperSelectHTML + '\\n' + scraperInfoLink + '\\n' + buttonHTML + '\\n' + toggleOptionsLinkHTML + '\\n' + optionsHTML + '\\n' + responseDivHTML;\n return div;\n\n case \"pth_torrent_overview\":\n var div = document.createElement('div');\n div.id = 'yadg_div'\n div.className = 'box';\n div.innerHTML = '
YADG
\\n
\\n\\n\\n' + scraperSelectHTML + '\\n' + scraperInfoLink + '\\n' + buttonHTML + '\\n' + toggleOptionsLinkHTML + '\\n' + optionsHTML + '\\n' + responseDivHTML;\n return div;\n\n case \"pth_request\":\n case \"pth_request_edit\":\n var tr = document.createElement('tr');\n tr.className = \"yadg_tr\";\n tr.innerHTML = 'YADG:' + inputHTML + scraperSelectHTML + scraperInfoLink + buttonHTML + toggleOptionsLinkHTML + optionsHTML + responseDivHTML + '';\n return tr;\n\n case \"waffles_upload\":\n var tr = document.createElement('tr');\n tr.className = \"yadg_tr\";\n tr.innerHTML = '' + inputHTML + scraperSelectHTML + scraperInfoLink + buttonHTML + toggleOptionsLinkHTML + optionsHTML + responseDivHTML + '';\n return tr;\n\n case \"waffles_upload_new\":\n var p = document.createElement('p');\n p.className = \"yadg_p\";\n p.innerHTML = '' + inputHTML + scraperSelectHTML + scraperInfoLink + buttonHTML + toggleOptionsLinkHTML + optionsHTML + responseDivHTML;\n return p;\n\n case \"waffles_request\":\n var tr = document.createElement('tr');\n tr.className = \"yadg_tr\";\n tr.innerHTML = 'YADG:' + inputHTML + scraperSelectHTML + scraperInfoLink + buttonHTML + toggleOptionsLinkHTML + optionsHTML + responseDivHTML + '';\n return tr;\n\n default:\n // that should actually never happen\n return document.createElement('div');\n }\n },\n\n insertIntoPage : function(element) {\n switch (this.currentLocation) {\n case \"pth_upload\":\n var year_tr = document.getElementById('year_tr');\n year_tr.parentNode.insertBefore(element,year_tr);\n break;\n\n case \"pth_edit\":\n var summary_input = document.getElementsByName('summary')[0];\n summary_input.parentNode.insertBefore(element,summary_input.nextSibling.nextSibling);\n break;\n\n case \"pth_torrent_overview\":\n var add_artists_box = document.getElementsByClassName(\"box_addartists\")[0];\n add_artists_box.appendChild(element);\n break;\n\n case \"pth_request\":\n case \"pth_request_edit\":\n var artist_tr = document.getElementById('artist_tr');\n artist_tr.parentNode.insertBefore(element,artist_tr);\n break;\n\n case \"waffles_upload\":\n var submit_button = document.getElementsByName('submit')[0];\n submit_button.parentNode.parentNode.parentNode.insertBefore(element,submit_button.parentNode.parentNode);\n break;\n\n case \"waffles_upload_new\":\n var h4s = document.getElementsByTagName('h4');\n var div;\n for (var i=0; i < h4s.length; i++) {\n if (h4s[i].innerHTML.indexOf('read the rules') !== -1) {\n div = h4s[i].parentNode;\n break;\n }\n }\n div.appendChild(element);\n break;\n\n case \"waffles_request\":\n var category_select = document.getElementsByName('category')[0];\n category_select.parentNode.parentNode.parentNode.insertBefore(element,category_select.parentNode.parentNode);\n break;\n\n default:\n break;\n }\n },\n\n getDescriptionBox : function() {\n switch (this.currentLocation) {\n case \"pth_upload\":\n return document.getElementById('album_desc');\n\n case \"pth_edit\":\n return document.getElementsByName('body')[0];\n\n case \"pth_torrent_overview\":\n if (!this.hasOwnProperty(\"dummybox\")) {\n this.dummybox = document.createElement('div');\n }\n return this.dummybox;\n\n case \"pth_request\":\n case \"pth_request_edit\":\n return document.getElementsByName('description')[0];\n\n case \"waffles_upload\":\n return document.getElementById('descr');\n\n case \"waffles_upload_new\":\n return document.getElementById('id_descr');\n\n case \"waffles_request\":\n return document.getElementsByName('information')[0];\n\n default:\n // that should actually never happen\n return document.createElement('div');\n }\n },\n\n getFormFillFunction : function() {\n switch (this.currentLocation) {\n case \"pth_upload\":\n var f = function(rawData) {\n var artist_inputs = document.getElementsByName(\"artists[]\"),\n album_title_input = document.getElementById(\"title\"),\n year_input = document.getElementById(\"year\"),\n label_input = document.getElementById(\"record_label\"),\n catalog_input = document.getElementById(\"catalogue_number\"),\n tags_input = document.getElementById(\"tags\"),\n data = yadg.prepareRawResponse(rawData);\n\n if (data.artists != false) {\n var input_idx = 0;\n\n yadg_util.addRemoveArtistBoxes(data.effective_artist_count - artist_inputs.length);\n\n artist_inputs = document.getElementsByName(\"artists[]\");\n\n for (var i = 0; i < data.artist_keys.length; i++) {\n var artist_key = data.artist_keys[i],\n artist_types = data.artists[artist_key];\n\n for (var j = 0; j < artist_types.length; j++) {\n var artist_type = artist_types[j],\n artist_input = artist_inputs[input_idx],\n type_select = artist_input.nextSibling;\n\n while (type_select.tagName != 'SELECT') {\n type_select = type_select.nextSibling;\n }\n\n artist_input.value = artist_key;\n\n var option_offsets = yadg_util.getOptionOffsets(type_select);\n\n if (artist_type === \"main\") {\n type_select.selectedIndex = option_offsets[1];\n } else if (artist_type === \"guest\") {\n type_select.selectedIndex = option_offsets[2];\n } else if (artist_type === \"remixer\") {\n type_select.selectedIndex = option_offsets[3];\n } else {\n // we don't know this artist type, default to \"main\"\n type_select.selectedIndex = option_offsets[1];\n }\n\n // next artist input\n input_idx += 1;\n }\n }\n } else {\n for (var i = 0; i < artist_inputs.length; i++) {\n artist_inputs[i].value = '';\n }\n }\n\n if (data.tags != false) {\n tags_input.value = data.tag_string.toLowerCase();\n } else {\n tags_input.value = '';\n }\n\n yadg_util.setValueIfSet(data.year,year_input,data.year != false);\n yadg_util.setValueIfSet(data.title,album_title_input,data.title != false);\n yadg_util.setValueIfSet(data.label,label_input,data.label != false);\n yadg_util.setValueIfSet(data.catalog,catalog_input,data.catalog != false);\n };\n return f;\n\n case \"pth_edit\":\n f = function(rawData) {\n var summary_input = document.getElementsByName(\"summary\")[0];\n var data = yadg.prepareRawResponse(rawData);\n\n summary_input.value = 'YADG Update';\n };\n return f;\n\n case \"pth_torrent_overview\":\n f = function(rawData) {\n var artist_inputs = document.getElementsByName(\"aliasname[]\"),\n data = yadg.prepareRawResponse(rawData);\n\n if (data.artists != false) {\n var input_idx = 0;\n\n yadg_util.addRemoveArtistBoxes(data.effective_artist_count - artist_inputs.length);\n\n artist_inputs = document.getElementsByName(\"aliasname[]\");\n\n for (var i = 0; i < data.artist_keys.length; i++) {\n var artist_key = data.artist_keys[i],\n artist_types = data.artists[artist_key];\n\n for (var j = 0; j < artist_types.length; j++) {\n var artist_type = artist_types[j],\n artist_input = artist_inputs[input_idx],\n type_select = artist_input.nextSibling;\n\n while (type_select.tagName != 'SELECT') {\n type_select = type_select.nextSibling;\n }\n\n artist_input.value = artist_key;\n\n var option_offsets = yadg_util.getOptionOffsets(type_select);\n\n if (artist_type === \"main\") {\n type_select.selectedIndex = option_offsets[1];\n } else if (artist_type === \"guest\") {\n type_select.selectedIndex = option_offsets[2];\n } else if (artist_type === \"remixer\") {\n type_select.selectedIndex = option_offsets[3];\n } else {\n // we don't know this artist type, default to \"main\"\n type_select.selectedIndex = option_offsets[1];\n }\n\n // next artist input\n input_idx += 1;\n }\n }\n } else {\n for (var i = 0; i < artist_inputs.length; i++) {\n artist_inputs[i].value = '';\n }\n }\n };\n return f;\n\n case \"pth_request\":\n case \"pth_request_edit\":\n var f = function(rawData) {\n var artist_inputs = document.getElementsByName(\"artists[]\"),\n album_title_input = document.getElementsByName(\"title\")[0],\n year_input = document.getElementsByName(\"year\")[0],\n label_input = document.getElementsByName(\"recordlabel\")[0],\n catalog_input = document.getElementsByName(\"cataloguenumber\")[0],\n tags_input = document.getElementById(\"tags\"),\n data = yadg.prepareRawResponse(rawData);\n\n if (data.artists != false) {\n var input_idx = 0;\n\n yadg_util.addRemoveArtistBoxes(data.effective_artist_count - artist_inputs.length);\n\n artist_inputs = document.getElementsByName(\"artists[]\");\n\n for (var i = 0; i < data.artist_keys.length; i++) {\n var artist_key = data.artist_keys[i],\n artist_types = data.artists[artist_key];\n\n for (var j = 0; j < artist_types.length; j++) {\n var artist_type = artist_types[j],\n artist_input = artist_inputs[input_idx],\n type_select = artist_input.nextSibling;\n\n while (type_select.tagName != 'SELECT') {\n type_select = type_select.nextSibling;\n }\n\n artist_input.value = artist_key;\n\n var option_offsets = yadg_util.getOptionOffsets(type_select);\n\n if (artist_type === \"main\") {\n type_select.selectedIndex = option_offsets[1];\n } else if (artist_type === \"guest\") {\n type_select.selectedIndex = option_offsets[2];\n } else if (artist_type === \"remixer\") {\n type_select.selectedIndex = option_offsets[3];\n } else {\n // we don't know this artist type, default to \"main\"\n type_select.selectedIndex = option_offsets[1];\n }\n\n // next artist input\n input_idx += 1;\n }\n }\n } else {\n for (var i = 0; i < artist_inputs.length; i++) {\n artist_inputs[i].value = '';\n }\n }\n\n if (data.tags != false) {\n tags_input.value = data.tag_string.toLowerCase();\n } else {\n tags_input.value = '';\n }\n\n yadg_util.setValueIfSet(data.year,year_input,data.year != false);\n yadg_util.setValueIfSet(data.title,album_title_input,data.title != false);\n yadg_util.setValueIfSet(data.label,label_input,data.label != false);\n yadg_util.setValueIfSet(data.catalog,catalog_input,data.catalog != false);\n };\n return f;\n\n case \"waffles_upload\":\n var f = function(rawData) {\n var artist_input = document.getElementsByName(\"artist\")[0],\n album_title_input = document.getElementsByName(\"album\")[0],\n year_input = document.getElementsByName(\"year\")[0],\n va_checkbox = document.getElementById(\"va\"),\n tags_input = document.getElementById(\"tags\"),\n data = yadg.prepareRawResponse(rawData);\n\n if (data.artists != false) {\n if (data.is_various) {\n artist_input.value = \"\";\n va_checkbox.checked = true;\n } else {\n artist_input.value = data.flat_artist_string;\n va_checkbox.checked = false;\n }\n } else {\n va_checkbox.checked = false;\n artist_input.value = \"\";\n }\n\n yadg_util.setValueIfSet(data.year,year_input,data.year != false);\n yadg_util.setValueIfSet(data.title,album_title_input,data.title != false);\n\n if (data.tags != false) {\n tags_input.value = data.tag_string_nodots.toLowerCase();\n } else {\n tags_input.value = '';\n }\n\n yadg_util.exec(function() {formatName()});\n };\n return f;\n\n case \"waffles_upload_new\":\n var f = function(rawData) {\n var artist_input = document.getElementById(\"id_artist\"),\n album_title_input = document.getElementById(\"id_album\"),\n year_input = document.getElementById(\"id_year\"),\n va_checkbox = document.getElementById(\"id_va\"),\n tags_input = document.getElementById(\"id_tags\"),\n data = yadg.prepareRawResponse(rawData);\n\n if (data.artists != false) {\n if (data.is_various) {\n if (!va_checkbox.checked) {\n va_checkbox.click();\n }\n } else {\n if (va_checkbox.checked) {\n va_checkbox.click();\n }\n artist_input.value = data.flat_artist_string;\n }\n } else {\n if (va_checkbox.checked) {\n va_checkbox.click();\n }\n artist_input.value = \"\";\n }\n\n yadg_util.setValueIfSet(data.year,year_input,data.year != false);\n yadg_util.setValueIfSet(data.title,album_title_input,data.title != false);\n\n if (data.tags != false) {\n tags_input.value = data.tag_string_nodots.toLowerCase();\n } else {\n tags_input.value = '';\n }\n };\n return f;\n\n case \"waffles_request\":\n var f = function(rawData) {\n var artist_input = document.getElementsByName(\"artist\")[0],\n album_title_input = document.getElementsByName(\"title\")[0],\n year_input = document.getElementsByName(\"year\")[0],\n data = yadg.prepareRawResponse(rawData);\n\n if (data.artists != false) {\n if (data.is_various) {\n artist_input.value = \"Various Artists\";\n } else {\n artist_input.value = data.flat_artist_string;\n }\n } else {\n artist_input.value = \"\";\n }\n\n yadg_util.setValueIfSet(data.year,year_input,data.year != false);\n yadg_util.setValueIfSet(data.title,album_title_input,data.title != false);\n };\n return f;\n\n default:\n // that should actually never happen\n return function(data) {};\n }\n }\n};\n\nvar yadg_templates = {\n _templates : {},\n _template_urls : {},\n\n getTemplate : function(id, callback) {\n if (id in this._templates) {\n callback(this._templates[id]);\n } else if (id in this._template_urls) {\n var request = new requester(this._template_urls[id], 'GET', function(template) {\n yadg_templates.addTemplate(template);\n callback(template);\n }, null, yadg_templates.errorTemplate);\n request.send();\n } else {\n this.errorTemplate();\n }\n },\n\n addTemplate : function(template) {\n this._templates[template.id] = template;\n },\n\n addTemplateUrl : function(id, url) {\n this._template_urls[id] = url;\n },\n\n errorTemplate : function() {\n yadg.printError(\"Could not get template. Please choose another one.\", true);\n }\n};\n\nvar yadg_renderer = {\n _last_data : null,\n _last_template_id : null,\n\n render : function(template_id, data, callback, error_callback) {\n this._last_data = data;\n var new_template = this._last_template_id !== template_id;\n this._last_template_id = template_id;\n\n yadg_templates.getTemplate(template_id, function(template) {\n // the new template might have different dependencies, so initialize Swig with those\n if (new_template) {\n yadg_sandbox.resetSandbox();\n yadg_sandbox.initializeSwig(template.dependencies);\n }\n yadg_sandbox.renderTemplate(template.code, data, callback, error_callback);\n });\n },\n\n renderCached : function(template_id, callback, error_callback) {\n if (this.hasCached()) {\n this.render(template_id, this._last_data, callback, error_callback);\n }\n },\n\n hasCached : function() {\n return this._last_data !== null;\n },\n\n clearCached : function() {\n this._last_data = null;\n }\n};\n\nvar yadg = {\n yadgHost : \"https://yadg.cc\",\n baseURI : \"/api/v2/\",\n\n standardError : \"Sorry, an error occured. Please try again. If this error persists the user script might need updating.\",\n authenticationError : \"Your API token is invalid. Please provide a valid API token or remove the current one.\",\n lastStateError : false,\n\n isBusy : false,\n\n init : function() {\n this.scraperSelect = document.getElementById('yadg_scraper');\n this.formatSelect = document.getElementById('yadg_format');\n this.input = document.getElementById('yadg_input');\n this.responseDiv = document.getElementById('yadg_response');\n this.button = document.getElementById('yadg_submit');\n },\n\n getBaseURL : function() {\n return this.yadgHost + this.baseURI;\n },\n\n getScraperList : function(callback) {\n var url = this.getBaseURL() + \"scrapers/\";\n\n var request = new requester(url, 'GET', callback);\n\n request.send();\n },\n\n getFormatsList : function(callback) {\n var url = this.getBaseURL() + \"templates/\";\n\n this.getTemplates(url, [], callback);\n },\n\n getTemplates : function(url, templates, callback) {\n var request = new requester(url, 'GET', function(data) {\n for (var i = 0; i < data.results.length; i++) {\n templates.push(data.results[i]);\n }\n if (data.next !== null) {\n yadg.getTemplates(data.next, templates, callback);\n } else {\n callback(templates);\n }\n });\n\n request.send();\n },\n\n makeRequest : function(params) {\n if (this.isBusy) return;\n\n var data;\n if (params) {\n data = params;\n } else {\n data = {\n scraper: this.scraperSelect.options[this.scraperSelect.selectedIndex].value,\n input: this.input.value\n };\n }\n var url = this.getBaseURL() + 'query/';\n\n if (data.input !== '') {\n var request = new requester(url, 'POST', function(result) {\n yadg.getResult(result.url);\n }, data);\n this.busyStart();\n request.send();\n }\n },\n\n getResult : function(result_url) {\n var request = new requester(result_url, 'GET', function(response) {\n if (response.status == \"done\") {\n if (response.data.type == 'ReleaseResult') {\n var template_id = yadg.formatSelect.options[yadg.formatSelect.selectedIndex].value;\n yadg_renderer.render(template_id, response, factory.setDescriptionBoxValue, factory.setDescriptionBoxValue);\n\n if (yadg.lastStateError == true) {\n yadg.responseDiv.innerHTML = \"\";\n yadg.lastStateError = false;\n }\n\n var fillFunc = factory.getFormFillFunction();\n fillFunc(response.data);\n } else if (response.data.type == 'ListResult') {\n var ul = document.createElement('ul');\n ul.id = \"yadg_release_list\";\n\n var release_list = response.data.items;\n for (var i = 0; i < release_list.length;i++) {\n var name = release_list[i]['name'],\n info = release_list[i]['info'],\n query_params = release_list[i]['queryParams'],\n release_url = release_list[i]['url'];\n\n var li = document.createElement('li'),\n a = document.createElement('a');\n\n a.textContent = name;\n a.params = query_params;\n a.href = release_url;\n\n a.addEventListener('click',function(e) { e.preventDefault(); yadg.makeRequest(this.params);},false);\n\n li.appendChild(a);\n li.appendChild(document.createElement('br'));\n li.appendChild(document.createTextNode(info));\n\n ul.appendChild(li);\n }\n\n if (ul.childNodes.length != 0) {\n yadg.responseDiv.innerHTML = \"\";\n yadg.responseDiv.appendChild(ul);\n yadg.lastStateError = false;\n\n // we got a ListResult so clear the last ReleaseResult from the render cache\n yadg_renderer.clearCached();\n } else {\n yadg.printError('Sorry, there were no matches.');\n }\n } else if (response.data.type == 'NotFoundResult') {\n yadg.printError('I could not find the release with the given ID. You may want to try again with another one.');\n } else {\n yadg.printError('Something weird happened. Please try again');\n }\n yadg.busyStop();\n } else if (response.status == 'failed') {\n yadg.failed_callback();\n } else {\n var delay = function() { yadg.getResult(response.url); };\n window.setTimeout(delay, 1000);\n }\n });\n request.send();\n },\n\n printError : function(message, template_error) {\n this.responseDiv.innerHTML = \"\";\n this.responseDiv.appendChild(document.createTextNode(message));\n if (!template_error) {\n this.lastStateError = true;\n\n // there was a non template related error, so for consistencies sake clear the last ReleaseResult from the\n // render cache\n yadg_renderer.clearCached();\n }\n },\n\n failed_callback : function() {\n yadg.printError(yadg.standardError);\n yadg.busyStop();\n },\n\n failed_authentication_callback : function() {\n yadg.printError(yadg.authenticationError);\n yadg.busyStop();\n },\n\n busyStart : function() {\n this.isBusy = true;\n this.button.setAttribute('disabled',true);\n this.button.value = \"Please wait...\";\n this.input.setAttribute('disabled',true);\n this.scraperSelect.setAttribute('disabled',true);\n this.formatSelect.setAttribute('disabled',true);\n },\n\n busyStop : function() {\n this.button.removeAttribute('disabled');\n this.button.value = \"Fetch\";\n this.input.removeAttribute('disabled');\n this.scraperSelect.removeAttribute('disabled');\n this.formatSelect.removeAttribute('disabled');\n this.isBusy = false;\n },\n\n prepareRawResponse : function(rawData) {\n var result = {};\n\n result.artists = false;\n result.year = false;\n result.title = false;\n result.label = false;\n result.catalog = false;\n result.genre = false;\n result.style = false;\n result.tags = false;\n result.is_various = false;\n result.flat_artist_string = false;\n\n if (rawData.artists.length > 0) {\n result.artists = {};\n\n for (var i = 0; i < rawData.artists.length; i++) {\n var artist = rawData.artists[i];\n if (!artist[\"isVarious\"]) {\n result.artists[artist[\"name\"]] = artist[\"types\"];\n } else {\n result.is_various = true;\n }\n }\n }\n if (rawData.discs.length > 0) {\n for (var k = 0; k < rawData.discs.length; k++) {\n var disc = rawData.discs[k];\n for (var l = 0; l < disc[\"tracks\"].length; l++) {\n var track = disc[\"tracks\"][l];\n for (var m = 0; m < track[\"artists\"].length; m++) {\n var name = track[\"artists\"][m][\"name\"],\n type = track[\"artists\"][m][\"types\"];\n\n var newTypes = null;\n if (name in result.artists) {\n newTypes = result.artists[name].concat(type);\n // deduplicate new types array\n for(var i = 0; i < newTypes.length; ++i) {\n for(var j = i+1; j < newTypes.length; ++j) {\n if(newTypes[i] === newTypes[j])\n newTypes.splice(j--, 1);\n }\n }\n } else {\n newTypes = type;\n }\n\n result.artists[name] = newTypes;\n }\n }\n }\n }\n for (var i = 0; i < rawData['releaseEvents'].length; i++) {\n var event = rawData['releaseEvents'][i];\n if (event.date) {\n result.year = event.date.match(/\\d{4}/)[0];\n if (result.year.length != 4) {\n result.year = false;\n } else {\n break;\n }\n }\n }\n if (rawData.title) {\n result.title = rawData.title;\n }\n if (rawData.labelIds.length > 0) {\n var labelId = rawData['labelIds'][0];\n if (labelId.label) {\n result.label = labelId.label;\n }\n if (labelId.catalogueNrs.length > 0) {\n result.catalog = labelId.catalogueNrs[0];\n }\n }\n if (rawData.genres.length > 0) {\n result.genre = rawData.genres;\n }\n if (rawData.styles.length > 0) {\n result.style = rawData.styles;\n }\n if (result.genre != false && result.style != false) {\n result.tags = rawData.genres.concat(rawData.styles);\n } else if (result.genre != false) {\n result.tags = rawData.genres;\n } else if (result.style != false) {\n result.tags = rawData.styles;\n }\n\n if (result.tags != false) {\n result.tag_string = \"\";\n result.tag_string_nodots = \"\";\n\n for (var i = 0; i < result.tags.length; i++) {\n result.tag_string = result.tag_string + result.tags[i].replace(/\\s+/g,'.');\n result.tag_string_nodots = result.tag_string_nodots + result.tags[i].replace(/\\s+/g,' ');\n if (i != result.tags.length-1) {\n result.tag_string = result.tag_string + ', ';\n result.tag_string_nodots = result.tag_string_nodots + ', ';\n }\n }\n }\n\n if (result.artists != false) {\n // count the artists\n result.artists_length = 0;\n result.artist_keys = [];\n result.effective_artist_count = 0;\n\n for (var i in result.artists) {\n if (result.artists.hasOwnProperty(i)) {\n result.artists_length++;\n result.artist_keys.push(i);\n result.effective_artist_count += result.artists[i].length;\n }\n }\n }\n\n if (result.artists_length == 0) {\n result.artists = false;\n } else {\n // create a flat string of all the main artists\n var artist_string = \"\";\n\n for (var i = 0; i < result.artists_length; i++) {\n if (result.artists[result.artist_keys[i]].indexOf(\"main\") != -1) {\n if (artist_string != \"\" && i < result.artists_length - 2) {\n artist_string = artist_string + \", \";\n } else if (artist_string != \"\" && i < result.artists_length - 1) {\n artist_string = artist_string + \" & \";\n }\n artist_string = artist_string + result.artist_keys[i];\n }\n }\n\n result.flat_artist_string = artist_string;\n }\n\n return result;\n }\n};\n\nyadg_sandbox.init(function() {\n if (factory.init()) { // returns true if we run on a valid location\n yadg.init();\n }\n});\n"},"message":{"kind":"string","value":"Shorten name\n\n"},"old_file":{"kind":"string","value":"pth_yadg.user.js"},"subject":{"kind":"string","value":"Shorten name"},"git_diff":{"kind":"string","value":"th_yadg.user.js\n // ==UserScript==\n // @id pth-yadg\n// @name passtheheadphones.me - YADG\n// @name PTH YADG\n // @description This script provides integration with online description generator YADG (http://yadg.cc) - Credit to Slack06\n // @license https://github.com/SavageCore/yadg-pth-userscript/blob/master/LICENSE\n // @version 1.3.10"}}},{"rowIdx":870,"cells":{"lang":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"15b383afbb00992425732b1c3704f4a32967ee35"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"mure-apps/mure-library"},"new_contents":{"kind":"string","value":"/* eslint no-useless-escape: 0 */\nimport 'babel-polyfill';\nimport * as d3 from 'd3';\nimport datalib from 'datalib';\nimport md5 from 'md5';\nimport * as jsonpath from 'jsonpath';\nimport PouchDB from 'pouchdb';\nimport { Model } from 'uki';\nimport appList from './appList.json';\nimport mureInteractivityRunnerText from './mureInteractivityRunner.js';\n\nclass Mure extends Model {\n constructor () {\n super();\n this.appList = appList;\n // Check if we're even being used in the browser (mostly useful for getting\n // access to the applist in all-apps-dev-server.js)\n if (typeof document === 'undefined' || typeof window === 'undefined') {\n return;\n }\n\n // Enumerations...\n this.VALID_EVENTS = {\n fileListChange: {},\n fileChange: {},\n domChange: {},\n metadataChange: {},\n error: {}\n };\n\n this.CONTENT_FORMATS = {\n exclude: 0,\n blob: 1,\n dom: 2,\n base64: 3\n };\n\n this.SIGNALS = {\n cancelled: {}\n };\n\n this.ENCODING_TYPES = {\n constant: 0\n };\n\n // The namespace string for our custom XML\n this.NSString = 'http://mure-apps.github.io';\n d3.namespaces.mure = this.NSString;\n\n // Funky stuff to figure out if we're debugging (if that's the case, we want to use\n // localhost instead of the github link for all links)\n let windowTitle = document.getElementsByTagName('title')[0];\n windowTitle = windowTitle ? windowTitle.textContent : '';\n this.debugMode = window.location.hostname === 'localhost' && windowTitle.startsWith('Mure');\n\n // Figure out which app we are (or null if the mure library is being used somewhere else)\n this.currentApp = window.location.pathname.replace(/\\//g, '');\n if (!this.appList[this.currentApp]) {\n this.currentApp = null;\n }\n\n // Create / load the local database of files\n this.lastFile = null;\n this.db = this.getOrInitDb();\n\n // default error handling (apps can listen for / display error messages in addition to this):\n this.on('error', errorMessage => {\n console.warn(errorMessage);\n });\n this.catchDbError = errorObj => {\n this.trigger('error', 'Unexpected error reading PouchDB: ' + errorObj.message + '\\n' + errorObj.stack);\n };\n\n // in the absence of a custom dialogs, just use window.alert, window.confirm and window.prompt:\n this.alert = (message) => {\n return new Promise((resolve, reject) => {\n window.alert(message);\n resolve(true);\n });\n };\n this.confirm = (message) => {\n return new Promise((resolve, reject) => {\n resolve(window.confirm(message));\n });\n };\n this.prompt = (message, defaultValue) => {\n return new Promise((resolve, reject) => {\n resolve(window.prompt(message, defaultValue));\n });\n };\n }\n on (eventName, callback) {\n if (!this.VALID_EVENTS[eventName]) {\n throw new Error('Unknown event name: ' + eventName);\n } else {\n super.on(eventName, callback);\n }\n }\n customizeAlertDialog (showDialogFunction) {\n this.alert = showDialogFunction;\n }\n customizeConfirmDialog (showDialogFunction) {\n this.confirm = showDialogFunction;\n }\n customizePromptDialog (showDialogFunction) {\n this.prompt = showDialogFunction;\n }\n openApp (appName, newTab) {\n if (newTab) {\n window.open('/' + appName, '_blank');\n } else {\n window.location.pathname = '/' + appName;\n }\n }\n getOrInitDb () {\n let db = new PouchDB('mure');\n (async () => {\n this.lastFile = null;\n try {\n let prefs = await db.get('userPrefs');\n if (prefs.currentFile) {\n this.lastFile = await this.getFile(prefs.currentFile);\n }\n } catch (errorObj) {\n if (errorObj.message === 'missing') {\n db.put({\n _id: 'userPrefs',\n currentFile: null\n });\n } else {\n this.catchDbError(errorObj);\n }\n }\n })();\n\n db.changes({\n since: 'now',\n live: true,\n include_docs: true\n }).on('change', change => {\n let fileChanged;\n let fileListChanged;\n let domChanged;\n let metadataChanged;\n\n if (change.deleted) {\n if (change.doc._id !== this.lastFile._id) {\n // Weird corner case: if we just deleted a file that wasn't the current one,\n // we won't ever get a change event on the userPrefs object; in that case,\n // we need to trigger the fileListChanged event immediately\n (async () => {\n let fileList = await this.getFileList();\n this.trigger('fileListChange', fileList);\n })().catch(this.catchDbError);\n }\n // Whether or not the deleted file was the currently open one, don't\n // trigger any other events; we want events to fire in context of the\n // new stuff getting loaded below\n return;\n }\n\n let currentFile;\n if (change.doc._id === 'userPrefs') {\n // We just changed the currently open file; trigger all the events\n fileChanged = fileListChanged = domChanged = metadataChanged = true;\n currentFile = this.lastFile;\n } else {\n if (this.lastFile === null || this.lastFile._id !== change.doc._id) {\n // The file itself is changing; DON'T actually trigger any of the events\n // because userPrefs is about to be changed as well... and things listening\n // to changes that care about checking userPrefs will want to do it with\n // its value updated\n fileChanged = fileListChanged = domChanged = metadataChanged = false;\n } else {\n fileChanged = false;\n domChanged = this.lastFile._attachments[this.lastFile._id].digest !==\n change.doc._attachments[change.doc._id].digest;\n metadataChanged = this.lastFile.metadataDigest !== change.doc.metadataDigest;\n }\n this.lastFile = currentFile = change.doc;\n }\n\n if (fileChanged) {\n this.trigger('fileChange', currentFile);\n }\n if (fileListChanged) {\n (async () => {\n let fileList = await this.getFileList();\n this.trigger('fileListChange', fileList);\n })().catch(this.catchDbError);\n }\n if (domChanged) {\n (async () => {\n let blob = currentFile ? await this.getFileAsBlob(currentFile._id) : null;\n this.trigger('domChange', blob);\n })();\n }\n if (metadataChanged) {\n this.trigger('metadataChange', currentFile ? currentFile.metadata : null);\n }\n }).on('error', errorObj => {\n this.catchDbError(errorObj);\n });\n return db;\n }\n async setCurrentFile (filename) {\n return this.db.get('userPrefs').then(prefs => {\n prefs.currentFile = filename;\n return this.db.put(prefs);\n }).catch(this.catchDbError);\n }\n async getFile (filename, contentFormat) {\n if (!filename) {\n filename = await this.getCurrentFilename();\n }\n\n let pouchdbOptions = {};\n if (contentFormat !== this.CONTENT_FORMATS.exclude) {\n pouchdbOptions.attachments = true;\n if (contentFormat === this.CONTENT_FORMATS.blob) {\n pouchdbOptions.binary = true;\n }\n }\n\n if (filename !== null) {\n return this.db.get(filename, pouchdbOptions || {})\n .then(fileObj => {\n if (contentFormat === this.CONTENT_FORMATS.dom) {\n let xmlText = window.atob(fileObj._attachments[fileObj._id].data);\n let dom = new window.DOMParser().parseFromString(xmlText, 'image/svg+xml');\n fileObj._attachments[fileObj._id].dom = dom;\n }\n return fileObj;\n });\n } else {\n return Promise.resolve(null);\n }\n }\n async saveFile (options) {\n try {\n let existingDoc;\n if (!options.blobOrBase64string) {\n existingDoc = await this.getFile(options.filename, this.CONTENT_FORMATS.exclude);\n } else {\n existingDoc = await this.getFile(options.filename, this.CONTENT_FORMATS.blob);\n existingDoc._attachments[options.filename].data = options.blobOrBase64string;\n if ((!options.metadata || Object.keys(options.metadata).length === 0) &&\n Object.keys(existingDoc.metadata) > 0) {\n let userConfirmation = await this.confirm(\n 'It appears that the file you\\'re uploading has lost its Mure metadata. ' +\n 'This is fairly common when you\\'ve edited it with an external program.\\n\\n' +\n 'Restore the most recent metadata?');\n if (!userConfirmation) {\n existingDoc.metadata = {};\n existingDoc.metadataDigest = md5('{}');\n }\n }\n }\n if (options.metadata) {\n existingDoc.metadata = options.metadata;\n existingDoc.metadataDigest = md5(JSON.stringify(options.metadata));\n }\n return this.db.put(existingDoc);\n } catch (errorObj) {\n if (errorObj.message === 'missing') {\n // The file doesn't exist yet...\n let newDoc = {\n _id: options.filename,\n _attachments: {},\n metadata: options.metadata || {},\n metadataDigest: options.metadata ? md5(JSON.stringify(options.metadata)) : md5('{}')\n };\n if (!options.blobOrBase64string) {\n this.trigger('error', 'Attempted to save a file without contents!');\n }\n newDoc._attachments[options.filename] = {\n content_type: 'image/svg+xml',\n data: options.blobOrBase64string\n };\n return this.db.put(newDoc);\n } else {\n this.catchDbError(errorObj);\n return Promise.reject(errorObj);\n }\n }\n }\n async getMetadata (filename) {\n let currentFile = await this.getFile(filename, this.CONTENT_FORMATS.exclude);\n return currentFile !== null ? currentFile.metadata : null;\n }\n async getCurrentFilename () {\n return this.db.get('userPrefs').then(prefs => {\n return prefs.currentFile;\n });\n }\n async getFileList () {\n return this.db.allDocs()\n .then(response => {\n let result = [];\n response.rows.forEach(d => {\n if (d.id !== 'userPrefs') {\n result.push(d.id);\n }\n });\n return result;\n }).catch(this.catchDbError);\n }\n async getFileRevisions () {\n return this.db.allDocs()\n .then(response => {\n let result = {};\n response.rows.forEach(d => {\n if (d.id !== 'userPrefs') {\n result[d.id] = d.value.rev;\n }\n });\n return result;\n }).catch(this.catchDbError);\n }\n async readFile (reader, fileObj) {\n return new Promise((resolve, reject) => {\n reader.onloadend = xmlText => {\n resolve(xmlText.target.result);\n };\n reader.onerror = error => {\n reject(error);\n };\n reader.onabort = () => {\n reject(this.SIGNALS.cancelled);\n };\n reader.readAsText(fileObj);\n });\n }\n async validateFileName (originalName, takenNames, abortFunction) {\n // Ask multiple times if the user happens to enter another filename that already exists\n let filename = originalName;\n while (takenNames[filename]) {\n filename = await this.prompt(\n filename + ' already exists. Pick a new name, or leave it the same to overwrite:',\n filename);\n if (filename === null) {\n if (abortFunction) {\n abortFunction();\n }\n return Promise.reject(this.SIGNALS.cancelled);\n } else if (filename === '') {\n filename = await this.prompt('You must enter a file name (or click cancel to cancel the upload)');\n } else if (filename === originalName) {\n // They left it the same... overwrite!\n return filename;\n }\n }\n return filename;\n }\n inferParser (fileObj) {\n let ext = fileObj.type.split('/')[1];\n if (ext === 'csv') {\n return (contents) => { return datalib.read(contents, {type: 'csv', parse: 'auto'}); };\n } else if (ext === 'tsv') {\n return (contents) => { return datalib.read(contents, {type: 'tsv', parse: 'auto'}); };\n } else if (ext === 'dsv') {\n return (contents) => { return datalib.read(contents, {type: 'dsv', parse: 'auto'}); };\n } else if (ext === 'json') {\n // TODO: attempt to auto-discover topojson or treejson?\n return (contents) => { return datalib.read(contents, {type: 'json', parse: 'auto'}); };\n } else {\n return null;\n }\n }\n async uploadDataset (fileObj) {\n let parser = this.inferParser(fileObj);\n if (!parser) {\n let errorObj = new Error('Unknown data file type: ' + fileObj.type);\n this.trigger('error', errorObj);\n return Promise.reject(errorObj);\n }\n\n let metadata = await this.getMetadata();\n if (metadata === null) {\n let errorObj = new Error('Can\\'t embed a data file without an SVG file already open');\n this.trigger('error', errorObj);\n return Promise.reject(errorObj);\n }\n metadata.datasets = metadata.datasets || {};\n\n let reader = new window.FileReader();\n let dataFileName = await this.validateFileName(fileObj.name, metadata.datasets, reader.abort);\n let fileText = await this.readFile(reader, fileObj);\n\n metadata.datasets[dataFileName] = parser(fileText);\n return this.saveFile({ metadata });\n }\n async uploadSvg (fileObj) {\n let reader = new window.FileReader();\n let contentsPromise = this.readFile(reader, fileObj)\n .then(xmlText => {\n let dom = new window.DOMParser().parseFromString(xmlText, 'image/svg+xml');\n let contents = { metadata: this.extractMetadata(dom) };\n contents.base64data = window.btoa(new window.XMLSerializer().serializeToString(dom));\n return contents;\n });\n\n let filenamePromise = this.getFileRevisions()\n .catch(this.catchDbError)\n .then(revisionDict => {\n return this.validateFileName(fileObj.name, revisionDict, reader.abort);\n });\n\n return Promise.all([filenamePromise, contentsPromise]).then(([filename, contents]) => {\n return this.saveFile({\n filename,\n blobOrBase64string: contents.base64data,\n metadata: contents.metadata\n }).then(() => {\n return this.setCurrentFile(filename);\n });\n }).catch((errList) => {\n if (errList[0] !== this.SIGNALS.cancelled || errList[1] !== this.SIGNALS.cancelled) {\n // cancelling is not a problem; only reject if something else happened\n return Promise.reject(errList);\n }\n });\n }\n async deleteSvg (filename) {\n let userConfirmation = await this.confirm('Are you sure you want to delete ' + filename + '?');\n if (userConfirmation) {\n let currentFile = await this.getFile(filename, this.CONTENT_FORMATS.exclude);\n return this.db.remove(currentFile._id, currentFile._rev)\n .then(removeResponse => {\n if (this.lastFile && filename === this.lastFile._id) {\n return this.setCurrentFile(null).then(() => removeResponse);\n }\n return removeResponse;\n });\n } else {\n return Promise.resolve(false);\n }\n }\n extractMetadata (dom) {\n let self = this;\n let metadata = {};\n let d3dom = d3.select(dom.rootElement);\n\n // Extract the container for our metadata, if it exists\n let root = d3dom.select('#mure');\n if (root.size() === 0) {\n return metadata;\n }\n let nsElement = root.select('mure');\n if (nsElement.size() === 0) {\n return metadata;\n }\n\n // Any libraries?\n nsElement.selectAll('library').each(function (d) {\n if (!metadata.libraries) {\n metadata.libraries = [];\n }\n metadata.libraries.push(d3.select(this).attr('src'));\n });\n\n // Any scripts?\n nsElement.selectAll('script').each(function (d) {\n let el = d3.select(this);\n let script = {\n text: self.extractCDATA(el.text())\n };\n let id = el.attr('id');\n if (id) {\n if (id === 'mureInteractivityRunner') {\n // Don't store our interactivity runner script\n return;\n }\n script.id = id;\n }\n if (!metadata.scripts) {\n metadata.scripts = [];\n }\n metadata.scripts.push(script);\n });\n\n // Any datasets?\n nsElement.selectAll('datasets').each(function (d) {\n let el = d3.select(this);\n if (!metadata.datasets) {\n metadata.datasets = {};\n }\n metadata.datasets[el.attr('name')] = JSON.parse(self.extractCDATA(el.text()));\n });\n\n // Any data bindings?\n nsElement.selectAll('binding').each(function (d) {\n let el = d3.select(this);\n let binding = {\n id: el.attr('id'),\n dataRoot: el.attr('dataroot'),\n svgRoot: el.attr('svgroot'),\n keyFunction: JSON.parse(self.extractCDATA(el.text()))\n };\n\n if (!metadata.bindings) {\n metadata.bindings = {};\n }\n metadata.bindings[binding.id] = binding;\n });\n\n // Any encodings?\n nsElement.selectAll('encoding').each(function (d) {\n let el = d3.select(this);\n let encoding = {\n id: el.attr('id'),\n bindingId: el.attr('for'),\n spec: JSON.parse(self.extractCDATA(el.text()))\n };\n\n if (!metadata.encodings) {\n metadata.encodings = {};\n }\n metadata.encodings[encoding.id] = encoding;\n });\n\n return metadata;\n }\n extractCDATA (str) {\n return str.replace(/(/g, '');\n }\n getEmptyBinding (metadata, add) {\n let id = 1;\n /* eslint-disable no-unmodified-loop-condition */\n while (metadata.bindings && metadata.bindings['Binding Set ' + id]) {\n id++;\n }\n /* eslint-enable no-unmodified-loop-condition */\n let newBinding = {\n id: 'Binding Set ' + id,\n svgRoot: ':root',\n dataRoot: metadata.datasets && Object.keys(metadata.datasets).length > 0\n ? '$[\"' + Object.keys(metadata.datasets)[0] + '\"]' : '',\n keyFunction: {\n expression: '(d, e) => d.key === e.index'\n }\n };\n if (add) {\n if (!metadata.bindings) {\n metadata.bindings = {};\n }\n metadata.bindings[newBinding.id] = newBinding;\n }\n return newBinding;\n }\n getEmptyEncoding (metadata, add) {\n let id = 1;\n /* eslint-disable no-unmodified-loop-condition */\n while (metadata.encodings && metadata.encodings['Encoding ' + id]) {\n id++;\n }\n /* eslint-enable no-unmodified-loop-condition */\n let newEncoding = {\n id: 'Encoding ' + id,\n bindingId: '',\n spec: {}\n };\n if (add) {\n if (!metadata.encodings) {\n metadata.encodings = {};\n }\n metadata.encodings[newEncoding.id] = newEncoding;\n }\n return newEncoding;\n }\n embedMetadata (dom, metadata) {\n let d3dom = d3.select(dom.rootElement);\n\n // Top: need a metadata tag\n let root = d3dom.selectAll('#mure').data([0]);\n root.exit().remove();\n root = root.enter().append('metadata').attr('id', 'mure').merge(root);\n\n // Next down: a tag to define the namespace\n let nsElement = root.selectAll('mure').data([0]);\n nsElement.exit().remove();\n nsElement = nsElement.enter().append('mure').attr('xmlns', this.NSString).merge(nsElement);\n\n // Okay, we're in our custom namespace... let's figure out the libraries\n let libraryList = metadata.libraries || [];\n let libraries = nsElement.selectAll('library').data(libraryList);\n libraries.exit().remove();\n libraries = libraries.enter().append('library').merge(libraries);\n libraries.attr('src', d => d);\n\n // Let's deal with any user scripts\n let scriptList = metadata.scripts || [];\n let scripts = nsElement.selectAll('script').data(scriptList);\n scripts.exit().remove();\n let scriptsEnter = scripts.enter().append('script');\n scripts = scriptsEnter.merge(scripts);\n scripts.attr('id', d => d.id || null);\n scripts.each(function (d) {\n this.innerHTML = '';\n });\n\n // Remove mureInteractivityRunner by default to ensure it always comes after the\n // metadata tag (of course, only bother adding it if we have any libraries or scripts)\n d3dom.select('#mureInteractivityRunner').remove();\n if (libraryList.length > 0 || scriptList.length > 0) {\n d3dom.append('script')\n .attr('id', 'mureInteractivityRunner')\n .attr('type', 'text/javascript')\n .text(' d.key)\n .html(d => '');\n\n // Store data bindings\n let bindings = nsElement.selectAll('binding').data(d3.values(metadata.bindings || {}));\n bindings.exit().remove();\n let bindingsEnter = bindings.enter().append('binding');\n bindings = bindingsEnter.merge(bindings);\n bindings\n .attr('id', d => d.id)\n .attr('dataroot', d => d.dataRoot)\n .attr('svgroot', d => d.svgRoot)\n .html(d => '');\n\n // Store encoding metadata\n let encodings = nsElement.selectAll('encoding').data(d3.values(metadata.encodings || {}));\n encodings.exit().remove();\n let encodingsEnter = encodings.enter().append('encoding');\n encodings = encodingsEnter.merge(encodings);\n encodings\n .attr('id', d => d.id)\n .attr('bindingid', d => d.bindingId)\n .html(d => '');\n\n return dom;\n }\n async downloadSvg (filename) {\n let fileEntry = await this.getFile(filename, this.CONTENT_FORMATS.dom);\n if (!fileEntry) {\n throw new Error('Can\\'t download non-existent file: ' + filename);\n }\n let dom = this.embedMetadata(fileEntry._attachments[fileEntry._id].dom, fileEntry.metadata);\n let xmlText = new window.XMLSerializer().serializeToString(dom)\n .replace(/&lt;!\\[CDATA\\[/g, '');\n\n // create a fake link to initiate the download\n let a = document.createElement('a');\n a.style = 'display:none';\n let url = window.URL.createObjectURL(new window.Blob([xmlText], { type: 'image/svg+xml' }));\n a.href = url;\n a.download = filename;\n document.body.appendChild(a);\n a.click();\n window.URL.revokeObjectURL(url);\n a.parentNode.removeChild(a);\n }\n matchDataPaths (path1, path2, metadata) {\n if (!metadata || !metadata.datasets || !path1 || !path2) {\n return false;\n }\n let result1 = jsonpath.query(metadata.datasets, path1);\n let result2 = jsonpath.query(metadata.datasets, path2);\n if (result1.length !== 1 || result2.length !== 1) {\n return false;\n }\n return result1[0] === result2[0];\n }\n matchDomSelectors (selector1, selector2, dom) {\n if (!selector1 || !selector2) {\n return false;\n }\n let result1 = dom.querySelector(selector1);\n let result2 = dom.querySelector(selector2);\n return result1 === result2;\n }\n getMatches (metadata, dom) {\n let mapping = [];\n if (metadata && metadata.bindings && metadata.datasets && dom) {\n d3.values(metadata.bindings).forEach(binding => {\n mapping.push(...this.getMatchesForBinding(binding, metadata, dom));\n });\n }\n return mapping;\n }\n getMatchesForBinding (binding, metadata, dom) {\n if (!binding.dataRoot || !binding.svgRoot || !binding.keyFunction) {\n return [];\n }\n\n if (binding.keyFunction.customMapping) {\n return binding.keyFunction.customMapping;\n }\n\n /* eslint-disable no-eval */\n let expression = (0, eval)(binding.keyFunction.expression);\n /* eslint-enable no-eval */\n\n // Need to evaluate the expression for each n^2 possible pairing, and assign\n // mapping the first time the expression is true (but not after!\n // mapping can only be one-to-one!)\n let dataRoot = jsonpath.query(metadata.datasets, binding.dataRoot)[0];\n let dataEntries;\n if (dataRoot instanceof Array) {\n dataEntries = dataRoot.map((d, i) => {\n return {\n key: i,\n value: d\n };\n });\n } else if (typeof dataRoot === 'object') {\n dataEntries = d3.entries(dataRoot);\n } else {\n return; // a leaf was picked as a root... no mapping possible\n }\n\n let svgRoot = dom.querySelector(binding.svgRoot);\n let svgItems = Array.from(svgRoot.children);\n\n let mapping = {\n links: [],\n svgLookup: {},\n dataLookup: {}\n };\n\n dataEntries.forEach(dataEntry => {\n for (let itemIndex = 0; itemIndex < svgItems.length; itemIndex += 1) {\n if (mapping.svgLookup[itemIndex] !== undefined) {\n // this svg element has already been matched with a different dataEntry\n continue;\n }\n let svgEntry = {\n index: itemIndex,\n element: svgItems[itemIndex]\n };\n let expressionResult = null;\n try {\n expressionResult = expression(dataEntry, svgEntry);\n } catch (errorObj) {\n // todo: add interface helpers for debugging the expression\n throw errorObj;\n }\n if (expressionResult === true) {\n mapping.svgLookup[svgEntry.index] = mapping.links.length;\n mapping.dataLookup[dataEntry.key] = mapping.links.length;\n mapping.links.push({\n dataEntry,\n svgEntry\n });\n break;\n } else if (expressionResult !== false) {\n throw new Error('The expression must evaluate to true or false');\n }\n }\n });\n return mapping;\n }\n inferAllEncodings (binding, metadata, dom) {\n let mapping = this.getMatchesForBinding(binding, metadata, dom);\n\n // Trash all previous encodings associated with this binding\n if (metadata.encodings) {\n Object.keys(metadata.encodings).forEach(encodingId => {\n if (metadata.encodings[encodingId].bindingId === binding.id) {\n delete metadata.encodings[encodingId];\n }\n });\n } else {\n metadata.encodings = {};\n }\n\n // Create / get cached distribution of values\n let dataDistributions = {};\n let svgDistributions = {};\n mapping.links.forEach(link => {\n Object.keys(link.dataEntry.value).forEach(attr => {\n let value = link.dataEntry.value[attr];\n if (typeof value === 'string' || typeof value === 'number') {\n dataDistributions[attr] = dataDistributions[attr] || {};\n dataDistributions[attr][value] =\n (dataDistributions[attr][value] || 0) + 1;\n }\n });\n\n svgDistributions._tagName = svgDistributions._tagName || {};\n svgDistributions._tagName[link.svgEntry.element.tagName] =\n (svgDistributions._tagName[link.svgEntry.element.tagName] || 0) + 1;\n\n Array.from(link.svgEntry.element.attributes).forEach(attrObj => {\n let attr = attrObj.name;\n let value = link.svgEntry.element.getAttribute(attr);\n if (typeof value === 'string' || typeof value === 'number') {\n svgDistributions[attr] = svgDistributions[attr] || {};\n svgDistributions[attr][value] =\n (svgDistributions[attr][value] || 0) + 1;\n }\n });\n });\n\n // Generate all potential svg constant rules\n // TODO: infer data constants as well if we ever get around to\n // supporting the data cleaning use case\n Object.keys(svgDistributions).forEach(attr => {\n let encoding = this.getEmptyEncoding(metadata, true);\n encoding.bindingId = binding.id;\n encoding.spec.type = this.ENCODING_TYPES.constant;\n encoding.spec.attribute = attr;\n\n // Figure out the bin with the highest count, while calculating the error\n let value = null;\n let maxBinCount = 0;\n let totalCount = 0;\n Object.keys(svgDistributions[attr]).forEach(binLabel => {\n let binCount = svgDistributions[attr][binLabel];\n totalCount += binCount;\n if (binCount > maxBinCount) {\n value = binLabel;\n maxBinCount = binCount;\n }\n });\n encoding.spec.value = value;\n encoding.spec.error = (totalCount - maxBinCount) / totalCount;\n\n // Don't initially enable constants unless they're 100% accurate\n encoding.spec.enabled = encoding.spec.error === 0;\n });\n\n // TODO: generate linear, log, other model rules\n this.saveFile({ metadata });\n }\n}\n\nlet mure = new Mure();\nexport default mure;\n"},"new_file":{"kind":"string","value":"src/mure.js"},"old_contents":{"kind":"string","value":"/* eslint no-useless-escape: 0 */\nimport 'babel-polyfill';\nimport * as d3 from 'd3';\nimport datalib from 'datalib';\nimport md5 from 'md5';\nimport * as jsonpath from 'jsonpath';\nimport PouchDB from 'pouchdb';\nimport { Model } from 'uki';\nimport appList from './appList.json';\nimport mureInteractivityRunnerText from './mureInteractivityRunner.js';\n\nclass Mure extends Model {\n constructor () {\n super();\n this.appList = appList;\n // Check if we're even being used in the browser (mostly useful for getting\n // access to the applist in all-apps-dev-server.js)\n if (typeof document === 'undefined' || typeof window === 'undefined') {\n return;\n }\n\n // Enumerations...\n this.VALID_EVENTS = {\n fileListChange: {},\n fileChange: {},\n domChange: {},\n metadataChange: {},\n error: {}\n };\n\n this.CONTENT_FORMATS = {\n exclude: 0,\n blob: 1,\n dom: 2,\n base64: 3\n };\n\n this.SIGNALS = {\n cancelled: {}\n };\n\n // The namespace string for our custom XML\n this.NSString = 'http://mure-apps.github.io';\n d3.namespaces.mure = this.NSString;\n\n // Funky stuff to figure out if we're debugging (if that's the case, we want to use\n // localhost instead of the github link for all links)\n let windowTitle = document.getElementsByTagName('title')[0];\n windowTitle = windowTitle ? windowTitle.textContent : '';\n this.debugMode = window.location.hostname === 'localhost' && windowTitle.startsWith('Mure');\n\n // Figure out which app we are (or null if the mure library is being used somewhere else)\n this.currentApp = window.location.pathname.replace(/\\//g, '');\n if (!this.appList[this.currentApp]) {\n this.currentApp = null;\n }\n\n // Create / load the local database of files\n this.lastFile = null;\n this.db = this.getOrInitDb();\n\n // default error handling (apps can listen for / display error messages in addition to this):\n this.on('error', errorMessage => {\n console.warn(errorMessage);\n });\n this.catchDbError = errorObj => {\n this.trigger('error', 'Unexpected error reading PouchDB: ' + errorObj.message + '\\n' + errorObj.stack);\n };\n\n // in the absence of a custom dialogs, just use window.alert, window.confirm and window.prompt:\n this.alert = (message) => {\n return new Promise((resolve, reject) => {\n window.alert(message);\n resolve(true);\n });\n };\n this.confirm = (message) => {\n return new Promise((resolve, reject) => {\n resolve(window.confirm(message));\n });\n };\n this.prompt = (message, defaultValue) => {\n return new Promise((resolve, reject) => {\n resolve(window.prompt(message, defaultValue));\n });\n };\n }\n on (eventName, callback) {\n if (!this.VALID_EVENTS[eventName]) {\n throw new Error('Unknown event name: ' + eventName);\n } else {\n super.on(eventName, callback);\n }\n }\n customizeAlertDialog (showDialogFunction) {\n this.alert = showDialogFunction;\n }\n customizeConfirmDialog (showDialogFunction) {\n this.confirm = showDialogFunction;\n }\n customizePromptDialog (showDialogFunction) {\n this.prompt = showDialogFunction;\n }\n openApp (appName, newTab) {\n if (newTab) {\n window.open('/' + appName, '_blank');\n } else {\n window.location.pathname = '/' + appName;\n }\n }\n getOrInitDb () {\n let db = new PouchDB('mure');\n (async () => {\n this.lastFile = null;\n try {\n let prefs = await db.get('userPrefs');\n if (prefs.currentFile) {\n this.lastFile = await this.getFile(prefs.currentFile);\n }\n } catch (errorObj) {\n if (errorObj.message === 'missing') {\n db.put({\n _id: 'userPrefs',\n currentFile: null\n });\n } else {\n this.catchDbError(errorObj);\n }\n }\n })();\n\n db.changes({\n since: 'now',\n live: true,\n include_docs: true\n }).on('change', change => {\n let fileChanged;\n let fileListChanged;\n let domChanged;\n let metadataChanged;\n\n if (change.deleted) {\n if (change.doc._id !== this.lastFile._id) {\n // Weird corner case: if we just deleted a file that wasn't the current one,\n // we won't ever get a change event on the userPrefs object; in that case,\n // we need to trigger the fileListChanged event immediately\n (async () => {\n let fileList = await this.getFileList();\n this.trigger('fileListChange', fileList);\n })().catch(this.catchDbError);\n }\n // Whether or not the deleted file was the currently open one, don't\n // trigger any other events; we want events to fire in context of the\n // new stuff getting loaded below\n return;\n }\n\n let currentFile;\n if (change.doc._id === 'userPrefs') {\n // We just changed the currently open file; trigger all the events\n fileChanged = fileListChanged = domChanged = metadataChanged = true;\n currentFile = this.lastFile;\n } else {\n if (this.lastFile === null || this.lastFile._id !== change.doc._id) {\n // The file itself is changing; DON'T actually trigger any of the events\n // because userPrefs is about to be changed as well... and things listening\n // to changes that care about checking userPrefs will want to do it with\n // its value updated\n fileChanged = fileListChanged = domChanged = metadataChanged = false;\n } else {\n fileChanged = false;\n domChanged = this.lastFile._attachments[this.lastFile._id].digest !==\n change.doc._attachments[change.doc._id].digest;\n metadataChanged = this.lastFile.metadataDigest !== change.doc.metadataDigest;\n }\n this.lastFile = currentFile = change.doc;\n }\n\n if (fileChanged) {\n this.trigger('fileChange', currentFile);\n }\n if (fileListChanged) {\n (async () => {\n let fileList = await this.getFileList();\n this.trigger('fileListChange', fileList);\n })().catch(this.catchDbError);\n }\n if (domChanged) {\n (async () => {\n let blob = currentFile ? await this.getFileAsBlob(currentFile._id) : null;\n this.trigger('domChange', blob);\n })();\n }\n if (metadataChanged) {\n this.trigger('metadataChange', currentFile ? currentFile.metadata : null);\n }\n }).on('error', errorObj => {\n this.catchDbError(errorObj);\n });\n return db;\n }\n async setCurrentFile (filename) {\n return this.db.get('userPrefs').then(prefs => {\n prefs.currentFile = filename;\n return this.db.put(prefs);\n }).catch(this.catchDbError);\n }\n async getFile (filename, contentFormat) {\n if (!filename) {\n filename = await this.getCurrentFilename();\n }\n\n let pouchdbOptions = {};\n if (contentFormat !== this.CONTENT_FORMATS.exclude) {\n pouchdbOptions.attachments = true;\n if (contentFormat === this.CONTENT_FORMATS.blob) {\n pouchdbOptions.binary = true;\n }\n }\n\n if (filename !== null) {\n return this.db.get(filename, pouchdbOptions || {})\n .then(fileObj => {\n if (contentFormat === this.CONTENT_FORMATS.dom) {\n let xmlText = window.atob(fileObj._attachments[fileObj._id].data);\n let dom = new window.DOMParser().parseFromString(xmlText, 'image/svg+xml');\n fileObj._attachments[fileObj._id].dom = dom;\n }\n return fileObj;\n });\n } else {\n return Promise.resolve(null);\n }\n }\n async saveFile (options) {\n try {\n let existingDoc;\n if (!options.blobOrBase64string) {\n existingDoc = await this.getFile(options.filename, this.CONTENT_FORMATS.exclude);\n } else {\n existingDoc = await this.getFile(options.filename, this.CONTENT_FORMATS.blob);\n existingDoc._attachments[options.filename].data = options.blobOrBase64string;\n if ((!options.metadata || Object.keys(options.metadata).length === 0) &&\n Object.keys(existingDoc.metadata) > 0) {\n let userConfirmation = await this.confirm(\n 'It appears that the file you\\'re uploading has lost its Mure metadata. ' +\n 'This is fairly common when you\\'ve edited it with an external program.\\n\\n' +\n 'Restore the most recent metadata?');\n if (!userConfirmation) {\n existingDoc.metadata = {};\n existingDoc.metadataDigest = md5('{}');\n }\n }\n }\n if (options.metadata) {\n existingDoc.metadata = options.metadata;\n existingDoc.metadataDigest = md5(JSON.stringify(options.metadata));\n }\n return this.db.put(existingDoc);\n } catch (errorObj) {\n if (errorObj.message === 'missing') {\n // The file doesn't exist yet...\n let newDoc = {\n _id: options.filename,\n _attachments: {},\n metadata: options.metadata || {},\n metadataDigest: options.metadata ? md5(JSON.stringify(options.metadata)) : md5('{}')\n };\n if (!options.blobOrBase64string) {\n this.trigger('error', 'Attempted to save a file without contents!');\n }\n newDoc._attachments[options.filename] = {\n content_type: 'image/svg+xml',\n data: options.blobOrBase64string\n };\n return this.db.put(newDoc);\n } else {\n this.catchDbError(errorObj);\n return Promise.reject(errorObj);\n }\n }\n }\n async getMetadata (filename) {\n let currentFile = await this.getFile(filename, this.CONTENT_FORMATS.exclude);\n return currentFile !== null ? currentFile.metadata : null;\n }\n async getCurrentFilename () {\n return this.db.get('userPrefs').then(prefs => {\n return prefs.currentFile;\n });\n }\n async getFileList () {\n return this.db.allDocs()\n .then(response => {\n let result = [];\n response.rows.forEach(d => {\n if (d.id !== 'userPrefs') {\n result.push(d.id);\n }\n });\n return result;\n }).catch(this.catchDbError);\n }\n async getFileRevisions () {\n return this.db.allDocs()\n .then(response => {\n let result = {};\n response.rows.forEach(d => {\n if (d.id !== 'userPrefs') {\n result[d.id] = d.value.rev;\n }\n });\n return result;\n }).catch(this.catchDbError);\n }\n async readFile (reader, fileObj) {\n return new Promise((resolve, reject) => {\n reader.onloadend = xmlText => {\n resolve(xmlText.target.result);\n };\n reader.onerror = error => {\n reject(error);\n };\n reader.onabort = () => {\n reject(this.SIGNALS.cancelled);\n };\n reader.readAsText(fileObj);\n });\n }\n async validateFileName (originalName, takenNames, abortFunction) {\n // Ask multiple times if the user happens to enter another filename that already exists\n let filename = originalName;\n while (takenNames[filename]) {\n filename = await this.prompt(\n filename + ' already exists. Pick a new name, or leave it the same to overwrite:',\n filename);\n if (filename === null) {\n if (abortFunction) {\n abortFunction();\n }\n return Promise.reject(this.SIGNALS.cancelled);\n } else if (filename === '') {\n filename = await this.prompt('You must enter a file name (or click cancel to cancel the upload)');\n } else if (filename === originalName) {\n // They left it the same... overwrite!\n return filename;\n }\n }\n return filename;\n }\n inferParser (fileObj) {\n let ext = fileObj.type.split('/')[1];\n if (ext === 'csv') {\n return (contents) => { return datalib.read(contents, {type: 'csv', parse: 'auto'}); };\n } else if (ext === 'tsv') {\n return (contents) => { return datalib.read(contents, {type: 'tsv', parse: 'auto'}); };\n } else if (ext === 'dsv') {\n return (contents) => { return datalib.read(contents, {type: 'dsv', parse: 'auto'}); };\n } else if (ext === 'json') {\n // TODO: attempt to auto-discover topojson or treejson?\n return (contents) => { return datalib.read(contents, {type: 'json', parse: 'auto'}); };\n } else {\n return null;\n }\n }\n async uploadDataset (fileObj) {\n let parser = this.inferParser(fileObj);\n if (!parser) {\n let errorObj = new Error('Unknown data file type: ' + fileObj.type);\n this.trigger('error', errorObj);\n return Promise.reject(errorObj);\n }\n\n let metadata = await this.getMetadata();\n if (metadata === null) {\n let errorObj = new Error('Can\\'t embed a data file without an SVG file already open');\n this.trigger('error', errorObj);\n return Promise.reject(errorObj);\n }\n metadata.datasets = metadata.datasets || {};\n\n let reader = new window.FileReader();\n let dataFileName = await this.validateFileName(fileObj.name, metadata.datasets, reader.abort);\n let fileText = await this.readFile(reader, fileObj);\n\n metadata.datasets[dataFileName] = parser(fileText);\n return this.saveFile({ metadata });\n }\n async uploadSvg (fileObj) {\n let reader = new window.FileReader();\n let contentsPromise = this.readFile(reader, fileObj)\n .then(xmlText => {\n let dom = new window.DOMParser().parseFromString(xmlText, 'image/svg+xml');\n let contents = { metadata: this.extractMetadata(dom) };\n contents.base64data = window.btoa(new window.XMLSerializer().serializeToString(dom));\n return contents;\n });\n\n let filenamePromise = this.getFileRevisions()\n .catch(this.catchDbError)\n .then(revisionDict => {\n return this.validateFileName(fileObj.name, revisionDict, reader.abort);\n });\n\n return Promise.all([filenamePromise, contentsPromise]).then(([filename, contents]) => {\n return this.saveFile({\n filename,\n blobOrBase64string: contents.base64data,\n metadata: contents.metadata\n }).then(() => {\n return this.setCurrentFile(filename);\n });\n }).catch((errList) => {\n if (errList[0] !== this.SIGNALS.cancelled || errList[1] !== this.SIGNALS.cancelled) {\n // cancelling is not a problem; only reject if something else happened\n return Promise.reject(errList);\n }\n });\n }\n async deleteSvg (filename) {\n let userConfirmation = await this.confirm('Are you sure you want to delete ' + filename + '?');\n if (userConfirmation) {\n let currentFile = await this.getFile(filename, this.CONTENT_FORMATS.exclude);\n return this.db.remove(currentFile._id, currentFile._rev)\n .then(removeResponse => {\n if (this.lastFile && filename === this.lastFile._id) {\n return this.setCurrentFile(null).then(() => removeResponse);\n }\n return removeResponse;\n });\n } else {\n return Promise.resolve(false);\n }\n }\n extractMetadata (dom) {\n let self = this;\n let metadata = {};\n let d3dom = d3.select(dom.rootElement);\n\n // Extract the container for our metadata, if it exists\n let root = d3dom.select('#mure');\n if (root.size() === 0) {\n return metadata;\n }\n let nsElement = root.select('mure');\n if (nsElement.size() === 0) {\n return metadata;\n }\n\n // Any libraries?\n nsElement.selectAll('library').each(function (d) {\n if (!metadata.libraries) {\n metadata.libraries = [];\n }\n metadata.libraries.push(d3.select(this).attr('src'));\n });\n\n // Any scripts?\n nsElement.selectAll('script').each(function (d) {\n let el = d3.select(this);\n let script = {\n text: self.extractCDATA(el.text())\n };\n let id = el.attr('id');\n if (id) {\n if (id === 'mureInteractivityRunner') {\n // Don't store our interactivity runner script\n return;\n }\n script.id = id;\n }\n if (!metadata.scripts) {\n metadata.scripts = [];\n }\n metadata.scripts.push(script);\n });\n\n // Any datasets?\n nsElement.selectAll('datasets').each(function (d) {\n let el = d3.select(this);\n if (!metadata.datasets) {\n metadata.datasets = {};\n }\n metadata.datasets[el.attr('name')] = JSON.parse(self.extractCDATA(el.text()));\n });\n\n // Any data bindings?\n nsElement.selectAll('binding').each(function (d) {\n let el = d3.select(this);\n let binding = {\n id: el.attr('id'),\n dataRoot: el.attr('dataroot'),\n svgRoot: el.attr('svgroot'),\n keyFunction: JSON.parse(self.extractCDATA(el.text()))\n };\n\n if (!metadata.bindings) {\n metadata.bindings = {};\n }\n metadata.bindings[binding.id] = binding;\n });\n\n // Any encodings?\n nsElement.selectAll('encoding').each(function (d) {\n let el = d3.select(this);\n let encoding = {\n id: el.attr('id'),\n bindingId: el.attr('for'),\n spec: JSON.parse(self.extractCDATA(el.text()))\n };\n\n if (!metadata.encodings) {\n metadata.encodings = {};\n }\n metadata.encodings[encoding.id] = encoding;\n });\n\n return metadata;\n }\n extractCDATA (str) {\n return str.replace(/(/g, '');\n }\n getEmptyBinding (metadata, add) {\n let id = 1;\n /* eslint-disable no-unmodified-loop-condition */\n while (metadata.bindings && metadata.bindings['Binding' + id]) {\n id++;\n }\n /* eslint-enable no-unmodified-loop-condition */\n let newBinding = {\n id: 'Binding Set ' + id,\n svgRoot: ':root',\n dataRoot: metadata.datasets && Object.keys(metadata.datasets).length > 0\n ? '$[\"' + Object.keys(metadata.datasets)[0] + '\"]' : '',\n keyFunction: {\n expression: '(d, e) => d.key === e.index'\n }\n };\n if (add) {\n if (!metadata.bindings) {\n metadata.bindings = {};\n }\n metadata.bindings[newBinding.id] = newBinding;\n }\n return newBinding;\n }\n getEmptyEncoding (metadata, add) {\n let id = 1;\n /* eslint-disable no-unmodified-loop-condition */\n while (metadata.encodings && metadata.encodings['Encoding' + id]) {\n id++;\n }\n /* eslint-enable no-unmodified-loop-condition */\n let newEncoding = {\n id: 'Encoding' + id,\n bindingId: '',\n spec: {}\n };\n if (add) {\n if (!metadata.encodings) {\n metadata.encodings = {};\n }\n metadata.encodings[newEncoding.id] = newEncoding;\n }\n return newEncoding;\n }\n embedMetadata (dom, metadata) {\n let d3dom = d3.select(dom.rootElement);\n\n // Top: need a metadata tag\n let root = d3dom.selectAll('#mure').data([0]);\n root.exit().remove();\n root = root.enter().append('metadata').attr('id', 'mure').merge(root);\n\n // Next down: a tag to define the namespace\n let nsElement = root.selectAll('mure').data([0]);\n nsElement.exit().remove();\n nsElement = nsElement.enter().append('mure').attr('xmlns', this.NSString).merge(nsElement);\n\n // Okay, we're in our custom namespace... let's figure out the libraries\n let libraryList = metadata.libraries || [];\n let libraries = nsElement.selectAll('library').data(libraryList);\n libraries.exit().remove();\n libraries = libraries.enter().append('library').merge(libraries);\n libraries.attr('src', d => d);\n\n // Let's deal with any user scripts\n let scriptList = metadata.scripts || [];\n let scripts = nsElement.selectAll('script').data(scriptList);\n scripts.exit().remove();\n let scriptsEnter = scripts.enter().append('script');\n scripts = scriptsEnter.merge(scripts);\n scripts.attr('id', d => d.id || null);\n scripts.each(function (d) {\n this.innerHTML = '';\n });\n\n // Remove mureInteractivityRunner by default to ensure it always comes after the\n // metadata tag (of course, only bother adding it if we have any libraries or scripts)\n d3dom.select('#mureInteractivityRunner').remove();\n if (libraryList.length > 0 || scriptList.length > 0) {\n d3dom.append('script')\n .attr('id', 'mureInteractivityRunner')\n .attr('type', 'text/javascript')\n .text(' d.key)\n .html(d => '');\n\n // Store data bindings\n let bindings = nsElement.selectAll('binding').data(d3.values(metadata.bindings || {}));\n bindings.exit().remove();\n let bindingsEnter = bindings.enter().append('binding');\n bindings = bindingsEnter.merge(bindings);\n bindings\n .attr('id', d => d.id)\n .attr('dataroot', d => d.dataRoot)\n .attr('svgroot', d => d.svgRoot)\n .html(d => '');\n\n // Store encoding metadata\n let encodings = nsElement.selectAll('encoding').data(d3.values(metadata.encodings || {}));\n encodings.exit().remove();\n let encodingsEnter = encodings.enter().append('encoding');\n encodings = encodingsEnter.merge(encodings);\n encodings\n .attr('id', d => d.id)\n .attr('bindingid', d => d.bindingId)\n .html(d => '');\n\n return dom;\n }\n async downloadSvg (filename) {\n let fileEntry = await this.getFile(filename, this.CONTENT_FORMATS.dom);\n if (!fileEntry) {\n throw new Error('Can\\'t download non-existent file: ' + filename);\n }\n let dom = this.embedMetadata(fileEntry._attachments[fileEntry._id].dom, fileEntry.metadata);\n let xmlText = new window.XMLSerializer().serializeToString(dom)\n .replace(/&lt;!\\[CDATA\\[/g, '');\n\n // create a fake link to initiate the download\n let a = document.createElement('a');\n a.style = 'display:none';\n let url = window.URL.createObjectURL(new window.Blob([xmlText], { type: 'image/svg+xml' }));\n a.href = url;\n a.download = filename;\n document.body.appendChild(a);\n a.click();\n window.URL.revokeObjectURL(url);\n a.parentNode.removeChild(a);\n }\n matchDataPaths (path1, path2, metadata) {\n if (!metadata || !metadata.datasets || !path1 || !path2) {\n return false;\n }\n let result1 = jsonpath.query(metadata.datasets, path1);\n let result2 = jsonpath.query(metadata.datasets, path2);\n if (result1.length !== 1 || result2.length !== 1) {\n return false;\n }\n return result1[0] === result2[0];\n }\n matchDomSelectors (selector1, selector2, dom) {\n if (!selector1 || !selector2) {\n return false;\n }\n let result1 = dom.querySelector(selector1);\n let result2 = dom.querySelector(selector2);\n return result1 === result2;\n }\n getMatches (metadata, dom) {\n let mapping = [];\n if (metadata && metadata.bindings && metadata.datasets && dom) {\n d3.values(metadata.bindings).forEach(binding => {\n mapping.push(...this.getMatchesForBinding(binding, metadata, dom));\n });\n }\n return mapping;\n }\n getMatchesForBinding (binding, metadata, dom) {\n if (!binding.dataRoot || !binding.svgRoot || !binding.keyFunction) {\n return [];\n }\n\n if (binding.keyFunction.customMapping) {\n return binding.keyFunction.customMapping;\n }\n\n /* eslint-disable no-eval */\n let expression = (0, eval)(binding.keyFunction.expression);\n /* eslint-enable no-eval */\n\n // Need to evaluate the expression for each n^2 possible pairing, and assign\n // mapping the first time the expression is true (but not after!\n // mapping can only be one-to-one!)\n let dataRoot = jsonpath.query(metadata.datasets, binding.dataRoot)[0];\n let dataEntries;\n if (dataRoot instanceof Array) {\n dataEntries = dataRoot.map((d, i) => {\n return {\n key: i,\n value: d\n };\n });\n } else if (typeof dataRoot === 'object') {\n dataEntries = d3.entries(dataRoot);\n } else {\n return; // a leaf was picked as a root... no mapping possible\n }\n\n let svgRoot = dom.querySelector(binding.svgRoot);\n let svgItems = Array.from(svgRoot.children);\n\n let mapping = {\n links: [],\n svgLookup: {},\n dataLookup: {}\n };\n\n dataEntries.forEach(dataEntry => {\n for (let itemIndex = 0; itemIndex < svgItems.length; itemIndex += 1) {\n if (mapping.svgLookup[itemIndex] !== undefined) {\n // this svg element has already been matched with a different dataEntry\n continue;\n }\n let svgEntry = {\n index: itemIndex,\n element: svgItems[itemIndex]\n };\n let expressionResult = null;\n try {\n expressionResult = expression(dataEntry, svgEntry);\n } catch (errorObj) {\n // todo: add interface helpers for debugging the expression\n throw errorObj;\n }\n if (expressionResult === true) {\n mapping.svgLookup[svgEntry.index] = mapping.links.length;\n mapping.dataLookup[dataEntry.key] = mapping.links.length;\n mapping.links.push({\n dataEntry,\n svgEntry\n });\n break;\n } else if (expressionResult !== false) {\n throw new Error('The expression must evaluate to true or false');\n }\n }\n });\n return mapping;\n }\n inferAllEncodings (binding, metadata, dom) {\n let mapping = this.getMatchesForBinding(binding, metadata, dom);\n\n // Create / get cached distribution of values\n let dataDistributions = {};\n let svgDistributions = {};\n mapping.links.forEach(link => {\n Object.keys(link.dataEntry.value).forEach(attr => {\n let value = link.dataEntry.value[attr];\n if (typeof value === 'string' || typeof value === 'number') {\n dataDistributions[attr] = dataDistributions[attr] || {};\n dataDistributions[attr][value] =\n (dataDistributions[attr][value] || 0) + 1;\n }\n });\n\n svgDistributions._tagName = svgDistributions._tagName || {};\n svgDistributions._tagName[link.svgEntry.element.tagName] =\n (svgDistributions._tagName[link.svgEntry.element.tagName] || 0) + 1;\n\n Array.from(link.svgEntry.element.attributes).forEach(attrObj => {\n let attr = attrObj.name;\n let value = link.svgEntry.element.getAttribute(attr);\n if (typeof value === 'string' || typeof value === 'number') {\n svgDistributions[attr] = svgDistributions[attr] || {};\n svgDistributions[attr][value] =\n (svgDistributions[attr][value] || 0) + 1;\n }\n });\n });\n\n let quantitativePool = {};\n let categoricalPool = {};\n }\n}\n\nlet mure = new Mure();\nexport default mure;\n"},"message":{"kind":"string","value":"Learn constant constraints (not really \"encodings\" yet)\n"},"old_file":{"kind":"string","value":"src/mure.js"},"subject":{"kind":"string","value":"Learn constant constraints (not really \"encodings\" yet)"},"git_diff":{"kind":"string","value":"rc/mure.js\n \n this.SIGNALS = {\n cancelled: {}\n };\n\n this.ENCODING_TYPES = {\n constant: 0\n };\n \n // The namespace string for our custom XML\n getEmptyBinding (metadata, add) {\n let id = 1;\n /* eslint-disable no-unmodified-loop-condition */\n while (metadata.bindings && metadata.bindings['Binding' + id]) {\n while (metadata.bindings && metadata.bindings['Binding Set ' + id]) {\n id++;\n }\n /* eslint-enable no-unmodified-loop-condition */\n getEmptyEncoding (metadata, add) {\n let id = 1;\n /* eslint-disable no-unmodified-loop-condition */\n while (metadata.encodings && metadata.encodings['Encoding' + id]) {\n while (metadata.encodings && metadata.encodings['Encoding ' + id]) {\n id++;\n }\n /* eslint-enable no-unmodified-loop-condition */\n let newEncoding = {\n id: 'Encoding' + id,\n id: 'Encoding ' + id,\n bindingId: '',\n spec: {}\n };\n inferAllEncodings (binding, metadata, dom) {\n let mapping = this.getMatchesForBinding(binding, metadata, dom);\n \n // Trash all previous encodings associated with this binding\n if (metadata.encodings) {\n Object.keys(metadata.encodings).forEach(encodingId => {\n if (metadata.encodings[encodingId].bindingId === binding.id) {\n delete metadata.encodings[encodingId];\n }\n });\n } else {\n metadata.encodings = {};\n }\n\n // Create / get cached distribution of values\n let dataDistributions = {};\n let svgDistributions = {};\n });\n });\n \n let quantitativePool = {};\n let categoricalPool = {};\n // Generate all potential svg constant rules\n // TODO: infer data constants as well if we ever get around to\n // supporting the data cleaning use case\n Object.keys(svgDistributions).forEach(attr => {\n let encoding = this.getEmptyEncoding(metadata, true);\n encoding.bindingId = binding.id;\n encoding.spec.type = this.ENCODING_TYPES.constant;\n encoding.spec.attribute = attr;\n\n // Figure out the bin with the highest count, while calculating the error\n let value = null;\n let maxBinCount = 0;\n let totalCount = 0;\n Object.keys(svgDistributions[attr]).forEach(binLabel => {\n let binCount = svgDistributions[attr][binLabel];\n totalCount += binCount;\n if (binCount > maxBinCount) {\n value = binLabel;\n maxBinCount = binCount;\n }\n });\n encoding.spec.value = value;\n encoding.spec.error = (totalCount - maxBinCount) / totalCount;\n\n // Don't initially enable constants unless they're 100% accurate\n encoding.spec.enabled = encoding.spec.error === 0;\n });\n\n // TODO: generate linear, log, other model rules\n this.saveFile({ metadata });\n }\n }\n "}}},{"rowIdx":871,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"ea07ff5ce778a78249039d9f84c1dbab4856ebc4"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"googleinterns/step188-2020,googleinterns/step188-2020,googleinterns/step188-2020"},"new_contents":{"kind":"string","value":"package com.google.sps.utilities;\n\nimport com.google.cloud.Date;\nimport com.google.sps.data.Event;\nimport com.google.sps.data.User;\nimport com.google.sps.data.OpportunitySignup;\nimport com.google.sps.data.User;\nimport com.google.sps.data.VolunteeringOpportunity;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.Set;\nimport java.util.UUID;\n\n/* Class containing utilities for testing. */\npublic class TestUtils {\n private static final String NAME = \"Bob Smith\";\n private static final String EMAIL = \"bobsmith@example.com\";\n private static final String EVENT_NAME = \"Team Meeting\";\n private static final String DESCRIPTION = \"Daily Team Sync\";\n private static final Set LABELS =\n Collections.unmodifiableSet(new HashSet<>(Arrays.asList(\"Tech\", \"Work\")));\n private static final String LOCATION = \"Remote\";\n private static final Date DATE = Date.fromYearMonthDay(2016, 9, 15);\n private static final String DATE_STRING = \"09/15/2016\";\n private static final String TIME = \"3:00PM-5:00PM\";\n private static final User HOST = new User.Builder(NAME, EMAIL).build();\n private static final String EVENT_ID = \"0883de79-17d7-49a3-a866-dbd5135062a8\";\n private static final String OPPORTUNITY_NAME = \"Performer\";\n private static final int NUMBER_OF_SPOTS = 240;\n private static final String VOLUNTEER_EMAIL = \"volunteer@gmail.com\";\n \n private static final Set INTERESTS =\n Collections.unmodifiableSet(new HashSet<>(Arrays.asList(\"Conservation\", \"Food\")));\n private static final Set SKILLS =\n Collections.unmodifiableSet(new HashSet<>(Arrays.asList(\"Cooking\")));\n\n /*\n * Returns a new Event object with the given user as host.\n * @param user host to be used to create a Event object\n * @return an event with given user as host\n */\n public static Event newEventWithHost(User user) {\n return new Event.Builder(EVENT_NAME, DESCRIPTION, LABELS, LOCATION, DATE, TIME, user).build();\n }\n\n /** Returns a new VolunteeringOpportunity object with arbitrary parameters. */\n public static VolunteeringOpportunity newVolunteeringOpportunity() {\n return new VolunteeringOpportunity.Builder(EVENT_ID, OPPORTUNITY_NAME, NUMBER_OF_SPOTS).build();\n }\n\n /*\n * Returns a new VolunteeringOpportunity object with the given eventId.\n * @param eventId event ID used to create a VolunteeringOpportunity object\n * @return a volunteering opportunity with the given event ID\n */\n public static VolunteeringOpportunity newVolunteeringOpportunityWithEventId(String eventId) {\n return new VolunteeringOpportunity.Builder(eventId, OPPORTUNITY_NAME, NUMBER_OF_SPOTS).build();\n }\n\n /*\n * Returns a new OpportunitySignup object with the given opportunityId.\n * @param opportunityId opportunity ID to create an OpportunitySignup object\n * @return an opportunity signup with given opportunity ID\n */\n public static OpportunitySignup newOpportunitySignupWithOpportunityId(String opportunityId) {\n return new OpportunitySignup.Builder(opportunityId, VOLUNTEER_EMAIL).build();\n }\n \n /** Returns a new User object with arbitrary attributes. */\n public static User newUser() {\n return new User.Builder(NAME, EMAIL).setInterests(INTERESTS).setSkills(SKILLS).build();\n }\n\n /** Returns a new User object with arbitrary attributes and given email. */\n public static User newUserWithEmail(String email) {\n return new User.Builder(NAME, email).setInterests(INTERESTS).setSkills(SKILLS).build();\n }\n \n /** Returns a random ID. */\n public static String newRandomId() {\n return UUID.randomUUID().toString();\n }\n}\n"},"new_file":{"kind":"string","value":"project/src/main/java/com/google/sps/utilities/TestUtils.java"},"old_contents":{"kind":"string","value":"package com.google.sps.utilities;\n\nimport com.google.cloud.Date;\nimport com.google.sps.data.Event;\nimport com.google.sps.data.User;\nimport com.google.sps.data.OpportunitySignup;\nimport com.google.sps.data.User;\nimport com.google.sps.data.VolunteeringOpportunity;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.Set;\nimport java.util.UUID;\n\n/* Class containing utilities for testing. */\npublic class TestUtils {\n private static final String NAME = \"Bob Smith\";\n private static final String EMAIL = \"bobsmith@example.com\";\n private static final String EVENT_NAME = \"Team Meeting\";\n private static final String DESCRIPTION = \"Daily Team Sync\";\n private static final Set LABELS =\n Collections.unmodifiableSet(new HashSet<>(Arrays.asList(\"Tech\", \"Work\")));\n private static final String LOCATION = \"Remote\";\n private static final Date DATE = Date.fromYearMonthDay(2016, 9, 15);\n private static final String DATE_STRING = \"09/15/2016\";\n private static final String TIME = \"3:00PM-5:00PM\";\n private static final User HOST = new User.Builder(NAME, EMAIL).build();\n private static final String EVENT_ID = \"0883de79-17d7-49a3-a866-dbd5135062a8\";\n private static final String OPPORTUNITY_NAME = \"Performer\";\n private static final int NUMBER_OF_SPOTS = 240;\n private static final String VOLUNTEER_EMAIL = \"volunteer@gmail.com\";\n \n private static final Set INTERESTS =\n Collections.unmodifiableSet(new HashSet<>(Arrays.asList(\"Conservation\", \"Food\")));\n private static final Set SKILLS =\n Collections.unmodifiableSet(new HashSet<>(Arrays.asList(\"Cooking\")));\n\n /*\n * Returns a new Event object with the given user as host.\n * @param user host to be used to create a Event object\n * @return an event with given user as host\n */\n public static Event newEventWithHost(User user) {\n return new Event.Builder(EVENT_NAME, DESCRIPTION, LABELS, LOCATION, DATE, TIME, user).build();\n }\n\n /** Returns a new VolunteeringOpportunity object with arbitrary parameters. */\n public static VolunteeringOpportunity newVolunteeringOpportunity() {\n return new VolunteeringOpportunity.Builder(EVENT_ID, OPPORTUNITY_NAME, NUMBER_OF_SPOTS).build();\n }\n\n /*\n * Returns a new VolunteeringOpportunity object with the given eventId.\n * @param eventId event ID used to create a VolunteeringOpportunity object\n * @return a volunteering opportunity with the given event ID\n */\n public static VolunteeringOpportunity newVolunteeringOpportunityWithEventId(String eventId) {\n return new VolunteeringOpportunity.Builder(eventId, OPPORTUNITY_NAME, NUMBER_OF_SPOTS).build();\n }\n\n /*\n * Returns a new OpportunitySignup object with the given opportunityId.\n * @param opportunityId opportunity ID to create an OpportunitySignup object\n * @return an opportunity signup with given opportunity ID\n */\n public static OpportunitySignup newOpportunitySignupWithOpportunityId(String opportunityId) {\n return new OpportunitySignup.Builder(opportunityId, VOLUNTEER_EMAIL).build();\n }\n \n /** Returns a new User object with arbitrary attributes. */\n public static User newUser(String email) {\n return new User.Builder(USER_NAME, email).setInterests(INTERESTS).setSkills(SKILLS).build();\n }\n \n /** Returns a random ID. */\n public static String newRandomId() {\n return UUID.randomUUID().toString();\n }\n}\n"},"message":{"kind":"string","value":"Fix newUser definitions\n"},"old_file":{"kind":"string","value":"project/src/main/java/com/google/sps/utilities/TestUtils.java"},"subject":{"kind":"string","value":"Fix newUser definitions"},"git_diff":{"kind":"string","value":"roject/src/main/java/com/google/sps/utilities/TestUtils.java\n }\n \n /** Returns a new User object with arbitrary attributes. */\n public static User newUser(String email) {\n return new User.Builder(USER_NAME, email).setInterests(INTERESTS).setSkills(SKILLS).build();\n public static User newUser() {\n return new User.Builder(NAME, EMAIL).setInterests(INTERESTS).setSkills(SKILLS).build();\n }\n\n /** Returns a new User object with arbitrary attributes and given email. */\n public static User newUserWithEmail(String email) {\n return new User.Builder(NAME, email).setInterests(INTERESTS).setSkills(SKILLS).build();\n }\n \n /** Returns a random ID. */"}}},{"rowIdx":872,"cells":{"lang":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"71bab2f615eb21ca04e973d62a7046fb836c6722"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"jccazeaux/rivets,re-clone/rivets,zongkelong/rivets,GerHobbelt/rivets,zongkelong/rivets,altmind/rivets,mikeric/rivets,GerHobbelt/rivets,benderTheCrime/tiny-rivets,jccazeaux/rivets,moneyadviceservice/rivets,QAPInt/rivets,MishaMykhalyuk/rivets,GerHobbelt/rivets,altmind/rivets,kangax/rivets,QAPInt/rivets,MishaMykhalyuk/rivets,re-clone/rivets,mikeric/rivets,nopnop/rivets,zongkelong/rivets,nopnop/rivets,npmcomponent/mikeric-rivets,jccazeaux/rivets,mikeric/rivets,re-clone/rivets,nopnop/rivets,altmind/rivets,QAPInt/rivets,MishaMykhalyuk/rivets"},"new_contents":{"kind":"string","value":"describe('Rivets.Binding', function() {\n var model, el, view, binding;\n\n beforeEach(function() {\n rivets.configure({\n adapter: {\n subscribe: function() {},\n unsubscribe: function() {},\n read: function() {},\n publish: function() {}\n }\n });\n\n el = document.createElement('div');\n el.setAttribute('data-text', 'obj.name');\n view = rivets.bind(el, {obj: {}});\n binding = view.bindings[0];\n model = binding.model;\n });\n\n it('gets assigned the routine function matching the identifier', function() {\n expect(binding.routine).toBe(rivets.routines.text);\n });\n\n describe('bind()', function() {\n it('subscribes to the model for changes via the adapter', function() {\n spyOn(rivets.config.adapter, 'subscribe');\n binding.bind();\n expect(rivets.config.adapter.subscribe).toHaveBeenCalledWith(model, 'name', binding.set);\n });\n\n describe('with preloadData set to true', function() {\n beforeEach(function() {\n rivets.config.preloadData = true;\n });\n\n it('sets the initial value via the adapter', function() {\n spyOn(binding, 'set');\n spyOn(rivets.config.adapter, 'read');\n binding.bind();\n expect(rivets.config.adapter.read).toHaveBeenCalledWith(model, 'name');\n expect(binding.set).toHaveBeenCalled();\n });\n });\n\n describe('with the bypass option set to true', function() {\n beforeEach(function() {\n binding.options.bypass = true;\n });\n\n it('sets the initial value from the model directly', function() {\n spyOn(binding, 'set');\n binding.model.name = 'espresso';\n binding.bind();\n expect(binding.set).toHaveBeenCalledWith('espresso');\n });\n });\n\n describe('with dependencies', function() {\n beforeEach(function() {\n binding.options.dependencies = ['fname', 'lname'];\n });\n\n it('sets up observers on the dependant attributes', function() {\n spyOn(rivets.config.adapter, 'subscribe');\n binding.bind();\n expect(rivets.config.adapter.subscribe).toHaveBeenCalledWith(model, 'fname', binding.dependencyCallbacks['fname']);\n expect(rivets.config.adapter.subscribe).toHaveBeenCalledWith(model, 'lname', binding.dependencyCallbacks['lname']);\n });\n });\n });\n\n describe('set()', function() {\n it('performs the binding routine with the supplied value', function() {\n spyOn(binding, 'routine');\n binding.set('sweater');\n expect(binding.routine).toHaveBeenCalledWith(el, 'sweater');\n });\n\n it('applies any formatters to the value before performing the routine', function() {\n rivets.config.formatters = {\n awesome: function(value) { return 'awesome ' + value }\n };\n binding.formatters.push('awesome');\n spyOn(binding, 'routine');\n binding.set('sweater');\n expect(binding.routine).toHaveBeenCalledWith(el, 'awesome sweater');\n });\n\n describe('on an event binding', function() {\n beforeEach(function() {\n binding.options.special = 'event';\n });\n\n it('performs the binding routine with the supplied function and current listener', function() {\n spyOn(binding, 'routine');\n func = function() { return 1 + 2; }\n binding.set(func);\n expect(binding.routine).toHaveBeenCalledWith(el, func, undefined);\n });\n\n it('passes the previously set funcation as the current listener on subsequent calls', function() {\n spyOn(binding, 'routine');\n funca = function() { return 1 + 2; };\n funcb = function() { return 2 + 5; };\n\n binding.set(funca);\n expect(binding.routine).toHaveBeenCalledWith(el, funca, undefined);\n\n binding.set(funcb);\n expect(binding.routine).toHaveBeenCalledWith(el, funcb, funca);\n });\n });\n });\n \n describe('publish()', function() {\n it(\"should publish the value of a number input\", function() {\n numberInput = document.createElement('input');\n numberInput.setAttribute('type', 'number');\n numberInput.setAttribute('data-value', 'obj.num');\n \n view = rivets.bind(numberInput, {obj: {num: 42}});\n binding = view.bindings[0];\n model = binding.model;\n\n numberInput.value = 42;\n \n spyOn(rivets.config.adapter, 'publish');\n binding.publish({target: numberInput});\n expect(rivets.config.adapter.publish).toHaveBeenCalledWith(model, 'num', '42');\n });\n });\n\n describe('formattedValue()', function() {\n it('applies the current formatters on the supplied value', function() {\n rivets.config.formatters = {\n awesome: function(value) { return 'awesome ' + value }\n };\n binding.formatters.push('awesome');\n expect(binding.formattedValue('hat')).toBe('awesome hat');\n });\n \n it('uses formatters on the model', function() {\n model.modelAwesome = function(value) { return 'model awesome ' + value };\n binding.formatters.push('modelAwesome');\n expect(binding.formattedValue('hat')).toBe('model awesome hat');\n });\n\n describe('with a multi-argument formatter string', function() {\n beforeEach(function() {\n rivets.config.formatters = {\n awesome: function(value, prefix) {\n return prefix + ' awesome ' + value;\n }\n };\n binding.formatters.push('awesome super');\n });\n \n it('applies the formatter with arguments', function() {\n expect(binding.formattedValue('jacket')).toBe('super awesome jacket');\n });\n });\n });\n});\n"},"new_file":{"kind":"string","value":"spec/rivets/binding.js"},"old_contents":{"kind":"string","value":"describe('Rivets.Binding', function() {\n var model, el, view, binding;\n\n beforeEach(function() {\n rivets.configure({\n adapter: {\n subscribe: function() {},\n unsubscribe: function() {},\n read: function() {},\n publish: function() {}\n }\n });\n\n el = document.createElement('div');\n el.setAttribute('data-text', 'obj.name');\n view = rivets.bind(el, {obj: {}});\n binding = view.bindings[0];\n model = binding.model;\n });\n\n it('gets assigned the routine function matching the identifier', function() {\n expect(binding.routine).toBe(rivets.routines.text);\n });\n\n describe('bind()', function() {\n it('subscribes to the model for changes via the adapter', function() {\n spyOn(rivets.config.adapter, 'subscribe');\n binding.bind();\n expect(rivets.config.adapter.subscribe).toHaveBeenCalled();\n });\n\n describe('with preloadData set to true', function() {\n beforeEach(function() {\n rivets.config.preloadData = true;\n });\n\n it('sets the initial value via the adapter', function() {\n spyOn(binding, 'set');\n spyOn(rivets.config.adapter, 'read');\n binding.bind();\n expect(binding.set).toHaveBeenCalled();\n expect(rivets.config.adapter.read).toHaveBeenCalled();\n });\n });\n\n describe('with the bypass option set to true', function() {\n beforeEach(function() {\n binding.options.bypass = true;\n });\n\n it('sets the initial value from the model directly', function() {\n spyOn(binding, 'set');\n binding.model.name = 'espresso';\n binding.bind();\n expect(binding.set).toHaveBeenCalledWith('espresso');\n });\n });\n });\n\n describe('set()', function() {\n it('performs the binding routine with the supplied value', function() {\n spyOn(binding, 'routine');\n binding.set('sweater');\n expect(binding.routine).toHaveBeenCalledWith(el, 'sweater');\n });\n\n it('applies any formatters to the value before performing the routine', function() {\n rivets.config.formatters = {\n awesome: function(value) { return 'awesome ' + value }\n };\n binding.formatters.push('awesome');\n spyOn(binding, 'routine');\n binding.set('sweater');\n expect(binding.routine).toHaveBeenCalledWith(el, 'awesome sweater');\n });\n\n describe('on an event binding', function() {\n beforeEach(function() {\n binding.options.special = 'event';\n });\n\n it('performs the binding routine with the supplied function and current listener', function() {\n spyOn(binding, 'routine');\n func = function() { return 1 + 2; }\n binding.set(func);\n expect(binding.routine).toHaveBeenCalledWith(el, func, undefined);\n });\n\n it('passes the previously set funcation as the current listener on subsequent calls', function() {\n spyOn(binding, 'routine');\n funca = function() { return 1 + 2; };\n funcb = function() { return 2 + 5; };\n\n binding.set(funca);\n expect(binding.routine).toHaveBeenCalledWith(el, funca, undefined);\n\n binding.set(funcb);\n expect(binding.routine).toHaveBeenCalledWith(el, funcb, funca);\n });\n });\n });\n \n describe('publish()', function() {\n it(\"should publish the value of a number input\", function() {\n numberInput = document.createElement('input');\n numberInput.setAttribute('type', 'number');\n numberInput.setAttribute('data-value', 'obj.num');\n \n view = rivets.bind(numberInput, {obj: {num: 42}});\n binding = view.bindings[0];\n model = binding.model;\n\n numberInput.value = 42;\n \n spyOn(rivets.config.adapter, 'publish');\n binding.publish({target: numberInput});\n expect(rivets.config.adapter.publish).toHaveBeenCalledWith(model, 'num', '42');\n });\n });\n\n describe('formattedValue()', function() {\n it('applies the current formatters on the supplied value', function() {\n rivets.config.formatters = {\n awesome: function(value) { return 'awesome ' + value }\n };\n binding.formatters.push('awesome');\n expect(binding.formattedValue('hat')).toBe('awesome hat');\n });\n \n it('uses formatters on the model', function() {\n model.modelAwesome = function(value) { return 'model awesome ' + value };\n binding.formatters.push('modelAwesome');\n expect(binding.formattedValue('hat')).toBe('model awesome hat');\n });\n\n describe('with a multi-argument formatter string', function() {\n beforeEach(function() {\n rivets.config.formatters = {\n awesome: function(value, prefix) {\n return prefix + ' awesome ' + value;\n }\n };\n binding.formatters.push('awesome super');\n });\n \n it('applies the formatter with arguments', function() {\n expect(binding.formattedValue('jacket')).toBe('super awesome jacket');\n });\n });\n });\n});\n"},"message":{"kind":"string","value":"Add initial spec for binding with dependent attributes.\n"},"old_file":{"kind":"string","value":"spec/rivets/binding.js"},"subject":{"kind":"string","value":"Add initial spec for binding with dependent attributes."},"git_diff":{"kind":"string","value":"pec/rivets/binding.js\n it('subscribes to the model for changes via the adapter', function() {\n spyOn(rivets.config.adapter, 'subscribe');\n binding.bind();\n expect(rivets.config.adapter.subscribe).toHaveBeenCalled();\n expect(rivets.config.adapter.subscribe).toHaveBeenCalledWith(model, 'name', binding.set);\n });\n \n describe('with preloadData set to true', function() {\n spyOn(binding, 'set');\n spyOn(rivets.config.adapter, 'read');\n binding.bind();\n expect(rivets.config.adapter.read).toHaveBeenCalledWith(model, 'name');\n expect(binding.set).toHaveBeenCalled();\n expect(rivets.config.adapter.read).toHaveBeenCalled();\n });\n });\n \n binding.model.name = 'espresso';\n binding.bind();\n expect(binding.set).toHaveBeenCalledWith('espresso');\n });\n });\n\n describe('with dependencies', function() {\n beforeEach(function() {\n binding.options.dependencies = ['fname', 'lname'];\n });\n\n it('sets up observers on the dependant attributes', function() {\n spyOn(rivets.config.adapter, 'subscribe');\n binding.bind();\n expect(rivets.config.adapter.subscribe).toHaveBeenCalledWith(model, 'fname', binding.dependencyCallbacks['fname']);\n expect(rivets.config.adapter.subscribe).toHaveBeenCalledWith(model, 'lname', binding.dependencyCallbacks['lname']);\n });\n });\n });"}}},{"rowIdx":873,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"bsd-3-clause"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"261b0f4e9baa82ebc873eee9c149ff810e853c7d"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"NCIP/rembrandt,NCIP/rembrandt,NCIP/rembrandt,NCIP/rembrandt,NCIP/rembrandt,NCIP/rembrandt"},"new_contents":{"kind":"string","value":"package gov.nih.nci.rembrandt.web.struts.action;\n\nimport gov.nih.nci.caintegrator.application.lists.UserList;\nimport gov.nih.nci.caintegrator.application.util.ClassHelper;\nimport gov.nih.nci.caintegrator.dto.de.ArrayPlatformDE;\nimport gov.nih.nci.caintegrator.dto.de.MultiGroupComparisonAdjustmentTypeDE;\nimport gov.nih.nci.caintegrator.dto.de.StatisticTypeDE;\nimport gov.nih.nci.caintegrator.dto.de.StatisticalSignificanceDE;\nimport gov.nih.nci.caintegrator.dto.de.ExprFoldChangeDE.UpRegulation;\nimport gov.nih.nci.caintegrator.dto.query.ClassComparisonQueryDTO;\nimport gov.nih.nci.caintegrator.dto.query.ClinicalQueryDTO;\nimport gov.nih.nci.caintegrator.dto.query.QueryType;\nimport gov.nih.nci.caintegrator.enumeration.MultiGroupComparisonAdjustmentType;\nimport gov.nih.nci.caintegrator.enumeration.Operator;\nimport gov.nih.nci.caintegrator.enumeration.StatisticalMethodType;\nimport gov.nih.nci.caintegrator.enumeration.StatisticalSignificanceType;\nimport gov.nih.nci.caintegrator.exceptions.FrameworkException;\nimport gov.nih.nci.caintegrator.security.UserCredentials;\nimport gov.nih.nci.caintegrator.service.findings.Finding;\nimport gov.nih.nci.rembrandt.dto.query.PatientUserListQueryDTO;\n\n\nimport gov.nih.nci.rembrandt.cache.RembrandtPresentationTierCache;\nimport gov.nih.nci.rembrandt.dto.query.ClinicalDataQuery;\nimport gov.nih.nci.rembrandt.service.findings.RembrandtFindingsFactory;\nimport gov.nih.nci.rembrandt.util.RembrandtConstants;\nimport gov.nih.nci.rembrandt.web.bean.SessionQueryBag;\nimport gov.nih.nci.rembrandt.web.factory.ApplicationFactory;\nimport gov.nih.nci.rembrandt.web.helper.GroupRetriever;\nimport gov.nih.nci.rembrandt.web.helper.EnumCaseChecker;\nimport gov.nih.nci.rembrandt.web.helper.SampleBasedQueriesRetriever;\nimport gov.nih.nci.rembrandt.web.struts.form.ClassComparisonForm;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport javax.servlet.http.HttpSession;\n\nimport org.apache.log4j.Logger;\nimport org.apache.struts.action.ActionForm;\nimport org.apache.struts.action.ActionForward;\nimport org.apache.struts.action.ActionMapping;\nimport org.apache.struts.actions.DispatchAction;\n\n\n\n/**\n* caIntegrator License\n* \n* Copyright 2001-2005 Science Applications International Corporation (\"SAIC\"). \n* The software subject to this notice and license includes both human readable source code form and machine readable, \n* binary, object code form (\"the caIntegrator Software\"). The caIntegrator Software was developed in conjunction with \n* the National Cancer Institute (\"NCI\") by NCI employees and employees of SAIC. \n* To the extent government employees are authors, any rights in such works shall be subject to Title 17 of the United States\n* Code, section 105. \n* This caIntegrator Software License (the \"License\") is between NCI and You. \"You (or \"Your\") shall mean a person or an \n* entity, and all other entities that control, are controlled by, or are under common control with the entity. \"Control\" \n* for purposes of this definition means (i) the direct or indirect power to cause the direction or management of such entity,\n* whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) \n* beneficial ownership of such entity. \n* This License is granted provided that You agree to the conditions described below. NCI grants You a non-exclusive, \n* worldwide, perpetual, fully-paid-up, no-charge, irrevocable, transferable and royalty-free right and license in its rights \n* in the caIntegrator Software to (i) use, install, access, operate, execute, copy, modify, translate, market, publicly \n* display, publicly perform, and prepare derivative works of the caIntegrator Software; (ii) distribute and have distributed \n* to and by third parties the caIntegrator Software and any modifications and derivative works thereof; \n* and (iii) sublicense the foregoing rights set out in (i) and (ii) to third parties, including the right to license such \n* rights to further third parties. For sake of clarity, and not by way of limitation, NCI shall have no right of accounting\n* or right of payment from You or Your sublicensees for the rights granted under this License. This License is granted at no\n* charge to You. \n* 1. Your redistributions of the source code for the Software must retain the above copyright notice, this list of conditions\n* and the disclaimer and limitation of liability of Article 6, below. Your redistributions in object code form must reproduce \n* the above copyright notice, this list of conditions and the disclaimer of Article 6 in the documentation and/or other materials\n* provided with the distribution, if any. \n* 2. Your end-user documentation included with the redistribution, if any, must include the following acknowledgment: \"This \n* product includes software developed by SAIC and the National Cancer Institute.\" If You do not include such end-user \n* documentation, You shall include this acknowledgment in the Software itself, wherever such third-party acknowledgments \n* normally appear.\n* 3. You may not use the names \"The National Cancer Institute\", \"NCI\" \"Science Applications International Corporation\" and \n* \"SAIC\" to endorse or promote products derived from this Software. This License does not authorize You to use any \n* trademarks, service marks, trade names, logos or product names of either NCI or SAIC, except as required to comply with\n* the terms of this License. \n* 4. For sake of clarity, and not by way of limitation, You may incorporate this Software into Your proprietary programs and \n* into any third party proprietary programs. However, if You incorporate the Software into third party proprietary \n* programs, You agree that You are solely responsible for obtaining any permission from such third parties required to \n* incorporate the Software into such third party proprietary programs and for informing Your sublicensees, including \n* without limitation Your end-users, of their obligation to secure any required permissions from such third parties \n* before incorporating the Software into such third party proprietary software programs. In the event that You fail \n* to obtain such permissions, You agree to indemnify NCI for any claims against NCI by such third parties, except to \n* the extent prohibited by law, resulting from Your failure to obtain such permissions. \n* 5. For sake of clarity, and not by way of limitation, You may add Your own copyright statement to Your modifications and \n* to the derivative works, and You may provide additional or different license terms and conditions in Your sublicenses \n* of modifications of the Software, or any derivative works of the Software as a whole, provided Your use, reproduction, \n* and distribution of the Work otherwise complies with the conditions stated in this License.\n* 6. THIS SOFTWARE IS PROVIDED \"AS IS,\" AND ANY EXPRESSED OR IMPLIED WARRANTIES, (INCLUDING, BUT NOT LIMITED TO, \n* THE IMPLIED WARRANTIES OF MERCHANTABILITY, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED. \n* IN NO EVENT SHALL THE NATIONAL CANCER INSTITUTE, SAIC, OR THEIR AFFILIATES BE LIABLE FOR ANY DIRECT, INDIRECT, \n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE \n* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF \n* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT \n* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n* \n*/\n\npublic class ClassComparisonAction extends DispatchAction {\n\t\n\tprivate UserCredentials credentials; \n\tprivate static Logger logger = Logger.getLogger(ClassComparisonAction.class);\n private RembrandtPresentationTierCache presentationTierCache = ApplicationFactory.getPresentationTierCache();\n /***\n * These are the default error values used when an invalid enum type\n * parameter has been passed to the action. These default values should\n * be verified as useful in all cases.\n */\n private MultiGroupComparisonAdjustmentType ERROR_MULTI_GROUP_COMPARE_ADJUSTMENT_TYPE = MultiGroupComparisonAdjustmentType.FWER;\n private StatisticalMethodType ERROR_STATISTICAL_METHOD_TYPE = StatisticalMethodType.TTest;\n /**\n * Method submittal\n * \n * @param ActionMapping\n * mapping\n * @param ActionForm\n * form\n * @param HttpServletRequest\n * request\n * @param HttpServletResponse\n * response\n * @return ActionForward\n * @throws Exception\n */\n public ActionForward submit(ActionMapping mapping, ActionForm form,\n HttpServletRequest request, HttpServletResponse response)\n throws Exception {\n ClassComparisonForm classComparisonForm = (ClassComparisonForm) form;\n String sessionId = request.getSession().getId();\n ClassComparisonQueryDTO classComparisonQueryDTO = createClassComparisonQueryDTO(classComparisonForm,request.getSession());\n \n /*Create the InstituteDEs using credentials from the local session.\n * May want to put these in the cache eventually.\n */ \n if(request.getSession().getAttribute(RembrandtConstants.USER_CREDENTIALS)!=null){\n credentials = (UserCredentials) request.getSession().getAttribute(RembrandtConstants.USER_CREDENTIALS);\n classComparisonQueryDTO.setInstitutionDEs(credentials.getInstitutes());\n }\n if (classComparisonQueryDTO!=null) {\n SessionQueryBag queryBag = presentationTierCache.getSessionQueryBag(sessionId);\n queryBag.putQueryDTO(classComparisonQueryDTO, classComparisonForm);\n presentationTierCache.putSessionQueryBag(sessionId, queryBag);\n } \n \n RembrandtFindingsFactory factory = new RembrandtFindingsFactory();\n Finding finding = null;\n try {\n finding = factory.createClassComparisonFinding(classComparisonQueryDTO,sessionId,classComparisonQueryDTO.getQueryName());\n } catch (FrameworkException e) {\n e.printStackTrace();\n }\n \n return mapping.findForward(\"viewResults\");\n }\n \n public ActionForward setup(ActionMapping mapping, ActionForm form,\n HttpServletRequest request, HttpServletResponse response)\n throws Exception {\n ClassComparisonForm classComparisonForm = (ClassComparisonForm) form;\n /*setup the defined Disease query names and the list of samples selected from a Resultset*/ \n GroupRetriever groupRetriever = new GroupRetriever();\n classComparisonForm.setExistingGroupsList(groupRetriever.getClinicalGroupsCollection(request.getSession()));\n \n return mapping.findForward(\"backToClassComparison\");\n }\n \n private ClassComparisonQueryDTO createClassComparisonQueryDTO(ClassComparisonForm classComparisonQueryForm, HttpSession session){\n\n ClassComparisonQueryDTO classComparisonQueryDTO = (ClassComparisonQueryDTO)ApplicationFactory.newQueryDTO(QueryType.CLASS_COMPARISON_QUERY);\n classComparisonQueryDTO.setQueryName(classComparisonQueryForm.getAnalysisResultName());\n \n \n //Create the clinical query DTO collection from the selected groups in the form\n List clinicalQueryCollection = new ArrayList();\n \n if(classComparisonQueryForm.getSelectedGroups() != null && classComparisonQueryForm.getSelectedGroups().length == 2 ){\n for(int i=0; i clinicalQueryCollection = new ArrayList();\n \n if(classComparisonQueryForm.getSelectedGroups() != null && classComparisonQueryForm.getSelectedGroups().length == 2 ){\n for(int i=0; irc/gov/nih/nci/rembrandt/web/struts/action/ClassComparisonAction.java\n PatientUserListQueryDTO patientQueryDTO = new PatientUserListQueryDTO(session,myValueName);\n clinicalQueryCollection.add(patientQueryDTO);\n if(i==1){//the second group is always baseline\n patientQueryDTO.setBaseline(true);\n \t//to set baseline only when the statistical method \n \t//is not FTest\n \tif(!\"FTest\".equals(classComparisonQueryForm.getStatisticalMethod()))\n \t\tpatientQueryDTO.setBaseline(true);\n }\n }\n }"}}},{"rowIdx":874,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"56305e9807251882b664682da86b4d38a7c9946c"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"Hipparchus-Math/hipparchus,Hipparchus-Math/hipparchus,apache/commons-math,apache/commons-math,sdinot/hipparchus,apache/commons-math,Hipparchus-Math/hipparchus,sdinot/hipparchus,sdinot/hipparchus,Hipparchus-Math/hipparchus,sdinot/hipparchus,apache/commons-math"},"new_contents":{"kind":"string","value":"/*\n * Copyright 2003-2005 The Apache Software Foundation.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.apache.commons.math.distribution;\n\n/**\n * Test cases for TDistribution.\n * Extends ContinuousDistributionAbstractTest. See class javadoc for\n * ContinuousDistributionAbstractTest for details.\n *\n * @version $Revision: 1.15 $ $Date$\n */\npublic class TDistributionTest extends ContinuousDistributionAbstractTest {\n\n /**\n * Constructor for TDistributionTest.\n * @param name\n */\n public TDistributionTest(String name) {\n super(name);\n }\n\n//-------------- Implementations for abstract methods -----------------------\n\n /** Creates the default continuous distribution instance to use in tests. */\n public ContinuousDistribution makeDistribution() {\n return DistributionFactory.newInstance().createTDistribution(5.0);\n }\n\n /** Creates the default cumulative probability distribution test input values */\n public double[] makeCumulativeTestPoints() {\n // quantiles computed using R version 1.8.1 (linux version)\n return new double[] {-5.89343,-3.36493, -2.570582, -2.015048,\n -1.475884, 0.0, 5.89343, 3.36493, 2.570582,\n 2.015048, 1.475884};\n }\n\n /** Creates the default cumulative probability density test expected values */\n public double[] makeCumulativeTestValues() {\n return new double[] {0.001d, 0.01d, 0.025d, 0.05d, 0.1d, 0.5d, 0.999d,\n 0.990d, 0.975d, 0.950d, 0.900d};\n }\n\n // --------------------- Override tolerance --------------\n protected void setup() throws Exception {\n super.setUp();\n setTolerance(1E-6);\n }\n\n //---------------------------- Additional test cases -------------------------\n /**\n * @see \n * Bug report that prompted this unit test.\n */\n public void testCumulativeProbabilityAgaintStackOverflow() throws Exception {\n \tTDistributionImpl td = new TDistributionImpl(5.);\n \tdouble est;\n \test = td.cumulativeProbability(.1);\n \test = td.cumulativeProbability(.01);\n }\n\n public void testSmallDf() throws Exception {\n setDistribution(DistributionFactory.newInstance().createTDistribution(1d));\n setTolerance(1E-4);\n // quantiles computed using R version 1.8.1 (linux version)\n setCumulativeTestPoints(new double[] {-318.3088, -31.82052, -12.70620, -6.313752,\n -3.077684, 0.0, 318.3088, 31.82052, 12.70620,\n 6.313752, 3.077684});\n setInverseCumulativeTestValues(getCumulativeTestPoints());\n verifyCumulativeProbabilities();\n verifyInverseCumulativeProbabilities();\n }\n\n public void testInverseCumulativeProbabilityExtremes() throws Exception {\n setInverseCumulativeTestPoints(new double[] {0, 1});\n setInverseCumulativeTestValues(\n new double[] {Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY});\n verifyInverseCumulativeProbabilities();\n }\n\n public void testDfAccessors() {\n TDistribution distribution = (TDistribution) getDistribution();\n assertEquals(5d, distribution.getDegreesOfFreedom(), Double.MIN_VALUE);\n distribution.setDegreesOfFreedom(4d);\n assertEquals(4d, distribution.getDegreesOfFreedom(), Double.MIN_VALUE);\n try {\n distribution.setDegreesOfFreedom(0d);\n fail(\"Expecting IllegalArgumentException for df = 0\");\n } catch (IllegalArgumentException ex) {\n // expected\n }\n }\n\n}\n"},"new_file":{"kind":"string","value":"src/test/org/apache/commons/math/distribution/TDistributionTest.java"},"old_contents":{"kind":"string","value":"/*\n * Copyright 2003-2005 The Apache Software Foundation.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.apache.commons.math.distribution;\n\n/**\n * Test cases for TDistribution.\n * Extends ContinuousDistributionAbstractTest. See class javadoc for\n * ContinuousDistributionAbstractTest for details.\n *\n * @version $Revision: 1.15 $ $Date$\n */\npublic class TDistributionTest extends ContinuousDistributionAbstractTest {\n\n /**\n * Constructor for TDistributionTest.\n * @param name\n */\n public TDistributionTest(String name) {\n super(name);\n }\n\n//-------------- Implementations for abstract methods -----------------------\n\n /** Creates the default continuous distribution instance to use in tests. */\n public ContinuousDistribution makeDistribution() {\n return DistributionFactory.newInstance().createTDistribution(5.0);\n }\n\n /** Creates the default cumulative probability distribution test input values */\n public double[] makeCumulativeTestPoints() {\n // quantiles computed using R version 1.8.1 (linux version)\n return new double[] {-5.89343,-3.36493, -2.570582, -2.015048,\n -1.475884, 0.0, 5.89343, 3.36493, 2.570582,\n 2.015048, 1.475884};\n }\n\n /** Creates the default cumulative probability density test expected values */\n public double[] makeCumulativeTestValues() {\n return new double[] {0.001d, 0.01d, 0.025d, 0.05d, 0.1d, 0.0d, 0.999d,\n 0.990d, 0.975d, 0.950d, 0.900d};\n }\n\n // --------------------- Override tolerance --------------\n protected void setup() throws Exception {\n super.setUp();\n setTolerance(1E-6);\n }\n\n //---------------------------- Additional test cases -------------------------\n /**\n * @see \n * Bug report that prompted this unit test.\n */\n public void testCumulativeProbabilityAgaintStackOverflow() throws Exception {\n \tTDistributionImpl td = new TDistributionImpl(5.);\n \tdouble est;\n \test = td.cumulativeProbability(.1);\n \test = td.cumulativeProbability(.01);\n }\n\n public void testSmallDf() throws Exception {\n setDistribution(DistributionFactory.newInstance().createTDistribution(1d));\n setTolerance(1E-4);\n // quantiles computed using R version 1.8.1 (linux version)\n setCumulativeTestPoints(new double[] {-318.3088, -31.82052, -12.70620, -6.313752,\n -3.077684, 318.3088, 31.82052, 12.70620,\n 6.313752, 3.077684});\n setInverseCumulativeTestValues(getCumulativeTestPoints());\n verifyCumulativeProbabilities();\n verifyInverseCumulativeProbabilities();\n }\n\n public void testInverseCumulativeProbabilityExtremes() throws Exception {\n setInverseCumulativeTestPoints(new double[] {0, 1});\n setInverseCumulativeTestValues(\n new double[] {Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY});\n verifyInverseCumulativeProbabilities();\n }\n\n public void testDfAccessors() {\n TDistribution distribution = (TDistribution) getDistribution();\n assertEquals(5d, distribution.getDegreesOfFreedom(), Double.MIN_VALUE);\n distribution.setDegreesOfFreedom(4d);\n assertEquals(4d, distribution.getDegreesOfFreedom(), Double.MIN_VALUE);\n try {\n distribution.setDegreesOfFreedom(0d);\n fail(\"Expecting IllegalArgumentException for df = 0\");\n } catch (IllegalArgumentException ex) {\n // expected\n }\n }\n\n}\n"},"message":{"kind":"string","value":"fixed incorrect test data that was causing test failures.\n\ngit-svn-id: ba027325f5cbd8d0def94cfab53a7170165593ea@155246 13f79535-47bb-0310-9956-ffa450edef68\n"},"old_file":{"kind":"string","value":"src/test/org/apache/commons/math/distribution/TDistributionTest.java"},"subject":{"kind":"string","value":"fixed incorrect test data that was causing test failures."},"git_diff":{"kind":"string","value":"rc/test/org/apache/commons/math/distribution/TDistributionTest.java\n \n /** Creates the default cumulative probability density test expected values */\n public double[] makeCumulativeTestValues() {\n return new double[] {0.001d, 0.01d, 0.025d, 0.05d, 0.1d, 0.0d, 0.999d,\n return new double[] {0.001d, 0.01d, 0.025d, 0.05d, 0.1d, 0.5d, 0.999d,\n 0.990d, 0.975d, 0.950d, 0.900d};\n }\n \n setTolerance(1E-4);\n // quantiles computed using R version 1.8.1 (linux version)\n setCumulativeTestPoints(new double[] {-318.3088, -31.82052, -12.70620, -6.313752,\n -3.077684, 318.3088, 31.82052, 12.70620,\n -3.077684, 0.0, 318.3088, 31.82052, 12.70620,\n 6.313752, 3.077684});\n setInverseCumulativeTestValues(getCumulativeTestPoints());\n verifyCumulativeProbabilities();"}}},{"rowIdx":875,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"c2dbc0aaeb98403db25dd97f951676114b7c6403"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"ldbc/ldbc_graphalytics,ldbc/ldbc_graphalytics,tudelft-atlarge/graphalytics,tudelft-atlarge/graphalytics,tudelft-atlarge/graphalytics,ldbc/ldbc_graphalytics,tudelft-atlarge/graphalytics,ldbc/ldbc_graphalytics,tudelft-atlarge/graphalytics,ldbc/ldbc_graphalytics"},"new_contents":{"kind":"string","value":"/*\n * Copyright 2015 Delft University of Technology\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 nl.tudelft.graphalytics;\n\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Paths;\n\nimport nl.tudelft.graphalytics.network.ExecutorService;\nimport nl.tudelft.graphalytics.util.TimeUtility;\nimport org.apache.commons.configuration.Configuration;\nimport org.apache.commons.configuration.ConfigurationException;\nimport org.apache.commons.configuration.PropertiesConfiguration;\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\n\nimport nl.tudelft.graphalytics.domain.Benchmark;\nimport nl.tudelft.graphalytics.domain.BenchmarkResult;\nimport nl.tudelft.graphalytics.domain.BenchmarkSuite;\nimport nl.tudelft.graphalytics.domain.BenchmarkSuiteResult;\nimport nl.tudelft.graphalytics.domain.BenchmarkSuiteResult.BenchmarkSuiteResultBuilder;\nimport nl.tudelft.graphalytics.domain.Graph;\nimport nl.tudelft.graphalytics.domain.GraphSet;\nimport nl.tudelft.graphalytics.domain.NestedConfiguration;\nimport nl.tudelft.graphalytics.domain.SystemDetails;\nimport nl.tudelft.graphalytics.plugin.Plugins;\nimport nl.tudelft.graphalytics.util.GraphFileManager;\n\n/**\n * Helper class for executing all benchmarks in a BenchmarkSuite on a specific Platform.\n *\n * @author Tim Hegeman\n */\npublic class BenchmarkSuiteExecutor {\n\tprivate static final Logger LOG = LogManager.getLogger();\n\tprivate ExecutorService service;\n\n\n\tpublic static final String BENCHMARK_PROPERTIES_FILE = \"benchmark.properties\";\n\n\tprivate final BenchmarkSuite benchmarkSuite;\n\tprivate final Platform platform;\n\tprivate final Plugins plugins;\n\tprivate final int timeoutDuration;\n\n\t/**\n\t * @param benchmarkSuite the suite of benchmarks to run\n\t * @param platform the platform instance to run the benchmarks on\n\t * @param plugins collection of loaded plugins\n\t */\n\tpublic BenchmarkSuiteExecutor(BenchmarkSuite benchmarkSuite, Platform platform, Plugins plugins) {\n\t\tthis.benchmarkSuite = benchmarkSuite;\n\t\tthis.platform = platform;\n\t\tthis.plugins = plugins;\n\n\t\ttry {\n\t\t\tConfiguration benchmarkConf = new PropertiesConfiguration(BENCHMARK_PROPERTIES_FILE);\n\t\t\ttimeoutDuration = benchmarkConf.getInt(\"benchmark.run.timeout\");\n\t\t} catch (ConfigurationException e) {\n\t\t\te.printStackTrace();\n\t\t\tthrow new IllegalStateException(\"Failed to load configurations from \" + BENCHMARK_PROPERTIES_FILE);\n\t\t}\n\n\t\t// Init the executor service;\n\t\tExecutorService.InitService(this);\n\t}\n\n\n\t/**\n\t * Executes the Graphalytics benchmark suite on the given platform. The benchmarks are grouped by graph so that each\n\t * graph is uploaded to the platform exactly once. After executing all benchmarks for a specific graph, the graph\n\t * is deleted from the platform.\n\t *\n\t * @return a BenchmarkSuiteResult object containing the gathered benchmark results and details\n\t */\n\tpublic BenchmarkSuiteResult execute() {\n\t\t// TODO: Retrieve configuration for system, platform, and platform per benchmark\n\n\t\t// Use a BenchmarkSuiteResultBuilder to track the benchmark results gathered throughout execution\n\t\tBenchmarkSuiteResultBuilder benchmarkSuiteResultBuilder = new BenchmarkSuiteResultBuilder(benchmarkSuite);\n\n\t\tlong totalStartTime = System.currentTimeMillis();\n\t\tint finishedBenchmark = 0;\n\t\tint numBenchmark = benchmarkSuite.getBenchmarks().size();\n\n\n\t\tLOG.info(\"\");\n\t\tLOG.info(String.format(\"This benchmark suite consists of %s benchmarks in total.\", numBenchmark));\n\n\n\t\tfor (GraphSet graphSet : benchmarkSuite.getGraphSets()) {\n\t\t\tfor (Graph graph : graphSet.getGraphs()) {\n\n\n\t\t\t\tLOG.debug(String.format(\"Preparing for %s benchmark runs that use graph %s.\",\n\t\t\t\t\t\tbenchmarkSuite.getBenchmarksForGraph(graph).size(), graph.getName()));\n\n\n\t\t\t\tLOG.info(\"\");\n\t\t\t\tLOG.info(String.format(\"=======Start of Upload Graph %s =======\", graph.getName()));\n\n\t\t\t\t// Skip the graph if there are no benchmarks to run on it\n\t\t\t\tif (benchmarkSuite.getBenchmarksForGraph(graph).isEmpty()) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// Ensure that the graph input files exist (i.e. generate them from the GraphSet sources if needed)\n\t\t\t\ttry {\n\t\t\t\t\tGraphFileManager.ensureGraphFilesExist(graph);\n\t\t\t\t} catch (IOException ex) {\n\t\t\t\t\tLOG.error(\"Can not ensure that graph \\\"\" + graph.getName() + \"\\\" exists, skipping.\", ex);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// Upload the graph\n\t\t\t\ttry {\n\t\t\t\t\tplatform.uploadGraph(graph);\n\t\t\t\t} catch (Exception ex) {\n\t\t\t\t\tLOG.error(\"Failed to upload graph \\\"\" + graph.getName() + \"\\\", skipping.\", ex);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\n\t\t\t\tLOG.info(String.format(\"=======End of Upload Graph %s =======\", graph.getName()));\n\t\t\t\tLOG.info(\"\");\n\n\t\t\t\t// Execute all benchmarks for this graph\n\t\t\t\tfor (Benchmark benchmark : benchmarkSuite.getBenchmarksForGraph(graph)) {\n\t\t\t\t\t// Ensure that the output directory exists, if needed\n\t\t\t\t\tif (benchmark.isOutputRequired()) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tFiles.createDirectories(Paths.get(benchmark.getOutputPath()).getParent());\n\t\t\t\t\t\t} catch (IOException e) {\n\t\t\t\t\t\t\tLOG.error(\"Failed to create output directory \\\"\" +\n\t\t\t\t\t\t\t\t\tPaths.get(benchmark.getOutputPath()).getParent() + \"\\\", skipping.\", e);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tString benchmarkText = String.format(\"%s:\\\"%s on %s\\\"\", benchmark.getId(), benchmark.getAlgorithm().getAcronym(), graphSet.getName());\n\n\t\t\t\t\tLOG.info(\"\");\n\t\t\t\t\tLOG.info(String.format(\"=======Start of Benchmark %s [%s/%s]=======\", benchmark.getId(), finishedBenchmark + 1, numBenchmark));\n\n\t\t\t\t\t// Execute the pre-benchmark steps of all plugins\n\t\t\t\t\tplugins.preBenchmark(benchmark);\n\n\n\t\t\t\t\tLOG.info(String.format(\"Benchmark %s started.\", benchmarkText));\n\n\t\t\t\t\tProcess process = BenchmarkRunner.InitializeJvmProcess(platform.getName(), benchmark.getId());\n\t\t\t\t\tBenchmarkRunnerInfo runnerInfo = new BenchmarkRunnerInfo(benchmark, process);\n\t\t\t\t\tExecutorService.runnerInfos.put(benchmark.getId(), runnerInfo);\n\n\t\t\t\t\t// wait for runner to get started.\n\n\t\t\t\t\tlong waitingStarted;\n\n\t\t\t\t\tLOG.info(\"Initializing benchmark runner...\");\n\t\t\t\t\twaitingStarted = System.currentTimeMillis();\n\t\t\t\t\twhile (!runnerInfo.isRegistered()) {\n\t\t\t\t\t\tif(System.currentTimeMillis() - waitingStarted > 10 * 1000) {\n\t\t\t\t\t\t\tLOG.error(\"There is no response from the benchmark runner. Benchmark run failed.\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tTimeUtility.waitFor(1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tLOG.info(\"The benchmark runner is initialized.\");\n\n\t\t\t\t\tLOG.info(\"Running benchmark...\");\n\t\t\t\t\tLOG.info(\"Benchmark logs at: \\\"\" + benchmark.getLogPath() +\"\\\".\");\n\t\t\t\t\tLOG.info(\"Waiting for completion... (Timeout after \" + timeoutDuration + \" seconds)\");\n\t\t\t\t\twaitingStarted = System.currentTimeMillis();\n\t\t\t\t\twhile (!runnerInfo.isCompleted()) {\n\t\t\t\t\t\tif(System.currentTimeMillis() - waitingStarted > timeoutDuration * 1000) {\n\t\t\t\t\t\t\tLOG.error(\"Timeout is reached. This benchmark run is skipped.\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tTimeUtility.waitFor(1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tBenchmarkRunner.TerminateJvmProcess(process);\n\n\t\t\t\t\tBenchmarkResult benchmarkResult = runnerInfo.getBenchmarkResult();\n\t\t\t\t\tif(benchmarkResult != null) {\n\t\t\t\t\t\tbenchmarkSuiteResultBuilder.withBenchmarkResult(benchmarkResult);\n\n\t\t\t\t\t\tlong makespan = (benchmarkResult.getEndOfBenchmark().getTime() - benchmarkResult.getStartOfBenchmark().getTime());\n\t\t\t\t\t\tLOG.info(String.format(\"Benchmark %s %s (completed: %s, validated: %s), which took: %s ms.\",\n\t\t\t\t\t\t\t\tbenchmark.getId(),\n\t\t\t\t\t\t\t\tbenchmarkResult.isSuccessful() ? \"succeed\" : \"failed\",\n\t\t\t\t\t\t\t\tbenchmarkResult.isCompleted(),\n\t\t\t\t\t\t\t\tbenchmarkResult.isValidated(),\n\t\t\t\t\t\t\t\tmakespan));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tbenchmarkSuiteResultBuilder.withoutBenchmarkResult(benchmark);\n\t\t\t\t\t\tLOG.info(String.format(\"Benchmark %s %s (completed: %s, validated: %s).\",\n\t\t\t\t\t\t\t\tbenchmark.getId(), \"failed\", false, false));\n\t\t\t\t\t}\n\n\t\t\t\t\tLOG.info(String.format(\"Benchmark %s ended.\", benchmarkText));\n\n\n\t\t\t\t\t// Execute the post-benchmark steps of all plugins\n\n\t\t\t\t\tLOG.info(String.format(\"Cleaning up %s.\", benchmarkText));\n\t\t\t\t\tplatform.cleanup(benchmark);\n\t\t\t\t\tplugins.postBenchmark(benchmark, benchmarkResult);\n\n\t\t\t\t\tfinishedBenchmark++;\n\t\t\t\t\tLOG.info(String.format(\"=======End of Benchmark %s [%s/%s]=======\", benchmark.getId(), finishedBenchmark, numBenchmark));\n\t\t\t\t\tLOG.info(\"\");\n\t\t\t\t\tLOG.info(\"\");\n\t\t\t\t}\n\n\t\t\t\t// Delete the graph\n\t\t\t\tplatform.deleteGraph(graph.getName());\n\t\t\t}\n\t\t}\n\t\tservice.terminate();\n\n\t\tlong totalEndTime = System.currentTimeMillis();\n\t\tlong totalDuration = totalEndTime - totalStartTime;\n\n\t\t// Dump the used configuration\n\t\tNestedConfiguration benchmarkConfiguration = NestedConfiguration.empty();\n\t\ttry {\n\t\t\tConfiguration configuration = new PropertiesConfiguration(\"benchmark.properties\");\n\t\t\tbenchmarkConfiguration = NestedConfiguration.fromExternalConfiguration(configuration,\n\t\t\t\t\t\"benchmark.properties\");\n\t\t} catch (ConfigurationException e) {\n\t\t\t// Already reported during loading of benchmark\n\t\t}\n\n\t\t// Construct the BenchmarkSuiteResult\n\t\treturn benchmarkSuiteResultBuilder.buildFromConfiguration(SystemDetails.empty(),\n\t\t\t\tbenchmarkConfiguration,\n\t\t\t\tplatform.getPlatformConfiguration(), totalDuration);\n\t}\n\n\tpublic void setService(ExecutorService service) {\n\t\tthis.service = service;\n\t}\n}\n"},"new_file":{"kind":"string","value":"graphalytics-core/src/main/java/nl/tudelft/graphalytics/BenchmarkSuiteExecutor.java"},"old_contents":{"kind":"string","value":"/*\n * Copyright 2015 Delft University of Technology\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 nl.tudelft.graphalytics;\n\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Paths;\n\nimport nl.tudelft.graphalytics.network.ExecutorService;\nimport nl.tudelft.graphalytics.util.TimeUtility;\nimport org.apache.commons.configuration.Configuration;\nimport org.apache.commons.configuration.ConfigurationException;\nimport org.apache.commons.configuration.PropertiesConfiguration;\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\n\nimport nl.tudelft.graphalytics.domain.Benchmark;\nimport nl.tudelft.graphalytics.domain.BenchmarkResult;\nimport nl.tudelft.graphalytics.domain.BenchmarkSuite;\nimport nl.tudelft.graphalytics.domain.BenchmarkSuiteResult;\nimport nl.tudelft.graphalytics.domain.BenchmarkSuiteResult.BenchmarkSuiteResultBuilder;\nimport nl.tudelft.graphalytics.domain.Graph;\nimport nl.tudelft.graphalytics.domain.GraphSet;\nimport nl.tudelft.graphalytics.domain.NestedConfiguration;\nimport nl.tudelft.graphalytics.domain.SystemDetails;\nimport nl.tudelft.graphalytics.plugin.Plugins;\nimport nl.tudelft.graphalytics.util.GraphFileManager;\n\n/**\n * Helper class for executing all benchmarks in a BenchmarkSuite on a specific Platform.\n *\n * @author Tim Hegeman\n */\npublic class BenchmarkSuiteExecutor {\n\tprivate static final Logger LOG = LogManager.getLogger();\n\tprivate ExecutorService service;\n\n\n\tpublic static final String BENCHMARK_PROPERTIES_FILE = \"benchmark.properties\";\n\n\tprivate final BenchmarkSuite benchmarkSuite;\n\tprivate final Platform platform;\n\tprivate final Plugins plugins;\n\tprivate final int timeoutDuration;\n\n\t/**\n\t * @param benchmarkSuite the suite of benchmarks to run\n\t * @param platform the platform instance to run the benchmarks on\n\t * @param plugins collection of loaded plugins\n\t */\n\tpublic BenchmarkSuiteExecutor(BenchmarkSuite benchmarkSuite, Platform platform, Plugins plugins) {\n\t\tthis.benchmarkSuite = benchmarkSuite;\n\t\tthis.platform = platform;\n\t\tthis.plugins = plugins;\n\n\t\ttry {\n\t\t\tConfiguration benchmarkConf = new PropertiesConfiguration(BENCHMARK_PROPERTIES_FILE);\n\t\t\ttimeoutDuration = benchmarkConf.getInt(\"benchmark.run.timeout\");\n\t\t} catch (ConfigurationException e) {\n\t\t\te.printStackTrace();\n\t\t\tthrow new IllegalStateException(\"Failed to load configurations from \" + BENCHMARK_PROPERTIES_FILE);\n\t\t}\n\n\t\t// Init the executor service;\n\t\tExecutorService.InitService(this);\n\t}\n\n\n\t/**\n\t * Executes the Graphalytics benchmark suite on the given platform. The benchmarks are grouped by graph so that each\n\t * graph is uploaded to the platform exactly once. After executing all benchmarks for a specific graph, the graph\n\t * is deleted from the platform.\n\t *\n\t * @return a BenchmarkSuiteResult object containing the gathered benchmark results and details\n\t */\n\tpublic BenchmarkSuiteResult execute() {\n\t\t// TODO: Retrieve configuration for system, platform, and platform per benchmark\n\n\t\t// Use a BenchmarkSuiteResultBuilder to track the benchmark results gathered throughout execution\n\t\tBenchmarkSuiteResultBuilder benchmarkSuiteResultBuilder = new BenchmarkSuiteResultBuilder(benchmarkSuite);\n\n\t\tlong totalStartTime = System.currentTimeMillis();\n\t\tint finishedBenchmark = 0;\n\t\tint numBenchmark = benchmarkSuite.getBenchmarks().size();\n\n\n\t\tLOG.info(\"\");\n\t\tLOG.info(String.format(\"This benchmark suite consists of %s benchmarks in total.\", numBenchmark));\n\n\n\t\tfor (GraphSet graphSet : benchmarkSuite.getGraphSets()) {\n\t\t\tfor (Graph graph : graphSet.getGraphs()) {\n\n\n\t\t\t\tLOG.debug(String.format(\"Preparing for %s benchmark runs that use graph %s.\",\n\t\t\t\t\t\tbenchmarkSuite.getBenchmarksForGraph(graph).size(), graph.getName()));\n\n\n\t\t\t\tLOG.info(\"\");\n\t\t\t\tLOG.info(String.format(\"=======Start of Upload Graph %s =======\", graph.getName()));\n\n\t\t\t\t// Skip the graph if there are no benchmarks to run on it\n\t\t\t\tif (benchmarkSuite.getBenchmarksForGraph(graph).isEmpty()) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// Ensure that the graph input files exist (i.e. generate them from the GraphSet sources if needed)\n\t\t\t\ttry {\n\t\t\t\t\tGraphFileManager.ensureGraphFilesExist(graph);\n\t\t\t\t} catch (IOException ex) {\n\t\t\t\t\tLOG.error(\"Can not ensure that graph \\\"\" + graph.getName() + \"\\\" exists, skipping.\", ex);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// Upload the graph\n\t\t\t\ttry {\n\t\t\t\t\tplatform.uploadGraph(graph);\n\t\t\t\t} catch (Exception ex) {\n\t\t\t\t\tLOG.error(\"Failed to upload graph \\\"\" + graph.getName() + \"\\\", skipping.\", ex);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\n\t\t\t\tLOG.info(String.format(\"=======End of Upload Graph %s =======\", graph.getName()));\n\t\t\t\tLOG.info(\"\");\n\n\t\t\t\t// Execute all benchmarks for this graph\n\t\t\t\tfor (Benchmark benchmark : benchmarkSuite.getBenchmarksForGraph(graph)) {\n\t\t\t\t\t// Ensure that the output directory exists, if needed\n\t\t\t\t\tif (benchmark.isOutputRequired()) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tFiles.createDirectories(Paths.get(benchmark.getOutputPath()).getParent());\n\t\t\t\t\t\t} catch (IOException e) {\n\t\t\t\t\t\t\tLOG.error(\"Failed to create output directory \\\"\" +\n\t\t\t\t\t\t\t\t\tPaths.get(benchmark.getOutputPath()).getParent() + \"\\\", skipping.\", e);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tString benchmarkText = String.format(\"%s:\\\"%s on %s\\\"\", benchmark.getId(), benchmark.getAlgorithm().getAcronym(), graphSet.getName());\n\n\t\t\t\t\tLOG.info(\"\");\n\t\t\t\t\tLOG.info(String.format(\"=======Start of Benchmark %s [%s/%s]=======\", benchmark.getId(), finishedBenchmark + 1, numBenchmark));\n\n\t\t\t\t\t// Execute the pre-benchmark steps of all plugins\n\t\t\t\t\tplugins.preBenchmark(benchmark);\n\n\n\t\t\t\t\tLOG.info(String.format(\"Benchmark %s started.\", benchmarkText));\n\n\t\t\t\t\tProcess process = BenchmarkRunner.InitializeJvmProcess(platform.getName(), benchmark.getId());\n\t\t\t\t\tBenchmarkRunnerInfo runnerInfo = new BenchmarkRunnerInfo(benchmark, process);\n\t\t\t\t\tExecutorService.runnerInfos.put(benchmark.getId(), runnerInfo);\n\n\t\t\t\t\t// wait for runner to get started.\n\n\t\t\t\t\tlong waitingStarted;\n\n\t\t\t\t\tLOG.info(\"Initializing benchmark runner...\");\n\t\t\t\t\twaitingStarted = System.currentTimeMillis();\n\t\t\t\t\twhile (!runnerInfo.isRegistered()) {\n\t\t\t\t\t\tif(System.currentTimeMillis() - waitingStarted > 10 * 1000) {\n\t\t\t\t\t\t\tLOG.error(\"There is no response from the benchmark runner. Benchmark run failed.\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tTimeUtility.waitFor(1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tLOG.info(\"The benchmark runner is initialized.\");\n\n\t\t\t\t\tLOG.info(\"Running benchmark...\");\n\t\t\t\t\tLOG.info(\"Benchmark logs are stored at: \\\"\" + benchmark.getLogPath() +\"\\\".\");\n\t\t\t\t\tLOG.info(\"Waiting for completion... (Timeout after \" + timeoutDuration + \" seconds)\");\n\t\t\t\t\twaitingStarted = System.currentTimeMillis();\n\t\t\t\t\twhile (!runnerInfo.isCompleted()) {\n\t\t\t\t\t\tif(System.currentTimeMillis() - waitingStarted > timeoutDuration * 1000) {\n\t\t\t\t\t\t\tLOG.error(\"Timeout is reached. This benchmark run is skipped.\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tTimeUtility.waitFor(1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tBenchmarkRunner.TerminateJvmProcess(process);\n\n\t\t\t\t\tBenchmarkResult benchmarkResult = runnerInfo.getBenchmarkResult();\n\t\t\t\t\tif(benchmarkResult != null) {\n\t\t\t\t\t\tbenchmarkSuiteResultBuilder.withBenchmarkResult(benchmarkResult);\n\n\t\t\t\t\t\tlong makespan = (benchmarkResult.getEndOfBenchmark().getTime() - benchmarkResult.getStartOfBenchmark().getTime());\n\t\t\t\t\t\tLOG.info(String.format(\"Benchmark %s %s (completed: %s, validated: %s), which took: %s ms.\",\n\t\t\t\t\t\t\t\tbenchmark.getId(),\n\t\t\t\t\t\t\t\tbenchmarkResult.isSuccessful() ? \"succeed\" : \"failed\",\n\t\t\t\t\t\t\t\tbenchmarkResult.isCompleted(),\n\t\t\t\t\t\t\t\tbenchmarkResult.isValidated(),\n\t\t\t\t\t\t\t\tmakespan));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tbenchmarkSuiteResultBuilder.withoutBenchmarkResult(benchmark);\n\t\t\t\t\t\tLOG.info(String.format(\"Benchmark %s %s (completed: %s, validated: %s).\",\n\t\t\t\t\t\t\t\tbenchmark.getId(), \"failed\", false, false));\n\t\t\t\t\t}\n\n\t\t\t\t\tLOG.info(String.format(\"Benchmark %s ended.\", benchmarkText));\n\n\n\t\t\t\t\t// Execute the post-benchmark steps of all plugins\n\n\t\t\t\t\tLOG.info(String.format(\"Cleaning up %s.\", benchmarkText));\n\t\t\t\t\tplatform.cleanup(benchmark);\n\t\t\t\t\tplugins.postBenchmark(benchmark, benchmarkResult);\n\n\t\t\t\t\tfinishedBenchmark++;\n\t\t\t\t\tLOG.info(String.format(\"=======End of Benchmark %s [%s/%s]=======\", benchmark.getId(), finishedBenchmark, numBenchmark));\n\t\t\t\t\tLOG.info(\"\");\n\t\t\t\t}\n\n\t\t\t\t// Delete the graph\n\t\t\t\tplatform.deleteGraph(graph.getName());\n\t\t\t}\n\t\t}\n\t\tservice.terminate();\n\n\t\tlong totalEndTime = System.currentTimeMillis();\n\t\tlong totalDuration = totalEndTime - totalStartTime;\n\n\t\t// Dump the used configuration\n\t\tNestedConfiguration benchmarkConfiguration = NestedConfiguration.empty();\n\t\ttry {\n\t\t\tConfiguration configuration = new PropertiesConfiguration(\"benchmark.properties\");\n\t\t\tbenchmarkConfiguration = NestedConfiguration.fromExternalConfiguration(configuration,\n\t\t\t\t\t\"benchmark.properties\");\n\t\t} catch (ConfigurationException e) {\n\t\t\t// Already reported during loading of benchmark\n\t\t}\n\n\t\t// Construct the BenchmarkSuiteResult\n\t\treturn benchmarkSuiteResultBuilder.buildFromConfiguration(SystemDetails.empty(),\n\t\t\t\tbenchmarkConfiguration,\n\t\t\t\tplatform.getPlatformConfiguration(), totalDuration);\n\t}\n\n\tpublic void setService(ExecutorService service) {\n\t\tthis.service = service;\n\t}\n}\n"},"message":{"kind":"string","value":"Update logging mechanism.\n"},"old_file":{"kind":"string","value":"graphalytics-core/src/main/java/nl/tudelft/graphalytics/BenchmarkSuiteExecutor.java"},"subject":{"kind":"string","value":"Update logging mechanism."},"git_diff":{"kind":"string","value":"raphalytics-core/src/main/java/nl/tudelft/graphalytics/BenchmarkSuiteExecutor.java\n \t\t\t\t\tLOG.info(\"The benchmark runner is initialized.\");\n \n \t\t\t\t\tLOG.info(\"Running benchmark...\");\n\t\t\t\t\tLOG.info(\"Benchmark logs are stored at: \\\"\" + benchmark.getLogPath() +\"\\\".\");\n\t\t\t\t\tLOG.info(\"Benchmark logs at: \\\"\" + benchmark.getLogPath() +\"\\\".\");\n \t\t\t\t\tLOG.info(\"Waiting for completion... (Timeout after \" + timeoutDuration + \" seconds)\");\n \t\t\t\t\twaitingStarted = System.currentTimeMillis();\n \t\t\t\t\twhile (!runnerInfo.isCompleted()) {\n \t\t\t\t\tfinishedBenchmark++;\n \t\t\t\t\tLOG.info(String.format(\"=======End of Benchmark %s [%s/%s]=======\", benchmark.getId(), finishedBenchmark, numBenchmark));\n \t\t\t\t\tLOG.info(\"\");\n\t\t\t\t\tLOG.info(\"\");\n \t\t\t\t}\n \n \t\t\t\t// Delete the graph"}}},{"rowIdx":876,"cells":{"lang":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"7bf69ace57ba82dbd0d4c32308f07f69a19781da"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"react-circuit/ultra,gt3/ultra-router"},"new_contents":{"kind":"string","value":"function noop() {}\n\nfunction id(x) { return x }\n\nfunction isFn(t) {\n return typeof t === 'function' ? t : void 0\n}\n\nconst strProto = Object.getPrototypeOf('')\nfunction isStr(s) {\n return Object.getPrototypeOf(Object(s)) === strProto\n}\n\nfunction empty(t) {\n return !t || (!t.length && !Object.keys(t).length)\n}\n\nexport { id, isFn, isStr, empty }\n\nfunction makeArray(arr) {\n return Array.isArray(arr) ? arr : empty(arr) ? [] : [arr]\n}\n\nfunction pipe(...fns) {\n function invoke(v) {\n return fns.reduce((acc, fn) => (fn ? fn.call(this, acc) : acc), v)\n }\n return fns.length > 0 ? invoke : id\n}\n\nconst flattenToObj = (arr, base = {}) => Object.assign(base, ...arr)\n\nfunction exclude(t, ...keys) {\n return flattenToObj(Object.keys(t).filter(k => keys.indexOf(k) === -1).map(k => ({ [k]: t[k] })))\n}\n\nfunction substitute(literals, values, removeEmpty) {\n let vals = Array.from(values, v => v || '')\n let lits = Array.from(literals, v => v || '')\n if (removeEmpty && lits.length > vals.length) {\n lits = [lits[0], ...lits.slice(1).map((l, i) => l || (vals[i] = ''))]\n }\n return String.raw({ raw: lits }, ...vals)\n}\n\nfunction escapeRx(string) {\n return string.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\nfunction warnOn(truthy, msg) {\n return truthy && console.error(msg)\n}\nlet $devWarnOn = noop\nif (process.env.NODE_ENV !== 'production') {\n $devWarnOn = warnOn\n}\n\nexport { makeArray, pipe, flattenToObj, exclude, substitute, escapeRx, $devWarnOn }\n\nexport class Timer {\n static isTimer(timer) {\n return timer && timer instanceof Timer ? timer : false\n }\n constructor(cb, ms = 0, autoRun = true) {\n this.run = this.run.bind(this, cb, ms)\n if (autoRun) this.run()\n }\n get active() {\n return !!this.ref\n }\n run(cb, ms) {\n return (this.ref = setTimeout(this.stop.bind(this, cb), ms))\n }\n stop(cb) {\n clearTimeout(this.ref)\n this.ref = undefined\n return cb && cb()\n }\n}\n"},"new_file":{"kind":"string","value":"src/router/utils.js"},"old_contents":{"kind":"string","value":"function noop() {}\n\nfunction isFn(t) {\n return typeof t === 'function' ? t : void 0\n}\n\nconst strProto = Object.getPrototypeOf('')\nfunction isStr(s) {\n return Object.getPrototypeOf(Object(s)) === strProto\n}\n\nfunction empty(t) {\n return !t || (!t.length && !Object.keys(t).length)\n}\n\nexport { isFn, isStr, empty }\n\nfunction makeArray(arr) {\n return Array.isArray(arr) ? arr : empty(arr) ? [] : [arr]\n}\n\nfunction pipe(...fns) {\n function invoke(v) {\n return fns.reduce((acc, fn) => (fn ? fn.call(this, acc) : acc), v)\n }\n return invoke\n}\n\nconst flattenToObj = (arr, base = {}) => Object.assign(base, ...arr)\n\nfunction exclude(t, ...keys) {\n return flattenToObj(Object.keys(t).filter(k => keys.indexOf(k) === -1).map(k => ({ [k]: t[k] })))\n}\n\nfunction substitute(literals, values, removeEmpty) {\n let vals = Array.from(values, v => v || '')\n let lits = Array.from(literals, v => v || '')\n if (removeEmpty && lits.length > vals.length) {\n lits = [lits[0], ...lits.slice(1).map((l, i) => l || (vals[i] = ''))]\n }\n return String.raw({ raw: lits }, ...vals)\n}\n\nfunction escapeRx(string) {\n return string.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\nfunction warnOn(truthy, msg) {\n return truthy && console.error(msg)\n}\nlet $devWarnOn = noop\nif (process.env.NODE_ENV !== 'production') {\n $devWarnOn = warnOn\n}\n\nexport { makeArray, pipe, flattenToObj, exclude, substitute, escapeRx, $devWarnOn }\n\nexport class Timer {\n static isTimer(timer) {\n return timer && timer instanceof Timer ? timer : false\n }\n constructor(cb, ms = 0, autoRun = true) {\n this.run = this.run.bind(this, cb, ms)\n if (autoRun) this.run()\n }\n get active() {\n return !!this.ref\n }\n run(cb, ms) {\n return (this.ref = setTimeout(this.stop.bind(this, cb), ms))\n }\n stop(cb) {\n clearTimeout(this.ref)\n this.ref = undefined\n return cb && cb()\n }\n}\n"},"message":{"kind":"string","value":"pipe should return identity when no fn is provided\n"},"old_file":{"kind":"string","value":"src/router/utils.js"},"subject":{"kind":"string","value":"pipe should return identity when no fn is provided"},"git_diff":{"kind":"string","value":"rc/router/utils.js\n function noop() {}\n\nfunction id(x) { return x }\n \n function isFn(t) {\n return typeof t === 'function' ? t : void 0\n return !t || (!t.length && !Object.keys(t).length)\n }\n \nexport { isFn, isStr, empty }\nexport { id, isFn, isStr, empty }\n \n function makeArray(arr) {\n return Array.isArray(arr) ? arr : empty(arr) ? [] : [arr]\n function invoke(v) {\n return fns.reduce((acc, fn) => (fn ? fn.call(this, acc) : acc), v)\n }\n return invoke\n return fns.length > 0 ? invoke : id\n }\n \n const flattenToObj = (arr, base = {}) => Object.assign(base, ...arr)"}}},{"rowIdx":877,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"f427414adc620073a034aa0f2ea38545070b6747"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"FUNCATE/TerraMobile,TerraMobile/TerraMobile,TerraMobile/Java-OpenMobility,FUNCATE/TerraMobile,FUNCATE/Java-OpenMobility,opengeospatial/Java-OpenMobility,TerraMobile/TerraMobile"},"new_contents":{"kind":"string","value":"/*\n * GeoPackage.java\n * \n * Copyright 2013, Augmented Technologies Ltd.\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.augtech.geoapi.geopackage;\n\nimport java.io.ByteArrayOutputStream;\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.IOException;\nimport java.io.RandomAccessFile;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\n\nimport org.opengis.feature.simple.SimpleFeature;\nimport org.opengis.feature.simple.SimpleFeatureType;\nimport org.opengis.feature.type.AttributeType;\nimport org.opengis.feature.type.FeatureType;\nimport org.opengis.feature.type.GeometryDescriptor;\nimport org.opengis.feature.type.Name;\nimport org.opengis.geometry.BoundingBox;\nimport org.opengis.referencing.crs.CoordinateReferenceSystem;\n\nimport com.augtech.geoapi.feature.SimpleFeatureImpl;\nimport com.augtech.geoapi.geometry.BoundingBoxImpl;\nimport com.augtech.geoapi.geopackage.geometry.GeometryDecoder;\nimport com.augtech.geoapi.geopackage.geometry.OGCWKBWriter;\nimport com.augtech.geoapi.geopackage.geometry.StandardGeometryDecoder;\nimport com.augtech.geoapi.geopackage.table.FeatureField;\nimport com.augtech.geoapi.geopackage.table.FeaturesTable;\nimport com.augtech.geoapi.geopackage.table.FeaturesTable.GeometryInfo;\nimport com.augtech.geoapi.geopackage.table.GpkgContents;\nimport com.augtech.geoapi.geopackage.table.GpkgDataColumnConstraint;\nimport com.augtech.geoapi.geopackage.table.GpkgDataColumnConstraint.DataColumnConstraint;\nimport com.augtech.geoapi.geopackage.table.GpkgDataColumns;\nimport com.augtech.geoapi.geopackage.table.GpkgExtensions;\nimport com.augtech.geoapi.geopackage.table.GpkgExtensions.Extension;\nimport com.augtech.geoapi.geopackage.table.GpkgGeometryColumns;\nimport com.augtech.geoapi.geopackage.table.GpkgMetaData;\nimport com.augtech.geoapi.geopackage.table.GpkgMetaDataReference;\nimport com.augtech.geoapi.geopackage.table.GpkgSpatialRefSys;\nimport com.augtech.geoapi.geopackage.table.GpkgTileMatrix;\nimport com.augtech.geoapi.geopackage.table.GpkgTileMatrixSet;\nimport com.augtech.geoapi.geopackage.table.GpkgTriggers;\nimport com.augtech.geoapi.geopackage.table.TilesTable;\nimport com.augtech.geoapi.geopackage.table.TilesTable.TileMatrixInfo;\nimport com.augtech.geoapi.geopackage.views.GpkgView;\nimport com.augtech.geoapi.geopackage.views.STGeometryColumns;\nimport com.augtech.geoapi.geopackage.views.STSpatialRefSys;\nimport com.augtech.geoapi.geopackage.views.SpatialRefSys;\nimport com.augtech.geoapi.referncing.CoordinateReferenceSystemImpl;\nimport com.vividsolutions.jts.geom.Envelope;\nimport com.vividsolutions.jts.geom.Geometry;\nimport com.vividsolutions.jts.io.ByteOrderValues;\nimport com.vividsolutions.jts.simplify.DouglasPeuckerSimplifier;\n\npublic class GeoPackage {\n\tprotected ISQLDatabase sqlDB = null;\n\tprotected File dbFile = null;\n\t\n\tpublic enum JavaType {\n\t\tINTEGER,\n\t\tSTRING,\n\t\tBOOLEAN,\n\t\tFLOAT,\n\t\tDOUBLE,\n\t\tBYTE_ARR,\n\t\tUNKNOWN\n\t}\n\t/** A map of possible SQL Field types to {@link JavaType} enum values.\n\t * Field type names are all lowercase */\n\tpublic Map sqlTypeMap = new HashMap();\n\t\n\tpublic Logger log = Logger.getAnonymousLogger();\n\tprivate Map sysTables = new HashMap();\n\tprivate Map sysViews = new HashMap();\n\tprivate Map userTables = new HashMap();\n\t\n\t/** The name to create (if required) and test for use as a FeatureID within the GeoPackage */\n\tpublic static String FEATURE_ID_FIELD_NAME = \"feature_id\";\n\t/** For each new FeaturesTable, create an R*Tree index if the SQLite library supports it?\n\t * Default is True. If the library does not support R*Tree ({@link ISQLDatabase#hasRTreeEnabled()}\n\t * then indexes cannot be created. */\n\tpublic static final boolean CREATE_RTREE_FOR_FEATURES = true;\n\t/** The OGC GeoPackage specification these statements relate to */\n\tpublic static final String SPEC_VERSION = \"OGC 12-128r9 - 0.9.7 - v8\";\n\t/** The maximum currently supported GeoPacakge version */\n\tpublic static final int MAX_GPKG_VERSION = 0;\n\t/** The Sqlite registered application_id for a GeoPackage */\n\tpublic static final int GPKG_APPLICATION_ID = Integer.decode(\"0x47503130\");\n\t/** The maximum number of vertices permissible on a single Geometry. \n\t * -1 = no limit */\n\tprotected int MAX_VERTEX_LIMIT = -1;\n\t/** If True, reading of GeoPackage headers, pragmas and Geometry encodings will\n\t * be validated against the specification and exceptions thrown if not valid.\n\t * If False, checks will be performed, but exceptions won't be thrown unless\n\t * data cannot be understood. Typical examples are the application_id pragma and Geometry.*/\n\tpublic static boolean MODE_STRICT = true;\n\t\t\n\t/** The Geometry version to write in to the Geometry columns. Default is 0 \n\t * for Version 1.0 */\n\tpublic static int GPKG_GEOM_HEADER_VERSION = 0;\n\t\n\t/** If {@code True} insert StandardGeoPackageBinary geometries into the GeoPackage.\n\t * If {@code False} then the Geometry header is set to ExtendedGeoPackageBinary \n\t * (which this implementation does not yet implement - clause 3.1.2, Annex K of spec).\n\t * Default is {@code True} */\n\tpublic static boolean GPKG_GEOMETRY_STANDARD = true;\n\t/** Encode new Geometry in Little Endian order? Default is {@code False} */\n\tpublic static boolean GPKG_GEOMETRY_LITTLE_ENDIAN = false;\n\t\n\tpublic static final int Z_M_VALUES_PROHIBIT = 0;\n\tpublic static final int Z_M_VALUES_MANDATORY = 1;\n\tpublic static final int Z_M_VALUES_OPTIONAL = 2;\n\t\n\t/** An array of extensions applicable to this GeoPackage */\n\tprotected Extension[] gpkgExtensions = null;\n\t/** The maximum number of records to fetch in one go through the cursor. Default is 1000.\n\t * Increasing this number may result in slightly faster queries on large recordsets,\n\t * but could also result in memory exceptions or missing records (especially on mobile\n\t * devices with limited memory. (Tested on Android at 1000) */\n\tpublic static int MAX_RECORDS_PER_CURSOR = 1000;\n\t\n\t/** Connect to, or create a new GeoPackage with the supplied name and version.

\n\t * If the supplied name already exists then the database is checked to see if it\n\t * is a valid GeoPackage. If the supplied file does not exist, a new empty GeoPackage\n\t * is created with the supplied name.\n\t * \n\t * @param fileName The name of the GeoPackage to create or connect to. The .gpkg extension is added \n\t * if not supplied.\n\t * @param overwrite Overwrite the existing GeoPackage?\n\t * @throws Exception If an existing GeoPackage fails the validity check.\n\t * @see #isGPKGValid()\n\t */\n\tpublic GeoPackage(ISQLDatabase sqlDB, boolean overwrite) {\n\t\t\n\t\tif (!sqlDB.getDatabaseFile().toString().endsWith(\".gpkg\"))\n\t\t\tthrow new IllegalArgumentException(\"Invalid file extension for database - Must be .gpkg\");\n\n\t\t\n\t\tthis.sqlDB = sqlDB;\n\t\tthis.dbFile = sqlDB.getDatabaseFile();\n\n\t\tif (overwrite) {\n\t\t\tif (dbFile.exists() && !dbFile.delete()) \n\t\t\t\tthrow new IllegalArgumentException(\"Unable to overwrite GeoPackage file\");\n\t\t}\n\n\t\t// Load table definitions\n\t\tsysTables.put(GpkgSpatialRefSys.TABLE_NAME, new GpkgSpatialRefSys());\n\t\tsysTables.put(GpkgContents.TABLE_NAME, new GpkgContents() );\n\t\tsysTables.put(GpkgDataColumnConstraint.TABLE_NAME, new GpkgDataColumnConstraint());\n\t\tsysTables.put(GpkgDataColumns.TABLE_NAME, new GpkgDataColumns());\n\t\tsysTables.put(GpkgExtensions.TABLE_NAME, new GpkgExtensions());\n\t\tsysTables.put(GpkgGeometryColumns.TABLE_NAME, new GpkgGeometryColumns());\n\t\tsysTables.put(GpkgMetaData.TABLE_NAME, new GpkgMetaData());\n\t\tsysTables.put(GpkgMetaDataReference.TABLE_NAME, new GpkgMetaDataReference());\n\t\tsysTables.put(GpkgTileMatrix.TABLE_NAME, new GpkgTileMatrix());\n\t\tsysTables.put(GpkgTileMatrixSet.TABLE_NAME, new GpkgTileMatrixSet());\n\t\t\n\t\tsysViews.put(SpatialRefSys.VIEW_NAME, new SpatialRefSys());\n\t\tsysViews.put(STGeometryColumns.VIEW_NAME, new STGeometryColumns());\n\t\tsysViews.put(STSpatialRefSys.VIEW_NAME, new STSpatialRefSys());\n\t\t//sysViews.put(GeometryColumns.VIEW_NAME, new GeometryColumns()); // Requires function definition\n\n\t\t// Look-ups for sql to Java\n\t\tsqlTypeMap.put(\"int\", JavaType.INTEGER);\n\t\tsqlTypeMap.put(\"integer\", JavaType.INTEGER);\n\t\tsqlTypeMap.put(\"tinyint\", JavaType.INTEGER);\n\t\tsqlTypeMap.put(\"text\", JavaType.STRING);\n\t\tsqlTypeMap.put(\"date\", JavaType.STRING);\n\t\tsqlTypeMap.put(\"datetime\", JavaType.STRING);\n\t\tsqlTypeMap.put(\"string\", JavaType.STRING);\n\t\tsqlTypeMap.put(\"boolean\", JavaType.BOOLEAN);\n\t\tsqlTypeMap.put(\"float\", JavaType.FLOAT);\n\t\tsqlTypeMap.put(\"double\", JavaType.DOUBLE);\n\t\tsqlTypeMap.put(\"real\", JavaType.DOUBLE);\n\t\tsqlTypeMap.put(\"long\", JavaType.DOUBLE);\n\t\tsqlTypeMap.put(\"geometry\", JavaType.BYTE_ARR);\n\t\tsqlTypeMap.put(\"blob\", JavaType.BYTE_ARR);\n\t\tsqlTypeMap.put(\"none\", JavaType.BYTE_ARR);\n\t\t\n\t\t/* If the file alread exists, check it is a valid geopackage */\n\t\tif (dbFile.exists()) {\n\n\t\t\tif (!isGPKGValid(false)) \n\t\t\t\tthrow new IllegalArgumentException(\"GeoPackage \"+dbFile.getName()+\" failed integrity checks - Check the source.\");\n\t\t\t\n\t\t} else {\n\t\t\t\n\t\t\tlog.log(Level.INFO, \"Database file does not exist. Creating new GeoPackage \"+dbFile.getName());\n\t\t\t\n\t\t\t// Create the DB file\n\t\t\tthis.sqlDB.createDatabase();\n\n\t\t\tfor (GpkgTable tab : sysTables.values()) \n\t\t\t\ttab.create(this);\n\t\t\tfor (GpkgView view : sysViews.values()) \n\t\t\t\tview.create(this);\n\n\t\t\t// Our standard triggers\n\t\t\tfor (String stmt : GpkgTriggers.ALL_STANDARD_TRIGGERS) sqlDB.execSQL( stmt );\n\t\t\t\n\t\t\tfor (String stmt : GpkgSpatialRefSys.INSERT_DEFAULT_SPATIAL_REF_SYS) \n\t\t\t\tsqlDB.execSQL( stmt );\n\t\t\t\n\t\t\t// Try setting the application_id pragma through Sqlite implementation\n\t\t\tif ( !setGpkgAppPragma() ) setGpkgAppHeader();\n\t\t\t\n\t\t\tif (!isGPKGValid(true)) \n\t\t\t\tthrow new IllegalArgumentException(\"GeoPackage \"+dbFile.getName()+\" failed integrity checks - Check the source.\");\n\t\t\t\n\t\t}\n\t\t\n\t\tlog.log(Level.INFO, \"Connected to GeoPackage \"+dbFile.getName());\n\t}\n\t/** Get the name of the database file associated with this GeoPackage\n\t * \n\t * @return\n\t */\n\tpublic String getDatabaseFileName() {\n\t\treturn this.dbFile.toString();\n\t}\n\t/** Close the underlying SQLite DB instance associated with this GeoPackge\n\t * \n\t */\n\tpublic void close() {\n\t\tthis.sqlDB.close();\n\t}\n\t/** Check for the {@link #GPKG_APPLICATION_ID} in the database Pragma application_id\n\t * field.\n\t * \n\t * @return True if its set\n\t */\n\tprivate boolean isGpkgAppPragmaSet() {\n\t\tboolean isGPKG = false;\n\n\t\tICursor c = sqlDB.doRawQuery(\"pragma application_id\");\n\t\tif (c.moveToFirst()) {\n\t\t\tisGPKG = c.getInt(0)==GPKG_APPLICATION_ID;\n\t\t}\n\t\tc.close();\n\t\t\n\t\treturn isGPKG;\n\t}\n\t/** Set the GeoPackage application ID pragma.\n\t * \n\t * @return True if set successfully.\n\t */\n\tprivate boolean setGpkgAppPragma() {\n\t\t\n\t\tif (!sqlDB.isOpen()) sqlDB.getDatabase(true);\n\t\tsqlDB.doRawQuery(\"pragma application_id=\"+GPKG_APPLICATION_ID);\n\t\t\n\t\treturn isGpkgAppPragmaSet();\n\t}\n\t/** Manually test whether the SQLite header contains the {@link #GPKG_APPLICATION_ID}\n\t * This is used as no current version of Android supports a version of Sqlite that supports the\n\t * pragma 'application_id', therefore we write to the header manually.\n\t * \n\t * @return True if its set.\n\t */\n\tprivate boolean isGpkgAppHeaderSet() {\n\t\tif (sqlDB.isOpen()) sqlDB.close();\n\t\t\n\t\tboolean isSet = false;\n\t\ttry {\n\t\t\tRandomAccessFile raf = new RandomAccessFile(dbFile, \"r\");\n\t\t\traf.seek(68);\n\t\t\tint n68 = raf.readInt();\n\t\t\tisSet = n68==GPKG_APPLICATION_ID;\n\t\t\traf.close();\n\t\t} catch (FileNotFoundException e) {\n\t\t\te.printStackTrace();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\t\n\t\treturn isSet;\n\t}\n\t/** Manually set the SQLite file header to include the {@link #GPKG_APPLICATION_ID}.\n\t * This is used as no current version of Android supports a version of Sqlite that supports the\n\t * pragma 'application_id', therefore we write to the header manually.\n\t * \n\t * @return True if set, false if there was an error.\n\t */\n\tprivate boolean setGpkgAppHeader() {\n\t\tif (sqlDB.isOpen()) sqlDB.close();\n\t\t\n\t\t/* */\n\t\ttry {\n\t\t\tRandomAccessFile raf = new RandomAccessFile(dbFile, \"rw\");\n\t\t\traf.seek(68);\n\t\t\traf.writeInt( GPKG_APPLICATION_ID );\n\t\t\traf.close();\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\treturn true;\n\t}\n\t/** Check that the GeoPackage is valid according to tests outlined in the specification,\n\t * namely that the application_id is correct, a database integrity returns 'ok' and there\n\t * are no foreign key issues.

\n\t * This check is performed automatically when connecting to a GeoPackage, but should \n\t * be performed before passing a GeoPackage to another client application or service. \n\t * \n\t * @param doIntegrity True to perform a PRAGMA integrity_check. This can take a long\n\t * time on large files (>250mb), therefore it is only normally run \n\t * when a GeoPackage is created through this library.\n\t * \n\t * @return True if the checks pass.\n\t */\n\tpublic boolean isGPKGValid(boolean doIntegrity) {\n\t\tboolean isGPKG = false;\n\t\tboolean integrity = false;\n\t\tboolean foreignKey = false;\n\t\t\n\t\tisGPKG = isGpkgAppPragmaSet();\n\t\tif ( !isGPKG && MODE_STRICT ) isGPKG = isGpkgAppHeaderSet();\n\t\t\n\t\tsqlDB.getDatabase(false);\n\t\tICursor c = null;\n\n\t\tif (doIntegrity) {\n\t\t\tc = sqlDB.doRawQuery(\"PRAGMA integrity_check\");\n\t\t\tif (c.moveToFirst()) {\n\t\t\t\tintegrity = c.getString(0).equals(\"ok\");\n\t\t\t}\n\t\t\tc.close();\n\t\t} else {\n\t\t\tintegrity = true;\n\t\t}\n\t\t\n\t\tc = sqlDB.doRawQuery(\"PRAGMA foreign_key_check\");\n\t\tforeignKey = c.moveToFirst();\n\t\tc.close();\n\t\t\n\t\t// Check all system tables are in the database\n\t\tboolean tabsExist = true;\n\t\tfor (GpkgTable gt : sysTables.values()) {\n\t\t\tif (!gt.isTableInDB(this)) {\n\t\t\t\ttabsExist = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn (isGPKG || MODE_STRICT==false) && integrity && !foreignKey && tabsExist;\n\t\t\n\t}\n\t/** Get the database associated with this GeoPackage\n\t * \n\t * @return\n\t */\n\tpublic ISQLDatabase getDatabase() {\n\t\treturn this.sqlDB;\n\t}\n\n\t/** Get all tiles in the table, at the specified zoom, in order to cover the supplied\n\t * bounding box.\n\t * \n\t * @param tableName The table to query\n\t * @param bbox The extents of the area to cover.\n\t * @param zoomLevel What tile level, or zoom, should the query get\n\t * @return\n\t * @throws Exception\n\t */\n\tpublic List getTiles(String tableName, BoundingBox bbox, int zoomLevel) throws Exception {\n\t\tlog.log(Level.INFO, \"BBOX query for images in \"+tableName);\n\t\t\n\t\tList allFeats = new ArrayList();\n\t\t\n\t\tGpkgTable tilesTable = getUserTable( tableName, GpkgTable.TABLE_TYPE_TILES );\n\t\t\n\t\t// IF strict, check for primary key, although not essential for this query\n\t\tif (MODE_STRICT) { \n\t\t\tif (tilesTable.getPrimaryKey(this).equals(\"unknown\"))\n\t\t\t\tthrow new Exception(\"Primary key not defined on table \"+tableName );\n\t\t}\n\t\t\n\t\t// Is BBOX valid against the table or tile_matrix_set?\n\t\tif ( !checkBBOXAgainstLast(tilesTable, bbox, false, false)) return allFeats;\n\t\t\n\t\t// Tile matrix data for this table\n\t\tGpkgRecords tmRecs = getSystemTable(GpkgTileMatrix.TABLE_NAME).query(\n\t\t\t\tthis, \"table_name='\"+tableName+\"' AND zoom_level=\"+zoomLevel);\n\t\tif (tmRecs.getFieldInt(0, \"zoom_level\")!=zoomLevel)\n\t\t\tthrow new Exception(\"Zoom level \"+zoomLevel+\" is not defined for this tile pyramid\");\n\t\t\n\t\tint tmWidth = tmRecs.getFieldInt(0, \"tile_width\");\n\t\tint tmHeight = tmRecs.getFieldInt(0, \"tile_height\");\n\t\tdouble pixX = tmRecs.getFieldDouble(0, \"pixel_x_size\");\n\t\tdouble pixY = tmRecs.getFieldDouble(0, \"pixel_y_size\");\n\t\t\n\t\t// Construct a temporary matrix_set bbox (for convenience)\n\t\tGpkgRecords tms = getSystemTable(GpkgTileMatrixSet.TABLE_NAME).query(this, \"table_name='\"+tilesTable.tableName+\"'\");\n\t\tBoundingBox tmsBox = new BoundingBoxImpl(\n\t\t\t\ttms.getFieldDouble(0, \"min_x\"), \n\t\t\t\ttms.getFieldDouble(0, \"max_x\"), \n\t\t\t\ttms.getFieldDouble(0, \"min_y\"), \n\t\t\t\ttms.getFieldDouble(0, \"max_y\"));\n\t\t\n\t\t/* TODO Get all tiles in the table at the specified zoom and check the bounds?,\n\t\t * or something else...\n\t\t */\n\t\t\n\t\t\n\t\t/* Calculate the min and max rows and columns.\n\t\t * This mechanism works for 3857 (slippy tiles) but serious doubt it does for \n\t\t * anything else, therefore have to test with other projections and create a generic\n\t\t * mechanism for creating a where clause from a bounding box */\n\t\tint minX = (int) Math.round( (bbox.getMinX() - tmsBox.getMinX() ) / (tmWidth * pixX) );\n\t\tint maxX = (int) Math.round( (bbox.getMaxX() - tmsBox.getMinX() ) / (tmWidth * pixX) );\n\t\tint minY = (int) Math.round( (tmsBox.getMaxY() - bbox.getMaxY() ) / (tmHeight * pixY) );\n\t\tint maxY = (int) Math.round( (tmsBox.getMaxY() - bbox.getMinY() ) / (tmHeight * pixY) );\n\t\t\n\t\tString strWhere = String.format(\n\t\t\t\t\"zoom_level=%s AND tile_column >= %s AND tile_column <= %s AND tile_row >=%s AND tile_row <=%s\", \n\t\t\t\tzoomLevel, minX, maxX, minY, maxY);\n\n\t\treturn getTiles(tableName, strWhere);\n\t\t\n\t}\n\t/** Query the GeoPackage for one or more tiles based on a where clause.\n\t * The SimpleFeature's that are returned have a {@linkplain FeatureType} name\n\t * matching the tableName and a {@link GeometryDescriptor} mathing that defined\n\t * in gpkg_contents for the table.

\n\t * The feature id (accessible via {@link SimpleFeature#getID()}) is the of the form \n\t * TableName-RecordID-zoom-row_ref-col_ref (or tableName-id-zoom-x-y)

\n\t * The image data is stored as a byte[] on an attribute named 'the_image' and the bounds\n\t * of the tile are stored as a {@link BoundingBox} on an attribute named 'the_geom'.\n\t * \n\t * @param tableName The {@linkplain TilesTable#getTableName()} to query\n\t * @param whereClause The SQL where clause, excluding the word 'where'\n\t * @return A List of {@linkplain SimpleFeature}'s \n\t * @throws Exception\n\t */\n\tpublic List getTiles(String tableName, String whereClause) throws Exception {\n\t\tlog.log(Level.INFO, \"WHERE query for images in \"+tableName);\n\t\t\n\t\tList allFeats = new ArrayList();\n\t\t\n\t\tTilesTable tilesTable = (TilesTable)getUserTable( tableName, GpkgTable.TABLE_TYPE_TILES );\n\t\t\n\t\t// IF strict, check for primary key, although not essential for this query\n\t\tif (MODE_STRICT) { \n\t\t\tif (tilesTable.getPrimaryKey(this).equals(\"unknown\"))\n\t\t\t\tthrow new Exception(\"Primary key not defined on table \"+tableName );\n\t\t}\n\t\t\n\t\t// Get the records matching our query\n\t\tGpkgRecords featRecords = tilesTable.query(this, whereClause);\n\t\tif (featRecords.size()==0) return allFeats;\n\t\t\n\t\t// Construct the feature type\n\t\tSimpleFeatureType featureType = tilesTable.getSchema();\n\t\t\n\t\tList attrValues = null;\n\t\tTileMatrixInfo tmi = ((TilesTable)tilesTable).getTileMatrixInfo();\n\t\t\n\t\t// Now go through each record building the feature with it's attribute values\n\t\tfor (int rIdx=0; rIdx < featRecords.size(); rIdx++) {\n\t\t\t\n\t\t\t// Create new list so previous values are not over-written \n\t\t\tattrValues = new ArrayList();\n\t\t\tattrValues.add( featRecords.getFieldBlob(rIdx, \"tile_data\") );\n\t\t\t\n\t\t\t// Construct bounding box for tile\n\t\t\tBoundingBox bbox = tmi.getTileBounds(\n\t\t\t\t\tfeatRecords.getFieldInt(rIdx, \"tile_column\"),\n\t\t\t\t\tfeatRecords.getFieldInt(rIdx, \"tile_row\"),\n\t\t\t\t\tfeatRecords.getFieldInt(rIdx, \"zoom_level\")\n\t\t\t\t\t);\n\t\t\tattrValues.add( bbox );\n\t\t\t\n\t\t\t// Tile details\n\t\t\tattrValues.add( featRecords.getFieldInt(rIdx, \"tile_column\") );\n\t\t\tattrValues.add( featRecords.getFieldInt(rIdx, \"tile_row\") );\n\t\t\tattrValues.add( featRecords.getFieldInt(rIdx, \"zoom_level\") );\n\t\t\t\n\t\t\t// The ID for this tile\n\t\t\tString fid = String.format(\"%s-%s-%s-%s-%s\",\n\t\t\t\t\ttableName,\n\t\t\t\t\tfeatRecords.getFieldInt(rIdx, \"id\"),\n\t\t\t\t\tfeatRecords.getFieldInt(rIdx, \"tile_column\"),\n\t\t\t\t\tfeatRecords.getFieldInt(rIdx, \"tile_row\"),\n\t\t\t\t\tfeatRecords.getFieldInt(rIdx, \"zoom_level\")\n\t\t\t\t\t);\n\t\t\t\n\t\t\t// Create the feature and add to list of all features\n\t\t\tallFeats.add( new SimpleFeatureImpl(fid, attrValues, featureType ) );\n\t\t}\n\t\t\n\t\treturn allFeats;\n\t}\n\t/** Check if this feature is in the GeoPackage.

\n\t * The query is based on {@link SimpleFeatureType#getTypeName()} = tableName and \n\t * {@link SimpleFeature#getID()} = Table.featureFieldName\n\t * \n\t * @param simpleFeature The feature to test.\n\t * @return True if found\n\t */\n\tpublic boolean isFeatureInGeoPackage(SimpleFeature simpleFeature) {\n\t\tString tableName = simpleFeature.getType().getTypeName();\n\t\tFeaturesTable featTable = (FeaturesTable)getUserTable( tableName, GpkgTable.TABLE_TYPE_FEATURES );\n\t\t\n\t\treturn featTable.isFeatureInTable(simpleFeature);\n\n\t}\n\t/** Get a list of all SimpleFeature's within, or intersecting with, the supplied BoundingBox.

\n\t * This version always performs an intersection test and does not check the bbox is within or \n\t * intersecting with the table extents. A StandardGeometryDecoder is used for reading feature\n\t * data.\n\t * \n\t * @param tableName The case sensitive table name in this GeoPackage to query.\n\t * @param bbox The {@link BoundingBox} to find features in, or intersecting with.\n\t * @return A list of {@linkplain SimpleFeature}'s\n\t * @throws Exception If the SRS of the supplied {@link BoundingBox} does not match the SRS of\n\t * the table being queried.\n\t */\n\tpublic List getFeatures(String tableName, BoundingBox bbox) throws Exception {\n\t\treturn getFeatures(tableName, bbox, true, true, new StandardGeometryDecoder() );\n\t}\n\t/** Get a list of {@link SimpleFeature} from the GeoPackage by specifying a where clause\n\t * (for example {@code featureId='pipe.1234'} or {@code id=1234} )\n\t * \n\t * @param tableName The case sensitive table name that holds the feature (probably \n\t * the localName of {@link SimpleFeatureType#getName()}\n\t * @param whereClause The 'Where' clause, less the where. Passing Null will return \n\t * all records from the table, which is discouraged.\n\t * @param geomDecoder The type of {@linkplain GeometryDecoder} to use.\n\t * @return A list of SimpleFeature's or an empty list if none were found in the specified table\n\t * matching the the filter\n\t * \n\t * @throws Exception\n\t */\n\tpublic List getFeatures(String tableName, String whereClause, GeometryDecoder geomDecoder) \n\t\t\tthrows Exception {\n\t\t\n\t\tFeaturesTable featTable = (FeaturesTable)getUserTable( tableName, GpkgTable.TABLE_TYPE_FEATURES );\n\t\t\n\t\tString stmt = \"SELECT * FROM [\"+tableName+\"]\";\n\t\tif (whereClause!=null && !whereClause.equals(\"\")) stmt+=\" WHERE \"+whereClause;\n\t\t\n\t\treturn getFeatures(stmt, featTable, geomDecoder);\n\t\t\n\t}\n\t/** Get a list of all SimpleFeature's within, or intersecting with, the supplied BoundingBox.\n\t * \n\t * @param tableName The case sensitive table name in this GeoPackage to query.\n\t * @param bbox The {@link BoundingBox} to find features in, or intersecting with.\n\t * @param includeIntersect Should feature's intersecting with the supplied box be returned?\n\t * @param testExtents Should the bbox be tested against the data extents in gpkg_contents before\n\t * issuing the query? If False a short test on the extents is performed. (In case table\n\t * extents are null) \n\t * @param geomDecoder The {@link GeometryDecoder} to use for reading feature geometries.\n\t * @return A list of {@linkplain SimpleFeature}'s\n\t * @throws Exception If the SRS of the supplied {@link BoundingBox} does not match the SRS of\n\t * the table being queried.\n\t */\n\tpublic List getFeatures(String tableName, BoundingBox bbox, boolean includeIntersect, \n\t\t\tboolean testExtents, GeometryDecoder geomDecoder) throws Exception {\n\t\tlog.log(Level.INFO, \"BBOX query for features in \"+tableName);\n\t\t\n\t\tList allFeats = new ArrayList();\n\n\t\tFeaturesTable featTable = (FeaturesTable)getUserTable( tableName, GpkgTable.TABLE_TYPE_FEATURES );\n\t\t\n\t\t// Is BBOX valid against the table?\n\t\tif ( !checkBBOXAgainstLast(featTable, bbox, includeIntersect, testExtents)) return allFeats;\n\t\t\n\t\tGeometryInfo gi = featTable.getGeometryInfo();\n\t\t\n\t\tStringBuffer sqlStmt = new StringBuffer();\n\t\tString pk = featTable.getPrimaryKey(this);\n\t\t\n\t\tif (MODE_STRICT) {\n\t\t\tif (pk.equals(\"rowid\"))\n\t\t\t\tthrow new Exception(\"Primary key not defined on table \"+featTable.getTableName() );\n\t\t}\n\t\t\n\t\t// If this GeoPackage is RTREE enabled, use the spatial index\n\t\tif (sqlDB.hasRTreeEnabled() && gi.hasSpatialIndex()) {\n\n\t\t\tString idxTable = \"[rtree_\"+tableName+\"_\"+gi.getColumnName()+\"]\";\n\n\t\t\tsqlStmt.append(\"SELECT [\").append(tableName).append(\"].* FROM [\").append(tableName).append(\"], \");\n\t\t\tsqlStmt.append(idxTable).append(\" WHERE [\");\n\t\t\tsqlStmt.append(tableName).append(\"].\").append(pk).append(\"=\");\n\t\t\tsqlStmt.append(idxTable).append(\".id\");\n\t\t\tsqlStmt.append(\" AND MinX>=\").append( bbox.getMinX() );\n\t\t\tsqlStmt.append(\" AND MaxX<=\").append( bbox.getMaxX() );\n\t\t\tsqlStmt.append(\" AND MinY>=\").append( bbox.getMinY() );\n\t\t\tsqlStmt.append(\" AND MaxY<=\").append( bbox.getMaxY() );\n\t\t\t\n\t\t\treturn getFeatures(sqlStmt.toString(), featTable, geomDecoder);\n\t\t\t\n\t\t}\n\n\t\t/* Query all records in the feature table and check the header envelope\n\t\t * for matchin/ intersecting bounds. If the envelope is null, then the full\n\t\t * geometry is read and checked */\n\t\t\n\t\tsqlStmt.append(\"SELECT * FROM [\").append(tableName).append(\"] WHERE id IN(\");\n\t\t\n\t\t// Query only for feature geometry and test that before getting all attributes\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint totalRecs = featTable.getCount(this);\n\t\t\n\t\tint lastPK = 0, recCount = 0, hitCount = 0;\n\t\tboolean hit = false;\n\t\tEnvelope headerEnv = null;\n\t\tEnvelope query = new Envelope(bbox.getMinX(), bbox.getMaxX(), bbox.getMinY(), bbox.getMaxY());\n\t\t\n\t\t\n\t\t/* Deprecated getCount() on Cursor to save the cursor iterating\n\t\t * whole ResultSet on underlying Cursor implementation */\n\t\t\n\t\t// While we have less records than total for table..\n\t\twhile (recCount < totalRecs) {\n\t\t\t\n\t\t\tString sql = String.format(\"SELECT %s,%s FROM [%s] WHERE %s > %s ORDER BY %s LIMIT %s\",\n\t\t\t\t\tpk, gi.getColumnName(), tableName, pk, lastPK, pk, MAX_RECORDS_PER_CURSOR);\n\t\t\tICursor cPage = getDatabase().doRawQuery( sql );\n\n\t\t\t// Go through these x number of records\n\t\t\tboolean hasRecords = false;\n\t\t\twhile (cPage.moveToNext()) {\n\t\t\t\t\n\t\t\t\thasRecords = true;\n\t\t\t\t// Decode the geometry and test\n\t\t\t\theaderEnv = geomDecoder.setGeometryData( cPage.getBlob(1) ).getEnvelope();\n\t\t\t\t\n\t\t\t\t// No bbox from header, so decode the whole geometry (a lot slower)\n\t\t\t\tif (headerEnv.isNull() && !geomDecoder.isEmptyGeom()) {\n\t\t\t\t\theaderEnv = geomDecoder.getGeometry().getEnvelopeInternal();\n\t\t\t\t}\n\t\n\t\t\t\t// Test bounds\n\t\t\t\thit = (includeIntersect ? query.intersects( headerEnv ) : false) || query.contains( headerEnv ) || headerEnv.contains( query );\n\t\t\t\tif (hit) {\n\t\t\t\t\tsqlStmt.append(cPage.getInt(0)).append(\",\");\n\t\t\t\t\thitCount++;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// Store the last key we saw for the next page query\n\t\t\t\tlastPK = cPage.getInt(0);\n\t\t\t\trecCount++;\n\t\t\t}\n\t\t\n\t\t\tcPage.close();\n\t\t\tif (hasRecords==false) break;\n\t\t}\n\n\t\tlog.log(Level.INFO, recCount+\" geometries checked in \"+(System.currentTimeMillis()-startTime)/1000+\" seconds\");\n\t\t\n\t\t\n\t\t// Didn't find anything\n\t\tif (hitCount==0) return allFeats;\n\t\t\n\t\tsqlStmt.setLength(sqlStmt.length()-1);// How many id's can the DB handle??\n\t\tsqlStmt.append(\");\");\n\n\t\treturn getFeatures(sqlStmt.toString(), featTable, geomDecoder );\n\t\t\n\t}\n\t\n\t/** Get a list of {@link SimpleFeature} from the GeoPackage by specifying a full SQL statement.\n\t * \n\t * @param sqlStatement\n\t * @param featTable\n\t * @param geomDecoder The type of {@linkplain GeometryDecoder} to use.\n\t * @return A list of SimpleFeature's or an empty list if none were found in the specified table\n\t * matching the the filter\n\t * @throws Exception\n\t */\n\tprotected List getFeatures(String sqlStatement, FeaturesTable featTable, GeometryDecoder geomDecoder)\n\t\t\tthrows Exception {\n\t\t\n\t\tList allFeats = new ArrayList();\n\n\t\tint totalRecs = featTable.getCount(this);\n\n\t\tif (totalRecs==0) return allFeats;\n\t\t\n\t\tSimpleFeatureType featureType = featTable.getSchema();\n\t\tList attrTypes = featureType.getTypes();\n\t\tGeometryInfo geomInfo = featTable.getGeometryInfo();\n\t\t\n\t\t// Find the feature id field\n\t\tString featureFieldName = \"\";\n\t\tfor (GpkgField gf : featTable.getFields() ) {\n\t\t\tif ( ((FeatureField)gf).isFeatureID() ) {\n\t\t\t\tfeatureFieldName = gf.getFieldName();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t\t\t\n\t\t/* Query the table in 'pages' of LIMIT number */\n\n\t\tlong startTime = System.currentTimeMillis();\n\t\tString pk = featTable.getPrimaryKey(this);\n\t\t\n\t\tif (MODE_STRICT) {\n\t\t\tif (pk.equals(\"rowid\"))\n\t\t\t\tthrow new Exception(\"Primary key not defined on table \"+featTable.getTableName() );\n\t\t}\n\t\t\n\t\tint lastPK = 0, recCount = 0;\n\t\tsqlStatement = sqlStatement.endsWith(\";\") ? sqlStatement.substring(0, sqlStatement.length()-1) : sqlStatement;\n\t\tint whereIdx = sqlStatement.toLowerCase().indexOf(\"where\");\n\t\tsqlStatement = whereIdx>0 ? sqlStatement+\" AND \" : sqlStatement+\" WHERE \";\n\t\tArrayList attrValues = new ArrayList();\n\t\tObject value = null;\n\t\tString fid;\n\t\tGpkgRecords featRecords = null;\n\t\tString sql = \"\"; \n\t\tString fieldName = null;\n\t\t\n\t\t// While we have less records than total for table..\n\t\twhile (recCount < totalRecs) {\n\n\t\t\tsql = String.format(sqlStatement+\"%s > %s ORDER BY %s LIMIT %s\",\n\t\t\t\t\tpk, lastPK, pk, MAX_RECORDS_PER_CURSOR);\n\t\t\tfeatRecords = featTable.rawQuery(this, sql );\n\n\t\t\tif (featRecords.size()==0) break;\n\n\t\t\t// Now go through each record building the feature with it's attribute values\n\t\t\tfor (int rIdx=0; rIdx < featRecords.size(); rIdx++) {\n\n\t\t\t\t// Create new list so previous values are not overridden \n\t\t\t\tattrValues = new ArrayList();\n\t\t\t\tfid = null;\n\t\t\t\t\n\t\t\t\t/* For each type definition, get the value, ensuring the \n\t\t\t\t * correct order is maintained on the value list*/\n\t\t\t\tfor (int typeIdx=0; typeIdx < attrTypes.size(); typeIdx++) {\n\t\t\t\t\t\n\t\t\t\t\tfieldName = attrTypes.get( typeIdx ).getName().getLocalPart();\n\t\t\t\t\tvalue = featRecords.get(rIdx).get( featRecords.getFieldIdx(fieldName) );\n\t\t\t\t\t\n\t\t\t\t\t// If defined as the feature's ID, store for feature creation\n\t\t\t\t\tif ( fieldName.equals(featureFieldName) ) {\n\t\t\t\t\t\t\n\t\t\t\t\t\tfid = String.valueOf( value );\n\t\t\t\t\t\tcontinue; // Add as ID, not an attribute\n\t\t\t\t\t\t\n\t\t\t\t\t} else if (fieldName.equals(geomInfo.getColumnName())) {\n\t\t\t\t\t\t\n\t\t\t\t\t\t// If geometry column, decode to actual Geometry\n\t\t\t\t\t\tvalue = geomDecoder.setGeometryData( (byte[])value ).getGeometry();\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tattrValues.add(value);\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\tattrValues.trimToSize();\n\t\t\t\t\n\t\t\t\t// Get or create a feature id?\n\t\t\t\tif (fid==null || fid.equals(\"null\")) fid = featTable.getTableName()+\".\"+recCount;\n\n\t\t\t\t// Create the feature and add to list of all features\n\t\t\t\tallFeats.add( new SimpleFeatureImpl(fid, attrValues, featureType ) );\n\n\t\t\t\t// Store the last key we saw for the next page query\n\t\t\t\tlastPK = featRecords.getFieldInt(rIdx, pk );\n\t\t\t\trecCount++;\n\t\t\t}\n\t\t}\n\n\t\tfeatRecords = null;\n\t\tgeomDecoder.clear();\n\t\t\n\t\tlog.log(Level.INFO, recCount+\" features built in \"+(System.currentTimeMillis()-startTime)/1000+\" secs\");\n\t\t\n\t\treturn allFeats;\n\t\t\n\t}\n\n\t/** Convenience method to check the passed bounding box (for a query) CRS matches\n\t * that on the {@link #lastFeatTable} and the bbox is within/ intersects with the \n\t * table boundingbox\n\t * \n\t * @param checkTable The table to check the query box against\n\t * @param queryBBox The query Bounding box\n\t * @param includeIntersect If vector/ feature data, should we test for intersection as\n\t * well as contains?\n\t * @param shortTest If True only the CRS's are tested to make sure they match. If False, the \n\t * table and/ or tile matrix set extents are tested as well.\n\t * @return True if checks pass\n\t */\n\tprivate boolean checkBBOXAgainstLast(GpkgTable checkTable, BoundingBox queryBBox, boolean includeIntersect, boolean shortTest) {\n\t\t\n\t\t// Check the SRS's are the same (Projection beyond scope of implementation)\n\t\tBoundingBox tableBbox = checkTable.getBounds();\n\t\tString qCode = queryBBox.getCoordinateReferenceSystem().getName().getCode();\n\t\tString qCodeS = queryBBox.getCoordinateReferenceSystem().getName().getCodeSpace();\n\t\t\n\t\tString tCode = tableBbox.getCoordinateReferenceSystem().getName().getCode();\n\t\tString tCodeS = tableBbox.getCoordinateReferenceSystem().getName().getCodeSpace();\n\t\t\n\t\tif (!qCode.equalsIgnoreCase(tCode) || !qCodeS.equalsIgnoreCase(tCodeS)) {\n\t\t\tlog.log(Level.WARNING, \"Passed bounding box SRS does not match table SRS\");\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tif (shortTest) return true;\n\t\t\n\t\t\n\t\t/* If GpkgContents has null bounds for this table do full query,\n\t\t * otherwise test the table bounds */\n\t\tboolean queryTable = false;\n\t\t\n\t\tif (!tableBbox.isEmpty()) {\n\t\t\t\n\t\t\tif (checkTable instanceof TilesTable) {\n\t\t\t\t// If tiles, bbox must be inside table extents\n\t\t\t\tqueryTable = queryBBox.intersects( tableBbox ) || tableBbox.contains( queryBBox );\n\t\t\t} else {\n\t\t\t\t// If features, inside or intersects\n\t\t\t\tqueryTable = (includeIntersect ? queryBBox.intersects( tableBbox ) : false) || \n\t\t\t\t\t\t queryBBox.contains( tableBbox ) ||\n\t\t\t\t\t\t tableBbox.contains(queryBBox);\n\t\t\t}\n\t\t\t\n\t\t} else {\n\t\t\t\n\t\t\tif (checkTable instanceof TilesTable) {\n\t\t\t\t// If a tiles table and no bounds in contents, check the tile_matrix_set definitions\n\t\t\t\t\tGpkgRecords tms = null;\n\t\t\t\t\ttry {\n\t\t\t\t\t\ttms = getSystemTable(GpkgTileMatrixSet.TABLE_NAME).query(this, \"table_name='\"+checkTable.tableName+\"'\");\n\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\t// Construct a bbox to test against\n\t\t\t\t\tCoordinateReferenceSystem crs = new CoordinateReferenceSystemImpl(\"\"+tms.getFieldInt(0, \"srs_id\"));\n\t\t\t\t\tBoundingBox tmsBox = new BoundingBoxImpl(\n\t\t\t\t\t\t\ttms.getFieldDouble(0, \"min_x\"), \n\t\t\t\t\t\t\ttms.getFieldDouble(0, \"max_x\"), \n\t\t\t\t\t\t\ttms.getFieldDouble(0, \"min_y\"), \n\t\t\t\t\t\t\ttms.getFieldDouble(0, \"max_y\"),\n\t\t\t\t\t\t\tcrs);\n\t\t\t\t\tqueryTable = queryBBox.intersects( tmsBox ) || tmsBox.contains( queryBBox );\n\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn queryTable;\n\t}\n\t\n\t/** Get a specific GeoPackage system table\n\t * \n\t * @param tableName\n\t * @return\n\t */\n\tpublic GpkgTable getSystemTable(String tableName) {\n\t\treturn sysTables.get(tableName);\n\t}\n\t/** Get one of the user defined tables by name. If the table has not\n\t * been loaded then it is created and cached.\n\t * \n\t * @param tableName The name of the table.\n\t * @param tableType Either {@link GpkgTable#TABLE_TYPE_FEATURES} || {@link GpkgTable#TABLE_TYPE_TILES}\n\t * @return An instance of the table.\n\t * @throws IllegalArgumentException if the table type is not one of the above, or the \n\t * table does not exist in the GeoPackage.\n\t */\n\tpublic GpkgTable getUserTable(String tableName, String tableType) {\n\t\tGpkgTable gpkgTable = userTables.get(tableName);\n\t\t\n\t\tif (gpkgTable==null) {\n\t\t\tif (tableType.equals(GpkgTable.TABLE_TYPE_FEATURES) ) {\n\t\t\t\tgpkgTable = new FeaturesTable(this, tableName);\n\t\t\t} else if (tableType.equals(GpkgTable.TABLE_TYPE_TILES) ) {\n\t\t\t\tgpkgTable = new TilesTable(this, tableName);\n\t\t\t} else {\n\t\t\t\tthrow new IllegalArgumentException(\"Incompatible user table type: \"+tableType);\n\t\t\t}\n\t\t\t\n\t\t\tif (!gpkgTable.isTableInGpkg(this))\n\t\t\t\tthrow new IllegalArgumentException(\"Table \"+tableName+\" does not exist in the GeoPackage\");\n\t\t\t\n\t\t\tuserTables.put(tableName, gpkgTable);\n\t\t}\n\t\t\n\t\treturn gpkgTable;\n\t}\n\t/** Get a list of all user tables within the current GeoPackage.

\n\t * Note that the results of this query are not cached in the same way that system tables are and\n\t * the table data is not populated until a relevant method/ query (on the table) is \n\t * called. This allows for quicker/ lower cost checks on the number and/ or names of tables in \n\t * the GeoPackage.\n\t * \n\t * @param tableType Either {@link GpkgTable#TABLE_TYPE_FEATURES} or {@link GpkgTable#TABLE_TYPE_TILES}\n\t * @return A new list of tables or an empty list if none were found or the wrong tableType was specified.\n\t */\n\tpublic List getUserTables(String tableType) {\n\t\tArrayList ret = new ArrayList();\n\t\t\n\t\tif (!tableType.equals(GpkgTable.TABLE_TYPE_FEATURES) && !tableType.equals(GpkgTable.TABLE_TYPE_TILES))\n\t\t\treturn ret;\n\t\t\n\t\tICursor tables = null;\n\t\ttry {\n\t\t\ttables = sysTables.get(GpkgContents.TABLE_NAME).query(this, new String[]{\"table_name\"},\n\t\t\t\t\t\"data_type='\"+tableType+\"'\");\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t\treturn ret;\n\t\t}\n\t\t\n\t\tGpkgTable tab = null;\n\t\t\n\t\twhile(tables.moveToNext()) {\n\t\t\t\n\t\t\tif (tableType.equals(GpkgTable.TABLE_TYPE_FEATURES)) {\n\t\t\t\ttab = new FeaturesTable(this, tables.getString(0));\n\t\t\t} else {\n\t\t\t\ttab = new TilesTable(this, tables.getString(0));\n\t\t\t}\n\t\t\t\n\t\t\tret.add(tab);\n\t\t}\n\t\ttables.close();\n\t\t\n\t\tret.trimToSize();\n\t\treturn ret;\n\t}\n\n\t/** Insert a collection of tiles in to the GeoPackage\n\t * \n\t * @param features\n\t * @return The number of tiles inserted\n\t * @throws Exception\n\t */\n\tpublic int insertTiles(Collection features) throws Exception {\n\t\tint numInserted = 0;\n\t\tlong rec = -1;\n\t\t\n\t\tfor (SimpleFeature sf : features) {\n\t\t\trec = insertTile(sf);\n\t\t\tif( rec>-1 ) numInserted++;\n\t\t\t\n\t\t}\n\t\t\n\t\treturn numInserted;\n\t}\n\t/** Insert a tile into the GeoPackage from a SimpleFeature.

\n\t * The tile reference is taken from the feature ID in the form of zoom/xRef/yRef\n\t * with or without leading information. The zoom/x/y should be the last three parts\n\t * of the ID, which can include a file extension.

\n\t * The first instance of a byte[] on the feature's attribute will be taken as the image\n\t * data.\n\t * \n\t * @param feature The {@link SimpleFeature} with details as above\n\t * @return The row id of the newly inserted record if successful\n\t * \n\t * @throws Exception If the table does not exist in the GeoPackage or the supplied\n\t * tile reference is not valid for the table or the attributes and/ or reference cannot \n\t * be decoded.\n\t */\n\tpublic long insertTile(SimpleFeature feature) throws Exception {\n\t\t\n\t\tbyte[] tileData = null;\n\t\t// Cycle feature attrs to get the image data (assumes first byte[] is image)\n\t\tfor (int i=0; i w || tileColumn < 1 || tileRow > h || tileRow < 1 || w==-1 || h==-1) {\n\t\t\tthrow new Exception(\"Supplied tile reference is outside the scope of the tile matrix for \"+tableName);\n\t\t}\n\n\t\tMap values = new HashMap();\n\t\tvalues.put(\"zoom_level\", zoom);\n\t\tvalues.put(\"tile_column\", tileColumn);\n\t\tvalues.put(\"tile_row\", tileRow);\n\t\tvalues.put(\"tile_data\", tile);\n\t\t\n\t\tlong recID = tilesTable.insert(this, values);\n\t\t\n\t\tif (recID>0) updateLastChange(tilesTable.getTableName(), tilesTable.getTableType());\n\t\t\n\t\treturn recID;\n\t}\n\t/** Check if a SRS with the supplied code is loaded in GpkgSpatialRefSys\n\t * \n\t * @param srsName The string value of the srs_name or srs_id\n\t * @return True if loaded, false if not or there was an error.\n\t */\n\tpublic boolean isSRSLoaded(String srsName) {\n\t\tboolean loaded = false;\n\t\t\n\t\tint srsID = -2;\n\t\ttry {\n\t\t\tsrsID = Integer.parseInt( srsName );\n\t\t} catch (NumberFormatException ignore) {\n\t\t\t// TODO Look-up the EPSG code number somehow?\n\t\t}\n\t\t\n\t\tString strWhere = srsID>-2 ? \"srs_id=\"+srsID : \"srs_name='\"+srsName+\"'\";\n\n\t\ttry {\n\t\t\tICursor cur = getSystemTable(GpkgSpatialRefSys.TABLE_NAME).query(\n\t\t\t\t\tthis, new String[]{\"srs_name\"}, strWhere);\n\t\t\t\n\t\t\tloaded = cur.moveToNext();\n\t\t\tcur.close();\n\t\t\t\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\t\n\t\treturn loaded;\n\t}\n\n\t/** Create a {@linkplain FeaturesTable} from a {@link SimpleFeatureType}\n\t * \n\t * @param featureType The SimpleFeatureType to use.\n\t * @param tableExtents The extents for this table\n\t * @return The new FeaturesTable\n\t * @throws Exception If the supplied data is invalid or constraints are not \n\t * met (i.e No matching SRS definition in the gpkg_spatial_ref_sys table)\n\t */\n\tpublic FeaturesTable createFeaturesTable(SimpleFeatureType featureType, BoundingBox tableExtents) throws Exception {\n\t\tFeaturesTable ft = new FeaturesTable( this, featureType.getTypeName());\n\t\t\n\t\tft.create( featureType, tableExtents );\n\t\t\n\t\treturn ft;\n\t}\n\t/** Add all {@link SimpleFeature}'s on the supplied collection into the GeoPackage as a batch.\n\t * If there are multiple feature types within the collection they are\n\t * automatically split to their corresponding tables.\n\t * The table name to insert into is taken from the local part of\n\t * the {@link FeatureType#getName()}.

\n\t * The relevant tables must already exist in the GeoPackage.\n\t * \n\t * @param features\n\t * @return The number of records inserted\n\t * @throws Exception\n\t */\n\tpublic int insertFeatures(Collection features) throws Exception {\n\t\t\n\t\t/* Features within the collection could be different types, so split\n\t\t * in to seperate lists for batch insertion */\n\t\tMap> sfByType = new HashMap>();\n\t\tfor (SimpleFeature sf : features) {\n\t\t\tName tName = sf.getType().getName();\n\t\t\tList thisType = sfByType.get(tName);\n\t\t\t\n\t\t\tif (thisType==null) {\n\t\t\t\tthisType = new ArrayList();\n\t\t\t\tsfByType.put(tName, thisType);\n\t\t\t}\n\t\t\tthisType.add(sf);\n\t\t\t\n\t\t}\n\t\t\n\t\tint numInserted = 0;\n\t\tFeaturesTable featTable = null;\n\t\t\n\t\t// For each set of feature's in our individual lists..\n\t\tfor (Map.Entry> e : sfByType.entrySet()) {\n\t\t\t\n\t\t\tfeatTable = (FeaturesTable)getUserTable( \n\t\t\t\t\te.getKey().getLocalPart(), GpkgTable.TABLE_TYPE_FEATURES );\n\t\t\tList> insertVals = new ArrayList>();\n\t\t\t\n\t\t\tCollection tabFields = featTable.getFields();\n\t\t\t\n\t\t\t\n\t\t\t// Get and check dimensional output\n\t\t\tint mOpt = featTable.getGeometryInfo().getMOption();\n\t\t\tint zOpt = featTable.getGeometryInfo().getZOption();\n\t\t\tint dimension = 2;\n\t\t\tif (\tmOpt==Z_M_VALUES_MANDATORY || zOpt==Z_M_VALUES_MANDATORY \n\t\t\t\t\t|| mOpt==Z_M_VALUES_OPTIONAL || zOpt==Z_M_VALUES_OPTIONAL) {\n\t\t\t\tdimension = 3;\n\t\t\t}\n\t\t\tif (mOpt==Z_M_VALUES_MANDATORY && zOpt==Z_M_VALUES_MANDATORY)\n\t\t\t\tthrow new IllegalArgumentException(\"4 dimensional output is not supported\");\n\t\t\t\n\t\t\t\n\t\t\t// Build values for each feature of this type..\n\t\t\tfor (SimpleFeature sf : e.getValue()) {\n\t\t\t\tinsertVals.add( buildInsertValues(sf, tabFields, dimension) );\n\t\t\t}\n\t\t\t\n\t\t\t// Do the update on the table\n\t\t\tnumInserted += featTable.insert(this, insertVals);\n\t\t\tinsertVals = null;\n\t\t}\n\t\t\n\t\tsfByType = null;\n\t\t\n\t\tif (numInserted>0) updateLastChange(featTable.getTableName(), featTable.getTableType());\n\t\t\n\t\treturn numInserted; \n\t}\n\t/** Insert a single {@link SimpleFeature} into the GeoPackage.\n\t * The table name to insert into is taken from the local part of\n\t * the {@link FeatureType#getName()}.\n\t * \n\t * @param feature The SimpleFeature to insert.\n\t * @return The RowID of the new record or -1 if not inserted\n\t * @throws Exception\n\t * @see {@link #insertFeatures(Collection)} for batch processing many features\n\t */\n\tpublic long insertFeature(SimpleFeature feature) throws Exception {\n\t\tSimpleFeatureType type = feature.getType();\n\t\t\n\t\tFeaturesTable featTable = (FeaturesTable)getUserTable( \n\t\t\t\ttype.getName().getLocalPart(), GpkgTable.TABLE_TYPE_FEATURES );\n\n\t\t// Get and check dimensional output\n\t\tint mOpt = featTable.getGeometryInfo().getMOption();\n\t\tint zOpt = featTable.getGeometryInfo().getZOption();\n\t\tint dimension = 2;\n\t\tif (\tmOpt==Z_M_VALUES_MANDATORY || zOpt==Z_M_VALUES_MANDATORY \n\t\t\t\t|| mOpt==Z_M_VALUES_OPTIONAL || zOpt==Z_M_VALUES_OPTIONAL) {\n\t\t\tdimension = 3;\n\t\t}\n\t\tif (mOpt==Z_M_VALUES_MANDATORY && zOpt==Z_M_VALUES_MANDATORY)\n\t\t\tthrow new IllegalArgumentException(\"4 dimensional output is not supported\");\n\t\t\n\t\tMap values = buildInsertValues(feature, featTable.getFields(), dimension);\n\t\t\n\t\tlong recID = featTable.insert(this, values);\n\t\t\n\t\tif (recID>0) updateLastChange(featTable.getTableName(), featTable.getTableType());\n\t\t\n\t\treturn recID;\n\t}\n\t/** Create a Map of field name to field value for inserting into a table.\n\t * \n\t * @param feature The {@link SimpleFeature}\n\t * @param tabFields The GeoPackage table fields to use for building the map.\n\t * @param geomDimension 2 or 3 for the Geomaetry ordinates/\n\t * @return A Map \n\t * @throws IOException\n\t */\n\tprivate Map buildInsertValues(SimpleFeature feature, \n\t\t\tCollection tabFields, int geomDimension) throws IOException {\n\t\t\n\t\t// Construct values\n\t\tSimpleFeatureType type = feature.getType();\n\t\tMap values = new HashMap();\n\t\tObject value = null;\n\t\tFeatureField field = null;\n\t\tboolean passConstraint = true;\n\t\t\n\t\t// For each field defined in the table...\n\t\tfor (GpkgField f : tabFields) {\n\t\t\t\n\t\t\tif (f.isPrimaryKey()) continue; // We can't update the PK!\n\t\t\n\t\t\tfield = (FeatureField)f;\n\t\t\t\n\t\t\t// If defined as feature id, use getID, else find the attribute\n\t\t\tif ( field.isFeatureID() ) {\n\t\t\t\tvalue = feature.getID();\n\t\t\t} else {\n\t\t\t\tint idx = type.indexOf( field.getFieldName() );\n\t\t\t\t/* If the field is not available on the type, set to null to ensure\n\t\t\t\t * the value list matches the table definition */\n\t\t\t\tif (idx==-1 || idx > type.getAttributeCount()) {\n\t\t\t\t\tvalue = null; \n\t\t\t\t} else {\n\t\t\t\t\tvalue = feature.getAttribute(idx);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tpassConstraint = true;\n\t\t\t\n\t\t\t// Check constraint if not a blob\n\t\t\tif (field.getMimeType()==null && field.getConstraint()!=null) {\n\t\t\t\tpassConstraint = field.getConstraint().isValueValid( value );\n\t\t\t}\n\t\t\t\n\t\t\tif(passConstraint) {\n\t\t\t\tif (value instanceof Geometry) {\n\t\t\t\t\tvalues.put(field.getFieldName(), encodeGeometry( (Geometry)value, geomDimension ) );\n\t\t\t\t} else {\n\t\t\t\t\tvalues.put(field.getFieldName(), value);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (MODE_STRICT) {\n\t\t\t\t\tthrow new IllegalArgumentException(\"Field \"+field.getFieldName()+\" did not pass constraint check\");\n\t\t\t\t}\n\t\t\t\tlog.log(Level.WARNING, \"Field \"+field.getFieldName()+\" did not pass constraint check; Inserting Null\");\n\t\t\t\tvalues.put(field.getFieldName(), null);\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t\treturn values;\n\t}\n\t/** Set a limit on the number of vertices permissible on a single geometry\n\t * when trying to insert new features. If the limit is exceeded then the \n\t * geometries are simplified using the supplied tolerance.\n\t * Default is no limit (-1)\n\t * \n\t * @param limitTo Max vertices\n\t * @param tolerance The tolerance to apply during simplification. This value\n\t * should be appropriate to the geometry's SRS\n\t */\n\tpublic void setSimplifyOnInsertion(int limitTo, double tolerance) {\n\t\tthis.MAX_VERTEX_LIMIT = limitTo;\n\t\tsimpleTolerance = tolerance;\n\t}\n\tprivate double simpleTolerance = 1;\n\t/** Encode a JTS {@link Geometry} to standard GeoPackage geometry blob\n\t * \n\t * @param geom The Geometry to encode\n\t * @param outputDimension How many dimensions to write (2 or 3). JTS does not support 4\n\t * @return\n\t * @throws IOException\n\t */\n\tprivate byte[] encodeGeometry(Geometry geom, int outputDimension) throws IOException {\n\t\tif (geom==null) throw new IOException(\"Null Geometry passed\");\n\t\t\n\t\tif (outputDimension < 2 || outputDimension > 3)\n\t\t\tthrow new IllegalArgumentException(\"Output dimension must be 2 or 3\");\n\t\t\n\t\t// Stop outrageous geometries from being encoded and inserted\n\t\tif (MAX_VERTEX_LIMIT>0) {\n\t\t\tint b4 = geom.getNumPoints();\n\t\t\tif (b4 > MAX_VERTEX_LIMIT) {\n\t\t\t\tgeom = DouglasPeuckerSimplifier.simplify(geom, simpleTolerance);\n\t\t\t\tgeom.geometryChanged();\n\t\t\t\tint af = geom.getNumPoints();\n\t\t\t\tlog.log(Level.WARNING, \"Geometry Simplified for insertion: \"+b4+\" to \"+af+\" points\");\n\t\t\t}\n\t\t}\n\t\t\n\t\tByteArrayOutputStream output = new ByteArrayOutputStream();\n\n\t\t// 'Magic' and Version\n\t\toutput.write( \"GP\".getBytes() );\n\t\toutput.write( GPKG_GEOM_HEADER_VERSION );\n\t\t\n\t\t// Header flags\n\t\tint endianOrder = ByteOrderValues.BIG_ENDIAN;\n\t\tbyte flags = 0;\n\t\tif (GPKG_GEOMETRY_LITTLE_ENDIAN) {\n\t\t\tflags = (byte) (flags | (1 << 0));\n\t\t\tendianOrder = ByteOrderValues.LITTLE_ENDIAN;\n\t\t}\n\t\tif (!geom.getEnvelopeInternal().isNull()) {\n\t\t\t/* JTS Envelope geoms are only ever XY, not XYZ or XYZM\n\t\t\t * therefore we only ever set the 2nd bit to 1 */\n\t\t\tflags = (byte) (flags | (1 << 1));\n\t\t}\n\t\tif ( geom.isEmpty() ) {\n\t\t\t// Set envelope bit to 0\n\t\t\tflags = (byte) (flags | (1 << 0));\n\t\t\t// Flag the geometry is empty\n\t\t\tflags = (byte) (flags | (1 << 4));\n\t\t}\n\t\tif (GPKG_GEOMETRY_STANDARD==false) {\n\t\t\t// ExtendedGeoPackageBinary encoding\n\t\t\tflags = (byte) (flags | (1 << 5));\n\t\t}\n\t\t// Bits 7 and 8 are currently reserved and un-used\n\t\toutput.write(flags);\n\t\t\n\t\t// SRS\n\t\tbyte[] buffer = new byte[4];\n\t\tByteOrderValues.putInt(geom.getSRID(), buffer, endianOrder);\n\t\toutput.write(buffer);\n\t\t\n\t\tEnvelope envelope = geom.getEnvelopeInternal();\n\t\t/* Geom envelope - JTS only supports 2 dimensional envelopes. If Geom is\n\t\t * empty then we don't encode an envelope */\n\t\tif (!envelope.isNull() && !geom.isEmpty()) {\n\t\t\tbuffer = new byte[8];\n\t\t\t// Min X\n\t\t\tByteOrderValues.putDouble(envelope.getMinX(), buffer, endianOrder);\n\t\t\toutput.write(buffer);\n\t\t\t// Max X\n\t\t\tByteOrderValues.putDouble(envelope.getMaxX(), buffer, endianOrder);\n\t\t\toutput.write(buffer);\n\t\t\t// Min Y\n\t\t\tByteOrderValues.putDouble(envelope.getMinY(), buffer, endianOrder);\n\t\t\toutput.write(buffer);\n\t\t\t// Max Y\n\t\t\tByteOrderValues.putDouble(envelope.getMaxY(), buffer, endianOrder);\n\t\t\toutput.write(buffer);\n\t\t}\n\t\t\n\t\t// Write the geometry\n\t\toutput.write( new OGCWKBWriter( outputDimension ).write(geom) );\n\t\t\n\t\tbuffer = output.toByteArray();\n\t\toutput.close();\n\t\t\n\t\treturn buffer;\n\t}\n\t/** Update last_change field in GpkgContents for the given table name and type\n\t * to 'now'.\n\t * \n\t * @param tableName\n\t * @param tableType\n\t */\n\tprivate void updateLastChange(String tableName, String tableType) {\n\t\tMap values = new HashMap();\n\t\tvalues.put(\"last_change\", DateUtil.serializeDateTime(System.currentTimeMillis(), true) );\n\t\tString where = String.format(\"table_name='%s' and data_type='%s'\", tableName, tableType);\n\t\tgetSystemTable(GpkgContents.TABLE_NAME).update(this, values, where);\n\t}\n\t/** Insert an OWS Context document correctly in to the GeoPackage.

\n\t * This method only allows for one Context Document within the GeoPackage.\n\t * \n\t * @param contextDoc Properly formatted document as a String (JSON or XML)\n\t * @param mimeType The encoding of the Context document (JSON or XML)\n\t * @param overwrite If True any current record is overwritten. If False\n\t * and there is an existing record then nothing is done and the method will \n\t * return False.\n\t * @return True if inserted/ updated successfully.\n\t */\n\tpublic boolean insertOWSContext(String contextDoc, String mimeType, boolean overwrite) {\n\t\tif (contextDoc==null || contextDoc.equals(\"\") || mimeType==null) return false;\n\t\tif (\t!mimeType.equalsIgnoreCase(\"text/xml\") &&\n\t\t\t\t!mimeType.equalsIgnoreCase(\"application/xml\") &&\n\t\t\t\t!mimeType.equalsIgnoreCase(\"application/json\") ) {\n\t\t\tthrow new IllegalArgumentException(\"Incorrect mimeType specified\");\n\t\t}\n\t\t\t\t\n\t\t// Do we have an existing record?\n\t\tGpkgTable md = getSystemTable(GpkgMetaData.TABLE_NAME);\n\t\tICursor c = md.query(this, new String[]{\"id\"}, \"md_standard_uri='http://www.opengis.net/owc/1.0'\");\n\t\tint cID = -1;\n\t\tif (c.moveToNext()) {\n\t\t\tcID = c.getInt(0);\n\t\t\tc.close();\n\t\t}\n\t\t\n\t\tMap values = new HashMap();\n\t\tvalues.put(\"md_scope\", GpkgMetaData.SCOPE_UNDEFINED);\n\t\tvalues.put(\"md_standard_uri\", \"http://www.opengis.net/owc/1.0\");\n\t\tvalues.put(\"mime_type\", mimeType);\n\t\tvalues.put(\"metadata\", contextDoc);\n\t\t\n\t\tboolean updated = false;\n\t\tlong mdRec = -1, mdrRec = -1;\n\t\tif (overwrite && cID > -1) {\n\t\t\tupdated = md.update(this, values, \"id=\"+cID) > 0;\n\t\t} else if (cID > -1) {\n\t\t\t// Don't overwrite, but has record so return false\n\t\t\treturn false;\n\t\t} else if (cID==-1) {\n\t\t\t// No record, so insert\n\t\t\tmdRec = getSystemTable(GpkgMetaData.TABLE_NAME).insert(this, values);\n\t\t}\n\t\t\n\t\t// Didn't insert or update\n\t\tif (mdRec==-1 && updated==false) return false;\n\t\t\n\t\tvalues.clear();\n\t\t\n\t\tif (updated) {\n\t\t\t// Update timestamp\n\t\t\tvalues.put(\"timestamp\", DateUtil.serializeDateTime(System.currentTimeMillis(), true) );\n\t\t\tmdrRec = getSystemTable(GpkgMetaDataReference.TABLE_NAME).update(this, values, \"md_file_id=\"+cID);\n\t\t} else {\n\t\t\tvalues.put(\"reference_scope\", GpkgMetaDataReference.SCOPE_GEOPACKAGE);\n\t\t\tvalues.put(\"md_file_id\", mdRec);\n\t\t\tmdrRec = getSystemTable(GpkgMetaDataReference.TABLE_NAME).insert(this, values);\n\t\t}\n\t\t\n\t\t// Rollback GpkgMetaData if reference not inserted\n\t\tif (mdrRec < 1) {\n\t\t\tgetSystemTable(GpkgMetaData.TABLE_NAME).delete(this, \"id=\"+mdRec);\n\t\t}\n\t\t\n\t\treturn mdrRec > -1;\n\t}\n\t/** Get the String representation of an OWS Context Document from the GeoPackage.

\n\t * Only the first Context Document within the GeoPackage is returned\n\t * ( as defined by md_standard_uri='http://www.opengis.net/owc/1.0' )\n\t * \n\t * @return String[] The first entry is the Context mime-type, the second is the \n\t * String representation of the document.\n\t */\n\tpublic String[] getOWSContext() {\n\t\tString[] ret = new String[2];\n\t\t\n\t\tICursor c = getSystemTable(GpkgMetaData.TABLE_NAME).query(\n\t\t\t\t\t\tthis, \n\t\t\t\t\t\tnew String[]{\"mime_type\", \"metadata\"},\n\t\t\t\t\t\t\"md_standard_uri='http://www.opengis.net/owc/1.0'\");\n\t\tif(c.moveToFirst()) {\n\t\t\tret = new String[] {c.getString(0), c.getString(1)};\n\t\t}\n\t\tc.close();\n\t\t\n\t\treturn ret;\n\t}\n\t/** Add a new constraint to the GeoPackage that can be referenced, using the same constraint_name,\n\t * from gpkg_data_columns.

\n\t * \n\t * The constraint must be created before a record that uses it is inserted into gpkg_data_columns, therefore\n\t * constraint names specified on {@link AttributeType}'s via the user-data must be added through this \n\t * method prior to passing the attribute definitions to \n\t * {@link #createFeatureTable(String, String, List, List, BoundingBox, String, boolean)} \n\t * with dataColumns set to True.

\n\t * \n\t * Any existing constraint(s) in the GeoPackage with the same name are updated (delete-insert).

\n\t * \n\t * @param tableName The name of the table to apply this constraint to.\n\t * @param columnNames An array of column names to apply this constrain to, WRT the tableName\n\t * @param dcConstraint {@link DataColumnConstraint}\n\t * \n\t */\n\tpublic long addDataColumnConstraint(String tableName, String[] columnNames, DataColumnConstraint dcConstraint) {\n\t\tif (dcConstraint==null || dcConstraint.isValid()==false) return -1L;\n\t\t\n\t\tGpkgDataColumnConstraint dcc = new GpkgDataColumnConstraint();\n\t\tDataColumnConstraint existingDCC = dcc.getConstraint(this, dcConstraint.constraintName);\n\t\t\n\t\tif (existingDCC!=null) {\n\t\t\tif (existingDCC.constraintType.equals(GpkgDataColumnConstraint.TYPE_ENUM)) {\n\t\t\t\t/* Do we want to delete everything and re-insert, or check and update?\n\t\t\t\t * Currently delete everything and re-insert */\n\t\t\t\tdcc.delete(this, \"constraint_name='\"+dcConstraint.constraintName+\"'\");\n\t\t\t} else {\n\t\t\t\tdcc.delete(this, \"constraint_name='\"+dcConstraint.constraintName+\"'\");\n\t\t\t}\n\t\t}\n\n\t\t// Insert the constraint\n\t\tlong newRec = dcc.insert(this, dcConstraint.toMap());\n\t\t\n\t\t// Didn't insert/ update so don't update feature table\n\t\tif (newRec ==-1) return -1L;\n\t\t\n\t\t// Update GpkgDataColumns for the specified columns\n\t\tMap vals = null;\n\t\tGpkgTable sys = getSystemTable(GpkgDataColumns.TABLE_NAME);\n\t\tfor (String col : columnNames) {\n\t\t\tvals = new HashMap();\n\t\t\tvals.put(\"constraint_name\", dcConstraint.constraintName);\n\t\t\tsys.update(this, vals, \"table_name='\"+tableName+\"' AND column_name='\"+col+\"';\");\n\t\t}\n\n\t\treturn newRec;\n\t}\n\n\n\t/** Check that the supplied geometry type name is valid for a GeoPackage\n\t * \n\t * @param geomDescriptor The GeometryDescriptor to check from.\n\t * @return True if its valid\n\t */\n\tpublic boolean isGeomTypeValid(GeometryDescriptor geomDescriptor) {\n\t\tString geomType = geomDescriptor.getType().getName().getLocalPart().toLowerCase();\n\n\t\tif (geomType.equals(\"geometry\")) {\n\t\t\treturn true;\n\t\t} else\tif (geomType.equals(\"point\")) {\n\t\t\treturn true;\n\t\t} else if (geomType.equals(\"linestring\")) {\n\t\t\treturn true;\n\t\t} else if (geomType.equals(\"polygon\")) {\n\t\t\treturn true;\n\t\t} else if (geomType.equals(\"multipoint\")) {\n\t\t\treturn true;\n\t\t} else if (geomType.equals(\"multilinestring\")) {\n\t\t\treturn true;\n\t\t} else if (geomType.equals(\"multipolygon\")) {\n\t\t\treturn true;\n\t\t} else if (geomType.equals(\"geomcollection\")) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\t/** Encode basic Java types to those permissible in a GeoPackage\n\t * \n\t * @param object The object value to decode\n\t * @return A String usable for a table definition data type. Defaults to TEXT for\n\t * any unknown class or Object\n\t */\n\tpublic static String encodeType(Class clazz) {\n\t\tString name = clazz.getSimpleName().toLowerCase();\n\n\t\tif (name.equals(\"integer\") || name.equals(\"int\")) {\n\t\t\treturn \"INTEGER\";\n\t\t} else if (name.equals(\"string\")) {\n\t\t\treturn \"TEXT\";\n\t\t} else if (name.equals(\"boolean\") || name.equals(\"byte\")) {\n\t\t\treturn \"BOOL\";\n\t\t} else if (name.equals(\"double\") || name.equals(\"float\")) {\n\t\t\treturn \"REAL\";\n\t\t} else if (name.equals(\"long\")) {\n\t\t\treturn \"INTEGER\";\n\t\t} else if (name.equals(\"geometry\") || name.equals(\"byte[]\")) {\n\t\t\treturn \"BLOB\";\n\t\t}\n\t\t\n\t\treturn \"TEXT\";\n\t}\n\t/** Decode SQLite data types to Java classes\n\t * \n\t * @param sqlType\n\t * @return\n\t */\n\tpublic Class decodeType(String sqlType) {\n\t\t\n\t\tJavaType jType = sqlTypeMap.get(sqlType.toLowerCase());\n\t\tif (jType==null || jType==JavaType.UNKNOWN) \n\t\t\tthrow new IllegalArgumentException(\"Unknown SQL data type '\"+sqlType+\"'\");\n\t\t\n\t\tswitch (jType) {\n\t\tcase INTEGER:\n\t\t\treturn Integer.class;\n\t\tcase STRING:\n\t\t\treturn String.class;\n\t\tcase BOOLEAN:\n\t\t\treturn Boolean.class;\n\t\tcase FLOAT:\n\t\t\treturn Float.class;\n\t\tcase DOUBLE:\n\t\t\treturn Double.class;\n\t\tcase BYTE_ARR:\n\t\t\treturn Byte[].class;\n\t\t}\n\n\t\treturn String.class;\n\t}\n\n\n\n}\n"},"new_file":{"kind":"string","value":"AugTech_GeoAPI_Impl/com/augtech/geoapi/geopackage/GeoPackage.java"},"old_contents":{"kind":"string","value":"/*\n * GeoPackage.java\n * \n * Copyright 2013, Augmented Technologies Ltd.\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.augtech.geoapi.geopackage;\n\nimport java.io.ByteArrayOutputStream;\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.IOException;\nimport java.io.RandomAccessFile;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\n\nimport org.opengis.feature.simple.SimpleFeature;\nimport org.opengis.feature.simple.SimpleFeatureType;\nimport org.opengis.feature.type.AttributeType;\nimport org.opengis.feature.type.FeatureType;\nimport org.opengis.feature.type.GeometryDescriptor;\nimport org.opengis.feature.type.Name;\nimport org.opengis.geometry.BoundingBox;\nimport org.opengis.referencing.crs.CoordinateReferenceSystem;\n\nimport com.augtech.geoapi.feature.SimpleFeatureImpl;\nimport com.augtech.geoapi.geometry.BoundingBoxImpl;\nimport com.augtech.geoapi.geopackage.geometry.GeometryDecoder;\nimport com.augtech.geoapi.geopackage.geometry.OGCWKBWriter;\nimport com.augtech.geoapi.geopackage.geometry.StandardGeometryDecoder;\nimport com.augtech.geoapi.geopackage.table.FeatureField;\nimport com.augtech.geoapi.geopackage.table.FeaturesTable;\nimport com.augtech.geoapi.geopackage.table.FeaturesTable.GeometryInfo;\nimport com.augtech.geoapi.geopackage.table.GpkgContents;\nimport com.augtech.geoapi.geopackage.table.GpkgDataColumnConstraint;\nimport com.augtech.geoapi.geopackage.table.GpkgDataColumnConstraint.DataColumnConstraint;\nimport com.augtech.geoapi.geopackage.table.GpkgDataColumns;\nimport com.augtech.geoapi.geopackage.table.GpkgExtensions;\nimport com.augtech.geoapi.geopackage.table.GpkgExtensions.Extension;\nimport com.augtech.geoapi.geopackage.table.GpkgGeometryColumns;\nimport com.augtech.geoapi.geopackage.table.GpkgMetaData;\nimport com.augtech.geoapi.geopackage.table.GpkgMetaDataReference;\nimport com.augtech.geoapi.geopackage.table.GpkgSpatialRefSys;\nimport com.augtech.geoapi.geopackage.table.GpkgTileMatrix;\nimport com.augtech.geoapi.geopackage.table.GpkgTileMatrixSet;\nimport com.augtech.geoapi.geopackage.table.GpkgTriggers;\nimport com.augtech.geoapi.geopackage.table.TilesTable;\nimport com.augtech.geoapi.geopackage.table.TilesTable.TileMatrixInfo;\nimport com.augtech.geoapi.geopackage.views.GpkgView;\nimport com.augtech.geoapi.geopackage.views.STGeometryColumns;\nimport com.augtech.geoapi.geopackage.views.STSpatialRefSys;\nimport com.augtech.geoapi.geopackage.views.SpatialRefSys;\nimport com.augtech.geoapi.referncing.CoordinateReferenceSystemImpl;\nimport com.vividsolutions.jts.geom.Envelope;\nimport com.vividsolutions.jts.geom.Geometry;\nimport com.vividsolutions.jts.io.ByteOrderValues;\nimport com.vividsolutions.jts.simplify.DouglasPeuckerSimplifier;\n\npublic class GeoPackage {\n\tprotected ISQLDatabase sqlDB = null;\n\tprotected File dbFile = null;\n\t\n\tpublic enum JavaType {\n\t\tINTEGER,\n\t\tSTRING,\n\t\tBOOLEAN,\n\t\tFLOAT,\n\t\tDOUBLE,\n\t\tBYTE_ARR,\n\t\tUNKNOWN\n\t}\n\t/** A map of possible SQL Field types to {@link JavaType} enum values.\n\t * Field type names are all lowercase */\n\tpublic Map sqlTypeMap = new HashMap();\n\t\n\tpublic Logger log = Logger.getAnonymousLogger();\n\tprivate Map sysTables = new HashMap();\n\tprivate Map sysViews = new HashMap();\n\tprivate Map userTables = new HashMap();\n\t\n\t/** The name to create (if required) and test for use as a FeatureID within the GeoPackage */\n\tpublic static String FEATURE_ID_FIELD_NAME = \"feature_id\";\n\t/** For each new FeaturesTable, create an R*Tree index if the SQLite library supports it?\n\t * Default is True. If the library does not support R*Tree ({@link ISQLDatabase#hasRTreeEnabled()}\n\t * then indexes cannot be created. */\n\tpublic static final boolean CREATE_RTREE_FOR_FEATURES = true;\n\t/** The OGC GeoPackage specification these statements relate to */\n\tpublic static final String SPEC_VERSION = \"OGC 12-128r9 - 0.9.7 - v8\";\n\t/** The maximum currently supported GeoPacakge version */\n\tpublic static final int MAX_GPKG_VERSION = 0;\n\t/** The Sqlite registered application_id for a GeoPackage */\n\tpublic static final int GPKG_APPLICATION_ID = Integer.decode(\"0x47503130\");\n\t/** The maximum number of vertices permissible on a single Geometry. \n\t * -1 = no limit */\n\tprotected int MAX_VERTEX_LIMIT = -1;\n\t/** If True, reading of GeoPackage headers, pragmas and Geometry encodings will\n\t * be validated against the specification and exceptions thrown if not valid.\n\t * If False, checks will be performed, but exceptions won't be thrown unless\n\t * data cannot be understood. Typical examples are the application_id pragma and Geometry.*/\n\tpublic static boolean MODE_STRICT = true;\n\t\t\n\t/** The Geometry version to write in to the Geometry columns. Default is 0 \n\t * for Version 1.0 */\n\tpublic static int GPKG_GEOM_HEADER_VERSION = 0;\n\t\n\t/** If {@code True} insert StandardGeoPackageBinary geometries into the GeoPackage.\n\t * If {@code False} then the Geometry header is set to ExtendedGeoPackageBinary \n\t * (which this implementation does not yet implement - clause 3.1.2, Annex K of spec).\n\t * Default is {@code True} */\n\tpublic static boolean GPKG_GEOMETRY_STANDARD = true;\n\t/** Encode new Geometry in Little Endian order? Default is {@code False} */\n\tpublic static boolean GPKG_GEOMETRY_LITTLE_ENDIAN = false;\n\t\n\tpublic static final int Z_M_VALUES_PROHIBIT = 0;\n\tpublic static final int Z_M_VALUES_MANDATORY = 1;\n\tpublic static final int Z_M_VALUES_OPTIONAL = 2;\n\t\n\t/** An array of extensions applicable to this GeoPackage */\n\tprotected Extension[] gpkgExtensions = null;\n\t/** The maximum number of records to fetch in one go through the cursor. Default is 1000.\n\t * Increasing this number may result in slightly faster queries on large recordsets,\n\t * but could also result in memory exceptions or missing records (especially on mobile\n\t * devices with limited memory. (Tested on Android at 1000) */\n\tpublic static int MAX_RECORDS_PER_CURSOR = 1000;\n\t\n\t/** Connect to, or create a new GeoPackage with the supplied name and version.

\n\t * If the supplied name already exists then the database is checked to see if it\n\t * is a valid GeoPackage. If the supplied file does not exist, a new empty GeoPackage\n\t * is created with the supplied name.\n\t * \n\t * @param fileName The name of the GeoPackage to create or connect to. The .gpkg extension is added \n\t * if not supplied.\n\t * @param overwrite Overwrite the existing GeoPackage?\n\t * @throws Exception If an existing GeoPackage fails the validity check.\n\t * @see #isGPKGValid()\n\t */\n\tpublic GeoPackage(ISQLDatabase sqlDB, boolean overwrite) {\n\t\t\n\t\tif (!sqlDB.getDatabaseFile().toString().endsWith(\".gpkg\"))\n\t\t\tthrow new IllegalArgumentException(\"Invalid file extension for database - Must be .gpkg\");\n\n\t\t\n\t\tthis.sqlDB = sqlDB;\n\t\tthis.dbFile = sqlDB.getDatabaseFile();\n\n\t\tif (overwrite) {\n\t\t\tif (dbFile.exists() && !dbFile.delete()) \n\t\t\t\tthrow new IllegalArgumentException(\"Unable to overwrite GeoPackage file\");\n\t\t}\n\n\t\t// Load table definitions\n\t\tsysTables.put(GpkgSpatialRefSys.TABLE_NAME, new GpkgSpatialRefSys());\n\t\tsysTables.put(GpkgContents.TABLE_NAME, new GpkgContents() );\n\t\tsysTables.put(GpkgDataColumnConstraint.TABLE_NAME, new GpkgDataColumnConstraint());\n\t\tsysTables.put(GpkgDataColumns.TABLE_NAME, new GpkgDataColumns());\n\t\tsysTables.put(GpkgExtensions.TABLE_NAME, new GpkgExtensions());\n\t\tsysTables.put(GpkgGeometryColumns.TABLE_NAME, new GpkgGeometryColumns());\n\t\tsysTables.put(GpkgMetaData.TABLE_NAME, new GpkgMetaData());\n\t\tsysTables.put(GpkgMetaDataReference.TABLE_NAME, new GpkgMetaDataReference());\n\t\tsysTables.put(GpkgTileMatrix.TABLE_NAME, new GpkgTileMatrix());\n\t\tsysTables.put(GpkgTileMatrixSet.TABLE_NAME, new GpkgTileMatrixSet());\n\t\t\n\t\tsysViews.put(SpatialRefSys.VIEW_NAME, new SpatialRefSys());\n\t\tsysViews.put(STGeometryColumns.VIEW_NAME, new STGeometryColumns());\n\t\tsysViews.put(STSpatialRefSys.VIEW_NAME, new STSpatialRefSys());\n\t\t//sysViews.put(GeometryColumns.VIEW_NAME, new GeometryColumns()); // Requires function definition\n\n\t\t// Look-ups for sql to Java\n\t\tsqlTypeMap.put(\"int\", JavaType.INTEGER);\n\t\tsqlTypeMap.put(\"integer\", JavaType.INTEGER);\n\t\tsqlTypeMap.put(\"tinyint\", JavaType.INTEGER);\n\t\tsqlTypeMap.put(\"text\", JavaType.STRING);\n\t\tsqlTypeMap.put(\"date\", JavaType.STRING);\n\t\tsqlTypeMap.put(\"datetime\", JavaType.STRING);\n\t\tsqlTypeMap.put(\"string\", JavaType.STRING);\n\t\tsqlTypeMap.put(\"boolean\", JavaType.BOOLEAN);\n\t\tsqlTypeMap.put(\"float\", JavaType.FLOAT);\n\t\tsqlTypeMap.put(\"double\", JavaType.DOUBLE);\n\t\tsqlTypeMap.put(\"real\", JavaType.DOUBLE);\n\t\tsqlTypeMap.put(\"long\", JavaType.DOUBLE);\n\t\tsqlTypeMap.put(\"geometry\", JavaType.BYTE_ARR);\n\t\tsqlTypeMap.put(\"blob\", JavaType.BYTE_ARR);\n\t\tsqlTypeMap.put(\"none\", JavaType.BYTE_ARR);\n\t\t\n\t\t/* If the file alread exists, check it is a valid geopackage */\n\t\tif (dbFile.exists()) {\n\n\t\t\tif (!isGPKGValid(false)) \n\t\t\t\tthrow new IllegalArgumentException(\"GeoPackage \"+dbFile.getName()+\" failed integrity checks - Check the source.\");\n\t\t\t\n\t\t} else {\n\t\t\t\n\t\t\tlog.log(Level.INFO, \"Database file does not exist. Creating new GeoPackage \"+dbFile.getName());\n\t\t\t\n\t\t\t// Create the DB file\n\t\t\tthis.sqlDB.createDatabase();\n\n\t\t\tfor (GpkgTable tab : sysTables.values()) \n\t\t\t\ttab.create(this);\n\t\t\tfor (GpkgView view : sysViews.values()) \n\t\t\t\tview.create(this);\n\n\t\t\t// Our standard triggers\n\t\t\tfor (String stmt : GpkgTriggers.ALL_STANDARD_TRIGGERS) sqlDB.execSQL( stmt );\n\t\t\t\n\t\t\tfor (String stmt : GpkgSpatialRefSys.INSERT_DEFAULT_SPATIAL_REF_SYS) \n\t\t\t\tsqlDB.execSQL( stmt );\n\t\t\t\n\t\t\t// Try setting the application_id pragma through Sqlite implementation\n\t\t\tif ( !setGpkgAppPragma() ) setGpkgAppHeader();\n\t\t\t\n\t\t\tif (!isGPKGValid(true)) \n\t\t\t\tthrow new IllegalArgumentException(\"GeoPackage \"+dbFile.getName()+\" failed integrity checks - Check the source.\");\n\t\t\t\n\t\t}\n\t\t\n\t\tlog.log(Level.INFO, \"Connected to GeoPackage \"+dbFile.getName());\n\t}\n\t/** Get the name of the database file associated with this GeoPackage\n\t * \n\t * @return\n\t */\n\tpublic String getDatabaseFileName() {\n\t\treturn this.dbFile.toString();\n\t}\n\t/** Close the underlying SQLite DB instance associated with this GeoPackge\n\t * \n\t */\n\tpublic void close() {\n\t\tthis.sqlDB.close();\n\t}\n\t/** Check for the {@link #GPKG_APPLICATION_ID} in the database Pragma application_id\n\t * field.\n\t * \n\t * @return True if its set\n\t */\n\tprivate boolean isGpkgAppPragmaSet() {\n\t\tboolean isGPKG = false;\n\n\t\tICursor c = sqlDB.doRawQuery(\"pragma application_id\");\n\t\tif (c.moveToFirst()) {\n\t\t\tisGPKG = c.getInt(0)==GPKG_APPLICATION_ID;\n\t\t}\n\t\tc.close();\n\t\t\n\t\treturn isGPKG;\n\t}\n\t/** Set the GeoPackage application ID pragma.\n\t * \n\t * @return True if set successfully.\n\t */\n\tprivate boolean setGpkgAppPragma() {\n\t\t\n\t\tif (!sqlDB.isOpen()) sqlDB.getDatabase(true);\n\t\tsqlDB.doRawQuery(\"pragma application_id=\"+GPKG_APPLICATION_ID);\n\t\t\n\t\treturn isGpkgAppPragmaSet();\n\t}\n\t/** Manually test whether the SQLite header contains the {@link #GPKG_APPLICATION_ID}\n\t * This is used as no current version of Android supports a version of Sqlite that supports the\n\t * pragma 'application_id', therefore we write to the header manually.\n\t * \n\t * @return True if its set.\n\t */\n\tprivate boolean isGpkgAppHeaderSet() {\n\t\tif (sqlDB.isOpen()) sqlDB.close();\n\t\t\n\t\tboolean isSet = false;\n\t\ttry {\n\t\t\tRandomAccessFile raf = new RandomAccessFile(dbFile, \"r\");\n\t\t\traf.seek(68);\n\t\t\tint n68 = raf.readInt();\n\t\t\tisSet = n68==GPKG_APPLICATION_ID;\n\t\t\traf.close();\n\t\t} catch (FileNotFoundException e) {\n\t\t\te.printStackTrace();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\t\n\t\treturn isSet;\n\t}\n\t/** Manually set the SQLite file header to include the {@link #GPKG_APPLICATION_ID}.\n\t * This is used as no current version of Android supports a version of Sqlite that supports the\n\t * pragma 'application_id', therefore we write to the header manually.\n\t * \n\t * @return True if set, false if there was an error.\n\t */\n\tprivate boolean setGpkgAppHeader() {\n\t\tif (sqlDB.isOpen()) sqlDB.close();\n\t\t\n\t\t/* */\n\t\ttry {\n\t\t\tRandomAccessFile raf = new RandomAccessFile(dbFile, \"rw\");\n\t\t\traf.seek(68);\n\t\t\traf.writeInt( GPKG_APPLICATION_ID );\n\t\t\traf.close();\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\treturn true;\n\t}\n\t/** Check that the GeoPackage is valid according to tests outlined in the specification,\n\t * namely that the application_id is correct, a database integrity returns 'ok' and there\n\t * are no foreign key issues.

\n\t * This check is performed automatically when connecting to a GeoPackage, but should \n\t * be performed before passing a GeoPackage to another client application or service. \n\t * \n\t * @param doIntegrity True to perform a PRAGMA integrity_check. This can take a long\n\t * time on large files (>250mb), therefore it is only normally run \n\t * when a GeoPackage is created through this library.\n\t * \n\t * @return True if the checks pass.\n\t */\n\tpublic boolean isGPKGValid(boolean doIntegrity) {\n\t\tboolean isGPKG = false;\n\t\tboolean integrity = false;\n\t\tboolean foreignKey = false;\n\t\t\n\t\tisGPKG = isGpkgAppPragmaSet();\n\t\tif ( !isGPKG && MODE_STRICT ) isGPKG = isGpkgAppHeaderSet();\n\t\t\n\t\tsqlDB.getDatabase(false);\n\t\tICursor c = null;\n\n\t\tif (doIntegrity) {\n\t\t\tc = sqlDB.doRawQuery(\"PRAGMA integrity_check\");\n\t\t\tif (c.moveToFirst()) {\n\t\t\t\tintegrity = c.getString(0).equals(\"ok\");\n\t\t\t}\n\t\t\tc.close();\n\t\t} else {\n\t\t\tintegrity = true;\n\t\t}\n\t\t\n\t\tc = sqlDB.doRawQuery(\"PRAGMA foreign_key_check\");\n\t\tforeignKey = c.moveToFirst();\n\t\tc.close();\n\t\t\n\t\t// Check all system tables are in the database\n\t\tboolean tabsExist = true;\n\t\tfor (GpkgTable gt : sysTables.values()) {\n\t\t\tif (!gt.isTableInDB(this)) {\n\t\t\t\ttabsExist = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn (isGPKG || MODE_STRICT==false) && integrity && !foreignKey && tabsExist;\n\t\t\n\t}\n\t/** Get the database associated with this GeoPackage\n\t * \n\t * @return\n\t */\n\tpublic ISQLDatabase getDatabase() {\n\t\treturn this.sqlDB;\n\t}\n\n\t/** Get all tiles in the table, at the specified zoom, in order to cover the supplied\n\t * bounding box.\n\t * \n\t * @param tableName The table to query\n\t * @param bbox The extents of the area to cover.\n\t * @param zoomLevel What tile level, or zoom, should the query get\n\t * @return\n\t * @throws Exception\n\t */\n\tpublic List getTiles(String tableName, BoundingBox bbox, int zoomLevel) throws Exception {\n\t\tlog.log(Level.INFO, \"BBOX query for images in \"+tableName);\n\t\t\n\t\tList allFeats = new ArrayList();\n\t\t\n\t\tGpkgTable tilesTable = getUserTable( tableName, GpkgTable.TABLE_TYPE_TILES );\n\t\t\n\t\t// IF strict, check for primary key, although not essential for this query\n\t\tif (MODE_STRICT) { \n\t\t\tif (tilesTable.getPrimaryKey(this).equals(\"unknown\"))\n\t\t\t\tthrow new Exception(\"Primary key not defined on table \"+tableName );\n\t\t}\n\t\t\n\t\t// Is BBOX valid against the table or tile_matrix_set?\n\t\tif ( !checkBBOXAgainstLast(tilesTable, bbox, false, false)) return allFeats;\n\t\t\n\t\t// Tile matrix data for this table\n\t\tGpkgRecords tmRecs = getSystemTable(GpkgTileMatrix.TABLE_NAME).query(\n\t\t\t\tthis, \"table_name='\"+tableName+\"' AND zoom_level=\"+zoomLevel);\n\t\tif (tmRecs.getFieldInt(0, \"zoom_level\")!=zoomLevel)\n\t\t\tthrow new Exception(\"Zoom level \"+zoomLevel+\" is not defined for this tile pyramid\");\n\t\t\n\t\tint tmWidth = tmRecs.getFieldInt(0, \"tile_width\");\n\t\tint tmHeight = tmRecs.getFieldInt(0, \"tile_height\");\n\t\tdouble pixX = tmRecs.getFieldDouble(0, \"pixel_x_size\");\n\t\tdouble pixY = tmRecs.getFieldDouble(0, \"pixel_y_size\");\n\t\t\n\t\t// Construct a temporary matrix_set bbox (for convenience)\n\t\tGpkgRecords tms = getSystemTable(GpkgTileMatrixSet.TABLE_NAME).query(this, \"table_name='\"+tilesTable.tableName+\"'\");\n\t\tBoundingBox tmsBox = new BoundingBoxImpl(\n\t\t\t\ttms.getFieldDouble(0, \"min_x\"), \n\t\t\t\ttms.getFieldDouble(0, \"max_x\"), \n\t\t\t\ttms.getFieldDouble(0, \"min_y\"), \n\t\t\t\ttms.getFieldDouble(0, \"max_y\"));\n\t\t\n\t\t/* TODO Get all tiles in the table at the specified zoom and check the bounds?,\n\t\t * or something else...\n\t\t */\n\t\t\n\t\t\n\t\t/* Calculate the min and max rows and columns.\n\t\t * This mechanism works for 3857 (slippy tiles) but serious doubt it does for \n\t\t * anything else, therefore have to test with other projections and create a generic\n\t\t * mechanism for creating a where clause from a bounding box */\n\t\tint minX = (int) Math.round( (bbox.getMinX() - tmsBox.getMinX() ) / (tmWidth * pixX) );\n\t\tint maxX = (int) Math.round( (bbox.getMaxX() - tmsBox.getMinX() ) / (tmWidth * pixX) );\n\t\tint minY = (int) Math.round( (tmsBox.getMaxY() - bbox.getMaxY() ) / (tmHeight * pixY) );\n\t\tint maxY = (int) Math.round( (tmsBox.getMaxY() - bbox.getMinY() ) / (tmHeight * pixY) );\n\t\t\n\t\tString strWhere = String.format(\n\t\t\t\t\"zoom_level=%s AND tile_column >= %s AND tile_column <= %s AND tile_row >=%s AND tile_row <=%s\", \n\t\t\t\tzoomLevel, minX, maxX, minY, maxY);\n\n\t\treturn getTiles(tableName, strWhere);\n\t\t\n\t}\n\t/** Query the GeoPackage for one or more tiles based on a where clause.\n\t * The SimpleFeature's that are returned have a {@linkplain FeatureType} name\n\t * matching the tableName and a {@link GeometryDescriptor} mathing that defined\n\t * in gpkg_contents for the table.

\n\t * The feature id (accessible via {@link SimpleFeature#getID()}) is the of the form \n\t * TableName-RecordID-zoom-row_ref-col_ref (or tableName-id-zoom-x-y)

\n\t * The image data is stored as a byte[] on an attribute named 'the_image' and the bounds\n\t * of the tile are stored as a {@link BoundingBox} on an attribute named 'the_geom'.\n\t * \n\t * @param tableName The {@linkplain TilesTable#getTableName()} to query\n\t * @param whereClause The SQL where clause, excluding the word 'where'\n\t * @return A List of {@linkplain SimpleFeature}'s \n\t * @throws Exception\n\t */\n\tpublic List getTiles(String tableName, String whereClause) throws Exception {\n\t\tlog.log(Level.INFO, \"WHERE query for images in \"+tableName);\n\t\t\n\t\tList allFeats = new ArrayList();\n\t\t\n\t\tTilesTable tilesTable = (TilesTable)getUserTable( tableName, GpkgTable.TABLE_TYPE_TILES );\n\t\t\n\t\t// IF strict, check for primary key, although not essential for this query\n\t\tif (MODE_STRICT) { \n\t\t\tif (tilesTable.getPrimaryKey(this).equals(\"unknown\"))\n\t\t\t\tthrow new Exception(\"Primary key not defined on table \"+tableName );\n\t\t}\n\t\t\n\t\t// Get the records matching our query\n\t\tGpkgRecords featRecords = tilesTable.query(this, whereClause);\n\t\tif (featRecords.size()==0) return allFeats;\n\t\t\n\t\t// Construct the feature type\n\t\tSimpleFeatureType featureType = tilesTable.getSchema();\n\t\t\n\t\tList attrValues = null;\n\t\tTileMatrixInfo tmi = ((TilesTable)tilesTable).getTileMatrixInfo();\n\t\t\n\t\t// Now go through each record building the feature with it's attribute values\n\t\tfor (int rIdx=0; rIdx < featRecords.size(); rIdx++) {\n\t\t\t\n\t\t\t// Create new list so previous values are not over-written \n\t\t\tattrValues = new ArrayList();\n\t\t\tattrValues.add( featRecords.getFieldBlob(rIdx, \"tile_data\") );\n\t\t\t\n\t\t\t// Construct bounding box for tile\n\t\t\tBoundingBox bbox = tmi.getTileBounds(\n\t\t\t\t\tfeatRecords.getFieldInt(rIdx, \"tile_column\"),\n\t\t\t\t\tfeatRecords.getFieldInt(rIdx, \"tile_row\"),\n\t\t\t\t\tfeatRecords.getFieldInt(rIdx, \"zoom_level\")\n\t\t\t\t\t);\n\t\t\tattrValues.add( bbox );\n\t\t\t\n\t\t\t// Tile details\n\t\t\tattrValues.add( featRecords.getFieldInt(rIdx, \"tile_column\") );\n\t\t\tattrValues.add( featRecords.getFieldInt(rIdx, \"tile_row\") );\n\t\t\tattrValues.add( featRecords.getFieldInt(rIdx, \"zoom_level\") );\n\t\t\t\n\t\t\t// The ID for this tile\n\t\t\tString fid = String.format(\"%s-%s-%s-%s-%s\",\n\t\t\t\t\ttableName,\n\t\t\t\t\tfeatRecords.getFieldInt(rIdx, \"id\"),\n\t\t\t\t\tfeatRecords.getFieldInt(rIdx, \"tile_column\"),\n\t\t\t\t\tfeatRecords.getFieldInt(rIdx, \"tile_row\"),\n\t\t\t\t\tfeatRecords.getFieldInt(rIdx, \"zoom_level\")\n\t\t\t\t\t);\n\t\t\t\n\t\t\t// Create the feature and add to list of all features\n\t\t\tallFeats.add( new SimpleFeatureImpl(fid, attrValues, featureType ) );\n\t\t}\n\t\t\n\t\treturn allFeats;\n\t}\n\t/** Check if this feature is in the GeoPackage.

\n\t * The query is based on {@link SimpleFeatureType#getTypeName()} = tableName and \n\t * {@link SimpleFeature#getID()} = Table.featureFieldName\n\t * \n\t * @param simpleFeature The feature to test.\n\t * @return True if found\n\t */\n\tpublic boolean isFeatureInGeoPackage(SimpleFeature simpleFeature) {\n\t\tString tableName = simpleFeature.getType().getTypeName();\n\t\tFeaturesTable featTable = (FeaturesTable)getUserTable( tableName, GpkgTable.TABLE_TYPE_FEATURES );\n\t\t\n\t\treturn featTable.isFeatureInTable(simpleFeature);\n\n\t}\n\t/** Get a list of all SimpleFeature's within, or intersecting with, the supplied BoundingBox.

\n\t * This version always performs an intersection test and does not check the bbox is within or \n\t * intersecting with the table extents. A StandardGeometryDecoder is used for reading feature\n\t * data.\n\t * \n\t * @param tableName The case sensitive table name in this GeoPackage to query.\n\t * @param bbox The {@link BoundingBox} to find features in, or intersecting with.\n\t * @return A list of {@linkplain SimpleFeature}'s\n\t * @throws Exception If the SRS of the supplied {@link BoundingBox} does not match the SRS of\n\t * the table being queried.\n\t */\n\tpublic List getFeatures(String tableName, BoundingBox bbox) throws Exception {\n\t\treturn getFeatures(tableName, bbox, true, true, new StandardGeometryDecoder() );\n\t}\n\t/** Get a list of {@link SimpleFeature} from the GeoPackage by specifying a where clause\n\t * (for example {@code featureId='pipe.1234'} or {@code id=1234} )\n\t * \n\t * @param tableName The case sensitive table name that holds the feature (probably \n\t * the localName of {@link SimpleFeatureType#getName()}\n\t * @param whereClause The 'Where' clause, less the where. Passing Null will return \n\t * all records from the table, which is discouraged.\n\t * @param geomDecoder The type of {@linkplain GeometryDecoder} to use.\n\t * @return A list of SimpleFeature's or an empty list if none were found in the specified table\n\t * matching the the filter\n\t * \n\t * @throws Exception\n\t */\n\tpublic List getFeatures(String tableName, String whereClause, GeometryDecoder geomDecoder) \n\t\t\tthrows Exception {\n\t\t\n\t\tFeaturesTable featTable = (FeaturesTable)getUserTable( tableName, GpkgTable.TABLE_TYPE_FEATURES );\n\t\t\n\t\tString stmt = \"SELECT * FROM [\"+tableName+\"]\";\n\t\tif (whereClause!=null && !whereClause.equals(\"\")) stmt+=\" WHERE \"+whereClause;\n\t\t\n\t\treturn getFeatures(stmt, featTable, geomDecoder);\n\t\t\n\t}\n\t/** Get a list of all SimpleFeature's within, or intersecting with, the supplied BoundingBox.\n\t * \n\t * @param tableName The case sensitive table name in this GeoPackage to query.\n\t * @param bbox The {@link BoundingBox} to find features in, or intersecting with.\n\t * @param includeIntersect Should feature's intersecting with the supplied box be returned?\n\t * @param testExtents Should the bbox be tested against the data extents in gpkg_contents before\n\t * issuing the query? If False a short test on the extents is performed. (In case table\n\t * extents are null) \n\t * @param geomDecoder The {@link GeometryDecoder} to use for reading feature geometries.\n\t * @return A list of {@linkplain SimpleFeature}'s\n\t * @throws Exception If the SRS of the supplied {@link BoundingBox} does not match the SRS of\n\t * the table being queried.\n\t */\n\tpublic List getFeatures(String tableName, BoundingBox bbox, boolean includeIntersect, \n\t\t\tboolean testExtents, GeometryDecoder geomDecoder) throws Exception {\n\t\tlog.log(Level.INFO, \"BBOX query for features in \"+tableName);\n\t\t\n\t\tList allFeats = new ArrayList();\n\n\t\tFeaturesTable featTable = (FeaturesTable)getUserTable( tableName, GpkgTable.TABLE_TYPE_FEATURES );\n\t\t\n\t\t// Is BBOX valid against the table?\n\t\tif ( !checkBBOXAgainstLast(featTable, bbox, includeIntersect, testExtents)) return allFeats;\n\t\t\n\t\tGeometryInfo gi = featTable.getGeometryInfo();\n\t\t\n\t\tStringBuffer sqlStmt = new StringBuffer();\n\t\tString pk = featTable.getPrimaryKey(this);\n\t\t\n\t\tif (MODE_STRICT) {\n\t\t\tif (pk.equals(\"rowid\"))\n\t\t\t\tthrow new Exception(\"Primary key not defined on table \"+featTable.getTableName() );\n\t\t}\n\t\t\n\t\t// If this GeoPackage is RTREE enabled, use the spatial index\n\t\tif (sqlDB.hasRTreeEnabled() && gi.hasSpatialIndex()) {\n\n\t\t\tString idxTable = \"[rtree_\"+tableName+\"_\"+gi.getColumnName()+\"]\";\n\n\t\t\tsqlStmt.append(\"SELECT [\").append(tableName).append(\"].* FROM [\").append(tableName).append(\"], \");\n\t\t\tsqlStmt.append(idxTable).append(\" WHERE [\");\n\t\t\tsqlStmt.append(tableName).append(\"].\").append(pk).append(\"=\");\n\t\t\tsqlStmt.append(idxTable).append(\".id\");\n\t\t\tsqlStmt.append(\" AND MinX>=\").append( bbox.getMinX() );\n\t\t\tsqlStmt.append(\" AND MaxX<=\").append( bbox.getMaxX() );\n\t\t\tsqlStmt.append(\" AND MinY>=\").append( bbox.getMinY() );\n\t\t\tsqlStmt.append(\" AND MaxY<=\").append( bbox.getMaxY() );\n\t\t\t\n\t\t\treturn getFeatures(sqlStmt.toString(), featTable, geomDecoder);\n\t\t\t\n\t\t}\n\n\t\t/* Query all records in the feature table and check the header envelope\n\t\t * for matchin/ intersecting bounds. If the envelope is null, then the full\n\t\t * geometry is read and checked */\n\t\t\n\t\tsqlStmt.append(\"SELECT * FROM [\").append(tableName).append(\"] WHERE id IN(\");\n\t\t\n\t\t// Query only for feature geometry and test that before getting all attributes\n\t\tlong startTime = System.currentTimeMillis();\n\t\tint totalRecs = featTable.getCount(this);\n\t\t\n\t\tint lastPK = 0, recCount = 0, hitCount = 0;\n\t\tboolean hit = false;\n\t\tEnvelope headerEnv = null;\n\t\tEnvelope query = new Envelope(bbox.getMinX(), bbox.getMaxX(), bbox.getMinY(), bbox.getMaxY());\n\t\t\n\t\t\n\t\t/* Deprecated getCount() on Cursor to save the cursor iterating\n\t\t * whole ResultSet on underlying Cursor implementation */\n\t\t\n\t\t// While we have less records than total for table..\n\t\twhile (recCount < totalRecs) {\n\t\t\t\n\t\t\tString sql = String.format(\"SELECT %s,%s FROM [%s] WHERE %s > %s ORDER BY %s LIMIT %s\",\n\t\t\t\t\tpk, gi.getColumnName(), tableName, pk, lastPK, pk, MAX_RECORDS_PER_CURSOR);\n\t\t\tICursor cPage = getDatabase().doRawQuery( sql );\n\n\t\t\t// Go through these x number of records\n\t\t\tboolean hasRecords = false;\n\t\t\twhile (cPage.moveToNext()) {\n\t\t\t\t\n\t\t\t\thasRecords = true;\n\t\t\t\t// Decode the geometry and test\n\t\t\t\theaderEnv = geomDecoder.setGeometryData( cPage.getBlob(1) ).getEnvelope();\n\t\t\t\t\n\t\t\t\t// No bbox from header, so decode the whole geometry (a lot slower)\n\t\t\t\tif (headerEnv.isNull() && !geomDecoder.isEmptyGeom()) {\n\t\t\t\t\theaderEnv = geomDecoder.getGeometry().getEnvelopeInternal();\n\t\t\t\t}\n\t\n\t\t\t\t// Test bounds\n\t\t\t\thit = (includeIntersect ? query.intersects( headerEnv ) : false) || query.contains( headerEnv ) || headerEnv.contains( query );\n\t\t\t\tif (hit) {\n\t\t\t\t\tsqlStmt.append(cPage.getInt(0)).append(\",\");\n\t\t\t\t\thitCount++;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// Store the last key we saw for the next page query\n\t\t\t\tlastPK = cPage.getInt(0);\n\t\t\t\trecCount++;\n\t\t\t}\n\t\t\n\t\t\tcPage.close();\n\t\t\tif (hasRecords==false) break;\n\t\t}\n\n\t\tlog.log(Level.INFO, recCount+\" geometries checked in \"+(System.currentTimeMillis()-startTime)/1000+\" seconds\");\n\t\t\n\t\t\n\t\t// Didn't find anything\n\t\tif (hitCount==0) return allFeats;\n\t\t\n\t\tsqlStmt.setLength(sqlStmt.length()-1);// How many id's can the DB handle??\n\t\tsqlStmt.append(\");\");\n\n\t\treturn getFeatures(sqlStmt.toString(), featTable, geomDecoder );\n\t\t\n\t}\n\t\n\t/** Get a list of {@link SimpleFeature} from the GeoPackage by specifying a full SQL statement.\n\t * \n\t * @param sqlStatement\n\t * @param featTable\n\t * @param geomDecoder The type of {@linkplain GeometryDecoder} to use.\n\t * @return A list of SimpleFeature's or an empty list if none were found in the specified table\n\t * matching the the filter\n\t * @throws Exception\n\t */\n\tprotected List getFeatures(String sqlStatement, FeaturesTable featTable, GeometryDecoder geomDecoder)\n\t\t\tthrows Exception {\n\t\t\n\t\tList allFeats = new ArrayList();\n\n\t\tint totalRecs = featTable.getCount(this);\n\n\t\tif (totalRecs==0) return allFeats;\n\t\t\n\t\tSimpleFeatureType featureType = featTable.getSchema();\n\t\tList attrTypes = featureType.getTypes();\n\t\tGeometryInfo geomInfo = featTable.getGeometryInfo();\n\t\t\n\t\t// Find the feature id field\n\t\tString featureFieldName = \"\";\n\t\tfor (GpkgField gf : featTable.getFields() ) {\n\t\t\tif ( ((FeatureField)gf).isFeatureID() ) {\n\t\t\t\tfeatureFieldName = gf.getFieldName();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t\t\t\n\t\t/* Query the table in 'pages' of LIMIT number */\n\n\t\tlong startTime = System.currentTimeMillis();\n\t\tString pk = featTable.getPrimaryKey(this);\n\t\t\n\t\tif (MODE_STRICT) {\n\t\t\tif (pk.equals(\"rowid\"))\n\t\t\t\tthrow new Exception(\"Primary key not defined on table \"+featTable.getTableName() );\n\t\t}\n\t\t\n\t\tint lastPK = 0, recCount = 0;\n\t\tsqlStatement = sqlStatement.endsWith(\";\") ? sqlStatement.substring(0, sqlStatement.length()-1) : sqlStatement;\n\t\tint whereIdx = sqlStatement.toLowerCase().indexOf(\"where\");\n\t\tsqlStatement = whereIdx>0 ? sqlStatement+\" AND \" : sqlStatement+\" WHERE \";\n\t\tArrayList attrValues = new ArrayList();\n\t\tObject value = null;\n\t\tString fid;\n\t\tGpkgRecords featRecords = null;\n\t\tString sql = \"\"; \n\t\tString fieldName = null;\n\t\t\n\t\t// While we have less records than total for table..\n\t\twhile (recCount < totalRecs) {\n\n\t\t\tsql = String.format(sqlStatement+\"%s > %s ORDER BY %s LIMIT %s\",\n\t\t\t\t\tpk, lastPK, pk, MAX_RECORDS_PER_CURSOR);\n\t\t\tfeatRecords = featTable.rawQuery(this, sql );\n\n\t\t\tif (featRecords.size()==0) break;\n\n\t\t\t// Now go through each record building the feature with it's attribute values\n\t\t\tfor (int rIdx=0; rIdx < featRecords.size(); rIdx++) {\n\n\t\t\t\t// Create new list so previous values are not overridden \n\t\t\t\tattrValues = new ArrayList();\n\t\t\t\tfid = null;\n\t\t\t\t\n\t\t\t\t/* For each type definition, get the value, ensuring the \n\t\t\t\t * correct order is maintained on the value list*/\n\t\t\t\tfor (int typeIdx=0; typeIdx < attrTypes.size(); typeIdx++) {\n\t\t\t\t\t\n\t\t\t\t\tfieldName = attrTypes.get( typeIdx ).getName().getLocalPart();\n\t\t\t\t\tvalue = featRecords.get(rIdx).get( featRecords.getFieldIdx(fieldName) );\n\t\t\t\t\t\n\t\t\t\t\t// If defined as the feature's ID, store for feature creation\n\t\t\t\t\tif ( fieldName.equals(featureFieldName) ) {\n\t\t\t\t\t\t\n\t\t\t\t\t\tfid = String.valueOf( value );\n\t\t\t\t\t\tcontinue; // Add as ID, not an attribute\n\t\t\t\t\t\t\n\t\t\t\t\t} else if (fieldName.equals(geomInfo.getColumnName())) {\n\t\t\t\t\t\t\n\t\t\t\t\t\t// If geometry column, decode to actual Geometry\n\t\t\t\t\t\tvalue = geomDecoder.setGeometryData( (byte[])value ).getGeometry();\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tattrValues.add(value);\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\tattrValues.trimToSize();\n\t\t\t\t\n\t\t\t\t// Get or create a feature id?\n\t\t\t\tif (fid==null || fid.equals(\"null\")) fid = featTable.getTableName()+\".\"+recCount;\n\n\t\t\t\t// Create the feature and add to list of all features\n\t\t\t\tallFeats.add( new SimpleFeatureImpl(fid, attrValues, featureType ) );\n\n\t\t\t\t// Store the last key we saw for the next page query\n\t\t\t\tlastPK = featRecords.getFieldInt(rIdx, pk );\n\t\t\t\trecCount++;\n\t\t\t}\n\t\t}\n\n\t\tfeatRecords = null;\n\t\tgeomDecoder.clear();\n\t\t\n\t\tlog.log(Level.INFO, recCount+\" features built in \"+(System.currentTimeMillis()-startTime)/1000+\" secs\");\n\t\t\n\t\treturn allFeats;\n\t\t\n\t}\n\n\t/** Convenience method to check the passed bounding box (for a query) CRS matches\n\t * that on the {@link #lastFeatTable} and the bbox is within/ intersects with the \n\t * table boundingbox\n\t * \n\t * @param checkTable The table to check the query box against\n\t * @param queryBBox The query Bounding box\n\t * @param includeIntersect If vector/ feature data, should we test for intersection as\n\t * well as contains?\n\t * @param shortTest If True only the CRS's are tested to make sure they match. If False, the \n\t * table and/ or tile matrix set extents are tested as well.\n\t * @return True if checks pass\n\t */\n\tprivate boolean checkBBOXAgainstLast(GpkgTable checkTable, BoundingBox queryBBox, boolean includeIntersect, boolean shortTest) {\n\t\t\n\t\t// Check the SRS's are the same (Projection beyond scope of implementation)\n\t\tBoundingBox tableBbox = checkTable.getBounds();\n\t\tString qCode = queryBBox.getCoordinateReferenceSystem().getName().getCode();\n\t\tString qCodeS = queryBBox.getCoordinateReferenceSystem().getName().getCodeSpace();\n\t\t\n\t\tString tCode = tableBbox.getCoordinateReferenceSystem().getName().getCode();\n\t\tString tCodeS = tableBbox.getCoordinateReferenceSystem().getName().getCodeSpace();\n\t\t\n\t\tif (!qCode.equalsIgnoreCase(tCode) || !qCodeS.equalsIgnoreCase(tCodeS)) {\n\t\t\tlog.log(Level.WARNING, \"Passed bounding box SRS does not match table SRS\");\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tif (shortTest) return true;\n\t\t\n\t\t\n\t\t/* If GpkgContents has null bounds for this table do full query,\n\t\t * otherwise test the table bounds */\n\t\tboolean queryTable = false;\n\t\t\n\t\tif (!tableBbox.isEmpty()) {\n\t\t\t\n\t\t\tif (checkTable instanceof TilesTable) {\n\t\t\t\t// If tiles, bbox must be inside table extents\n\t\t\t\tqueryTable = queryBBox.intersects( tableBbox ) || tableBbox.contains( queryBBox );\n\t\t\t} else {\n\t\t\t\t// If features, inside or intersects\n\t\t\t\tqueryTable = (includeIntersect ? queryBBox.intersects( tableBbox ) : false) || \n\t\t\t\t\t\t queryBBox.contains( tableBbox ) ||\n\t\t\t\t\t\t tableBbox.contains(queryBBox);\n\t\t\t}\n\t\t\t\n\t\t} else {\n\t\t\t\n\t\t\tif (checkTable instanceof TilesTable) {\n\t\t\t\t// If a tiles table and no bounds in contents, check the tile_matrix_set definitions\n\t\t\t\t\tGpkgRecords tms = null;\n\t\t\t\t\ttry {\n\t\t\t\t\t\ttms = getSystemTable(GpkgTileMatrixSet.TABLE_NAME).query(this, \"table_name='\"+checkTable.tableName+\"'\");\n\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\t// Construct a bbox to test against\n\t\t\t\t\tCoordinateReferenceSystem crs = new CoordinateReferenceSystemImpl(\"\"+tms.getFieldInt(0, \"srs_id\"));\n\t\t\t\t\tBoundingBox tmsBox = new BoundingBoxImpl(\n\t\t\t\t\t\t\ttms.getFieldDouble(0, \"min_x\"), \n\t\t\t\t\t\t\ttms.getFieldDouble(0, \"max_x\"), \n\t\t\t\t\t\t\ttms.getFieldDouble(0, \"min_y\"), \n\t\t\t\t\t\t\ttms.getFieldDouble(0, \"max_y\"),\n\t\t\t\t\t\t\tcrs);\n\t\t\t\t\tqueryTable = queryBBox.intersects( tmsBox ) || tmsBox.contains( queryBBox );\n\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn queryTable;\n\t}\n\t\n\t/** Get a specific GeoPackage system table\n\t * \n\t * @param tableName\n\t * @return\n\t */\n\tpublic GpkgTable getSystemTable(String tableName) {\n\t\treturn sysTables.get(tableName);\n\t}\n\t/** Get one of the user defined tables by name. If the table has not\n\t * been loaded then it is created and cached.\n\t * \n\t * @param tableName The name of the table.\n\t * @param tableType Either {@link GpkgTable#TABLE_TYPE_FEATURES} || {@link GpkgTable#TABLE_TYPE_TILES}\n\t * @return An instance of the table.\n\t * @throws IllegalArgumentException if the table type is not one of the above, or the \n\t * table does not exist in the GeoPackage.\n\t */\n\tpublic GpkgTable getUserTable(String tableName, String tableType) {\n\t\tGpkgTable gpkgTable = userTables.get(tableName);\n\t\t\n\t\tif (gpkgTable==null) {\n\t\t\tif (tableType.equals(GpkgTable.TABLE_TYPE_FEATURES) ) {\n\t\t\t\tgpkgTable = new FeaturesTable(this, tableName);\n\t\t\t} else if (tableType.equals(GpkgTable.TABLE_TYPE_TILES) ) {\n\t\t\t\tgpkgTable = new TilesTable(this, tableName);\n\t\t\t} else {\n\t\t\t\tthrow new IllegalArgumentException(\"Incompatible user table type: \"+tableType);\n\t\t\t}\n\t\t\t\n\t\t\tif (!gpkgTable.isTableInGpkg(this))\n\t\t\t\tthrow new IllegalArgumentException(\"Table \"+tableName+\" does not exist in the GeoPackage\");\n\t\t\t\n\t\t\tuserTables.put(tableName, gpkgTable);\n\t\t}\n\t\t\n\t\treturn gpkgTable;\n\t}\n\t/** Get a list of all user tables within the current GeoPackage.

\n\t * Note that the results of this query are not cached in the same way that system tables are and\n\t * the table data is not populated until a relevant method/ query (on the table) is \n\t * called. This allows for quicker/ lower cost checks on the number and/ or names of tables in \n\t * the GeoPackage.\n\t * \n\t * @param tableType Either {@link GpkgTable#TABLE_TYPE_FEATURES} or {@link GpkgTable#TABLE_TYPE_TILES}\n\t * @return A new list of tables or an empty list if none were found or the wrong tableType was specified.\n\t */\n\tpublic List getUserTables(String tableType) {\n\t\tArrayList ret = new ArrayList();\n\t\t\n\t\tif (!tableType.equals(GpkgTable.TABLE_TYPE_FEATURES) && !tableType.equals(GpkgTable.TABLE_TYPE_TILES))\n\t\t\treturn ret;\n\t\t\n\t\tICursor tables = null;\n\t\ttry {\n\t\t\ttables = sysTables.get(GpkgContents.TABLE_NAME).query(this, new String[]{\"table_name\"},\n\t\t\t\t\t\"data_type='\"+tableType+\"'\");\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t\treturn ret;\n\t\t}\n\t\t\n\t\tGpkgTable tab = null;\n\t\t\n\t\twhile(tables.moveToNext()) {\n\t\t\t\n\t\t\tif (tableType.equals(GpkgTable.TABLE_TYPE_FEATURES)) {\n\t\t\t\ttab = new FeaturesTable(this, tables.getString(0));\n\t\t\t} else {\n\t\t\t\ttab = new TilesTable(this, tables.getString(0));\n\t\t\t}\n\t\t\t\n\t\t\tret.add(tab);\n\t\t}\n\t\ttables.close();\n\t\t\n\t\tret.trimToSize();\n\t\treturn ret;\n\t}\n\n\t/** Insert a collection of tiles in to the GeoPackage\n\t * \n\t * @param features\n\t * @return The number of tiles inserted\n\t * @throws Exception\n\t */\n\tpublic int insertTiles(Collection features) throws Exception {\n\t\tint numInserted = 0;\n\t\tlong rec = -1;\n\t\t\n\t\tfor (SimpleFeature sf : features) {\n\t\t\trec = insertTile(sf);\n\t\t\tif( rec>-1 ) numInserted++;\n\t\t\t\n\t\t}\n\t\t\n\t\treturn numInserted;\n\t}\n\t/** Insert a tile into the GeoPackage from a SimpleFeature.

\n\t * The tile reference is taken from the feature ID in the form of zoom/xRef/yRef\n\t * with or without leading information. The zoom/x/y should be the last three parts\n\t * of the ID, which can include a file extension.

\n\t * The first instance of a byte[] on the feature's attribute will be taken as the image\n\t * data.\n\t * \n\t * @param feature The {@link SimpleFeature} with details as above\n\t * @return The row id of the newly inserted record if successful\n\t * \n\t * @throws Exception If the table does not exist in the GeoPackage or the supplied\n\t * tile reference is not valid for the table or the attributes and/ or reference cannot \n\t * be decoded.\n\t */\n\tpublic long insertTile(SimpleFeature feature) throws Exception {\n\t\t\n\t\tbyte[] tileData = null;\n\t\t// Cycle feature attrs to get the image data (assumes first byte[] is image)\n\t\tfor (int i=0; i w || tileColumn < 1 || tileRow > h || tileRow < 1 || w==-1 || h==-1) {\n\t\t\tthrow new Exception(\"Supplied tile reference is outside the scope of the tile matrix for \"+tableName);\n\t\t}\n\n\t\tMap values = new HashMap();\n\t\tvalues.put(\"zoom_level\", zoom);\n\t\tvalues.put(\"tile_column\", tileColumn);\n\t\tvalues.put(\"tile_row\", tileRow);\n\t\tvalues.put(\"tile_data\", tile);\n\t\t\n\t\tlong recID = tilesTable.insert(this, values);\n\t\t\n\t\tif (recID>0) updateLastChange(tilesTable.getTableName(), tilesTable.getTableType());\n\t\t\n\t\treturn recID;\n\t}\n\t/** Check if a SRS with the supplied code is loaded in GpkgSpatialRefSys\n\t * \n\t * @param srsName The string value of the srs_name or srs_id\n\t * @return True if loaded, false if not or there was an error.\n\t */\n\tpublic boolean isSRSLoaded(String srsName) {\n\t\tboolean loaded = false;\n\t\t\n\t\tint srsID = -2;\n\t\ttry {\n\t\t\tsrsID = Integer.parseInt( srsName );\n\t\t} catch (NumberFormatException ignore) {\n\t\t\t// TODO Look-up the EPSG code number somehow?\n\t\t}\n\t\t\n\t\tString strWhere = srsID>-2 ? \"srs_id=\"+srsID : \"srs_name='\"+srsName+\"'\";\n\n\t\ttry {\n\t\t\tICursor cur = getSystemTable(GpkgSpatialRefSys.TABLE_NAME).query(\n\t\t\t\t\tthis, new String[]{\"srs_name\"}, strWhere);\n\t\t\t\n\t\t\tloaded = cur.moveToNext();\n\t\t\tcur.close();\n\t\t\t\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\t\n\t\treturn loaded;\n\t}\n\n\t/** Create a {@linkplain FeaturesTable} from a {@link SimpleFeatureType}\n\t * \n\t * @param featureType The SimpleFeatureType to use.\n\t * @param tableExtents The extents for this table\n\t * @return The new FeaturesTable\n\t * @throws Exception If the supplied data is invalid or constraints are not \n\t * met (i.e No matching SRS definition in the gpkg_spatial_ref_sys table)\n\t */\n\tpublic FeaturesTable createFeaturesTable(SimpleFeatureType featureType, BoundingBox tableExtents) throws Exception {\n\t\tFeaturesTable ft = new FeaturesTable( this, featureType.getTypeName());\n\t\t\n\t\tft.create( featureType, tableExtents );\n\t\t\n\t\treturn ft;\n\t}\n\t/** Add all {@link SimpleFeature}'s on the supplied collection into the GeoPackage as a batch.\n\t * If there are multiple feature types within the collection they are\n\t * automatically split to their corresponding tables.\n\t * The table name to insert into is taken from the local part of\n\t * the {@link FeatureType#getName()}.\n\t * \n\t * @param features\n\t * @return The number of records inserted\n\t * @throws Exception\n\t */\n\tpublic int insertFeatures(Collection features) throws Exception {\n\t\t\n\t\t/* Features within the collection could be different types, so split\n\t\t * in to seperate lists for batch insertion */\n\t\tMap> typeList = new HashMap>();\n\t\tfor (SimpleFeature sf : features) {\n\t\t\tName tName = sf.getType().getName();\n\t\t\tList thisType = typeList.get(tName);\n\t\t\t\n\t\t\tif (thisType==null) {\n\t\t\t\tthisType = new ArrayList();\n\t\t\t\ttypeList.put(tName, thisType);\n\t\t\t}\n\t\t\tthisType.add(sf);\n\t\t\t\n\t\t}\n\t\t\n\t\tint numInserted = 0;\n\t\tFeaturesTable featTable = null;\n\t\t\n\t\t// For each set of feature's in our individual lists..\n\t\tfor (Map.Entry> e : typeList.entrySet()) {\n\t\t\t\n\t\t\tfeatTable = (FeaturesTable)getUserTable( \n\t\t\t\t\te.getKey().getLocalPart(), GpkgTable.TABLE_TYPE_FEATURES );\n\t\t\tList> insertVals = new ArrayList>();\n\t\t\t\n\t\t\tCollection tabFields = featTable.getFields();\n\t\t\t\n\t\t\t\n\t\t\t// Get and check dimensional output\n\t\t\tint mOpt = featTable.getGeometryInfo().getMOption();\n\t\t\tint zOpt = featTable.getGeometryInfo().getZOption();\n\t\t\tint dimension = 2;\n\t\t\tif (\tmOpt==Z_M_VALUES_MANDATORY || zOpt==Z_M_VALUES_MANDATORY \n\t\t\t\t\t|| mOpt==Z_M_VALUES_OPTIONAL || zOpt==Z_M_VALUES_OPTIONAL) {\n\t\t\t\tdimension = 3;\n\t\t\t}\n\t\t\tif (mOpt==Z_M_VALUES_MANDATORY && zOpt==Z_M_VALUES_MANDATORY)\n\t\t\t\tthrow new IllegalArgumentException(\"4 dimensional output is not supported\");\n\t\t\t\n\t\t\t\n\t\t\t// Build values for each feature of this type..\n\t\t\tfor (SimpleFeature sf : e.getValue()) {\n\t\t\t\tinsertVals.add( buildInsertValues(sf, tabFields, dimension) );\n\t\t\t}\n\t\t\t\n\t\t\t// Do the update on the table\n\t\t\tnumInserted += featTable.insert(this, insertVals);\n\t\t\tinsertVals = null;\n\t\t}\n\t\t\n\t\ttypeList = null;\n\t\t\n\t\tif (numInserted>0) updateLastChange(featTable.getTableName(), featTable.getTableType());\n\t\t\n\t\treturn numInserted; \n\t}\n\t/** Insert a single {@link SimpleFeature} into the GeoPackage.\n\t * The table name to insert into is taken from the local part of\n\t * the {@link FeatureType#getName()}.\n\t * \n\t * @param feature The SimpleFeature to insert.\n\t * @return The RowID of the new record or -1 if not inserted\n\t * @throws Exception\n\t * @see {@link #insertFeatures(Collection)} for batch processing many features\n\t */\n\tpublic long insertFeature(SimpleFeature feature) throws Exception {\n\t\tSimpleFeatureType type = feature.getType();\n\t\t\n\t\tFeaturesTable featTable = (FeaturesTable)getUserTable( \n\t\t\t\ttype.getName().getLocalPart(), GpkgTable.TABLE_TYPE_FEATURES );\n\n\t\t// Get and check dimensional output\n\t\tint mOpt = featTable.getGeometryInfo().getMOption();\n\t\tint zOpt = featTable.getGeometryInfo().getZOption();\n\t\tint dimension = 2;\n\t\tif (\tmOpt==Z_M_VALUES_MANDATORY || zOpt==Z_M_VALUES_MANDATORY \n\t\t\t\t|| mOpt==Z_M_VALUES_OPTIONAL || zOpt==Z_M_VALUES_OPTIONAL) {\n\t\t\tdimension = 3;\n\t\t}\n\t\tif (mOpt==Z_M_VALUES_MANDATORY && zOpt==Z_M_VALUES_MANDATORY)\n\t\t\tthrow new IllegalArgumentException(\"4 dimensional output is not supported\");\n\t\t\n\t\tMap values = buildInsertValues(feature, featTable.getFields(), dimension);\n\t\t\n\t\tlong recID = featTable.insert(this, values);\n\t\t\n\t\tif (recID>0) updateLastChange(featTable.getTableName(), featTable.getTableType());\n\t\t\n\t\treturn recID;\n\t}\n\t/** Create a Map of field name to field value for inserting into a table.\n\t * \n\t * @param feature The {@link SimpleFeature}\n\t * @param tabFields The GeoPackage table fields to use for building the map.\n\t * @param geomDimension 2 or 3 for the Geomaetry ordinates/\n\t * @return A Map \n\t * @throws IOException\n\t */\n\tprivate Map buildInsertValues(SimpleFeature feature, \n\t\t\tCollection tabFields, int geomDimension) throws IOException {\n\t\t\n\t\t// Construct values\n\t\tSimpleFeatureType type = feature.getType();\n\t\tMap values = new HashMap();\n\t\tObject value = null;\n\t\tFeatureField field = null;\n\t\tboolean passConstraint = true;\n\t\t\n\t\t// For each field defined in the table...\n\t\tfor (GpkgField f : tabFields) {\n\t\t\t\n\t\t\tif (f.isPrimaryKey()) continue; // We can't update the PK!\n\t\t\n\t\t\tfield = (FeatureField)f;\n\t\t\t\n\t\t\t// If defined as feature id, use getID, else find the attribute\n\t\t\tif ( field.isFeatureID() ) {\n\t\t\t\tvalue = feature.getID();\n\t\t\t} else {\n\t\t\t\tint idx = type.indexOf( field.getFieldName() );\n\t\t\t\t//This field isn't defined on the feature type, so can't insert value\n\t\t\t\tif (idx==-1 || idx > type.getAttributeCount()) continue; \n\t\t\t\t\n\t\t\t\tvalue = feature.getAttribute(idx);\n\t\t\t}\n\n\t\t\tpassConstraint = true;\n\t\t\t\n\t\t\t// Check constraint if not a blob\n\t\t\tif (field.getMimeType()==null && field.getConstraint()!=null) {\n\t\t\t\tpassConstraint = field.getConstraint().isValueValid( value );\n\t\t\t}\n\t\t\t\n\t\t\tif(passConstraint) {\n\t\t\t\tif (value instanceof Geometry) {\n\t\t\t\t\tvalues.put(field.getFieldName(), encodeGeometry( (Geometry)value, geomDimension ) );\n\t\t\t\t} else {\n\t\t\t\t\tvalues.put(field.getFieldName(), value);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (MODE_STRICT) {\n\t\t\t\t\tthrow new IllegalArgumentException(\"Field \"+field.getFieldName()+\" did not pass constraint check\");\n\t\t\t\t}\n\t\t\t\tlog.log(Level.WARNING, \"Field \"+field.getFieldName()+\" did not pass constraint check; Inserting Null\");\n\t\t\t\tvalues.put(field.getFieldName(), null);\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t\treturn values;\n\t}\n\t/** Set a limit on the number of vertices permissible on a single geometry\n\t * when trying to insert new features. If the limit is exceeded then the \n\t * geometries are simplified using the supplied tolerance.\n\t * Default is no limit (-1)\n\t * \n\t * @param limitTo Max vertices\n\t * @param tolerance The tolerance to apply during simplification. This value\n\t * should be appropriate to the geometry's SRS\n\t */\n\tpublic void setSimplifyOnInsertion(int limitTo, double tolerance) {\n\t\tthis.MAX_VERTEX_LIMIT = limitTo;\n\t\tsimpleTolerance = tolerance;\n\t}\n\tprivate double simpleTolerance = 1;\n\t/** Encode a JTS {@link Geometry} to standard GeoPackage geometry blob\n\t * \n\t * @param geom The Geometry to encode\n\t * @param outputDimension How many dimensions to write (2 or 3). JTS does not support 4\n\t * @return\n\t * @throws IOException\n\t */\n\tprivate byte[] encodeGeometry(Geometry geom, int outputDimension) throws IOException {\n\t\tif (geom==null) throw new IOException(\"Null Geometry passed\");\n\t\t\n\t\tif (outputDimension < 2 || outputDimension > 3)\n\t\t\tthrow new IllegalArgumentException(\"Output dimension must be 2 or 3\");\n\t\t\n\t\t// Stop outrageous geometries from being encoded and inserted\n\t\tif (MAX_VERTEX_LIMIT>0) {\n\t\t\tint b4 = geom.getNumPoints();\n\t\t\tif (b4 > MAX_VERTEX_LIMIT) {\n\t\t\t\tgeom = DouglasPeuckerSimplifier.simplify(geom, simpleTolerance);\n\t\t\t\tgeom.geometryChanged();\n\t\t\t\tint af = geom.getNumPoints();\n\t\t\t\tlog.log(Level.WARNING, \"Geometry Simplified for insertion: \"+b4+\" to \"+af+\" points\");\n\t\t\t}\n\t\t}\n\t\t\n\t\tByteArrayOutputStream output = new ByteArrayOutputStream();\n\n\t\t// 'Magic' and Version\n\t\toutput.write( \"GP\".getBytes() );\n\t\toutput.write( GPKG_GEOM_HEADER_VERSION );\n\t\t\n\t\t// Header flags\n\t\tint endianOrder = ByteOrderValues.BIG_ENDIAN;\n\t\tbyte flags = 0;\n\t\tif (GPKG_GEOMETRY_LITTLE_ENDIAN) {\n\t\t\tflags = (byte) (flags | (1 << 0));\n\t\t\tendianOrder = ByteOrderValues.LITTLE_ENDIAN;\n\t\t}\n\t\tif (!geom.getEnvelopeInternal().isNull()) {\n\t\t\t/* JTS Envelope geoms are only ever XY, not XYZ or XYZM\n\t\t\t * therefore we only ever set the 2nd bit to 1 */\n\t\t\tflags = (byte) (flags | (1 << 1));\n\t\t}\n\t\tif ( geom.isEmpty() ) {\n\t\t\t// Set envelope bit to 0\n\t\t\tflags = (byte) (flags | (1 << 0));\n\t\t\t// Flag the geometry is empty\n\t\t\tflags = (byte) (flags | (1 << 4));\n\t\t}\n\t\tif (GPKG_GEOMETRY_STANDARD==false) {\n\t\t\t// ExtendedGeoPackageBinary encoding\n\t\t\tflags = (byte) (flags | (1 << 5));\n\t\t}\n\t\t// Bits 7 and 8 are currently reserved and un-used\n\t\toutput.write(flags);\n\t\t\n\t\t// SRS\n\t\tbyte[] buffer = new byte[4];\n\t\tByteOrderValues.putInt(geom.getSRID(), buffer, endianOrder);\n\t\toutput.write(buffer);\n\t\t\n\t\tEnvelope envelope = geom.getEnvelopeInternal();\n\t\t/* Geom envelope - JTS only supports 2 dimensional envelopes. If Geom is\n\t\t * empty then we don't encode an envelope */\n\t\tif (!envelope.isNull() && !geom.isEmpty()) {\n\t\t\tbuffer = new byte[8];\n\t\t\t// Min X\n\t\t\tByteOrderValues.putDouble(envelope.getMinX(), buffer, endianOrder);\n\t\t\toutput.write(buffer);\n\t\t\t// Max X\n\t\t\tByteOrderValues.putDouble(envelope.getMaxX(), buffer, endianOrder);\n\t\t\toutput.write(buffer);\n\t\t\t// Min Y\n\t\t\tByteOrderValues.putDouble(envelope.getMinY(), buffer, endianOrder);\n\t\t\toutput.write(buffer);\n\t\t\t// Max Y\n\t\t\tByteOrderValues.putDouble(envelope.getMaxY(), buffer, endianOrder);\n\t\t\toutput.write(buffer);\n\t\t}\n\t\t\n\t\t// Write the geometry\n\t\toutput.write( new OGCWKBWriter( outputDimension ).write(geom) );\n\t\t\n\t\tbuffer = output.toByteArray();\n\t\toutput.close();\n\t\t\n\t\treturn buffer;\n\t}\n\t/** Update last_change field in GpkgContents for the given table name and type\n\t * to 'now'.\n\t * \n\t * @param tableName\n\t * @param tableType\n\t */\n\tprivate void updateLastChange(String tableName, String tableType) {\n\t\tMap values = new HashMap();\n\t\tvalues.put(\"last_change\", DateUtil.serializeDateTime(System.currentTimeMillis(), true) );\n\t\tString where = String.format(\"table_name='%s' and data_type='%s'\", tableName, tableType);\n\t\tgetSystemTable(GpkgContents.TABLE_NAME).update(this, values, where);\n\t}\n\t/** Insert an OWS Context document correctly in to the GeoPackage.

\n\t * This method only allows for one Context Document within the GeoPackage.\n\t * \n\t * @param contextDoc Properly formatted document as a String (JSON or XML)\n\t * @param mimeType The encoding of the Context document (JSON or XML)\n\t * @param overwrite If True any current record is overwritten. If False\n\t * and there is an existing record then nothing is done and the method will \n\t * return False.\n\t * @return True if inserted/ updated successfully.\n\t */\n\tpublic boolean insertOWSContext(String contextDoc, String mimeType, boolean overwrite) {\n\t\tif (contextDoc==null || contextDoc.equals(\"\") || mimeType==null) return false;\n\t\tif (\t!mimeType.equalsIgnoreCase(\"text/xml\") &&\n\t\t\t\t!mimeType.equalsIgnoreCase(\"application/xml\") &&\n\t\t\t\t!mimeType.equalsIgnoreCase(\"application/json\") ) {\n\t\t\tthrow new IllegalArgumentException(\"Incorrect mimeType specified\");\n\t\t}\n\t\t\t\t\n\t\t// Do we have an existing record?\n\t\tGpkgTable md = getSystemTable(GpkgMetaData.TABLE_NAME);\n\t\tICursor c = md.query(this, new String[]{\"id\"}, \"md_standard_uri='http://www.opengis.net/owc/1.0'\");\n\t\tint cID = -1;\n\t\tif (c.moveToNext()) {\n\t\t\tcID = c.getInt(0);\n\t\t\tc.close();\n\t\t}\n\t\t\n\t\tMap values = new HashMap();\n\t\tvalues.put(\"md_scope\", GpkgMetaData.SCOPE_UNDEFINED);\n\t\tvalues.put(\"md_standard_uri\", \"http://www.opengis.net/owc/1.0\");\n\t\tvalues.put(\"mime_type\", mimeType);\n\t\tvalues.put(\"metadata\", contextDoc);\n\t\t\n\t\tboolean updated = false;\n\t\tlong mdRec = -1, mdrRec = -1;\n\t\tif (overwrite && cID > -1) {\n\t\t\tupdated = md.update(this, values, \"id=\"+cID) > 0;\n\t\t} else if (cID > -1) {\n\t\t\t// Don't overwrite, but has record so return false\n\t\t\treturn false;\n\t\t} else if (cID==-1) {\n\t\t\t// No record, so insert\n\t\t\tmdRec = getSystemTable(GpkgMetaData.TABLE_NAME).insert(this, values);\n\t\t}\n\t\t\n\t\t// Didn't insert or update\n\t\tif (mdRec==-1 && updated==false) return false;\n\t\t\n\t\tvalues.clear();\n\t\t\n\t\tif (updated) {\n\t\t\t// Update timestamp\n\t\t\tvalues.put(\"timestamp\", DateUtil.serializeDateTime(System.currentTimeMillis(), true) );\n\t\t\tmdrRec = getSystemTable(GpkgMetaDataReference.TABLE_NAME).update(this, values, \"md_file_id=\"+cID);\n\t\t} else {\n\t\t\tvalues.put(\"reference_scope\", GpkgMetaDataReference.SCOPE_GEOPACKAGE);\n\t\t\tvalues.put(\"md_file_id\", mdRec);\n\t\t\tmdrRec = getSystemTable(GpkgMetaDataReference.TABLE_NAME).insert(this, values);\n\t\t}\n\t\t\n\t\t// Rollback GpkgMetaData if reference not inserted\n\t\tif (mdrRec < 1) {\n\t\t\tgetSystemTable(GpkgMetaData.TABLE_NAME).delete(this, \"id=\"+mdRec);\n\t\t}\n\t\t\n\t\treturn mdrRec > -1;\n\t}\n\t/** Get the String representation of an OWS Context Document from the GeoPackage.

\n\t * Only the first Context Document within the GeoPackage is returned\n\t * ( as defined by md_standard_uri='http://www.opengis.net/owc/1.0' )\n\t * \n\t * @return String[] The first entry is the Context mime-type, the second is the \n\t * String representation of the document.\n\t */\n\tpublic String[] getOWSContext() {\n\t\tString[] ret = new String[2];\n\t\t\n\t\tICursor c = getSystemTable(GpkgMetaData.TABLE_NAME).query(\n\t\t\t\t\t\tthis, \n\t\t\t\t\t\tnew String[]{\"mime_type\", \"metadata\"},\n\t\t\t\t\t\t\"md_standard_uri='http://www.opengis.net/owc/1.0'\");\n\t\tif(c.moveToFirst()) {\n\t\t\tret = new String[] {c.getString(0), c.getString(1)};\n\t\t}\n\t\tc.close();\n\t\t\n\t\treturn ret;\n\t}\n\t/** Add a new constraint to the GeoPackage that can be referenced, using the same constraint_name,\n\t * from gpkg_data_columns.

\n\t * \n\t * The constraint must be created before a record that uses it is inserted into gpkg_data_columns, therefore\n\t * constraint names specified on {@link AttributeType}'s via the user-data must be added through this \n\t * method prior to passing the attribute definitions to \n\t * {@link #createFeatureTable(String, String, List, List, BoundingBox, String, boolean)} \n\t * with dataColumns set to True.

\n\t * \n\t * Any existing constraint(s) in the GeoPackage with the same name are updated (delete-insert).

\n\t * \n\t * @param tableName The name of the table to apply this constraint to.\n\t * @param columnNames An array of column names to apply this constrain to, WRT the tableName\n\t * @param dcConstraint {@link DataColumnConstraint}\n\t * \n\t */\n\tpublic long addDataColumnConstraint(String tableName, String[] columnNames, DataColumnConstraint dcConstraint) {\n\t\tif (dcConstraint==null || dcConstraint.isValid()==false) return -1L;\n\t\t\n\t\tGpkgDataColumnConstraint dcc = new GpkgDataColumnConstraint();\n\t\tDataColumnConstraint existingDCC = dcc.getConstraint(this, dcConstraint.constraintName);\n\t\t\n\t\tif (existingDCC!=null) {\n\t\t\tif (existingDCC.constraintType.equals(GpkgDataColumnConstraint.TYPE_ENUM)) {\n\t\t\t\t/* Do we want to delete everything and re-insert, or check and update?\n\t\t\t\t * Currently delete everything and re-insert */\n\t\t\t\tdcc.delete(this, \"constraint_name='\"+dcConstraint.constraintName+\"'\");\n\t\t\t} else {\n\t\t\t\tdcc.delete(this, \"constraint_name='\"+dcConstraint.constraintName+\"'\");\n\t\t\t}\n\t\t}\n\n\t\t// Insert the constraint\n\t\tlong newRec = dcc.insert(this, dcConstraint.toMap());\n\t\t\n\t\t// Didn't insert/ update so don't update feature table\n\t\tif (newRec ==-1) return -1L;\n\t\t\n\t\t// Update GpkgDataColumns for the specified columns\n\t\tMap vals = null;\n\t\tGpkgTable sys = getSystemTable(GpkgDataColumns.TABLE_NAME);\n\t\tfor (String col : columnNames) {\n\t\t\tvals = new HashMap();\n\t\t\tvals.put(\"constraint_name\", dcConstraint.constraintName);\n\t\t\tsys.update(this, vals, \"table_name='\"+tableName+\"' AND column_name='\"+col+\"';\");\n\t\t}\n\n\t\treturn newRec;\n\t}\n\n\n\t/** Check that the supplied geometry type name is valid for a GeoPackage\n\t * \n\t * @param geomDescriptor The GeometryDescriptor to check from.\n\t * @return True if its valid\n\t */\n\tpublic boolean isGeomTypeValid(GeometryDescriptor geomDescriptor) {\n\t\tString geomType = geomDescriptor.getType().getName().getLocalPart().toLowerCase();\n\n\t\tif (geomType.equals(\"geometry\")) {\n\t\t\treturn true;\n\t\t} else\tif (geomType.equals(\"point\")) {\n\t\t\treturn true;\n\t\t} else if (geomType.equals(\"linestring\")) {\n\t\t\treturn true;\n\t\t} else if (geomType.equals(\"polygon\")) {\n\t\t\treturn true;\n\t\t} else if (geomType.equals(\"multipoint\")) {\n\t\t\treturn true;\n\t\t} else if (geomType.equals(\"multilinestring\")) {\n\t\t\treturn true;\n\t\t} else if (geomType.equals(\"multipolygon\")) {\n\t\t\treturn true;\n\t\t} else if (geomType.equals(\"geomcollection\")) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\t/** Encode basic Java types to those permissible in a GeoPackage\n\t * \n\t * @param object The object value to decode\n\t * @return A String usable for a table definition data type. Defaults to TEXT for\n\t * any unknown class or Object\n\t */\n\tpublic static String encodeType(Class clazz) {\n\t\tString name = clazz.getSimpleName().toLowerCase();\n\n\t\tif (name.equals(\"integer\") || name.equals(\"int\")) {\n\t\t\treturn \"INTEGER\";\n\t\t} else if (name.equals(\"string\")) {\n\t\t\treturn \"TEXT\";\n\t\t} else if (name.equals(\"boolean\") || name.equals(\"byte\")) {\n\t\t\treturn \"BOOL\";\n\t\t} else if (name.equals(\"double\") || name.equals(\"float\")) {\n\t\t\treturn \"REAL\";\n\t\t} else if (name.equals(\"long\")) {\n\t\t\treturn \"INTEGER\";\n\t\t} else if (name.equals(\"geometry\") || name.equals(\"byte[]\")) {\n\t\t\treturn \"BLOB\";\n\t\t}\n\t\t\n\t\treturn \"TEXT\";\n\t}\n\t/** Decode SQLite data types to Java classes\n\t * \n\t * @param sqlType\n\t * @return\n\t */\n\tpublic Class decodeType(String sqlType) {\n\t\t\n\t\tJavaType jType = sqlTypeMap.get(sqlType.toLowerCase());\n\t\tif (jType==null || jType==JavaType.UNKNOWN) \n\t\t\tthrow new IllegalArgumentException(\"Unknown SQL data type '\"+sqlType+\"'\");\n\t\t\n\t\tswitch (jType) {\n\t\tcase INTEGER:\n\t\t\treturn Integer.class;\n\t\tcase STRING:\n\t\t\treturn String.class;\n\t\tcase BOOLEAN:\n\t\t\treturn Boolean.class;\n\t\tcase FLOAT:\n\t\t\treturn Float.class;\n\t\tcase DOUBLE:\n\t\t\treturn Double.class;\n\t\tcase BYTE_ARR:\n\t\t\treturn Byte[].class;\n\t\t}\n\n\t\treturn String.class;\n\t}\n\n\n\n}\n"},"message":{"kind":"string","value":"Fixed bug inserting features\n\nWhen features were being inserted and an attribute didn't exist the\nvalue insertion was skipped, compared to inserting Null, causing values\nto go into the wrong fields\n"},"old_file":{"kind":"string","value":"AugTech_GeoAPI_Impl/com/augtech/geoapi/geopackage/GeoPackage.java"},"subject":{"kind":"string","value":"Fixed bug inserting features"},"git_diff":{"kind":"string","value":"ugTech_GeoAPI_Impl/com/augtech/geoapi/geopackage/GeoPackage.java\n \t * If there are multiple feature types within the collection they are\n \t * automatically split to their corresponding tables.\n \t * The table name to insert into is taken from the local part of\n\t * the {@link FeatureType#getName()}.\n\t * the {@link FeatureType#getName()}.

\n\t * The relevant tables must already exist in the GeoPackage.\n \t * \n \t * @param features\n \t * @return The number of records inserted\n \t\t\n \t\t/* Features within the collection could be different types, so split\n \t\t * in to seperate lists for batch insertion */\n\t\tMap> typeList = new HashMap>();\n\t\tMap> sfByType = new HashMap>();\n \t\tfor (SimpleFeature sf : features) {\n \t\t\tName tName = sf.getType().getName();\n\t\t\tList thisType = typeList.get(tName);\n\t\t\tList thisType = sfByType.get(tName);\n \t\t\t\n \t\t\tif (thisType==null) {\n \t\t\t\tthisType = new ArrayList();\n\t\t\t\ttypeList.put(tName, thisType);\n\t\t\t\tsfByType.put(tName, thisType);\n \t\t\t}\n \t\t\tthisType.add(sf);\n \t\t\t\n \t\tFeaturesTable featTable = null;\n \t\t\n \t\t// For each set of feature's in our individual lists..\n\t\tfor (Map.Entry> e : typeList.entrySet()) {\n\t\tfor (Map.Entry> e : sfByType.entrySet()) {\n \t\t\t\n \t\t\tfeatTable = (FeaturesTable)getUserTable( \n \t\t\t\t\te.getKey().getLocalPart(), GpkgTable.TABLE_TYPE_FEATURES );\n \t\t\tinsertVals = null;\n \t\t}\n \t\t\n\t\ttypeList = null;\n\t\tsfByType = null;\n \t\t\n \t\tif (numInserted>0) updateLastChange(featTable.getTableName(), featTable.getTableType());\n \t\t\n \t\t\t\tvalue = feature.getID();\n \t\t\t} else {\n \t\t\t\tint idx = type.indexOf( field.getFieldName() );\n\t\t\t\t//This field isn't defined on the feature type, so can't insert value\n\t\t\t\tif (idx==-1 || idx > type.getAttributeCount()) continue; \n\t\t\t\t\n\t\t\t\tvalue = feature.getAttribute(idx);\n\t\t\t\t/* If the field is not available on the type, set to null to ensure\n\t\t\t\t * the value list matches the table definition */\n\t\t\t\tif (idx==-1 || idx > type.getAttributeCount()) {\n\t\t\t\t\tvalue = null; \n\t\t\t\t} else {\n\t\t\t\t\tvalue = feature.getAttribute(idx);\n\t\t\t\t}\n \t\t\t}\n \n \t\t\tpassConstraint = true;"}}},{"rowIdx":878,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"ba2ba2f1d00d12f1fcaac6454eea1292a1e4b318"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"spring-cloud/spring-cloud-dataflow-admin-cloudfoundry,spring-cloud/spring-cloud-dataflow-admin-cloudfoundry,spring-cloud/spring-cloud-dataflow-server-cloudfoundry,spring-cloud/spring-cloud-dataflow-admin-cloudfoundry,spring-cloud/spring-cloud-dataflow-server-cloudfoundry,spring-cloud/spring-cloud-dataflow-server-cloudfoundry"},"new_contents":{"kind":"string","value":"/*\n * Copyright 2016 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.springframework.cloud.dataflow.server.cloudfoundry.resource;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Iterator;\nimport java.util.LinkedHashMap;\nimport java.util.Map;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport org.springframework.cloud.deployer.resource.support.DelegatingResourceLoader;\nimport org.springframework.core.io.Resource;\nimport org.springframework.core.io.ResourceLoader;\nimport org.springframework.util.Assert;\nimport org.springframework.util.FileSystemUtils;\n\n/**\n * A wrapper around a {@link org.springframework.core.io.ResourceLoader} that deletes returned Resources (assumed to\n * be on the file system) once disk space is getting low. Least Recently Used entries are removed first.\n *\n *

This wrapper is typically meant to be used to clean Maven {@literal .m2/repository} entries, but also works\n * with other files. For the former case, if entries are under the configured {@link #repositoryCache} path (typically\n * the {@literal .m2/repository} path), then the whole parent directory of the resource is removed. Otherwise, the sole\n * resource file is deleted.

\n *\n * @author Eric Bottard\n */\n// NOTE: extends DelegatingResourceLoader as a\n// work around https://github.com/spring-cloud/spring-cloud-dataflow/issues/1064 for now\n/*default*/ class LRUCleaningResourceLoader extends DelegatingResourceLoader {\n\n\tprivate static final Logger logger = LoggerFactory.getLogger(LRUCleaningResourceLoader.class);\n\n\tprivate final File repositoryCache;\n\n\tprivate final ResourceLoader delegate;\n\n\tprivate final Map lruCache = this.new LRUCache();\n\n\tprivate final float targetFreeSpaceRatio;\n\n\t/**\n\t * Instantiates a new LRUCleaning resource loader.\n\t * @param delegate the ResourceLoader to wrap, assumed to be file system based.\n\t * @param targetFreeSpaceRatio The target free disk space ratio, between 0 and 1.\n\t * @param repositoryCache The directory location of the maven cache.\n\t */\n\tpublic LRUCleaningResourceLoader(ResourceLoader delegate, float targetFreeSpaceRatio, File repositoryCache) {\n\t\tAssert.notNull(delegate, \"delegate cannot be null\");\n\t\tAssert.isTrue(0 <= targetFreeSpaceRatio && targetFreeSpaceRatio <= 1, \"targetFreeSpaceRatio should between [0,1] inclusive.\");\n\t\tthis.delegate = delegate;\n\t\tthis.targetFreeSpaceRatio = targetFreeSpaceRatio;\n\t\tthis.repositoryCache = repositoryCache;\n\t}\n\n\t@Override\n\tpublic Resource getResource(String location) {\n\t\tResource resource = delegate.getResource(location);\n\t\ttry {\n\t\t\tFile file = resource.getFile();\n\t\t\tsynchronized (lruCache) {\n\t\t\t\tlruCache.put(file, null);\n\t\t\t}\n\t\t\treturn resource;\n\t\t}\n\t\tcatch (IOException e) {\n\t\t\tthrow new RuntimeException(getClass().getSimpleName()\n\t\t\t\t+ \" is meant to work with File resolvable Resources. Exception trying to resolve \" + location, e);\n\t\t}\n\t}\n\n\t@Override\n\tpublic ClassLoader getClassLoader() {\n\t\treturn delegate.getClassLoader();\n\t}\n\n\tprivate class LRUCache extends LinkedHashMap {\n\n\t\tLRUCache() {\n\t\t\tsuper(5, .75f, true);\n\t\t}\n\n\t\t@Override\n\t\tprotected boolean removeEldestEntry(Map.Entry eldest) {\n\t\t\tfor (Iterator it = keySet().iterator(); it.hasNext(); ) {\n\t\t\t\tFile file = it.next();\n\t\t\t\tlogger.info(\"Looking at {}, {} / {} = {}% free space\", file, file.getFreeSpace(), file.getTotalSpace(), 100f * file.getFreeSpace() / file.getTotalSpace());\n\t\t\t\tif (shouldDelete(file) && it.hasNext()) { // never delete the most recent entry\n\t\t\t\t\tcleanup(file);\n\t\t\t\t\tit.remove();\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false; // We already did some cleanup, don't let superclass do its logic\n\t\t}\n\n\t\tprivate void cleanup(File file) {\n\t\t\tif (repositoryCache != null && file.getPath().startsWith(repositoryCache.getPath())) {\n\t\t\t\tboolean success = FileSystemUtils.deleteRecursively(file.getParentFile());\n\t\t\t\tlogger.debug(\"[{}] Deleting {} parent directory to regain free space {}\", success ? \"SUCCESS\" : \"FAILED\", file);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tboolean success = file.delete();\n\t\t\t\tlogger.debug(\"[{}] Deleting {} to regain free space\", success ? \"SUCCESS\" : \"FAILED\", file);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate boolean shouldDelete(File file) {\n\t\treturn ((float) file.getFreeSpace()) / file.getTotalSpace() < targetFreeSpaceRatio;\n\t}\n}\n"},"new_file":{"kind":"string","value":"spring-cloud-dataflow-server-cloudfoundry-autoconfig/src/main/java/org/springframework/cloud/dataflow/server/cloudfoundry/resource/LRUCleaningResourceLoader.java"},"old_contents":{"kind":"string","value":"/*\n * Copyright 2016 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.springframework.cloud.dataflow.server.cloudfoundry.resource;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Iterator;\nimport java.util.LinkedHashMap;\nimport java.util.Map;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport org.springframework.cloud.deployer.resource.support.DelegatingResourceLoader;\nimport org.springframework.core.io.Resource;\nimport org.springframework.core.io.ResourceLoader;\nimport org.springframework.util.Assert;\nimport org.springframework.util.FileSystemUtils;\n\n/**\n * A wrapper around a {@link org.springframework.core.io.ResourceLoader} that deletes returned Resources (assumed to\n * be on the file system) once disk space is getting low. Least Recently Used entries are removed first.\n *\n *

This wrapper is typically meant to be used to clean Maven {@literal .m2/repository} entries, but also works\n * with other files. For the former case, if entries are under the configured {@link #repositoryCache} path (typically\n * the {@literal .m2/repository} path), then the whole parent directory of the resource is removed. Otherwise, the sole\n * resource file is deleted.

\n *\n * @author Eric Bottard\n */\n// NOTE: extends DelegatingResourceLoader as a\n// work around https://github.com/spring-cloud/spring-cloud-dataflow/issues/1064 for now\n/*default*/ class LRUCleaningResourceLoader extends DelegatingResourceLoader {\n\n\tprivate static final Logger logger = LoggerFactory.getLogger(LRUCleaningResourceLoader.class);\n\n\tprivate final File repositoryCache;\n\n\tprivate final ResourceLoader delegate;\n\n\tprivate final Map lruCache = this.new LRUCache();\n\n\tprivate final float targetFreeSpaceRatio;\n\n\t/**\n\t * Instantiates a new LRUCleaning resource loader.\n\t * @param delegate the ResourceLoader to wrap, assumed to be file system based.\n\t * @param targetFreeSpaceRatio The target free disk space ratio, between 0 and 1.\n\t * @param repositoryCache The directory location of the maven cache.\n\t */\n\tpublic LRUCleaningResourceLoader(ResourceLoader delegate, float targetFreeSpaceRatio, File repositoryCache) {\n\t\tAssert.notNull(delegate, \"delegate cannot be null\");\n\t\tAssert.isTrue(0 < targetFreeSpaceRatio && targetFreeSpaceRatio < 1, \"targetFreeSpaceRatio should be between 0 and 1\");\n\t\tthis.delegate = delegate;\n\t\tthis.targetFreeSpaceRatio = targetFreeSpaceRatio;\n\t\tthis.repositoryCache = repositoryCache;\n\t}\n\n\t@Override\n\tpublic Resource getResource(String location) {\n\t\tResource resource = delegate.getResource(location);\n\t\ttry {\n\t\t\tFile file = resource.getFile();\n\t\t\tsynchronized (lruCache) {\n\t\t\t\tlruCache.put(file, null);\n\t\t\t}\n\t\t\treturn resource;\n\t\t}\n\t\tcatch (IOException e) {\n\t\t\tthrow new RuntimeException(getClass().getSimpleName()\n\t\t\t\t+ \" is meant to work with File resolvable Resources. Exception trying to resolve \" + location, e);\n\t\t}\n\t}\n\n\t@Override\n\tpublic ClassLoader getClassLoader() {\n\t\treturn delegate.getClassLoader();\n\t}\n\n\tprivate class LRUCache extends LinkedHashMap {\n\n\t\tLRUCache() {\n\t\t\tsuper(5, .75f, true);\n\t\t}\n\n\t\t@Override\n\t\tprotected boolean removeEldestEntry(Map.Entry eldest) {\n\t\t\tfor (Iterator it = keySet().iterator(); it.hasNext(); ) {\n\t\t\t\tFile file = it.next();\n\t\t\t\tlogger.info(\"Looking at {}, {} / {} = {}% free space\", file, file.getFreeSpace(), file.getTotalSpace(), 100f * file.getFreeSpace() / file.getTotalSpace());\n\t\t\t\tif (shouldDelete(file) && it.hasNext()) { // never delete the most recent entry\n\t\t\t\t\tcleanup(file);\n\t\t\t\t\tit.remove();\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false; // We already did some cleanup, don't let superclass do its logic\n\t\t}\n\n\t\tprivate void cleanup(File file) {\n\t\t\tif (repositoryCache != null && file.getPath().startsWith(repositoryCache.getPath())) {\n\t\t\t\tboolean success = FileSystemUtils.deleteRecursively(file.getParentFile());\n\t\t\t\tlogger.debug(\"[{}] Deleting {} parent directory to regain free space {}\", success ? \"SUCCESS\" : \"FAILED\", file);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tboolean success = file.delete();\n\t\t\t\tlogger.debug(\"[{}] Deleting {} to regain free space\", success ? \"SUCCESS\" : \"FAILED\", file);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate boolean shouldDelete(File file) {\n\t\treturn ((float) file.getFreeSpace()) / file.getTotalSpace() < targetFreeSpaceRatio;\n\t}\n}\n"},"message":{"kind":"string","value":"Change assertion to be inclusive of 0 and 1 for free disk percentage\n\nFixes #244\n"},"old_file":{"kind":"string","value":"spring-cloud-dataflow-server-cloudfoundry-autoconfig/src/main/java/org/springframework/cloud/dataflow/server/cloudfoundry/resource/LRUCleaningResourceLoader.java"},"subject":{"kind":"string","value":"Change assertion to be inclusive of 0 and 1 for free disk percentage"},"git_diff":{"kind":"string","value":"pring-cloud-dataflow-server-cloudfoundry-autoconfig/src/main/java/org/springframework/cloud/dataflow/server/cloudfoundry/resource/LRUCleaningResourceLoader.java\n \t */\n \tpublic LRUCleaningResourceLoader(ResourceLoader delegate, float targetFreeSpaceRatio, File repositoryCache) {\n \t\tAssert.notNull(delegate, \"delegate cannot be null\");\n\t\tAssert.isTrue(0 < targetFreeSpaceRatio && targetFreeSpaceRatio < 1, \"targetFreeSpaceRatio should be between 0 and 1\");\n\t\tAssert.isTrue(0 <= targetFreeSpaceRatio && targetFreeSpaceRatio <= 1, \"targetFreeSpaceRatio should between [0,1] inclusive.\");\n \t\tthis.delegate = delegate;\n \t\tthis.targetFreeSpaceRatio = targetFreeSpaceRatio;\n \t\tthis.repositoryCache = repositoryCache;"}}},{"rowIdx":879,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"cd86fbf2b2a1ebb174f9984ab946b12e94f2ea81"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"kduretec/TestDataGenerator"},"new_contents":{"kind":"string","value":"package benchmarkdp.datagenerator.app;\n\nimport java.io.File;\nimport java.io.IOException;\n\nimport org.apache.commons.io.FileUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport benchmarkdp.datagenerator.generator.utils.ZipUtil;\nimport benchmarkdp.datagenerator.properties.ExperimentProperties;\nimport benchmarkdp.datagenerator.testcase.TestCaseContainer;\nimport benchmarkdp.datagenerator.workflow.IWorkflowStep;\n\npublic class ToolEvaluatorStep implements IWorkflowStep {\n\n\tprivate static Logger log = LoggerFactory.getLogger(ToolEvaluatorStep.class);\n\n\tprivate static String COM_FOLDER_TO = \"/Users/kresimir/Mount/Hephaistos/Experiments/TaskIn\";\n\tprivate static String COM_FOLDER_FROM = \"/Users/kresimir/Mount/Hephaistos/Experiments/TaskOut\";\n\n\t@Override\n\tpublic void executeStep(ExperimentProperties ep, TestCaseContainer tCC) {\n\n\t\tlog.info(\"Tool Evaluator step\");\n\t\tif (ep.getExperimentState().compareTo(\"TEST_CASES_FINALIZED\") == 0) {\n\t\t\tcopyToEvaluation(ep, tCC);\n\t\t} else if (ep.getExperimentState().compareTo(\"TEST_CASES_SEND_TO_EVALUATION\") == 0) {\n\n\t\t}\n\n\t}\n\n\t@Override\n\tpublic IWorkflowStep nextStep() {\n\t\t// TODO Auto-generated method stub\n\t\treturn null;\n\t}\n\n\tprivate void copyToEvaluation(ExperimentProperties ep, TestCaseContainer tCC) {\n\t\tlog.info(\"Sending documents to evaluation\");\n\n\t\ttry {\n\t\t\tString experimentName = ep.getExperimentName();\n\t\t\tString pathTmp = ep.getFullFolderPath() + \"/tmp/\" + experimentName;\n\t\t\tFile f = new File(pathTmp);\n\t\t\tif (!f.exists()) {\n\t\t\t\tf.mkdirs();\n\t\t\t}\n\t\t\tString zipFolder = pathTmp;\n\t\t\tpathTmp = pathTmp + \"/\" + experimentName;\n\t\t\tFile sDocs = new File(ep.getFullFolderPath() + ep.getDocumentFolder());\n\t\t\tFile dDocs = new File(pathTmp + \"/Documents\");\n\t\t\tFileUtils.copyDirectory(sDocs, dDocs);\n\t\t\tFile sText = new File(ep.getFullFolderPath() + ep.getTextFolder());\n\t\t\tFile dText = new File(pathTmp + \"/GroundTruth/Text\");\n\t\t\tFileUtils.copyDirectory(sText, dText);\n\t\t\tFile sMet = new File(ep.getFullFolderPath() + ep.getMetadataFolder());\n\t\t\tFile dMet = new File(pathTmp + \"/GroundTruth/Metadata\");\n\t\t\tFileUtils.copyDirectory(sMet, dMet);\n\t\t\t\n\t\t\tFile propFile = new File (ep.getFullFolderPath() + \"properties.xml\");\n\t\t\tFileUtils.copyFileToDirectory(propFile, f);\n\t\t\tFile tcFile = new File (ep.getFullFolderPath() + \"testCases.xml\");\n\t\t\tFileUtils.copyFileToDirectory(tcFile, f);\n\t\t\t\n\t\t\tZipUtil.zipFolder(zipFolder, COM_FOLDER_TO, ep.getExperimentName());\n\t\t\t//FileUtils.deleteDirectory(new File(ep.getFullFolderPath() + \"/tmp\"));\n\t\t\t\n\t\t} catch (IOException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n}\n"},"new_file":{"kind":"string","value":"DataGenerator/src/benchmarkdp/datagenerator/app/ToolEvaluatorStep.java"},"old_contents":{"kind":"string","value":"package benchmarkdp.datagenerator.app;\n\nimport java.io.File;\nimport java.io.IOException;\n\nimport org.apache.commons.io.FileUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport benchmarkdp.datagenerator.generator.utils.ZipUtil;\nimport benchmarkdp.datagenerator.properties.ExperimentProperties;\nimport benchmarkdp.datagenerator.testcase.TestCaseContainer;\nimport benchmarkdp.datagenerator.workflow.IWorkflowStep;\n\npublic class ToolEvaluatorStep implements IWorkflowStep {\n\n\tprivate static Logger log = LoggerFactory.getLogger(ToolEvaluatorStep.class);\n\n\tprivate static String COM_FOLDER_TO = \"/Users/kresimir/Mount/Hephaistos/Experiments/TaskIn\";\n\tprivate static String COM_FOLDER_FROM = \"/Users/kresimir/Mount/Hephaistos/Experiments/TaskOut\";\n\n\t@Override\n\tpublic void executeStep(ExperimentProperties ep, TestCaseContainer tCC) {\n\n\t\tlog.info(\"Tool Evaluator step\");\n\t\tif (ep.getExperimentState().compareTo(\"TEST_CASES_FINALIZED\") == 0) {\n\t\t\tcopyToEvaluation(ep, tCC);\n\t\t} else if (ep.getExperimentState().compareTo(\"TEST_CASES_SEND_TO_EVALUATION\") == 0) {\n\n\t\t}\n\n\t}\n\n\t@Override\n\tpublic IWorkflowStep nextStep() {\n\t\t// TODO Auto-generated method stub\n\t\treturn null;\n\t}\n\n\tprivate void copyToEvaluation(ExperimentProperties ep, TestCaseContainer tCC) {\n\t\tlog.info(\"Sending documents to evaluation\");\n\n\t\ttry {\n\t\t\tString experimentName = ep.getExperimentName();\n\t\t\tString pathTmp = ep.getFullFolderPath() + \"/tmp/\" + experimentName;\n\t\t\tFile f = new File(pathTmp);\n\t\t\tif (!f.exists()) {\n\t\t\t\tf.mkdirs();\n\t\t\t}\n\t\t\tFile sDocs = new File(ep.getFullFolderPath() + ep.getDocumentFolder());\n\t\t\tFile dDocs = new File(pathTmp + \"/Documents\");\n\t\t\tFileUtils.copyDirectory(sDocs, dDocs);\n\t\t\tFile sText = new File(ep.getFullFolderPath() + ep.getTextFolder());\n\t\t\tFile dText = new File(pathTmp + \"/GroundTruth/Text\");\n\t\t\tFileUtils.copyDirectory(sText, dText);\n\t\t\tFile sMet = new File(ep.getFullFolderPath() + ep.getMetadataFolder());\n\t\t\tFile dMet = new File(pathTmp + \"/GroundTruth/Metadata\");\n\t\t\tFileUtils.copyDirectory(sMet, dMet);\n\t\t\t\n\t\t\tFile propFile = new File (ep.getFullFolderPath() + \"properties.xml\");\n\t\t\tFileUtils.copyFileToDirectory(propFile, f);\n\t\t\tFile tcFile = new File (ep.getFullFolderPath() + \"testCases.xml\");\n\t\t\tFileUtils.copyFileToDirectory(tcFile, f);\n\t\t\t\n\t\t\tZipUtil.zipFolder(pathTmp, COM_FOLDER_TO, ep.getExperimentName());\n\t\t\tFileUtils.deleteDirectory(new File(ep.getFullFolderPath() + \"/tmp\"));\n\t\t\t\n\t\t} catch (IOException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n}\n"},"message":{"kind":"string","value":"small updates\n"},"old_file":{"kind":"string","value":"DataGenerator/src/benchmarkdp/datagenerator/app/ToolEvaluatorStep.java"},"subject":{"kind":"string","value":"small updates"},"git_diff":{"kind":"string","value":"ataGenerator/src/benchmarkdp/datagenerator/app/ToolEvaluatorStep.java\n \t\t\tif (!f.exists()) {\n \t\t\t\tf.mkdirs();\n \t\t\t}\n\t\t\tString zipFolder = pathTmp;\n\t\t\tpathTmp = pathTmp + \"/\" + experimentName;\n \t\t\tFile sDocs = new File(ep.getFullFolderPath() + ep.getDocumentFolder());\n \t\t\tFile dDocs = new File(pathTmp + \"/Documents\");\n \t\t\tFileUtils.copyDirectory(sDocs, dDocs);\n \t\t\tFile tcFile = new File (ep.getFullFolderPath() + \"testCases.xml\");\n \t\t\tFileUtils.copyFileToDirectory(tcFile, f);\n \t\t\t\n\t\t\tZipUtil.zipFolder(pathTmp, COM_FOLDER_TO, ep.getExperimentName());\n\t\t\tFileUtils.deleteDirectory(new File(ep.getFullFolderPath() + \"/tmp\"));\n\t\t\tZipUtil.zipFolder(zipFolder, COM_FOLDER_TO, ep.getExperimentName());\n\t\t\t//FileUtils.deleteDirectory(new File(ep.getFullFolderPath() + \"/tmp\"));\n \t\t\t\n \t\t} catch (IOException e) {\n \t\t\t// TODO Auto-generated catch block"}}},{"rowIdx":880,"cells":{"lang":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"bsd-2-clause"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"268e74b13ed5ea4c330a367b9f429b74c7d12dcd"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"t2ym/thin-polymer,t2ym/thin-polymer"},"new_contents":{"kind":"string","value":"/*\n@license https://github.com/t2ym/thin-polymer/blob/master/LICENSE.md\nCopyright (c) 2016, Tetsuya Mori . All rights reserved.\n*/\n(function () {\n function UncamelCase (name) {\n return name\n // insert a hyphen between lower & upper\n .replace(/([a-z0-9])([A-Z])/g, '$1 $2')\n // space before last upper in a sequence followed by lower\n .replace(/\\b([A-Z]+)([A-Z])([a-z0-9])/, '$1 $2$3')\n // replace spaces with hyphens\n .replace(/ /g, '-')\n // lowercase\n .toLowerCase();\n }\n function functionName (func) {\n return typeof func === 'function' ? \n func.toString().replace(/^[\\S\\s]*?function\\s*/, \"\").replace(/[\\s\\(\\/][\\S\\s]+$/, \"\") :\n undefined;\n }\n if (!window.Prototype) {\n Object.defineProperty(window, 'Prototype', {\n get: function () {\n return function (id) {\n return this.PolymerElements ? this.PolymerElements[id] : undefined;\n };\n },\n set: function (proto) {\n /*\n Patterns:\n a) template id {}\n b) template id {is}\n c) document.template id {is}\n d) template {is}\n e) {is}\n f) class Is {template}\n g) {is,template}\n */\n var id;\n var classId;\n var obj;\n var name = proto.name || functionName(proto);\n var current; // currentScript\n var template = null;\n var previous; // previousSibling template\n var cousin; // dom5.serialize output support\n\n current = Polymer.Settings.useNativeImports ? document.currentScript\n : document._currentScript;\n\n previous = current.previousSibling;\n while (previous && !previous.tagName) {\n previous = previous.previousSibling;\n }\n if (previous && previous.tagName !== 'template'.toUpperCase()) {\n previous = null;\n }\n if (!previous) {\n // search for cousin template\n if (current.parentNode.tagName === 'body'.toUpperCase()) {\n previous = current.parentNode.previousSibling;\n while (previous && !previous.tagName) {\n previous = previous.previousSibling;\n }\n if (previous && previous.tagName.toLowerCase() === 'head') {\n for (var i = 0; i < previous.childNodes.length; i++) {\n if (previous.childNodes[i].tagName === 'template'.toUpperCase()) {\n cousin = previous.childNodes[i];\n break;\n }\n }\n }\n }\n if (cousin) {\n previous = cousin;\n }\n else {\n previous = null;\n }\n }\n\n if (!proto.is && (!name || name === 'class' || name === 'Prototype')) {\n if (previous) {\n id = previous.id;\n if (id) {\n // Pattern a)\n template = previous;\n proto.is = id;\n }\n }\n }\n else {\n if (proto.is) {\n id = proto.is;\n }\n else if (typeof proto === 'function' && name) {\n // ES6 class\n id = UncamelCase(name);\n classId = name;\n obj = new proto();\n if (obj.template) {\n // Pattern f)\n template = document.createElement('template');\n template.innerHTML = obj.template;\n var children = Array.prototype.filter.call(template.content.childNodes, \n function (node) { return node.tagName; });\n var topChild = children.length === 1 ? children[0] : undefined;\n if (topChild && topChild.tagName.toLowerCase() === 'template') {\n template = topChild;\n }\n }\n obj.is = id;\n Object.getOwnPropertyNames(obj.__proto__).forEach(function (prop) {\n obj[prop] = obj.__proto__[prop];\n });\n proto = obj;\n }\n if (!template && proto.template) {\n // Pattern g)\n template = document.createElement('template');\n template.innerHTML = proto.template;\n }\n if (!template) {\n // Pattern b), c)\n template = current.ownerDocument\n .querySelector('template[id=' + id + ']') || \n document.querySelector('template[id=' + id + ']');\n }\n if (!template && previous && !previous.id) {\n // Pattern d)\n template = previous;\n template.id = id;\n }\n else {\n // Pattern e)\n }\n }\n\n if (!id) {\n throw 'Custom element name is not defined';\n }\n\n // register dom-module\n if (template) {\n var domModule = document.createElement('dom-module');\n var assetUrl = new URL(current.baseURI || window.currentImport.baseURI);\n domModule.appendChild(template);\n domModule.setAttribute('assetpath', \n assetUrl.pathname.indexOf('.vulcanized.') < 0 ?\n assetUrl.pathname :\n template.hasAttribute('assetpath') ? \n template.getAttribute('assetpath') : \n assetUrl.pathname);\n domModule.register(id);\n }\n\n // register Polymer element\n this.PolymerElements = this.PolymerElements || {};\n classId = classId || id.split('-').map(function (word) {\n return word[0].toUpperCase() + word.substr(1);\n }).join('');\n var PrototypeGeneratorName = 'Polymer'; // to pass jshint\n if (this.PolymerElements[id]) {\n console.warn('Discarding duplicate regitration of custom element ' + id);\n }\n else {\n this.PolymerElements[id] = window[PrototypeGeneratorName](proto); // to pass strip\n this.PolymerElements[classId] = this.PolymerElements[id];\n }\n return this.PolymerElements[id];\n }\n });\n }\n})();\n"},"new_file":{"kind":"string","value":"thin-polymer.js"},"old_contents":{"kind":"string","value":"/*\n@license https://github.com/t2ym/thin-polymer/blob/master/LICENSE.md\nCopyright (c) 2016, Tetsuya Mori . All rights reserved.\n*/\n(function () {\n function UncamelCase (name) {\n return name\n // insert a hyphen between lower & upper\n .replace(/([a-z0-9])([A-Z])/g, '$1 $2')\n // space before last upper in a sequence followed by lower\n .replace(/\\b([A-Z]+)([A-Z])([a-z0-9])/, '$1 $2$3')\n // replace spaces with hyphens\n .replace(/ /g, '-')\n // lowercase\n .toLowerCase();\n }\n function functionName (func) {\n return typeof func === 'function' ? \n func.toString().replace(/^[\\S\\s]*?function\\s*/, \"\").replace(/[\\s\\(\\/][\\S\\s]+$/, \"\") :\n undefined;\n }\n if (!window.Prototype) {\n Object.defineProperty(window, 'Prototype', {\n get: function () {\n return function (id) {\n return this.PolymerElements ? this.PolymerElements[id] : undefined;\n };\n },\n set: function (proto) {\n /*\n Patterns:\n a) template id {}\n b) template id {is}\n c) document.template id {is}\n d) template {is}\n e) {is}\n f) class Is {template}\n g) {is,template}\n */\n var id;\n var classId;\n var name = proto.name || functionName(proto);\n var current; // currentScript\n var template = null;\n var previous; // previousSibling template\n var cousin; // dom5.serialize output support\n\n current = Polymer.Settings.useNativeImports ? document.currentScript\n : document._currentScript;\n\n previous = current.previousSibling;\n while (previous && !previous.tagName) {\n previous = previous.previousSibling;\n }\n if (previous && previous.tagName !== 'template'.toUpperCase()) {\n previous = null;\n }\n if (!previous) {\n // search for cousin template\n if (current.parentNode.tagName === 'body'.toUpperCase()) {\n previous = current.parentNode.previousSibling;\n while (previous && !previous.tagName) {\n previous = previous.previousSibling;\n }\n if (previous && previous.tagName.toLowerCase() === 'head') {\n for (var i = 0; i < previous.childNodes.length; i++) {\n if (previous.childNodes[i].tagName === 'template'.toUpperCase()) {\n cousin = previous.childNodes[i];\n break;\n }\n }\n }\n }\n if (cousin) {\n previous = cousin;\n }\n else {\n previous = null;\n }\n }\n\n if (!proto.is && !name) {\n if (previous) {\n id = previous.id;\n if (id) {\n // Pattern a)\n template = previous;\n proto.is = id;\n }\n }\n }\n else {\n if (proto.is) {\n id = proto.is;\n }\n else if (typeof proto === 'function' && name) {\n // ES6 class\n id = UncamelCase(name);\n classId = name;\n proto = new proto();\n if (proto.template) {\n // Pattern f)\n template = document.createElement('template');\n template.innerHTML = proto.template;\n var children = Array.prototype.filter.call(template.content.childNodes, \n function (node) { return node.tagName; });\n var topChild = children.length === 1 ? children[0] : undefined;\n if (topChild && topChild.tagName.toLowerCase() === 'template') {\n template = topChild;\n }\n }\n proto = proto.__proto__;\n proto.is = id;\n }\n if (!template && proto.template) {\n // Pattern g)\n template = document.createElement('template');\n template.innerHTML = proto.template;\n }\n if (!template) {\n // Pattern b), c)\n template = current.ownerDocument\n .querySelector('template[id=' + id + ']') || \n document.querySelector('template[id=' + id + ']');\n }\n if (!template && previous && !previous.id) {\n // Pattern d)\n template = previous;\n template.id = id;\n }\n else {\n // Pattern e)\n }\n }\n\n if (!id) {\n throw 'Custom element name is not defined';\n }\n\n // register dom-module\n if (template) {\n var domModule = document.createElement('dom-module');\n var assetUrl = new URL(current.baseURI || window.currentImport.baseURI);\n domModule.appendChild(template);\n domModule.setAttribute('assetpath', \n assetUrl.pathname.indexOf('.vulcanized.') < 0 ?\n assetUrl.pathname :\n template.hasAttribute('assetpath') ? \n template.getAttribute('assetpath') : \n assetUrl.pathname);\n domModule.register(id);\n }\n\n // register Polymer element\n this.PolymerElements = this.PolymerElements || {};\n classId = classId || id.split('-').map(function (word) {\n return word[0].toUpperCase() + word.substr(1);\n }).join('');\n var PrototypeGeneratorName = 'Polymer'; // to pass jshint\n if (this.PolymerElements[id]) {\n console.warn('Discarding duplicate regitration of custom element ' + id);\n }\n else {\n this.PolymerElements[id] = window[PrototypeGeneratorName](proto); // to pass strip\n this.PolymerElements[classId] = this.PolymerElements[id];\n }\n return this.PolymerElements[id];\n }\n });\n }\n})();\n"},"message":{"kind":"string","value":"Copy properties of prototype\n"},"old_file":{"kind":"string","value":"thin-polymer.js"},"subject":{"kind":"string","value":"Copy properties of prototype"},"git_diff":{"kind":"string","value":"hin-polymer.js\n */\n var id;\n var classId;\n var obj;\n var name = proto.name || functionName(proto);\n var current; // currentScript\n var template = null;\n }\n }\n \n if (!proto.is && !name) {\n if (!proto.is && (!name || name === 'class' || name === 'Prototype')) {\n if (previous) {\n id = previous.id;\n if (id) {\n // ES6 class\n id = UncamelCase(name);\n classId = name;\n proto = new proto();\n if (proto.template) {\n obj = new proto();\n if (obj.template) {\n // Pattern f)\n template = document.createElement('template');\n template.innerHTML = proto.template;\n template.innerHTML = obj.template;\n var children = Array.prototype.filter.call(template.content.childNodes, \n function (node) { return node.tagName; });\n var topChild = children.length === 1 ? children[0] : undefined;\n template = topChild;\n }\n }\n proto = proto.__proto__;\n proto.is = id;\n obj.is = id;\n Object.getOwnPropertyNames(obj.__proto__).forEach(function (prop) {\n obj[prop] = obj.__proto__[prop];\n });\n proto = obj;\n }\n if (!template && proto.template) {\n // Pattern g)"}}},{"rowIdx":881,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"c04ae392e81e5ad840cf4f5295d0d31cf6377ef2"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"mybatis/guice,hazendaz/guice,johnzeringue/guice,WilliamRen/guice"},"new_contents":{"kind":"string","value":"/*\n * Copyright 2010 The myBatis Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.mybatis.guice;\n\nimport static org.mybatis.guice.iterables.Iterables.foreach;\n\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedHashSet;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.Map.Entry;\n\nimport javax.sql.DataSource;\n\nimport org.apache.ibatis.io.ResolverUtil;\nimport org.apache.ibatis.mapping.Environment;\nimport org.apache.ibatis.plugin.Interceptor;\nimport org.apache.ibatis.reflection.factory.DefaultObjectFactory;\nimport org.apache.ibatis.reflection.factory.ObjectFactory;\nimport org.apache.ibatis.session.Configuration;\nimport org.apache.ibatis.session.SqlSessionFactory;\nimport org.apache.ibatis.transaction.TransactionFactory;\nimport org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;\nimport org.apache.ibatis.type.TypeHandler;\nimport org.mybatis.guice.configuration.ConfigurationProvider;\nimport org.mybatis.guice.configuration.Mappers;\nimport org.mybatis.guice.configuration.TypeAliases;\nimport org.mybatis.guice.datasource.builtin.UnpooledDataSourceProvider;\nimport org.mybatis.guice.environment.EnvironmentProvider;\nimport org.mybatis.guice.iterables.Each;\nimport org.mybatis.guice.session.SqlSessionFactoryProvider;\n\nimport com.google.inject.Module;\nimport com.google.inject.Provider;\nimport com.google.inject.Scopes;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.multibindings.MapBinder;\nimport com.google.inject.multibindings.Multibinder;\n\n/**\n * Easy to use helper Module that alleviates users to write the boilerplate\n * google-guice bindings to create the SqlSessionFactory.\n *\n * @version $Id$\n */\npublic final class MyBatisModule extends AbstractMyBatisModule {\n\n /**\n * The DataSource Provider class reference.\n */\n private final Class> dataSourceProviderType;\n\n /**\n * The TransactionFactory class reference.\n */\n private final Class transactionFactoryType;\n\n /**\n * The user defined aliases.\n */\n private final Map> aliases;\n\n /**\n * The user defined type handlers.\n */\n private final Map, Class> handlers;\n\n /**\n * The user defined Interceptor classes.\n */\n private final Set> interceptorsClasses;\n\n /**\n * The ObjectFactory class reference.\n */\n private Class objectFactoryType;\n\n /**\n * The user defined mapper classes.\n */\n private final Set> mapperClasses;\n\n /**\n * Creates a new module that binds all the needed modules to create the\n * SqlSessionFactory, injecting all the required components.\n *\n * @param dataSourceProviderType the DataSource Provider class reference.\n * @param transactionFactoryType the TransactionFactory class reference.\n * @param aliases the user defined aliases.\n * @param handlers the user defined type handlers.\n * @param interceptorsClasses the user defined Interceptor classes.\n * @param objectFactoryType the ObjectFactory class reference.\n * @param mapperClasses the user defined mapper classes.\n */\n private MyBatisModule(\n Class> dataSourceProviderType,\n Class transactionFactoryType,\n Map> aliases,\n Map, Class> handlers,\n Set> interceptorsClasses,\n Class objectFactoryType,\n Set> mapperClasses) {\n this.dataSourceProviderType = dataSourceProviderType;\n this.transactionFactoryType = transactionFactoryType;\n this.aliases = aliases;\n this.handlers = handlers;\n this.interceptorsClasses = interceptorsClasses;\n this.objectFactoryType = objectFactoryType;\n this.mapperClasses = mapperClasses;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n protected void configure() {\n super.configure();\n\n // needed binding\n this.bind(DataSource.class).toProvider(this.dataSourceProviderType).in(Scopes.SINGLETON);\n this.bind(TransactionFactory.class).to(this.transactionFactoryType).in(Scopes.SINGLETON);\n this.bind(Environment.class).toProvider(EnvironmentProvider.class).in(Scopes.SINGLETON);\n this.bind(Configuration.class).toProvider(ConfigurationProvider.class).in(Scopes.SINGLETON);\n this.bind(ObjectFactory.class).to(this.objectFactoryType).in(Scopes.SINGLETON);\n this.bind(SqlSessionFactory.class).toProvider(SqlSessionFactoryProvider.class).in(Scopes.SINGLETON);\n\n // optional bindings\n\n // aliases\n if (!this.aliases.isEmpty()) {\n this.bind(new TypeLiteral>>(){}).annotatedWith(TypeAliases.class).toInstance(this.aliases);\n }\n\n // type handlers\n foreach(this.handlers).handle(new Each,Class>>() {\n\n private MapBinder, TypeHandler> handlerBinder;\n\n public void doHandle(Entry, Class> alias) {\n if (this.handlerBinder == null) {\n this.handlerBinder =\n MapBinder.newMapBinder(binder(), new TypeLiteral>(){}, new TypeLiteral(){});\n }\n\n this.handlerBinder.addBinding(alias.getKey()).to(alias.getValue()).in(Scopes.SINGLETON);\n }\n });\n\n // interceptors plugin\n foreach(this.interceptorsClasses).handle(new Each>() {\n\n private Multibinder interceptorsMultibinder;\n\n public void doHandle(Class interceptorType) {\n if (this.interceptorsMultibinder == null) {\n this.interceptorsMultibinder = Multibinder.newSetBinder(binder(), Interceptor.class);\n }\n this.interceptorsMultibinder.addBinding().to(interceptorType).in(Scopes.SINGLETON);\n }\n });\n\n // mappers\n if (!this.mapperClasses.isEmpty()) {\n this.bind(new TypeLiteral>>() {}).annotatedWith(Mappers.class).toInstance(this.mapperClasses);\n foreach(this.mapperClasses).handle(new EachMapper(this.binder()));\n }\n }\n\n /**\n * The {@link MyBatisModule} Builder.\n *\n * By default the Builder uses the following settings:\n *
    \n *
  • DataSource Provider type: {@link UnpooledDataSourceProvider};
  • \n *
  • TransactionFactory type: org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
  • \n *
  • ObjectFactory type: org.apache.ibatis.reflection.factory.ObjectFactory.
  • \n *
\n */\n public static final class Builder {\n\n /**\n * The DataSource Provider class reference.\n */\n private Class> dataSourceProviderType = UnpooledDataSourceProvider.class;\n\n /**\n * The TransactionFactory class reference.\n */\n private Class transactionFactoryType = JdbcTransactionFactory.class;\n\n /**\n * The user defined aliases.\n */\n private final Map> aliases = new HashMap>();\n\n /**\n * The user defined type handlers.\n */\n private final Map, Class> handlers = new HashMap, Class>();\n\n /**\n * The user defined Interceptor classes.\n */\n private final Set> interceptorsClasses = new HashSet>();\n\n /**\n * The ObjectFactory Provider class reference.\n */\n private Class objectFactoryType = DefaultObjectFactory.class;\n\n /**\n * The user defined mapper classes.\n */\n private final Set> mapperClasses = new LinkedHashSet>();\n\n /**\n * Set the DataSource Provider type has to be bound.\n *\n * @param dataSourceProviderType the DataSource Provider type.\n * @return this {@code Builder} instance.\n */\n public Builder setDataSourceProviderType(Class> dataSourceProviderType) {\n if (dataSourceProviderType == null) {\n throw new IllegalArgumentException(\"Parameter 'dataSourceProviderType' must be not null\");\n }\n this.dataSourceProviderType = dataSourceProviderType;\n return this;\n }\n\n /**\n * Set the TransactionFactory type has to be bound.\n *\n * @param transactionFactoryType the TransactionFactory type.\n * @return this {@code Builder} instance.\n */\n public Builder setTransactionFactoryType(Class transactionFactoryType) {\n if (transactionFactoryType == null) {\n throw new IllegalArgumentException(\"Parameter 'transactionFactoryType' must be not null\");\n }\n this.transactionFactoryType = transactionFactoryType;\n return this;\n }\n\n /**\n * Adding simple aliases means that every specified class will be bound\n * using the simple class name, i.e. {@code com.acme.Foo} becomes {@code Foo}.\n *\n * @param types the specified types have to be bind.\n * @return this {@code Builder} instance.\n */\n public Builder addSimpleAliases(final Class...types) {\n if (types != null) {\n return this.addSimpleAliases(Arrays.asList(types));\n }\n return this;\n }\n\n /**\n * Adding simple aliases means that every specified class will be bound\n * using the simple class name, i.e. {@code com.acme.Foo} becomes {@code Foo}.\n *\n * @param types the specified types have to be bind.\n * @return this {@code Builder} instance.\n */\n public Builder addSimpleAliases(final Collection> types) {\n foreach(types).handle(new Each>() {\n public void doHandle(Class clazz) {\n addAlias(clazz.getSimpleName(), clazz);\n }\n });\n return this;\n }\n\n /**\n * Adds all Classes in the given package as a simple alias.\n * Adding simple aliases means that every specified class will be bound\n * using the simple class name, i.e. {@code com.acme.Foo} becomes {@code Foo}.\n *\n * @param packageName the specified package to search for classes to alias.\n * @return this {@code Builder} instance.\n */\n public Builder addSimpleAliases(final String packageName) {\n return this.addSimpleAliases(getClasses(packageName));\n }\n\n /**\n * Adds all Classes in the given package as a simple alias.\n * Adding simple aliases means that every specified class will be bound\n * using the simple class name, i.e. {@code com.acme.Foo} becomes {@code Foo}.\n *\n * @param packageName the specified package to search for classes to alias.\n * @param test a test to run against the objects found in the specified package.\n * @return this {@code Builder} instance.\n */\n public Builder addSimpleAliases(final String packageName, final ResolverUtil.Test test) {\n return this.addSimpleAliases(getClasses(test, packageName));\n }\n\n /**\n * Add a user defined binding.\n *\n * @param alias the string type alias\n * @param clazz the type has to be bound.\n */\n public Builder addAlias(final String alias, final Class clazz) {\n this.aliases.put(alias, clazz);\n return this;\n }\n\n /**\n * Add a user defined Type Handler letting google-guice creating it.\n *\n * @param type the specified type has to be handled.\n * @param handler the handler type.\n * @return this {@code Builder} instance.\n */\n public Builder addTypeHandler(final Class type, final Class handler) {\n this.handlers.put(type, handler);\n return this;\n }\n\n /**\n * Adds the user defined myBatis interceptors plugins types, letting\n * google-guice creating them.\n *\n * @param interceptorsClasses the user defined MyBatis interceptors plugins types.\n * @return this {@code Builder} instance.\n * \n */\n public Builder addInterceptorsClasses(Class...interceptorsClasses) {\n if (interceptorsClasses != null) {\n return this.addInterceptorsClasses(Arrays.asList(interceptorsClasses));\n }\n return this;\n }\n\n /**\n * Adds the user defined MyBatis interceptors plugins types, letting\n * google-guice creating them.\n *\n * @param interceptorsClasses the user defined MyBatis Interceptors plugins types.\n * @return this {@code Builder} instance.\n * \n */\n public Builder addInterceptorsClasses(Collection> interceptorsClasses) {\n if (interceptorsClasses != null) {\n this.interceptorsClasses.addAll(interceptorsClasses);\n }\n return this;\n }\n\n /**\n * Adds the user defined MyBatis interceptors plugins types in the given package,\n * letting google-guice creating them.\n *\n * @param packageName the package where looking for Interceptors plugins types.\n * @return this {@code Builder} instance.\n */\n public Builder addInterceptorsClasses(String packageName) {\n if (packageName == null) {\n throw new IllegalArgumentException(\"Parameter 'packageName' must be not null\");\n }\n return this.addInterceptorsClasses(new ResolverUtil()\n .find(new ResolverUtil.IsA(Interceptor.class), packageName)\n .getClasses());\n }\n\n /**\n * Sets the ObjectFactory class.\n *\n * @param objectFactoryType the ObjectFactory type.\n * @return this {@code Builder} instance.\n */\n public Builder setObjectFactoryType(Class objectFactoryType) {\n if (objectFactoryType == null) {\n throw new IllegalArgumentException(\"Parameter 'objectFactoryType' must be not null\");\n }\n this.objectFactoryType = objectFactoryType;\n return this;\n }\n\n /**\n * Adds the user defined mapper classes.\n *\n * @param mapperClasses the user defined mapper classes.\n * @return this {@code Builder} instance.\n * \n */\n public Builder addMapperClasses(Class...mapperClasses) {\n if (mapperClasses != null) {\n return this.addMapperClasses(Arrays.asList(mapperClasses));\n }\n return this;\n }\n\n /**\n * Adds the user defined mapper classes.\n *\n * @param mapperClasses the user defined mapper classes.\n * @return this {@code Builder} instance.\n * \n */\n public Builder addMapperClasses(Collection> mapperClasses) {\n if (mapperClasses != null) {\n this.mapperClasses.addAll(mapperClasses);\n }\n return this;\n }\n\n /**\n * Adds the user defined mapper classes.\n *\n * @param packageName the specified package to search for mappers to add.\n * @return this {@code Builder} instance.\n * \n */\n public Builder addMapperClasses(final String packageName) {\n return this.addMapperClasses(getClasses(packageName));\n }\n\n /**\n * Adds the user defined mapper classes.\n *\n * @param packageName the specified package to search for mappers to add.\n * @param test a test to run against the objects found in the specified package.\n * @return this {@code Builder} instance.\n * \n */\n public Builder addMapperClasses(final String packageName, final ResolverUtil.Test test) {\n return this.addMapperClasses(getClasses(test, packageName));\n }\n\n /**\n * Create a new {@link MyBatisModule} instance based on this {@link Builder}\n * instance configuration.\n *\n * @return a new {@link MyBatisModule} instance.\n */\n public Module create() {\n return new MyBatisModule(this.dataSourceProviderType,\n this.transactionFactoryType,\n this.aliases,\n this.handlers,\n this.interceptorsClasses,\n this.objectFactoryType,\n this.mapperClasses);\n }\n\n /**\n * Return a set of all classes contained in the given package.\n *\n * @param packageName the package has to be analyzed.\n * @return a set of all classes contained in the given package.\n */\n private static Set> getClasses(String packageName) {\n return getClasses(new ResolverUtil.IsA(Object.class), packageName);\n }\n\n /**\n * Return a set of all classes contained in the given package that match with\n * the given test requirement.\n *\n * @param test the class filter on the given package.\n * @param packageName the package has to be analyzed.\n * @return a set of all classes contained in the given package.\n */\n private static Set> getClasses(ResolverUtil.Test test, String packageName) {\n if (test == null) {\n throw new IllegalArgumentException(\"Parameter 'test' must be not null\");\n }\n if (packageName == null) {\n throw new IllegalArgumentException(\"Parameter 'packageName' must be not null\");\n }\n return new ResolverUtil().find(test, packageName).getClasses();\n }\n\n }\n\n}\n"},"new_file":{"kind":"string","value":"src/main/java/org/mybatis/guice/MyBatisModule.java"},"old_contents":{"kind":"string","value":"/*\n * Copyright 2010 The myBatis Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.mybatis.guice;\n\nimport static org.mybatis.guice.iterables.Iterables.foreach;\n\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedHashSet;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.Map.Entry;\n\nimport javax.sql.DataSource;\n\nimport org.apache.ibatis.io.ResolverUtil;\nimport org.apache.ibatis.mapping.Environment;\nimport org.apache.ibatis.plugin.Interceptor;\nimport org.apache.ibatis.reflection.factory.DefaultObjectFactory;\nimport org.apache.ibatis.reflection.factory.ObjectFactory;\nimport org.apache.ibatis.session.Configuration;\nimport org.apache.ibatis.session.SqlSessionFactory;\nimport org.apache.ibatis.transaction.TransactionFactory;\nimport org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;\nimport org.apache.ibatis.type.TypeHandler;\nimport org.mybatis.guice.configuration.ConfigurationProvider;\nimport org.mybatis.guice.configuration.Mappers;\nimport org.mybatis.guice.configuration.TypeAliases;\nimport org.mybatis.guice.datasource.builtin.UnpooledDataSourceProvider;\nimport org.mybatis.guice.environment.EnvironmentProvider;\nimport org.mybatis.guice.iterables.Each;\nimport org.mybatis.guice.session.SqlSessionFactoryProvider;\n\nimport com.google.inject.Module;\nimport com.google.inject.Provider;\nimport com.google.inject.Scopes;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.multibindings.MapBinder;\nimport com.google.inject.multibindings.Multibinder;\n\n/**\n * Easy to use helper Module that alleviates users to write the boilerplate\n * google-guice bindings to create the SqlSessionFactory.\n *\n * @version $Id$\n */\npublic final class MyBatisModule extends AbstractMyBatisModule {\n\n /**\n * The DataSource Provider class reference.\n */\n private final Class> dataSourceProviderType;\n\n /**\n * The TransactionFactory class reference.\n */\n private final Class transactionFactoryType;\n\n /**\n * The user defined aliases.\n */\n private final Map> aliases;\n\n /**\n * The user defined type handlers.\n */\n private final Map, Class> handlers;\n\n /**\n * The user defined Interceptor classes.\n */\n private final Set> interceptorsClasses;\n\n /**\n * The ObjectFactory class reference.\n */\n private Class objectFactoryType;\n\n /**\n * The user defined mapper classes.\n */\n private final Set> mapperClasses;\n\n /**\n * Creates a new module that binds all the needed modules to create the\n * SqlSessionFactory, injecting all the required components.\n *\n * @param dataSourceProviderType the DataSource Provider class reference.\n * @param transactionFactoryType the TransactionFactory class reference.\n * @param aliases the user defined aliases.\n * @param handlers the user defined type handlers.\n * @param interceptorsClasses the user defined Interceptor classes.\n * @param objectFactoryType the ObjectFactory class reference.\n * @param mapperClasses the user defined mapper classes.\n */\n private MyBatisModule(\n Class> dataSourceProviderType,\n Class transactionFactoryType,\n Map> aliases,\n Map, Class> handlers,\n Set> interceptorsClasses,\n Class objectFactoryType,\n Set> mapperClasses) {\n this.dataSourceProviderType = dataSourceProviderType;\n this.transactionFactoryType = transactionFactoryType;\n this.aliases = aliases;\n this.handlers = handlers;\n this.interceptorsClasses = interceptorsClasses;\n this.objectFactoryType = objectFactoryType;\n this.mapperClasses = mapperClasses;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n protected void configure() {\n super.configure();\n\n // needed binding\n this.bind(DataSource.class).toProvider(this.dataSourceProviderType).in(Scopes.SINGLETON);\n this.bind(TransactionFactory.class).to(this.transactionFactoryType).in(Scopes.SINGLETON);\n this.bind(Environment.class).toProvider(EnvironmentProvider.class).in(Scopes.SINGLETON);\n this.bind(Configuration.class).toProvider(ConfigurationProvider.class).in(Scopes.SINGLETON);\n this.bind(ObjectFactory.class).to(this.objectFactoryType).in(Scopes.SINGLETON);\n this.bind(SqlSessionFactory.class).toProvider(SqlSessionFactoryProvider.class);\n\n // optional bindings\n\n // aliases\n if (!this.aliases.isEmpty()) {\n this.bind(new TypeLiteral>>(){}).annotatedWith(TypeAliases.class).toInstance(this.aliases);\n }\n\n // type handlers\n foreach(this.handlers).handle(new Each,Class>>() {\n\n private MapBinder, TypeHandler> handlerBinder;\n\n public void doHandle(Entry, Class> alias) {\n if (this.handlerBinder == null) {\n this.handlerBinder =\n MapBinder.newMapBinder(binder(), new TypeLiteral>(){}, new TypeLiteral(){});\n }\n\n this.handlerBinder.addBinding(alias.getKey()).to(alias.getValue()).in(Scopes.SINGLETON);\n }\n });\n\n // interceptors plugin\n foreach(this.interceptorsClasses).handle(new Each>() {\n\n private Multibinder interceptorsMultibinder;\n\n public void doHandle(Class interceptorType) {\n if (this.interceptorsMultibinder == null) {\n this.interceptorsMultibinder = Multibinder.newSetBinder(binder(), Interceptor.class);\n }\n this.interceptorsMultibinder.addBinding().to(interceptorType).in(Scopes.SINGLETON);\n }\n });\n\n // mappers\n if (!this.mapperClasses.isEmpty()) {\n this.bind(new TypeLiteral>>() {}).annotatedWith(Mappers.class).toInstance(this.mapperClasses);\n foreach(this.mapperClasses).handle(new EachMapper(this.binder()));\n }\n }\n\n /**\n * The {@link MyBatisModule} Builder.\n *\n * By default the Builder uses the following settings:\n *
    \n *
  • DataSource Provider type: {@link UnpooledDataSourceProvider};
  • \n *
  • TransactionFactory type: org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
  • \n *
  • ObjectFactory type: org.apache.ibatis.reflection.factory.ObjectFactory.
  • \n *
\n */\n public static final class Builder {\n\n /**\n * The DataSource Provider class reference.\n */\n private Class> dataSourceProviderType = UnpooledDataSourceProvider.class;\n\n /**\n * The TransactionFactory class reference.\n */\n private Class transactionFactoryType = JdbcTransactionFactory.class;\n\n /**\n * The user defined aliases.\n */\n private final Map> aliases = new HashMap>();\n\n /**\n * The user defined type handlers.\n */\n private final Map, Class> handlers = new HashMap, Class>();\n\n /**\n * The user defined Interceptor classes.\n */\n private final Set> interceptorsClasses = new HashSet>();\n\n /**\n * The ObjectFactory Provider class reference.\n */\n private Class objectFactoryType = DefaultObjectFactory.class;\n\n /**\n * The user defined mapper classes.\n */\n private final Set> mapperClasses = new LinkedHashSet>();\n\n /**\n * Set the DataSource Provider type has to be bound.\n *\n * @param dataSourceProviderType the DataSource Provider type.\n * @return this {@code Builder} instance.\n */\n public Builder setDataSourceProviderType(Class> dataSourceProviderType) {\n if (dataSourceProviderType == null) {\n throw new IllegalArgumentException(\"Parameter 'dataSourceProviderType' must be not null\");\n }\n this.dataSourceProviderType = dataSourceProviderType;\n return this;\n }\n\n /**\n * Set the TransactionFactory type has to be bound.\n *\n * @param transactionFactoryType the TransactionFactory type.\n * @return this {@code Builder} instance.\n */\n public Builder setTransactionFactoryType(Class transactionFactoryType) {\n if (transactionFactoryType == null) {\n throw new IllegalArgumentException(\"Parameter 'transactionFactoryType' must be not null\");\n }\n this.transactionFactoryType = transactionFactoryType;\n return this;\n }\n\n /**\n * Adding simple aliases means that every specified class will be bound\n * using the simple class name, i.e. {@code com.acme.Foo} becomes {@code Foo}.\n *\n * @param types the specified types have to be bind.\n * @return this {@code Builder} instance.\n */\n public Builder addSimpleAliases(final Class...types) {\n if (types != null) {\n return this.addSimpleAliases(Arrays.asList(types));\n }\n return this;\n }\n\n /**\n * Adding simple aliases means that every specified class will be bound\n * using the simple class name, i.e. {@code com.acme.Foo} becomes {@code Foo}.\n *\n * @param types the specified types have to be bind.\n * @return this {@code Builder} instance.\n */\n public Builder addSimpleAliases(final Collection> types) {\n foreach(types).handle(new Each>() {\n public void doHandle(Class clazz) {\n addAlias(clazz.getSimpleName(), clazz);\n }\n });\n return this;\n }\n\n /**\n * Adds all Classes in the given package as a simple alias.\n * Adding simple aliases means that every specified class will be bound\n * using the simple class name, i.e. {@code com.acme.Foo} becomes {@code Foo}.\n *\n * @param packageName the specified package to search for classes to alias.\n * @return this {@code Builder} instance.\n */\n public Builder addSimpleAliases(final String packageName) {\n return this.addSimpleAliases(getClasses(packageName));\n }\n\n /**\n * Adds all Classes in the given package as a simple alias.\n * Adding simple aliases means that every specified class will be bound\n * using the simple class name, i.e. {@code com.acme.Foo} becomes {@code Foo}.\n *\n * @param packageName the specified package to search for classes to alias.\n * @param test a test to run against the objects found in the specified package.\n * @return this {@code Builder} instance.\n */\n public Builder addSimpleAliases(final String packageName, final ResolverUtil.Test test) {\n return this.addSimpleAliases(getClasses(test, packageName));\n }\n\n /**\n * Add a user defined binding.\n *\n * @param alias the string type alias\n * @param clazz the type has to be bound.\n */\n public Builder addAlias(final String alias, final Class clazz) {\n this.aliases.put(alias, clazz);\n return this;\n }\n\n /**\n * Add a user defined Type Handler letting google-guice creating it.\n *\n * @param type the specified type has to be handled.\n * @param handler the handler type.\n * @return this {@code Builder} instance.\n */\n public Builder addTypeHandler(final Class type, final Class handler) {\n this.handlers.put(type, handler);\n return this;\n }\n\n /**\n * Adds the user defined myBatis interceptors plugins types, letting\n * google-guice creating them.\n *\n * @param interceptorsClasses the user defined MyBatis interceptors plugins types.\n * @return this {@code Builder} instance.\n * \n */\n public Builder addInterceptorsClasses(Class...interceptorsClasses) {\n if (interceptorsClasses != null) {\n return this.addInterceptorsClasses(Arrays.asList(interceptorsClasses));\n }\n return this;\n }\n\n /**\n * Adds the user defined MyBatis interceptors plugins types, letting\n * google-guice creating them.\n *\n * @param interceptorsClasses the user defined MyBatis Interceptors plugins types.\n * @return this {@code Builder} instance.\n * \n */\n public Builder addInterceptorsClasses(Collection> interceptorsClasses) {\n if (interceptorsClasses != null) {\n this.interceptorsClasses.addAll(interceptorsClasses);\n }\n return this;\n }\n\n /**\n * Adds the user defined MyBatis interceptors plugins types in the given package,\n * letting google-guice creating them.\n *\n * @param packageName the package where looking for Interceptors plugins types.\n * @return this {@code Builder} instance.\n */\n public Builder addInterceptorsClasses(String packageName) {\n if (packageName == null) {\n throw new IllegalArgumentException(\"Parameter 'packageName' must be not null\");\n }\n return this.addInterceptorsClasses(new ResolverUtil()\n .find(new ResolverUtil.IsA(Interceptor.class), packageName)\n .getClasses());\n }\n\n /**\n * Sets the ObjectFactory class.\n *\n * @param objectFactoryType the ObjectFactory type.\n * @return this {@code Builder} instance.\n */\n public Builder setObjectFactoryType(Class objectFactoryType) {\n if (objectFactoryType == null) {\n throw new IllegalArgumentException(\"Parameter 'objectFactoryType' must be not null\");\n }\n this.objectFactoryType = objectFactoryType;\n return this;\n }\n\n /**\n * Adds the user defined mapper classes.\n *\n * @param mapperClasses the user defined mapper classes.\n * @return this {@code Builder} instance.\n * \n */\n public Builder addMapperClasses(Class...mapperClasses) {\n if (mapperClasses != null) {\n return this.addMapperClasses(Arrays.asList(mapperClasses));\n }\n return this;\n }\n\n /**\n * Adds the user defined mapper classes.\n *\n * @param mapperClasses the user defined mapper classes.\n * @return this {@code Builder} instance.\n * \n */\n public Builder addMapperClasses(Collection> mapperClasses) {\n if (mapperClasses != null) {\n this.mapperClasses.addAll(mapperClasses);\n }\n return this;\n }\n\n /**\n * Adds the user defined mapper classes.\n *\n * @param packageName the specified package to search for mappers to add.\n * @return this {@code Builder} instance.\n * \n */\n public Builder addMapperClasses(final String packageName) {\n return this.addMapperClasses(getClasses(packageName));\n }\n\n /**\n * Adds the user defined mapper classes.\n *\n * @param packageName the specified package to search for mappers to add.\n * @param test a test to run against the objects found in the specified package.\n * @return this {@code Builder} instance.\n * \n */\n public Builder addMapperClasses(final String packageName, final ResolverUtil.Test test) {\n return this.addMapperClasses(getClasses(test, packageName));\n }\n\n /**\n * Create a new {@link MyBatisModule} instance based on this {@link Builder}\n * instance configuration.\n *\n * @return a new {@link MyBatisModule} instance.\n */\n public Module create() {\n return new MyBatisModule(this.dataSourceProviderType,\n this.transactionFactoryType,\n this.aliases,\n this.handlers,\n this.interceptorsClasses,\n this.objectFactoryType,\n this.mapperClasses);\n }\n\n /**\n * Return a set of all classes contained in the given package.\n *\n * @param packageName the package has to be analyzed.\n * @return a set of all classes contained in the given package.\n */\n private static Set> getClasses(String packageName) {\n return getClasses(new ResolverUtil.IsA(Object.class), packageName);\n }\n\n /**\n * Return a set of all classes contained in the given package that match with\n * the given test requirement.\n *\n * @param test the class filter on the given package.\n * @param packageName the package has to be analyzed.\n * @return a set of all classes contained in the given package.\n */\n private static Set> getClasses(ResolverUtil.Test test, String packageName) {\n if (test == null) {\n throw new IllegalArgumentException(\"Parameter 'test' must be not null\");\n }\n if (packageName == null) {\n throw new IllegalArgumentException(\"Parameter 'packageName' must be not null\");\n }\n return new ResolverUtil().find(test, packageName).getClasses();\n }\n\n }\n\n}\n"},"message":{"kind":"string","value":"added missing SqlSessionFactory singleton scope in binding\n"},"old_file":{"kind":"string","value":"src/main/java/org/mybatis/guice/MyBatisModule.java"},"subject":{"kind":"string","value":"added missing SqlSessionFactory singleton scope in binding"},"git_diff":{"kind":"string","value":"rc/main/java/org/mybatis/guice/MyBatisModule.java\n this.bind(Environment.class).toProvider(EnvironmentProvider.class).in(Scopes.SINGLETON);\n this.bind(Configuration.class).toProvider(ConfigurationProvider.class).in(Scopes.SINGLETON);\n this.bind(ObjectFactory.class).to(this.objectFactoryType).in(Scopes.SINGLETON);\n this.bind(SqlSessionFactory.class).toProvider(SqlSessionFactoryProvider.class);\n this.bind(SqlSessionFactory.class).toProvider(SqlSessionFactoryProvider.class).in(Scopes.SINGLETON);\n \n // optional bindings\n "}}},{"rowIdx":882,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"1074426a3acc154ed3c20e1f9c385bd696a83d15"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community"},"new_contents":{"kind":"string","value":"// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.\n\npackage com.intellij.codeInsight.daemon.impl;\n\nimport com.intellij.codeInsight.daemon.GutterMark;\nimport com.intellij.lang.annotation.HighlightSeverity;\nimport com.intellij.openapi.application.ApplicationManager;\nimport com.intellij.openapi.editor.Document;\nimport com.intellij.openapi.editor.RangeMarker;\nimport com.intellij.openapi.editor.colors.EditorColorsScheme;\nimport com.intellij.openapi.editor.event.DocumentEvent;\nimport com.intellij.openapi.editor.ex.DocumentEx;\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.impl.RedBlackTree;\nimport com.intellij.openapi.editor.impl.SweepProcessor;\nimport com.intellij.openapi.editor.markup.*;\nimport com.intellij.openapi.project.Project;\nimport com.intellij.openapi.util.*;\nimport com.intellij.psi.PsiDocumentManager;\nimport com.intellij.psi.PsiFile;\nimport com.intellij.util.Consumer;\nimport com.intellij.util.Processor;\nimport com.intellij.util.containers.ContainerUtil;\nimport gnu.trove.THashMap;\nimport gnu.trove.THashSet;\nimport org.jetbrains.annotations.NotNull;\nimport org.jetbrains.annotations.Nullable;\n\nimport java.awt.*;\nimport java.util.*;\nimport java.util.List;\n\npublic class UpdateHighlightersUtil {\n private static final Comparator BY_START_OFFSET_NODUPS = (o1, o2) -> {\n int d = o1.getActualStartOffset() - o2.getActualStartOffset();\n if (d != 0) return d;\n d = o1.getActualEndOffset() - o2.getActualEndOffset();\n if (d != 0) return d;\n\n d = Comparing.compare(o1.getSeverity(), o2.getSeverity());\n if (d != 0) return -d; // higher severity first, to prevent warnings overlap errors\n\n if (!Comparing.equal(o1.type, o2.type)) {\n return String.valueOf(o1.type).compareTo(String.valueOf(o2.type));\n }\n\n if (!Comparing.equal(o1.getGutterIconRenderer(), o2.getGutterIconRenderer())) {\n return String.valueOf(o1.getGutterIconRenderer()).compareTo(String.valueOf(o2.getGutterIconRenderer()));\n }\n\n if (!Comparing.equal(o1.forcedTextAttributes, o2.forcedTextAttributes)) {\n return String.valueOf(o1.getGutterIconRenderer()).compareTo(String.valueOf(o2.getGutterIconRenderer()));\n }\n\n if (!Comparing.equal(o1.forcedTextAttributesKey, o2.forcedTextAttributesKey)) {\n return String.valueOf(o1.getGutterIconRenderer()).compareTo(String.valueOf(o2.getGutterIconRenderer()));\n }\n\n return Comparing.compare(o1.getDescription(), o2.getDescription());\n };\n\n private static boolean isCoveredByOffsets(HighlightInfo info, HighlightInfo coveredBy) {\n return coveredBy.startOffset <= info.startOffset && info.endOffset <= coveredBy.endOffset && info.getGutterIconRenderer() == null;\n }\n\n static void addHighlighterToEditorIncrementally(@NotNull Project project,\n @NotNull Document document,\n @NotNull PsiFile file,\n int startOffset,\n int endOffset,\n @NotNull final HighlightInfo info,\n @Nullable final EditorColorsScheme colorsScheme, // if null global scheme will be used\n final int group,\n @NotNull Map ranges2markersCache) {\n ApplicationManager.getApplication().assertIsDispatchThread();\n if (isFileLevelOrGutterAnnotation(info)) return;\n if (info.getStartOffset() < startOffset || info.getEndOffset() > endOffset) return;\n\n MarkupModel markup = DocumentMarkupModel.forDocument(document, project, true);\n final SeverityRegistrar severityRegistrar = SeverityRegistrar.getSeverityRegistrar(project);\n final boolean myInfoIsError = isSevere(info, severityRegistrar);\n Processor otherHighlightInTheWayProcessor = oldInfo -> {\n if (!myInfoIsError && isCovered(info, severityRegistrar, oldInfo)) {\n return false;\n }\n\n return oldInfo.getGroup() != group || !oldInfo.equalsByActualOffset(info);\n };\n boolean allIsClear = DaemonCodeAnalyzerEx.processHighlights(document, project,\n null, info.getActualStartOffset(), info.getActualEndOffset(),\n otherHighlightInTheWayProcessor);\n if (allIsClear) {\n createOrReuseHighlighterFor(info, colorsScheme, document, group, file, (MarkupModelEx)markup, null, ranges2markersCache, severityRegistrar);\n\n clearWhiteSpaceOptimizationFlag(document);\n assertMarkupConsistent(markup, project);\n }\n }\n\n public static boolean isFileLevelOrGutterAnnotation(HighlightInfo info) {\n return info.isFileLevelAnnotation() || info.getGutterIconRenderer() != null;\n }\n\n public static void setHighlightersToEditor(@NotNull Project project,\n @NotNull Document document,\n int startOffset,\n int endOffset,\n @NotNull Collection highlights,\n @Nullable final EditorColorsScheme colorsScheme, // if null global scheme will be used\n int group) {\n TextRange range = new TextRange(startOffset, endOffset);\n ApplicationManager.getApplication().assertIsDispatchThread();\n\n PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document);\n final DaemonCodeAnalyzerEx codeAnalyzer = DaemonCodeAnalyzerEx.getInstanceEx(project);\n codeAnalyzer.cleanFileLevelHighlights(project, group, psiFile);\n\n MarkupModel markup = DocumentMarkupModel.forDocument(document, project, true);\n assertMarkupConsistent(markup, project);\n\n setHighlightersInRange(project, document, range, colorsScheme, new ArrayList<>(highlights), (MarkupModelEx)markup, group);\n }\n\n // set highlights inside startOffset,endOffset but outside priorityRange\n static void setHighlightersOutsideRange(@NotNull final Project project,\n @NotNull final Document document,\n @NotNull final PsiFile psiFile,\n @NotNull final List infos,\n @Nullable final EditorColorsScheme colorsScheme,\n // if null global scheme will be used\n final int startOffset,\n final int endOffset,\n @NotNull final ProperTextRange priorityRange,\n final int group) {\n ApplicationManager.getApplication().assertIsDispatchThread();\n\n final DaemonCodeAnalyzerEx codeAnalyzer = DaemonCodeAnalyzerEx.getInstanceEx(project);\n if (startOffset == 0 && endOffset == document.getTextLength()) {\n codeAnalyzer.cleanFileLevelHighlights(project, group, psiFile);\n }\n\n final MarkupModel markup = DocumentMarkupModel.forDocument(document, project, true);\n assertMarkupConsistent(markup, project);\n\n final SeverityRegistrar severityRegistrar = SeverityRegistrar.getSeverityRegistrar(project);\n final HighlightersRecycler infosToRemove = new HighlightersRecycler();\n ContainerUtil.quickSort(infos, BY_START_OFFSET_NODUPS);\n Set infoSet = new THashSet<>(infos);\n\n Processor processor = info -> {\n if (info.getGroup() == group) {\n RangeHighlighter highlighter = info.getHighlighter();\n int hiStart = highlighter.getStartOffset();\n int hiEnd = highlighter.getEndOffset();\n if (!info.isFromInjection() && hiEnd < document.getTextLength() && (hiEnd != 0 && hiEnd <= startOffset || hiStart >= endOffset)) {\n return true; // injections are oblivious to restricting range\n }\n boolean toRemove = infoSet.contains(info) ||\n !priorityRange.containsRange(hiStart, hiEnd) &&\n (hiEnd != document.getTextLength() || priorityRange.getEndOffset() != document.getTextLength());\n if (toRemove) {\n infosToRemove.recycleHighlighter(highlighter);\n info.setHighlighter(null);\n }\n }\n return true;\n };\n DaemonCodeAnalyzerEx.processHighlightsOverlappingOutside(document, project, null, priorityRange.getStartOffset(), priorityRange.getEndOffset(), processor);\n\n final Map ranges2markersCache = new THashMap<>(10);\n final boolean[] changed = {false};\n SweepProcessor.Generator generator = proc -> ContainerUtil.process(infos, proc);\n SweepProcessor.sweep(generator, (offset, info, atStart, overlappingIntervals) -> {\n if (!atStart) return true;\n if (!info.isFromInjection() && info.getEndOffset() < document.getTextLength() && (info.getEndOffset() <= startOffset || info.getStartOffset()>=endOffset)) return true; // injections are oblivious to restricting range\n\n if (info.isFileLevelAnnotation()) {\n codeAnalyzer.addFileLevelHighlight(project, group, info, psiFile);\n changed[0] = true;\n return true;\n }\n if (isWarningCoveredByError(info, overlappingIntervals, severityRegistrar)) {\n return true;\n }\n if (info.getStartOffset() < priorityRange.getStartOffset() || info.getEndOffset() > priorityRange.getEndOffset()) {\n createOrReuseHighlighterFor(info, colorsScheme, document, group, psiFile, (MarkupModelEx)markup, infosToRemove,\n ranges2markersCache, severityRegistrar);\n changed[0] = true;\n }\n return true;\n });\n for (RangeHighlighter highlighter : infosToRemove.forAllInGarbageBin()) {\n highlighter.dispose();\n changed[0] = true;\n }\n\n if (changed[0]) {\n clearWhiteSpaceOptimizationFlag(document);\n }\n assertMarkupConsistent(markup, project);\n }\n\n static void setHighlightersInRange(@NotNull final Project project,\n @NotNull final Document document,\n @NotNull final TextRange range,\n @Nullable final EditorColorsScheme colorsScheme, // if null global scheme will be used\n @NotNull final List infos,\n @NotNull final MarkupModelEx markup,\n final int group) {\n ApplicationManager.getApplication().assertIsDispatchThread();\n\n final SeverityRegistrar severityRegistrar = SeverityRegistrar.getSeverityRegistrar(project);\n final HighlightersRecycler infosToRemove = new HighlightersRecycler();\n DaemonCodeAnalyzerEx.processHighlights(document, project, null, range.getStartOffset(), range.getEndOffset(), info -> {\n if (info.getGroup() == group) {\n RangeHighlighter highlighter = info.getHighlighter();\n int hiStart = highlighter.getStartOffset();\n int hiEnd = highlighter.getEndOffset();\n boolean willBeRemoved = hiEnd == document.getTextLength() && range.getEndOffset() == document.getTextLength()\n /*|| range.intersectsStrict(hiStart, hiEnd)*/ || range.containsRange(hiStart, hiEnd) /*|| hiStart <= range.getStartOffset() && hiEnd >= range.getEndOffset()*/;\n if (willBeRemoved) {\n infosToRemove.recycleHighlighter(highlighter);\n info.setHighlighter(null);\n }\n }\n return true;\n });\n\n ContainerUtil.quickSort(infos, BY_START_OFFSET_NODUPS);\n final Map ranges2markersCache = new THashMap<>(10);\n final PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document);\n final DaemonCodeAnalyzerEx codeAnalyzer = DaemonCodeAnalyzerEx.getInstanceEx(project);\n final boolean[] changed = {false};\n SweepProcessor.Generator generator = (Processor processor) -> ContainerUtil.process(infos, processor);\n SweepProcessor.sweep(generator, (offset, info, atStart, overlappingIntervals) -> {\n if (!atStart) {\n return true;\n }\n if (info.isFileLevelAnnotation() && psiFile != null && psiFile.getViewProvider().isPhysical()) {\n codeAnalyzer.addFileLevelHighlight(project, group, info, psiFile);\n changed[0] = true;\n return true;\n }\n if (isWarningCoveredByError(info, overlappingIntervals, severityRegistrar)) {\n return true;\n }\n if (info.getStartOffset() >= range.getStartOffset() && info.getEndOffset() <= range.getEndOffset() && psiFile != null) {\n createOrReuseHighlighterFor(info, colorsScheme, document, group, psiFile, markup, infosToRemove, ranges2markersCache, severityRegistrar);\n changed[0] = true;\n }\n return true;\n });\n for (RangeHighlighter highlighter : infosToRemove.forAllInGarbageBin()) {\n highlighter.dispose();\n changed[0] = true;\n }\n\n if (changed[0]) {\n clearWhiteSpaceOptimizationFlag(document);\n }\n assertMarkupConsistent(markup, project);\n }\n\n private static boolean isWarningCoveredByError(@NotNull HighlightInfo info,\n @NotNull Collection overlappingIntervals,\n @NotNull SeverityRegistrar severityRegistrar) {\n if (!isSevere(info, severityRegistrar)) {\n for (HighlightInfo overlapping : overlappingIntervals) {\n if (isCovered(info, severityRegistrar, overlapping)) return true;\n }\n }\n return false;\n }\n\n private static boolean isCovered(@NotNull HighlightInfo warning, @NotNull SeverityRegistrar severityRegistrar, @NotNull HighlightInfo candidate) {\n if (!isCoveredByOffsets(warning, candidate)) return false;\n HighlightSeverity severity = candidate.getSeverity();\n if (severity == HighlightInfoType.SYMBOL_TYPE_SEVERITY) return false; // syntax should not interfere with warnings\n return isSevere(candidate, severityRegistrar);\n }\n\n private static boolean isSevere(@NotNull HighlightInfo info, @NotNull SeverityRegistrar severityRegistrar) {\n HighlightSeverity severity = info.getSeverity();\n return severityRegistrar.compare(HighlightSeverity.ERROR, severity) <= 0 || severity == HighlightInfoType.SYMBOL_TYPE_SEVERITY;\n }\n\n private static void createOrReuseHighlighterFor(@NotNull final HighlightInfo info,\n @Nullable final EditorColorsScheme colorsScheme, // if null global scheme will be used\n @NotNull final Document document,\n final int group,\n @NotNull final PsiFile psiFile,\n @NotNull MarkupModelEx markup,\n @Nullable HighlightersRecycler infosToRemove,\n @NotNull final Map ranges2markersCache,\n @NotNull SeverityRegistrar severityRegistrar) {\n int infoStartOffset = info.startOffset;\n int infoEndOffset = info.endOffset;\n\n final int docLength = document.getTextLength();\n if (infoEndOffset > docLength) {\n infoEndOffset = docLength;\n infoStartOffset = Math.min(infoStartOffset, infoEndOffset);\n }\n if (infoEndOffset == infoStartOffset && !info.isAfterEndOfLine()) {\n if (infoEndOffset == docLength) return; // empty highlighter beyond file boundaries\n infoEndOffset++; //show something in case of empty highlightinfo\n }\n\n info.setGroup(group);\n\n int layer = getLayer(info, severityRegistrar);\n RangeHighlighterEx highlighter = infosToRemove == null ? null : (RangeHighlighterEx)infosToRemove.pickupHighlighterFromGarbageBin(infoStartOffset, infoEndOffset, layer);\n\n final TextRange finalInfoRange = new TextRange(infoStartOffset, infoEndOffset);\n final TextAttributes infoAttributes = info.getTextAttributes(psiFile, colorsScheme);\n Consumer changeAttributes = finalHighlighter -> {\n if (infoAttributes != null) {\n finalHighlighter.setTextAttributes(infoAttributes);\n }\n\n info.setHighlighter(finalHighlighter);\n finalHighlighter.setAfterEndOfLine(info.isAfterEndOfLine());\n\n Color color = info.getErrorStripeMarkColor(psiFile, colorsScheme);\n finalHighlighter.setErrorStripeMarkColor(color);\n if (info != finalHighlighter.getErrorStripeTooltip()) {\n finalHighlighter.setErrorStripeTooltip(info);\n }\n GutterMark renderer = info.getGutterIconRenderer();\n finalHighlighter.setGutterIconRenderer((GutterIconRenderer)renderer);\n\n ranges2markersCache.put(finalInfoRange, info.getHighlighter());\n if (info.quickFixActionRanges != null) {\n List> list =\n new ArrayList<>(info.quickFixActionRanges.size());\n for (Pair pair : info.quickFixActionRanges) {\n TextRange textRange = pair.second;\n RangeMarker marker = getOrCreate(document, ranges2markersCache, textRange);\n list.add(Pair.create(pair.first, marker));\n }\n info.quickFixActionMarkers = ContainerUtil.createLockFreeCopyOnWriteList(list);\n }\n ProperTextRange fixRange = info.getFixTextRange();\n if (finalInfoRange.equals(fixRange)) {\n info.fixMarker = null; // null means it the same as highlighter'\n }\n else {\n info.fixMarker = getOrCreate(document, ranges2markersCache, fixRange);\n }\n };\n\n if (highlighter == null) {\n highlighter = markup.addRangeHighlighterAndChangeAttributes(infoStartOffset, infoEndOffset, layer, null,\n HighlighterTargetArea.EXACT_RANGE, false, changeAttributes);\n if (HighlightInfoType.VISIBLE_IF_FOLDED.contains(info.type)) {\n highlighter.setVisibleIfFolded(true);\n }\n }\n else {\n markup.changeAttributesInBatch(highlighter, changeAttributes);\n }\n\n if (infoAttributes != null) {\n boolean attributesSet = Comparing.equal(infoAttributes, highlighter.getTextAttributes());\n assert attributesSet : \"Info: \" + infoAttributes +\n \"; colorsScheme: \" + (colorsScheme == null ? \"[global]\" : colorsScheme.getName()) +\n \"; highlighter:\" + highlighter.getTextAttributes();\n }\n }\n\n private static int getLayer(@NotNull HighlightInfo info, @NotNull SeverityRegistrar severityRegistrar) {\n final HighlightSeverity severity = info.getSeverity();\n int layer;\n if (severity == HighlightSeverity.WARNING) {\n layer = HighlighterLayer.WARNING;\n }\n else if (severity == HighlightSeverity.WEAK_WARNING) {\n layer = HighlighterLayer.WEAK_WARNING;\n }\n else if (severityRegistrar.compare(severity, HighlightSeverity.ERROR) >= 0) {\n layer = HighlighterLayer.ERROR;\n }\n else if (severity == HighlightInfoType.INJECTED_FRAGMENT_SEVERITY) {\n layer = HighlighterLayer.CARET_ROW-1;\n }\n else if (severity == HighlightInfoType.ELEMENT_UNDER_CARET_SEVERITY) {\n layer = HighlighterLayer.ELEMENT_UNDER_CARET;\n }\n else {\n layer = HighlighterLayer.ADDITIONAL_SYNTAX;\n }\n return layer;\n }\n\n @NotNull\n private static RangeMarker getOrCreate(@NotNull Document document, @NotNull Map ranges2markersCache, @NotNull TextRange textRange) {\n return ranges2markersCache.computeIfAbsent(textRange, __ -> document.createRangeMarker(textRange));\n }\n\n private static final Key TYPING_INSIDE_HIGHLIGHTER_OCCURRED = Key.create(\"TYPING_INSIDE_HIGHLIGHTER_OCCURRED\");\n static boolean isWhitespaceOptimizationAllowed(@NotNull Document document) {\n return document.getUserData(TYPING_INSIDE_HIGHLIGHTER_OCCURRED) == null;\n }\n private static void disableWhiteSpaceOptimization(@NotNull Document document) {\n document.putUserData(TYPING_INSIDE_HIGHLIGHTER_OCCURRED, Boolean.TRUE);\n }\n private static void clearWhiteSpaceOptimizationFlag(@NotNull Document document) {\n document.putUserData(TYPING_INSIDE_HIGHLIGHTER_OCCURRED, null);\n }\n\n static void updateHighlightersByTyping(@NotNull Project project, @NotNull DocumentEvent e) {\n ApplicationManager.getApplication().assertIsDispatchThread();\n\n final Document document = e.getDocument();\n if (document instanceof DocumentEx && ((DocumentEx)document).isInBulkUpdate()) return;\n\n final MarkupModel markup = DocumentMarkupModel.forDocument(document, project, true);\n assertMarkupConsistent(markup, project);\n\n final int start = e.getOffset() - 1;\n final int end = start + e.getOldLength();\n\n final List toRemove = new ArrayList<>();\n DaemonCodeAnalyzerEx.processHighlights(document, project, null, start, end, info -> {\n if (!info.needUpdateOnTyping()) return true;\n\n RangeHighlighter highlighter = info.getHighlighter();\n int highlighterStart = highlighter.getStartOffset();\n int highlighterEnd = highlighter.getEndOffset();\n if (info.isAfterEndOfLine()) {\n if (highlighterStart < document.getTextLength()) {\n highlighterStart += 1;\n }\n if (highlighterEnd < document.getTextLength()) {\n highlighterEnd += 1;\n }\n }\n if (!highlighter.isValid() || start < highlighterEnd && highlighterStart <= end) {\n toRemove.add(info);\n }\n return true;\n });\n\n for (HighlightInfo info : toRemove) {\n if (!info.getHighlighter().isValid() || info.type.equals(HighlightInfoType.WRONG_REF)) {\n info.getHighlighter().dispose();\n }\n }\n\n assertMarkupConsistent(markup, project);\n\n if (!toRemove.isEmpty()) {\n disableWhiteSpaceOptimization(document);\n }\n }\n\n private static void assertMarkupConsistent(@NotNull final MarkupModel markup, @NotNull Project project) {\n if (!RedBlackTree.VERIFY) {\n return;\n }\n Document document = markup.getDocument();\n DaemonCodeAnalyzerEx.processHighlights(document, project, null, 0, document.getTextLength(), info -> {\n assert ((MarkupModelEx)markup).containsHighlighter(info.getHighlighter());\n return true;\n });\n RangeHighlighter[] allHighlighters = markup.getAllHighlighters();\n for (RangeHighlighter highlighter : allHighlighters) {\n if (!highlighter.isValid()) continue;\n HighlightInfo info = HighlightInfo.fromRangeHighlighter(highlighter);\n if (info == null) continue;\n boolean contains = !DaemonCodeAnalyzerEx\n .processHighlights(document, project, null, info.getActualStartOffset(), info.getActualEndOffset(),\n highlightInfo -> BY_START_OFFSET_NODUPS.compare(highlightInfo, info) != 0);\n assert contains: info;\n }\n }\n}\n"},"new_file":{"kind":"string","value":"platform/analysis-impl/src/com/intellij/codeInsight/daemon/impl/UpdateHighlightersUtil.java"},"old_contents":{"kind":"string","value":"// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.\n\npackage com.intellij.codeInsight.daemon.impl;\n\nimport com.intellij.codeInsight.daemon.GutterMark;\nimport com.intellij.lang.annotation.HighlightSeverity;\nimport com.intellij.openapi.application.ApplicationManager;\nimport com.intellij.openapi.editor.Document;\nimport com.intellij.openapi.editor.RangeMarker;\nimport com.intellij.openapi.editor.colors.EditorColorsScheme;\nimport com.intellij.openapi.editor.event.DocumentEvent;\nimport com.intellij.openapi.editor.ex.DocumentEx;\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.impl.RedBlackTree;\nimport com.intellij.openapi.editor.impl.SweepProcessor;\nimport com.intellij.openapi.editor.markup.*;\nimport com.intellij.openapi.project.Project;\nimport com.intellij.openapi.util.*;\nimport com.intellij.psi.PsiDocumentManager;\nimport com.intellij.psi.PsiFile;\nimport com.intellij.util.Consumer;\nimport com.intellij.util.Processor;\nimport com.intellij.util.containers.ContainerUtil;\nimport gnu.trove.THashMap;\nimport gnu.trove.THashSet;\nimport org.jetbrains.annotations.NotNull;\nimport org.jetbrains.annotations.Nullable;\n\nimport java.awt.*;\nimport java.util.*;\nimport java.util.List;\n\npublic class UpdateHighlightersUtil {\n private static final Comparator BY_START_OFFSET_NODUPS = (o1, o2) -> {\n int d = o1.getActualStartOffset() - o2.getActualStartOffset();\n if (d != 0) return d;\n d = o1.getActualEndOffset() - o2.getActualEndOffset();\n if (d != 0) return d;\n\n d = Comparing.compare(o1.getSeverity(), o2.getSeverity());\n if (d != 0) return -d; // higher severity first, to prevent warnings overlap errors\n\n if (!Comparing.equal(o1.type, o2.type)) {\n return String.valueOf(o1.type).compareTo(String.valueOf(o2.type));\n }\n\n if (!Comparing.equal(o1.getGutterIconRenderer(), o2.getGutterIconRenderer())) {\n return String.valueOf(o1.getGutterIconRenderer()).compareTo(String.valueOf(o2.getGutterIconRenderer()));\n }\n\n if (!Comparing.equal(o1.forcedTextAttributes, o2.forcedTextAttributes)) {\n return String.valueOf(o1.getGutterIconRenderer()).compareTo(String.valueOf(o2.getGutterIconRenderer()));\n }\n\n if (!Comparing.equal(o1.forcedTextAttributesKey, o2.forcedTextAttributesKey)) {\n return String.valueOf(o1.getGutterIconRenderer()).compareTo(String.valueOf(o2.getGutterIconRenderer()));\n }\n\n return Comparing.compare(o1.getDescription(), o2.getDescription());\n };\n\n private static boolean isCoveredByOffsets(HighlightInfo info, HighlightInfo coveredBy) {\n return coveredBy.startOffset <= info.startOffset && info.endOffset <= coveredBy.endOffset && info.getGutterIconRenderer() == null;\n }\n\n static void addHighlighterToEditorIncrementally(@NotNull Project project,\n @NotNull Document document,\n @NotNull PsiFile file,\n int startOffset,\n int endOffset,\n @NotNull final HighlightInfo info,\n @Nullable final EditorColorsScheme colorsScheme, // if null global scheme will be used\n final int group,\n @NotNull Map ranges2markersCache) {\n ApplicationManager.getApplication().assertIsDispatchThread();\n if (isFileLevelOrGutterAnnotation(info)) return;\n if (info.getStartOffset() < startOffset || info.getEndOffset() > endOffset) return;\n\n MarkupModel markup = DocumentMarkupModel.forDocument(document, project, true);\n final SeverityRegistrar severityRegistrar = SeverityRegistrar.getSeverityRegistrar(project);\n final boolean myInfoIsError = isSevere(info, severityRegistrar);\n Processor otherHighlightInTheWayProcessor = oldInfo -> {\n if (!myInfoIsError && isCovered(info, severityRegistrar, oldInfo)) {\n return false;\n }\n\n return oldInfo.getGroup() != group || !oldInfo.equalsByActualOffset(info);\n };\n boolean allIsClear = DaemonCodeAnalyzerEx.processHighlights(document, project,\n null, info.getActualStartOffset(), info.getActualEndOffset(),\n otherHighlightInTheWayProcessor);\n if (allIsClear) {\n createOrReuseHighlighterFor(info, colorsScheme, document, group, file, (MarkupModelEx)markup, null, ranges2markersCache, severityRegistrar);\n\n clearWhiteSpaceOptimizationFlag(document);\n assertMarkupConsistent(markup, project);\n }\n }\n\n public static boolean isFileLevelOrGutterAnnotation(HighlightInfo info) {\n return info.isFileLevelAnnotation() || info.getGutterIconRenderer() != null;\n }\n\n public static void setHighlightersToEditor(@NotNull Project project,\n @NotNull Document document,\n int startOffset,\n int endOffset,\n @NotNull Collection highlights,\n @Nullable final EditorColorsScheme colorsScheme, // if null global scheme will be used\n int group) {\n TextRange range = new TextRange(startOffset, endOffset);\n ApplicationManager.getApplication().assertIsDispatchThread();\n\n PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document);\n final DaemonCodeAnalyzerEx codeAnalyzer = DaemonCodeAnalyzerEx.getInstanceEx(project);\n codeAnalyzer.cleanFileLevelHighlights(project, group, psiFile);\n\n MarkupModel markup = DocumentMarkupModel.forDocument(document, project, true);\n assertMarkupConsistent(markup, project);\n\n setHighlightersInRange(project, document, range, colorsScheme, new ArrayList<>(highlights), (MarkupModelEx)markup, group);\n }\n\n // set highlights inside startOffset,endOffset but outside priorityRange\n static void setHighlightersOutsideRange(@NotNull final Project project,\n @NotNull final Document document,\n @NotNull final PsiFile psiFile,\n @NotNull final List infos,\n @Nullable final EditorColorsScheme colorsScheme,\n // if null global scheme will be used\n final int startOffset,\n final int endOffset,\n @NotNull final ProperTextRange priorityRange,\n final int group) {\n ApplicationManager.getApplication().assertIsDispatchThread();\n\n final DaemonCodeAnalyzerEx codeAnalyzer = DaemonCodeAnalyzerEx.getInstanceEx(project);\n if (startOffset == 0 && endOffset == document.getTextLength()) {\n codeAnalyzer.cleanFileLevelHighlights(project, group, psiFile);\n }\n\n final MarkupModel markup = DocumentMarkupModel.forDocument(document, project, true);\n assertMarkupConsistent(markup, project);\n\n final SeverityRegistrar severityRegistrar = SeverityRegistrar.getSeverityRegistrar(project);\n final HighlightersRecycler infosToRemove = new HighlightersRecycler();\n ContainerUtil.quickSort(infos, BY_START_OFFSET_NODUPS);\n Set infoSet = new THashSet<>(infos);\n\n Processor processor = info -> {\n if (info.getGroup() == group) {\n RangeHighlighter highlighter = info.getHighlighter();\n int hiStart = highlighter.getStartOffset();\n int hiEnd = highlighter.getEndOffset();\n if (!info.isFromInjection() && hiEnd < document.getTextLength() && (hiEnd <= startOffset || hiStart >= endOffset)) {\n return true; // injections are oblivious to restricting range\n }\n boolean toRemove = infoSet.contains(info) ||\n !priorityRange.containsRange(hiStart, hiEnd) &&\n (hiEnd != document.getTextLength() || priorityRange.getEndOffset() != document.getTextLength());\n if (toRemove) {\n infosToRemove.recycleHighlighter(highlighter);\n info.setHighlighter(null);\n }\n }\n return true;\n };\n DaemonCodeAnalyzerEx.processHighlightsOverlappingOutside(document, project, null, priorityRange.getStartOffset(), priorityRange.getEndOffset(), processor);\n\n final Map ranges2markersCache = new THashMap<>(10);\n final boolean[] changed = {false};\n SweepProcessor.Generator generator = proc -> ContainerUtil.process(infos, proc);\n SweepProcessor.sweep(generator, (offset, info, atStart, overlappingIntervals) -> {\n if (!atStart) return true;\n if (!info.isFromInjection() && info.getEndOffset() < document.getTextLength() && (info.getEndOffset() <= startOffset || info.getStartOffset()>=endOffset)) return true; // injections are oblivious to restricting range\n\n if (info.isFileLevelAnnotation()) {\n codeAnalyzer.addFileLevelHighlight(project, group, info, psiFile);\n changed[0] = true;\n return true;\n }\n if (isWarningCoveredByError(info, overlappingIntervals, severityRegistrar)) {\n return true;\n }\n if (info.getStartOffset() < priorityRange.getStartOffset() || info.getEndOffset() > priorityRange.getEndOffset()) {\n createOrReuseHighlighterFor(info, colorsScheme, document, group, psiFile, (MarkupModelEx)markup, infosToRemove,\n ranges2markersCache, severityRegistrar);\n changed[0] = true;\n }\n return true;\n });\n for (RangeHighlighter highlighter : infosToRemove.forAllInGarbageBin()) {\n highlighter.dispose();\n changed[0] = true;\n }\n\n if (changed[0]) {\n clearWhiteSpaceOptimizationFlag(document);\n }\n assertMarkupConsistent(markup, project);\n }\n\n static void setHighlightersInRange(@NotNull final Project project,\n @NotNull final Document document,\n @NotNull final TextRange range,\n @Nullable final EditorColorsScheme colorsScheme, // if null global scheme will be used\n @NotNull final List infos,\n @NotNull final MarkupModelEx markup,\n final int group) {\n ApplicationManager.getApplication().assertIsDispatchThread();\n\n final SeverityRegistrar severityRegistrar = SeverityRegistrar.getSeverityRegistrar(project);\n final HighlightersRecycler infosToRemove = new HighlightersRecycler();\n DaemonCodeAnalyzerEx.processHighlights(document, project, null, range.getStartOffset(), range.getEndOffset(), info -> {\n if (info.getGroup() == group) {\n RangeHighlighter highlighter = info.getHighlighter();\n int hiStart = highlighter.getStartOffset();\n int hiEnd = highlighter.getEndOffset();\n boolean willBeRemoved = hiEnd == document.getTextLength() && range.getEndOffset() == document.getTextLength()\n /*|| range.intersectsStrict(hiStart, hiEnd)*/ || range.containsRange(hiStart, hiEnd) /*|| hiStart <= range.getStartOffset() && hiEnd >= range.getEndOffset()*/;\n if (willBeRemoved) {\n infosToRemove.recycleHighlighter(highlighter);\n info.setHighlighter(null);\n }\n }\n return true;\n });\n\n ContainerUtil.quickSort(infos, BY_START_OFFSET_NODUPS);\n final Map ranges2markersCache = new THashMap<>(10);\n final PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document);\n final DaemonCodeAnalyzerEx codeAnalyzer = DaemonCodeAnalyzerEx.getInstanceEx(project);\n final boolean[] changed = {false};\n SweepProcessor.Generator generator = (Processor processor) -> ContainerUtil.process(infos, processor);\n SweepProcessor.sweep(generator, (offset, info, atStart, overlappingIntervals) -> {\n if (!atStart) {\n return true;\n }\n if (info.isFileLevelAnnotation() && psiFile != null && psiFile.getViewProvider().isPhysical()) {\n codeAnalyzer.addFileLevelHighlight(project, group, info, psiFile);\n changed[0] = true;\n return true;\n }\n if (isWarningCoveredByError(info, overlappingIntervals, severityRegistrar)) {\n return true;\n }\n if (info.getStartOffset() >= range.getStartOffset() && info.getEndOffset() <= range.getEndOffset() && psiFile != null) {\n createOrReuseHighlighterFor(info, colorsScheme, document, group, psiFile, markup, infosToRemove, ranges2markersCache, severityRegistrar);\n changed[0] = true;\n }\n return true;\n });\n for (RangeHighlighter highlighter : infosToRemove.forAllInGarbageBin()) {\n highlighter.dispose();\n changed[0] = true;\n }\n\n if (changed[0]) {\n clearWhiteSpaceOptimizationFlag(document);\n }\n assertMarkupConsistent(markup, project);\n }\n\n private static boolean isWarningCoveredByError(@NotNull HighlightInfo info,\n @NotNull Collection overlappingIntervals,\n @NotNull SeverityRegistrar severityRegistrar) {\n if (!isSevere(info, severityRegistrar)) {\n for (HighlightInfo overlapping : overlappingIntervals) {\n if (isCovered(info, severityRegistrar, overlapping)) return true;\n }\n }\n return false;\n }\n\n private static boolean isCovered(@NotNull HighlightInfo warning, @NotNull SeverityRegistrar severityRegistrar, @NotNull HighlightInfo candidate) {\n if (!isCoveredByOffsets(warning, candidate)) return false;\n HighlightSeverity severity = candidate.getSeverity();\n if (severity == HighlightInfoType.SYMBOL_TYPE_SEVERITY) return false; // syntax should not interfere with warnings\n return isSevere(candidate, severityRegistrar);\n }\n\n private static boolean isSevere(@NotNull HighlightInfo info, @NotNull SeverityRegistrar severityRegistrar) {\n HighlightSeverity severity = info.getSeverity();\n return severityRegistrar.compare(HighlightSeverity.ERROR, severity) <= 0 || severity == HighlightInfoType.SYMBOL_TYPE_SEVERITY;\n }\n\n private static void createOrReuseHighlighterFor(@NotNull final HighlightInfo info,\n @Nullable final EditorColorsScheme colorsScheme, // if null global scheme will be used\n @NotNull final Document document,\n final int group,\n @NotNull final PsiFile psiFile,\n @NotNull MarkupModelEx markup,\n @Nullable HighlightersRecycler infosToRemove,\n @NotNull final Map ranges2markersCache,\n @NotNull SeverityRegistrar severityRegistrar) {\n int infoStartOffset = info.startOffset;\n int infoEndOffset = info.endOffset;\n\n final int docLength = document.getTextLength();\n if (infoEndOffset > docLength) {\n infoEndOffset = docLength;\n infoStartOffset = Math.min(infoStartOffset, infoEndOffset);\n }\n if (infoEndOffset == infoStartOffset && !info.isAfterEndOfLine()) {\n if (infoEndOffset == docLength) return; // empty highlighter beyond file boundaries\n infoEndOffset++; //show something in case of empty highlightinfo\n }\n\n info.setGroup(group);\n\n int layer = getLayer(info, severityRegistrar);\n RangeHighlighterEx highlighter = infosToRemove == null ? null : (RangeHighlighterEx)infosToRemove.pickupHighlighterFromGarbageBin(infoStartOffset, infoEndOffset, layer);\n\n final TextRange finalInfoRange = new TextRange(infoStartOffset, infoEndOffset);\n final TextAttributes infoAttributes = info.getTextAttributes(psiFile, colorsScheme);\n Consumer changeAttributes = finalHighlighter -> {\n if (infoAttributes != null) {\n finalHighlighter.setTextAttributes(infoAttributes);\n }\n\n info.setHighlighter(finalHighlighter);\n finalHighlighter.setAfterEndOfLine(info.isAfterEndOfLine());\n\n Color color = info.getErrorStripeMarkColor(psiFile, colorsScheme);\n finalHighlighter.setErrorStripeMarkColor(color);\n if (info != finalHighlighter.getErrorStripeTooltip()) {\n finalHighlighter.setErrorStripeTooltip(info);\n }\n GutterMark renderer = info.getGutterIconRenderer();\n finalHighlighter.setGutterIconRenderer((GutterIconRenderer)renderer);\n\n ranges2markersCache.put(finalInfoRange, info.getHighlighter());\n if (info.quickFixActionRanges != null) {\n List> list =\n new ArrayList<>(info.quickFixActionRanges.size());\n for (Pair pair : info.quickFixActionRanges) {\n TextRange textRange = pair.second;\n RangeMarker marker = getOrCreate(document, ranges2markersCache, textRange);\n list.add(Pair.create(pair.first, marker));\n }\n info.quickFixActionMarkers = ContainerUtil.createLockFreeCopyOnWriteList(list);\n }\n ProperTextRange fixRange = info.getFixTextRange();\n if (finalInfoRange.equals(fixRange)) {\n info.fixMarker = null; // null means it the same as highlighter'\n }\n else {\n info.fixMarker = getOrCreate(document, ranges2markersCache, fixRange);\n }\n };\n\n if (highlighter == null) {\n highlighter = markup.addRangeHighlighterAndChangeAttributes(infoStartOffset, infoEndOffset, layer, null,\n HighlighterTargetArea.EXACT_RANGE, false, changeAttributes);\n if (HighlightInfoType.VISIBLE_IF_FOLDED.contains(info.type)) {\n highlighter.setVisibleIfFolded(true);\n }\n }\n else {\n markup.changeAttributesInBatch(highlighter, changeAttributes);\n }\n\n if (infoAttributes != null) {\n boolean attributesSet = Comparing.equal(infoAttributes, highlighter.getTextAttributes());\n assert attributesSet : \"Info: \" + infoAttributes +\n \"; colorsScheme: \" + (colorsScheme == null ? \"[global]\" : colorsScheme.getName()) +\n \"; highlighter:\" + highlighter.getTextAttributes();\n }\n }\n\n private static int getLayer(@NotNull HighlightInfo info, @NotNull SeverityRegistrar severityRegistrar) {\n final HighlightSeverity severity = info.getSeverity();\n int layer;\n if (severity == HighlightSeverity.WARNING) {\n layer = HighlighterLayer.WARNING;\n }\n else if (severity == HighlightSeverity.WEAK_WARNING) {\n layer = HighlighterLayer.WEAK_WARNING;\n }\n else if (severityRegistrar.compare(severity, HighlightSeverity.ERROR) >= 0) {\n layer = HighlighterLayer.ERROR;\n }\n else if (severity == HighlightInfoType.INJECTED_FRAGMENT_SEVERITY) {\n layer = HighlighterLayer.CARET_ROW-1;\n }\n else if (severity == HighlightInfoType.ELEMENT_UNDER_CARET_SEVERITY) {\n layer = HighlighterLayer.ELEMENT_UNDER_CARET;\n }\n else {\n layer = HighlighterLayer.ADDITIONAL_SYNTAX;\n }\n return layer;\n }\n\n @NotNull\n private static RangeMarker getOrCreate(@NotNull Document document, @NotNull Map ranges2markersCache, @NotNull TextRange textRange) {\n return ranges2markersCache.computeIfAbsent(textRange, __ -> document.createRangeMarker(textRange));\n }\n\n private static final Key TYPING_INSIDE_HIGHLIGHTER_OCCURRED = Key.create(\"TYPING_INSIDE_HIGHLIGHTER_OCCURRED\");\n static boolean isWhitespaceOptimizationAllowed(@NotNull Document document) {\n return document.getUserData(TYPING_INSIDE_HIGHLIGHTER_OCCURRED) == null;\n }\n private static void disableWhiteSpaceOptimization(@NotNull Document document) {\n document.putUserData(TYPING_INSIDE_HIGHLIGHTER_OCCURRED, Boolean.TRUE);\n }\n private static void clearWhiteSpaceOptimizationFlag(@NotNull Document document) {\n document.putUserData(TYPING_INSIDE_HIGHLIGHTER_OCCURRED, null);\n }\n\n static void updateHighlightersByTyping(@NotNull Project project, @NotNull DocumentEvent e) {\n ApplicationManager.getApplication().assertIsDispatchThread();\n\n final Document document = e.getDocument();\n if (document instanceof DocumentEx && ((DocumentEx)document).isInBulkUpdate()) return;\n\n final MarkupModel markup = DocumentMarkupModel.forDocument(document, project, true);\n assertMarkupConsistent(markup, project);\n\n final int start = e.getOffset() - 1;\n final int end = start + e.getOldLength();\n\n final List toRemove = new ArrayList<>();\n DaemonCodeAnalyzerEx.processHighlights(document, project, null, start, end, info -> {\n if (!info.needUpdateOnTyping()) return true;\n\n RangeHighlighter highlighter = info.getHighlighter();\n int highlighterStart = highlighter.getStartOffset();\n int highlighterEnd = highlighter.getEndOffset();\n if (info.isAfterEndOfLine()) {\n if (highlighterStart < document.getTextLength()) {\n highlighterStart += 1;\n }\n if (highlighterEnd < document.getTextLength()) {\n highlighterEnd += 1;\n }\n }\n if (!highlighter.isValid() || start < highlighterEnd && highlighterStart <= end) {\n toRemove.add(info);\n }\n return true;\n });\n\n for (HighlightInfo info : toRemove) {\n if (!info.getHighlighter().isValid() || info.type.equals(HighlightInfoType.WRONG_REF)) {\n info.getHighlighter().dispose();\n }\n }\n\n assertMarkupConsistent(markup, project);\n\n if (!toRemove.isEmpty()) {\n disableWhiteSpaceOptimization(document);\n }\n }\n\n private static void assertMarkupConsistent(@NotNull final MarkupModel markup, @NotNull Project project) {\n if (!RedBlackTree.VERIFY) {\n return;\n }\n Document document = markup.getDocument();\n DaemonCodeAnalyzerEx.processHighlights(document, project, null, 0, document.getTextLength(), info -> {\n assert ((MarkupModelEx)markup).containsHighlighter(info.getHighlighter());\n return true;\n });\n RangeHighlighter[] allHighlighters = markup.getAllHighlighters();\n for (RangeHighlighter highlighter : allHighlighters) {\n if (!highlighter.isValid()) continue;\n HighlightInfo info = HighlightInfo.fromRangeHighlighter(highlighter);\n if (info == null) continue;\n boolean contains = !DaemonCodeAnalyzerEx\n .processHighlights(document, project, null, info.getActualStartOffset(), info.getActualEndOffset(),\n highlightInfo -> BY_START_OFFSET_NODUPS.compare(highlightInfo, info) != 0);\n assert contains: info;\n }\n }\n}\n"},"message":{"kind":"string","value":"IDEA-198593 Errors reported by JSON annotator disappear only on typing\n"},"old_file":{"kind":"string","value":"platform/analysis-impl/src/com/intellij/codeInsight/daemon/impl/UpdateHighlightersUtil.java"},"subject":{"kind":"string","value":"IDEA-198593 Errors reported by JSON annotator disappear only on typing"},"git_diff":{"kind":"string","value":"latform/analysis-impl/src/com/intellij/codeInsight/daemon/impl/UpdateHighlightersUtil.java\n RangeHighlighter highlighter = info.getHighlighter();\n int hiStart = highlighter.getStartOffset();\n int hiEnd = highlighter.getEndOffset();\n if (!info.isFromInjection() && hiEnd < document.getTextLength() && (hiEnd <= startOffset || hiStart >= endOffset)) {\n if (!info.isFromInjection() && hiEnd < document.getTextLength() && (hiEnd != 0 && hiEnd <= startOffset || hiStart >= endOffset)) {\n return true; // injections are oblivious to restricting range\n }\n boolean toRemove = infoSet.contains(info) ||"}}},{"rowIdx":883,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"bsd-3-clause"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"508869a9e1c61d4f90c0dd7447861bd98c3587a8"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"NCIP/cab2b,NCIP/cab2b,NCIP/cab2b"},"new_contents":{"kind":"string","value":"package edu.wustl.cab2b.client.ui.searchDataWizard;\r\n\r\nimport java.awt.BorderLayout;\r\nimport java.awt.Color;\r\nimport java.awt.Dimension;\r\nimport java.awt.FlowLayout;\r\nimport java.awt.event.ActionEvent;\r\nimport java.awt.event.ActionListener;\r\nimport java.io.BufferedWriter;\r\nimport java.io.File;\r\nimport java.io.FileWriter;\r\nimport java.io.IOException;\r\nimport java.io.PrintWriter;\r\n\r\nimport javax.swing.JDialog;\r\nimport javax.swing.JFileChooser;\r\nimport javax.swing.JScrollPane;\r\n\r\nimport edu.wustl.cab2b.client.ui.controls.Cab2bButton;\r\nimport edu.wustl.cab2b.client.ui.controls.Cab2bLabel;\r\nimport edu.wustl.cab2b.client.ui.controls.Cab2bPanel;\r\nimport edu.wustl.cab2b.client.ui.mainframe.MainFrame;\r\nimport edu.wustl.cab2b.client.ui.mainframe.NewWelcomePanel;\r\nimport edu.wustl.cab2b.client.ui.util.WindowUtilities;\r\nimport edu.wustl.cab2b.common.domain.DCQL;\r\n\r\n/**\r\n * This class displays the DCQL Panel which shows the XML format of DCQL along with function of saving the XML file \r\n * \r\n * @author gaurav_mehta\r\n */\r\npublic class ShowDCQLPanel extends Cab2bPanel {\r\n\r\n /* JDialog in which the Panel is displayed */\r\n private JDialog dialog;\r\n\r\n // Cab2bLabel in which the entire XML is \r\n final private Cab2bLabel xmlTextPane = new Cab2bLabel();\r\n\r\n // Cab2bPanel for showing Success and failure messages\r\n final Cab2bPanel messagePanel = new Cab2bPanel();\r\n \r\n private String dcqlString;\r\n\r\n /**\r\n * @param dcql \r\n */\r\n public ShowDCQLPanel(DCQL dcql) {\r\n this.dcqlString = dcql.getDcqlQuery();\r\n initGUI();\r\n }\r\n\r\n private void initGUI() {\r\n String xmlText = new XmlParser().parseXml(dcqlString);\r\n\r\n xmlTextPane.setText(xmlText);\r\n xmlTextPane.setBackground(Color.WHITE);\r\n\r\n Cab2bPanel xmlPanel = new Cab2bPanel();\r\n xmlPanel.add(xmlTextPane);\r\n xmlPanel.setBackground(Color.WHITE);\r\n\r\n JScrollPane scrollPane = new JScrollPane();\r\n scrollPane.getViewport().add(xmlPanel);\r\n scrollPane.getViewport().setBackground(Color.WHITE);\r\n\r\n Cab2bPanel xmlNavigationPanel = new Cab2bPanel();\r\n Cab2bButton exportButton = new Cab2bButton(\"Export\");\r\n Cab2bButton cancelButton = new Cab2bButton(\"Cancel\");\r\n\r\n // Action Listener for Export Button\r\n exportButton.addActionListener(new ExportButtonListner());\r\n\r\n // Action Listener for Cancel Button\r\n cancelButton.addActionListener(new ActionListener() {\r\n public void actionPerformed(ActionEvent actionEvent) {\r\n dialog.dispose();\r\n }\r\n });\r\n\r\n Cab2bPanel buttonPanel = new Cab2bPanel();\r\n FlowLayout flowLayout = new FlowLayout(FlowLayout.RIGHT);\r\n buttonPanel.setLayout(flowLayout);\r\n buttonPanel.add(exportButton);\r\n buttonPanel.add(cancelButton);\r\n buttonPanel.setBackground(new Color(240, 240, 240));\r\n\r\n xmlNavigationPanel.add(\"br left\", messagePanel);\r\n xmlNavigationPanel.add(\"hfill\", buttonPanel);\r\n xmlNavigationPanel.setPreferredSize(new Dimension(880, 50));\r\n xmlNavigationPanel.setBackground(new Color(240, 240, 240));\r\n\r\n setLayout(new BorderLayout());\r\n add(scrollPane, BorderLayout.CENTER);\r\n add(xmlNavigationPanel, BorderLayout.SOUTH);\r\n }\r\n\r\n /**\r\n * JDialog for showing DCQL XML Details Panel\r\n * \r\n * @return\r\n */\r\n public JDialog showInDialog() {\r\n Dimension dimension = MainFrame.getScreenDimesion();\r\n dialog = WindowUtilities.setInDialog(NewWelcomePanel.getMainFrame(), this, \"DCQL Xml\", new Dimension(\r\n (int) (dimension.width * 0.77), (int) (dimension.height * 0.65)), true, false);\r\n dialog.setVisible(true);\r\n\r\n return dialog;\r\n }\r\n \r\n private boolean writeFile(File file, String dataString) {\r\n try {\r\n PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file)));\r\n out.print(dataString);\r\n out.flush();\r\n out.close();\r\n } catch (IOException e) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Action listener class for Export Button. It saves the XML file to user defined location in user defined format\r\n */\r\n class ExportButtonListner implements ActionListener {\r\n \t\r\n public void actionPerformed(ActionEvent actionEvent) {\r\n JFileChooser fileChooser = new JFileChooser();\r\n\r\n // A call to JFileChooser's ShowSaveDialog PopUp\r\n fileChooser.showSaveDialog(NewWelcomePanel.getMainFrame());\r\n\r\n File file = fileChooser.getSelectedFile();\r\n // Function call for writing the File and saving it\r\n boolean saveReturnValue = writeFile(file, dcqlString);\r\n if (saveReturnValue == true) {\r\n Cab2bLabel successResultLabel = new Cab2bLabel(\"File Saved Successfully\");\r\n successResultLabel.setForeground(Color.GREEN);\r\n messagePanel.add(successResultLabel);\r\n messagePanel.repaint();\r\n } else {\r\n Cab2bLabel failureResultLabel = new Cab2bLabel(\"File Could not be Saved\");\r\n failureResultLabel.setForeground(Color.RED);\r\n messagePanel.add(failureResultLabel);\r\n messagePanel.repaint();\r\n\r\n }\r\n }\r\n }\r\n}\r\n"},"new_file":{"kind":"string","value":"source/client/main/edu/wustl/cab2b/client/ui/searchDataWizard/ShowDCQLPanel.java"},"old_contents":{"kind":"string","value":"package edu.wustl.cab2b.client.ui.searchDataWizard;\r\n\r\nimport java.awt.BorderLayout;\r\nimport java.awt.Color;\r\nimport java.awt.Dimension;\r\nimport java.awt.FlowLayout;\r\nimport java.awt.event.ActionEvent;\r\nimport java.awt.event.ActionListener;\r\nimport java.io.BufferedWriter;\r\nimport java.io.File;\r\nimport java.io.FileWriter;\r\nimport java.io.IOException;\r\nimport java.io.PrintWriter;\r\n\r\nimport javax.swing.JDialog;\r\nimport javax.swing.JFileChooser;\r\nimport javax.swing.JScrollPane;\r\n\r\nimport edu.wustl.cab2b.client.ui.controls.Cab2bButton;\r\nimport edu.wustl.cab2b.client.ui.controls.Cab2bLabel;\r\nimport edu.wustl.cab2b.client.ui.controls.Cab2bPanel;\r\nimport edu.wustl.cab2b.client.ui.mainframe.MainFrame;\r\nimport edu.wustl.cab2b.client.ui.mainframe.NewWelcomePanel;\r\nimport edu.wustl.cab2b.client.ui.util.WindowUtilities;\r\nimport edu.wustl.cab2b.common.domain.DCQL;\r\n\r\n/**\r\n * This class displays the DCQL Panel which shows the XML format of DCQL along with function of saving the XML file \r\n * \r\n * @author gaurav_mehta\r\n */\r\npublic class ShowDCQLPanel extends Cab2bPanel {\r\n\r\n /* JDialog in which the Panel is displayed */\r\n private JDialog dialog;\r\n\r\n // Cab2bLabel in which the entire XML is \r\n final private Cab2bLabel xmlTextPane = new Cab2bLabel();\r\n\r\n // Cab2bPanel for showing Success and failure messages\r\n final Cab2bPanel messagePanel = new Cab2bPanel();\r\n\r\n /**\r\n * @param dcql \r\n */\r\n public ShowDCQLPanel(DCQL dcql) {\r\n initGUI(dcql);\r\n }\r\n\r\n private void initGUI(DCQL dcql) {\r\n String xmlText = new XmlParser().parseXml(dcql.getDcqlQuery());\r\n\r\n xmlTextPane.setText(xmlText);\r\n xmlTextPane.setBackground(Color.WHITE);\r\n\r\n Cab2bPanel xmlPanel = new Cab2bPanel();\r\n xmlPanel.add(xmlTextPane);\r\n xmlPanel.setBackground(Color.WHITE);\r\n\r\n JScrollPane scrollPane = new JScrollPane();\r\n scrollPane.getViewport().add(xmlPanel);\r\n scrollPane.getViewport().setBackground(Color.WHITE);\r\n\r\n Cab2bPanel xmlNavigationPanel = new Cab2bPanel();\r\n Cab2bButton exportButton = new Cab2bButton(\"Export\");\r\n Cab2bButton cancelButton = new Cab2bButton(\"Cancel\");\r\n\r\n // Action Listener for Export Button\r\n exportButton.addActionListener(new ExportButtonListner());\r\n\r\n // Action Listener for Cancel Button\r\n cancelButton.addActionListener(new ActionListener() {\r\n public void actionPerformed(ActionEvent actionEvent) {\r\n dialog.dispose();\r\n }\r\n });\r\n\r\n Cab2bPanel buttonPanel = new Cab2bPanel();\r\n FlowLayout flowLayout = new FlowLayout(FlowLayout.RIGHT);\r\n buttonPanel.setLayout(flowLayout);\r\n buttonPanel.add(exportButton);\r\n buttonPanel.add(cancelButton);\r\n buttonPanel.setBackground(new Color(240, 240, 240));\r\n\r\n xmlNavigationPanel.add(\"br left\", messagePanel);\r\n xmlNavigationPanel.add(\"hfill\", buttonPanel);\r\n xmlNavigationPanel.setPreferredSize(new Dimension(880, 50));\r\n xmlNavigationPanel.setBackground(new Color(240, 240, 240));\r\n\r\n setLayout(new BorderLayout());\r\n add(scrollPane, BorderLayout.CENTER);\r\n add(xmlNavigationPanel, BorderLayout.SOUTH);\r\n }\r\n\r\n /**\r\n * JDialog for showing DCQL XML Details Panel\r\n * \r\n * @return\r\n */\r\n public JDialog showInDialog() {\r\n Dimension dimension = MainFrame.getScreenDimesion();\r\n dialog = WindowUtilities.setInDialog(NewWelcomePanel.getMainFrame(), this, \"DCQL Xml\", new Dimension(\r\n (int) (dimension.width * 0.77), (int) (dimension.height * 0.65)), true, false);\r\n dialog.setVisible(true);\r\n\r\n return dialog;\r\n }\r\n \r\n private boolean writeFile(File file, String dataString) {\r\n try {\r\n PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file)));\r\n out.print(dataString);\r\n out.flush();\r\n out.close();\r\n } catch (IOException e) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Action listener class for Export Button. It saves the XML file to user defined location in user defined format\r\n */\r\n class ExportButtonListner implements ActionListener {\r\n public void actionPerformed(ActionEvent actionEvent) {\r\n JFileChooser fileChooser = new JFileChooser();\r\n\r\n // A call to JFileChooser's ShowSaveDialog PopUp\r\n fileChooser.showSaveDialog(NewWelcomePanel.getMainFrame());\r\n\r\n File file = fileChooser.getSelectedFile();\r\n // Function call for writing the File and saving it\r\n boolean saveReturnValue = writeFile(file, xmlTextPane.getText());\r\n if (saveReturnValue == true) {\r\n Cab2bLabel successResultLabel = new Cab2bLabel(\"File Saved Successfully\");\r\n successResultLabel.setForeground(Color.GREEN);\r\n messagePanel.add(successResultLabel);\r\n messagePanel.repaint();\r\n } else {\r\n Cab2bLabel failureResultLabel = new Cab2bLabel(\"File Could not be Saved\");\r\n failureResultLabel.setForeground(Color.RED);\r\n messagePanel.add(failureResultLabel);\r\n messagePanel.repaint();\r\n\r\n }\r\n }\r\n }\r\n}\r\n"},"message":{"kind":"string","value":"Fix for Bug # 10563\n\n"},"old_file":{"kind":"string","value":"source/client/main/edu/wustl/cab2b/client/ui/searchDataWizard/ShowDCQLPanel.java"},"subject":{"kind":"string","value":"Fix for Bug # 10563"},"git_diff":{"kind":"string","value":"ource/client/main/edu/wustl/cab2b/client/ui/searchDataWizard/ShowDCQLPanel.java\n \n // Cab2bPanel for showing Success and failure messages\n final Cab2bPanel messagePanel = new Cab2bPanel();\n \n private String dcqlString;\n \n /**\n * @param dcql \n */\n public ShowDCQLPanel(DCQL dcql) {\n initGUI(dcql);\n this.dcqlString = dcql.getDcqlQuery();\n initGUI();\n }\n \n private void initGUI(DCQL dcql) {\n String xmlText = new XmlParser().parseXml(dcql.getDcqlQuery());\n private void initGUI() {\n String xmlText = new XmlParser().parseXml(dcqlString);\n \n xmlTextPane.setText(xmlText);\n xmlTextPane.setBackground(Color.WHITE);\n * Action listener class for Export Button. It saves the XML file to user defined location in user defined format\n */\n class ExportButtonListner implements ActionListener {\n \t\n public void actionPerformed(ActionEvent actionEvent) {\n JFileChooser fileChooser = new JFileChooser();\n \n \n File file = fileChooser.getSelectedFile();\n // Function call for writing the File and saving it\n boolean saveReturnValue = writeFile(file, xmlTextPane.getText());\n boolean saveReturnValue = writeFile(file, dcqlString);\n if (saveReturnValue == true) {\n Cab2bLabel successResultLabel = new Cab2bLabel(\"File Saved Successfully\");\n successResultLabel.setForeground(Color.GREEN);"}}},{"rowIdx":884,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"bsd-3-clause"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"d9a5f8b141245b6d489995f667f343b4f49e449e"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"tinkerpop/gremlin,ccagnoli/gremlin,cesarmarinhorj/gremlin,cesarmarinhorj/gremlin,tinkerpop/gremlin,ccagnoli/gremlin,samanalysis/gremlin,samanalysis/gremlin"},"new_contents":{"kind":"string","value":"package com.tinkerpop.gremlin.pipes;\n\nimport com.tinkerpop.pipes.AbstractPipe;\nimport com.tinkerpop.pipes.ExpandableIterator;\nimport com.tinkerpop.pipes.Pipe;\nimport groovy.lang.Closure;\n\nimport java.util.Iterator;\nimport java.util.List;\n\n/**\n * @author Marko A. Rodriguez (http://markorodriguez.com)\n */\npublic class LoopPipe extends AbstractPipe {\n\n private final Closure doLoopClosure;\n private final Pipe toLoopPipe;\n private ExpandableIterator expando;\n\n public LoopPipe(final Pipe toLoopPipe, final Closure doLoopClosure) {\n this.toLoopPipe = toLoopPipe;\n this.doLoopClosure = doLoopClosure;\n }\n\n protected S processNextStart() {\n while (true) {\n final S e = this.toLoopPipe.next();\n if ((Boolean) doLoopClosure.call(e)) {\n this.expando.add(e);\n } else {\n return e;\n }\n }\n }\n\n public void setStarts(final Iterator iterator) {\n this.expando = new ExpandableIterator(iterator);\n this.toLoopPipe.setStarts(this.expando);\n }\n\n public String toString() {\n return super.toString() + \"<\" + this.toLoopPipe + \">\";\n }\n\n public List getPath() {\n return this.toLoopPipe.getPath();\n }\n}\n"},"new_file":{"kind":"string","value":"src/main/java/com/tinkerpop/gremlin/pipes/LoopPipe.java"},"old_contents":{"kind":"string","value":"package com.tinkerpop.gremlin.pipes;\n\nimport com.tinkerpop.pipes.AbstractPipe;\nimport com.tinkerpop.pipes.ExpandableIterator;\nimport com.tinkerpop.pipes.Pipe;\nimport groovy.lang.Closure;\n\nimport java.util.Iterator;\nimport java.util.List;\n\n/**\n * @author Marko A. Rodriguez (http://markorodriguez.com)\n */\npublic class LoopPipe extends AbstractPipe {\n\n private final Closure doLoopClosure;\n private final Pipe toLoopPipe;\n private ExpandableIterator expando;\n\n public LoopPipe(final Pipe toLoopPipe, final Closure doLoopClosure) {\n this.toLoopPipe = toLoopPipe;\n this.doLoopClosure = doLoopClosure;\n }\n\n protected S processNextStart() {\n while (true) {\n final S e = this.toLoopPipe.next();\n if ((Boolean) doLoopClosure.call(e)) {\n this.expando.add(e);\n } else {\n return e;\n }\n }\n }\n\n public void setStarts(final Iterator iterator) {\n this.expando = new ExpandableIterator(iterator);\n this.toLoopPipe.setStarts(this.expando);\n }\n\n public String toString() {\n return super.toString() + \"[\" + this.toLoopPipe + \"]\";\n }\n\n public List getPath() {\n return this.toLoopPipe.getPath();\n }\n}\n"},"message":{"kind":"string","value":"fixed toString() of LoopPipe.\n"},"old_file":{"kind":"string","value":"src/main/java/com/tinkerpop/gremlin/pipes/LoopPipe.java"},"subject":{"kind":"string","value":"fixed toString() of LoopPipe."},"git_diff":{"kind":"string","value":"rc/main/java/com/tinkerpop/gremlin/pipes/LoopPipe.java\n }\n \n public String toString() {\n return super.toString() + \"[\" + this.toLoopPipe + \"]\";\n return super.toString() + \"<\" + this.toLoopPipe + \">\";\n }\n \n public List getPath() {"}}},{"rowIdx":885,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"eb608ac4a4017128804782f45b6ef742b989b622"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"RokKos/FRI_Programiranje,RokKos/FRI_Programiranje,RokKos/FRI_Programiranje,RokKos/FRI_Programiranje,RokKos/FRI_Programiranje,RokKos/FRI_Programiranje,RokKos/FRI_Programiranje"},"new_contents":{"kind":"string","value":"/**\n * @author sliva\n */\npackage compiler.phases.abstr;\n\nimport java.util.*;\nimport compiler.common.report.*;\nimport compiler.data.dertree.*;\nimport compiler.data.dertree.DerNode.Nont;\nimport compiler.data.dertree.visitor.*;\nimport compiler.data.symbol.Symbol.Term;\nimport compiler.data.abstree.*;\nimport compiler.data.abstree.AbsBinExpr.Oper;\n\n/**\n * Transforms a derivation tree to an abstract syntax tree.\n * \n * @author sliva\n */\npublic class AbsTreeConstructor implements DerVisitor {\n\n\tprivate final String PTR_NODE = \"Expected PTR node\";\n\tprivate final String ARR_NODE = \"Expected ARR node\";\n\tprivate final String GOT_STR = \" got: \";\n\tprivate final String TOO_MANY_NODES = \"There are zore or more than 3 nodes\";\n\tprivate final String DECL_NODE = \"Declaration node doesn't start with TYP, FUN or VAR\";\n\tprivate final String WRONG_BINARY_NODE = \"This binary operator doesn't exist.\";\n\tprivate final Location kNULL_LOCATION = new Location(0, 0);\n\n\t@Override\n\tpublic AbsTree visit(DerLeaf leaf, AbsTree visArg) {\n\t\tthrow new Report.InternalError();\n\t}\n\n\t@Override\n\tpublic AbsTree visit(DerNode node, AbsTree visArg) {\n\t\tswitch (node.label) {\n\n\t\tcase Source: {\n\t\t\tAbsDecls decls = (AbsDecls) node.subtree(0).accept(this, null);\n\t\t\treturn new AbsSource(decls, decls);\n\t\t}\n\n\t\tcase Decls:\n\t\tcase DeclsRest: {\n\t\t\tif (node.numSubtrees() == 0)\n\t\t\t\treturn null;\n\t\t\tVector allDecls = new Vector();\n\t\t\tAbsDecl decl = (AbsDecl) node.subtree(0).accept(this, null);\n\t\t\tallDecls.add(decl);\n\t\t\tAbsDecls decls = (AbsDecls) node.subtree(1).accept(this, null);\n\t\t\tif (decls != null)\n\t\t\t\tallDecls.addAll(decls.decls());\n\t\t\treturn new AbsDecls(new Location(decl, decls == null ? decl : decls), allDecls);\n\t\t}\n\n\t\tcase Decl: {\n\t\t\tDerLeaf typeOfDecleration = (DerLeaf) node.subtree(0);\n\t\t\tswitch (typeOfDecleration.symb.token) {\n\t\t\tcase VAR: {\n\t\t\t\tAbsParDecl parDecl = (AbsParDecl) node.subtree(1).accept(this, null);\n\t\t\t\tLocation loc = new Location(typeOfDecleration, parDecl);\n\t\t\t\treturn new AbsVarDecl(loc, parDecl.name, parDecl.type);\n\t\t\t}\n\n\t\t\tcase TYP: {\n\t\t\t\tAbsParDecl parDecl = (AbsParDecl) node.subtree(1).accept(this, null);\n\t\t\t\tLocation loc = new Location(typeOfDecleration, parDecl);\n\t\t\t\treturn new AbsTypDecl(loc, parDecl.name, parDecl.type);\n\t\t\t}\n\n\t\t\tcase FUN: {\n\t\t\t\tDerLeaf funName = (DerLeaf) node.subtree(1);\n\t\t\t\tAbsParDecls parDecls = (AbsParDecls) node.subtree(2).accept(this, null);\n\t\t\t\tAbsType type = (AbsType) node.subtree(3).accept(this, null);\n\t\t\t\tAbsExpr expr = (AbsExpr) node.subtree(4).accept(this, null);\n\n\t\t\t\tif (expr.location().equals(kNULL_LOCATION)) {\n\t\t\t\t\tLocation loc = new Location(typeOfDecleration, type);\n\t\t\t\t\treturn new AbsFunDecl(loc, funName.symb.lexeme, parDecls, type);\n\t\t\t\t} else {\n\t\t\t\t\tLocation loc = new Location(typeOfDecleration, expr);\n\t\t\t\t\treturn new AbsFunDef(loc, funName.symb.lexeme, parDecls, type, expr);\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tdefault:\n\t\t\t\tthrow new Report.Error(typeOfDecleration.location(),\n\t\t\t\t\t\tDECL_NODE + GOT_STR + typeOfDecleration.symb.token.toString());\n\t\t\t}\n\t\t}\n\n\t\tcase ParDecl: {\n\t\t\treturn DeformParDecl(node);\n\t\t}\n\n\t\tcase Type: {\n\t\t\tif (node.numSubtrees() == 1) {\n\n\t\t\t\t// This is only check for ( Type )\n\t\t\t\tif (node.subtree(0) instanceof DerNode) {\n\t\t\t\t\treturn node.subtree(0).accept(this, null);\n\t\t\t\t} else if (node.subtree(0) instanceof DerLeaf) {\n\t\t\t\t\tDerLeaf primitiveTypeNode = (DerLeaf) node.subtree(0);\n\t\t\t\t\tAbsAtomType.Type primitiveType;\n\t\t\t\t\tswitch (primitiveTypeNode.symb.token) {\n\t\t\t\t\tcase VOID:\n\t\t\t\t\t\tprimitiveType = AbsAtomType.Type.VOID;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase BOOL:\n\t\t\t\t\t\tprimitiveType = AbsAtomType.Type.BOOL;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase CHAR:\n\t\t\t\t\t\tprimitiveType = AbsAtomType.Type.CHAR;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase INT:\n\t\t\t\t\t\tprimitiveType = AbsAtomType.Type.INT;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tdefault:\n\t\t\t\t\t\t// TODO: Error (Maybe)\n\t\t\t\t\t\treturn new AbsTypName(primitiveTypeNode.location(), primitiveTypeNode.symb.lexeme);\n\t\t\t\t\t}\n\n\t\t\t\t\treturn new AbsAtomType(primitiveTypeNode.location(), primitiveType);\n\t\t\t\t}\n\t\t\t} else if (node.numSubtrees() == 2) {\n\t\t\t\tDerLeaf ptr = (DerLeaf) node.subtree(0);\n\t\t\t\tif (ptr.symb.token == Term.PTR) {\n\t\t\t\t\tAbsType subType = (AbsType) node.subtree(1).accept(this, null);\n\t\t\t\t\tLocation loc = new Location(ptr, subType);\n\t\t\t\t\treturn new AbsPtrType(loc, subType);\n\t\t\t\t} else if (ptr.symb.token == Term.REC) {\n\t\t\t\t\tAbsCompDecls compDecls = (AbsCompDecls) node.subtree(1).accept(this, null);\n\t\t\t\t\tLocation loc = new Location(ptr, compDecls);\n\t\t\t\t\treturn new AbsRecType(loc, compDecls);\n\t\t\t\t} else {\n\t\t\t\t\tthrow new Report.Error(ptr.location(), PTR_NODE + GOT_STR + ptr.symb.token.toString());\n\t\t\t\t}\n\n\t\t\t} else if (node.numSubtrees() == 3) {\n\t\t\t\tDerLeaf arr = (DerLeaf) node.subtree(0);\n\t\t\t\tif (arr.symb.token != Term.ARR) {\n\t\t\t\t\tthrow new Report.Error(arr.location(), ARR_NODE + GOT_STR + arr.symb.token.toString());\n\t\t\t\t}\n\n\t\t\t\tAbsExpr length = (AbsExpr) node.subtree(1).accept(this, null);\n\t\t\t\tAbsType elemType = (AbsType) node.subtree(2).accept(this, null);\n\t\t\t\tLocation loc = new Location(arr, elemType);\n\t\t\t\treturn new AbsArrType(loc, length, elemType);\n\n\t\t\t} else {\n\t\t\t\tthrow new Report.Error(node.location(), TOO_MANY_NODES + GOT_STR + node.numSubtrees());\n\t\t\t}\n\t\t}\n\n\t\tcase ParDecls: {\n\t\t\treturn DeformParDecls(node);\n\t\t}\n\n\t\tcase ParDeclsRest: {\n\t\t\treturn DeformParDecls(node);\n\t\t}\n\n\t\tcase BodyEps: {\n\t\t\tif (node.numSubtrees() == 0) {\n\t\t\t\t// Hacky try to find other expr that is not abstrac and has less field\n\t\t\t\treturn Epsilon();\n\t\t\t}\n\n\t\t\treturn node.subtree(1).accept(this, null);\n\t\t}\n\n\t\tcase CompDecls:\n\t\tcase CompDeclsRest: {\n\t\t\tif (node.numSubtrees() == 0) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tVector allCompDecls = new Vector();\n\t\t\tAbsCompDecl compDecl = (AbsCompDecl) node.subtree(0).accept(this, null);\n\t\t\tallCompDecls.add(compDecl);\n\t\t\tAbsCompDecls compDecls = (AbsCompDecls) node.subtree(1).accept(this, null);\n\t\t\tif (compDecls != null) {\n\t\t\t\tallCompDecls.addAll(compDecls.compDecls());\n\t\t\t}\n\t\t\tLocation loc = new Location(compDecl, compDecls == null ? compDecl : compDecls);\n\t\t\treturn new AbsCompDecls(loc, allCompDecls);\n\t\t}\n\n\t\tcase CompDecl: {\n\t\t\treturn DeformCompDecl(node);\n\t\t}\n\n\t\tcase Expr:\n\t\tcase DisjExpr:\n\t\tcase ConjExpr:\n\t\tcase RelExpr:\n\t\tcase AddExpr:\n\t\tcase MulExpr: {\n\t\t\treturn ExpressionTransform(node, visArg);\n\t\t}\n\n\t\tcase DisjExprRest:\n\t\tcase ConjExprRest:\n\t\tcase AddExprRest:\n\t\tcase MulExprRest: {\n\t\t\tif (node.numSubtrees() == 0) {\n\t\t\t\treturn visArg;\n\t\t\t}\n\n\t\t\tDerLeaf operatorNode = (DerLeaf) node.subtree(0);\n\t\t\tAbsBinExpr.Oper oper = kTermToBinOper.get(operatorNode.symb.token);\n\t\t\tif (oper == null) {\n\t\t\t\tthrow new Report.Error(node.location(), WRONG_BINARY_NODE + GOT_STR + node.numSubtrees());\n\t\t\t}\n\n\t\t\tAbsExpr leftOperand = (AbsExpr) node.subtree(1).accept(this, null);\n\t\t\tLocation loc = new Location(visArg, leftOperand);\n\t\t\tAbsBinExpr binExpr = new AbsBinExpr(loc, oper, (AbsExpr) visArg, leftOperand);\n\n\t\t\tAbsExpr rightOperand = (AbsExpr) node.subtree(2).accept(this, binExpr);\n\t\t\t// rightOperand.location());\n\t\t\treturn rightOperand;\n\n\t\t}\n\n\t\tcase RelExprRest: {\n\t\t\tif (node.numSubtrees() == 0) {\n\t\t\t\treturn visArg;\n\t\t\t}\n\n\t\t\tDerLeaf operatorNode = (DerLeaf) node.subtree(0);\n\t\t\tAbsBinExpr.Oper oper = kTermToBinOper.get(operatorNode.symb.token);\n\t\t\tif (oper == null) {\n\t\t\t\tthrow new Report.Error(node.location(), WRONG_BINARY_NODE + GOT_STR + node.numSubtrees());\n\t\t\t}\n\n\t\t\tAbsExpr leftOperand = (AbsExpr) node.subtree(1).accept(this, null);\n\t\t\tLocation loc = new Location(visArg, leftOperand);\n\t\t\treturn new AbsBinExpr(loc, oper, (AbsExpr) visArg, leftOperand);\n\t\t}\n\n\t\tcase PrefExpr: {\n\t\t\tif (node.subtree(0) instanceof DerLeaf) {\n\t\t\t\tDerLeaf operatorNode = (DerLeaf) node.subtree(0);\n\t\t\t\tAbsUnExpr.Oper oper = kTermToUnarOper.get(operatorNode.symb.token);\n\n\t\t\t\tif (oper != null) {\n\t\t\t\t\tAbsExpr subExpr = (AbsExpr) node.subtree(1).accept(this, null);\n\t\t\t\t\tLocation loc = new Location(operatorNode, subExpr);\n\t\t\t\t\treturn new AbsUnExpr(loc, oper, subExpr);\n\t\t\t\t}\n\n\t\t\t\tif (operatorNode.symb.token == Term.NEW) {\n\t\t\t\t\tAbsType type = (AbsType) node.subtree(1).accept(this, null);\n\t\t\t\t\tLocation loc = new Location(operatorNode, type);\n\t\t\t\t\treturn new AbsNewExpr(loc, type);\n\t\t\t\t}\n\n\t\t\t\tif (operatorNode.symb.token == Term.DEL) {\n\t\t\t\t\tAbsExpr expr = (AbsExpr) node.subtree(1).accept(this, null);\n\t\t\t\t\tLocation loc = new Location(operatorNode, expr);\n\t\t\t\t\treturn new AbsDelExpr(loc, expr);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tDerNode exprNode = (DerNode) node.subtree(0);\n\t\t\t\tAbsExpr expr = (AbsExpr) exprNode.accept(this, null);\n\t\t\t\tif (exprNode.label == Nont.Expr) {\n\t\t\t\t\treturn node.subtree(1).accept(this, expr);\n\t\t\t\t} else if (exprNode.label == Nont.PstfExpr) {\n\t\t\t\t\treturn node.subtree(1).accept(this, expr);\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\n\t\tcase PstfExprRest: {\n\t\t\tif (node.numSubtrees() == 0) {\n\t\t\t\treturn visArg;\n\t\t\t}\n\n\t\t\tif (node.subtree(0) instanceof DerLeaf) {\n\t\t\t\tDerLeaf varNode = (DerLeaf) node.subtree(0);\n\t\t\t\tAbsVarName varName = new AbsVarName(varNode, varNode.symb.lexeme);\n\t\t\t\tLocation loc = new Location(visArg, varName);\n\t\t\t\tAbsRecExpr recordExpr = new AbsRecExpr(loc, (AbsExpr) visArg, varName);\n\t\t\t\treturn node.subtree(1).accept(this, recordExpr);\n\t\t\t} else {\n\t\t\t\tAbsExpr index = (AbsExpr) node.subtree(0).accept(this, null);\n\t\t\t\tLocation loc = new Location(visArg, index);\n\t\t\t\tAbsArrExpr arrExpr = new AbsArrExpr(loc, (AbsExpr) visArg, index);\n\t\t\t\treturn node.subtree(1).accept(this, arrExpr);\n\t\t\t}\n\t\t}\n\n\t\tcase PstfExpr: {\n\t\t\treturn node.subtree(0).accept(this, null);\n\t\t}\n\n\t\tcase AtomExpr: {\n\t\t\tif (node.numSubtrees() == 1) {\n\t\t\t\treturn node.subtree(0).accept(this, null);\n\t\t\t}\n\n\t\t\tif (node.numSubtrees() == 2) {\n\t\t\t\tboolean isNull = node.subtree(1).accept(this, null) instanceof AbsAtomExpr\n\t\t\t\t\t\t&& node.subtree(1).accept(this, null).location().equals(kNULL_LOCATION);\n\t\t\t\tif (isNull) {\n\t\t\t\t\tDerLeaf varName = (DerLeaf) node.subtree(0);\n\t\t\t\t\tLocation loc = new Location(varName, varName);\n\t\t\t\t\treturn new AbsVarName(loc, varName.symb.lexeme);\n\t\t\t\t} else {\n\t\t\t\t\tAbsArgs funArgs = (AbsArgs) node.subtree(1).accept(this, null);\n\t\t\t\t\tDerLeaf funName = (DerLeaf) node.subtree(0);\n\t\t\t\t\tLocation loc = new Location(funName, funArgs.args().size() != 0 ? funArgs : funName);\n\t\t\t\t\treturn new AbsFunName(loc, funName.symb.lexeme, funArgs);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (node.numSubtrees() == 3) {\n\t\t\t\tAbsStmts statements = (AbsStmts) node.subtree(0).accept(this, null);\n\t\t\t\tAbsExpr expr = (AbsExpr) node.subtree(1).accept(this, null);\n\t\t\t\tAbsDecls decls = (AbsDecls) node.subtree(2).accept(this, null);\n\n\t\t\t\tif (decls == null) {\n\t\t\t\t\tLocation loc = new Location(statements, expr);\n\t\t\t\t\treturn new AbsBlockExpr(loc, EpsilonDecls(), statements, expr);\n\t\t\t\t}\n\n\t\t\t\tLocation loc = new Location(statements, decls);\n\t\t\t\treturn new AbsBlockExpr(loc, decls, statements, expr);\n\t\t\t}\n\t\t}\n\t\tcase Literal: {\n\t\t\tDerLeaf literal = (DerLeaf) node.subtree(0);\n\t\t\treturn new AbsAtomExpr(literal, kTermToLitType.get(literal.symb.token), literal.symb.lexeme);\n\t\t}\n\n\t\tcase CastEps: {\n\t\t\tif (node.numSubtrees() == 0) {\n\t\t\t\treturn visArg;\n\t\t\t}\n\n\t\t\tAbsType type = (AbsType) node.subtree(0).accept(this, null);\n\t\t\t// Double check this for location\n\t\t\tLocation loc = new Location(visArg, type);\n\t\t\treturn new AbsCastExpr(loc, (AbsExpr) visArg, type);\n\t\t}\n\n\t\tcase CallEps:\n\t\t\tif (node.numSubtrees() == 0) {\n\t\t\t\treturn Epsilon();\n\t\t\t}\n\n\t\t\treturn node.subtree(0).accept(this, null);\n\t\tcase Args: {\n\t\t\tif (node.numSubtrees() == 0) {\n\t\t\t\treturn EpsilonArgs();\n\t\t\t}\n\n\t\t\treturn node.subtree(0).accept(this, null);\n\t\t}\n\n\t\tcase ArgsEps:\n\t\tcase ArgsRest: {\n\t\t\tif (node.numSubtrees() == 0) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tVector allExpr = new Vector();\n\t\t\tAbsExpr expr = (AbsExpr) node.subtree(0).accept(this, null);\n\t\t\tallExpr.add(expr);\n\t\t\tAbsArgs args = (AbsArgs) node.subtree(1).accept(this, null);\n\t\t\tif (args != null) {\n\t\t\t\tallExpr.addAll(args.args());\n\t\t\t}\n\t\t\tLocation loc = new Location(expr, args == null ? expr : args);\n\t\t\treturn new AbsArgs(loc, allExpr);\n\t\t}\n\n\t\tcase Stmts:\n\t\tcase StmtsRest: {\n\t\t\tif (node.numSubtrees() == 0) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tVector allStmts = new Vector();\n\t\t\tAbsStmt stmt = (AbsStmt) node.subtree(0).accept(this, null);\n\t\t\tallStmts.add(stmt);\n\t\t\tAbsStmts stmts = (AbsStmts) node.subtree(1).accept(this, null);\n\t\t\tif (stmts != null) {\n\t\t\t\tallStmts.addAll(stmts.stmts());\n\t\t\t}\n\t\t\tLocation loc = new Location(stmt, stmts == null ? stmt : stmts);\n\t\t\treturn new AbsStmts(loc, allStmts);\n\n\t\t}\n\t\tcase Stmt: {\n\t\t\tif (node.numSubtrees() == 2) {\n\t\t\t\tAbsExpr expr = (AbsExpr) node.subtree(0).accept(this, null);\n\t\t\t\treturn node.subtree(1).accept(this, expr);\n\t\t\t}\n\n\t\t\tif (node.numSubtrees() == 3) {\n\t\t\t\tAbsExpr condition = (AbsExpr) node.subtree(1).accept(this, null);\n\t\t\t\tAbsStmts doStatements = (AbsStmts) node.subtree(2).accept(this, null);\n\t\t\t\tLocation loc = new Location((DerLeaf) node.subtree(0), doStatements);\n\t\t\t\treturn new AbsWhileStmt(loc, condition, doStatements);\n\t\t\t}\n\n\t\t\tif (node.numSubtrees() == 4) {\n\t\t\t\tAbsExpr condition = (AbsExpr) node.subtree(1).accept(this, null);\n\t\t\t\tAbsStmts thenStatements = (AbsStmts) node.subtree(2).accept(this, null);\n\t\t\t\tAbsStmts elseStatements = (AbsStmts) node.subtree(3).accept(this, null);\n\n\t\t\t\tif (elseStatements == null) {\n\t\t\t\t\tLocation loc = new Location((DerLeaf) node.subtree(0), thenStatements);\n\t\t\t\t\treturn new AbsIfStmt(loc, condition, thenStatements, EpsilonStmts());\n\t\t\t\t}\n\n\t\t\t\tLocation loc = new Location((DerLeaf) node.subtree(0), elseStatements);\n\t\t\t\treturn new AbsIfStmt(loc, condition, thenStatements, elseStatements);\n\t\t\t}\n\n\t\t}\n\n\t\tcase AssignEps: {\n\t\t\tif (node.numSubtrees() == 0) {\n\t\t\t\treturn new AbsExprStmt(visArg, (AbsExpr) visArg);\n\t\t\t}\n\t\t\tAbsExpr rightSide = (AbsExpr) node.subtree(0).accept(this, null);\n\n\t\t\tLocation loc = new Location(visArg, rightSide);\n\t\t\treturn new AbsAssignStmt(loc, (AbsExpr) visArg, rightSide);\n\t\t}\n\n\t\tcase ElseEps:\n\t\tcase WhereEps: {\n\t\t\tif (node.numSubtrees() == 0) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\treturn node.subtree(0).accept(this, null);\n\t\t}\n\n\t\t} // End Switch\n\n\t\treturn visArg;\n\n\t}\n\n\t// Helper function\n\tprivate AbsTree DeformParDecls(DerNode node) {\n\t\tif (node.numSubtrees() == 0) {\n\t\t\treturn new AbsParDecls(kNULL_LOCATION, new Vector());\n\t\t}\n\n\t\tVector allParDecls = new Vector();\n\t\tAbsParDecl parDecl = (AbsParDecl) node.subtree(0).accept(this, null);\n\t\tallParDecls.add(parDecl);\n\t\tAbsParDecls parDecls = (AbsParDecls) node.subtree(1).accept(this, null);\n\t\tif (parDecls != null) {\n\t\t\tallParDecls.addAll(parDecls.parDecls());\n\t\t}\n\n\t\tLocation loc = new Location(parDecl, parDecls.equals(kNULL_LOCATION) ? parDecl : parDecls);\n\t\treturn new AbsParDecls(loc, allParDecls);\n\t}\n\n\tprivate AbsTree DeformParDecl(DerNode node) {\n\t\tDerLeaf identifier = (DerLeaf) node.subtree(0);\n\t\tAbsType type = (AbsType) node.subtree(1).accept(this, null);\n\t\tLocation loc = new Location(identifier, type);\n\t\treturn new AbsParDecl(loc, identifier.symb.lexeme, type);\n\t}\n\n\t// Same function just other class\n\tprivate AbsTree DeformCompDecl(DerNode node) {\n\t\tDerLeaf identifier = (DerLeaf) node.subtree(0);\n\t\tAbsType type = (AbsType) node.subtree(1).accept(this, null);\n\t\tLocation loc = new Location(identifier, type);\n\t\treturn new AbsCompDecl(loc, identifier.symb.lexeme, type);\n\t}\n\n\tprivate AbsTree ExpressionTransform(DerNode node, AbsTree visArg) {\n\t\tif (node.numSubtrees() == 0) {\n\t\t\treturn visArg;\n\t\t}\n\n\t\tif (node.numSubtrees() == 1) {\n\t\t\treturn node.subtree(0).accept(this, null);\n\t\t}\n\t\tAbsExpr leftOperand = (AbsExpr) node.subtree(0).accept(this, null);\n\t\tAbsExpr rightOperand = (AbsExpr) node.subtree(1).accept(this, leftOperand);\n\t\treturn rightOperand;\n\t}\n\n\tprivate AbsTree Epsilon() {\n\t\t// Hacky try to find other expr that is not abstrac and has less field\n\t\treturn new AbsAtomExpr(kNULL_LOCATION, AbsAtomExpr.Type.VOID, \"\");\n\t}\n\n\tprivate AbsArgs EpsilonArgs() {\n\t\treturn new AbsArgs(kNULL_LOCATION, new Vector());\n\t}\n\n\tprivate AbsDecls EpsilonDecls() {\n\t\treturn new AbsDecls(kNULL_LOCATION, new Vector());\n\t}\n\n\tprivate AbsStmts EpsilonStmts() {\n\t\treturn new AbsStmts(kNULL_LOCATION, new Vector());\n\t}\n\n\tprivate Map kTermToBinOper = new HashMap() {\n\t\t{\n\t\t\tput(Term.IOR, AbsBinExpr.Oper.IOR);\n\t\t\tput(Term.XOR, AbsBinExpr.Oper.XOR);\n\t\t\tput(Term.AND, AbsBinExpr.Oper.AND);\n\t\t\tput(Term.EQU, AbsBinExpr.Oper.EQU);\n\t\t\tput(Term.NEQ, AbsBinExpr.Oper.NEQ);\n\t\t\tput(Term.LTH, AbsBinExpr.Oper.LTH);\n\t\t\tput(Term.GTH, AbsBinExpr.Oper.GTH);\n\t\t\tput(Term.LEQ, AbsBinExpr.Oper.LEQ);\n\t\t\tput(Term.GEQ, AbsBinExpr.Oper.GEQ);\n\t\t\tput(Term.ADD, AbsBinExpr.Oper.ADD);\n\t\t\tput(Term.SUB, AbsBinExpr.Oper.SUB);\n\t\t\tput(Term.MUL, AbsBinExpr.Oper.MUL);\n\t\t\tput(Term.DIV, AbsBinExpr.Oper.DIV);\n\t\t\tput(Term.MOD, AbsBinExpr.Oper.MOD);\n\n\t\t}\n\t};\n\n\tprivate Map kTermToUnarOper = new HashMap() {\n\t\t{\n\t\t\tput(Term.NOT, AbsUnExpr.Oper.NOT);\n\t\t\tput(Term.ADDR, AbsUnExpr.Oper.ADDR);\n\t\t\tput(Term.DATA, AbsUnExpr.Oper.DATA);\n\t\t\tput(Term.ADD, AbsUnExpr.Oper.ADD);\n\t\t\tput(Term.SUB, AbsUnExpr.Oper.SUB);\n\n\t\t}\n\t};\n\n\tprivate Map kTermToLitType = new HashMap() {\n\t\t{\n\t\t\tput(Term.VOIDCONST, AbsAtomExpr.Type.VOID);\n\t\t\tput(Term.BOOLCONST, AbsAtomExpr.Type.BOOL);\n\t\t\tput(Term.PTRCONST, AbsAtomExpr.Type.PTR);\n\t\t\tput(Term.INTCONST, AbsAtomExpr.Type.INT);\n\t\t\tput(Term.CHARCONST, AbsAtomExpr.Type.CHAR);\n\t\t\tput(Term.STRCONST, AbsAtomExpr.Type.STR);\n\n\t\t}\n\t};\n}\n"},"new_file":{"kind":"string","value":"PREV/prev/srcs/compiler/phases/abstr/AbsTreeConstructor.java"},"old_contents":{"kind":"string","value":"/**\n * @author sliva\n */\npackage compiler.phases.abstr;\n\nimport java.util.*;\nimport compiler.common.report.*;\nimport compiler.data.dertree.*;\nimport compiler.data.dertree.DerNode.Nont;\nimport compiler.data.dertree.visitor.*;\nimport compiler.data.symbol.Symbol.Term;\nimport compiler.data.abstree.*;\nimport compiler.data.abstree.AbsBinExpr.Oper;\n\n/**\n * Transforms a derivation tree to an abstract syntax tree.\n * \n * @author sliva\n */\npublic class AbsTreeConstructor implements DerVisitor {\n\n\tprivate final String PTR_NODE = \"Expected PTR node\";\n\tprivate final String ARR_NODE = \"Expected ARR node\";\n\tprivate final String GOT_STR = \" got: \";\n\tprivate final String TOO_MANY_NODES = \"There are zore or more than 3 nodes\";\n\tprivate final String DECL_NODE = \"Declaration node doesn't start with TYP, FUN or VAR\";\n\tprivate final String WRONG_BINARY_NODE = \"This binary operator doesn't exist.\";\n\tprivate final Location kNULL_LOCATION = new Location(0, 0);\n\n\t@Override\n\tpublic AbsTree visit(DerLeaf leaf, AbsTree visArg) {\n\t\tthrow new Report.InternalError();\n\t}\n\n\t@Override\n\tpublic AbsTree visit(DerNode node, AbsTree visArg) {\n\t\tswitch (node.label) {\n\n\t\tcase Source: {\n\t\t\tAbsDecls decls = (AbsDecls) node.subtree(0).accept(this, null);\n\t\t\treturn new AbsSource(decls, decls);\n\t\t}\n\n\t\tcase Decls:\n\t\tcase DeclsRest: {\n\t\t\tif (node.numSubtrees() == 0)\n\t\t\t\treturn null;\n\t\t\tVector allDecls = new Vector();\n\t\t\tAbsDecl decl = (AbsDecl) node.subtree(0).accept(this, null);\n\t\t\tallDecls.add(decl);\n\t\t\tAbsDecls decls = (AbsDecls) node.subtree(1).accept(this, null);\n\t\t\tif (decls != null)\n\t\t\t\tallDecls.addAll(decls.decls());\n\t\t\treturn new AbsDecls(new Location(decl, decls == null ? decl : decls), allDecls);\n\t\t}\n\n\t\tcase Decl: {\n\t\t\tDerLeaf typeOfDecleration = (DerLeaf) node.subtree(0);\n\t\t\tswitch (typeOfDecleration.symb.token) {\n\t\t\tcase VAR: {\n\t\t\t\tAbsParDecl parDecl = (AbsParDecl) node.subtree(1).accept(this, null);\n\t\t\t\tLocation loc = new Location(typeOfDecleration, parDecl);\n\t\t\t\treturn new AbsVarDecl(loc, parDecl.name, parDecl.type);\n\t\t\t}\n\n\t\t\tcase TYP: {\n\t\t\t\tAbsParDecl parDecl = (AbsParDecl) node.subtree(1).accept(this, null);\n\t\t\t\tLocation loc = new Location(typeOfDecleration, parDecl);\n\t\t\t\treturn new AbsTypDecl(loc, parDecl.name, parDecl.type);\n\t\t\t}\n\n\t\t\tcase FUN: {\n\t\t\t\tDerLeaf funName = (DerLeaf) node.subtree(1);\n\t\t\t\tAbsParDecls parDecls = (AbsParDecls) node.subtree(2).accept(this, null);\n\t\t\t\tAbsType type = (AbsType) node.subtree(3).accept(this, null);\n\t\t\t\tAbsExpr expr = (AbsExpr) node.subtree(4).accept(this, null);\n\n\t\t\t\tif (expr.location().equals(kNULL_LOCATION)) {\n\t\t\t\t\tLocation loc = new Location(typeOfDecleration, type);\n\t\t\t\t\treturn new AbsFunDecl(loc, funName.symb.lexeme, parDecls, type);\n\t\t\t\t} else {\n\t\t\t\t\tLocation loc = new Location(typeOfDecleration, expr);\n\t\t\t\t\treturn new AbsFunDef(loc, funName.symb.lexeme, parDecls, type, expr);\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tdefault:\n\t\t\t\tthrow new Report.Error(typeOfDecleration.location(),\n\t\t\t\t\t\tDECL_NODE + GOT_STR + typeOfDecleration.symb.token.toString());\n\t\t\t}\n\t\t}\n\n\t\tcase ParDecl: {\n\t\t\treturn DeformParDecl(node);\n\t\t}\n\n\t\tcase Type: {\n\t\t\tif (node.numSubtrees() == 1) {\n\n\t\t\t\t// This is only check for ( Type )\n\t\t\t\tif (node.subtree(0) instanceof DerNode) {\n\t\t\t\t\treturn node.subtree(0).accept(this, null);\n\t\t\t\t} else if (node.subtree(0) instanceof DerLeaf) {\n\t\t\t\t\tDerLeaf primitiveTypeNode = (DerLeaf) node.subtree(0);\n\t\t\t\t\tAbsAtomType.Type primitiveType;\n\t\t\t\t\tswitch (primitiveTypeNode.symb.token) {\n\t\t\t\t\tcase VOID:\n\t\t\t\t\t\tprimitiveType = AbsAtomType.Type.VOID;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase BOOL:\n\t\t\t\t\t\tprimitiveType = AbsAtomType.Type.BOOL;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase CHAR:\n\t\t\t\t\t\tprimitiveType = AbsAtomType.Type.CHAR;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase INT:\n\t\t\t\t\t\tprimitiveType = AbsAtomType.Type.INT;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tdefault:\n\t\t\t\t\t\t// TODO: Error (Maybe)\n\t\t\t\t\t\treturn new AbsTypName(primitiveTypeNode.location(), primitiveTypeNode.symb.lexeme);\n\t\t\t\t\t}\n\n\t\t\t\t\treturn new AbsAtomType(primitiveTypeNode.location(), primitiveType);\n\t\t\t\t}\n\t\t\t} else if (node.numSubtrees() == 2) {\n\t\t\t\tDerLeaf ptr = (DerLeaf) node.subtree(0);\n\t\t\t\tif (ptr.symb.token == Term.PTR) {\n\t\t\t\t\tAbsType subType = (AbsType) node.subtree(1).accept(this, null);\n\t\t\t\t\tLocation loc = new Location(ptr, subType);\n\t\t\t\t\treturn new AbsPtrType(loc, subType);\n\t\t\t\t} else if (ptr.symb.token == Term.REC) {\n\t\t\t\t\tAbsCompDecls compDecls = (AbsCompDecls) node.subtree(1).accept(this, null);\n\t\t\t\t\tLocation loc = new Location(ptr, compDecls);\n\t\t\t\t\treturn new AbsRecType(loc, compDecls);\n\t\t\t\t} else {\n\t\t\t\t\tthrow new Report.Error(ptr.location(), PTR_NODE + GOT_STR + ptr.symb.token.toString());\n\t\t\t\t}\n\n\t\t\t} else if (node.numSubtrees() == 3) {\n\t\t\t\tDerLeaf arr = (DerLeaf) node.subtree(0);\n\t\t\t\tif (arr.symb.token != Term.ARR) {\n\t\t\t\t\tthrow new Report.Error(arr.location(), ARR_NODE + GOT_STR + arr.symb.token.toString());\n\t\t\t\t}\n\n\t\t\t\tAbsExpr length = (AbsExpr) node.subtree(1).accept(this, null);\n\t\t\t\tAbsType elemType = (AbsType) node.subtree(2).accept(this, null);\n\t\t\t\tLocation loc = new Location(arr, elemType);\n\t\t\t\treturn new AbsArrType(loc, length, elemType);\n\n\t\t\t} else {\n\t\t\t\tthrow new Report.Error(node.location(), TOO_MANY_NODES + GOT_STR + node.numSubtrees());\n\t\t\t}\n\t\t}\n\n\t\tcase ParDecls: {\n\t\t\treturn DeformParDecls(node);\n\t\t}\n\n\t\tcase ParDeclsRest: {\n\t\t\treturn DeformParDecls(node);\n\t\t}\n\n\t\tcase BodyEps: {\n\t\t\tif (node.numSubtrees() == 0) {\n\t\t\t\t// Hacky try to find other expr that is not abstrac and has less field\n\t\t\t\treturn Epsilon();\n\t\t\t}\n\n\t\t\treturn node.subtree(1).accept(this, null);\n\t\t}\n\n\t\tcase CompDecls:\n\t\tcase CompDeclsRest: {\n\t\t\tif (node.numSubtrees() == 0) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tVector allCompDecls = new Vector();\n\t\t\tAbsCompDecl compDecl = (AbsCompDecl) node.subtree(0).accept(this, null);\n\t\t\tallCompDecls.add(compDecl);\n\t\t\tAbsCompDecls compDecls = (AbsCompDecls) node.subtree(1).accept(this, null);\n\t\t\tif (compDecls != null) {\n\t\t\t\tallCompDecls.addAll(compDecls.compDecls());\n\t\t\t}\n\t\t\tLocation loc = new Location(compDecl, compDecls == null ? compDecl : compDecls);\n\t\t\treturn new AbsCompDecls(loc, allCompDecls);\n\t\t}\n\n\t\tcase CompDecl: {\n\t\t\treturn DeformCompDecl(node);\n\t\t}\n\n\t\tcase Expr:\n\t\tcase DisjExpr:\n\t\tcase ConjExpr:\n\t\tcase RelExpr:\n\t\tcase AddExpr:\n\t\tcase MulExpr: {\n\t\t\treturn ExpressionTransform(node, visArg);\n\t\t}\n\n\t\tcase DisjExprRest:\n\t\tcase ConjExprRest:\n\t\tcase AddExprRest:\n\t\tcase MulExprRest: {\n\t\t\tif (node.numSubtrees() == 0) {\n\t\t\t\treturn visArg;\n\t\t\t}\n\n\t\t\tDerLeaf operatorNode = (DerLeaf) node.subtree(0);\n\t\t\tAbsBinExpr.Oper oper = kTermToBinOper.get(operatorNode.symb.token);\n\t\t\tif (oper == null) {\n\t\t\t\tthrow new Report.Error(node.location(), WRONG_BINARY_NODE + GOT_STR + node.numSubtrees());\n\t\t\t}\n\n\t\t\tAbsExpr leftOperand = (AbsExpr) node.subtree(1).accept(this, null);\n\t\t\tLocation loc = new Location(visArg, leftOperand);\n\t\t\tAbsBinExpr binExpr = new AbsBinExpr(loc, oper, (AbsExpr) visArg, leftOperand);\n\n\t\t\tAbsExpr rightOperand = (AbsExpr) node.subtree(2).accept(this, binExpr);\n\t\t\t// rightOperand.location());\n\t\t\treturn rightOperand;\n\n\t\t}\n\n\t\tcase RelExprRest: {\n\t\t\tif (node.numSubtrees() == 0) {\n\t\t\t\treturn visArg;\n\t\t\t}\n\n\t\t\tDerLeaf operatorNode = (DerLeaf) node.subtree(0);\n\t\t\tAbsBinExpr.Oper oper = kTermToBinOper.get(operatorNode.symb.token);\n\t\t\tif (oper == null) {\n\t\t\t\tthrow new Report.Error(node.location(), WRONG_BINARY_NODE + GOT_STR + node.numSubtrees());\n\t\t\t}\n\n\t\t\tAbsExpr leftOperand = (AbsExpr) node.subtree(1).accept(this, null);\n\t\t\tLocation loc = new Location(visArg, leftOperand);\n\t\t\treturn new AbsBinExpr(loc, oper, (AbsExpr) visArg, leftOperand);\n\t\t}\n\n\t\tcase PrefExpr: {\n\t\t\tif (node.subtree(0) instanceof DerLeaf) {\n\t\t\t\tDerLeaf operatorNode = (DerLeaf) node.subtree(0);\n\t\t\t\tAbsUnExpr.Oper oper = kTermToUnarOper.get(operatorNode.symb.token);\n\n\t\t\t\tif (oper != null) {\n\t\t\t\t\tAbsExpr subExpr = (AbsExpr) node.subtree(1).accept(this, null);\n\t\t\t\t\tLocation loc = new Location(operatorNode, subExpr);\n\t\t\t\t\treturn new AbsUnExpr(loc, oper, subExpr);\n\t\t\t\t}\n\n\t\t\t\tif (operatorNode.symb.token == Term.NEW) {\n\t\t\t\t\tAbsType type = (AbsType) node.subtree(1).accept(this, null);\n\t\t\t\t\tLocation loc = new Location(operatorNode, type);\n\t\t\t\t\treturn new AbsNewExpr(loc, type);\n\t\t\t\t}\n\n\t\t\t\tif (operatorNode.symb.token == Term.DEL) {\n\t\t\t\t\tAbsExpr expr = (AbsExpr) node.subtree(1).accept(this, null);\n\t\t\t\t\tLocation loc = new Location(operatorNode, expr);\n\t\t\t\t\treturn new AbsDelExpr(loc, expr);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tDerNode exprNode = (DerNode) node.subtree(0);\n\t\t\t\tAbsExpr expr = (AbsExpr) exprNode.accept(this, null);\n\t\t\t\tif (exprNode.label == Nont.Expr) {\n\t\t\t\t\treturn node.subtree(1).accept(this, expr);\n\t\t\t\t} else if (exprNode.label == Nont.PstfExpr) {\n\t\t\t\t\treturn node.subtree(1).accept(this, expr);\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\n\t\tcase PstfExprRest: {\n\t\t\tif (node.numSubtrees() == 0) {\n\t\t\t\treturn visArg;\n\t\t\t}\n\n\t\t\tif (node.subtree(0) instanceof DerLeaf) {\n\t\t\t\tDerLeaf varNode = (DerLeaf) node.subtree(0);\n\t\t\t\tAbsVarName varName = new AbsVarName(varNode, varNode.symb.lexeme);\n\t\t\t\tLocation loc = new Location(visArg, varName);\n\t\t\t\tAbsRecExpr recordExpr = new AbsRecExpr(loc, (AbsExpr) visArg, varName);\n\t\t\t\treturn node.subtree(1).accept(this, recordExpr);\n\t\t\t} else {\n\t\t\t\tAbsExpr index = (AbsExpr) node.subtree(0).accept(this, null);\n\t\t\t\tLocation loc = new Location(visArg, index);\n\t\t\t\tAbsArrExpr arrExpr = new AbsArrExpr(loc, (AbsExpr) visArg, index);\n\t\t\t\treturn node.subtree(1).accept(this, arrExpr);\n\t\t\t}\n\t\t}\n\n\t\tcase PstfExpr: {\n\t\t\treturn node.subtree(0).accept(this, null);\n\t\t}\n\n\t\tcase AtomExpr: {\n\t\t\tif (node.numSubtrees() == 1) {\n\t\t\t\treturn node.subtree(0).accept(this, null);\n\t\t\t}\n\n\t\t\tif (node.numSubtrees() == 2) {\n\t\t\t\tboolean isNull = node.subtree(1).accept(this, null) instanceof AbsAtomExpr\n\t\t\t\t\t\t&& node.subtree(1).accept(this, null).location().equals(kNULL_LOCATION);\n\t\t\t\tif (isNull) {\n\t\t\t\t\tDerLeaf varName = (DerLeaf) node.subtree(0);\n\t\t\t\t\tLocation loc = new Location(varName, varName);\n\t\t\t\t\treturn new AbsVarName(loc, varName.symb.lexeme);\n\t\t\t\t} else {\n\t\t\t\t\tAbsArgs funArgs = (AbsArgs) node.subtree(1).accept(this, null);\n\t\t\t\t\tDerLeaf funName = (DerLeaf) node.subtree(0);\n\t\t\t\t\tLocation loc = new Location(funName, funArgs);\n\t\t\t\t\treturn new AbsFunName(loc, funName.symb.lexeme, funArgs);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (node.numSubtrees() == 3) {\n\t\t\t\tAbsStmts statements = (AbsStmts) node.subtree(0).accept(this, null);\n\t\t\t\tAbsExpr expr = (AbsExpr) node.subtree(1).accept(this, null);\n\t\t\t\tAbsDecls decls = (AbsDecls) node.subtree(2).accept(this, null);\n\n\t\t\t\tif (decls == null) {\n\t\t\t\t\tLocation loc = new Location(statements, expr);\n\t\t\t\t\treturn new AbsBlockExpr(loc, EpsilonDecls(), statements, expr);\n\t\t\t\t}\n\n\t\t\t\tLocation loc = new Location(statements, decls);\n\t\t\t\treturn new AbsBlockExpr(loc, decls, statements, expr);\n\t\t\t}\n\t\t}\n\t\tcase Literal: {\n\t\t\tDerLeaf literal = (DerLeaf) node.subtree(0);\n\t\t\treturn new AbsAtomExpr(literal, kTermToLitType.get(literal.symb.token), literal.symb.lexeme);\n\t\t}\n\n\t\tcase CastEps: {\n\t\t\tif (node.numSubtrees() == 0) {\n\t\t\t\treturn visArg;\n\t\t\t}\n\n\t\t\tAbsType type = (AbsType) node.subtree(0).accept(this, null);\n\t\t\t// Double check this for location\n\t\t\tLocation loc = new Location(visArg, type);\n\t\t\treturn new AbsCastExpr(loc, (AbsExpr) visArg, type);\n\t\t}\n\n\t\tcase CallEps:\n\t\t\tif (node.numSubtrees() == 0) {\n\t\t\t\treturn Epsilon();\n\t\t\t}\n\n\t\t\treturn node.subtree(0).accept(this, null);\n\t\tcase Args: {\n\t\t\tif (node.numSubtrees() == 0) {\n\t\t\t\treturn EpsilonArgs();\n\t\t\t}\n\n\t\t\treturn node.subtree(0).accept(this, null);\n\t\t}\n\n\t\tcase ArgsEps:\n\t\tcase ArgsRest: {\n\t\t\tif (node.numSubtrees() == 0) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tVector allExpr = new Vector();\n\t\t\tAbsExpr expr = (AbsExpr) node.subtree(0).accept(this, null);\n\t\t\tallExpr.add(expr);\n\t\t\tAbsArgs args = (AbsArgs) node.subtree(1).accept(this, null);\n\t\t\tif (args != null) {\n\t\t\t\tallExpr.addAll(args.args());\n\t\t\t}\n\t\t\tLocation loc = new Location(expr, args == null ? expr : args);\n\t\t\treturn new AbsArgs(loc, allExpr);\n\t\t}\n\n\t\tcase Stmts:\n\t\tcase StmtsRest: {\n\t\t\tif (node.numSubtrees() == 0) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tVector allStmts = new Vector();\n\t\t\tAbsStmt stmt = (AbsStmt) node.subtree(0).accept(this, null);\n\t\t\tallStmts.add(stmt);\n\t\t\tAbsStmts stmts = (AbsStmts) node.subtree(1).accept(this, null);\n\t\t\tif (stmts != null) {\n\t\t\t\tallStmts.addAll(stmts.stmts());\n\t\t\t}\n\t\t\tLocation loc = new Location(stmt, stmts == null ? stmt : stmts);\n\t\t\treturn new AbsStmts(loc, allStmts);\n\n\t\t}\n\t\tcase Stmt: {\n\t\t\tif (node.numSubtrees() == 2) {\n\t\t\t\tAbsExpr expr = (AbsExpr) node.subtree(0).accept(this, null);\n\t\t\t\treturn node.subtree(1).accept(this, expr);\n\t\t\t}\n\n\t\t\tif (node.numSubtrees() == 3) {\n\t\t\t\tAbsExpr condition = (AbsExpr) node.subtree(1).accept(this, null);\n\t\t\t\tAbsStmts doStatements = (AbsStmts) node.subtree(2).accept(this, null);\n\t\t\t\tLocation loc = new Location((DerLeaf) node.subtree(0), doStatements);\n\t\t\t\treturn new AbsWhileStmt(loc, condition, doStatements);\n\t\t\t}\n\n\t\t\tif (node.numSubtrees() == 4) {\n\t\t\t\tAbsExpr condition = (AbsExpr) node.subtree(1).accept(this, null);\n\t\t\t\tAbsStmts thenStatements = (AbsStmts) node.subtree(2).accept(this, null);\n\t\t\t\tAbsStmts elseStatements = (AbsStmts) node.subtree(3).accept(this, null);\n\n\t\t\t\tif (elseStatements == null) {\n\t\t\t\t\tLocation loc = new Location((DerLeaf) node.subtree(0), thenStatements);\n\t\t\t\t\treturn new AbsIfStmt(loc, condition, thenStatements, EpsilonStmts());\n\t\t\t\t}\n\n\t\t\t\tLocation loc = new Location((DerLeaf) node.subtree(0), elseStatements);\n\t\t\t\treturn new AbsIfStmt(loc, condition, thenStatements, elseStatements);\n\t\t\t}\n\n\t\t}\n\n\t\tcase AssignEps: {\n\t\t\tif (node.numSubtrees() == 0) {\n\t\t\t\treturn new AbsExprStmt(visArg, (AbsExpr) visArg);\n\t\t\t}\n\t\t\tAbsExpr rightSide = (AbsExpr) node.subtree(0).accept(this, null);\n\n\t\t\tLocation loc = new Location(visArg, rightSide);\n\t\t\treturn new AbsAssignStmt(loc, (AbsExpr) visArg, rightSide);\n\t\t}\n\n\t\tcase ElseEps:\n\t\tcase WhereEps: {\n\t\t\tif (node.numSubtrees() == 0) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\treturn node.subtree(0).accept(this, null);\n\t\t}\n\n\t\t} // End Switch\n\n\t\treturn visArg;\n\n\t}\n\n\t// Helper function\n\tprivate AbsTree DeformParDecls(DerNode node) {\n\t\tif (node.numSubtrees() == 0) {\n\t\t\treturn new AbsParDecls(kNULL_LOCATION, new Vector());\n\t\t}\n\n\t\tVector allParDecls = new Vector();\n\t\tAbsParDecl parDecl = (AbsParDecl) node.subtree(0).accept(this, null);\n\t\tallParDecls.add(parDecl);\n\t\tAbsParDecls parDecls = (AbsParDecls) node.subtree(1).accept(this, null);\n\t\tif (parDecls != null) {\n\t\t\tallParDecls.addAll(parDecls.parDecls());\n\t\t}\n\n\t\tLocation loc = new Location(parDecl, parDecls.equals(kNULL_LOCATION) ? parDecl : parDecls);\n\t\treturn new AbsParDecls(loc, allParDecls);\n\t}\n\n\tprivate AbsTree DeformParDecl(DerNode node) {\n\t\tDerLeaf identifier = (DerLeaf) node.subtree(0);\n\t\tAbsType type = (AbsType) node.subtree(1).accept(this, null);\n\t\tLocation loc = new Location(identifier, type);\n\t\treturn new AbsParDecl(loc, identifier.symb.lexeme, type);\n\t}\n\n\t// Same function just other class\n\tprivate AbsTree DeformCompDecl(DerNode node) {\n\t\tDerLeaf identifier = (DerLeaf) node.subtree(0);\n\t\tAbsType type = (AbsType) node.subtree(1).accept(this, null);\n\t\tLocation loc = new Location(identifier, type);\n\t\treturn new AbsCompDecl(loc, identifier.symb.lexeme, type);\n\t}\n\n\tprivate AbsTree ExpressionTransform(DerNode node, AbsTree visArg) {\n\t\tif (node.numSubtrees() == 0) {\n\t\t\treturn visArg;\n\t\t}\n\n\t\tif (node.numSubtrees() == 1) {\n\t\t\treturn node.subtree(0).accept(this, null);\n\t\t}\n\t\tAbsExpr leftOperand = (AbsExpr) node.subtree(0).accept(this, null);\n\t\tAbsExpr rightOperand = (AbsExpr) node.subtree(1).accept(this, leftOperand);\n\t\treturn rightOperand;\n\t}\n\n\tprivate AbsTree Epsilon() {\n\t\t// Hacky try to find other expr that is not abstrac and has less field\n\t\treturn new AbsAtomExpr(kNULL_LOCATION, AbsAtomExpr.Type.VOID, \"\");\n\t}\n\n\tprivate AbsArgs EpsilonArgs() {\n\t\treturn new AbsArgs(kNULL_LOCATION, new Vector());\n\t}\n\n\tprivate AbsDecls EpsilonDecls() {\n\t\treturn new AbsDecls(kNULL_LOCATION, new Vector());\n\t}\n\n\tprivate AbsStmts EpsilonStmts() {\n\t\treturn new AbsStmts(kNULL_LOCATION, new Vector());\n\t}\n\n\tprivate Map kTermToBinOper = new HashMap() {\n\t\t{\n\t\t\tput(Term.IOR, AbsBinExpr.Oper.IOR);\n\t\t\tput(Term.XOR, AbsBinExpr.Oper.XOR);\n\t\t\tput(Term.AND, AbsBinExpr.Oper.AND);\n\t\t\tput(Term.EQU, AbsBinExpr.Oper.EQU);\n\t\t\tput(Term.NEQ, AbsBinExpr.Oper.NEQ);\n\t\t\tput(Term.LTH, AbsBinExpr.Oper.LTH);\n\t\t\tput(Term.GTH, AbsBinExpr.Oper.GTH);\n\t\t\tput(Term.LEQ, AbsBinExpr.Oper.LEQ);\n\t\t\tput(Term.GEQ, AbsBinExpr.Oper.GEQ);\n\t\t\tput(Term.ADD, AbsBinExpr.Oper.ADD);\n\t\t\tput(Term.SUB, AbsBinExpr.Oper.SUB);\n\t\t\tput(Term.MUL, AbsBinExpr.Oper.MUL);\n\t\t\tput(Term.DIV, AbsBinExpr.Oper.DIV);\n\t\t\tput(Term.MOD, AbsBinExpr.Oper.MOD);\n\n\t\t}\n\t};\n\n\tprivate Map kTermToUnarOper = new HashMap() {\n\t\t{\n\t\t\tput(Term.NOT, AbsUnExpr.Oper.NOT);\n\t\t\tput(Term.ADDR, AbsUnExpr.Oper.ADDR);\n\t\t\tput(Term.DATA, AbsUnExpr.Oper.DATA);\n\t\t\tput(Term.ADD, AbsUnExpr.Oper.ADD);\n\t\t\tput(Term.SUB, AbsUnExpr.Oper.SUB);\n\n\t\t}\n\t};\n\n\tprivate Map kTermToLitType = new HashMap() {\n\t\t{\n\t\t\tput(Term.VOIDCONST, AbsAtomExpr.Type.VOID);\n\t\t\tput(Term.BOOLCONST, AbsAtomExpr.Type.BOOL);\n\t\t\tput(Term.PTRCONST, AbsAtomExpr.Type.PTR);\n\t\t\tput(Term.INTCONST, AbsAtomExpr.Type.INT);\n\t\t\tput(Term.CHARCONST, AbsAtomExpr.Type.CHAR);\n\t\t\tput(Term.STRCONST, AbsAtomExpr.Type.STR);\n\n\t\t}\n\t};\n}\n"},"message":{"kind":"string","value":"PREV - Abstr : Right position of function arguments\n"},"old_file":{"kind":"string","value":"PREV/prev/srcs/compiler/phases/abstr/AbsTreeConstructor.java"},"subject":{"kind":"string","value":"PREV - Abstr : Right position of function arguments"},"git_diff":{"kind":"string","value":"REV/prev/srcs/compiler/phases/abstr/AbsTreeConstructor.java\n \t\t\t\t} else {\n \t\t\t\t\tAbsArgs funArgs = (AbsArgs) node.subtree(1).accept(this, null);\n \t\t\t\t\tDerLeaf funName = (DerLeaf) node.subtree(0);\n\t\t\t\t\tLocation loc = new Location(funName, funArgs);\n\t\t\t\t\tLocation loc = new Location(funName, funArgs.args().size() != 0 ? funArgs : funName);\n \t\t\t\t\treturn new AbsFunName(loc, funName.symb.lexeme, funArgs);\n \t\t\t\t}\n \t\t\t}"}}},{"rowIdx":886,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"agpl-3.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"e80647ee8c6e404f442028ca41e4372c771434e4"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"poum/libreplan,dgray16/libreplan,Marine-22/libre,LibrePlan/libreplan,poum/libreplan,LibrePlan/libreplan,skylow95/libreplan,Marine-22/libre,skylow95/libreplan,dgray16/libreplan,PaulLuchyn/libreplan,LibrePlan/libreplan,LibrePlan/libreplan,LibrePlan/libreplan,dgray16/libreplan,PaulLuchyn/libreplan,PaulLuchyn/libreplan,dgray16/libreplan,PaulLuchyn/libreplan,skylow95/libreplan,Marine-22/libre,poum/libreplan,Marine-22/libre,skylow95/libreplan,poum/libreplan,PaulLuchyn/libreplan,dgray16/libreplan,poum/libreplan,skylow95/libreplan,dgray16/libreplan,Marine-22/libre,skylow95/libreplan,PaulLuchyn/libreplan,LibrePlan/libreplan,LibrePlan/libreplan,PaulLuchyn/libreplan,Marine-22/libre,poum/libreplan,dgray16/libreplan"},"new_contents":{"kind":"string","value":"/*\n * This file is part of LibrePlan\n *\n * Copyright (C) 2009-2010 Fundación para o Fomento da Calidade Industrial e\n * Desenvolvemento Tecnolóxico de Galicia\n * Copyright (C) 2010-2012 Igalia, S.L.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see .\n */\n\npackage org.libreplan.web.planner;\n\nimport static org.libreplan.web.I18nHelper._;\nimport static org.libreplan.web.common.Util.addCurrencySymbol;\nimport static org.zkoss.ganttz.data.constraint.ConstraintOnComparableValues.biggerOrEqualThan;\nimport static org.zkoss.ganttz.data.constraint.ConstraintOnComparableValues.equalTo;\nimport static org.zkoss.ganttz.data.constraint.ConstraintOnComparableValues.lessOrEqualThan;\n\nimport java.math.BigDecimal;\nimport java.math.RoundingMode;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.Date;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\nimport org.apache.commons.lang.StringUtils;\nimport org.apache.commons.lang.Validate;\nimport org.apache.commons.lang.math.Fraction;\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\nimport org.joda.time.Days;\nimport org.joda.time.Duration;\nimport org.joda.time.LocalDate;\nimport org.joda.time.Seconds;\nimport org.libreplan.business.calendars.entities.BaseCalendar;\nimport org.libreplan.business.common.IAdHocTransactionService;\nimport org.libreplan.business.common.IOnTransaction;\nimport org.libreplan.business.common.daos.IConfigurationDAO;\nimport org.libreplan.business.common.entities.ProgressType;\nimport org.libreplan.business.externalcompanies.daos.IExternalCompanyDAO;\nimport org.libreplan.business.labels.entities.Label;\nimport org.libreplan.business.orders.daos.IOrderElementDAO;\nimport org.libreplan.business.orders.entities.Order;\nimport org.libreplan.business.orders.entities.OrderElement;\nimport org.libreplan.business.orders.entities.OrderStatusEnum;\nimport org.libreplan.business.orders.entities.SumChargedEffort;\nimport org.libreplan.business.orders.entities.SumExpenses;\nimport org.libreplan.business.planner.daos.IResourceAllocationDAO;\nimport org.libreplan.business.planner.daos.ITaskElementDAO;\nimport org.libreplan.business.planner.entities.Dependency;\nimport org.libreplan.business.planner.entities.Dependency.Type;\nimport org.libreplan.business.planner.entities.GenericResourceAllocation;\nimport org.libreplan.business.planner.entities.IMoneyCostCalculator;\nimport org.libreplan.business.planner.entities.ITaskPositionConstrained;\nimport org.libreplan.business.planner.entities.MoneyCostCalculator;\nimport org.libreplan.business.planner.entities.PositionConstraintType;\nimport org.libreplan.business.planner.entities.ResourceAllocation;\nimport org.libreplan.business.planner.entities.ResourceAllocation.Direction;\nimport org.libreplan.business.planner.entities.SpecificResourceAllocation;\nimport org.libreplan.business.planner.entities.Task;\nimport org.libreplan.business.planner.entities.TaskElement;\nimport org.libreplan.business.planner.entities.TaskElement.IDatesHandler;\nimport org.libreplan.business.planner.entities.TaskGroup;\nimport org.libreplan.business.planner.entities.TaskPositionConstraint;\nimport org.libreplan.business.resources.daos.ICriterionDAO;\nimport org.libreplan.business.resources.daos.IResourcesSearcher;\nimport org.libreplan.business.resources.entities.Criterion;\nimport org.libreplan.business.resources.entities.Resource;\nimport org.libreplan.business.scenarios.entities.Scenario;\nimport org.libreplan.business.workingday.EffortDuration;\nimport org.libreplan.business.workingday.IntraDayDate;\nimport org.libreplan.business.workingday.IntraDayDate.PartialDay;\nimport org.libreplan.web.planner.order.PlanningStateCreator.PlanningState;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.beans.factory.config.BeanDefinition;\nimport org.springframework.context.annotation.Scope;\nimport org.springframework.stereotype.Component;\nimport org.zkoss.ganttz.IDatesMapper;\nimport org.zkoss.ganttz.ProjectStatusEnum;\nimport org.zkoss.ganttz.adapters.DomainDependency;\nimport org.zkoss.ganttz.adapters.IAdapterToTaskFundamentalProperties;\nimport org.zkoss.ganttz.data.DependencyType;\nimport org.zkoss.ganttz.data.GanttDate;\nimport org.zkoss.ganttz.data.GanttDate.Cases;\nimport org.zkoss.ganttz.data.GanttDate.CustomDate;\nimport org.zkoss.ganttz.data.GanttDate.LocalDateBased;\nimport org.zkoss.ganttz.data.ITaskFundamentalProperties;\nimport org.zkoss.ganttz.data.constraint.Constraint;\nimport org.zkoss.ganttz.util.ReentranceGuard;\nimport org.zkoss.ganttz.util.ReentranceGuard.IReentranceCases;\n\n/**\n * @author Óscar González Fernández \n * @author Manuel Rego Casasnovas \n */\n@Component\n@Scope(BeanDefinition.SCOPE_SINGLETON)\npublic class TaskElementAdapter {\n\n private static final Log LOG = LogFactory.getLog(TaskElementAdapter.class);\n\n public static List> getStartConstraintsFor(\n TaskElement taskElement, LocalDate orderInitDate) {\n if (taskElement instanceof ITaskPositionConstrained) {\n ITaskPositionConstrained task = (ITaskPositionConstrained) taskElement;\n TaskPositionConstraint startConstraint = task\n .getPositionConstraint();\n final PositionConstraintType constraintType = startConstraint\n .getConstraintType();\n switch (constraintType) {\n case AS_SOON_AS_POSSIBLE:\n if (orderInitDate != null) {\n return Collections\n .singletonList(biggerOrEqualThan(toGantt(orderInitDate)));\n }\n return Collections.emptyList();\n case START_IN_FIXED_DATE:\n return Collections\n .singletonList(equalTo(toGantt(startConstraint\n .getConstraintDate())));\n case START_NOT_EARLIER_THAN:\n return Collections\n .singletonList(biggerOrEqualThan(toGantt(startConstraint\n .getConstraintDate())));\n }\n }\n return Collections.emptyList();\n }\n\n public static List> getEndConstraintsFor(\n TaskElement taskElement, LocalDate deadline) {\n if (taskElement instanceof ITaskPositionConstrained) {\n ITaskPositionConstrained task = (ITaskPositionConstrained) taskElement;\n TaskPositionConstraint endConstraint = task.getPositionConstraint();\n PositionConstraintType type = endConstraint.getConstraintType();\n switch (type) {\n case AS_LATE_AS_POSSIBLE:\n if (deadline != null) {\n return Collections\n .singletonList(lessOrEqualThan(toGantt(deadline)));\n }\n case FINISH_NOT_LATER_THAN:\n GanttDate date = toGantt(endConstraint.getConstraintDate());\n return Collections.singletonList(lessOrEqualThan(date));\n }\n }\n return Collections.emptyList();\n }\n\n public static GanttDate toGantt(IntraDayDate date) {\n return toGantt(date, null);\n }\n\n public static GanttDate toGantt(IntraDayDate date,\n EffortDuration dayCapacity) {\n if (date == null) {\n return null;\n }\n if (dayCapacity == null) {\n // a sensible default\n dayCapacity = EffortDuration.hours(8);\n }\n return new GanttDateAdapter(date, dayCapacity);\n }\n\n public static GanttDate toGantt(LocalDate date) {\n if (date == null) {\n return null;\n }\n return GanttDate.createFrom(date);\n }\n\n public static IntraDayDate toIntraDay(GanttDate date) {\n if (date == null) {\n return null;\n }\n return date.byCases(new Cases(\n GanttDateAdapter.class) {\n\n @Override\n public IntraDayDate on(LocalDateBased localDate) {\n return IntraDayDate.startOfDay(localDate.getLocalDate());\n }\n\n @Override\n protected IntraDayDate onCustom(GanttDateAdapter customType) {\n return customType.date;\n }\n });\n }\n\n public IAdapterToTaskFundamentalProperties createForCompany(\n Scenario currentScenario) {\n Adapter result = new Adapter();\n result.useScenario(currentScenario);\n result.setPreventCalculateResourcesText(true);\n return result;\n }\n\n public IAdapterToTaskFundamentalProperties createForOrder(\n Scenario currentScenario, Order order, PlanningState planningState) {\n Adapter result = new Adapter(planningState);\n result.useScenario(currentScenario);\n result.setInitDate(asLocalDate(order.getInitDate()));\n result.setDeadline(asLocalDate(order.getDeadline()));\n return result;\n }\n\n private LocalDate asLocalDate(Date date) {\n return date != null ? LocalDate.fromDateFields(date) : null;\n }\n\n @Autowired\n private IAdHocTransactionService transactionService;\n\n private final ReentranceGuard reentranceGuard = new ReentranceGuard();\n\n @Autowired\n private IOrderElementDAO orderElementDAO;\n\n @Autowired\n private ITaskElementDAO taskDAO;\n\n @Autowired\n private ICriterionDAO criterionDAO;\n\n @Autowired\n private IResourceAllocationDAO resourceAllocationDAO;\n\n @Autowired\n private IExternalCompanyDAO externalCompanyDAO;\n\n @Autowired\n private IResourcesSearcher searcher;\n\n @Autowired\n private IConfigurationDAO configurationDAO;\n\n @Autowired\n private IMoneyCostCalculator moneyCostCalculator;\n\n static class GanttDateAdapter extends CustomDate {\n\n private static final int DAY_MILLISECONDS = (int) Days.days(1)\n .toStandardDuration().getMillis();\n\n private final IntraDayDate date;\n private final Duration workingDayDuration;\n\n GanttDateAdapter(IntraDayDate date, EffortDuration capacityForDay) {\n this.date = date;\n this.workingDayDuration = toMilliseconds(capacityForDay);\n }\n\n protected int compareToCustom(CustomDate customType) {\n if (customType instanceof GanttDateAdapter) {\n GanttDateAdapter other = (GanttDateAdapter) customType;\n return this.date.compareTo(other.date);\n }\n throw new RuntimeException(\"incompatible type: \" + customType);\n }\n\n protected int compareToLocalDate(LocalDate localDate) {\n return this.date.compareTo(localDate);\n }\n\n public IntraDayDate getDate() {\n return date;\n }\n\n @Override\n public Date toDayRoundedDate() {\n return date.toDateTimeAtStartOfDay().toDate();\n }\n\n @Override\n public LocalDate toLocalDate() {\n return date.getDate();\n }\n\n @Override\n public LocalDate asExclusiveEnd() {\n return date.asExclusiveEnd();\n }\n\n @Override\n protected boolean isEqualsToCustom(CustomDate customType) {\n if (customType instanceof GanttDateAdapter) {\n GanttDateAdapter other = (GanttDateAdapter) customType;\n return this.date.equals(other.date);\n }\n return false;\n }\n\n @Override\n public int hashCode() {\n return date.hashCode();\n }\n\n @Override\n public int toPixels(IDatesMapper datesMapper) {\n int pixesUntilDate = datesMapper.toPixels(this.date.getDate());\n EffortDuration effortDuration = date.getEffortDuration();\n Duration durationInDay = calculateDurationInDayFor(effortDuration);\n int pixelsInsideDay = datesMapper.toPixels(durationInDay);\n return pixesUntilDate + pixelsInsideDay;\n }\n\n private Duration calculateDurationInDayFor(EffortDuration effortDuration) {\n if (workingDayDuration.getStandardSeconds() == 0) {\n return Duration.ZERO;\n }\n Fraction fraction = fractionOfWorkingDayFor(effortDuration);\n try {\n return new Duration(fraction.multiplyBy(\n Fraction.getFraction(DAY_MILLISECONDS, 1)).intValue());\n } catch (ArithmeticException e) {\n // if fraction overflows use floating point arithmetic\n return new Duration(\n (int) (fraction.doubleValue() * DAY_MILLISECONDS));\n }\n }\n\n @SuppressWarnings(\"unchecked\")\n private Fraction fractionOfWorkingDayFor(EffortDuration effortDuration) {\n Duration durationInDay = toMilliseconds(effortDuration);\n // cast to int is safe because there are not enough seconds in\n // day\n // to overflow\n Fraction fraction = Fraction.getFraction(\n (int) durationInDay.getStandardSeconds(),\n (int) workingDayDuration.getStandardSeconds());\n return (Fraction) Collections.min(Arrays.asList(fraction,\n Fraction.ONE));\n }\n\n private static Duration toMilliseconds(EffortDuration duration) {\n return Seconds.seconds(duration.getSeconds()).toStandardDuration();\n }\n }\n\n /**\n * Responsible of adaptating a {@link TaskElement} into a\n * {@link ITaskFundamentalProperties}
\n * @author Óscar González Fernández \n */\n public class Adapter implements\n IAdapterToTaskFundamentalProperties {\n\n private Scenario scenario;\n\n private LocalDate initDate;\n\n private LocalDate deadline;\n\n private boolean preventCalculateResourcesText = false;\n\n private final PlanningState planningState;\n\n private void useScenario(Scenario scenario) {\n this.scenario = scenario;\n }\n\n private void setInitDate(LocalDate initDate) {\n this.initDate = initDate;\n }\n\n private void setDeadline(LocalDate deadline) {\n this.deadline = deadline;\n }\n\n public boolean isPreventCalculateResourcesText() {\n return preventCalculateResourcesText;\n }\n\n public void setPreventCalculateResourcesText(\n boolean preventCalculateResourcesText) {\n this.preventCalculateResourcesText = preventCalculateResourcesText;\n }\n\n public Adapter() {\n this(null);\n }\n\n public Adapter(PlanningState planningState) {\n this.planningState = planningState;\n }\n\n private class TaskElementWrapper implements ITaskFundamentalProperties {\n\n private final TaskElement taskElement;\n\n private final Scenario currentScenario;\n\n protected TaskElementWrapper(Scenario currentScenario,\n TaskElement taskElement) {\n Validate.notNull(currentScenario);\n this.currentScenario = currentScenario;\n this.taskElement = taskElement;\n }\n\n private final IUpdatablePosition position = new IUpdatablePosition() {\n\n @Override\n public void setEndDate(GanttDate endDate) {\n stepsBeforePossibleReallocation();\n getDatesHandler(taskElement).moveEndTo(toIntraDay(endDate));\n }\n\n @Override\n public void setBeginDate(final GanttDate beginDate) {\n stepsBeforePossibleReallocation();\n getDatesHandler(taskElement).moveTo(toIntraDay(beginDate));\n }\n\n @Override\n public void resizeTo(final GanttDate endDate) {\n stepsBeforePossibleReallocation();\n updateTaskPositionConstraint(endDate);\n getDatesHandler(taskElement).resizeTo(toIntraDay(endDate));\n }\n\n private void stepsBeforePossibleReallocation() {\n taskDAO.reattach(taskElement);\n }\n\n @Override\n public void moveTo(GanttDate newStart) {\n if (taskElement instanceof ITaskPositionConstrained) {\n ITaskPositionConstrained task = (ITaskPositionConstrained) taskElement;\n GanttDate newEnd = inferEndFrom(newStart);\n if (task.getPositionConstraint()\n .isConstraintAppliedToStart()) {\n setBeginDate(newStart);\n } else {\n setEndDate(newEnd);\n }\n task.explicityMoved(toIntraDay(newStart), toIntraDay(newEnd));\n }\n }\n };\n\n @Override\n public void setName(String name) {\n taskElement.setName(name);\n }\n\n @Override\n public void setNotes(String notes) {\n taskElement.setNotes(notes);\n }\n\n @Override\n public String getName() {\n return taskElement.getName();\n }\n\n @Override\n public String getCode() {\n return taskElement.getCode();\n }\n\n @Override\n public String getProjectCode() {\n return taskElement.getProjectCode();\n }\n\n @Override\n public String getNotes() {\n return taskElement.getNotes();\n }\n\n @Override\n public GanttDate getBeginDate() {\n IntraDayDate start = taskElement.getIntraDayStartDate();\n return toGantt(start);\n }\n\n private GanttDate toGantt(IntraDayDate date) {\n BaseCalendar calendar = taskElement.getCalendar();\n if (calendar == null) {\n return TaskElementAdapter.toGantt(date);\n }\n return TaskElementAdapter.toGantt(date, calendar\n .getCapacityOn(PartialDay.wholeDay(date.getDate())));\n }\n\n @Override\n public void doPositionModifications(\n final IModifications modifications) {\n reentranceGuard.entranceRequested(new IReentranceCases() {\n\n @Override\n public void ifNewEntrance() {\n transactionService.runOnReadOnlyTransaction(asTransaction(modifications));\n }\n\n IOnTransaction asTransaction(\n final IModifications modifications) {\n return new IOnTransaction() {\n\n @Override\n public Void execute() {\n if (planningState != null) {\n planningState\n .reassociateResourcesWithSession();\n }\n modifications.doIt(position);\n return null;\n }\n };\n }\n\n @Override\n public void ifAlreadyInside() {\n modifications.doIt(position);\n }\n });\n }\n\n @Override\n public GanttDate getEndDate() {\n return toGantt(taskElement.getIntraDayEndDate());\n }\n\n IDatesHandler getDatesHandler(TaskElement taskElement) {\n return taskElement.getDatesHandler(currentScenario, searcher);\n }\n\n private void updateTaskPositionConstraint(GanttDate endDate) {\n if (taskElement instanceof ITaskPositionConstrained) {\n ITaskPositionConstrained task = (ITaskPositionConstrained) taskElement;\n PositionConstraintType constraintType = task\n .getPositionConstraint().getConstraintType();\n if (constraintType\n .compareTo(PositionConstraintType.FINISH_NOT_LATER_THAN) == 0\n || constraintType\n .compareTo(PositionConstraintType.AS_LATE_AS_POSSIBLE) == 0) {\n task.explicityMoved(taskElement.getIntraDayStartDate(),\n toIntraDay(endDate));\n }\n }\n }\n\n @Override\n public GanttDate getHoursAdvanceBarEndDate() {\n return calculateLimitDateProportionalToTaskElementSize(getHoursAdvanceBarPercentage());\n }\n\n @Override\n public BigDecimal getHoursAdvanceBarPercentage() {\n OrderElement orderElement = taskElement.getOrderElement();\n if (orderElement == null) {\n return BigDecimal.ZERO;\n }\n\n EffortDuration totalChargedEffort = orderElement\n .getSumChargedEffort() != null ? orderElement\n .getSumChargedEffort().getTotalChargedEffort()\n : EffortDuration.zero();\n\n EffortDuration estimatedEffort = taskElement.getSumOfAssignedEffort();\n\n if(estimatedEffort.isZero()) {\n estimatedEffort = EffortDuration.hours(orderElement.getWorkHours());\n if(estimatedEffort.isZero()) {\n return BigDecimal.ZERO;\n }\n }\n return new BigDecimal(totalChargedEffort.divivedBy(\n estimatedEffort).doubleValue()).setScale(2,\n RoundingMode.HALF_UP);\n }\n\n @Override\n public GanttDate getMoneyCostBarEndDate() {\n return calculateLimitDateProportionalToTaskElementSize(getMoneyCostBarPercentage());\n }\n\n private GanttDate calculateLimitDateProportionalToTaskElementSize(\n BigDecimal proportion) {\n if (proportion.compareTo(BigDecimal.ZERO) == 0) {\n return getBeginDate();\n }\n\n IntraDayDate start = taskElement.getIntraDayStartDate();\n IntraDayDate end = taskElement.getIntraDayEndDate();\n\n EffortDuration effortBetween = start.effortUntil(end);\n int seconds = new BigDecimal(effortBetween.getSeconds())\n .multiply(proportion).toBigInteger().intValue();\n return TaskElementAdapter.toGantt(\n start.addEffort(EffortDuration.seconds(seconds)),\n EffortDuration.hours(8));\n }\n\n @Override\n public BigDecimal getMoneyCostBarPercentage() {\n return MoneyCostCalculator.getMoneyCostProportion(\n getMoneyCost(), getBudget());\n }\n\n private BigDecimal getBudget() {\n if ((taskElement == null)\n || (taskElement.getOrderElement() == null)) {\n return BigDecimal.ZERO;\n }\n return taskElement.getOrderElement().getBudget();\n }\n\n private BigDecimal getTotalCalculatedBudget() {\n if ((taskElement == null)\n || (taskElement.getOrderElement() == null)) {\n return BigDecimal.ZERO;\n }\n return transactionService\n .runOnReadOnlyTransaction(new IOnTransaction() {\n\n @Override\n public BigDecimal execute() {\n return taskElement.getOrderElement()\n .getTotalBudget();\n }\n });\n }\n\n private BigDecimal getMoneyCost() {\n if ((taskElement == null)\n || (taskElement.getOrderElement() == null)) {\n return BigDecimal.ZERO;\n }\n return transactionService\n .runOnReadOnlyTransaction(new IOnTransaction() {\n\n @Override\n public BigDecimal execute() {\n return moneyCostCalculator.getTotalMoneyCost(taskElement\n .getOrderElement());\n }\n });\n }\n\n private BigDecimal getHoursMoneyCost() {\n if ((taskElement == null) || (taskElement.getOrderElement() == null)) {\n return BigDecimal.ZERO;\n }\n\n return transactionService\n .runOnReadOnlyTransaction(new IOnTransaction() {\n @Override\n public BigDecimal execute() {\n return moneyCostCalculator.getHoursMoneyCost(taskElement.getOrderElement());\n }\n });\n }\n\n private BigDecimal getExpensesMoneyCost() {\n if ((taskElement == null) || (taskElement.getOrderElement() == null)) {\n return BigDecimal.ZERO;\n }\n\n return transactionService\n .runOnReadOnlyTransaction(new IOnTransaction() {\n @Override\n public BigDecimal execute() {\n return moneyCostCalculator.getExpensesMoneyCost(taskElement\n .getOrderElement());\n }\n });\n }\n\n @Override\n public GanttDate getAdvanceBarEndDate(String progressType) {\n return getAdvanceBarEndDate(ProgressType.asEnum(progressType));\n }\n\n private GanttDate getAdvanceBarEndDate(ProgressType progressType) {\n BigDecimal advancePercentage = BigDecimal.ZERO;\n if (taskElement.getOrderElement() != null) {\n advancePercentage = taskElement\n .getAdvancePercentage(progressType);\n }\n return getAdvanceBarEndDate(advancePercentage);\n }\n\n @Override\n public GanttDate getAdvanceBarEndDate() {\n return getAdvanceBarEndDate(getAdvancePercentage());\n }\n\n private boolean isTaskRoot(TaskElement taskElement) {\n return taskElement instanceof TaskGroup\n && taskElement.getParent() == null;\n }\n\n private ProgressType getProgressTypeFromConfiguration() {\n return transactionService\n .runOnReadOnlyTransaction(new IOnTransaction() {\n @Override\n public ProgressType execute() {\n return configurationDAO.getConfiguration()\n .getProgressType();\n }\n });\n }\n\n private GanttDate getAdvanceBarEndDate(BigDecimal advancePercentage) {\n return calculateLimitDateProportionalToTaskElementSize(advancePercentage);\n }\n\n @Override\n public String getTooltipText() {\n if (taskElement.isMilestone()\n || taskElement.getOrderElement() == null) {\n return \"\";\n }\n return transactionService\n .runOnReadOnlyTransaction(new IOnTransaction() {\n\n @Override\n public String execute() {\n orderElementDAO.reattach(taskElement\n .getOrderElement());\n return buildTooltipText();\n }\n });\n }\n\n @Override\n public String getLabelsText() {\n if (taskElement.isMilestone()\n || taskElement.getOrderElement() == null) {\n return \"\";\n }\n return transactionService\n .runOnReadOnlyTransaction(new IOnTransaction() {\n\n @Override\n public String execute() {\n orderElementDAO.reattach(taskElement\n .getOrderElement());\n return buildLabelsText();\n }\n });\n }\n\n @Override\n public String getResourcesText() {\n if (isPreventCalculateResourcesText()\n || taskElement.getOrderElement() == null) {\n return \"\";\n }\n try {\n return transactionService\n .runOnAnotherReadOnlyTransaction(new IOnTransaction() {\n\n @Override\n public String execute() {\n orderElementDAO.reattach(taskElement\n .getOrderElement());\n if (taskElement.isSubcontracted()) {\n externalCompanyDAO.reattach(taskElement\n .getSubcontractedCompany());\n }\n return buildResourcesText();\n }\n });\n } catch (Exception e) {\n LOG.error(\"error calculating resources text\", e);\n return \"\";\n }\n }\n\n private Set