{ // 获取包含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\".getBytes());\n out.flush();\n }\n s.close();\n return;\n }\n destination = currentProxy;\n usingWWWProxy = true;\n if (_log.shouldLog(Log.DEBUG))\n _log.debug(getPrefix(requestId) + \"Host doesnt end with .i2p and it contains a period [\" + host + \"]: wwwProxy!\");\n } else {\n request = request.substring(pos + 1);\n pos = request.indexOf(\"/\");\n destination = request.substring(0, pos);\n line = method + \" \" + request.substring(pos);\n }\n\n boolean isValid = usingWWWProxy || isSupportedAddress(host, protocol);\n if (!isValid) {\n if (_log.shouldLog(Log.INFO)) _log.info(getPrefix(requestId) + \"notValid(\" + host + \")\");\n method = null;\n destination = null;\n break;\n } else if (!usingWWWProxy) {\n if (_log.shouldLog(Log.INFO)) _log.info(getPrefix(requestId) + \"host=getHostName(\" + destination + \")\");\n host = getHostName(destination); // hide original host\n }\n\n if (_log.shouldLog(Log.DEBUG)) {\n _log.debug(getPrefix(requestId) + \"METHOD:\" + method + \":\");\n _log.debug(getPrefix(requestId) + \"PROTOC:\" + protocol + \":\");\n _log.debug(getPrefix(requestId) + \"HOST :\" + host + \":\");\n _log.debug(getPrefix(requestId) + \"DEST :\" + destination + \":\");\n }\n \n } else {\n if (line.startsWith(\"Host: \") && !usingWWWProxy) {\n line = \"Host: \" + host;\n if (_log.shouldLog(Log.INFO)) \n _log.info(getPrefix(requestId) + \"Setting host = \" + host);\n }\n }\n \n if (line.length() == 0) {\n newRequest.append(\"Connection: close\\r\\n\\r\\n\");\n break;\n } else {\n newRequest.append(line).append(\"\\r\\n\"); // HTTP spec\n }\n }\n if (_log.shouldLog(Log.DEBUG))\n _log.debug(getPrefix(requestId) + \"NewRequest header: [\" + newRequest.toString() + \"]\");\n \n while (br.ready()) { // empty the buffer (POST requests)\n int i = br.read();\n if (i != -1) {\n newRequest.append((char) i);\n }\n }\n if (method == null || destination == null) {\n l.log(\"No HTTP method found in the request.\");\n if (out != null) {\n out.write(ERR_REQUEST_DENIED);\n out.write(\"

Generated on: \".getBytes());\n out.write(new Date().toString().getBytes());\n out.write(\"\\n\".getBytes());\n out.flush();\n }\n s.close();\n return;\n }\n \n if (_log.shouldLog(Log.DEBUG))\n _log.debug(getPrefix(requestId) + \"Destination: \" + destination);\n \n Destination dest = I2PTunnel.destFromName(destination);\n if (dest == null) {\n l.log(\"Could not resolve \" + destination + \".\");\n if (_log.shouldLog(Log.WARN))\n _log.warn(\"Unable to resolve \" + destination + \" (proxy? \" + usingWWWProxy + \", request: \" + targetRequest);\n writeErrorMessage(ERR_DESTINATION_UNKNOWN, out, targetRequest, usingWWWProxy, destination);\n s.close();\n return;\n }\n String remoteID;\n I2PSocket i2ps = createI2PSocket(dest);\n byte[] data = newRequest.toString().getBytes(\"ISO-8859-1\");\n I2PTunnelRunner runner = new I2PTunnelRunner(s, i2ps, sockLock, data);\n timeoutThread = new InactivityTimeoutThread(runner, out, targetRequest, usingWWWProxy, currentProxy, s, requestId);\n timeoutThread.start();\n } catch (SocketException ex) {\n if (timeoutThread != null) timeoutThread.disable();\n _log.info(getPrefix(requestId) + \"Error trying to connect\", ex);\n l.log(ex.getMessage());\n handleHTTPClientException(ex, out, targetRequest, usingWWWProxy, currentProxy, requestId);\n closeSocket(s);\n } catch (IOException ex) {\n if (timeoutThread != null) timeoutThread.disable();\n _log.info(getPrefix(requestId) + \"Error trying to connect\", ex);\n l.log(ex.getMessage());\n handleHTTPClientException(ex, out, targetRequest, usingWWWProxy, currentProxy, requestId);\n closeSocket(s);\n } catch (I2PException ex) {\n if (timeoutThread != null) timeoutThread.disable();\n _log.info(\"getPrefix(requestId) + Error trying to connect\", ex);\n l.log(ex.getMessage());\n handleHTTPClientException(ex, out, targetRequest, usingWWWProxy, currentProxy, requestId);\n closeSocket(s);\n }\n }\n\n private static final long INACTIVITY_TIMEOUT = 120 * 1000;\n private static volatile long __timeoutId = 0;\n\n private class InactivityTimeoutThread extends I2PThread {\n \n private Socket s;\n private I2PTunnelRunner _runner;\n private OutputStream _out;\n private String _targetRequest;\n private boolean _useWWWProxy;\n private String _currentProxy;\n private long _requestId;\n private boolean _disabled;\n private Object _disableLock = new Object();\n\n public InactivityTimeoutThread(I2PTunnelRunner runner, OutputStream out, String targetRequest,\n boolean useWWWProxy, String currentProxy, Socket s, long requestId) {\n this.s = s;\n _runner = runner;\n _out = out;\n _targetRequest = targetRequest;\n _useWWWProxy = useWWWProxy;\n _currentProxy = currentProxy;\n _disabled = false;\n _requestId = requestId;\n long timeoutId = ++__timeoutId;\n setName(\"InactivityThread \" + getPrefix(requestId) + timeoutId);\n }\n\n public void disable() {\n _disabled = true;\n synchronized (_disableLock) {\n _disableLock.notifyAll();\n }\n }\n\n public void run() {\n while (!_disabled) {\n if (_runner.isFinished()) {\n if (_log.shouldLog(Log.INFO)) _log.info(getPrefix(_requestId) + \"HTTP client request completed prior to timeout\");\n return;\n }\n if (_runner.getLastActivityOn() < Clock.getInstance().now() - INACTIVITY_TIMEOUT) {\n if (_runner.getStartedOn() < Clock.getInstance().now() - INACTIVITY_TIMEOUT) {\n if (_log.shouldLog(Log.WARN))\n _log.warn(getPrefix(_requestId) + \"HTTP client request timed out (lastActivity: \"\n + new Date(_runner.getLastActivityOn()) + \", startedOn: \"\n + new Date(_runner.getStartedOn()) + \")\");\n timeout();\n return;\n } else {\n // runner hasn't been going to long enough\n }\n } else {\n // there has been activity in the period\n }\n synchronized (_disableLock) {\n try {\n _disableLock.wait(INACTIVITY_TIMEOUT);\n } catch (InterruptedException ie) {\n }\n }\n }\n }\n\n private void timeout() {\n _log.info(getPrefix(_requestId) + \"Inactivity timeout reached\");\n l.log(\"Inactivity timeout reached\");\n if (_out != null) {\n try {\n if (_runner.getLastActivityOn() > 0) {\n // some data has been sent, so don't 404 it\n } else {\n writeErrorMessage(ERR_TIMEOUT, _out, _targetRequest, _useWWWProxy, _currentProxy);\n }\n } catch (IOException ioe) {\n _log.warn(getPrefix(_requestId) + \"Error writing out the 'timeout' message\", ioe);\n }\n } else {\n _log.warn(getPrefix(_requestId) + \"Client disconnected before we could say we timed out\");\n }\n closeSocket(s);\n }\n }\n\n private final static String getHostName(String host) {\n if (host == null) return null;\n try {\n Destination dest = I2PTunnel.destFromName(host);\n if (dest == null) return \"i2p\";\n return dest.toBase64();\n } catch (DataFormatException dfe) {\n return \"i2p\";\n }\n }\n\n private static void writeErrorMessage(byte[] errMessage, OutputStream out, String targetRequest,\n boolean usingWWWProxy, String wwwProxy) throws IOException {\n if (out != null) {\n out.write(errMessage);\n if (targetRequest != null) {\n out.write(targetRequest.getBytes());\n if (usingWWWProxy) out.write((\"
WWW proxy: \" + wwwProxy).getBytes());\n }\n out.write(\"

Generated on: \".getBytes());\n out.write(new Date().toString().getBytes());\n out.write(\"\\n\".getBytes());\n out.flush();\n }\n }\n\n private void handleHTTPClientException(Exception ex, OutputStream out, String targetRequest,\n boolean usingWWWProxy, String wwwProxy, long requestId) {\n \n if (_log.shouldLog(Log.WARN))\n _log.warn(getPrefix(requestId) + \"Error sending to \" + wwwProxy + \" (proxy? \" + usingWWWProxy + \", request: \" + targetRequest, ex);\n if (out != null) {\n try {\n writeErrorMessage(ERR_DESTINATION_UNKNOWN, out, targetRequest, usingWWWProxy, wwwProxy);\n } catch (IOException ioe) {\n _log.warn(getPrefix(requestId) + \"Error writing out the 'destination was unknown' \" + \"message\", ioe);\n }\n } else {\n _log.warn(getPrefix(requestId) + \"Client disconnected before we could say that destination \" + \"was unknown\", ex);\n }\n }\n\n private final static String SUPPORTED_HOSTS[] = { \"i2p\", \"www.i2p.com\", \"i2p.\"};\n\n private boolean isSupportedAddress(String host, String protocol) {\n if ((host == null) || (protocol == null)) return false;\n boolean found = false;\n String lcHost = host.toLowerCase();\n for (int i = 0; i < SUPPORTED_HOSTS.length; i++) {\n if (SUPPORTED_HOSTS[i].equals(lcHost)) {\n found = true;\n break;\n }\n }\n\n if (!found) {\n try {\n Destination d = I2PTunnel.destFromName(host);\n if (d == null) return false;\n } catch (DataFormatException dfe) {\n }\n }\n\n return protocol.equalsIgnoreCase(\"http://\");\n }\n}\n"},"new_file":{"kind":"string","value":"apps/i2ptunnel/java/src/net/i2p/i2ptunnel/I2PTunnelHTTPClient.java"},"old_contents":{"kind":"string","value":"/* I2PTunnel is GPL'ed (with the exception mentioned in I2PTunnel.java)\n * (c) 2003 - 2004 mihi\n */\npackage net.i2p.i2ptunnel;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.OutputStream;\nimport java.net.Socket;\nimport java.net.SocketException;\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.StringTokenizer;\n\nimport net.i2p.I2PAppContext;\nimport net.i2p.I2PException;\nimport net.i2p.client.streaming.I2PSocket;\nimport net.i2p.data.DataFormatException;\nimport net.i2p.data.Destination;\nimport net.i2p.util.Clock;\nimport net.i2p.util.EventDispatcher;\nimport net.i2p.util.I2PThread;\nimport net.i2p.util.Log;\n\n/**\n * Act as a mini HTTP proxy, handling various different types of requests,\n * forwarding them through I2P appropriately, and displaying the reply. Supported\n * request formats are:

\n *   $method http://$site[$port]/$path $protocolVersion\n * or\n *   $method $path $protocolVersion\\nHost: $site\n * or\n *   $method http://i2p/$site/$path $protocolVersion\n * or \n *   $method /$site/$path $protocolVersion\n * 
\n *\n * If the $site resolves with the I2P naming service, then it is directed towards\n * that eepsite, otherwise it is directed towards this client's outproxy (typically\n * \"squid.i2p\"). Only HTTP is supported (no HTTPS, ftp, mailto, etc). Both GET\n * and POST have been tested, though other $methods should work.\n *\n */\npublic class I2PTunnelHTTPClient extends I2PTunnelClientBase implements Runnable {\n private static final Log _log = new Log(I2PTunnelHTTPClient.class);\n\n private List proxyList;\n\n private final static byte[] ERR_REQUEST_DENIED =\n (\"HTTP/1.1 403 Access Denied\\r\\n\"+\n \"Content-Type: text/html; charset=iso-8859-1\\r\\n\"+\n \"Cache-control: no-cache\\r\\n\"+\n \"\\r\\n\"+\n \"

I2P ERROR: REQUEST DENIED

\"+\n \"You attempted to connect to a non-I2P website or location.
\")\n .getBytes();\n \n private final static byte[] ERR_DESTINATION_UNKNOWN =\n (\"HTTP/1.1 503 Service Unavailable\\r\\n\"+\n \"Content-Type: text/html; charset=iso-8859-1\\r\\n\"+\n \"Cache-control: no-cache\\r\\n\"+\n \"\\r\\n\"+\n \"

I2P ERROR: DESTINATION NOT FOUND

\"+\n \"That I2P Destination was not found. Perhaps you pasted in the \"+\n \"wrong BASE64 I2P Destination or the link you are following is \"+\n \"bad. The host (or the WWW proxy, if you're using one) could also \"+\n\t \"be temporarily offline. You may want to retry. \"+\n \"Could not find the following Destination:

\")\n .getBytes();\n \n private final static byte[] ERR_TIMEOUT =\n (\"HTTP/1.1 504 Gateway Timeout\\r\\n\"+\n \"Content-Type: text/html; charset=iso-8859-1\\r\\n\"+\n \"Cache-control: no-cache\\r\\n\\r\\n\"+\n \"

I2P ERROR: TIMEOUT

\"+\n \"That Destination was reachable, but timed out getting a \"+\n \"response. This is likely a temporary error, so you should simply \"+\n \"try to refresh, though if the problem persists, the remote \"+\n \"destination may have issues. Could not get a response from \"+\n \"the following Destination:

\")\n .getBytes();\n\n /** used to assign unique IDs to the threads / clients. no logic or functionality */\n private static volatile long __clientId = 0;\n\n /**\n * @throws IllegalArgumentException if the I2PTunnel does not contain\n * valid config to contact the router\n */\n public I2PTunnelHTTPClient(int localPort, Logging l, boolean ownDest, \n String wwwProxy, EventDispatcher notifyThis, \n I2PTunnel tunnel) throws IllegalArgumentException {\n super(localPort, ownDest, l, notifyThis, \"HTTPHandler \" + (++__clientId), tunnel);\n\n if (waitEventValue(\"openBaseClientResult\").equals(\"error\")) {\n notifyEvent(\"openHTTPClientResult\", \"error\");\n return;\n }\n\n proxyList = new ArrayList();\n if (wwwProxy != null) {\n StringTokenizer tok = new StringTokenizer(wwwProxy, \",\");\n while (tok.hasMoreTokens())\n proxyList.add(tok.nextToken().trim());\n }\n\n setName(getLocalPort() + \" -> HTTPClient [WWW outproxy list: \" + wwwProxy + \"]\");\n\n startRunning();\n\n notifyEvent(\"openHTTPClientResult\", \"ok\");\n }\n\n private String getPrefix() { return \"Client[\" + _clientId + \"]: \"; }\n \n private String selectProxy() {\n if (proxyList.size() <= 0) {\n l.log(\"Proxy list is emtpy - no outproxy available\");\n return null;\n }\n int index = I2PAppContext.getGlobalContext().random().nextInt(proxyList.size());\n return (String)proxyList.get(index);\n }\n \n protected void clientConnectionRun(Socket s) {\n OutputStream out = null;\n String targetRequest = null;\n boolean usingWWWProxy = false;\n String currentProxy = null;\n InactivityTimeoutThread timeoutThread = null;\n try {\n out = s.getOutputStream();\n BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream(), \"ISO-8859-1\"));\n String line, method = null, protocol = null, host = null, destination = null;\n StringBuffer newRequest = new StringBuffer();\n while ((line = br.readLine()) != null) {\n if (_log.shouldLog(Log.DEBUG))\n _log.debug(getPrefix() + \"Line=[\" + line + \"]\");\n \n if (line.startsWith(\"Connection: \") || \n line.startsWith(\"Keep-Alive: \") || \n line.startsWith(\"Proxy-Connection: \"))\n continue;\n \n if (method == null) { // first line (GET /base64/realaddr)\n if (_log.shouldLog(Log.DEBUG))\n _log.debug(getPrefix() + \"Method is null for [\" + line + \"]\");\n \n int pos = line.indexOf(\" \");\n if (pos == -1) break;\n method = line.substring(0, pos);\n String request = line.substring(pos + 1);\n if (request.startsWith(\"/\") && getTunnel().getClientOptions().getProperty(\"i2ptunnel.noproxy\") != null) {\n request = \"http://i2p\" + request;\n }\n pos = request.indexOf(\"//\");\n if (pos == -1) {\n method = null;\n break;\n }\n protocol = request.substring(0, pos + 2);\n request = request.substring(pos + 2);\n\n targetRequest = request;\n\n pos = request.indexOf(\"/\");\n if (pos == -1) {\n method = null;\n break;\n }\n host = request.substring(0, pos);\n\n // Quick hack for foo.bar.i2p\n if (host.toLowerCase().endsWith(\".i2p\")) {\n destination = host;\n host = getHostName(destination);\n line = method + \" \" + request.substring(pos);\n } else if (host.indexOf(\".\") != -1) {\n // The request must be forwarded to a WWW proxy\n currentProxy = selectProxy();\n destination = currentProxy;\n usingWWWProxy = true;\n if (_log.shouldLog(Log.DEBUG))\n _log.debug(getPrefix() + \"Host doesnt end with .i2p and it contains a period [\" + host + \"]: wwwProxy!\");\n } else {\n request = request.substring(pos + 1);\n pos = request.indexOf(\"/\");\n destination = request.substring(0, pos);\n line = method + \" \" + request.substring(pos);\n }\n\n boolean isValid = usingWWWProxy || isSupportedAddress(host, protocol);\n if (!isValid) {\n if (_log.shouldLog(Log.INFO)) _log.info(getPrefix() + \"notValid(\" + host + \")\");\n method = null;\n destination = null;\n break;\n } else if (!usingWWWProxy) {\n if (_log.shouldLog(Log.INFO)) _log.info(getPrefix() + \"host=getHostName(\" + destination + \")\");\n host = getHostName(destination); // hide original host\n }\n\n if (_log.shouldLog(Log.DEBUG)) {\n _log.debug(getPrefix() + \"METHOD:\" + method + \":\");\n _log.debug(getPrefix() + \"PROTOC:\" + protocol + \":\");\n _log.debug(getPrefix() + \"HOST :\" + host + \":\");\n _log.debug(getPrefix() + \"DEST :\" + destination + \":\");\n }\n \n } else {\n if (line.startsWith(\"Host: \") && !usingWWWProxy) {\n line = \"Host: \" + host;\n if (_log.shouldLog(Log.INFO)) \n _log.info(getPrefix() + \"Setting host = \" + host);\n }\n }\n \n if (line.length() == 0) {\n newRequest.append(\"Connection: close\\r\\n\\r\\n\");\n break;\n } else {\n newRequest.append(line).append(\"\\r\\n\"); // HTTP spec\n }\n }\n if (_log.shouldLog(Log.DEBUG))\n _log.debug(getPrefix() + \"NewRequest header: [\" + newRequest.toString() + \"]\");\n \n while (br.ready()) { // empty the buffer (POST requests)\n int i = br.read();\n if (i != -1) {\n newRequest.append((char) i);\n }\n }\n if (method == null || destination == null) {\n l.log(\"No HTTP method found in the request.\");\n if (out != null) {\n out.write(ERR_REQUEST_DENIED);\n out.write(\"

Generated on: \".getBytes());\n out.write(new Date().toString().getBytes());\n out.write(\"\\n\".getBytes());\n out.flush();\n }\n s.close();\n return;\n }\n \n if (_log.shouldLog(Log.DEBUG))\n _log.debug(getPrefix() + \"Destination: \" + destination);\n \n Destination dest = I2PTunnel.destFromName(destination);\n if (dest == null) {\n l.log(\"Could not resolve \" + destination + \".\");\n if (_log.shouldLog(Log.WARN))\n _log.warn(\"Unable to resolve \" + destination + \" (proxy? \" + usingWWWProxy + \", request: \" + targetRequest);\n writeErrorMessage(ERR_DESTINATION_UNKNOWN, out, targetRequest, usingWWWProxy, destination);\n s.close();\n return;\n }\n String remoteID;\n I2PSocket i2ps = createI2PSocket(dest);\n byte[] data = newRequest.toString().getBytes(\"ISO-8859-1\");\n I2PTunnelRunner runner = new I2PTunnelRunner(s, i2ps, sockLock, data);\n timeoutThread = new InactivityTimeoutThread(runner, out, targetRequest, usingWWWProxy, currentProxy, s);\n timeoutThread.start();\n } catch (SocketException ex) {\n if (timeoutThread != null) timeoutThread.disable();\n _log.info(getPrefix() + \"Error trying to connect\", ex);\n l.log(ex.getMessage());\n handleHTTPClientException(ex, out, targetRequest, usingWWWProxy, currentProxy);\n closeSocket(s);\n } catch (IOException ex) {\n if (timeoutThread != null) timeoutThread.disable();\n _log.info(getPrefix() + \"Error trying to connect\", ex);\n l.log(ex.getMessage());\n handleHTTPClientException(ex, out, targetRequest, usingWWWProxy, currentProxy);\n closeSocket(s);\n } catch (I2PException ex) {\n if (timeoutThread != null) timeoutThread.disable();\n _log.info(\"getPrefix() + Error trying to connect\", ex);\n l.log(ex.getMessage());\n handleHTTPClientException(ex, out, targetRequest, usingWWWProxy, currentProxy);\n closeSocket(s);\n }\n }\n\n private static final long INACTIVITY_TIMEOUT = 120 * 1000;\n private static volatile long __timeoutId = 0;\n\n private class InactivityTimeoutThread extends I2PThread {\n\n private Socket s;\n private I2PTunnelRunner _runner;\n private OutputStream _out;\n private String _targetRequest;\n private boolean _useWWWProxy;\n private String _currentProxy;\n private boolean _disabled;\n private Object _disableLock = new Object();\n\n public InactivityTimeoutThread(I2PTunnelRunner runner, OutputStream out, String targetRequest,\n boolean useWWWProxy, String currentProxy, Socket s) {\n this.s = s;\n _runner = runner;\n _out = out;\n _targetRequest = targetRequest;\n _useWWWProxy = useWWWProxy;\n _currentProxy = currentProxy;\n _disabled = false;\n long timeoutId = ++__timeoutId;\n setName(\"InactivityThread \" + getPrefix() + timeoutId);\n }\n\n public void disable() {\n _disabled = true;\n synchronized (_disableLock) {\n _disableLock.notifyAll();\n }\n }\n\n public void run() {\n while (!_disabled) {\n if (_runner.isFinished()) {\n if (_log.shouldLog(Log.INFO)) _log.info(getPrefix() + \"HTTP client request completed prior to timeout\");\n return;\n }\n if (_runner.getLastActivityOn() < Clock.getInstance().now() - INACTIVITY_TIMEOUT) {\n if (_runner.getStartedOn() < Clock.getInstance().now() - INACTIVITY_TIMEOUT) {\n if (_log.shouldLog(Log.WARN))\n _log.warn(getPrefix() + \"HTTP client request timed out (lastActivity: \"\n + new Date(_runner.getLastActivityOn()) + \", startedOn: \"\n + new Date(_runner.getStartedOn()) + \")\");\n timeout();\n return;\n } else {\n // runner hasn't been going to long enough\n }\n } else {\n // there has been activity in the period\n }\n synchronized (_disableLock) {\n try {\n _disableLock.wait(INACTIVITY_TIMEOUT);\n } catch (InterruptedException ie) {\n }\n }\n }\n }\n\n private void timeout() {\n _log.info(getPrefix() + \"Inactivity timeout reached\");\n l.log(\"Inactivity timeout reached\");\n if (_out != null) {\n try {\n if (_runner.getLastActivityOn() > 0) {\n // some data has been sent, so don't 404 it\n } else {\n writeErrorMessage(ERR_TIMEOUT, _out, _targetRequest, _useWWWProxy, _currentProxy);\n }\n } catch (IOException ioe) {\n _log.warn(getPrefix() + \"Error writing out the 'timeout' message\", ioe);\n }\n } else {\n _log.warn(getPrefix() + \"Client disconnected before we could say we timed out\");\n }\n closeSocket(s);\n }\n }\n\n private final static String getHostName(String host) {\n try {\n Destination dest = I2PTunnel.destFromName(host);\n if (dest == null) return \"i2p\";\n return dest.toBase64();\n } catch (DataFormatException dfe) {\n return \"i2p\";\n }\n }\n\n private static void writeErrorMessage(byte[] errMessage, OutputStream out, String targetRequest,\n boolean usingWWWProxy, String wwwProxy) throws IOException {\n if (out != null) {\n out.write(errMessage);\n if (targetRequest != null) {\n out.write(targetRequest.getBytes());\n if (usingWWWProxy) out.write((\"
WWW proxy: \" + wwwProxy).getBytes());\n }\n out.write(\"

Generated on: \".getBytes());\n out.write(new Date().toString().getBytes());\n out.write(\"\\n\".getBytes());\n out.flush();\n }\n }\n\n private void handleHTTPClientException(Exception ex, OutputStream out, String targetRequest,\n boolean usingWWWProxy, String wwwProxy) {\n \n if (_log.shouldLog(Log.WARN))\n _log.warn(\"Error sending to \" + wwwProxy + \" (proxy? \" + usingWWWProxy + \", request: \" + targetRequest, ex);\n if (out != null) {\n try {\n writeErrorMessage(ERR_DESTINATION_UNKNOWN, out, targetRequest, usingWWWProxy, wwwProxy);\n } catch (IOException ioe) {\n _log.warn(getPrefix() + \"Error writing out the 'destination was unknown' \" + \"message\", ioe);\n }\n } else {\n _log.warn(getPrefix() + \"Client disconnected before we could say that destination \" + \"was unknown\", ex);\n }\n }\n\n private final static String SUPPORTED_HOSTS[] = { \"i2p\", \"www.i2p.com\", \"i2p.\"};\n\n private boolean isSupportedAddress(String host, String protocol) {\n if ((host == null) || (protocol == null)) return false;\n boolean found = false;\n String lcHost = host.toLowerCase();\n for (int i = 0; i < SUPPORTED_HOSTS.length; i++) {\n if (SUPPORTED_HOSTS[i].equals(lcHost)) {\n found = true;\n break;\n }\n }\n\n if (!found) {\n try {\n Destination d = I2PTunnel.destFromName(host);\n if (d == null) return false;\n } catch (DataFormatException dfe) {\n }\n }\n\n return protocol.equalsIgnoreCase(\"http://\");\n }\n}\n"},"message":{"kind":"string","value":"deal with no proxy available\nmore carefully retrieve a proxy\nlogging (w/ unique requestId)\n"},"old_file":{"kind":"string","value":"apps/i2ptunnel/java/src/net/i2p/i2ptunnel/I2PTunnelHTTPClient.java"},"subject":{"kind":"string","value":"deal with no proxy available more carefully retrieve a proxy logging (w/ unique requestId)"},"git_diff":{"kind":"string","value":"pps/i2ptunnel/java/src/net/i2p/i2ptunnel/I2PTunnelHTTPClient.java\n \"the following Destination:

\")\n .getBytes();\n \n private final static byte[] ERR_NO_OUTPROXY =\n (\"HTTP/1.1 503 Service Unavailable\\r\\n\"+\n \"Content-Type: text/html; charset=iso-8859-1\\r\\n\"+\n \"Cache-control: no-cache\\r\\n\"+\n \"\\r\\n\"+\n \"

I2P ERROR: No outproxy found

\"+\n \"Your request was for a site outside of I2P, but you have no \"+\n \"HTTP outproxy configured. Please configure an outproxy in I2PTunnel\")\n .getBytes();\n \n /** used to assign unique IDs to the threads / clients. no logic or functionality */\n private static volatile long __clientId = 0;\n \n notifyEvent(\"openHTTPClientResult\", \"ok\");\n }\n \n private String getPrefix() { return \"Client[\" + _clientId + \"]: \"; }\n private String getPrefix(long requestId) { return \"Client[\" + _clientId + \"/\" + requestId + \"]: \"; }\n \n private String selectProxy() {\n if (proxyList.size() <= 0) {\n l.log(\"Proxy list is emtpy - no outproxy available\");\n return null;\n }\n int index = I2PAppContext.getGlobalContext().random().nextInt(proxyList.size());\n return (String)proxyList.get(index);\n synchronized (proxyList) {\n int size = proxyList.size();\n if (size <= 0) {\n if (_log.shouldLog(Log.INFO))\n _log.info(\"Proxy list is empty - no outproxy available\");\n l.log(\"Proxy list is emtpy - no outproxy available\");\n return null;\n }\n int index = I2PAppContext.getGlobalContext().random().nextInt(size);\n if (index >= size) index = size - 1;\n if (index < 0) return null;\n String proxy = (String)proxyList.get(index);\n return proxy;\n }\n }\n \n private static long __requestId = 0;\n protected void clientConnectionRun(Socket s) {\n OutputStream out = null;\n String targetRequest = null;\n boolean usingWWWProxy = false;\n String currentProxy = null;\n InactivityTimeoutThread timeoutThread = null;\n long requestId = ++__requestId;\n try {\n out = s.getOutputStream();\n BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream(), \"ISO-8859-1\"));\n StringBuffer newRequest = new StringBuffer();\n while ((line = br.readLine()) != null) {\n if (_log.shouldLog(Log.DEBUG))\n _log.debug(getPrefix() + \"Line=[\" + line + \"]\");\n _log.debug(getPrefix(requestId) + \"Line=[\" + line + \"]\");\n \n if (line.startsWith(\"Connection: \") || \n line.startsWith(\"Keep-Alive: \") || \n \n if (method == null) { // first line (GET /base64/realaddr)\n if (_log.shouldLog(Log.DEBUG))\n _log.debug(getPrefix() + \"Method is null for [\" + line + \"]\");\n _log.debug(getPrefix(requestId) + \"Method is null for [\" + line + \"]\");\n \n int pos = line.indexOf(\" \");\n if (pos == -1) break;\n line = method + \" \" + request.substring(pos);\n } else if (host.indexOf(\".\") != -1) {\n // The request must be forwarded to a WWW proxy\n if (_log.shouldLog(Log.DEBUG))\n _log.debug(\"Before selecting outproxy for \" + host);\n currentProxy = selectProxy();\n if (_log.shouldLog(Log.DEBUG))\n _log.debug(\"After selecting outproxy for \" + host + \": \" + currentProxy);\n if (currentProxy == null) {\n if (_log.shouldLog(Log.WARN))\n _log.warn(getPrefix(requestId) + \"Host wants to be outproxied, but we dont have any!\");\n l.log(\"No HTTP outproxy found for the request.\");\n if (out != null) {\n out.write(ERR_NO_OUTPROXY);\n out.write(\"

Generated on: \".getBytes());\n out.write(new Date().toString().getBytes());\n out.write(\"\\n\".getBytes());\n out.flush();\n }\n s.close();\n return;\n }\n destination = currentProxy;\n usingWWWProxy = true;\n if (_log.shouldLog(Log.DEBUG))\n _log.debug(getPrefix() + \"Host doesnt end with .i2p and it contains a period [\" + host + \"]: wwwProxy!\");\n _log.debug(getPrefix(requestId) + \"Host doesnt end with .i2p and it contains a period [\" + host + \"]: wwwProxy!\");\n } else {\n request = request.substring(pos + 1);\n pos = request.indexOf(\"/\");\n \n boolean isValid = usingWWWProxy || isSupportedAddress(host, protocol);\n if (!isValid) {\n if (_log.shouldLog(Log.INFO)) _log.info(getPrefix() + \"notValid(\" + host + \")\");\n if (_log.shouldLog(Log.INFO)) _log.info(getPrefix(requestId) + \"notValid(\" + host + \")\");\n method = null;\n destination = null;\n break;\n } else if (!usingWWWProxy) {\n if (_log.shouldLog(Log.INFO)) _log.info(getPrefix() + \"host=getHostName(\" + destination + \")\");\n if (_log.shouldLog(Log.INFO)) _log.info(getPrefix(requestId) + \"host=getHostName(\" + destination + \")\");\n host = getHostName(destination); // hide original host\n }\n \n if (_log.shouldLog(Log.DEBUG)) {\n _log.debug(getPrefix() + \"METHOD:\" + method + \":\");\n _log.debug(getPrefix() + \"PROTOC:\" + protocol + \":\");\n _log.debug(getPrefix() + \"HOST :\" + host + \":\");\n _log.debug(getPrefix() + \"DEST :\" + destination + \":\");\n _log.debug(getPrefix(requestId) + \"METHOD:\" + method + \":\");\n _log.debug(getPrefix(requestId) + \"PROTOC:\" + protocol + \":\");\n _log.debug(getPrefix(requestId) + \"HOST :\" + host + \":\");\n _log.debug(getPrefix(requestId) + \"DEST :\" + destination + \":\");\n }\n \n } else {\n if (line.startsWith(\"Host: \") && !usingWWWProxy) {\n line = \"Host: \" + host;\n if (_log.shouldLog(Log.INFO)) \n _log.info(getPrefix() + \"Setting host = \" + host);\n _log.info(getPrefix(requestId) + \"Setting host = \" + host);\n }\n }\n \n }\n }\n if (_log.shouldLog(Log.DEBUG))\n _log.debug(getPrefix() + \"NewRequest header: [\" + newRequest.toString() + \"]\");\n _log.debug(getPrefix(requestId) + \"NewRequest header: [\" + newRequest.toString() + \"]\");\n \n while (br.ready()) { // empty the buffer (POST requests)\n int i = br.read();\n }\n \n if (_log.shouldLog(Log.DEBUG))\n _log.debug(getPrefix() + \"Destination: \" + destination);\n _log.debug(getPrefix(requestId) + \"Destination: \" + destination);\n \n Destination dest = I2PTunnel.destFromName(destination);\n if (dest == null) {\n I2PSocket i2ps = createI2PSocket(dest);\n byte[] data = newRequest.toString().getBytes(\"ISO-8859-1\");\n I2PTunnelRunner runner = new I2PTunnelRunner(s, i2ps, sockLock, data);\n timeoutThread = new InactivityTimeoutThread(runner, out, targetRequest, usingWWWProxy, currentProxy, s);\n timeoutThread = new InactivityTimeoutThread(runner, out, targetRequest, usingWWWProxy, currentProxy, s, requestId);\n timeoutThread.start();\n } catch (SocketException ex) {\n if (timeoutThread != null) timeoutThread.disable();\n _log.info(getPrefix() + \"Error trying to connect\", ex);\n _log.info(getPrefix(requestId) + \"Error trying to connect\", ex);\n l.log(ex.getMessage());\n handleHTTPClientException(ex, out, targetRequest, usingWWWProxy, currentProxy);\n handleHTTPClientException(ex, out, targetRequest, usingWWWProxy, currentProxy, requestId);\n closeSocket(s);\n } catch (IOException ex) {\n if (timeoutThread != null) timeoutThread.disable();\n _log.info(getPrefix() + \"Error trying to connect\", ex);\n _log.info(getPrefix(requestId) + \"Error trying to connect\", ex);\n l.log(ex.getMessage());\n handleHTTPClientException(ex, out, targetRequest, usingWWWProxy, currentProxy);\n handleHTTPClientException(ex, out, targetRequest, usingWWWProxy, currentProxy, requestId);\n closeSocket(s);\n } catch (I2PException ex) {\n if (timeoutThread != null) timeoutThread.disable();\n _log.info(\"getPrefix() + Error trying to connect\", ex);\n _log.info(\"getPrefix(requestId) + Error trying to connect\", ex);\n l.log(ex.getMessage());\n handleHTTPClientException(ex, out, targetRequest, usingWWWProxy, currentProxy);\n handleHTTPClientException(ex, out, targetRequest, usingWWWProxy, currentProxy, requestId);\n closeSocket(s);\n }\n }\n private static volatile long __timeoutId = 0;\n \n private class InactivityTimeoutThread extends I2PThread {\n\n \n private Socket s;\n private I2PTunnelRunner _runner;\n private OutputStream _out;\n private String _targetRequest;\n private boolean _useWWWProxy;\n private String _currentProxy;\n private long _requestId;\n private boolean _disabled;\n private Object _disableLock = new Object();\n \n public InactivityTimeoutThread(I2PTunnelRunner runner, OutputStream out, String targetRequest,\n boolean useWWWProxy, String currentProxy, Socket s) {\n boolean useWWWProxy, String currentProxy, Socket s, long requestId) {\n this.s = s;\n _runner = runner;\n _out = out;\n _useWWWProxy = useWWWProxy;\n _currentProxy = currentProxy;\n _disabled = false;\n _requestId = requestId;\n long timeoutId = ++__timeoutId;\n setName(\"InactivityThread \" + getPrefix() + timeoutId);\n setName(\"InactivityThread \" + getPrefix(requestId) + timeoutId);\n }\n \n public void disable() {\n public void run() {\n while (!_disabled) {\n if (_runner.isFinished()) {\n if (_log.shouldLog(Log.INFO)) _log.info(getPrefix() + \"HTTP client request completed prior to timeout\");\n if (_log.shouldLog(Log.INFO)) _log.info(getPrefix(_requestId) + \"HTTP client request completed prior to timeout\");\n return;\n }\n if (_runner.getLastActivityOn() < Clock.getInstance().now() - INACTIVITY_TIMEOUT) {\n if (_runner.getStartedOn() < Clock.getInstance().now() - INACTIVITY_TIMEOUT) {\n if (_log.shouldLog(Log.WARN))\n _log.warn(getPrefix() + \"HTTP client request timed out (lastActivity: \"\n _log.warn(getPrefix(_requestId) + \"HTTP client request timed out (lastActivity: \"\n + new Date(_runner.getLastActivityOn()) + \", startedOn: \"\n + new Date(_runner.getStartedOn()) + \")\");\n timeout();\n }\n \n private void timeout() {\n _log.info(getPrefix() + \"Inactivity timeout reached\");\n _log.info(getPrefix(_requestId) + \"Inactivity timeout reached\");\n l.log(\"Inactivity timeout reached\");\n if (_out != null) {\n try {\n writeErrorMessage(ERR_TIMEOUT, _out, _targetRequest, _useWWWProxy, _currentProxy);\n }\n } catch (IOException ioe) {\n _log.warn(getPrefix() + \"Error writing out the 'timeout' message\", ioe);\n _log.warn(getPrefix(_requestId) + \"Error writing out the 'timeout' message\", ioe);\n }\n } else {\n _log.warn(getPrefix() + \"Client disconnected before we could say we timed out\");\n _log.warn(getPrefix(_requestId) + \"Client disconnected before we could say we timed out\");\n }\n closeSocket(s);\n }\n }\n \n private final static String getHostName(String host) {\n if (host == null) return null;\n try {\n Destination dest = I2PTunnel.destFromName(host);\n if (dest == null) return \"i2p\";\n }\n \n private void handleHTTPClientException(Exception ex, OutputStream out, String targetRequest,\n boolean usingWWWProxy, String wwwProxy) {\n boolean usingWWWProxy, String wwwProxy, long requestId) {\n \n if (_log.shouldLog(Log.WARN))\n _log.warn(\"Error sending to \" + wwwProxy + \" (proxy? \" + usingWWWProxy + \", request: \" + targetRequest, ex);\n _log.warn(getPrefix(requestId) + \"Error sending to \" + wwwProxy + \" (proxy? \" + usingWWWProxy + \", request: \" + targetRequest, ex);\n if (out != null) {\n try {\n writeErrorMessage(ERR_DESTINATION_UNKNOWN, out, targetRequest, usingWWWProxy, wwwProxy);\n } catch (IOException ioe) {\n _log.warn(getPrefix() + \"Error writing out the 'destination was unknown' \" + \"message\", ioe);\n _log.warn(getPrefix(requestId) + \"Error writing out the 'destination was unknown' \" + \"message\", ioe);\n }\n } else {\n _log.warn(getPrefix() + \"Client disconnected before we could say that destination \" + \"was unknown\", ex);\n _log.warn(getPrefix(requestId) + \"Client disconnected before we could say that destination \" + \"was unknown\", ex);\n }\n }\n "}}},{"rowIdx":199973,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"8a5e811c7fbc3eb660e8705cab306d317a379326"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"MightyPirates/OC-LuaJ,MightyPirates/OC-LuaJ"},"new_contents":{"kind":"string","value":"package org.luaj.vm2;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.UnsupportedEncodingException;\n\nimport junit.framework.TestCase;\n\nimport org.luaj.vm2.lib.jse.JsePlatform;\n\npublic class StringTest extends TestCase {\n\n\tprotected void setUp() throws Exception {\n\t\tJsePlatform.standardGlobals();\n\t}\n\n\tpublic void testToInputStream() throws IOException {\n\t\tLuaString str = LuaString.valueOf(\"Hello\");\n\t\t\n\t\tInputStream is = str.toInputStream();\n\t\t\n\t\tassertEquals( 'H', is.read() );\n\t\tassertEquals( 'e', is.read() );\n\t\tassertEquals( 2, is.skip( 2 ) );\n\t\tassertEquals( 'o', is.read() );\n\t\tassertEquals( -1, is.read() );\n\t\t\n\t\tassertTrue( is.markSupported() );\n\t\t\n\t\tis.reset();\n\t\t\n\t\tassertEquals( 'H', is.read() );\n\t\tis.mark( 4 );\n\t\t\n\t\tassertEquals( 'e', is.read() );\n\t\tis.reset();\n\t\tassertEquals( 'e', is.read() );\n\t\t\n\t\tLuaString substr = str.substring( 1, 4 );\n\t\tassertEquals( 3, substr.length() );\n\t\t\n\t\tis.close();\n\t\tis = substr.toInputStream();\n\t\t\n\t\tassertEquals( 'e', is.read() );\n\t\tassertEquals( 'l', is.read() );\n\t\tassertEquals( 'l', is.read() );\n\t\tassertEquals( -1, is.read() );\n\t\t\n\t\tis = substr.toInputStream();\n\t\tis.reset();\n\t\t\n\t\tassertEquals( 'e', is.read() );\n\t}\n\t\n\t\n\tprivate static final String userFriendly( String s ) {\n\t\tStringBuffer sb = new StringBuffer();\n\t\tfor ( int i=0, n=s.length(); i= 0x80 ) { \n\t\t\t\tsb.append( \"\\\\u\"+Integer.toHexString(0x10000+c).substring(1) );\n\t\t\t} else {\n\t\t\t\tsb.append( (char) c );\n\t\t\t}\n\t\t}\n\t\treturn sb.toString();\n\t}\n\n\tpublic void testUtf820482051() throws UnsupportedEncodingException {\n\t\tint i = 2048;\n\t\tchar[] c = { (char) (i+0), (char) (i+1), (char) (i+2), (char) (i+3) };\n\t\tString before = new String(c)+\" \"+i+\"-\"+(i+4);\n\t\tLuaString ls = LuaString.valueOf(before);\n\t\tString after = ls.tojstring();\n\t\tassertEquals( userFriendly( before ), userFriendly( after ) );\n\t}\n\t\n\tpublic void testUtf8() {\t\t\n\t\tfor ( int i=4; i<0xffff; i+=4 ) {\n\t\t\tchar[] c = { (char) (i+0), (char) (i+1), (char) (i+2), (char) (i+3) };\n\t\t\tString before = new String(c)+\" \"+i+\"-\"+(i+4);\n\t\t\tLuaString ls = LuaString.valueOf(before);\n\t\t\tString after = ls.tojstring();\n\t\t\tassertEquals( userFriendly( before ), userFriendly( after ) );\n\t\t}\n\t\tchar[] c = { (char) (1), (char) (2), (char) (3) };\n\t\tString before = new String(c)+\" 1-3\";\n\t\tLuaString ls = LuaString.valueOf(before);\n\t\tString after = ls.tojstring();\n\t\tassertEquals( userFriendly( before ), userFriendly( after ) );\n\t}\n\n\tpublic void testSpotCheckUtf8() throws UnsupportedEncodingException {\n\t\tbyte[] bytes = {(byte)194,(byte)160,(byte)194,(byte)161,(byte)194,(byte)162,(byte)194,(byte)163,(byte)194,(byte)164};\n\t\tString expected = new String(bytes, \"UTF8\");\n\t\tString actual = LuaString.valueOf(bytes).tojstring();\n\t\tchar[] d = actual.toCharArray();\n\t\tassertEquals(160, d[0]);\n\t\tassertEquals(161, d[1]);\n\t\tassertEquals(162, d[2]);\n\t\tassertEquals(163, d[3]);\n\t\tassertEquals(164, d[4]);\n\t\tassertEquals(expected, actual);\n\t}\n\t\n\tpublic void testNullTerminated() {\t\t\n\t\tchar[] c = { 'a', 'b', 'c', '\\0', 'd', 'e', 'f' };\n\t\tString before = new String(c);\n\t\tLuaString ls = LuaString.valueOf(before);\n\t\tString after = ls.tojstring();\n\t\tassertEquals( userFriendly( \"abc\\0def\" ), userFriendly( after ) );\n\t}\n\n\tpublic void testRecentStringsCacheDifferentHashcodes() {\n\t\tfinal byte[] abc = {'a', 'b', 'c' };\n\t\tfinal byte[] xyz = {'x', 'y', 'z' };\n\t\tfinal LuaString abc1 = LuaString.valueOf(abc);\n\t\tfinal LuaString xyz1 = LuaString.valueOf(xyz);\n\t\tfinal LuaString abc2 = LuaString.valueOf(abc);\n\t\tfinal LuaString xyz2 = LuaString.valueOf(xyz);\n\t\tfinal int mod = LuaString.RECENT_STRINGS_CACHE_SIZE;\n\t\tassertTrue(abc1.hashCode() % mod != xyz1.hashCode() % mod);\n\t\tassertSame(abc1, abc2);\n\t\tassertSame(xyz1, xyz2);\n\t}\n\n\tpublic void testRecentStringsCacheHashCollisionCacheHit() {\n\t\tfinal byte[] abc = {'a', 'b', 'c' };\n\t\tfinal byte[] lyz = {'l', 'y', 'z' }; // chosen to have hash collision with 'abc'\n\t\tfinal LuaString abc1 = LuaString.valueOf(abc);\n\t\tfinal LuaString abc2 = LuaString.valueOf(abc); // in cache: 'abc'\n\t\tfinal LuaString lyz1 = LuaString.valueOf(lyz);\n\t\tfinal LuaString lyz2 = LuaString.valueOf(lyz); // in cache: 'lyz'\n\t\tfinal int mod = LuaString.RECENT_STRINGS_CACHE_SIZE;\n\t\tassertEquals(abc1.hashCode() % mod, lyz1.hashCode() % mod);\n\t\tassertNotSame(abc1, lyz1);\n\t\tassertFalse(abc1.equals(lyz1));\n\t\tassertSame(abc1, abc2);\n\t\tassertSame(lyz1, lyz2);\n\t}\n\n\tpublic void testRecentStringsCacheHashCollisionCacheMiss() {\n\t\tfinal byte[] abc = {'a', 'b', 'c' };\n\t\tfinal byte[] lyz = {'l', 'y', 'z' }; // chosen to have hash collision with 'abc'\n\t\tfinal LuaString abc1 = LuaString.valueOf(abc);\n\t\tfinal LuaString lyz1 = LuaString.valueOf(lyz); // in cache: 'abc'\n\t\tfinal LuaString abc2 = LuaString.valueOf(abc); // in cache: 'lyz'\n\t\tfinal LuaString lyz2 = LuaString.valueOf(lyz); // in cache: 'abc'\n\t\tfinal int mod = LuaString.RECENT_STRINGS_CACHE_SIZE;\n\t\tassertEquals(abc1.hashCode() % mod, lyz1.hashCode() % mod);\n\t\tassertNotSame(abc1, lyz1);\n\t\tassertFalse(abc1.equals(lyz1));\n\t\tassertNotSame(abc1, abc2);\n\t\tassertNotSame(lyz1, lyz2);\n\t}\n\n\tpublic void testRecentStringsLongStrings() {\n\t\tbyte[] abc = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\".getBytes();\n\t\tassertTrue(abc.length > LuaString.RECENT_STRINGS_MAX_LENGTH);\n\t\tLuaString abc1 = LuaString.valueOf(abc);\n\t\tLuaString abc2 = LuaString.valueOf(abc);\n\t\tassertNotSame(abc1, abc2);\n\t}\n\n\tpublic void testRecentStringsUsingJavaStrings() {\n\t\tfinal String abc = \"abc\";\n\t\tfinal String lyz = \"lyz\"; // chosen to have hash collision with 'abc'\n\t\tfinal String xyz = \"xyz\";\n\n\t\tfinal LuaString abc1 = LuaString.valueOf(abc);\n\t\tfinal LuaString abc2 = LuaString.valueOf(abc);\n\t\tfinal LuaString lyz1 = LuaString.valueOf(lyz);\n\t\tfinal LuaString lyz2 = LuaString.valueOf(lyz);\n\t\tfinal LuaString xyz1 = LuaString.valueOf(xyz);\n\t\tfinal LuaString xyz2 = LuaString.valueOf(xyz);\n\t\tfinal int mod = LuaString.RECENT_STRINGS_CACHE_SIZE;\n\t\tassertEquals(abc1.hashCode() % mod, lyz1.hashCode() % mod);\n\t\tassertFalse(abc1.hashCode() % mod == xyz1.hashCode() % mod);\n\t\tassertSame(abc1, abc2);\n\t\tassertSame(lyz1, lyz2);\n\t\tassertSame(xyz1, xyz2);\n\n\t\tfinal LuaString abc3 = LuaString.valueOf(abc);\n\t\tfinal LuaString lyz3 = LuaString.valueOf(lyz);\n\t\tfinal LuaString xyz3 = LuaString.valueOf(xyz);\n\n\t\tfinal LuaString abc4 = LuaString.valueOf(abc);\n\t\tfinal LuaString lyz4 = LuaString.valueOf(lyz);\n\t\tfinal LuaString xyz4 = LuaString.valueOf(xyz);\n\t\tassertNotSame(abc3, abc4); // because of hash collision\n\t\tassertNotSame(lyz3, lyz4); // because of hash collision\n\t\tassertSame(xyz3, xyz4); // because hashes do not collide\n\t}\n\t\n\tpublic void testLongSubstringGetsOldBacking() {\n\t\tLuaString src = LuaString.valueOf(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\");\n\t\tLuaString sub1 = src.substring(10, 40);\n\t\tassertSame(src.m_bytes, sub1.m_bytes);\n\t\tassertEquals(sub1.m_offset, 10);\n\t\tassertEquals(sub1.m_length, 30);\n\t}\n\t\n\tpublic void testShortSubstringGetsNewBacking() {\n\t\tLuaString src = LuaString.valueOf(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\");\n\t\tLuaString sub1 = src.substring(10, 20);\n\t\tLuaString sub2 = src.substring(10, 20);\n\t\tassertEquals(sub1.m_offset, 0);\n\t\tassertEquals(sub1.m_length, 10);\n\t\tassertSame(sub1, sub2);\n\t\tassertFalse(src.m_bytes == sub1.m_bytes);\n\t}\n\t\n\tpublic void testShortSubstringOfVeryLongStringGetsNewBacking() {\n\t\tLuaString src = LuaString.valueOf(\n\t\t\t\t\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\" +\n\t\t\t\t\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\" );\n\t\tLuaString sub1 = src.substring(10, 50);\n\t\tLuaString sub2 = src.substring(10, 50);\n\t\tassertEquals(sub1.m_offset, 0);\n\t\tassertEquals(sub1.m_length, 40);\n\t\tassertFalse(sub1 == sub2);\n\t\tassertFalse(src.m_bytes == sub1.m_bytes);\n\t}\n}\n"},"new_file":{"kind":"string","value":"test/junit/org/luaj/vm2/StringTest.java"},"old_contents":{"kind":"string","value":"package org.luaj.vm2;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.UnsupportedEncodingException;\n\nimport junit.framework.TestCase;\n\nimport org.luaj.vm2.lib.jse.JsePlatform;\n\npublic class StringTest extends TestCase {\n\n\tprotected void setUp() throws Exception {\n\t\tJsePlatform.standardGlobals();\n\t}\n\n\tpublic void testToInputStream() throws IOException {\n\t\tLuaString str = LuaString.valueOf(\"Hello\");\n\t\t\n\t\tInputStream is = str.toInputStream();\n\t\t\n\t\tassertEquals( 'H', is.read() );\n\t\tassertEquals( 'e', is.read() );\n\t\tassertEquals( 2, is.skip( 2 ) );\n\t\tassertEquals( 'o', is.read() );\n\t\tassertEquals( -1, is.read() );\n\t\t\n\t\tassertTrue( is.markSupported() );\n\t\t\n\t\tis.reset();\n\t\t\n\t\tassertEquals( 'H', is.read() );\n\t\tis.mark( 4 );\n\t\t\n\t\tassertEquals( 'e', is.read() );\n\t\tis.reset();\n\t\tassertEquals( 'e', is.read() );\n\t\t\n\t\tLuaString substr = str.substring( 1, 4 );\n\t\tassertEquals( 3, substr.length() );\n\t\t\n\t\tis.close();\n\t\tis = substr.toInputStream();\n\t\t\n\t\tassertEquals( 'e', is.read() );\n\t\tassertEquals( 'l', is.read() );\n\t\tassertEquals( 'l', is.read() );\n\t\tassertEquals( -1, is.read() );\n\t\t\n\t\tis = substr.toInputStream();\n\t\tis.reset();\n\t\t\n\t\tassertEquals( 'e', is.read() );\n\t}\n\t\n\t\n\tprivate static final String userFriendly( String s ) {\n\t\tStringBuffer sb = new StringBuffer();\n\t\tfor ( int i=0, n=s.length(); i= 0x80 ) { \n\t\t\t\tsb.append( \"\\\\u\"+Integer.toHexString(0x10000+c).substring(1) );\n\t\t\t} else {\n\t\t\t\tsb.append( (char) c );\n\t\t\t}\n\t\t}\n\t\treturn sb.toString();\n\t}\n\n\tpublic void testUtf820482051() throws UnsupportedEncodingException {\n\t\tint i = 2048;\n\t\tchar[] c = { (char) (i+0), (char) (i+1), (char) (i+2), (char) (i+3) };\n\t\tString before = new String(c)+\" \"+i+\"-\"+(i+4);\n\t\tLuaString ls = LuaString.valueOf(before);\n\t\tString after = ls.tojstring();\n\t\tassertEquals( userFriendly( before ), userFriendly( after ) );\n\t}\n\t\n\tpublic void testUtf8() {\t\t\n\t\tfor ( int i=4; i<0xffff; i+=4 ) {\n\t\t\tchar[] c = { (char) (i+0), (char) (i+1), (char) (i+2), (char) (i+3) };\n\t\t\tString before = new String(c)+\" \"+i+\"-\"+(i+4);\n\t\t\tLuaString ls = LuaString.valueOf(before);\n\t\t\tString after = ls.tojstring();\n\t\t\tassertEquals( userFriendly( before ), userFriendly( after ) );\n\t\t}\n\t\tchar[] c = { (char) (1), (char) (2), (char) (3) };\n\t\tString before = new String(c)+\" 1-3\";\n\t\tLuaString ls = LuaString.valueOf(before);\n\t\tString after = ls.tojstring();\n\t\tassertEquals( userFriendly( before ), userFriendly( after ) );\n\t}\n\n\tpublic void testSpotCheckUtf8() throws UnsupportedEncodingException {\n\t\tbyte[] bytes = {(byte)194,(byte)160,(byte)194,(byte)161,(byte)194,(byte)162,(byte)194,(byte)163,(byte)194,(byte)164};\n\t\tString expected = new String(bytes, \"UTF8\");\n\t\tString actual = LuaString.valueOf(bytes).tojstring();\n\t\tchar[] d = actual.toCharArray();\n\t\tassertEquals(160, d[0]);\n\t\tassertEquals(161, d[1]);\n\t\tassertEquals(162, d[2]);\n\t\tassertEquals(163, d[3]);\n\t\tassertEquals(164, d[4]);\n\t\tassertEquals(expected, actual);\n\t}\n\t\n\tpublic void testNullTerminated() {\t\t\n\t\tchar[] c = { 'a', 'b', 'c', '\\0', 'd', 'e', 'f' };\n\t\tString before = new String(c);\n\t\tLuaString ls = LuaString.valueOf(before);\n\t\tString after = ls.tojstring();\n\t\tassertEquals( userFriendly( \"abc\\0def\" ), userFriendly( after ) );\n\t}\n\n\tpublic void testRecentStringsCacheDifferentHashcodes() {\n\t\tfinal byte[] abc = {'a', 'b', 'c' };\n\t\tfinal byte[] xyz = {'x', 'y', 'z' };\n\t\tfinal LuaString abc1 = LuaString.valueOf(abc);\n\t\tfinal LuaString xyz1 = LuaString.valueOf(xyz);\n\t\tfinal LuaString abc2 = LuaString.valueOf(abc);\n\t\tfinal LuaString xyz2 = LuaString.valueOf(xyz);\n\t\tfinal int mod = LuaString.RECENT_STRINGS_CACHE_SIZE;\n\t\tassertTrue(abc1.hashCode() % mod != xyz1.hashCode() % mod);\n\t\tassertSame(abc1, abc2);\n\t\tassertSame(xyz1, xyz2);\n\t}\n\n\tpublic void testRecentStringsCacheHashCollisionCacheHit() {\n\t\tfinal byte[] abc = {'a', 'b', 'c' };\n\t\tfinal byte[] lyz = {'l', 'y', 'z' }; // chosen to have hash collision with 'abc'\n\t\tfinal LuaString abc1 = LuaString.valueOf(abc);\n\t\tfinal LuaString abc2 = LuaString.valueOf(abc); // in cache: 'abc'\n\t\tfinal LuaString lyz1 = LuaString.valueOf(lyz);\n\t\tfinal LuaString lyz2 = LuaString.valueOf(lyz); // in cache: 'lyz'\n\t\tfinal int mod = LuaString.RECENT_STRINGS_CACHE_SIZE;\n\t\tassertEquals(abc1.hashCode() % mod, lyz1.hashCode() % mod);\n\t\tassertNotSame(abc1, lyz1);\n\t\tassertFalse(abc1.equals(lyz1));\n\t\tassertSame(abc1, abc2);\n\t\tassertSame(lyz1, lyz2);\n\t}\n\n\tpublic void testRecentStringsCacheHashCollisionCacheMiss() {\n\t\tfinal byte[] abc = {'a', 'b', 'c' };\n\t\tfinal byte[] lyz = {'l', 'y', 'z' }; // chosen to have hash collision with 'abc'\n\t\tfinal LuaString abc1 = LuaString.valueOf(abc);\n\t\tfinal LuaString lyz1 = LuaString.valueOf(lyz); // in cache: 'abc'\n\t\tfinal LuaString abc2 = LuaString.valueOf(abc); // in cache: 'lyz'\n\t\tfinal LuaString lyz2 = LuaString.valueOf(lyz); // in cache: 'abc'\n\t\tfinal int mod = LuaString.RECENT_STRINGS_CACHE_SIZE;\n\t\tassertEquals(abc1.hashCode() % mod, lyz1.hashCode() % mod);\n\t\tassertNotSame(abc1, lyz1);\n\t\tassertFalse(abc1.equals(lyz1));\n\t\tassertNotSame(abc1, abc2);\n\t\tassertNotSame(lyz1, lyz2);\n\t}\n\n\tpublic void testRecentStringsLongStrings() {\n\t\tbyte[] abc = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\".getBytes();\n\t\tassertTrue(abc.length > LuaString.RECENT_STRINGS_MAX_LENGTH);\n\t\tLuaString abc1 = LuaString.valueOf(abc);\n\t\tLuaString abc2 = LuaString.valueOf(abc);\n\t\tassertNotSame(abc1, abc2);\n\t}\n\n\tpublic void testRecentStringsUsingJavaStrings() {\n\t\tfinal String abc = \"abc\";\n\t\tfinal String lyz = \"lyz\"; // chosen to have hash collision with 'abc'\n\t\tfinal String xyz = \"xyz\";\n\n\t\tfinal LuaString abc1 = LuaString.valueOf(abc);\n\t\tfinal LuaString abc2 = LuaString.valueOf(abc);\n\t\tfinal LuaString lyz1 = LuaString.valueOf(lyz);\n\t\tfinal LuaString lyz2 = LuaString.valueOf(lyz);\n\t\tfinal LuaString xyz1 = LuaString.valueOf(xyz);\n\t\tfinal LuaString xyz2 = LuaString.valueOf(xyz);\n\t\tfinal int mod = LuaString.RECENT_STRINGS_CACHE_SIZE;\n\t\tassertEquals(abc1.hashCode() % mod, lyz1.hashCode() % mod);\n\t\tassertFalse(abc1.hashCode() % mod == xyz1.hashCode() % mod);\n\t\tassertSame(abc1, abc2);\n\t\tassertSame(lyz1, lyz2);\n\t\tassertSame(xyz1, xyz2);\n\n\t\tfinal LuaString abc3 = LuaString.valueOf(abc);\n\t\tfinal LuaString lyz3 = LuaString.valueOf(lyz);\n\t\tfinal LuaString xyz3 = LuaString.valueOf(xyz);\n\n\t\tfinal LuaString abc4 = LuaString.valueOf(abc);\n\t\tfinal LuaString lyz4 = LuaString.valueOf(lyz);\n\t\tfinal LuaString xyz4 = LuaString.valueOf(xyz);\n\t\tassertNotSame(abc3, abc4); // because of hash collision\n\t\tassertNotSame(lyz3, lyz4); // because of hash collision\n\t\tassertSame(xyz3, xyz4); // because hashes do not collide\n\t}\n\t\n\tpublic void testLongSubstringGetsOldBacking() {\n\t\tLuaString src = LuaString.valueOf(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\");\n\t\tLuaString sub1 = src.substring(10, 40);\n\t\tassertSame(src.m_bytes, sub1.m_bytes);\n\t\tassertEquals(sub1.m_offset, 10);\n\t\tassertEquals(sub1.m_length, 30);\n\t}\n\t\n\tpublic void testShortSubstringGetsNewBacking() {\n\t\tLuaString src = LuaString.valueOf(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\");\n\t\tLuaString sub1 = src.substring(10, 20);\n\t\tLuaString sub2 = src.substring(10, 20);\n\t\tassertEquals(sub1.m_offset, 0);\n\t\tassertEquals(sub1.m_length, 10);\n\t\tassertSame(sub1, sub2);\n\t\tassertFalse(src.m_bytes == sub1.m_bytes);\n\t}\n}\n"},"message":{"kind":"string","value":"Add test for long substring.\n"},"old_file":{"kind":"string","value":"test/junit/org/luaj/vm2/StringTest.java"},"subject":{"kind":"string","value":"Add test for long substring."},"git_diff":{"kind":"string","value":"est/junit/org/luaj/vm2/StringTest.java\n \t\tassertSame(sub1, sub2);\n \t\tassertFalse(src.m_bytes == sub1.m_bytes);\n \t}\n\t\n\tpublic void testShortSubstringOfVeryLongStringGetsNewBacking() {\n\t\tLuaString src = LuaString.valueOf(\n\t\t\t\t\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\" +\n\t\t\t\t\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\" );\n\t\tLuaString sub1 = src.substring(10, 50);\n\t\tLuaString sub2 = src.substring(10, 50);\n\t\tassertEquals(sub1.m_offset, 0);\n\t\tassertEquals(sub1.m_length, 40);\n\t\tassertFalse(sub1 == sub2);\n\t\tassertFalse(src.m_bytes == sub1.m_bytes);\n\t}\n }"}}},{"rowIdx":199974,"cells":{"lang":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"b56b3ca63f32eb01b9534e0a0d8b1fa2913cd40b"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"js-fns/date-fns,date-fns/date-fns,date-fns/date-fns,js-fns/date-fns,date-fns/date-fns"},"new_contents":{"kind":"string","value":"import path from 'path'\nimport fs from 'fs'\n\nconst files = fs.readdirSync(path.join(process.cwd(), 'src'))\n\nconst propertyRequireLines = files\n .filter((file) => file.match(/\\.js/))\n .map((file) => file.replace(/\\.js/, ''))\n .map((file) => ` ${camelize(file)}: require('./src/${file}')`)\n\nconst indexLines = ['module.exports = {']\n .concat(propertyRequireLines.join(',\\n'))\n .concat('}')\n\nfs.writeFileSync(path.join(process.cwd(), 'index.js'), `${indexLines.join('\\n')}\\n`)\n\nfunction camelize(str) {\n return str\n .split('_')\n .map((word, index) => {\n if (index === 0) {\n return word\n } else if (word === 'iso') {\n return 'ISO'\n } else {\n return word.charAt(0).toUpperCase() + word.slice(1)\n }\n })\n .join('')\n}\n"},"new_file":{"kind":"string","value":"scripts/generate_index.js"},"old_contents":{"kind":"string","value":"import path from 'path'\nimport fs from 'fs'\n\nconst files = fs.readdirSync(path.join(process.cwd(), 'src'))\n\nconst propertyRequireLines = files\n .filter((file) => file.match(/\\.js/))\n .map((file) => file.replace(/\\.js/, ''))\n .map((file) => ` ${camelize(file)}: require('./src/${file}')`)\n\nconst indexLines = ['module.exports = {']\n .concat(propertyRequireLines.join(',\\n'))\n .concat('}')\n\nfs.writeFileSync(path.join(process.cwd(), 'index.js'), `${indexLines.join('\\n')}\\n`)\n\nfunction camelize(str) {\n return str.replace(/[-_\\s]+(.)?/g, (match, c) => c ? c.toUpperCase() : '')\n}\n"},"message":{"kind":"string","value":"Fix scripts/generate_index.js so it correctly handles ISO week functions (closes #82)\n"},"old_file":{"kind":"string","value":"scripts/generate_index.js"},"subject":{"kind":"string","value":"Fix scripts/generate_index.js so it correctly handles ISO week functions (closes #82)"},"git_diff":{"kind":"string","value":"cripts/generate_index.js\n fs.writeFileSync(path.join(process.cwd(), 'index.js'), `${indexLines.join('\\n')}\\n`)\n \n function camelize(str) {\n return str.replace(/[-_\\s]+(.)?/g, (match, c) => c ? c.toUpperCase() : '')\n return str\n .split('_')\n .map((word, index) => {\n if (index === 0) {\n return word\n } else if (word === 'iso') {\n return 'ISO'\n } else {\n return word.charAt(0).toUpperCase() + word.slice(1)\n }\n })\n .join('')\n }"}}},{"rowIdx":199975,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"351cb517e2e6e5c357fb52c46b32bc527785a7ee"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"stanfy/enroscar,stanfy/enroscar"},"new_contents":{"kind":"string","value":"package com.stanfy.enroscar.goro;\n\nimport android.test.AndroidTestCase;\nimport android.test.FlakyTest;\n\nimport com.stanfy.enroscar.async.AsyncObserver;\nimport com.stanfy.enroscar.goro.support.AsyncGoro;\nimport com.stanfy.enroscar.goro.support.RxGoro;\n\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.CountDownLatch;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.Future;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.TimeoutException;\n\nimport rx.functions.Action0;\nimport rx.functions.Action1;\n\nimport static org.fest.assertions.api.Assertions.assertThat;\n\n/**\n * Test oneshot Goro usage.\n */\npublic class BoundGoroAndroidTest extends AndroidTestCase {\n\n private BoundGoro goro;\n\n private String res;\n\n private CountDownLatch scheduleSync;\n\n @Override\n protected void setUp() throws Exception {\n super.setUp();\n GoroService.setDelegateExecutor(null);\n goro = Goro.bindWith(getContext());\n res = \"fail\";\n\n scheduleSync = prepareScheduleSync();\n }\n\n private CountDownLatch prepareScheduleSync() throws InterruptedException {\n final CountDownLatch scheduleSync = new CountDownLatch(1);\n final CountDownLatch listenerSync = new CountDownLatch(1);\n GoroServiceAndroidTest.onMainThread(new Runnable() {\n @Override\n public void run() {\n goro.addTaskListener(new GoroListener() {\n @Override\n public void onTaskSchedule(Callable task, String queue) {\n scheduleSync.countDown();\n }\n\n @Override\n public void onTaskStart(Callable task) {\n\n }\n\n @Override\n public void onTaskFinish(Callable task, Object result) {\n\n }\n\n @Override\n public void onTaskCancel(Callable task) {\n\n }\n\n @Override\n public void onTaskError(Callable task, Throwable error) {\n\n }\n });\n listenerSync.countDown();\n }\n });\n listenerSync.await();\n return scheduleSync;\n }\n\n @FlakyTest\n public void testScheduleBindGet() {\n Future future = goro.schedule(new Callable() {\n @Override\n public Object call() throws Exception {\n throw new Exception(\"aha!\");\n }\n });\n goro.bindOneshot();\n awaitScheduling();\n\n try {\n future.get(10, TimeUnit.SECONDS);\n fail(\"Exception expected\");\n } catch (InterruptedException e) {\n throw new AssertionError(e);\n } catch (ExecutionException e) {\n assertEquals(\"aha!\", e.getCause().getMessage());\n } catch (TimeoutException e) {\n fail(\"Not executed\");\n }\n\n // unbound?\n // FIXME: bindOneShot is still flaky\n // assertNull(((BoundGoro.BoundGoroImpl) goro).getServiceObject());\n }\n\n private void awaitScheduling() {\n try {\n assertThat(scheduleSync.await(20, TimeUnit.SECONDS)).isTrue();\n } catch (InterruptedException e) {\n throw new AssertionError(e);\n }\n }\n\n @FlakyTest\n public void testScheduleObserveBind() {\n final CountDownLatch sync = new CountDownLatch(1);\n goro.schedule(new Callable() {\n @Override\n public String call() throws Exception {\n return \"ok\";\n }\n }).subscribe(new FutureObserver() {\n @Override\n public void onSuccess(String value) {\n res = value;\n sync.countDown();\n }\n @Override\n public void onError(Throwable error) {\n fail(error.getMessage());\n }\n });\n\n goro.bindOneshot();\n awaitScheduling();\n\n await(sync);\n\n // unbound?\n assertNull(((BoundGoro.BoundGoroImpl) goro).getServiceObject());\n\n assertEquals(\"ok\", res);\n }\n\n public void testWithAsyncIntegration() {\n final CountDownLatch sync = new CountDownLatch(1);\n new AsyncGoro(goro).schedule(new Callable() {\n @Override\n public String call() throws Exception {\n return \"async\";\n }\n }).subscribe(new AsyncObserver() {\n @Override\n public void onError(final Throwable e) {\n throw new AssertionError(e);\n }\n @Override\n public void onResult(final String data) {\n res = data;\n sync.countDown();\n }\n @Override\n public void onReset() {\n // nothing\n }\n });\n\n goro.bindOneshot();\n awaitScheduling();\n\n await(sync);\n assertEquals(\"async\", res);\n }\n\n public void testWithRxIntegration() {\n final CountDownLatch sync = new CountDownLatch(2);\n new RxGoro(goro).schedule(new Callable() {\n @Override\n public String call() throws Exception {\n return \"rx\";\n }\n }).doOnCompleted(new Action0() {\n @Override\n public void call() {\n sync.countDown();\n }\n }).subscribe(new Action1() {\n @Override\n public void call(String o) {\n res = o;\n sync.countDown();\n }\n });\n\n goro.bindOneshot();\n awaitScheduling();\n\n await(sync);\n\n assertEquals(\"rx\", res);\n }\n\n private void await(CountDownLatch sync) {\n try {\n assertEquals(true, sync.await(10, TimeUnit.SECONDS));\n } catch (InterruptedException e) {\n throw new AssertionError(e);\n }\n }\n\n}\n"},"new_file":{"kind":"string","value":"goro/core/src/androidTest/java/com/stanfy/enroscar/goro/BoundGoroAndroidTest.java"},"old_contents":{"kind":"string","value":"package com.stanfy.enroscar.goro;\n\nimport android.test.AndroidTestCase;\nimport android.test.FlakyTest;\n\nimport com.google.android.apps.common.testing.ui.espresso.Espresso;\nimport com.stanfy.enroscar.async.AsyncObserver;\nimport com.stanfy.enroscar.goro.support.AsyncGoro;\nimport com.stanfy.enroscar.goro.support.RxGoro;\n\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.CountDownLatch;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.Future;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.TimeoutException;\n\nimport rx.functions.Action0;\nimport rx.functions.Action1;\n\nimport static org.fest.assertions.api.Assertions.assertThat;\n\n/**\n * Test oneshot Goro usage.\n */\npublic class BoundGoroAndroidTest extends AndroidTestCase {\n\n private BoundGoro goro;\n\n private String res;\n\n private CountDownLatch scheduleSync;\n\n @Override\n protected void setUp() throws Exception {\n super.setUp();\n GoroService.setDelegateExecutor(null);\n goro = Goro.bindWith(getContext());\n res = \"fail\";\n\n scheduleSync = prepareScheduleSync();\n }\n\n private CountDownLatch prepareScheduleSync() throws InterruptedException {\n final CountDownLatch scheduleSync = new CountDownLatch(1);\n final CountDownLatch listenerSync = new CountDownLatch(1);\n GoroServiceAndroidTest.onMainThread(new Runnable() {\n @Override\n public void run() {\n goro.addTaskListener(new GoroListener() {\n @Override\n public void onTaskSchedule(Callable task, String queue) {\n scheduleSync.countDown();\n }\n\n @Override\n public void onTaskStart(Callable task) {\n\n }\n\n @Override\n public void onTaskFinish(Callable task, Object result) {\n\n }\n\n @Override\n public void onTaskCancel(Callable task) {\n\n }\n\n @Override\n public void onTaskError(Callable task, Throwable error) {\n\n }\n });\n listenerSync.countDown();\n }\n });\n listenerSync.await();\n return scheduleSync;\n }\n\n @FlakyTest\n public void testScheduleBindGet() {\n Future future = goro.schedule(new Callable() {\n @Override\n public Object call() throws Exception {\n throw new Exception(\"aha!\");\n }\n });\n goro.bindOneshot();\n awaitScheduling();\n\n try {\n future.get(10, TimeUnit.SECONDS);\n fail(\"Exception expected\");\n } catch (InterruptedException e) {\n throw new AssertionError(e);\n } catch (ExecutionException e) {\n assertEquals(\"aha!\", e.getCause().getMessage());\n } catch (TimeoutException e) {\n fail(\"Not executed\");\n }\n\n // unbound?\n // FIXME: bindOneShot is still flaky\n // assertNull(((BoundGoro.BoundGoroImpl) goro).getServiceObject());\n }\n\n private void awaitScheduling() {\n try {\n assertThat(scheduleSync.await(20, TimeUnit.SECONDS)).isTrue();\n } catch (InterruptedException e) {\n throw new AssertionError(e);\n }\n }\n\n @FlakyTest\n public void testScheduleObserveBind() {\n final CountDownLatch sync = new CountDownLatch(1);\n goro.schedule(new Callable() {\n @Override\n public String call() throws Exception {\n return \"ok\";\n }\n }).subscribe(new FutureObserver() {\n @Override\n public void onSuccess(String value) {\n res = value;\n sync.countDown();\n }\n @Override\n public void onError(Throwable error) {\n fail(error.getMessage());\n }\n });\n\n goro.bindOneshot();\n awaitScheduling();\n\n await(sync);\n\n // unbound?\n assertNull(((BoundGoro.BoundGoroImpl) goro).getServiceObject());\n\n assertEquals(\"ok\", res);\n }\n\n public void testWithAsyncIntegration() {\n final CountDownLatch sync = new CountDownLatch(1);\n new AsyncGoro(goro).schedule(new Callable() {\n @Override\n public String call() throws Exception {\n return \"async\";\n }\n }).subscribe(new AsyncObserver() {\n @Override\n public void onError(final Throwable e) {\n throw new AssertionError(e);\n }\n @Override\n public void onResult(final String data) {\n res = data;\n sync.countDown();\n }\n });\n\n goro.bindOneshot();\n awaitScheduling();\n\n await(sync);\n assertEquals(\"async\", res);\n }\n\n public void testWithRxIntegration() {\n final CountDownLatch sync = new CountDownLatch(2);\n new RxGoro(goro).schedule(new Callable() {\n @Override\n public String call() throws Exception {\n return \"rx\";\n }\n }).doOnCompleted(new Action0() {\n @Override\n public void call() {\n sync.countDown();\n }\n }).subscribe(new Action1() {\n @Override\n public void call(String o) {\n res = o;\n sync.countDown();\n }\n });\n\n goro.bindOneshot();\n awaitScheduling();\n\n await(sync);\n\n assertEquals(\"rx\", res);\n }\n\n private void await(CountDownLatch sync) {\n try {\n assertEquals(true, sync.await(10, TimeUnit.SECONDS));\n } catch (InterruptedException e) {\n throw new AssertionError(e);\n }\n }\n\n}\n"},"message":{"kind":"string","value":"fix test compilation\n"},"old_file":{"kind":"string","value":"goro/core/src/androidTest/java/com/stanfy/enroscar/goro/BoundGoroAndroidTest.java"},"subject":{"kind":"string","value":"fix test compilation"},"git_diff":{"kind":"string","value":"oro/core/src/androidTest/java/com/stanfy/enroscar/goro/BoundGoroAndroidTest.java\n import android.test.AndroidTestCase;\n import android.test.FlakyTest;\n \nimport com.google.android.apps.common.testing.ui.espresso.Espresso;\n import com.stanfy.enroscar.async.AsyncObserver;\n import com.stanfy.enroscar.goro.support.AsyncGoro;\n import com.stanfy.enroscar.goro.support.RxGoro;\n res = data;\n sync.countDown();\n }\n @Override\n public void onReset() {\n // nothing\n }\n });\n \n goro.bindOneshot();"}}},{"rowIdx":199976,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"bsd-3-clause"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"315d1cafd4c2427c125769376f7f0c0653e74853"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"bmc/curn,songfj/curn,songfj/curn,songfj/curn,songfj/curn,bmc/curn,bmc/curn,songfj/curn,bmc/curn,bmc/curn"},"new_contents":{"kind":"string","value":"/*---------------------------------------------------------------------------*\\\n $Id$\n ---------------------------------------------------------------------------\n This software is released under a Berkeley-style license:\n\n Copyright (c) 2004-2006 Brian M. Clapper. All rights reserved.\n\n Redistribution and use in source and binary forms are permitted provided\n that: (1) source distributions retain this entire copyright notice and\n comment; and (2) modifications made to the software are prominently\n mentioned, and a copy of the original software (or a pointer to its\n location) are included. The name of the author may not be used to endorse\n or promote products derived from this software without specific prior\n written permission.\n\n THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED\n WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF\n MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n\n Effectively, this means you can do what you want with the software except\n remove this notice or take advantage of the author's name. If you modify\n the software and redistribute your modified version, you must indicate that\n your version is a modification of the original, and you must provide either\n a pointer to or a copy of the original.\n\\*---------------------------------------------------------------------------*/\n\npackage org.clapper.curn;\n\nimport java.io.IOException;\nimport java.io.File;\nimport java.io.StringWriter;\nimport java.io.PrintWriter;\nimport java.text.ParseException;\nimport java.text.SimpleDateFormat;\nimport java.util.ArrayList;\nimport java.util.Calendar;\nimport java.util.Collection;\nimport java.util.Date;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.NoSuchElementException;\nimport java.util.Set;\n\nimport org.clapper.curn.parser.RSSChannel;\n\nimport org.clapper.util.cmdline.CommandLineUtility;\nimport org.clapper.util.cmdline.CommandLineException;\nimport org.clapper.util.cmdline.CommandLineUsageException;\nimport org.clapper.util.cmdline.UsageInfo;\nimport org.clapper.util.config.ConfigurationException;\nimport org.clapper.util.io.WordWrapWriter;\nimport org.clapper.util.logging.Logger;\nimport org.clapper.util.misc.BuildInfo;\n\n/**\n *

curn: Customizable Utilitarian RSS Notifier.

\n *\n *

curn is an RSS reader. It scans a configured set of URLs, each\n * one representing an RSS feed, and summarizes the results in an\n * easy-to-read text format. curn keeps track of URLs it's seen\n * before, using an on-disk cache; when using the cache, it will suppress\n * displaying URLs it has already reported (though that behavior can be\n * disabled). curn can be extended to use any RSS parser; its\n * built-in RSS parser, the\n * {@link org.clapper.curn.parser.minirss.MiniRSSParser MiniRSSParser}\n * class, can handle files in\n * {@link Atom}\n * format (0.3) and RSS formats\n * {@link 0.91},\n * 0.92,\n * {@link 1.0} and\n * {@link 2.0}.

\n *\n *

This class is a command-line wrapper for curn. Run it with\n * no parameters for a usage summary.

\n *\n * @version $Revision$\n */\npublic class Tool\n extends CommandLineUtility\n implements PostConfigPlugIn\n{\n /*----------------------------------------------------------------------*\\\n Private Constants\n \\*----------------------------------------------------------------------*/\n\n private static Collection DATE_FORMATS;\n\n static\n {\n DATE_FORMATS = new ArrayList();\n\n DATE_FORMATS.add (new DateParseInfo (\"yyyy/MM/dd hh:mm:ss a\", false));\n DATE_FORMATS.add (new DateParseInfo (\"yyyy/MM/dd hh:mm:ss\", false));\n DATE_FORMATS.add (new DateParseInfo (\"yyyy/MM/dd hh:mm a\", false));\n DATE_FORMATS.add (new DateParseInfo (\"yyyy/MM/dd hh:mm\", false));\n DATE_FORMATS.add (new DateParseInfo (\"yyyy/MM/dd h:mm a\", false));\n DATE_FORMATS.add (new DateParseInfo (\"yyyy/MM/dd h:mm\", false));\n DATE_FORMATS.add (new DateParseInfo (\"yyyy/MM/dd hh a\", false));\n DATE_FORMATS.add (new DateParseInfo (\"yyyy/MM/dd h a\", false));\n DATE_FORMATS.add (new DateParseInfo (\"yyyy/MM/dd HH:mm:ss\", false));\n DATE_FORMATS.add (new DateParseInfo (\"yyyy/MM/dd HH:mm\", false));\n DATE_FORMATS.add (new DateParseInfo (\"yyyy/MM/dd H:mm\", false));\n DATE_FORMATS.add (new DateParseInfo (\"yyyy/MM/dd\", false));\n DATE_FORMATS.add (new DateParseInfo (\"yy/MM/dd\", false));\n DATE_FORMATS.add (new DateParseInfo (\"hh:mm:ss a\", true));\n DATE_FORMATS.add (new DateParseInfo (\"hh:mm:ss\", true));\n DATE_FORMATS.add (new DateParseInfo (\"hh:mm a\", true));\n DATE_FORMATS.add (new DateParseInfo (\"hh:mm\", true));\n DATE_FORMATS.add (new DateParseInfo (\"h:mm a\", true));\n DATE_FORMATS.add (new DateParseInfo (\"h:mm\", true));\n DATE_FORMATS.add (new DateParseInfo (\"hh a\", true));\n DATE_FORMATS.add (new DateParseInfo (\"h a\", true));\n DATE_FORMATS.add (new DateParseInfo (\"HH:mm:ss a\", true));\n DATE_FORMATS.add (new DateParseInfo (\"HH:mm:ss\", true));\n DATE_FORMATS.add (new DateParseInfo (\"HH:mm a\", true));\n DATE_FORMATS.add (new DateParseInfo (\"HH:mm\", true));\n DATE_FORMATS.add (new DateParseInfo (\"H:mm a\", true));\n DATE_FORMATS.add (new DateParseInfo (\"H:mm\", true));\n };\n\n /*----------------------------------------------------------------------*\\\n Private Data Items\n \\*----------------------------------------------------------------------*/\n\n private String configPath = null;\n private boolean useCache = true;\n private Date currentTime = new Date();\n private boolean optShowBuildInfo = false;\n private boolean optShowVersion = false;\n private Boolean optShowDates = null;\n private Boolean optShowAuthors = null;\n private Boolean optRSSVersion = null;\n private Boolean optUpdateCache = null;\n private boolean useGzip = true;\n private int maxThreads = 0;\n\n /**\n * For log messages\n */\n private static Logger log = new Logger (Tool.class);\n\n /*----------------------------------------------------------------------*\\\n Main Program\n \\*----------------------------------------------------------------------*/\n\n public static void main (String[] args)\n {\n Tool tool = new Tool();\n\n try\n {\n tool.execute (args);\n }\n\n catch (CommandLineUsageException ex)\n {\n // Already reported\n\n System.exit (1);\n }\n\n catch (CommandLineException ex)\n {\n WordWrapWriter err = new WordWrapWriter (System.err);\n\n //err.println (ex.getMessage());\n ex.printStackTrace (System.err);\n System.exit (1);\n }\n\n catch (Exception ex)\n {\n ex.printStackTrace (System.err);\n System.exit (1);\n }\n }\n\n /*----------------------------------------------------------------------*\\\n Constructor\n \\*----------------------------------------------------------------------*/\n\n private Tool()\n {\n }\n\n /*----------------------------------------------------------------------*\\\n Public Methods Required by PlugIn Interface\n \\*----------------------------------------------------------------------*/\n\n public String getName()\n {\n return \"curn command-line interface\";\n }\n\n public void runPostConfigPlugIn (CurnConfig config)\n\tthrows CurnException\n {\n try\n {\n adjustConfiguration (config);\n }\n\n catch (ConfigurationException ex)\n {\n throw new CurnException (ex);\n }\n }\n\n /*----------------------------------------------------------------------*\\\n Protected Methods\n \\*----------------------------------------------------------------------*/\n\n /**\n * Called by parseParams() to handle any option it doesn't\n * recognize. If the option takes any parameters, the overridden\n * method must extract the parameter by advancing the supplied\n * Iterator (which returns String objects). This\n * default method simply throws an exception.\n *\n * @param shortOption the short option character, or\n * {@link UsageInfo#NO_SHORT_OPTION} if there isn't\n * one (i.e., if this is a long-only option).\n * @param longOption the long option string, without any leading\n * \"-\" characters, or null if this is a short-only\n * option\n * @param it the Iterator for the remainder of the\n * command line, for extracting parameters.\n *\n * @throws CommandLineUsageException on error\n * @throws NoSuchElementException overran the iterator (i.e., missing\n * parameter) \n */\n protected void parseCustomOption (char shortOption,\n String longOption,\n Iterator it)\n throws CommandLineUsageException,\n NoSuchElementException\n {\n switch (shortOption)\n {\n case 'a': // --authors\n optShowAuthors = Boolean.TRUE;\n break;\n\n case 'A': // --no-authors\n optShowAuthors = Boolean.FALSE;\n break;\n\n case 'B': // --build-info\n optShowBuildInfo = true;\n break;\n\n case 'C': // --no-cache\n useCache = false;\n break;\n\n case 'd': // --show-dates\n optShowDates = Boolean.TRUE;\n break;\n\n case 'D': // --no-dates\n optShowDates = Boolean.FALSE;\n break;\n\n case 'r': // --rss-version\n optRSSVersion = Boolean.TRUE;\n break;\n\n case 'R': // --no-rss-version\n optRSSVersion = Boolean.FALSE;\n break;\n\n case 't': // --time\n currentTime = parseDateTime (it.next());\n break;\n\n case 'T': // --threads\n String arg = it.next();\n\n try\n {\n maxThreads = Integer.parseInt (arg);\n if (maxThreads < 1)\n {\n throw new CommandLineUsageException\n (Constants.BUNDLE_NAME, \"Tool.negNumericOption\",\n \"Value for \\\"{0}\\\" (\\\"{1}\\\") option must be \"\n + \"greater than 0\",\n new Object[] {\"-t\", \"--threads\"});\n }\n }\n\n catch (NumberFormatException ex)\n {\n throw new CommandLineUsageException\n (Constants.BUNDLE_NAME, \"Tool.badNumericOption\",\n \"Bad numeric value \\\"{0}\\\" for \\\"{1}\\\" (\\\"{2}\\\") \"\n + \"option\",\n new Object[]\n {\n arg,\n \"-T\",\n \"--threads\"\n });\n }\n break;\n\n case 'u': // --no-update\n optUpdateCache = Boolean.FALSE;\n break;\n\n case 'v':\n optShowVersion = true;\n break;\n\n case 'z': // --gzip\n useGzip = true;\n break;\n\n case 'Z': // --no-gzip\n useGzip = false;\n break;\n\n default:\n // Should not happen.\n throw new IllegalStateException (\"(BUG) Unknown option. \"\n + \"Why am I here?\");\n }\n }\n\n /**\n *

Called by parseParams() once option parsing is complete,\n * this method must handle any additional parameters on the command\n * line. It's not necessary for the method to ensure that the iterator\n * has the right number of strings left in it. If you attempt to pull\n * too many parameters from the iterator, it'll throw a\n * NoSuchElementException, which parseParams() traps\n * and converts into a suitable error message. Similarly, if there are\n * any parameters left in the iterator when this method returns,\n * parseParams() throws an exception indicating that there are\n * too many parameters on the command line.

\n *\n *

This method is called unconditionally, even if there are no\n * parameters left on the command line, so it's a useful place to do\n * post-option consistency checks, as well.

\n *\n * @param it the Iterator for the remainder of the\n * command line\n *\n * @throws CommandLineUsageException on error\n * @throws NoSuchElementException attempt to iterate past end of args;\n * parseParams() automatically\n * handles this exception, so it's\n * safe for subclass implementations of\n * this method not to handle it\n */\n protected void processPostOptionCommandLine (Iterator it)\n throws CommandLineUsageException,\n NoSuchElementException\n {\n // If we're showing build information or the version, forget about\n // the remainder of the command line.\n\n if (! (optShowBuildInfo || optShowVersion))\n configPath = it.next();\n }\n\n /**\n * Called by parseParams() to get the custom command-line\n * options and parameters handled by the subclass. This list is used\n * solely to build a usage message. The overridden method must fill the\n * supplied UsageInfo object:\n *\n *
    \n *
  • Each parameter must be added to the object, via the\n * UsageInfo.addParameter() method. The first argument\n * to addParameter() is the parameter string (e.g.,\n * \"\" or \"input_file\"). The second parameter is the\n * one-line description. The description may be of any length,\n * but it should be a single line.\n *\n *
  • Each option must be added to the object, via the\n * UsageInfo.addOption() method. The first argument to\n * addOption() is the option string (e.g., \"-x\" or\n * \"-version\"). The second parameter is the one-line\n * description. The description may be of any length, but it\n * should be a single line.\n *
\n *\n * That information will be combined with the common options supported\n * by the base class, and used to build a usage message.\n *\n * @param info The UsageInfo object to fill.\n */\n protected void getCustomUsageInfo (UsageInfo info)\n {\n info.addOption ('a', \"show-authors\",\n \"Show the authors for each item, if available.\");\n info.addOption ('A', \"no-authors\",\n \"Don't the authors for each item, if available.\");\n info.addOption ('B', \"build-info\",\n \"Show full build information, then exit. \"\n + \"This option shows a bit more information than the \"\n + UsageInfo.LONG_OPTION_PREFIX\n + \"version option\");\n info.addOption ('C', \"no-cache\", \"Don't use a cache file at all.\");\n info.addOption ('d', \"show-dates\",\n \"Show dates on feeds and feed items, if available.\");\n info.addOption ('D', \"no-dates\",\n \"Don't show dates on feeds and feed items.\");\n info.addOption ('r', \"rss-version\",\n \"Show the RSS version each site uses.\");\n info.addOption ('R', \"no-rss-version\",\n \"Don't show the RSS version each site uses.\");\n info.addOption ('T', \"threads\", \"\",\n \"Set the number of concurrent download threads to \"\n + \". must be greater than 0.\");\n info.addOption ('u', \"no-update\",\n \"Read the cache, but don't update it.\");\n info.addOption ('v', \"version\",\n \"Show version information, then exit.\");\n info.addOption ('z', \"gzip\",\n \"Ask remote HTTP servers to gzip content before \"\n + \"sending it.\");\n info.addOption ('Z', \"no-gzip\",\n \"Don't ask remote HTTP servers to gzip content before \"\n + \"sending it.\");\n\n StringWriter sw = new StringWriter();\n PrintWriter pw = new PrintWriter (sw);\n Date sampleDate;\n BuildInfo buildInfo = Version.getBuildInfo(); \n SimpleDateFormat dateFormat;\n String dateString = buildInfo.getBuildDate();\n\n try\n {\n dateFormat = new SimpleDateFormat (BuildInfo.DATE_FORMAT_STRING);\n sampleDate = dateFormat.parse (dateString);\n }\n\n catch (Exception ex)\n {\n log.error (\"Can't parse build date string \\\"\"\n + dateString\n + \"\\\" using format \\\"\"\n + BuildInfo.DATE_FORMAT_STRING\n + \"\\\"\",\n ex);\n sampleDate = new Date();\n }\n\n Set printed = new HashSet();\n for (DateParseInfo dpi : DATE_FORMATS)\n {\n String s = dpi.formatDate (sampleDate);\n if (! printed.contains (s))\n {\n pw.println();\n pw.print (s);\n printed.add (s);\n }\n }\n\n info.addOption ('t', \"time\", \"