id
int32
0
165k
repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
16,100
rundeck/rundeck
core/src/main/java/com/dtolabs/rundeck/core/plugins/DirPluginScanner.java
DirPluginScanner.isExpired
public boolean isExpired(final ProviderIdent ident, final File file) { return !file.exists() || !scannedFiles.contains(memoize(file)); }
java
public boolean isExpired(final ProviderIdent ident, final File file) { return !file.exists() || !scannedFiles.contains(memoize(file)); }
[ "public", "boolean", "isExpired", "(", "final", "ProviderIdent", "ident", ",", "final", "File", "file", ")", "{", "return", "!", "file", ".", "exists", "(", ")", "||", "!", "scannedFiles", ".", "contains", "(", "memoize", "(", "file", ")", ")", ";", "}" ]
Return true if the entry has expired
[ "Return", "true", "if", "the", "entry", "has", "expired" ]
8070f774f55bffaa1118ff0c03aea319d40a9668
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/plugins/DirPluginScanner.java#L131-L133
16,101
rundeck/rundeck
core/src/main/java/com/dtolabs/rundeck/core/plugins/DirPluginScanner.java
DirPluginScanner.scanFor
private File scanFor(final ProviderIdent ident, final File[] files) throws PluginScannerException { final List<FileCache.MemoFile> candidates = new ArrayList<>(); HashSet<FileCache.MemoFile> prescanned = new HashSet<>(scannedFiles); HashSet<FileCache.MemoFile> newscanned = new HashSet<>(); for (final File file : files) { FileCache.MemoFile memo = memoize(file); if (cachedFileValidity(file)) { newscanned.add(memo); if (test(ident, file)) { candidates.add(memo); } } prescanned.remove(memo); } clearMemos(prescanned); scannedFiles = newscanned; if (candidates.size() == 1) { return candidates.get(0).getFile(); } if (candidates.size() > 1) { final File resolved = resolveProviderConflict(candidates); if(null==resolved) { log.warn( "More than one plugin file matched: " + StringArrayUtil.asString(candidates.toArray(), ",") +": "+ ident ); } else { return resolved; } } return null; }
java
private File scanFor(final ProviderIdent ident, final File[] files) throws PluginScannerException { final List<FileCache.MemoFile> candidates = new ArrayList<>(); HashSet<FileCache.MemoFile> prescanned = new HashSet<>(scannedFiles); HashSet<FileCache.MemoFile> newscanned = new HashSet<>(); for (final File file : files) { FileCache.MemoFile memo = memoize(file); if (cachedFileValidity(file)) { newscanned.add(memo); if (test(ident, file)) { candidates.add(memo); } } prescanned.remove(memo); } clearMemos(prescanned); scannedFiles = newscanned; if (candidates.size() == 1) { return candidates.get(0).getFile(); } if (candidates.size() > 1) { final File resolved = resolveProviderConflict(candidates); if(null==resolved) { log.warn( "More than one plugin file matched: " + StringArrayUtil.asString(candidates.toArray(), ",") +": "+ ident ); } else { return resolved; } } return null; }
[ "private", "File", "scanFor", "(", "final", "ProviderIdent", "ident", ",", "final", "File", "[", "]", "files", ")", "throws", "PluginScannerException", "{", "final", "List", "<", "FileCache", ".", "MemoFile", ">", "candidates", "=", "new", "ArrayList", "<>", "(", ")", ";", "HashSet", "<", "FileCache", ".", "MemoFile", ">", "prescanned", "=", "new", "HashSet", "<>", "(", "scannedFiles", ")", ";", "HashSet", "<", "FileCache", ".", "MemoFile", ">", "newscanned", "=", "new", "HashSet", "<>", "(", ")", ";", "for", "(", "final", "File", "file", ":", "files", ")", "{", "FileCache", ".", "MemoFile", "memo", "=", "memoize", "(", "file", ")", ";", "if", "(", "cachedFileValidity", "(", "file", ")", ")", "{", "newscanned", ".", "add", "(", "memo", ")", ";", "if", "(", "test", "(", "ident", ",", "file", ")", ")", "{", "candidates", ".", "add", "(", "memo", ")", ";", "}", "}", "prescanned", ".", "remove", "(", "memo", ")", ";", "}", "clearMemos", "(", "prescanned", ")", ";", "scannedFiles", "=", "newscanned", ";", "if", "(", "candidates", ".", "size", "(", ")", "==", "1", ")", "{", "return", "candidates", ".", "get", "(", "0", ")", ".", "getFile", "(", ")", ";", "}", "if", "(", "candidates", ".", "size", "(", ")", ">", "1", ")", "{", "final", "File", "resolved", "=", "resolveProviderConflict", "(", "candidates", ")", ";", "if", "(", "null", "==", "resolved", ")", "{", "log", ".", "warn", "(", "\"More than one plugin file matched: \"", "+", "StringArrayUtil", ".", "asString", "(", "candidates", ".", "toArray", "(", ")", ",", "\",\"", ")", "+", "\": \"", "+", "ident", ")", ";", "}", "else", "{", "return", "resolved", ";", "}", "}", "return", "null", ";", "}" ]
Return the first valid file found
[ "Return", "the", "first", "valid", "file", "found" ]
8070f774f55bffaa1118ff0c03aea319d40a9668
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/plugins/DirPluginScanner.java#L147-L181
16,102
rundeck/rundeck
core/src/main/java/com/dtolabs/rundeck/core/execution/impl/jsch/NodeSSHConnectionInfo.java
NodeSSHConnectionInfo.resolve
private String resolve(final String propName) { return ResolverUtil.resolveProperty(propName, null, node, frameworkProject, framework); }
java
private String resolve(final String propName) { return ResolverUtil.resolveProperty(propName, null, node, frameworkProject, framework); }
[ "private", "String", "resolve", "(", "final", "String", "propName", ")", "{", "return", "ResolverUtil", ".", "resolveProperty", "(", "propName", ",", "null", ",", "node", ",", "frameworkProject", ",", "framework", ")", ";", "}" ]
Resolve a property by looking for node attribute, project, then framework value @param propName @return
[ "Resolve", "a", "property", "by", "looking", "for", "node", "attribute", "project", "then", "framework", "value" ]
8070f774f55bffaa1118ff0c03aea319d40a9668
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/execution/impl/jsch/NodeSSHConnectionInfo.java#L177-L179
16,103
rundeck/rundeck
core/src/main/java/com/dtolabs/rundeck/core/execution/impl/jsch/NodeSSHConnectionInfo.java
NodeSSHConnectionInfo.nonBlank
public static String nonBlank(final String input) { if (null == input || "".equals(input.trim())) { return null; } else { return input.trim(); } }
java
public static String nonBlank(final String input) { if (null == input || "".equals(input.trim())) { return null; } else { return input.trim(); } }
[ "public", "static", "String", "nonBlank", "(", "final", "String", "input", ")", "{", "if", "(", "null", "==", "input", "||", "\"\"", ".", "equals", "(", "input", ".", "trim", "(", ")", ")", ")", "{", "return", "null", ";", "}", "else", "{", "return", "input", ".", "trim", "(", ")", ";", "}", "}" ]
Return null if the input is null or empty or whitespace, otherwise return the input string trimmed.
[ "Return", "null", "if", "the", "input", "is", "null", "or", "empty", "or", "whitespace", "otherwise", "return", "the", "input", "string", "trimmed", "." ]
8070f774f55bffaa1118ff0c03aea319d40a9668
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/execution/impl/jsch/NodeSSHConnectionInfo.java#L280-L286
16,104
rundeck/rundeck
core/src/main/java/com/dtolabs/rundeck/core/utils/JARVerifier.java
JARVerifier.verifySingleJarFile
public final void verifySingleJarFile(JarFile jf) throws IOException, CertificateException, VerifierException { Vector entriesVec = new Vector(); // Ensure there is a manifest file Manifest man = jf.getManifest(); if (man == null) { throw new VerifierException("The JAR is not signed"); } // Ensure all the entries' signatures verify correctly byte[] buffer = new byte[8192]; Enumeration entries = jf.entries(); while (entries.hasMoreElements()) { JarEntry je = (JarEntry) entries.nextElement(); entriesVec.addElement(je); InputStream is = jf.getInputStream(je); int n; while ((n = is.read(buffer, 0, buffer.length)) != -1) { // we just read. this will throw a SecurityException // if a signature/digest check fails. } is.close(); } jf.close(); // Get the list of signer certificates Enumeration e = entriesVec.elements(); while (e.hasMoreElements()) { JarEntry je = (JarEntry) e.nextElement(); if (je.isDirectory()) { continue; } // Every file must be signed - except // files in META-INF Certificate[] certs = je.getCertificates(); if ((certs == null) || (certs.length == 0)) { if (!je.getName().startsWith("META-INF")) { throw new VerifierException("The JAR file has unsigned files."); } } else { // Check whether the file // is signed as expected. // The framework may be signed by // multiple signers. At least one of // the signers must be a trusted signer. // First, determine the roots of the certificate chains Certificate[] chainRoots = getChainRoots(certs); boolean signedAsExpected = false; for (int i = 0; i < chainRoots.length; i++) { if (isTrusted((X509Certificate) chainRoots[i], trustedCaCerts)) { signedAsExpected = true; break; } } if (!signedAsExpected) { throw new VerifierException("The JAR file is not signed by a trusted signer"); } } } }
java
public final void verifySingleJarFile(JarFile jf) throws IOException, CertificateException, VerifierException { Vector entriesVec = new Vector(); // Ensure there is a manifest file Manifest man = jf.getManifest(); if (man == null) { throw new VerifierException("The JAR is not signed"); } // Ensure all the entries' signatures verify correctly byte[] buffer = new byte[8192]; Enumeration entries = jf.entries(); while (entries.hasMoreElements()) { JarEntry je = (JarEntry) entries.nextElement(); entriesVec.addElement(je); InputStream is = jf.getInputStream(je); int n; while ((n = is.read(buffer, 0, buffer.length)) != -1) { // we just read. this will throw a SecurityException // if a signature/digest check fails. } is.close(); } jf.close(); // Get the list of signer certificates Enumeration e = entriesVec.elements(); while (e.hasMoreElements()) { JarEntry je = (JarEntry) e.nextElement(); if (je.isDirectory()) { continue; } // Every file must be signed - except // files in META-INF Certificate[] certs = je.getCertificates(); if ((certs == null) || (certs.length == 0)) { if (!je.getName().startsWith("META-INF")) { throw new VerifierException("The JAR file has unsigned files."); } } else { // Check whether the file // is signed as expected. // The framework may be signed by // multiple signers. At least one of // the signers must be a trusted signer. // First, determine the roots of the certificate chains Certificate[] chainRoots = getChainRoots(certs); boolean signedAsExpected = false; for (int i = 0; i < chainRoots.length; i++) { if (isTrusted((X509Certificate) chainRoots[i], trustedCaCerts)) { signedAsExpected = true; break; } } if (!signedAsExpected) { throw new VerifierException("The JAR file is not signed by a trusted signer"); } } } }
[ "public", "final", "void", "verifySingleJarFile", "(", "JarFile", "jf", ")", "throws", "IOException", ",", "CertificateException", ",", "VerifierException", "{", "Vector", "entriesVec", "=", "new", "Vector", "(", ")", ";", "// Ensure there is a manifest file", "Manifest", "man", "=", "jf", ".", "getManifest", "(", ")", ";", "if", "(", "man", "==", "null", ")", "{", "throw", "new", "VerifierException", "(", "\"The JAR is not signed\"", ")", ";", "}", "// Ensure all the entries' signatures verify correctly", "byte", "[", "]", "buffer", "=", "new", "byte", "[", "8192", "]", ";", "Enumeration", "entries", "=", "jf", ".", "entries", "(", ")", ";", "while", "(", "entries", ".", "hasMoreElements", "(", ")", ")", "{", "JarEntry", "je", "=", "(", "JarEntry", ")", "entries", ".", "nextElement", "(", ")", ";", "entriesVec", ".", "addElement", "(", "je", ")", ";", "InputStream", "is", "=", "jf", ".", "getInputStream", "(", "je", ")", ";", "int", "n", ";", "while", "(", "(", "n", "=", "is", ".", "read", "(", "buffer", ",", "0", ",", "buffer", ".", "length", ")", ")", "!=", "-", "1", ")", "{", "// we just read. this will throw a SecurityException", "// if a signature/digest check fails.", "}", "is", ".", "close", "(", ")", ";", "}", "jf", ".", "close", "(", ")", ";", "// Get the list of signer certificates", "Enumeration", "e", "=", "entriesVec", ".", "elements", "(", ")", ";", "while", "(", "e", ".", "hasMoreElements", "(", ")", ")", "{", "JarEntry", "je", "=", "(", "JarEntry", ")", "e", ".", "nextElement", "(", ")", ";", "if", "(", "je", ".", "isDirectory", "(", ")", ")", "{", "continue", ";", "}", "// Every file must be signed - except", "// files in META-INF", "Certificate", "[", "]", "certs", "=", "je", ".", "getCertificates", "(", ")", ";", "if", "(", "(", "certs", "==", "null", ")", "||", "(", "certs", ".", "length", "==", "0", ")", ")", "{", "if", "(", "!", "je", ".", "getName", "(", ")", ".", "startsWith", "(", "\"META-INF\"", ")", ")", "{", "throw", "new", "VerifierException", "(", "\"The JAR file has unsigned files.\"", ")", ";", "}", "}", "else", "{", "// Check whether the file", "// is signed as expected.", "// The framework may be signed by", "// multiple signers. At least one of", "// the signers must be a trusted signer.", "// First, determine the roots of the certificate chains", "Certificate", "[", "]", "chainRoots", "=", "getChainRoots", "(", "certs", ")", ";", "boolean", "signedAsExpected", "=", "false", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "chainRoots", ".", "length", ";", "i", "++", ")", "{", "if", "(", "isTrusted", "(", "(", "X509Certificate", ")", "chainRoots", "[", "i", "]", ",", "trustedCaCerts", ")", ")", "{", "signedAsExpected", "=", "true", ";", "break", ";", "}", "}", "if", "(", "!", "signedAsExpected", ")", "{", "throw", "new", "VerifierException", "(", "\"The JAR file is not signed by a trusted signer\"", ")", ";", "}", "}", "}", "}" ]
Verify the JAR file signatures with the trusted CA certificates. @param jf jar file @throws IOException on io error @throws CertificateException on cert error @throws VerifierException If the jar file cannot be verified.
[ "Verify", "the", "JAR", "file", "signatures", "with", "the", "trusted", "CA", "certificates", "." ]
8070f774f55bffaa1118ff0c03aea319d40a9668
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/utils/JARVerifier.java#L141-L207
16,105
rundeck/rundeck
core/src/main/java/com/dtolabs/rundeck/core/execution/workflow/steps/node/impl/DefaultScriptFileNodeStepUtils.java
DefaultScriptFileNodeStepUtils.executeScriptFile
@Override public NodeStepResult executeScriptFile( StepExecutionContext context, INodeEntry node, String scriptString, String serverScriptFilePath, InputStream scriptAsStream, String fileExtension, String[] args, String scriptInterpreter, boolean quoted, final NodeExecutionService executionService, final boolean expandTokens ) throws NodeStepException { final String filename; if (null != scriptString) { filename = "dispatch-script.tmp"; } else if (null != serverScriptFilePath) { filename = new File(serverScriptFilePath).getName(); } else { filename = "dispatch-script.tmp"; } String ident = null != context.getDataContext() && null != context.getDataContext().get("job") ? context.getDataContext().get("job").get("execid") : null; String filepath = fileCopierUtil.generateRemoteFilepathForNode( node, context.getFramework().getFrameworkProjectMgr().getFrameworkProject(context.getFrameworkProject()), context.getFramework(), filename, fileExtension, ident ); try { File temp = writeScriptToTempFile( context, node, scriptString, serverScriptFilePath, scriptAsStream, expandTokens ); try { filepath = executionService.fileCopyFile( context, temp, node, filepath ); } finally { //clean up ScriptfileUtils.releaseTempFile(temp); } } catch (FileCopierException e) { throw new NodeStepException( e.getMessage(), e, e.getFailureReason(), node.getNodename() ); } catch (ExecutionException e) { throw new NodeStepException( e.getMessage(), e, e.getFailureReason(), node.getNodename() ); } return executeRemoteScript( context, context.getFramework(), node, args, filepath, scriptInterpreter, quoted ); }
java
@Override public NodeStepResult executeScriptFile( StepExecutionContext context, INodeEntry node, String scriptString, String serverScriptFilePath, InputStream scriptAsStream, String fileExtension, String[] args, String scriptInterpreter, boolean quoted, final NodeExecutionService executionService, final boolean expandTokens ) throws NodeStepException { final String filename; if (null != scriptString) { filename = "dispatch-script.tmp"; } else if (null != serverScriptFilePath) { filename = new File(serverScriptFilePath).getName(); } else { filename = "dispatch-script.tmp"; } String ident = null != context.getDataContext() && null != context.getDataContext().get("job") ? context.getDataContext().get("job").get("execid") : null; String filepath = fileCopierUtil.generateRemoteFilepathForNode( node, context.getFramework().getFrameworkProjectMgr().getFrameworkProject(context.getFrameworkProject()), context.getFramework(), filename, fileExtension, ident ); try { File temp = writeScriptToTempFile( context, node, scriptString, serverScriptFilePath, scriptAsStream, expandTokens ); try { filepath = executionService.fileCopyFile( context, temp, node, filepath ); } finally { //clean up ScriptfileUtils.releaseTempFile(temp); } } catch (FileCopierException e) { throw new NodeStepException( e.getMessage(), e, e.getFailureReason(), node.getNodename() ); } catch (ExecutionException e) { throw new NodeStepException( e.getMessage(), e, e.getFailureReason(), node.getNodename() ); } return executeRemoteScript( context, context.getFramework(), node, args, filepath, scriptInterpreter, quoted ); }
[ "@", "Override", "public", "NodeStepResult", "executeScriptFile", "(", "StepExecutionContext", "context", ",", "INodeEntry", "node", ",", "String", "scriptString", ",", "String", "serverScriptFilePath", ",", "InputStream", "scriptAsStream", ",", "String", "fileExtension", ",", "String", "[", "]", "args", ",", "String", "scriptInterpreter", ",", "boolean", "quoted", ",", "final", "NodeExecutionService", "executionService", ",", "final", "boolean", "expandTokens", ")", "throws", "NodeStepException", "{", "final", "String", "filename", ";", "if", "(", "null", "!=", "scriptString", ")", "{", "filename", "=", "\"dispatch-script.tmp\"", ";", "}", "else", "if", "(", "null", "!=", "serverScriptFilePath", ")", "{", "filename", "=", "new", "File", "(", "serverScriptFilePath", ")", ".", "getName", "(", ")", ";", "}", "else", "{", "filename", "=", "\"dispatch-script.tmp\"", ";", "}", "String", "ident", "=", "null", "!=", "context", ".", "getDataContext", "(", ")", "&&", "null", "!=", "context", ".", "getDataContext", "(", ")", ".", "get", "(", "\"job\"", ")", "?", "context", ".", "getDataContext", "(", ")", ".", "get", "(", "\"job\"", ")", ".", "get", "(", "\"execid\"", ")", ":", "null", ";", "String", "filepath", "=", "fileCopierUtil", ".", "generateRemoteFilepathForNode", "(", "node", ",", "context", ".", "getFramework", "(", ")", ".", "getFrameworkProjectMgr", "(", ")", ".", "getFrameworkProject", "(", "context", ".", "getFrameworkProject", "(", ")", ")", ",", "context", ".", "getFramework", "(", ")", ",", "filename", ",", "fileExtension", ",", "ident", ")", ";", "try", "{", "File", "temp", "=", "writeScriptToTempFile", "(", "context", ",", "node", ",", "scriptString", ",", "serverScriptFilePath", ",", "scriptAsStream", ",", "expandTokens", ")", ";", "try", "{", "filepath", "=", "executionService", ".", "fileCopyFile", "(", "context", ",", "temp", ",", "node", ",", "filepath", ")", ";", "}", "finally", "{", "//clean up", "ScriptfileUtils", ".", "releaseTempFile", "(", "temp", ")", ";", "}", "}", "catch", "(", "FileCopierException", "e", ")", "{", "throw", "new", "NodeStepException", "(", "e", ".", "getMessage", "(", ")", ",", "e", ",", "e", ".", "getFailureReason", "(", ")", ",", "node", ".", "getNodename", "(", ")", ")", ";", "}", "catch", "(", "ExecutionException", "e", ")", "{", "throw", "new", "NodeStepException", "(", "e", ".", "getMessage", "(", ")", ",", "e", ",", "e", ".", "getFailureReason", "(", ")", ",", "node", ".", "getNodename", "(", ")", ")", ";", "}", "return", "executeRemoteScript", "(", "context", ",", "context", ".", "getFramework", "(", ")", ",", "node", ",", "args", ",", "filepath", ",", "scriptInterpreter", ",", "quoted", ")", ";", "}" ]
Execute a script on a remote node @param context context @param node node @param scriptString string @param serverScriptFilePath file @param scriptAsStream stream @param fileExtension file extension @param args script args @param scriptInterpreter invoker string @param quoted true if args are quoted @param executionService service @return execution result @throws NodeStepException on error
[ "Execute", "a", "script", "on", "a", "remote", "node" ]
8070f774f55bffaa1118ff0c03aea319d40a9668
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/execution/workflow/steps/node/impl/DefaultScriptFileNodeStepUtils.java#L61-L141
16,106
rundeck/rundeck
core/src/main/java/com/dtolabs/rundeck/core/execution/workflow/steps/node/impl/DefaultScriptFileNodeStepUtils.java
DefaultScriptFileNodeStepUtils.writeScriptToTempFile
@Override public File writeScriptToTempFile( StepExecutionContext context, INodeEntry node, String scriptString, String serverScriptFilePath, InputStream scriptAsStream, boolean expandTokens ) throws FileCopierException { File temp; if (null != scriptString) { //expand tokens in the script temp = fileCopierUtil.writeScriptTempFile( context, null, null, scriptString, node, expandTokens ); } else if (null != serverScriptFilePath) { //DON'T expand tokens in the script //TODO: make token expansion optional for local file sources temp = new File(serverScriptFilePath); } else { //expand tokens in the script temp = fileCopierUtil.writeScriptTempFile( context, null, scriptAsStream, null, node, expandTokens ); } return temp; }
java
@Override public File writeScriptToTempFile( StepExecutionContext context, INodeEntry node, String scriptString, String serverScriptFilePath, InputStream scriptAsStream, boolean expandTokens ) throws FileCopierException { File temp; if (null != scriptString) { //expand tokens in the script temp = fileCopierUtil.writeScriptTempFile( context, null, null, scriptString, node, expandTokens ); } else if (null != serverScriptFilePath) { //DON'T expand tokens in the script //TODO: make token expansion optional for local file sources temp = new File(serverScriptFilePath); } else { //expand tokens in the script temp = fileCopierUtil.writeScriptTempFile( context, null, scriptAsStream, null, node, expandTokens ); } return temp; }
[ "@", "Override", "public", "File", "writeScriptToTempFile", "(", "StepExecutionContext", "context", ",", "INodeEntry", "node", ",", "String", "scriptString", ",", "String", "serverScriptFilePath", ",", "InputStream", "scriptAsStream", ",", "boolean", "expandTokens", ")", "throws", "FileCopierException", "{", "File", "temp", ";", "if", "(", "null", "!=", "scriptString", ")", "{", "//expand tokens in the script", "temp", "=", "fileCopierUtil", ".", "writeScriptTempFile", "(", "context", ",", "null", ",", "null", ",", "scriptString", ",", "node", ",", "expandTokens", ")", ";", "}", "else", "if", "(", "null", "!=", "serverScriptFilePath", ")", "{", "//DON'T expand tokens in the script", "//TODO: make token expansion optional for local file sources", "temp", "=", "new", "File", "(", "serverScriptFilePath", ")", ";", "}", "else", "{", "//expand tokens in the script", "temp", "=", "fileCopierUtil", ".", "writeScriptTempFile", "(", "context", ",", "null", ",", "scriptAsStream", ",", "null", ",", "node", ",", "expandTokens", ")", ";", "}", "return", "temp", ";", "}" ]
Copy the script input to a temp file and expand embedded tokens, if it is a string or inputstream. If it is a local file, use the original without modification @param context context @param node node @param scriptString string @param serverScriptFilePath file @param scriptAsStream stream @return temp file @throws FileCopierException on error
[ "Copy", "the", "script", "input", "to", "a", "temp", "file", "and", "expand", "embedded", "tokens", "if", "it", "is", "a", "string", "or", "inputstream", ".", "If", "it", "is", "a", "local", "file", "use", "the", "original", "without", "modification" ]
8070f774f55bffaa1118ff0c03aea319d40a9668
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/execution/workflow/steps/node/impl/DefaultScriptFileNodeStepUtils.java#L158-L195
16,107
rundeck/rundeck
core/src/main/java/com/dtolabs/rundeck/core/execution/workflow/steps/node/impl/DefaultScriptFileNodeStepUtils.java
DefaultScriptFileNodeStepUtils.removeArgsForOsFamily
@Override public ExecArgList removeArgsForOsFamily(String filepath, String osFamily) { if ("windows".equalsIgnoreCase(osFamily)) { return ExecArgList.fromStrings(false, "del", filepath); } else { return ExecArgList.fromStrings(false, "rm", "-f", filepath); } }
java
@Override public ExecArgList removeArgsForOsFamily(String filepath, String osFamily) { if ("windows".equalsIgnoreCase(osFamily)) { return ExecArgList.fromStrings(false, "del", filepath); } else { return ExecArgList.fromStrings(false, "rm", "-f", filepath); } }
[ "@", "Override", "public", "ExecArgList", "removeArgsForOsFamily", "(", "String", "filepath", ",", "String", "osFamily", ")", "{", "if", "(", "\"windows\"", ".", "equalsIgnoreCase", "(", "osFamily", ")", ")", "{", "return", "ExecArgList", ".", "fromStrings", "(", "false", ",", "\"del\"", ",", "filepath", ")", ";", "}", "else", "{", "return", "ExecArgList", ".", "fromStrings", "(", "false", ",", "\"rm\"", ",", "\"-f\"", ",", "filepath", ")", ";", "}", "}" ]
Return ExecArgList for removing a file for the given OS family @param filepath path @param osFamily family @return arg list
[ "Return", "ExecArgList", "for", "removing", "a", "file", "for", "the", "given", "OS", "family" ]
8070f774f55bffaa1118ff0c03aea319d40a9668
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/execution/workflow/steps/node/impl/DefaultScriptFileNodeStepUtils.java#L332-L339
16,108
rundeck/rundeck
core/src/main/java/com/dtolabs/rundeck/core/utils/NodeSet.java
NodeSet.shouldExclude
public boolean shouldExclude(final INodeEntry entry) { if(null!=getSingleNodeName()) { return !getSingleNodeName().equals(entry.getNodename()); } boolean includesMatch = includes != null && includes.matches(entry); boolean excludesMatch = excludes != null && excludes.matches(entry); if (null==excludes ||excludes.isBlank()) { return !includesMatch; } else if (null==includes || includes.isBlank()) { return excludesMatch; } else if(null!=includes && includes.isDominant()) { return !includesMatch && excludesMatch; }else{ return !includesMatch || excludesMatch; } }
java
public boolean shouldExclude(final INodeEntry entry) { if(null!=getSingleNodeName()) { return !getSingleNodeName().equals(entry.getNodename()); } boolean includesMatch = includes != null && includes.matches(entry); boolean excludesMatch = excludes != null && excludes.matches(entry); if (null==excludes ||excludes.isBlank()) { return !includesMatch; } else if (null==includes || includes.isBlank()) { return excludesMatch; } else if(null!=includes && includes.isDominant()) { return !includesMatch && excludesMatch; }else{ return !includesMatch || excludesMatch; } }
[ "public", "boolean", "shouldExclude", "(", "final", "INodeEntry", "entry", ")", "{", "if", "(", "null", "!=", "getSingleNodeName", "(", ")", ")", "{", "return", "!", "getSingleNodeName", "(", ")", ".", "equals", "(", "entry", ".", "getNodename", "(", ")", ")", ";", "}", "boolean", "includesMatch", "=", "includes", "!=", "null", "&&", "includes", ".", "matches", "(", "entry", ")", ";", "boolean", "excludesMatch", "=", "excludes", "!=", "null", "&&", "excludes", ".", "matches", "(", "entry", ")", ";", "if", "(", "null", "==", "excludes", "||", "excludes", ".", "isBlank", "(", ")", ")", "{", "return", "!", "includesMatch", ";", "}", "else", "if", "(", "null", "==", "includes", "||", "includes", ".", "isBlank", "(", ")", ")", "{", "return", "excludesMatch", ";", "}", "else", "if", "(", "null", "!=", "includes", "&&", "includes", ".", "isDominant", "(", ")", ")", "{", "return", "!", "includesMatch", "&&", "excludesMatch", ";", "}", "else", "{", "return", "!", "includesMatch", "||", "excludesMatch", ";", "}", "}" ]
Return true if the node entry should be excluded based on the includes and excludes parameters. When both include and exclude patterns match the node, it will be excluded based on which filterset is dominant. @param entry node descriptor entry @return true if the node should be excluded.
[ "Return", "true", "if", "the", "node", "entry", "should", "be", "excluded", "based", "on", "the", "includes", "and", "excludes", "parameters", ".", "When", "both", "include", "and", "exclude", "patterns", "match", "the", "node", "it", "will", "be", "excluded", "based", "on", "which", "filterset", "is", "dominant", "." ]
8070f774f55bffaa1118ff0c03aea319d40a9668
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/utils/NodeSet.java#L201-L217
16,109
rundeck/rundeck
core/src/main/java/com/dtolabs/rundeck/core/utils/NodeSet.java
NodeSet.validate
public void validate() { if (null != failedNodesfile && failedNodesfile.getName().startsWith("${") && failedNodesfile.getName() .endsWith("}")) { failedNodesfile=null; } }
java
public void validate() { if (null != failedNodesfile && failedNodesfile.getName().startsWith("${") && failedNodesfile.getName() .endsWith("}")) { failedNodesfile=null; } }
[ "public", "void", "validate", "(", ")", "{", "if", "(", "null", "!=", "failedNodesfile", "&&", "failedNodesfile", ".", "getName", "(", ")", ".", "startsWith", "(", "\"${\"", ")", "&&", "failedNodesfile", ".", "getName", "(", ")", ".", "endsWith", "(", "\"}\"", ")", ")", "{", "failedNodesfile", "=", "null", ";", "}", "}" ]
Validate input. If failedNodesfile looks like an invalid property reference, set it to null.
[ "Validate", "input", ".", "If", "failedNodesfile", "looks", "like", "an", "invalid", "property", "reference", "set", "it", "to", "null", "." ]
8070f774f55bffaa1118ff0c03aea319d40a9668
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/utils/NodeSet.java#L238-L243
16,110
rundeck/rundeck
core/src/main/java/com/dtolabs/rundeck/core/utils/NodeSet.java
NodeSet.fromFilter
public static NodeSet fromFilter(String filter) { Map<String, Map<String, String>> stringMapMap = parseFilter(filter); NodeSet nodeSet = new NodeSet(); nodeSet.createInclude(stringMapMap.get("include")); nodeSet.createExclude(stringMapMap.get("exclude")); return nodeSet; }
java
public static NodeSet fromFilter(String filter) { Map<String, Map<String, String>> stringMapMap = parseFilter(filter); NodeSet nodeSet = new NodeSet(); nodeSet.createInclude(stringMapMap.get("include")); nodeSet.createExclude(stringMapMap.get("exclude")); return nodeSet; }
[ "public", "static", "NodeSet", "fromFilter", "(", "String", "filter", ")", "{", "Map", "<", "String", ",", "Map", "<", "String", ",", "String", ">", ">", "stringMapMap", "=", "parseFilter", "(", "filter", ")", ";", "NodeSet", "nodeSet", "=", "new", "NodeSet", "(", ")", ";", "nodeSet", ".", "createInclude", "(", "stringMapMap", ".", "get", "(", "\"include\"", ")", ")", ";", "nodeSet", ".", "createExclude", "(", "stringMapMap", ".", "get", "(", "\"exclude\"", ")", ")", ";", "return", "nodeSet", ";", "}" ]
Create a NodeSet from a filter @param filter filter string @return node set
[ "Create", "a", "NodeSet", "from", "a", "filter" ]
8070f774f55bffaa1118ff0c03aea319d40a9668
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/utils/NodeSet.java#L380-L386
16,111
rundeck/rundeck
rundeck-storage/rundeck-storage-filesys/src/main/java/org/rundeck/storage/data/file/FileTreeUtil.java
FileTreeUtil.pathForFileInRoot
public static Path pathForFileInRoot( final File rootDir, final File file ) { String filePath = file.getAbsolutePath(); String rootPath = rootDir.getAbsolutePath(); if (!filePath.startsWith(rootPath)) { throw new IllegalArgumentException("not a file in the root directory: " + file); } return pathForRelativeFilepath(filePath.substring(rootPath.length())); }
java
public static Path pathForFileInRoot( final File rootDir, final File file ) { String filePath = file.getAbsolutePath(); String rootPath = rootDir.getAbsolutePath(); if (!filePath.startsWith(rootPath)) { throw new IllegalArgumentException("not a file in the root directory: " + file); } return pathForRelativeFilepath(filePath.substring(rootPath.length())); }
[ "public", "static", "Path", "pathForFileInRoot", "(", "final", "File", "rootDir", ",", "final", "File", "file", ")", "{", "String", "filePath", "=", "file", ".", "getAbsolutePath", "(", ")", ";", "String", "rootPath", "=", "rootDir", ".", "getAbsolutePath", "(", ")", ";", "if", "(", "!", "filePath", ".", "startsWith", "(", "rootPath", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"not a file in the root directory: \"", "+", "file", ")", ";", "}", "return", "pathForRelativeFilepath", "(", "filePath", ".", "substring", "(", "rootPath", ".", "length", "(", ")", ")", ")", ";", "}" ]
Return a storage Path given a file within a given root dir @param rootDir root dir to use @param file file @return sub path corresponding to the file @throws IllegalArgumentException if the file is not within the root
[ "Return", "a", "storage", "Path", "given", "a", "file", "within", "a", "given", "root", "dir" ]
8070f774f55bffaa1118ff0c03aea319d40a9668
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/rundeck-storage/rundeck-storage-filesys/src/main/java/org/rundeck/storage/data/file/FileTreeUtil.java#L46-L57
16,112
rundeck/rundeck
rundeck-storage/rundeck-storage-filesys/src/main/java/org/rundeck/storage/data/file/FileTreeUtil.java
FileTreeUtil.pathForRelativeFilepath
public static Path pathForRelativeFilepath( final String filepath, final String separator ) { String[] comps = filepath.split(Pattern.quote(separator)); return PathUtil.pathFromComponents(comps); }
java
public static Path pathForRelativeFilepath( final String filepath, final String separator ) { String[] comps = filepath.split(Pattern.quote(separator)); return PathUtil.pathFromComponents(comps); }
[ "public", "static", "Path", "pathForRelativeFilepath", "(", "final", "String", "filepath", ",", "final", "String", "separator", ")", "{", "String", "[", "]", "comps", "=", "filepath", ".", "split", "(", "Pattern", ".", "quote", "(", "separator", ")", ")", ";", "return", "PathUtil", ".", "pathFromComponents", "(", "comps", ")", ";", "}" ]
Return a storage path given a relative file path string @param filepath file path with given separator @param separator separator string @return storage path
[ "Return", "a", "storage", "path", "given", "a", "relative", "file", "path", "string" ]
8070f774f55bffaa1118ff0c03aea319d40a9668
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/rundeck-storage/rundeck-storage-filesys/src/main/java/org/rundeck/storage/data/file/FileTreeUtil.java#L82-L89
16,113
rundeck/rundeck
core/src/main/java/com/dtolabs/rundeck/core/execution/impl/jsch/JschNodeExecutor.java
JschNodeExecutor.passwordSourceWithPrefix
private PasswordSource passwordSourceWithPrefix( final NodeSSHConnectionInfo nodeAuthentication, final String prefix ) throws IOException { if (null != nodeAuthentication.getSudoPasswordStoragePath(prefix)) { return new BasicSource(nodeAuthentication.getSudoPasswordStorageData(prefix)); } else { return new BasicSource(nodeAuthentication.getSudoPassword(prefix)); } }
java
private PasswordSource passwordSourceWithPrefix( final NodeSSHConnectionInfo nodeAuthentication, final String prefix ) throws IOException { if (null != nodeAuthentication.getSudoPasswordStoragePath(prefix)) { return new BasicSource(nodeAuthentication.getSudoPasswordStorageData(prefix)); } else { return new BasicSource(nodeAuthentication.getSudoPassword(prefix)); } }
[ "private", "PasswordSource", "passwordSourceWithPrefix", "(", "final", "NodeSSHConnectionInfo", "nodeAuthentication", ",", "final", "String", "prefix", ")", "throws", "IOException", "{", "if", "(", "null", "!=", "nodeAuthentication", ".", "getSudoPasswordStoragePath", "(", "prefix", ")", ")", "{", "return", "new", "BasicSource", "(", "nodeAuthentication", ".", "getSudoPasswordStorageData", "(", "prefix", ")", ")", ";", "}", "else", "{", "return", "new", "BasicSource", "(", "nodeAuthentication", ".", "getSudoPassword", "(", "prefix", ")", ")", ";", "}", "}" ]
create password source @param nodeAuthentication auth @param prefix prefix @return source @throws IOException if password loading from storage fails
[ "create", "password", "source" ]
8070f774f55bffaa1118ff0c03aea319d40a9668
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/execution/impl/jsch/JschNodeExecutor.java#L502-L512
16,114
rundeck/rundeck
core/src/main/java/com/dtolabs/rundeck/core/execution/impl/jsch/JschNodeExecutor.java
JschNodeExecutor.shutdownAndAwaitTermination
void shutdownAndAwaitTermination(ExecutorService pool) { pool.shutdownNow(); // Disable new tasks from being submitted try { logger.debug("Waiting up to 30 seconds for ExecutorService to shut down"); // Wait a while for existing tasks to terminate if (!pool.awaitTermination(30, TimeUnit.SECONDS)) { logger.debug("Pool did not terminate"); } } catch (InterruptedException ie) { // (Re-)Cancel if current thread also interrupted pool.shutdownNow(); // Preserve interrupt status Thread.currentThread().interrupt(); } }
java
void shutdownAndAwaitTermination(ExecutorService pool) { pool.shutdownNow(); // Disable new tasks from being submitted try { logger.debug("Waiting up to 30 seconds for ExecutorService to shut down"); // Wait a while for existing tasks to terminate if (!pool.awaitTermination(30, TimeUnit.SECONDS)) { logger.debug("Pool did not terminate"); } } catch (InterruptedException ie) { // (Re-)Cancel if current thread also interrupted pool.shutdownNow(); // Preserve interrupt status Thread.currentThread().interrupt(); } }
[ "void", "shutdownAndAwaitTermination", "(", "ExecutorService", "pool", ")", "{", "pool", ".", "shutdownNow", "(", ")", ";", "// Disable new tasks from being submitted", "try", "{", "logger", ".", "debug", "(", "\"Waiting up to 30 seconds for ExecutorService to shut down\"", ")", ";", "// Wait a while for existing tasks to terminate", "if", "(", "!", "pool", ".", "awaitTermination", "(", "30", ",", "TimeUnit", ".", "SECONDS", ")", ")", "{", "logger", ".", "debug", "(", "\"Pool did not terminate\"", ")", ";", "}", "}", "catch", "(", "InterruptedException", "ie", ")", "{", "// (Re-)Cancel if current thread also interrupted", "pool", ".", "shutdownNow", "(", ")", ";", "// Preserve interrupt status", "Thread", ".", "currentThread", "(", ")", ".", "interrupt", "(", ")", ";", "}", "}" ]
Shutdown the ExecutorService
[ "Shutdown", "the", "ExecutorService" ]
8070f774f55bffaa1118ff0c03aea319d40a9668
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/execution/impl/jsch/JschNodeExecutor.java#L607-L621
16,115
rundeck/rundeck
core/src/main/java/com/dtolabs/rundeck/core/storage/StorageTreeFactory.java
StorageTreeFactory.baseConverter
private TreeBuilder<ResourceMeta> baseConverter(TreeBuilder<ResourceMeta> builder) { if(null!=defaultConverters && defaultConverters.contains("StorageTimestamperConverter")) { logger.debug("Configuring base converter: StorageTimestamperConverter" ); builder=builder.convert( new StorageConverterPluginAdapter( "builtin:timestamp", new StorageTimestamperConverter() ) ); } if(null!=defaultConverters && defaultConverters.contains("KeyStorageLayer")){ logger.debug("Configuring base converter: KeyStorageLayer" ); builder=builder.convert( new StorageConverterPluginAdapter( "builtin:ssh-storage", new KeyStorageLayer() ), PathUtil.asPath("/keys") ); } return builder; }
java
private TreeBuilder<ResourceMeta> baseConverter(TreeBuilder<ResourceMeta> builder) { if(null!=defaultConverters && defaultConverters.contains("StorageTimestamperConverter")) { logger.debug("Configuring base converter: StorageTimestamperConverter" ); builder=builder.convert( new StorageConverterPluginAdapter( "builtin:timestamp", new StorageTimestamperConverter() ) ); } if(null!=defaultConverters && defaultConverters.contains("KeyStorageLayer")){ logger.debug("Configuring base converter: KeyStorageLayer" ); builder=builder.convert( new StorageConverterPluginAdapter( "builtin:ssh-storage", new KeyStorageLayer() ), PathUtil.asPath("/keys") ); } return builder; }
[ "private", "TreeBuilder", "<", "ResourceMeta", ">", "baseConverter", "(", "TreeBuilder", "<", "ResourceMeta", ">", "builder", ")", "{", "if", "(", "null", "!=", "defaultConverters", "&&", "defaultConverters", ".", "contains", "(", "\"StorageTimestamperConverter\"", ")", ")", "{", "logger", ".", "debug", "(", "\"Configuring base converter: StorageTimestamperConverter\"", ")", ";", "builder", "=", "builder", ".", "convert", "(", "new", "StorageConverterPluginAdapter", "(", "\"builtin:timestamp\"", ",", "new", "StorageTimestamperConverter", "(", ")", ")", ")", ";", "}", "if", "(", "null", "!=", "defaultConverters", "&&", "defaultConverters", ".", "contains", "(", "\"KeyStorageLayer\"", ")", ")", "{", "logger", ".", "debug", "(", "\"Configuring base converter: KeyStorageLayer\"", ")", ";", "builder", "=", "builder", ".", "convert", "(", "new", "StorageConverterPluginAdapter", "(", "\"builtin:ssh-storage\"", ",", "new", "KeyStorageLayer", "(", ")", ")", ",", "PathUtil", ".", "asPath", "(", "\"/keys\"", ")", ")", ";", "}", "return", "builder", ";", "}" ]
Apply base converters for metadata timestamps @param builder builder @return builder
[ "Apply", "base", "converters", "for", "metadata", "timestamps" ]
8070f774f55bffaa1118ff0c03aea319d40a9668
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/storage/StorageTreeFactory.java#L122-L142
16,116
rundeck/rundeck
core/src/main/java/com/dtolabs/rundeck/core/storage/StorageTreeFactory.java
StorageTreeFactory.addLogger
private TreeBuilder<ResourceMeta> addLogger(TreeBuilder<ResourceMeta> builder, Map<String,String> config) { String loggerName= getLoggerName(); if (null != config.get(LOGGER_NAME)) { loggerName = config.get(LOGGER_NAME); } if (null == loggerName) { loggerName = ORG_RUNDECK_STORAGE_EVENTS_LOGGER_NAME; } logger.debug("Add log4j logger for storage with name: " + loggerName); return builder.listen(new StorageLogger(loggerName)); }
java
private TreeBuilder<ResourceMeta> addLogger(TreeBuilder<ResourceMeta> builder, Map<String,String> config) { String loggerName= getLoggerName(); if (null != config.get(LOGGER_NAME)) { loggerName = config.get(LOGGER_NAME); } if (null == loggerName) { loggerName = ORG_RUNDECK_STORAGE_EVENTS_LOGGER_NAME; } logger.debug("Add log4j logger for storage with name: " + loggerName); return builder.listen(new StorageLogger(loggerName)); }
[ "private", "TreeBuilder", "<", "ResourceMeta", ">", "addLogger", "(", "TreeBuilder", "<", "ResourceMeta", ">", "builder", ",", "Map", "<", "String", ",", "String", ">", "config", ")", "{", "String", "loggerName", "=", "getLoggerName", "(", ")", ";", "if", "(", "null", "!=", "config", ".", "get", "(", "LOGGER_NAME", ")", ")", "{", "loggerName", "=", "config", ".", "get", "(", "LOGGER_NAME", ")", ";", "}", "if", "(", "null", "==", "loggerName", ")", "{", "loggerName", "=", "ORG_RUNDECK_STORAGE_EVENTS_LOGGER_NAME", ";", "}", "logger", ".", "debug", "(", "\"Add log4j logger for storage with name: \"", "+", "loggerName", ")", ";", "return", "builder", ".", "listen", "(", "new", "StorageLogger", "(", "loggerName", ")", ")", ";", "}" ]
Append final listeners to the tree @param builder builder @return builder
[ "Append", "final", "listeners", "to", "the", "tree" ]
8070f774f55bffaa1118ff0c03aea319d40a9668
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/storage/StorageTreeFactory.java#L151-L161
16,117
rundeck/rundeck
core/src/main/java/com/dtolabs/rundeck/core/storage/StorageTreeFactory.java
StorageTreeFactory.baseStorage
private TreeBuilder<ResourceMeta> baseStorage(TreeBuilder<ResourceMeta> builder) { //set base using file storage, could be overridden Map<String, String> config1 = expandConfig(getBaseStorageConfig()); logger.debug("Default base storage provider: " + getBaseStorageType() + ", " + "config: " + config1); StoragePlugin base = loadPlugin( getBaseStorageType(), config1, storagePluginProviderService ); if(null==base) { throw new IllegalArgumentException("Plugin could not be loaded: " + getBaseStorageType()); } return builder.base(base); }
java
private TreeBuilder<ResourceMeta> baseStorage(TreeBuilder<ResourceMeta> builder) { //set base using file storage, could be overridden Map<String, String> config1 = expandConfig(getBaseStorageConfig()); logger.debug("Default base storage provider: " + getBaseStorageType() + ", " + "config: " + config1); StoragePlugin base = loadPlugin( getBaseStorageType(), config1, storagePluginProviderService ); if(null==base) { throw new IllegalArgumentException("Plugin could not be loaded: " + getBaseStorageType()); } return builder.base(base); }
[ "private", "TreeBuilder", "<", "ResourceMeta", ">", "baseStorage", "(", "TreeBuilder", "<", "ResourceMeta", ">", "builder", ")", "{", "//set base using file storage, could be overridden", "Map", "<", "String", ",", "String", ">", "config1", "=", "expandConfig", "(", "getBaseStorageConfig", "(", ")", ")", ";", "logger", ".", "debug", "(", "\"Default base storage provider: \"", "+", "getBaseStorageType", "(", ")", "+", "\", \"", "+", "\"config: \"", "+", "config1", ")", ";", "StoragePlugin", "base", "=", "loadPlugin", "(", "getBaseStorageType", "(", ")", ",", "config1", ",", "storagePluginProviderService", ")", ";", "if", "(", "null", "==", "base", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Plugin could not be loaded: \"", "+", "getBaseStorageType", "(", ")", ")", ";", "}", "return", "builder", ".", "base", "(", "base", ")", ";", "}" ]
Set up the base storage layer for the tree @param builder builder @return builder
[ "Set", "up", "the", "base", "storage", "layer", "for", "the", "tree" ]
8070f774f55bffaa1118ff0c03aea319d40a9668
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/storage/StorageTreeFactory.java#L170-L185
16,118
rundeck/rundeck
core/src/main/java/com/dtolabs/rundeck/core/storage/StorageTreeFactory.java
StorageTreeFactory.configureConverterPlugin
private TreeBuilder<ResourceMeta> configureConverterPlugin(TreeBuilder<ResourceMeta> builder, int index, Map<String, String> configProps) { String pref1 = getConverterConfigPrefix() + SEP + index; String pluginType = configProps.get(pref1 + SEP + TYPE); String pathProp = pref1 + SEP + PATH; String selectorProp = pref1 + SEP + RESOURCE_SELECTOR; String path = configProps.get(pathProp); String selector = configProps.get(selectorProp); if (null == path && null == selector) { throw new IllegalArgumentException("Converter plugin [" + index + "] specified by " + (pref1) + " MUST " + "define one of: " + pathProp + " OR " + selectorProp); } Map<String, String> config = subPropertyMap(pref1 + SEP + CONFIG + SEP, configProps); config = expandConfig(config); logger.debug("Add Converter[" + index + "]:" + (null != path ? path : "/") + "[" + (null != selector ? selector : "*") + "]" + " " + pluginType + ", config: " + config); return buildConverterPlugin(builder, pluginType, path, selector, config); }
java
private TreeBuilder<ResourceMeta> configureConverterPlugin(TreeBuilder<ResourceMeta> builder, int index, Map<String, String> configProps) { String pref1 = getConverterConfigPrefix() + SEP + index; String pluginType = configProps.get(pref1 + SEP + TYPE); String pathProp = pref1 + SEP + PATH; String selectorProp = pref1 + SEP + RESOURCE_SELECTOR; String path = configProps.get(pathProp); String selector = configProps.get(selectorProp); if (null == path && null == selector) { throw new IllegalArgumentException("Converter plugin [" + index + "] specified by " + (pref1) + " MUST " + "define one of: " + pathProp + " OR " + selectorProp); } Map<String, String> config = subPropertyMap(pref1 + SEP + CONFIG + SEP, configProps); config = expandConfig(config); logger.debug("Add Converter[" + index + "]:" + (null != path ? path : "/") + "[" + (null != selector ? selector : "*") + "]" + " " + pluginType + ", config: " + config); return buildConverterPlugin(builder, pluginType, path, selector, config); }
[ "private", "TreeBuilder", "<", "ResourceMeta", ">", "configureConverterPlugin", "(", "TreeBuilder", "<", "ResourceMeta", ">", "builder", ",", "int", "index", ",", "Map", "<", "String", ",", "String", ">", "configProps", ")", "{", "String", "pref1", "=", "getConverterConfigPrefix", "(", ")", "+", "SEP", "+", "index", ";", "String", "pluginType", "=", "configProps", ".", "get", "(", "pref1", "+", "SEP", "+", "TYPE", ")", ";", "String", "pathProp", "=", "pref1", "+", "SEP", "+", "PATH", ";", "String", "selectorProp", "=", "pref1", "+", "SEP", "+", "RESOURCE_SELECTOR", ";", "String", "path", "=", "configProps", ".", "get", "(", "pathProp", ")", ";", "String", "selector", "=", "configProps", ".", "get", "(", "selectorProp", ")", ";", "if", "(", "null", "==", "path", "&&", "null", "==", "selector", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Converter plugin [\"", "+", "index", "+", "\"] specified by \"", "+", "(", "pref1", ")", "+", "\" MUST \"", "+", "\"define one of: \"", "+", "pathProp", "+", "\" OR \"", "+", "selectorProp", ")", ";", "}", "Map", "<", "String", ",", "String", ">", "config", "=", "subPropertyMap", "(", "pref1", "+", "SEP", "+", "CONFIG", "+", "SEP", ",", "configProps", ")", ";", "config", "=", "expandConfig", "(", "config", ")", ";", "logger", ".", "debug", "(", "\"Add Converter[\"", "+", "index", "+", "\"]:\"", "+", "(", "null", "!=", "path", "?", "path", ":", "\"/\"", ")", "+", "\"[\"", "+", "(", "null", "!=", "selector", "?", "selector", ":", "\"*\"", ")", "+", "\"]\"", "+", "\" \"", "+", "pluginType", "+", "\", config: \"", "+", "config", ")", ";", "return", "buildConverterPlugin", "(", "builder", ",", "pluginType", ",", "path", ",", "selector", ",", "config", ")", ";", "}" ]
Configure converter plugins for the builder @param builder builder @param index given index @param configProps configuration properties @return builder
[ "Configure", "converter", "plugins", "for", "the", "builder" ]
8070f774f55bffaa1118ff0c03aea319d40a9668
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/storage/StorageTreeFactory.java#L204-L227
16,119
rundeck/rundeck
core/src/main/java/com/dtolabs/rundeck/core/storage/StorageTreeFactory.java
StorageTreeFactory.buildConverterPlugin
private TreeBuilder<ResourceMeta> buildConverterPlugin(TreeBuilder<ResourceMeta> builder, String pluginType, String path, String selector, Map<String, String> config) { StorageConverterPlugin converterPlugin = loadPlugin( pluginType, config, storageConverterPluginProviderService ); //convert tree under the subpath if specified, AND matching the selector if specified return builder.convert( new StorageConverterPluginAdapter(pluginType,converterPlugin), null != path ? PathUtil.asPath(path.trim()) : null, null != selector ? PathUtil.<ResourceMeta>resourceSelector(selector) : null ); }
java
private TreeBuilder<ResourceMeta> buildConverterPlugin(TreeBuilder<ResourceMeta> builder, String pluginType, String path, String selector, Map<String, String> config) { StorageConverterPlugin converterPlugin = loadPlugin( pluginType, config, storageConverterPluginProviderService ); //convert tree under the subpath if specified, AND matching the selector if specified return builder.convert( new StorageConverterPluginAdapter(pluginType,converterPlugin), null != path ? PathUtil.asPath(path.trim()) : null, null != selector ? PathUtil.<ResourceMeta>resourceSelector(selector) : null ); }
[ "private", "TreeBuilder", "<", "ResourceMeta", ">", "buildConverterPlugin", "(", "TreeBuilder", "<", "ResourceMeta", ">", "builder", ",", "String", "pluginType", ",", "String", "path", ",", "String", "selector", ",", "Map", "<", "String", ",", "String", ">", "config", ")", "{", "StorageConverterPlugin", "converterPlugin", "=", "loadPlugin", "(", "pluginType", ",", "config", ",", "storageConverterPluginProviderService", ")", ";", "//convert tree under the subpath if specified, AND matching the selector if specified", "return", "builder", ".", "convert", "(", "new", "StorageConverterPluginAdapter", "(", "pluginType", ",", "converterPlugin", ")", ",", "null", "!=", "path", "?", "PathUtil", ".", "asPath", "(", "path", ".", "trim", "(", ")", ")", ":", "null", ",", "null", "!=", "selector", "?", "PathUtil", ".", "<", "ResourceMeta", ">", "resourceSelector", "(", "selector", ")", ":", "null", ")", ";", "}" ]
Append a converter plugin to the tree builder @param builder builder @param pluginType converter plugin type @param path path @param selector metadata selector @param config plugin config data @return builder
[ "Append", "a", "converter", "plugin", "to", "the", "tree", "builder" ]
8070f774f55bffaa1118ff0c03aea319d40a9668
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/storage/StorageTreeFactory.java#L240-L253
16,120
rundeck/rundeck
core/src/main/java/com/dtolabs/rundeck/core/storage/StorageTreeFactory.java
StorageTreeFactory.subPropertyMap
private Map<String, String> subPropertyMap(String configPrefix, Map propertiesMap) { Map<String, String> config = new HashMap<String, String>(); for (Object o : propertiesMap.keySet()) { String key = (String) o; if (key.startsWith(configPrefix)) { String conf = key.substring(configPrefix.length()); config.put(conf, propertiesMap.get(key).toString()); } } return config; }
java
private Map<String, String> subPropertyMap(String configPrefix, Map propertiesMap) { Map<String, String> config = new HashMap<String, String>(); for (Object o : propertiesMap.keySet()) { String key = (String) o; if (key.startsWith(configPrefix)) { String conf = key.substring(configPrefix.length()); config.put(conf, propertiesMap.get(key).toString()); } } return config; }
[ "private", "Map", "<", "String", ",", "String", ">", "subPropertyMap", "(", "String", "configPrefix", ",", "Map", "propertiesMap", ")", "{", "Map", "<", "String", ",", "String", ">", "config", "=", "new", "HashMap", "<", "String", ",", "String", ">", "(", ")", ";", "for", "(", "Object", "o", ":", "propertiesMap", ".", "keySet", "(", ")", ")", "{", "String", "key", "=", "(", "String", ")", "o", ";", "if", "(", "key", ".", "startsWith", "(", "configPrefix", ")", ")", "{", "String", "conf", "=", "key", ".", "substring", "(", "configPrefix", ".", "length", "(", ")", ")", ";", "config", ".", "put", "(", "conf", ",", "propertiesMap", ".", "get", "(", "key", ")", ".", "toString", "(", ")", ")", ";", "}", "}", "return", "config", ";", "}" ]
Extract a map of the property values starting with the given prefix @param configPrefix prefix @param propertiesMap input @return map
[ "Extract", "a", "map", "of", "the", "property", "values", "starting", "with", "the", "given", "prefix" ]
8070f774f55bffaa1118ff0c03aea319d40a9668
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/storage/StorageTreeFactory.java#L264-L274
16,121
rundeck/rundeck
core/src/main/java/com/dtolabs/rundeck/core/storage/StorageTreeFactory.java
StorageTreeFactory.configureStoragePlugin
private void configureStoragePlugin(TreeBuilder<ResourceMeta> builder, int index, Map<String, String> configProps) { String pref1 = getStorageConfigPrefix() + SEP + index; String pluginType = configProps.get(pref1 + SEP + TYPE); String path = configProps.get(pref1 + SEP + PATH); boolean removePathPrefix = Boolean.parseBoolean(configProps.get(pref1 + SEP + REMOVE_PATH_PREFIX)); Map<String, String> config = subPropertyMap(pref1 + SEP + CONFIG + SEP, configProps); config = expandConfig(config); Tree<ResourceMeta> resourceMetaTree = loadPlugin( pluginType, config, storagePluginProviderService ); if (index == 1 && PathUtil.isRoot(path)) { logger.debug("New base Storage[" + index + "]:" + path + " " + pluginType + ", config: " + config); builder.base(resourceMetaTree); } else { logger.debug("Subtree Storage[" + index + "]:" + path + " " + pluginType + ", config: " + config); builder.subTree(PathUtil.asPath(path.trim()), resourceMetaTree, !removePathPrefix); } }
java
private void configureStoragePlugin(TreeBuilder<ResourceMeta> builder, int index, Map<String, String> configProps) { String pref1 = getStorageConfigPrefix() + SEP + index; String pluginType = configProps.get(pref1 + SEP + TYPE); String path = configProps.get(pref1 + SEP + PATH); boolean removePathPrefix = Boolean.parseBoolean(configProps.get(pref1 + SEP + REMOVE_PATH_PREFIX)); Map<String, String> config = subPropertyMap(pref1 + SEP + CONFIG + SEP, configProps); config = expandConfig(config); Tree<ResourceMeta> resourceMetaTree = loadPlugin( pluginType, config, storagePluginProviderService ); if (index == 1 && PathUtil.isRoot(path)) { logger.debug("New base Storage[" + index + "]:" + path + " " + pluginType + ", config: " + config); builder.base(resourceMetaTree); } else { logger.debug("Subtree Storage[" + index + "]:" + path + " " + pluginType + ", config: " + config); builder.subTree(PathUtil.asPath(path.trim()), resourceMetaTree, !removePathPrefix); } }
[ "private", "void", "configureStoragePlugin", "(", "TreeBuilder", "<", "ResourceMeta", ">", "builder", ",", "int", "index", ",", "Map", "<", "String", ",", "String", ">", "configProps", ")", "{", "String", "pref1", "=", "getStorageConfigPrefix", "(", ")", "+", "SEP", "+", "index", ";", "String", "pluginType", "=", "configProps", ".", "get", "(", "pref1", "+", "SEP", "+", "TYPE", ")", ";", "String", "path", "=", "configProps", ".", "get", "(", "pref1", "+", "SEP", "+", "PATH", ")", ";", "boolean", "removePathPrefix", "=", "Boolean", ".", "parseBoolean", "(", "configProps", ".", "get", "(", "pref1", "+", "SEP", "+", "REMOVE_PATH_PREFIX", ")", ")", ";", "Map", "<", "String", ",", "String", ">", "config", "=", "subPropertyMap", "(", "pref1", "+", "SEP", "+", "CONFIG", "+", "SEP", ",", "configProps", ")", ";", "config", "=", "expandConfig", "(", "config", ")", ";", "Tree", "<", "ResourceMeta", ">", "resourceMetaTree", "=", "loadPlugin", "(", "pluginType", ",", "config", ",", "storagePluginProviderService", ")", ";", "if", "(", "index", "==", "1", "&&", "PathUtil", ".", "isRoot", "(", "path", ")", ")", "{", "logger", ".", "debug", "(", "\"New base Storage[\"", "+", "index", "+", "\"]:\"", "+", "path", "+", "\" \"", "+", "pluginType", "+", "\", config: \"", "+", "config", ")", ";", "builder", ".", "base", "(", "resourceMetaTree", ")", ";", "}", "else", "{", "logger", ".", "debug", "(", "\"Subtree Storage[\"", "+", "index", "+", "\"]:\"", "+", "path", "+", "\" \"", "+", "pluginType", "+", "\", config: \"", "+", "config", ")", ";", "builder", ".", "subTree", "(", "PathUtil", ".", "asPath", "(", "path", ".", "trim", "(", ")", ")", ",", "resourceMetaTree", ",", "!", "removePathPrefix", ")", ";", "}", "}" ]
Configures storage plugins with the builder @param builder builder @param index current prop index @param configProps configuration properties
[ "Configures", "storage", "plugins", "with", "the", "builder" ]
8070f774f55bffaa1118ff0c03aea319d40a9668
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/storage/StorageTreeFactory.java#L283-L304
16,122
rundeck/rundeck
core/src/main/java/com/dtolabs/rundeck/core/storage/StorageTreeFactory.java
StorageTreeFactory.expandConfig
private Map<String, String> expandConfig(Map<String, String> map) { return expandAllProperties(map, getPropertyLookup().getPropertiesMap()); }
java
private Map<String, String> expandConfig(Map<String, String> map) { return expandAllProperties(map, getPropertyLookup().getPropertiesMap()); }
[ "private", "Map", "<", "String", ",", "String", ">", "expandConfig", "(", "Map", "<", "String", ",", "String", ">", "map", ")", "{", "return", "expandAllProperties", "(", "map", ",", "getPropertyLookup", "(", ")", ".", "getPropertiesMap", "(", ")", ")", ";", "}" ]
Expand embedded framework property references in the map values @param map map @return expanded map
[ "Expand", "embedded", "framework", "property", "references", "in", "the", "map", "values" ]
8070f774f55bffaa1118ff0c03aea319d40a9668
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/storage/StorageTreeFactory.java#L313-L315
16,123
rundeck/rundeck
core/src/main/java/com/dtolabs/rundeck/core/execution/script/ScriptfileUtils.java
ScriptfileUtils.writeScriptTempfile
public static File writeScriptTempfile( final Framework framework, final Reader source, final LineEndingStyle style ) throws IOException { return writeScriptTempfile(framework, null, null, source, style); }
java
public static File writeScriptTempfile( final Framework framework, final Reader source, final LineEndingStyle style ) throws IOException { return writeScriptTempfile(framework, null, null, source, style); }
[ "public", "static", "File", "writeScriptTempfile", "(", "final", "Framework", "framework", ",", "final", "Reader", "source", ",", "final", "LineEndingStyle", "style", ")", "throws", "IOException", "{", "return", "writeScriptTempfile", "(", "framework", ",", "null", ",", "null", ",", "source", ",", "style", ")", ";", "}" ]
Copy reader content to a tempfile for script execution @param framework framework @param source string content @param style style @return tempfile @throws IOException if an error occurs
[ "Copy", "reader", "content", "to", "a", "tempfile", "for", "script", "execution" ]
8070f774f55bffaa1118ff0c03aea319d40a9668
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/execution/script/ScriptfileUtils.java#L170-L178
16,124
rundeck/rundeck
core/src/main/java/com/dtolabs/rundeck/core/execution/script/ScriptfileUtils.java
ScriptfileUtils.writeScriptTempfile
public static File writeScriptTempfile( final Framework framework, final InputStream stream, final String source, final Reader reader, final LineEndingStyle style ) throws IOException { /* * Prepare a file to save the content */ final File scriptfile = createTempFile(framework); writeScriptFile(stream, source, reader, style, scriptfile); return scriptfile; }
java
public static File writeScriptTempfile( final Framework framework, final InputStream stream, final String source, final Reader reader, final LineEndingStyle style ) throws IOException { /* * Prepare a file to save the content */ final File scriptfile = createTempFile(framework); writeScriptFile(stream, source, reader, style, scriptfile); return scriptfile; }
[ "public", "static", "File", "writeScriptTempfile", "(", "final", "Framework", "framework", ",", "final", "InputStream", "stream", ",", "final", "String", "source", ",", "final", "Reader", "reader", ",", "final", "LineEndingStyle", "style", ")", "throws", "IOException", "{", "/*\n * Prepare a file to save the content\n */", "final", "File", "scriptfile", "=", "createTempFile", "(", "framework", ")", ";", "writeScriptFile", "(", "stream", ",", "source", ",", "reader", ",", "style", ",", "scriptfile", ")", ";", "return", "scriptfile", ";", "}" ]
Copy a source stream or string content to a tempfile for script execution @param framework framework @param stream source stream @param source content @param style file line ending style to use @param reader reader @return tempfile @throws IOException if an error occurs
[ "Copy", "a", "source", "stream", "or", "string", "content", "to", "a", "tempfile", "for", "script", "execution" ]
8070f774f55bffaa1118ff0c03aea319d40a9668
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/execution/script/ScriptfileUtils.java#L194-L210
16,125
rundeck/rundeck
core/src/main/java/com/dtolabs/rundeck/core/execution/script/ScriptfileUtils.java
ScriptfileUtils.writeScriptFile
public static void writeScriptFile( InputStream stream, String scriptString, Reader reader, LineEndingStyle style, File scriptfile ) throws IOException { try (FileWriter writer = new FileWriter(scriptfile)) { if (null != scriptString) { ScriptfileUtils.writeReader(new StringReader(scriptString), writer, style); } else if (null != reader) { ScriptfileUtils.writeReader(reader, writer, style); } else if (null != stream) { ScriptfileUtils.writeStream(stream, writer, style); } else { throw new IllegalArgumentException("no script source argument"); } } }
java
public static void writeScriptFile( InputStream stream, String scriptString, Reader reader, LineEndingStyle style, File scriptfile ) throws IOException { try (FileWriter writer = new FileWriter(scriptfile)) { if (null != scriptString) { ScriptfileUtils.writeReader(new StringReader(scriptString), writer, style); } else if (null != reader) { ScriptfileUtils.writeReader(reader, writer, style); } else if (null != stream) { ScriptfileUtils.writeStream(stream, writer, style); } else { throw new IllegalArgumentException("no script source argument"); } } }
[ "public", "static", "void", "writeScriptFile", "(", "InputStream", "stream", ",", "String", "scriptString", ",", "Reader", "reader", ",", "LineEndingStyle", "style", ",", "File", "scriptfile", ")", "throws", "IOException", "{", "try", "(", "FileWriter", "writer", "=", "new", "FileWriter", "(", "scriptfile", ")", ")", "{", "if", "(", "null", "!=", "scriptString", ")", "{", "ScriptfileUtils", ".", "writeReader", "(", "new", "StringReader", "(", "scriptString", ")", ",", "writer", ",", "style", ")", ";", "}", "else", "if", "(", "null", "!=", "reader", ")", "{", "ScriptfileUtils", ".", "writeReader", "(", "reader", ",", "writer", ",", "style", ")", ";", "}", "else", "if", "(", "null", "!=", "stream", ")", "{", "ScriptfileUtils", ".", "writeStream", "(", "stream", ",", "writer", ",", "style", ")", ";", "}", "else", "{", "throw", "new", "IllegalArgumentException", "(", "\"no script source argument\"", ")", ";", "}", "}", "}" ]
Write script content to a destination file from one of the sources @param stream stream source @param scriptString script content @param reader reader source @param style line ending style @param scriptfile destination file @throws IOException on io error
[ "Write", "script", "content", "to", "a", "destination", "file", "from", "one", "of", "the", "sources" ]
8070f774f55bffaa1118ff0c03aea319d40a9668
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/execution/script/ScriptfileUtils.java#L223-L243
16,126
rundeck/rundeck
core/src/main/java/com/dtolabs/rundeck/core/execution/script/ScriptfileUtils.java
ScriptfileUtils.setExecutePermissions
public static void setExecutePermissions(final File scriptfile) throws IOException { if (!scriptfile.setExecutable(true, true)) { System.err.println("Unable to set executable bit on temp script file, execution may fail: " + scriptfile .getAbsolutePath()); } }
java
public static void setExecutePermissions(final File scriptfile) throws IOException { if (!scriptfile.setExecutable(true, true)) { System.err.println("Unable to set executable bit on temp script file, execution may fail: " + scriptfile .getAbsolutePath()); } }
[ "public", "static", "void", "setExecutePermissions", "(", "final", "File", "scriptfile", ")", "throws", "IOException", "{", "if", "(", "!", "scriptfile", ".", "setExecutable", "(", "true", ",", "true", ")", ")", "{", "System", ".", "err", ".", "println", "(", "\"Unable to set executable bit on temp script file, execution may fail: \"", "+", "scriptfile", ".", "getAbsolutePath", "(", ")", ")", ";", "}", "}" ]
Set the executable flag on a file if supported by the OS @param scriptfile target file @throws IOException if an error occurs
[ "Set", "the", "executable", "flag", "on", "a", "file", "if", "supported", "by", "the", "OS" ]
8070f774f55bffaa1118ff0c03aea319d40a9668
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/execution/script/ScriptfileUtils.java#L287-L292
16,127
yasserg/crawler4j
crawler4j/src/main/java/edu/uci/ics/crawler4j/frontier/DocIDServer.java
DocIDServer.getDocId
public int getDocId(String url) { synchronized (mutex) { OperationStatus result = null; DatabaseEntry value = new DatabaseEntry(); try { DatabaseEntry key = new DatabaseEntry(url.getBytes()); result = docIDsDB.get(null, key, value, null); } catch (RuntimeException e) { if (config.isHaltOnError()) { throw e; } else { logger.error("Exception thrown while getting DocID", e); return -1; } } if ((result == OperationStatus.SUCCESS) && (value.getData().length > 0)) { return Util.byteArray2Int(value.getData()); } return -1; } }
java
public int getDocId(String url) { synchronized (mutex) { OperationStatus result = null; DatabaseEntry value = new DatabaseEntry(); try { DatabaseEntry key = new DatabaseEntry(url.getBytes()); result = docIDsDB.get(null, key, value, null); } catch (RuntimeException e) { if (config.isHaltOnError()) { throw e; } else { logger.error("Exception thrown while getting DocID", e); return -1; } } if ((result == OperationStatus.SUCCESS) && (value.getData().length > 0)) { return Util.byteArray2Int(value.getData()); } return -1; } }
[ "public", "int", "getDocId", "(", "String", "url", ")", "{", "synchronized", "(", "mutex", ")", "{", "OperationStatus", "result", "=", "null", ";", "DatabaseEntry", "value", "=", "new", "DatabaseEntry", "(", ")", ";", "try", "{", "DatabaseEntry", "key", "=", "new", "DatabaseEntry", "(", "url", ".", "getBytes", "(", ")", ")", ";", "result", "=", "docIDsDB", ".", "get", "(", "null", ",", "key", ",", "value", ",", "null", ")", ";", "}", "catch", "(", "RuntimeException", "e", ")", "{", "if", "(", "config", ".", "isHaltOnError", "(", ")", ")", "{", "throw", "e", ";", "}", "else", "{", "logger", ".", "error", "(", "\"Exception thrown while getting DocID\"", ",", "e", ")", ";", "return", "-", "1", ";", "}", "}", "if", "(", "(", "result", "==", "OperationStatus", ".", "SUCCESS", ")", "&&", "(", "value", ".", "getData", "(", ")", ".", "length", ">", "0", ")", ")", "{", "return", "Util", ".", "byteArray2Int", "(", "value", ".", "getData", "(", ")", ")", ";", "}", "return", "-", "1", ";", "}", "}" ]
Returns the docid of an already seen url. @param url the URL for which the docid is returned. @return the docid of the url if it is seen before. Otherwise -1 is returned.
[ "Returns", "the", "docid", "of", "an", "already", "seen", "url", "." ]
4fcddc86414d1831973aff94050af55c7aeff3bc
https://github.com/yasserg/crawler4j/blob/4fcddc86414d1831973aff94050af55c7aeff3bc/crawler4j/src/main/java/edu/uci/ics/crawler4j/frontier/DocIDServer.java#L71-L94
16,128
yasserg/crawler4j
crawler4j/src/main/java/edu/uci/ics/crawler4j/crawler/Page.java
Page.toByteArray
protected byte[] toByteArray(HttpEntity entity, int maxBytes) throws IOException { if (entity == null) { return new byte[0]; } try (InputStream is = entity.getContent()) { int size = (int) entity.getContentLength(); int readBufferLength = size; if (readBufferLength <= 0) { readBufferLength = 4096; } // in case when the maxBytes is less than the actual page size readBufferLength = Math.min(readBufferLength, maxBytes); // We allocate the buffer with either the actual size of the entity (if available) // or with the default 4KiB if the server did not return a value to avoid allocating // the full maxBytes (for the cases when the actual size will be smaller than maxBytes). ByteArrayBuffer buffer = new ByteArrayBuffer(readBufferLength); byte[] tmpBuff = new byte[4096]; int dataLength; while ((dataLength = is.read(tmpBuff)) != -1) { if (maxBytes > 0 && (buffer.length() + dataLength) > maxBytes) { truncated = true; dataLength = maxBytes - buffer.length(); } buffer.append(tmpBuff, 0, dataLength); if (truncated) { break; } } return buffer.toByteArray(); } }
java
protected byte[] toByteArray(HttpEntity entity, int maxBytes) throws IOException { if (entity == null) { return new byte[0]; } try (InputStream is = entity.getContent()) { int size = (int) entity.getContentLength(); int readBufferLength = size; if (readBufferLength <= 0) { readBufferLength = 4096; } // in case when the maxBytes is less than the actual page size readBufferLength = Math.min(readBufferLength, maxBytes); // We allocate the buffer with either the actual size of the entity (if available) // or with the default 4KiB if the server did not return a value to avoid allocating // the full maxBytes (for the cases when the actual size will be smaller than maxBytes). ByteArrayBuffer buffer = new ByteArrayBuffer(readBufferLength); byte[] tmpBuff = new byte[4096]; int dataLength; while ((dataLength = is.read(tmpBuff)) != -1) { if (maxBytes > 0 && (buffer.length() + dataLength) > maxBytes) { truncated = true; dataLength = maxBytes - buffer.length(); } buffer.append(tmpBuff, 0, dataLength); if (truncated) { break; } } return buffer.toByteArray(); } }
[ "protected", "byte", "[", "]", "toByteArray", "(", "HttpEntity", "entity", ",", "int", "maxBytes", ")", "throws", "IOException", "{", "if", "(", "entity", "==", "null", ")", "{", "return", "new", "byte", "[", "0", "]", ";", "}", "try", "(", "InputStream", "is", "=", "entity", ".", "getContent", "(", ")", ")", "{", "int", "size", "=", "(", "int", ")", "entity", ".", "getContentLength", "(", ")", ";", "int", "readBufferLength", "=", "size", ";", "if", "(", "readBufferLength", "<=", "0", ")", "{", "readBufferLength", "=", "4096", ";", "}", "// in case when the maxBytes is less than the actual page size", "readBufferLength", "=", "Math", ".", "min", "(", "readBufferLength", ",", "maxBytes", ")", ";", "// We allocate the buffer with either the actual size of the entity (if available)", "// or with the default 4KiB if the server did not return a value to avoid allocating", "// the full maxBytes (for the cases when the actual size will be smaller than maxBytes).", "ByteArrayBuffer", "buffer", "=", "new", "ByteArrayBuffer", "(", "readBufferLength", ")", ";", "byte", "[", "]", "tmpBuff", "=", "new", "byte", "[", "4096", "]", ";", "int", "dataLength", ";", "while", "(", "(", "dataLength", "=", "is", ".", "read", "(", "tmpBuff", ")", ")", "!=", "-", "1", ")", "{", "if", "(", "maxBytes", ">", "0", "&&", "(", "buffer", ".", "length", "(", ")", "+", "dataLength", ")", ">", "maxBytes", ")", "{", "truncated", "=", "true", ";", "dataLength", "=", "maxBytes", "-", "buffer", ".", "length", "(", ")", ";", "}", "buffer", ".", "append", "(", "tmpBuff", ",", "0", ",", "dataLength", ")", ";", "if", "(", "truncated", ")", "{", "break", ";", "}", "}", "return", "buffer", ".", "toByteArray", "(", ")", ";", "}", "}" ]
Read contents from an entity, with a specified maximum. This is a replacement of EntityUtils.toByteArray because that function does not impose a maximum size. @param entity The entity from which to read @param maxBytes The maximum number of bytes to read @return A byte array containing maxBytes or fewer bytes read from the entity @throws IOException Thrown when reading fails for any reason
[ "Read", "contents", "from", "an", "entity", "with", "a", "specified", "maximum", ".", "This", "is", "a", "replacement", "of", "EntityUtils", ".", "toByteArray", "because", "that", "function", "does", "not", "impose", "a", "maximum", "size", "." ]
4fcddc86414d1831973aff94050af55c7aeff3bc
https://github.com/yasserg/crawler4j/blob/4fcddc86414d1831973aff94050af55c7aeff3bc/crawler4j/src/main/java/edu/uci/ics/crawler4j/crawler/Page.java#L120-L154
16,129
yasserg/crawler4j
crawler4j/src/main/java/edu/uci/ics/crawler4j/crawler/Page.java
Page.load
public void load(HttpEntity entity, int maxBytes) throws IOException { contentType = null; Header type = entity.getContentType(); if (type != null) { contentType = type.getValue(); } contentEncoding = null; Header encoding = entity.getContentEncoding(); if (encoding != null) { contentEncoding = encoding.getValue(); } Charset charset; try { charset = ContentType.getOrDefault(entity).getCharset(); } catch (Exception e) { logger.warn("parse charset failed: {}", e.getMessage()); charset = Charset.forName("UTF-8"); } if (charset != null) { contentCharset = charset.displayName(); } contentData = toByteArray(entity, maxBytes); }
java
public void load(HttpEntity entity, int maxBytes) throws IOException { contentType = null; Header type = entity.getContentType(); if (type != null) { contentType = type.getValue(); } contentEncoding = null; Header encoding = entity.getContentEncoding(); if (encoding != null) { contentEncoding = encoding.getValue(); } Charset charset; try { charset = ContentType.getOrDefault(entity).getCharset(); } catch (Exception e) { logger.warn("parse charset failed: {}", e.getMessage()); charset = Charset.forName("UTF-8"); } if (charset != null) { contentCharset = charset.displayName(); } contentData = toByteArray(entity, maxBytes); }
[ "public", "void", "load", "(", "HttpEntity", "entity", ",", "int", "maxBytes", ")", "throws", "IOException", "{", "contentType", "=", "null", ";", "Header", "type", "=", "entity", ".", "getContentType", "(", ")", ";", "if", "(", "type", "!=", "null", ")", "{", "contentType", "=", "type", ".", "getValue", "(", ")", ";", "}", "contentEncoding", "=", "null", ";", "Header", "encoding", "=", "entity", ".", "getContentEncoding", "(", ")", ";", "if", "(", "encoding", "!=", "null", ")", "{", "contentEncoding", "=", "encoding", ".", "getValue", "(", ")", ";", "}", "Charset", "charset", ";", "try", "{", "charset", "=", "ContentType", ".", "getOrDefault", "(", "entity", ")", ".", "getCharset", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "logger", ".", "warn", "(", "\"parse charset failed: {}\"", ",", "e", ".", "getMessage", "(", ")", ")", ";", "charset", "=", "Charset", ".", "forName", "(", "\"UTF-8\"", ")", ";", "}", "if", "(", "charset", "!=", "null", ")", "{", "contentCharset", "=", "charset", ".", "displayName", "(", ")", ";", "}", "contentData", "=", "toByteArray", "(", "entity", ",", "maxBytes", ")", ";", "}" ]
Loads the content of this page from a fetched HttpEntity. @param entity HttpEntity @param maxBytes The maximum number of bytes to read @throws IOException when load fails
[ "Loads", "the", "content", "of", "this", "page", "from", "a", "fetched", "HttpEntity", "." ]
4fcddc86414d1831973aff94050af55c7aeff3bc
https://github.com/yasserg/crawler4j/blob/4fcddc86414d1831973aff94050af55c7aeff3bc/crawler4j/src/main/java/edu/uci/ics/crawler4j/crawler/Page.java#L163-L190
16,130
yasserg/crawler4j
crawler4j/src/main/java/edu/uci/ics/crawler4j/robotstxt/PathRule.java
PathRule.matchesRobotsPattern
public static boolean matchesRobotsPattern(String pattern, String path) { return robotsPatternToRegexp(pattern).matcher(path).matches(); }
java
public static boolean matchesRobotsPattern(String pattern, String path) { return robotsPatternToRegexp(pattern).matcher(path).matches(); }
[ "public", "static", "boolean", "matchesRobotsPattern", "(", "String", "pattern", ",", "String", "path", ")", "{", "return", "robotsPatternToRegexp", "(", "pattern", ")", ".", "matcher", "(", "path", ")", ".", "matches", "(", ")", ";", "}" ]
Check if the specified path matches a robots.txt pattern @param pattern The pattern to match @param path The path to match with the pattern @return True when the pattern matches, false if it does not
[ "Check", "if", "the", "specified", "path", "matches", "a", "robots", ".", "txt", "pattern" ]
4fcddc86414d1831973aff94050af55c7aeff3bc
https://github.com/yasserg/crawler4j/blob/4fcddc86414d1831973aff94050af55c7aeff3bc/crawler4j/src/main/java/edu/uci/ics/crawler4j/robotstxt/PathRule.java#L107-L109
16,131
yasserg/crawler4j
crawler4j/src/main/java/edu/uci/ics/crawler4j/crawler/CrawlConfig.java
CrawlConfig.validate
public void validate() throws Exception { if (crawlStorageFolder == null) { throw new Exception("Crawl storage folder is not set in the CrawlConfig."); } if (politenessDelay < 0) { throw new Exception("Invalid value for politeness delay: " + politenessDelay); } if (maxDepthOfCrawling < -1) { throw new Exception( "Maximum crawl depth should be either a positive number or -1 for unlimited depth" + "."); } if (maxDepthOfCrawling > Short.MAX_VALUE) { throw new Exception("Maximum value for crawl depth is " + Short.MAX_VALUE); } }
java
public void validate() throws Exception { if (crawlStorageFolder == null) { throw new Exception("Crawl storage folder is not set in the CrawlConfig."); } if (politenessDelay < 0) { throw new Exception("Invalid value for politeness delay: " + politenessDelay); } if (maxDepthOfCrawling < -1) { throw new Exception( "Maximum crawl depth should be either a positive number or -1 for unlimited depth" + "."); } if (maxDepthOfCrawling > Short.MAX_VALUE) { throw new Exception("Maximum value for crawl depth is " + Short.MAX_VALUE); } }
[ "public", "void", "validate", "(", ")", "throws", "Exception", "{", "if", "(", "crawlStorageFolder", "==", "null", ")", "{", "throw", "new", "Exception", "(", "\"Crawl storage folder is not set in the CrawlConfig.\"", ")", ";", "}", "if", "(", "politenessDelay", "<", "0", ")", "{", "throw", "new", "Exception", "(", "\"Invalid value for politeness delay: \"", "+", "politenessDelay", ")", ";", "}", "if", "(", "maxDepthOfCrawling", "<", "-", "1", ")", "{", "throw", "new", "Exception", "(", "\"Maximum crawl depth should be either a positive number or -1 for unlimited depth\"", "+", "\".\"", ")", ";", "}", "if", "(", "maxDepthOfCrawling", ">", "Short", ".", "MAX_VALUE", ")", "{", "throw", "new", "Exception", "(", "\"Maximum value for crawl depth is \"", "+", "Short", ".", "MAX_VALUE", ")", ";", "}", "}" ]
Validates the configs specified by this instance. @throws Exception on Validation fail
[ "Validates", "the", "configs", "specified", "by", "this", "instance", "." ]
4fcddc86414d1831973aff94050af55c7aeff3bc
https://github.com/yasserg/crawler4j/blob/4fcddc86414d1831973aff94050af55c7aeff3bc/crawler4j/src/main/java/edu/uci/ics/crawler4j/crawler/CrawlConfig.java#L243-L258
16,132
yasserg/crawler4j
crawler4j/src/main/java/edu/uci/ics/crawler4j/robotstxt/RobotstxtServer.java
RobotstxtServer.allows
public boolean allows(WebURL webURL) throws IOException, InterruptedException { if (!config.isEnabled()) { return true; } try { URL url = new URL(webURL.getURL()); String host = getHost(url); String path = url.getPath(); HostDirectives directives = host2directivesCache.get(host); if (directives != null && directives.needsRefetch()) { synchronized (host2directivesCache) { host2directivesCache.remove(host); directives = null; } } if (directives == null) { directives = fetchDirectives(url); } return directives.allows(path); } catch (MalformedURLException e) { logger.error("Bad URL in Robots.txt: " + webURL.getURL(), e); } logger.warn("RobotstxtServer: default: allow", webURL.getURL()); return true; }
java
public boolean allows(WebURL webURL) throws IOException, InterruptedException { if (!config.isEnabled()) { return true; } try { URL url = new URL(webURL.getURL()); String host = getHost(url); String path = url.getPath(); HostDirectives directives = host2directivesCache.get(host); if (directives != null && directives.needsRefetch()) { synchronized (host2directivesCache) { host2directivesCache.remove(host); directives = null; } } if (directives == null) { directives = fetchDirectives(url); } return directives.allows(path); } catch (MalformedURLException e) { logger.error("Bad URL in Robots.txt: " + webURL.getURL(), e); } logger.warn("RobotstxtServer: default: allow", webURL.getURL()); return true; }
[ "public", "boolean", "allows", "(", "WebURL", "webURL", ")", "throws", "IOException", ",", "InterruptedException", "{", "if", "(", "!", "config", ".", "isEnabled", "(", ")", ")", "{", "return", "true", ";", "}", "try", "{", "URL", "url", "=", "new", "URL", "(", "webURL", ".", "getURL", "(", ")", ")", ";", "String", "host", "=", "getHost", "(", "url", ")", ";", "String", "path", "=", "url", ".", "getPath", "(", ")", ";", "HostDirectives", "directives", "=", "host2directivesCache", ".", "get", "(", "host", ")", ";", "if", "(", "directives", "!=", "null", "&&", "directives", ".", "needsRefetch", "(", ")", ")", "{", "synchronized", "(", "host2directivesCache", ")", "{", "host2directivesCache", ".", "remove", "(", "host", ")", ";", "directives", "=", "null", ";", "}", "}", "if", "(", "directives", "==", "null", ")", "{", "directives", "=", "fetchDirectives", "(", "url", ")", ";", "}", "return", "directives", ".", "allows", "(", "path", ")", ";", "}", "catch", "(", "MalformedURLException", "e", ")", "{", "logger", ".", "error", "(", "\"Bad URL in Robots.txt: \"", "+", "webURL", ".", "getURL", "(", ")", ",", "e", ")", ";", "}", "logger", ".", "warn", "(", "\"RobotstxtServer: default: allow\"", ",", "webURL", ".", "getURL", "(", ")", ")", ";", "return", "true", ";", "}" ]
Please note that in the case of a bad URL, TRUE will be returned @throws InterruptedException @throws IOException
[ "Please", "note", "that", "in", "the", "case", "of", "a", "bad", "URL", "TRUE", "will", "be", "returned" ]
4fcddc86414d1831973aff94050af55c7aeff3bc
https://github.com/yasserg/crawler4j/blob/4fcddc86414d1831973aff94050af55c7aeff3bc/crawler4j/src/main/java/edu/uci/ics/crawler4j/robotstxt/RobotstxtServer.java#L77-L104
16,133
yasserg/crawler4j
crawler4j/src/main/java/edu/uci/ics/crawler4j/robotstxt/HostDirectives.java
HostDirectives.checkAccess
public int checkAccess(String path) { timeLastAccessed = System.currentTimeMillis(); int result = UNDEFINED; String myUA = config.getUserAgentName(); boolean ignoreUADisc = config.getIgnoreUADiscrimination(); // When checking rules, the list of rules is already ordered based on the // match of the user-agent of the clause with the user-agent of the crawler. // The most specific match should come first. // // Only the most specific match is obeyed, unless ignoreUADiscrimination is // enabled. In that case, any matching non-wildcard clause that explicitly // disallows the path is obeyed. If no such rule exists and any UA in the list // is allowed access, that rule is obeyed. for (UserAgentDirectives ua : rules) { int score = ua.match(myUA); // If ignoreUADisc is disabled and the current UA doesn't match, // the rest will not match so we are done here. if (score == 0 && !ignoreUADisc) { break; } // Match the rule to the path result = ua.checkAccess(path, userAgent); // If the result is ALLOWED or UNDEFINED, or if // this is a wildcard rule and ignoreUADisc is disabled, // this is the final verdict. if (result != DISALLOWED || (!ua.isWildcard() || !ignoreUADisc)) { break; } // This is a wildcard rule that disallows access. The verdict is stored, // but the other rules will also be checked to see if any specific UA is allowed // access to this path. If so, that positive UA discrimination is ignored // and we crawl the page anyway. } return result; }
java
public int checkAccess(String path) { timeLastAccessed = System.currentTimeMillis(); int result = UNDEFINED; String myUA = config.getUserAgentName(); boolean ignoreUADisc = config.getIgnoreUADiscrimination(); // When checking rules, the list of rules is already ordered based on the // match of the user-agent of the clause with the user-agent of the crawler. // The most specific match should come first. // // Only the most specific match is obeyed, unless ignoreUADiscrimination is // enabled. In that case, any matching non-wildcard clause that explicitly // disallows the path is obeyed. If no such rule exists and any UA in the list // is allowed access, that rule is obeyed. for (UserAgentDirectives ua : rules) { int score = ua.match(myUA); // If ignoreUADisc is disabled and the current UA doesn't match, // the rest will not match so we are done here. if (score == 0 && !ignoreUADisc) { break; } // Match the rule to the path result = ua.checkAccess(path, userAgent); // If the result is ALLOWED or UNDEFINED, or if // this is a wildcard rule and ignoreUADisc is disabled, // this is the final verdict. if (result != DISALLOWED || (!ua.isWildcard() || !ignoreUADisc)) { break; } // This is a wildcard rule that disallows access. The verdict is stored, // but the other rules will also be checked to see if any specific UA is allowed // access to this path. If so, that positive UA discrimination is ignored // and we crawl the page anyway. } return result; }
[ "public", "int", "checkAccess", "(", "String", "path", ")", "{", "timeLastAccessed", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "int", "result", "=", "UNDEFINED", ";", "String", "myUA", "=", "config", ".", "getUserAgentName", "(", ")", ";", "boolean", "ignoreUADisc", "=", "config", ".", "getIgnoreUADiscrimination", "(", ")", ";", "// When checking rules, the list of rules is already ordered based on the", "// match of the user-agent of the clause with the user-agent of the crawler.", "// The most specific match should come first.", "//", "// Only the most specific match is obeyed, unless ignoreUADiscrimination is", "// enabled. In that case, any matching non-wildcard clause that explicitly", "// disallows the path is obeyed. If no such rule exists and any UA in the list", "// is allowed access, that rule is obeyed.", "for", "(", "UserAgentDirectives", "ua", ":", "rules", ")", "{", "int", "score", "=", "ua", ".", "match", "(", "myUA", ")", ";", "// If ignoreUADisc is disabled and the current UA doesn't match,", "// the rest will not match so we are done here.", "if", "(", "score", "==", "0", "&&", "!", "ignoreUADisc", ")", "{", "break", ";", "}", "// Match the rule to the path", "result", "=", "ua", ".", "checkAccess", "(", "path", ",", "userAgent", ")", ";", "// If the result is ALLOWED or UNDEFINED, or if", "// this is a wildcard rule and ignoreUADisc is disabled,", "// this is the final verdict.", "if", "(", "result", "!=", "DISALLOWED", "||", "(", "!", "ua", ".", "isWildcard", "(", ")", "||", "!", "ignoreUADisc", ")", ")", "{", "break", ";", "}", "// This is a wildcard rule that disallows access. The verdict is stored,", "// but the other rules will also be checked to see if any specific UA is allowed", "// access to this path. If so, that positive UA discrimination is ignored", "// and we crawl the page anyway.", "}", "return", "result", ";", "}" ]
Check if any of the rules say anything about the specified path @param path The path to check @return One of ALLOWED, DISALLOWED or UNDEFINED
[ "Check", "if", "any", "of", "the", "rules", "say", "anything", "about", "the", "specified", "path" ]
4fcddc86414d1831973aff94050af55c7aeff3bc
https://github.com/yasserg/crawler4j/blob/4fcddc86414d1831973aff94050af55c7aeff3bc/crawler4j/src/main/java/edu/uci/ics/crawler4j/robotstxt/HostDirectives.java#L98-L137
16,134
yasserg/crawler4j
crawler4j/src/main/java/edu/uci/ics/crawler4j/url/URLCanonicalizer.java
URLCanonicalizer.createParameterMap
private static Map<String, String> createParameterMap(String queryString) { if ((queryString == null) || queryString.isEmpty()) { return null; } final String[] pairs = queryString.split("&"); final Map<String, String> params = new LinkedHashMap<>(pairs.length); for (final String pair : pairs) { if (pair.isEmpty()) { continue; } String[] tokens = pair.split("=", 2); switch (tokens.length) { case 1: if (pair.charAt(0) == '=') { params.put("", tokens[0]); } else { params.put(tokens[0], ""); } break; case 2: params.put(tokens[0], tokens[1]); break; } } return new LinkedHashMap<>(params); }
java
private static Map<String, String> createParameterMap(String queryString) { if ((queryString == null) || queryString.isEmpty()) { return null; } final String[] pairs = queryString.split("&"); final Map<String, String> params = new LinkedHashMap<>(pairs.length); for (final String pair : pairs) { if (pair.isEmpty()) { continue; } String[] tokens = pair.split("=", 2); switch (tokens.length) { case 1: if (pair.charAt(0) == '=') { params.put("", tokens[0]); } else { params.put(tokens[0], ""); } break; case 2: params.put(tokens[0], tokens[1]); break; } } return new LinkedHashMap<>(params); }
[ "private", "static", "Map", "<", "String", ",", "String", ">", "createParameterMap", "(", "String", "queryString", ")", "{", "if", "(", "(", "queryString", "==", "null", ")", "||", "queryString", ".", "isEmpty", "(", ")", ")", "{", "return", "null", ";", "}", "final", "String", "[", "]", "pairs", "=", "queryString", ".", "split", "(", "\"&\"", ")", ";", "final", "Map", "<", "String", ",", "String", ">", "params", "=", "new", "LinkedHashMap", "<>", "(", "pairs", ".", "length", ")", ";", "for", "(", "final", "String", "pair", ":", "pairs", ")", "{", "if", "(", "pair", ".", "isEmpty", "(", ")", ")", "{", "continue", ";", "}", "String", "[", "]", "tokens", "=", "pair", ".", "split", "(", "\"=\"", ",", "2", ")", ";", "switch", "(", "tokens", ".", "length", ")", "{", "case", "1", ":", "if", "(", "pair", ".", "charAt", "(", "0", ")", "==", "'", "'", ")", "{", "params", ".", "put", "(", "\"\"", ",", "tokens", "[", "0", "]", ")", ";", "}", "else", "{", "params", ".", "put", "(", "tokens", "[", "0", "]", ",", "\"\"", ")", ";", "}", "break", ";", "case", "2", ":", "params", ".", "put", "(", "tokens", "[", "0", "]", ",", "tokens", "[", "1", "]", ")", ";", "break", ";", "}", "}", "return", "new", "LinkedHashMap", "<>", "(", "params", ")", ";", "}" ]
Takes a query string, separates the constituent name-value pairs, and stores them in a LinkedHashMap ordered by their original order. @return Null if there is no query string.
[ "Takes", "a", "query", "string", "separates", "the", "constituent", "name", "-", "value", "pairs", "and", "stores", "them", "in", "a", "LinkedHashMap", "ordered", "by", "their", "original", "order", "." ]
4fcddc86414d1831973aff94050af55c7aeff3bc
https://github.com/yasserg/crawler4j/blob/4fcddc86414d1831973aff94050af55c7aeff3bc/crawler4j/src/main/java/edu/uci/ics/crawler4j/url/URLCanonicalizer.java#L127-L155
16,135
yasserg/crawler4j
crawler4j/src/main/java/edu/uci/ics/crawler4j/robotstxt/UserAgentDirectives.java
UserAgentDirectives.match
public int match(String userAgent) { userAgent = userAgent.toLowerCase(); int maxLength = 0; for (String ua : userAgents) { if (ua.equals("*") || userAgent.contains(ua)) { maxLength = Math.max(maxLength, ua.length()); } } return maxLength; }
java
public int match(String userAgent) { userAgent = userAgent.toLowerCase(); int maxLength = 0; for (String ua : userAgents) { if (ua.equals("*") || userAgent.contains(ua)) { maxLength = Math.max(maxLength, ua.length()); } } return maxLength; }
[ "public", "int", "match", "(", "String", "userAgent", ")", "{", "userAgent", "=", "userAgent", ".", "toLowerCase", "(", ")", ";", "int", "maxLength", "=", "0", ";", "for", "(", "String", "ua", ":", "userAgents", ")", "{", "if", "(", "ua", ".", "equals", "(", "\"*\"", ")", "||", "userAgent", ".", "contains", "(", "ua", ")", ")", "{", "maxLength", "=", "Math", ".", "max", "(", "maxLength", ",", "ua", ".", "length", "(", ")", ")", ";", "}", "}", "return", "maxLength", ";", "}" ]
Match the current user agent directive set with the given user agent. The returned value will be the maximum match length of any user agent. @param userAgent The user agent used by the crawler @return The maximum length of a matching user agent in this set of directives
[ "Match", "the", "current", "user", "agent", "directive", "set", "with", "the", "given", "user", "agent", ".", "The", "returned", "value", "will", "be", "the", "maximum", "match", "length", "of", "any", "user", "agent", "." ]
4fcddc86414d1831973aff94050af55c7aeff3bc
https://github.com/yasserg/crawler4j/blob/4fcddc86414d1831973aff94050af55c7aeff3bc/crawler4j/src/main/java/edu/uci/ics/crawler4j/robotstxt/UserAgentDirectives.java#L91-L100
16,136
yasserg/crawler4j
crawler4j/src/main/java/edu/uci/ics/crawler4j/crawler/WebCrawler.java
WebCrawler.init
public void init(int id, CrawlController crawlController) throws InstantiationException, IllegalAccessException { this.myId = id; this.pageFetcher = crawlController.getPageFetcher(); this.robotstxtServer = crawlController.getRobotstxtServer(); this.docIdServer = crawlController.getDocIdServer(); this.frontier = crawlController.getFrontier(); this.parser = crawlController.getParser(); this.myController = crawlController; this.isWaitingForNewURLs = false; this.batchReadSize = crawlController.getConfig().getBatchReadSize(); }
java
public void init(int id, CrawlController crawlController) throws InstantiationException, IllegalAccessException { this.myId = id; this.pageFetcher = crawlController.getPageFetcher(); this.robotstxtServer = crawlController.getRobotstxtServer(); this.docIdServer = crawlController.getDocIdServer(); this.frontier = crawlController.getFrontier(); this.parser = crawlController.getParser(); this.myController = crawlController; this.isWaitingForNewURLs = false; this.batchReadSize = crawlController.getConfig().getBatchReadSize(); }
[ "public", "void", "init", "(", "int", "id", ",", "CrawlController", "crawlController", ")", "throws", "InstantiationException", ",", "IllegalAccessException", "{", "this", ".", "myId", "=", "id", ";", "this", ".", "pageFetcher", "=", "crawlController", ".", "getPageFetcher", "(", ")", ";", "this", ".", "robotstxtServer", "=", "crawlController", ".", "getRobotstxtServer", "(", ")", ";", "this", ".", "docIdServer", "=", "crawlController", ".", "getDocIdServer", "(", ")", ";", "this", ".", "frontier", "=", "crawlController", ".", "getFrontier", "(", ")", ";", "this", ".", "parser", "=", "crawlController", ".", "getParser", "(", ")", ";", "this", ".", "myController", "=", "crawlController", ";", "this", ".", "isWaitingForNewURLs", "=", "false", ";", "this", ".", "batchReadSize", "=", "crawlController", ".", "getConfig", "(", ")", ".", "getBatchReadSize", "(", ")", ";", "}" ]
Initializes the current instance of the crawler @param id the id of this crawler instance @param crawlController the controller that manages this crawling session @throws IllegalAccessException @throws InstantiationException
[ "Initializes", "the", "current", "instance", "of", "the", "crawler" ]
4fcddc86414d1831973aff94050af55c7aeff3bc
https://github.com/yasserg/crawler4j/blob/4fcddc86414d1831973aff94050af55c7aeff3bc/crawler4j/src/main/java/edu/uci/ics/crawler4j/crawler/WebCrawler.java#L119-L130
16,137
yasserg/crawler4j
crawler4j/src/main/java/edu/uci/ics/crawler4j/crawler/WebCrawler.java
WebCrawler.onUnhandledException
protected void onUnhandledException(WebURL webUrl, Throwable e) { if (myController.getConfig().isHaltOnError() && !(e instanceof IOException)) { throw new RuntimeException("unhandled exception", e); } else { String urlStr = (webUrl == null ? "NULL" : webUrl.getURL()); logger.warn("Unhandled exception while fetching {}: {}", urlStr, e.getMessage()); logger.info("Stacktrace: ", e); // Do nothing by default (except basic logging) // Sub-classed can override this to add their custom functionality } }
java
protected void onUnhandledException(WebURL webUrl, Throwable e) { if (myController.getConfig().isHaltOnError() && !(e instanceof IOException)) { throw new RuntimeException("unhandled exception", e); } else { String urlStr = (webUrl == null ? "NULL" : webUrl.getURL()); logger.warn("Unhandled exception while fetching {}: {}", urlStr, e.getMessage()); logger.info("Stacktrace: ", e); // Do nothing by default (except basic logging) // Sub-classed can override this to add their custom functionality } }
[ "protected", "void", "onUnhandledException", "(", "WebURL", "webUrl", ",", "Throwable", "e", ")", "{", "if", "(", "myController", ".", "getConfig", "(", ")", ".", "isHaltOnError", "(", ")", "&&", "!", "(", "e", "instanceof", "IOException", ")", ")", "{", "throw", "new", "RuntimeException", "(", "\"unhandled exception\"", ",", "e", ")", ";", "}", "else", "{", "String", "urlStr", "=", "(", "webUrl", "==", "null", "?", "\"NULL\"", ":", "webUrl", ".", "getURL", "(", ")", ")", ";", "logger", ".", "warn", "(", "\"Unhandled exception while fetching {}: {}\"", ",", "urlStr", ",", "e", ".", "getMessage", "(", ")", ")", ";", "logger", ".", "info", "(", "\"Stacktrace: \"", ",", "e", ")", ";", "// Do nothing by default (except basic logging)", "// Sub-classed can override this to add their custom functionality", "}", "}" ]
This function is called when a unhandled exception was encountered during fetching @param webUrl URL where a unhandled exception occured
[ "This", "function", "is", "called", "when", "a", "unhandled", "exception", "was", "encountered", "during", "fetching" ]
4fcddc86414d1831973aff94050af55c7aeff3bc
https://github.com/yasserg/crawler4j/blob/4fcddc86414d1831973aff94050af55c7aeff3bc/crawler4j/src/main/java/edu/uci/ics/crawler4j/crawler/WebCrawler.java#L266-L276
16,138
yasserg/crawler4j
crawler4j/src/main/java/edu/uci/ics/crawler4j/crawler/WebCrawler.java
WebCrawler.shouldVisit
public boolean shouldVisit(Page referringPage, WebURL url) { if (myController.getConfig().isRespectNoFollow()) { return !((referringPage != null && referringPage.getContentType() != null && referringPage.getContentType().contains("html") && ((HtmlParseData)referringPage.getParseData()) .getMetaTagValue("robots") .contains("nofollow")) || url.getAttribute("rel").contains("nofollow")); } return true; }
java
public boolean shouldVisit(Page referringPage, WebURL url) { if (myController.getConfig().isRespectNoFollow()) { return !((referringPage != null && referringPage.getContentType() != null && referringPage.getContentType().contains("html") && ((HtmlParseData)referringPage.getParseData()) .getMetaTagValue("robots") .contains("nofollow")) || url.getAttribute("rel").contains("nofollow")); } return true; }
[ "public", "boolean", "shouldVisit", "(", "Page", "referringPage", ",", "WebURL", "url", ")", "{", "if", "(", "myController", ".", "getConfig", "(", ")", ".", "isRespectNoFollow", "(", ")", ")", "{", "return", "!", "(", "(", "referringPage", "!=", "null", "&&", "referringPage", ".", "getContentType", "(", ")", "!=", "null", "&&", "referringPage", ".", "getContentType", "(", ")", ".", "contains", "(", "\"html\"", ")", "&&", "(", "(", "HtmlParseData", ")", "referringPage", ".", "getParseData", "(", ")", ")", ".", "getMetaTagValue", "(", "\"robots\"", ")", ".", "contains", "(", "\"nofollow\"", ")", ")", "||", "url", ".", "getAttribute", "(", "\"rel\"", ")", ".", "contains", "(", "\"nofollow\"", ")", ")", ";", "}", "return", "true", ";", "}" ]
Classes that extends WebCrawler should overwrite this function to tell the crawler whether the given url should be crawled or not. The following default implementation indicates that all urls should be included in the crawl except those with a nofollow flag. @param url the url which we are interested to know whether it should be included in the crawl or not. @param referringPage The Page in which this url was found. @return if the url should be included in the crawl it returns true, otherwise false is returned.
[ "Classes", "that", "extends", "WebCrawler", "should", "overwrite", "this", "function", "to", "tell", "the", "crawler", "whether", "the", "given", "url", "should", "be", "crawled", "or", "not", ".", "The", "following", "default", "implementation", "indicates", "that", "all", "urls", "should", "be", "included", "in", "the", "crawl", "except", "those", "with", "a", "nofollow", "flag", "." ]
4fcddc86414d1831973aff94050af55c7aeff3bc
https://github.com/yasserg/crawler4j/blob/4fcddc86414d1831973aff94050af55c7aeff3bc/crawler4j/src/main/java/edu/uci/ics/crawler4j/crawler/WebCrawler.java#L369-L381
16,139
yasserg/crawler4j
crawler4j/src/main/java/edu/uci/ics/crawler4j/crawler/CrawlController.java
CrawlController.start
public <T extends WebCrawler> void start(Class<T> clazz, int numberOfCrawlers) { this.start(new DefaultWebCrawlerFactory<>(clazz), numberOfCrawlers, true); }
java
public <T extends WebCrawler> void start(Class<T> clazz, int numberOfCrawlers) { this.start(new DefaultWebCrawlerFactory<>(clazz), numberOfCrawlers, true); }
[ "public", "<", "T", "extends", "WebCrawler", ">", "void", "start", "(", "Class", "<", "T", ">", "clazz", ",", "int", "numberOfCrawlers", ")", "{", "this", ".", "start", "(", "new", "DefaultWebCrawlerFactory", "<>", "(", "clazz", ")", ",", "numberOfCrawlers", ",", "true", ")", ";", "}" ]
Start the crawling session and wait for it to finish. This method utilizes default crawler factory that creates new crawler using Java reflection @param clazz the class that implements the logic for crawler threads @param numberOfCrawlers the number of concurrent threads that will be contributing in this crawling session. @param <T> Your class extending WebCrawler
[ "Start", "the", "crawling", "session", "and", "wait", "for", "it", "to", "finish", ".", "This", "method", "utilizes", "default", "crawler", "factory", "that", "creates", "new", "crawler", "using", "Java", "reflection" ]
4fcddc86414d1831973aff94050af55c7aeff3bc
https://github.com/yasserg/crawler4j/blob/4fcddc86414d1831973aff94050af55c7aeff3bc/crawler4j/src/main/java/edu/uci/ics/crawler4j/crawler/CrawlController.java#L208-L210
16,140
yasserg/crawler4j
crawler4j/src/main/java/edu/uci/ics/crawler4j/crawler/CrawlController.java
CrawlController.start
public <T extends WebCrawler> void start(WebCrawlerFactory<T> crawlerFactory, int numberOfCrawlers) { this.start(crawlerFactory, numberOfCrawlers, true); }
java
public <T extends WebCrawler> void start(WebCrawlerFactory<T> crawlerFactory, int numberOfCrawlers) { this.start(crawlerFactory, numberOfCrawlers, true); }
[ "public", "<", "T", "extends", "WebCrawler", ">", "void", "start", "(", "WebCrawlerFactory", "<", "T", ">", "crawlerFactory", ",", "int", "numberOfCrawlers", ")", "{", "this", ".", "start", "(", "crawlerFactory", ",", "numberOfCrawlers", ",", "true", ")", ";", "}" ]
Start the crawling session and wait for it to finish. @param crawlerFactory factory to create crawlers on demand for each thread @param numberOfCrawlers the number of concurrent threads that will be contributing in this crawling session. @param <T> Your class extending WebCrawler
[ "Start", "the", "crawling", "session", "and", "wait", "for", "it", "to", "finish", "." ]
4fcddc86414d1831973aff94050af55c7aeff3bc
https://github.com/yasserg/crawler4j/blob/4fcddc86414d1831973aff94050af55c7aeff3bc/crawler4j/src/main/java/edu/uci/ics/crawler4j/crawler/CrawlController.java#L234-L237
16,141
yasserg/crawler4j
crawler4j/src/main/java/edu/uci/ics/crawler4j/crawler/CrawlController.java
CrawlController.startNonBlocking
public <T extends WebCrawler> void startNonBlocking(WebCrawlerFactory<T> crawlerFactory, final int numberOfCrawlers) { this.start(crawlerFactory, numberOfCrawlers, false); }
java
public <T extends WebCrawler> void startNonBlocking(WebCrawlerFactory<T> crawlerFactory, final int numberOfCrawlers) { this.start(crawlerFactory, numberOfCrawlers, false); }
[ "public", "<", "T", "extends", "WebCrawler", ">", "void", "startNonBlocking", "(", "WebCrawlerFactory", "<", "T", ">", "crawlerFactory", ",", "final", "int", "numberOfCrawlers", ")", "{", "this", ".", "start", "(", "crawlerFactory", ",", "numberOfCrawlers", ",", "false", ")", ";", "}" ]
Start the crawling session and return immediately. @param crawlerFactory factory to create crawlers on demand for each thread @param numberOfCrawlers the number of concurrent threads that will be contributing in this crawling session. @param <T> Your class extending WebCrawler
[ "Start", "the", "crawling", "session", "and", "return", "immediately", "." ]
4fcddc86414d1831973aff94050af55c7aeff3bc
https://github.com/yasserg/crawler4j/blob/4fcddc86414d1831973aff94050af55c7aeff3bc/crawler4j/src/main/java/edu/uci/ics/crawler4j/crawler/CrawlController.java#L249-L252
16,142
yasserg/crawler4j
crawler4j/src/main/java/edu/uci/ics/crawler4j/crawler/CrawlController.java
CrawlController.startNonBlocking
public <T extends WebCrawler> void startNonBlocking(Class<T> clazz, int numberOfCrawlers) { start(new DefaultWebCrawlerFactory<>(clazz), numberOfCrawlers, false); }
java
public <T extends WebCrawler> void startNonBlocking(Class<T> clazz, int numberOfCrawlers) { start(new DefaultWebCrawlerFactory<>(clazz), numberOfCrawlers, false); }
[ "public", "<", "T", "extends", "WebCrawler", ">", "void", "startNonBlocking", "(", "Class", "<", "T", ">", "clazz", ",", "int", "numberOfCrawlers", ")", "{", "start", "(", "new", "DefaultWebCrawlerFactory", "<>", "(", "clazz", ")", ",", "numberOfCrawlers", ",", "false", ")", ";", "}" ]
Start the crawling session and return immediately. This method utilizes default crawler factory that creates new crawler using Java reflection @param clazz the class that implements the logic for crawler threads @param numberOfCrawlers the number of concurrent threads that will be contributing in this crawling session. @param <T> Your class extending WebCrawler
[ "Start", "the", "crawling", "session", "and", "return", "immediately", ".", "This", "method", "utilizes", "default", "crawler", "factory", "that", "creates", "new", "crawler", "using", "Java", "reflection" ]
4fcddc86414d1831973aff94050af55c7aeff3bc
https://github.com/yasserg/crawler4j/blob/4fcddc86414d1831973aff94050af55c7aeff3bc/crawler4j/src/main/java/edu/uci/ics/crawler4j/crawler/CrawlController.java#L265-L267
16,143
yasserg/crawler4j
crawler4j/src/main/java/edu/uci/ics/crawler4j/crawler/CrawlController.java
CrawlController.waitUntilFinish
public void waitUntilFinish() { while (!finished) { synchronized (waitingLock) { if (config.isHaltOnError()) { Throwable t = getError(); if (t != null && config.isHaltOnError()) { if (t instanceof RuntimeException) { throw (RuntimeException)t; } else if (t instanceof Error) { throw (Error)t; } else { throw new RuntimeException("error on monitor thread", t); } } } if (finished) { return; } try { waitingLock.wait(); } catch (InterruptedException e) { logger.error("Error occurred", e); } } } }
java
public void waitUntilFinish() { while (!finished) { synchronized (waitingLock) { if (config.isHaltOnError()) { Throwable t = getError(); if (t != null && config.isHaltOnError()) { if (t instanceof RuntimeException) { throw (RuntimeException)t; } else if (t instanceof Error) { throw (Error)t; } else { throw new RuntimeException("error on monitor thread", t); } } } if (finished) { return; } try { waitingLock.wait(); } catch (InterruptedException e) { logger.error("Error occurred", e); } } } }
[ "public", "void", "waitUntilFinish", "(", ")", "{", "while", "(", "!", "finished", ")", "{", "synchronized", "(", "waitingLock", ")", "{", "if", "(", "config", ".", "isHaltOnError", "(", ")", ")", "{", "Throwable", "t", "=", "getError", "(", ")", ";", "if", "(", "t", "!=", "null", "&&", "config", ".", "isHaltOnError", "(", ")", ")", "{", "if", "(", "t", "instanceof", "RuntimeException", ")", "{", "throw", "(", "RuntimeException", ")", "t", ";", "}", "else", "if", "(", "t", "instanceof", "Error", ")", "{", "throw", "(", "Error", ")", "t", ";", "}", "else", "{", "throw", "new", "RuntimeException", "(", "\"error on monitor thread\"", ",", "t", ")", ";", "}", "}", "}", "if", "(", "finished", ")", "{", "return", ";", "}", "try", "{", "waitingLock", ".", "wait", "(", ")", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "logger", ".", "error", "(", "\"Error occurred\"", ",", "e", ")", ";", "}", "}", "}", "}" ]
Wait until this crawling session finishes.
[ "Wait", "until", "this", "crawling", "session", "finishes", "." ]
4fcddc86414d1831973aff94050af55c7aeff3bc
https://github.com/yasserg/crawler4j/blob/4fcddc86414d1831973aff94050af55c7aeff3bc/crawler4j/src/main/java/edu/uci/ics/crawler4j/crawler/CrawlController.java#L431-L456
16,144
yasserg/crawler4j
crawler4j/src/main/java/edu/uci/ics/crawler4j/crawler/CrawlController.java
CrawlController.addSeed
public void addSeed(String pageUrl, int docId) throws IOException, InterruptedException { String canonicalUrl = URLCanonicalizer.getCanonicalURL(pageUrl); if (canonicalUrl == null) { logger.error("Invalid seed URL: {}", pageUrl); } else { if (docId < 0) { docId = docIdServer.getDocId(canonicalUrl); if (docId > 0) { logger.trace("This URL is already seen."); return; } docId = docIdServer.getNewDocID(canonicalUrl); } else { try { docIdServer.addUrlAndDocId(canonicalUrl, docId); } catch (RuntimeException e) { if (config.isHaltOnError()) { throw e; } else { logger.error("Could not add seed: {}", e.getMessage()); } } } WebURL webUrl = new WebURL(); webUrl.setTldList(tldList); webUrl.setURL(canonicalUrl); webUrl.setDocid(docId); webUrl.setDepth((short) 0); if (robotstxtServer.allows(webUrl)) { frontier.schedule(webUrl); } else { // using the WARN level here, as the user specifically asked to add this seed logger.warn("Robots.txt does not allow this seed: {}", pageUrl); } } }
java
public void addSeed(String pageUrl, int docId) throws IOException, InterruptedException { String canonicalUrl = URLCanonicalizer.getCanonicalURL(pageUrl); if (canonicalUrl == null) { logger.error("Invalid seed URL: {}", pageUrl); } else { if (docId < 0) { docId = docIdServer.getDocId(canonicalUrl); if (docId > 0) { logger.trace("This URL is already seen."); return; } docId = docIdServer.getNewDocID(canonicalUrl); } else { try { docIdServer.addUrlAndDocId(canonicalUrl, docId); } catch (RuntimeException e) { if (config.isHaltOnError()) { throw e; } else { logger.error("Could not add seed: {}", e.getMessage()); } } } WebURL webUrl = new WebURL(); webUrl.setTldList(tldList); webUrl.setURL(canonicalUrl); webUrl.setDocid(docId); webUrl.setDepth((short) 0); if (robotstxtServer.allows(webUrl)) { frontier.schedule(webUrl); } else { // using the WARN level here, as the user specifically asked to add this seed logger.warn("Robots.txt does not allow this seed: {}", pageUrl); } } }
[ "public", "void", "addSeed", "(", "String", "pageUrl", ",", "int", "docId", ")", "throws", "IOException", ",", "InterruptedException", "{", "String", "canonicalUrl", "=", "URLCanonicalizer", ".", "getCanonicalURL", "(", "pageUrl", ")", ";", "if", "(", "canonicalUrl", "==", "null", ")", "{", "logger", ".", "error", "(", "\"Invalid seed URL: {}\"", ",", "pageUrl", ")", ";", "}", "else", "{", "if", "(", "docId", "<", "0", ")", "{", "docId", "=", "docIdServer", ".", "getDocId", "(", "canonicalUrl", ")", ";", "if", "(", "docId", ">", "0", ")", "{", "logger", ".", "trace", "(", "\"This URL is already seen.\"", ")", ";", "return", ";", "}", "docId", "=", "docIdServer", ".", "getNewDocID", "(", "canonicalUrl", ")", ";", "}", "else", "{", "try", "{", "docIdServer", ".", "addUrlAndDocId", "(", "canonicalUrl", ",", "docId", ")", ";", "}", "catch", "(", "RuntimeException", "e", ")", "{", "if", "(", "config", ".", "isHaltOnError", "(", ")", ")", "{", "throw", "e", ";", "}", "else", "{", "logger", ".", "error", "(", "\"Could not add seed: {}\"", ",", "e", ".", "getMessage", "(", ")", ")", ";", "}", "}", "}", "WebURL", "webUrl", "=", "new", "WebURL", "(", ")", ";", "webUrl", ".", "setTldList", "(", "tldList", ")", ";", "webUrl", ".", "setURL", "(", "canonicalUrl", ")", ";", "webUrl", ".", "setDocid", "(", "docId", ")", ";", "webUrl", ".", "setDepth", "(", "(", "short", ")", "0", ")", ";", "if", "(", "robotstxtServer", ".", "allows", "(", "webUrl", ")", ")", "{", "frontier", ".", "schedule", "(", "webUrl", ")", ";", "}", "else", "{", "// using the WARN level here, as the user specifically asked to add this seed", "logger", ".", "warn", "(", "\"Robots.txt does not allow this seed: {}\"", ",", "pageUrl", ")", ";", "}", "}", "}" ]
Adds a new seed URL. A seed URL is a URL that is fetched by the crawler to extract new URLs in it and follow them for crawling. You can also specify a specific document id to be assigned to this seed URL. This document id needs to be unique. Also, note that if you add three seeds with document ids 1,2, and 7. Then the next URL that is found during the crawl will get a doc id of 8. Also you need to ensure to add seeds in increasing order of document ids. Specifying doc ids is mainly useful when you have had a previous crawl and have stored the results and want to start a new crawl with seeds which get the same document ids as the previous crawl. @param pageUrl the URL of the seed @param docId the document id that you want to be assigned to this seed URL. @throws InterruptedException @throws IOException
[ "Adds", "a", "new", "seed", "URL", ".", "A", "seed", "URL", "is", "a", "URL", "that", "is", "fetched", "by", "the", "crawler", "to", "extract", "new", "URLs", "in", "it", "and", "follow", "them", "for", "crawling", ".", "You", "can", "also", "specify", "a", "specific", "document", "id", "to", "be", "assigned", "to", "this", "seed", "URL", ".", "This", "document", "id", "needs", "to", "be", "unique", ".", "Also", "note", "that", "if", "you", "add", "three", "seeds", "with", "document", "ids", "1", "2", "and", "7", ".", "Then", "the", "next", "URL", "that", "is", "found", "during", "the", "crawl", "will", "get", "a", "doc", "id", "of", "8", ".", "Also", "you", "need", "to", "ensure", "to", "add", "seeds", "in", "increasing", "order", "of", "document", "ids", "." ]
4fcddc86414d1831973aff94050af55c7aeff3bc
https://github.com/yasserg/crawler4j/blob/4fcddc86414d1831973aff94050af55c7aeff3bc/crawler4j/src/main/java/edu/uci/ics/crawler4j/crawler/CrawlController.java#L513-L549
16,145
yasserg/crawler4j
crawler4j/src/main/java/edu/uci/ics/crawler4j/crawler/CrawlController.java
CrawlController.addSeenUrl
public void addSeenUrl(String url, int docId) throws UnsupportedEncodingException { String canonicalUrl = URLCanonicalizer.getCanonicalURL(url); if (canonicalUrl == null) { logger.error("Invalid Url: {} (can't cannonicalize it!)", url); } else { try { docIdServer.addUrlAndDocId(canonicalUrl, docId); } catch (RuntimeException e) { if (config.isHaltOnError()) { throw e; } else { logger.error("Could not add seen url: {}", e.getMessage()); } } } }
java
public void addSeenUrl(String url, int docId) throws UnsupportedEncodingException { String canonicalUrl = URLCanonicalizer.getCanonicalURL(url); if (canonicalUrl == null) { logger.error("Invalid Url: {} (can't cannonicalize it!)", url); } else { try { docIdServer.addUrlAndDocId(canonicalUrl, docId); } catch (RuntimeException e) { if (config.isHaltOnError()) { throw e; } else { logger.error("Could not add seen url: {}", e.getMessage()); } } } }
[ "public", "void", "addSeenUrl", "(", "String", "url", ",", "int", "docId", ")", "throws", "UnsupportedEncodingException", "{", "String", "canonicalUrl", "=", "URLCanonicalizer", ".", "getCanonicalURL", "(", "url", ")", ";", "if", "(", "canonicalUrl", "==", "null", ")", "{", "logger", ".", "error", "(", "\"Invalid Url: {} (can't cannonicalize it!)\"", ",", "url", ")", ";", "}", "else", "{", "try", "{", "docIdServer", ".", "addUrlAndDocId", "(", "canonicalUrl", ",", "docId", ")", ";", "}", "catch", "(", "RuntimeException", "e", ")", "{", "if", "(", "config", ".", "isHaltOnError", "(", ")", ")", "{", "throw", "e", ";", "}", "else", "{", "logger", ".", "error", "(", "\"Could not add seen url: {}\"", ",", "e", ".", "getMessage", "(", ")", ")", ";", "}", "}", "}", "}" ]
This function can called to assign a specific document id to a url. This feature is useful when you have had a previous crawl and have stored the Urls and their associated document ids and want to have a new crawl which is aware of the previously seen Urls and won't re-crawl them. Note that if you add three seen Urls with document ids 1,2, and 7. Then the next URL that is found during the crawl will get a doc id of 8. Also you need to ensure to add seen Urls in increasing order of document ids. @param url the URL of the page @param docId the document id that you want to be assigned to this URL. @throws UnsupportedEncodingException
[ "This", "function", "can", "called", "to", "assign", "a", "specific", "document", "id", "to", "a", "url", ".", "This", "feature", "is", "useful", "when", "you", "have", "had", "a", "previous", "crawl", "and", "have", "stored", "the", "Urls", "and", "their", "associated", "document", "ids", "and", "want", "to", "have", "a", "new", "crawl", "which", "is", "aware", "of", "the", "previously", "seen", "Urls", "and", "won", "t", "re", "-", "crawl", "them", "." ]
4fcddc86414d1831973aff94050af55c7aeff3bc
https://github.com/yasserg/crawler4j/blob/4fcddc86414d1831973aff94050af55c7aeff3bc/crawler4j/src/main/java/edu/uci/ics/crawler4j/crawler/CrawlController.java#L568-L583
16,146
yasserg/crawler4j
crawler4j/src/main/java/edu/uci/ics/crawler4j/fetcher/PageFetcher.java
PageFetcher.addNtCredentials
private void addNtCredentials(NtAuthInfo authInfo, Map<AuthScope, Credentials> credentialsMap) { logger.info("NT authentication for: {}", authInfo.getLoginTarget()); try { Credentials credentials = new NTCredentials(authInfo.getUsername(), authInfo.getPassword(), InetAddress.getLocalHost().getHostName(), authInfo.getDomain()); credentialsMap.put(new AuthScope(authInfo.getHost(), authInfo.getPort()), credentials); } catch (UnknownHostException e) { logger.error("Error creating NT credentials", e); } }
java
private void addNtCredentials(NtAuthInfo authInfo, Map<AuthScope, Credentials> credentialsMap) { logger.info("NT authentication for: {}", authInfo.getLoginTarget()); try { Credentials credentials = new NTCredentials(authInfo.getUsername(), authInfo.getPassword(), InetAddress.getLocalHost().getHostName(), authInfo.getDomain()); credentialsMap.put(new AuthScope(authInfo.getHost(), authInfo.getPort()), credentials); } catch (UnknownHostException e) { logger.error("Error creating NT credentials", e); } }
[ "private", "void", "addNtCredentials", "(", "NtAuthInfo", "authInfo", ",", "Map", "<", "AuthScope", ",", "Credentials", ">", "credentialsMap", ")", "{", "logger", ".", "info", "(", "\"NT authentication for: {}\"", ",", "authInfo", ".", "getLoginTarget", "(", ")", ")", ";", "try", "{", "Credentials", "credentials", "=", "new", "NTCredentials", "(", "authInfo", ".", "getUsername", "(", ")", ",", "authInfo", ".", "getPassword", "(", ")", ",", "InetAddress", ".", "getLocalHost", "(", ")", ".", "getHostName", "(", ")", ",", "authInfo", ".", "getDomain", "(", ")", ")", ";", "credentialsMap", ".", "put", "(", "new", "AuthScope", "(", "authInfo", ".", "getHost", "(", ")", ",", "authInfo", ".", "getPort", "(", ")", ")", ",", "credentials", ")", ";", "}", "catch", "(", "UnknownHostException", "e", ")", "{", "logger", ".", "error", "(", "\"Error creating NT credentials\"", ",", "e", ")", ";", "}", "}" ]
Do NT auth for Microsoft AD sites.
[ "Do", "NT", "auth", "for", "Microsoft", "AD", "sites", "." ]
4fcddc86414d1831973aff94050af55c7aeff3bc
https://github.com/yasserg/crawler4j/blob/4fcddc86414d1831973aff94050af55c7aeff3bc/crawler4j/src/main/java/edu/uci/ics/crawler4j/fetcher/PageFetcher.java#L210-L220
16,147
umano/AndroidSlidingUpPanel
library/src/main/java/com/sothree/slidinguppanel/ViewDragHelper.java
ViewDragHelper.create
public static ViewDragHelper create(ViewGroup forParent, Interpolator interpolator, Callback cb) { return new ViewDragHelper(forParent.getContext(), forParent, interpolator, cb); }
java
public static ViewDragHelper create(ViewGroup forParent, Interpolator interpolator, Callback cb) { return new ViewDragHelper(forParent.getContext(), forParent, interpolator, cb); }
[ "public", "static", "ViewDragHelper", "create", "(", "ViewGroup", "forParent", ",", "Interpolator", "interpolator", ",", "Callback", "cb", ")", "{", "return", "new", "ViewDragHelper", "(", "forParent", ".", "getContext", "(", ")", ",", "forParent", ",", "interpolator", ",", "cb", ")", ";", "}" ]
Factory method to create a new ViewDragHelper with the specified interpolator. @param forParent Parent view to monitor @param interpolator interpolator for scroller @param cb Callback to provide information and receive events @return a new ViewDragHelper instance
[ "Factory", "method", "to", "create", "a", "new", "ViewDragHelper", "with", "the", "specified", "interpolator", "." ]
45a460435b07e764138a700328836cafc1ed5c42
https://github.com/umano/AndroidSlidingUpPanel/blob/45a460435b07e764138a700328836cafc1ed5c42/library/src/main/java/com/sothree/slidinguppanel/ViewDragHelper.java#L359-L361
16,148
umano/AndroidSlidingUpPanel
library/src/main/java/com/sothree/slidinguppanel/ViewDragHelper.java
ViewDragHelper.clampMag
private float clampMag(float value, float absMin, float absMax) { final float absValue = Math.abs(value); if (absValue < absMin) return 0; if (absValue > absMax) return value > 0 ? absMax : -absMax; return value; }
java
private float clampMag(float value, float absMin, float absMax) { final float absValue = Math.abs(value); if (absValue < absMin) return 0; if (absValue > absMax) return value > 0 ? absMax : -absMax; return value; }
[ "private", "float", "clampMag", "(", "float", "value", ",", "float", "absMin", ",", "float", "absMax", ")", "{", "final", "float", "absValue", "=", "Math", ".", "abs", "(", "value", ")", ";", "if", "(", "absValue", "<", "absMin", ")", "return", "0", ";", "if", "(", "absValue", ">", "absMax", ")", "return", "value", ">", "0", "?", "absMax", ":", "-", "absMax", ";", "return", "value", ";", "}" ]
Clamp the magnitude of value for absMin and absMax. If the value is below the minimum, it will be clamped to zero. If the value is above the maximum, it will be clamped to the maximum. @param value Value to clamp @param absMin Absolute value of the minimum significant value to return @param absMax Absolute value of the maximum value to return @return The clamped value with the same sign as <code>value</code>
[ "Clamp", "the", "magnitude", "of", "value", "for", "absMin", "and", "absMax", ".", "If", "the", "value", "is", "below", "the", "minimum", "it", "will", "be", "clamped", "to", "zero", ".", "If", "the", "value", "is", "above", "the", "maximum", "it", "will", "be", "clamped", "to", "the", "maximum", "." ]
45a460435b07e764138a700328836cafc1ed5c42
https://github.com/umano/AndroidSlidingUpPanel/blob/45a460435b07e764138a700328836cafc1ed5c42/library/src/main/java/com/sothree/slidinguppanel/ViewDragHelper.java#L697-L702
16,149
umano/AndroidSlidingUpPanel
library/src/main/java/com/sothree/slidinguppanel/ViewDragHelper.java
ViewDragHelper.tryCaptureViewForDrag
boolean tryCaptureViewForDrag(View toCapture, int pointerId) { if (toCapture == mCapturedView && mActivePointerId == pointerId) { // Already done! return true; } if (toCapture != null && mCallback.tryCaptureView(toCapture, pointerId)) { mActivePointerId = pointerId; captureChildView(toCapture, pointerId); return true; } return false; }
java
boolean tryCaptureViewForDrag(View toCapture, int pointerId) { if (toCapture == mCapturedView && mActivePointerId == pointerId) { // Already done! return true; } if (toCapture != null && mCallback.tryCaptureView(toCapture, pointerId)) { mActivePointerId = pointerId; captureChildView(toCapture, pointerId); return true; } return false; }
[ "boolean", "tryCaptureViewForDrag", "(", "View", "toCapture", ",", "int", "pointerId", ")", "{", "if", "(", "toCapture", "==", "mCapturedView", "&&", "mActivePointerId", "==", "pointerId", ")", "{", "// Already done!", "return", "true", ";", "}", "if", "(", "toCapture", "!=", "null", "&&", "mCallback", ".", "tryCaptureView", "(", "toCapture", ",", "pointerId", ")", ")", "{", "mActivePointerId", "=", "pointerId", ";", "captureChildView", "(", "toCapture", ",", "pointerId", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Attempt to capture the view with the given pointer ID. The callback will be involved. This will put us into the "dragging" state. If we've already captured this view with this pointer this method will immediately return true without consulting the callback. @param toCapture View to capture @param pointerId Pointer to capture with @return true if capture was successful
[ "Attempt", "to", "capture", "the", "view", "with", "the", "given", "pointer", "ID", ".", "The", "callback", "will", "be", "involved", ".", "This", "will", "put", "us", "into", "the", "dragging", "state", ".", "If", "we", "ve", "already", "captured", "this", "view", "with", "this", "pointer", "this", "method", "will", "immediately", "return", "true", "without", "consulting", "the", "callback", "." ]
45a460435b07e764138a700328836cafc1ed5c42
https://github.com/umano/AndroidSlidingUpPanel/blob/45a460435b07e764138a700328836cafc1ed5c42/library/src/main/java/com/sothree/slidinguppanel/ViewDragHelper.java#L927-L938
16,150
umano/AndroidSlidingUpPanel
library/src/main/java/com/sothree/slidinguppanel/ViewDragHelper.java
ViewDragHelper.checkTouchSlop
private boolean checkTouchSlop(View child, float dx, float dy) { if (child == null) { return false; } final boolean checkHorizontal = mCallback.getViewHorizontalDragRange(child) > 0; final boolean checkVertical = mCallback.getViewVerticalDragRange(child) > 0; if (checkHorizontal && checkVertical) { return dx * dx + dy * dy > mTouchSlop * mTouchSlop; } else if (checkHorizontal) { return Math.abs(dx) > mTouchSlop; } else if (checkVertical) { return Math.abs(dy) > mTouchSlop; } return false; }
java
private boolean checkTouchSlop(View child, float dx, float dy) { if (child == null) { return false; } final boolean checkHorizontal = mCallback.getViewHorizontalDragRange(child) > 0; final boolean checkVertical = mCallback.getViewVerticalDragRange(child) > 0; if (checkHorizontal && checkVertical) { return dx * dx + dy * dy > mTouchSlop * mTouchSlop; } else if (checkHorizontal) { return Math.abs(dx) > mTouchSlop; } else if (checkVertical) { return Math.abs(dy) > mTouchSlop; } return false; }
[ "private", "boolean", "checkTouchSlop", "(", "View", "child", ",", "float", "dx", ",", "float", "dy", ")", "{", "if", "(", "child", "==", "null", ")", "{", "return", "false", ";", "}", "final", "boolean", "checkHorizontal", "=", "mCallback", ".", "getViewHorizontalDragRange", "(", "child", ")", ">", "0", ";", "final", "boolean", "checkVertical", "=", "mCallback", ".", "getViewVerticalDragRange", "(", "child", ")", ">", "0", ";", "if", "(", "checkHorizontal", "&&", "checkVertical", ")", "{", "return", "dx", "*", "dx", "+", "dy", "*", "dy", ">", "mTouchSlop", "*", "mTouchSlop", ";", "}", "else", "if", "(", "checkHorizontal", ")", "{", "return", "Math", ".", "abs", "(", "dx", ")", ">", "mTouchSlop", ";", "}", "else", "if", "(", "checkVertical", ")", "{", "return", "Math", ".", "abs", "(", "dy", ")", ">", "mTouchSlop", ";", "}", "return", "false", ";", "}" ]
Check if we've crossed a reasonable touch slop for the given child view. If the child cannot be dragged along the horizontal or vertical axis, motion along that axis will not count toward the slop check. @param child Child to check @param dx Motion since initial position along X axis @param dy Motion since initial position along Y axis @return true if the touch slop has been crossed
[ "Check", "if", "we", "ve", "crossed", "a", "reasonable", "touch", "slop", "for", "the", "given", "child", "view", ".", "If", "the", "child", "cannot", "be", "dragged", "along", "the", "horizontal", "or", "vertical", "axis", "motion", "along", "that", "axis", "will", "not", "count", "toward", "the", "slop", "check", "." ]
45a460435b07e764138a700328836cafc1ed5c42
https://github.com/umano/AndroidSlidingUpPanel/blob/45a460435b07e764138a700328836cafc1ed5c42/library/src/main/java/com/sothree/slidinguppanel/ViewDragHelper.java#L1293-L1308
16,151
umano/AndroidSlidingUpPanel
library/src/main/java/com/sothree/slidinguppanel/ViewDragHelper.java
ViewDragHelper.checkTouchSlop
public boolean checkTouchSlop(int directions) { final int count = mInitialMotionX.length; for (int i = 0; i < count; i++) { if (checkTouchSlop(directions, i)) { return true; } } return false; }
java
public boolean checkTouchSlop(int directions) { final int count = mInitialMotionX.length; for (int i = 0; i < count; i++) { if (checkTouchSlop(directions, i)) { return true; } } return false; }
[ "public", "boolean", "checkTouchSlop", "(", "int", "directions", ")", "{", "final", "int", "count", "=", "mInitialMotionX", ".", "length", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "count", ";", "i", "++", ")", "{", "if", "(", "checkTouchSlop", "(", "directions", ",", "i", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Check if any pointer tracked in the current gesture has crossed the required slop threshold. <p>This depends on internal state populated by {@link #shouldInterceptTouchEvent(android.view.MotionEvent)} or {@link #processTouchEvent(android.view.MotionEvent)}. You should only rely on the results of this method after all currently available touch data has been provided to one of these two methods.</p> @param directions Combination of direction flags, see {@link #DIRECTION_HORIZONTAL}, {@link #DIRECTION_VERTICAL}, {@link #DIRECTION_ALL} @return true if the slop threshold has been crossed, false otherwise
[ "Check", "if", "any", "pointer", "tracked", "in", "the", "current", "gesture", "has", "crossed", "the", "required", "slop", "threshold", "." ]
45a460435b07e764138a700328836cafc1ed5c42
https://github.com/umano/AndroidSlidingUpPanel/blob/45a460435b07e764138a700328836cafc1ed5c42/library/src/main/java/com/sothree/slidinguppanel/ViewDragHelper.java#L1324-L1332
16,152
umano/AndroidSlidingUpPanel
library/src/main/java/com/sothree/slidinguppanel/ViewDragHelper.java
ViewDragHelper.checkTouchSlop
public boolean checkTouchSlop(int directions, int pointerId) { if (!isPointerDown(pointerId)) { return false; } final boolean checkHorizontal = (directions & DIRECTION_HORIZONTAL) == DIRECTION_HORIZONTAL; final boolean checkVertical = (directions & DIRECTION_VERTICAL) == DIRECTION_VERTICAL; final float dx = mLastMotionX[pointerId] - mInitialMotionX[pointerId]; final float dy = mLastMotionY[pointerId] - mInitialMotionY[pointerId]; if (checkHorizontal && checkVertical) { return dx * dx + dy * dy > mTouchSlop * mTouchSlop; } else if (checkHorizontal) { return Math.abs(dx) > mTouchSlop; } else if (checkVertical) { return Math.abs(dy) > mTouchSlop; } return false; }
java
public boolean checkTouchSlop(int directions, int pointerId) { if (!isPointerDown(pointerId)) { return false; } final boolean checkHorizontal = (directions & DIRECTION_HORIZONTAL) == DIRECTION_HORIZONTAL; final boolean checkVertical = (directions & DIRECTION_VERTICAL) == DIRECTION_VERTICAL; final float dx = mLastMotionX[pointerId] - mInitialMotionX[pointerId]; final float dy = mLastMotionY[pointerId] - mInitialMotionY[pointerId]; if (checkHorizontal && checkVertical) { return dx * dx + dy * dy > mTouchSlop * mTouchSlop; } else if (checkHorizontal) { return Math.abs(dx) > mTouchSlop; } else if (checkVertical) { return Math.abs(dy) > mTouchSlop; } return false; }
[ "public", "boolean", "checkTouchSlop", "(", "int", "directions", ",", "int", "pointerId", ")", "{", "if", "(", "!", "isPointerDown", "(", "pointerId", ")", ")", "{", "return", "false", ";", "}", "final", "boolean", "checkHorizontal", "=", "(", "directions", "&", "DIRECTION_HORIZONTAL", ")", "==", "DIRECTION_HORIZONTAL", ";", "final", "boolean", "checkVertical", "=", "(", "directions", "&", "DIRECTION_VERTICAL", ")", "==", "DIRECTION_VERTICAL", ";", "final", "float", "dx", "=", "mLastMotionX", "[", "pointerId", "]", "-", "mInitialMotionX", "[", "pointerId", "]", ";", "final", "float", "dy", "=", "mLastMotionY", "[", "pointerId", "]", "-", "mInitialMotionY", "[", "pointerId", "]", ";", "if", "(", "checkHorizontal", "&&", "checkVertical", ")", "{", "return", "dx", "*", "dx", "+", "dy", "*", "dy", ">", "mTouchSlop", "*", "mTouchSlop", ";", "}", "else", "if", "(", "checkHorizontal", ")", "{", "return", "Math", ".", "abs", "(", "dx", ")", ">", "mTouchSlop", ";", "}", "else", "if", "(", "checkVertical", ")", "{", "return", "Math", ".", "abs", "(", "dy", ")", ">", "mTouchSlop", ";", "}", "return", "false", ";", "}" ]
Check if the specified pointer tracked in the current gesture has crossed the required slop threshold. <p>This depends on internal state populated by {@link #shouldInterceptTouchEvent(android.view.MotionEvent)} or {@link #processTouchEvent(android.view.MotionEvent)}. You should only rely on the results of this method after all currently available touch data has been provided to one of these two methods.</p> @param directions Combination of direction flags, see {@link #DIRECTION_HORIZONTAL}, {@link #DIRECTION_VERTICAL}, {@link #DIRECTION_ALL} @param pointerId ID of the pointer to slop check as specified by MotionEvent @return true if the slop threshold has been crossed, false otherwise
[ "Check", "if", "the", "specified", "pointer", "tracked", "in", "the", "current", "gesture", "has", "crossed", "the", "required", "slop", "threshold", "." ]
45a460435b07e764138a700328836cafc1ed5c42
https://github.com/umano/AndroidSlidingUpPanel/blob/45a460435b07e764138a700328836cafc1ed5c42/library/src/main/java/com/sothree/slidinguppanel/ViewDragHelper.java#L1349-L1368
16,153
umano/AndroidSlidingUpPanel
library/src/main/java/com/sothree/slidinguppanel/ViewDragHelper.java
ViewDragHelper.isViewUnder
public boolean isViewUnder(View view, int x, int y) { if (view == null) { return false; } return x >= view.getLeft() && x < view.getRight() && y >= view.getTop() && y < view.getBottom(); }
java
public boolean isViewUnder(View view, int x, int y) { if (view == null) { return false; } return x >= view.getLeft() && x < view.getRight() && y >= view.getTop() && y < view.getBottom(); }
[ "public", "boolean", "isViewUnder", "(", "View", "view", ",", "int", "x", ",", "int", "y", ")", "{", "if", "(", "view", "==", "null", ")", "{", "return", "false", ";", "}", "return", "x", ">=", "view", ".", "getLeft", "(", ")", "&&", "x", "<", "view", ".", "getRight", "(", ")", "&&", "y", ">=", "view", ".", "getTop", "(", ")", "&&", "y", "<", "view", ".", "getBottom", "(", ")", ";", "}" ]
Determine if the supplied view is under the given point in the parent view's coordinate system. @param view Child view of the parent to hit test @param x X position to test in the parent's coordinate system @param y Y position to test in the parent's coordinate system @return true if the supplied view is under the given point, false otherwise
[ "Determine", "if", "the", "supplied", "view", "is", "under", "the", "given", "point", "in", "the", "parent", "view", "s", "coordinate", "system", "." ]
45a460435b07e764138a700328836cafc1ed5c42
https://github.com/umano/AndroidSlidingUpPanel/blob/45a460435b07e764138a700328836cafc1ed5c42/library/src/main/java/com/sothree/slidinguppanel/ViewDragHelper.java#L1462-L1470
16,154
umano/AndroidSlidingUpPanel
library/src/main/java/com/sothree/slidinguppanel/ScrollableViewHelper.java
ScrollableViewHelper.getScrollableViewScrollPosition
public int getScrollableViewScrollPosition(View scrollableView, boolean isSlidingUp) { if (scrollableView == null) return 0; if (scrollableView instanceof ScrollView) { if (isSlidingUp) { return scrollableView.getScrollY(); } else { ScrollView sv = ((ScrollView) scrollableView); View child = sv.getChildAt(0); return (child.getBottom() - (sv.getHeight() + sv.getScrollY())); } } else if (scrollableView instanceof ListView && ((ListView) scrollableView).getChildCount() > 0) { ListView lv = ((ListView) scrollableView); if (lv.getAdapter() == null) return 0; if (isSlidingUp) { View firstChild = lv.getChildAt(0); // Approximate the scroll position based on the top child and the first visible item return lv.getFirstVisiblePosition() * firstChild.getHeight() - firstChild.getTop(); } else { View lastChild = lv.getChildAt(lv.getChildCount() - 1); // Approximate the scroll position based on the bottom child and the last visible item return (lv.getAdapter().getCount() - lv.getLastVisiblePosition() - 1) * lastChild.getHeight() + lastChild.getBottom() - lv.getBottom(); } } else if (scrollableView instanceof RecyclerView && ((RecyclerView) scrollableView).getChildCount() > 0) { RecyclerView rv = ((RecyclerView) scrollableView); RecyclerView.LayoutManager lm = rv.getLayoutManager(); if (rv.getAdapter() == null) return 0; if (isSlidingUp) { View firstChild = rv.getChildAt(0); // Approximate the scroll position based on the top child and the first visible item return rv.getChildLayoutPosition(firstChild) * lm.getDecoratedMeasuredHeight(firstChild) - lm.getDecoratedTop(firstChild); } else { View lastChild = rv.getChildAt(rv.getChildCount() - 1); // Approximate the scroll position based on the bottom child and the last visible item return (rv.getAdapter().getItemCount() - 1) * lm.getDecoratedMeasuredHeight(lastChild) + lm.getDecoratedBottom(lastChild) - rv.getBottom(); } } else { return 0; } }
java
public int getScrollableViewScrollPosition(View scrollableView, boolean isSlidingUp) { if (scrollableView == null) return 0; if (scrollableView instanceof ScrollView) { if (isSlidingUp) { return scrollableView.getScrollY(); } else { ScrollView sv = ((ScrollView) scrollableView); View child = sv.getChildAt(0); return (child.getBottom() - (sv.getHeight() + sv.getScrollY())); } } else if (scrollableView instanceof ListView && ((ListView) scrollableView).getChildCount() > 0) { ListView lv = ((ListView) scrollableView); if (lv.getAdapter() == null) return 0; if (isSlidingUp) { View firstChild = lv.getChildAt(0); // Approximate the scroll position based on the top child and the first visible item return lv.getFirstVisiblePosition() * firstChild.getHeight() - firstChild.getTop(); } else { View lastChild = lv.getChildAt(lv.getChildCount() - 1); // Approximate the scroll position based on the bottom child and the last visible item return (lv.getAdapter().getCount() - lv.getLastVisiblePosition() - 1) * lastChild.getHeight() + lastChild.getBottom() - lv.getBottom(); } } else if (scrollableView instanceof RecyclerView && ((RecyclerView) scrollableView).getChildCount() > 0) { RecyclerView rv = ((RecyclerView) scrollableView); RecyclerView.LayoutManager lm = rv.getLayoutManager(); if (rv.getAdapter() == null) return 0; if (isSlidingUp) { View firstChild = rv.getChildAt(0); // Approximate the scroll position based on the top child and the first visible item return rv.getChildLayoutPosition(firstChild) * lm.getDecoratedMeasuredHeight(firstChild) - lm.getDecoratedTop(firstChild); } else { View lastChild = rv.getChildAt(rv.getChildCount() - 1); // Approximate the scroll position based on the bottom child and the last visible item return (rv.getAdapter().getItemCount() - 1) * lm.getDecoratedMeasuredHeight(lastChild) + lm.getDecoratedBottom(lastChild) - rv.getBottom(); } } else { return 0; } }
[ "public", "int", "getScrollableViewScrollPosition", "(", "View", "scrollableView", ",", "boolean", "isSlidingUp", ")", "{", "if", "(", "scrollableView", "==", "null", ")", "return", "0", ";", "if", "(", "scrollableView", "instanceof", "ScrollView", ")", "{", "if", "(", "isSlidingUp", ")", "{", "return", "scrollableView", ".", "getScrollY", "(", ")", ";", "}", "else", "{", "ScrollView", "sv", "=", "(", "(", "ScrollView", ")", "scrollableView", ")", ";", "View", "child", "=", "sv", ".", "getChildAt", "(", "0", ")", ";", "return", "(", "child", ".", "getBottom", "(", ")", "-", "(", "sv", ".", "getHeight", "(", ")", "+", "sv", ".", "getScrollY", "(", ")", ")", ")", ";", "}", "}", "else", "if", "(", "scrollableView", "instanceof", "ListView", "&&", "(", "(", "ListView", ")", "scrollableView", ")", ".", "getChildCount", "(", ")", ">", "0", ")", "{", "ListView", "lv", "=", "(", "(", "ListView", ")", "scrollableView", ")", ";", "if", "(", "lv", ".", "getAdapter", "(", ")", "==", "null", ")", "return", "0", ";", "if", "(", "isSlidingUp", ")", "{", "View", "firstChild", "=", "lv", ".", "getChildAt", "(", "0", ")", ";", "// Approximate the scroll position based on the top child and the first visible item", "return", "lv", ".", "getFirstVisiblePosition", "(", ")", "*", "firstChild", ".", "getHeight", "(", ")", "-", "firstChild", ".", "getTop", "(", ")", ";", "}", "else", "{", "View", "lastChild", "=", "lv", ".", "getChildAt", "(", "lv", ".", "getChildCount", "(", ")", "-", "1", ")", ";", "// Approximate the scroll position based on the bottom child and the last visible item", "return", "(", "lv", ".", "getAdapter", "(", ")", ".", "getCount", "(", ")", "-", "lv", ".", "getLastVisiblePosition", "(", ")", "-", "1", ")", "*", "lastChild", ".", "getHeight", "(", ")", "+", "lastChild", ".", "getBottom", "(", ")", "-", "lv", ".", "getBottom", "(", ")", ";", "}", "}", "else", "if", "(", "scrollableView", "instanceof", "RecyclerView", "&&", "(", "(", "RecyclerView", ")", "scrollableView", ")", ".", "getChildCount", "(", ")", ">", "0", ")", "{", "RecyclerView", "rv", "=", "(", "(", "RecyclerView", ")", "scrollableView", ")", ";", "RecyclerView", ".", "LayoutManager", "lm", "=", "rv", ".", "getLayoutManager", "(", ")", ";", "if", "(", "rv", ".", "getAdapter", "(", ")", "==", "null", ")", "return", "0", ";", "if", "(", "isSlidingUp", ")", "{", "View", "firstChild", "=", "rv", ".", "getChildAt", "(", "0", ")", ";", "// Approximate the scroll position based on the top child and the first visible item", "return", "rv", ".", "getChildLayoutPosition", "(", "firstChild", ")", "*", "lm", ".", "getDecoratedMeasuredHeight", "(", "firstChild", ")", "-", "lm", ".", "getDecoratedTop", "(", "firstChild", ")", ";", "}", "else", "{", "View", "lastChild", "=", "rv", ".", "getChildAt", "(", "rv", ".", "getChildCount", "(", ")", "-", "1", ")", ";", "// Approximate the scroll position based on the bottom child and the last visible item", "return", "(", "rv", ".", "getAdapter", "(", ")", ".", "getItemCount", "(", ")", "-", "1", ")", "*", "lm", ".", "getDecoratedMeasuredHeight", "(", "lastChild", ")", "+", "lm", ".", "getDecoratedBottom", "(", "lastChild", ")", "-", "rv", ".", "getBottom", "(", ")", ";", "}", "}", "else", "{", "return", "0", ";", "}", "}" ]
Returns the current scroll position of the scrollable view. If this method returns zero or less, it means at the scrollable view is in a position such as the panel should handle scrolling. If the method returns anything above zero, then the panel will let the scrollable view handle the scrolling @param scrollableView the scrollable view @param isSlidingUp whether or not the panel is sliding up or down @return the scroll position
[ "Returns", "the", "current", "scroll", "position", "of", "the", "scrollable", "view", ".", "If", "this", "method", "returns", "zero", "or", "less", "it", "means", "at", "the", "scrollable", "view", "is", "in", "a", "position", "such", "as", "the", "panel", "should", "handle", "scrolling", ".", "If", "the", "method", "returns", "anything", "above", "zero", "then", "the", "panel", "will", "let", "the", "scrollable", "view", "handle", "the", "scrolling" ]
45a460435b07e764138a700328836cafc1ed5c42
https://github.com/umano/AndroidSlidingUpPanel/blob/45a460435b07e764138a700328836cafc1ed5c42/library/src/main/java/com/sothree/slidinguppanel/ScrollableViewHelper.java#L24-L62
16,155
umano/AndroidSlidingUpPanel
library/src/main/java/com/sothree/slidinguppanel/SlidingUpPanelLayout.java
SlidingUpPanelLayout.onFinishInflate
@Override protected void onFinishInflate() { super.onFinishInflate(); if (mDragViewResId != -1) { setDragView(findViewById(mDragViewResId)); } if (mScrollableViewResId != -1) { setScrollableView(findViewById(mScrollableViewResId)); } }
java
@Override protected void onFinishInflate() { super.onFinishInflate(); if (mDragViewResId != -1) { setDragView(findViewById(mDragViewResId)); } if (mScrollableViewResId != -1) { setScrollableView(findViewById(mScrollableViewResId)); } }
[ "@", "Override", "protected", "void", "onFinishInflate", "(", ")", "{", "super", ".", "onFinishInflate", "(", ")", ";", "if", "(", "mDragViewResId", "!=", "-", "1", ")", "{", "setDragView", "(", "findViewById", "(", "mDragViewResId", ")", ")", ";", "}", "if", "(", "mScrollableViewResId", "!=", "-", "1", ")", "{", "setScrollableView", "(", "findViewById", "(", "mScrollableViewResId", ")", ")", ";", "}", "}" ]
Set the Drag View after the view is inflated
[ "Set", "the", "Drag", "View", "after", "the", "view", "is", "inflated" ]
45a460435b07e764138a700328836cafc1ed5c42
https://github.com/umano/AndroidSlidingUpPanel/blob/45a460435b07e764138a700328836cafc1ed5c42/library/src/main/java/com/sothree/slidinguppanel/SlidingUpPanelLayout.java#L353-L362
16,156
umano/AndroidSlidingUpPanel
library/src/main/java/com/sothree/slidinguppanel/SlidingUpPanelLayout.java
SlidingUpPanelLayout.setPanelHeight
public void setPanelHeight(int val) { if (getPanelHeight() == val) { return; } mPanelHeight = val; if (!mFirstLayout) { requestLayout(); } if (getPanelState() == PanelState.COLLAPSED) { smoothToBottom(); invalidate(); return; } }
java
public void setPanelHeight(int val) { if (getPanelHeight() == val) { return; } mPanelHeight = val; if (!mFirstLayout) { requestLayout(); } if (getPanelState() == PanelState.COLLAPSED) { smoothToBottom(); invalidate(); return; } }
[ "public", "void", "setPanelHeight", "(", "int", "val", ")", "{", "if", "(", "getPanelHeight", "(", ")", "==", "val", ")", "{", "return", ";", "}", "mPanelHeight", "=", "val", ";", "if", "(", "!", "mFirstLayout", ")", "{", "requestLayout", "(", ")", ";", "}", "if", "(", "getPanelState", "(", ")", "==", "PanelState", ".", "COLLAPSED", ")", "{", "smoothToBottom", "(", ")", ";", "invalidate", "(", ")", ";", "return", ";", "}", "}" ]
Set the collapsed panel height in pixels @param val A height in pixels
[ "Set", "the", "collapsed", "panel", "height", "in", "pixels" ]
45a460435b07e764138a700328836cafc1ed5c42
https://github.com/umano/AndroidSlidingUpPanel/blob/45a460435b07e764138a700328836cafc1ed5c42/library/src/main/java/com/sothree/slidinguppanel/SlidingUpPanelLayout.java#L410-L425
16,157
umano/AndroidSlidingUpPanel
library/src/main/java/com/sothree/slidinguppanel/SlidingUpPanelLayout.java
SlidingUpPanelLayout.setPanelState
public void setPanelState(PanelState state) { // Abort any running animation, to allow state change if(mDragHelper.getViewDragState() == ViewDragHelper.STATE_SETTLING){ Log.d(TAG, "View is settling. Aborting animation."); mDragHelper.abort(); } if (state == null || state == PanelState.DRAGGING) { throw new IllegalArgumentException("Panel state cannot be null or DRAGGING."); } if (!isEnabled() || (!mFirstLayout && mSlideableView == null) || state == mSlideState || mSlideState == PanelState.DRAGGING) return; if (mFirstLayout) { setPanelStateInternal(state); } else { if (mSlideState == PanelState.HIDDEN) { mSlideableView.setVisibility(View.VISIBLE); requestLayout(); } switch (state) { case ANCHORED: smoothSlideTo(mAnchorPoint, 0); break; case COLLAPSED: smoothSlideTo(0, 0); break; case EXPANDED: smoothSlideTo(1.0f, 0); break; case HIDDEN: int newTop = computePanelTopPosition(0.0f) + (mIsSlidingUp ? +mPanelHeight : -mPanelHeight); smoothSlideTo(computeSlideOffset(newTop), 0); break; } } }
java
public void setPanelState(PanelState state) { // Abort any running animation, to allow state change if(mDragHelper.getViewDragState() == ViewDragHelper.STATE_SETTLING){ Log.d(TAG, "View is settling. Aborting animation."); mDragHelper.abort(); } if (state == null || state == PanelState.DRAGGING) { throw new IllegalArgumentException("Panel state cannot be null or DRAGGING."); } if (!isEnabled() || (!mFirstLayout && mSlideableView == null) || state == mSlideState || mSlideState == PanelState.DRAGGING) return; if (mFirstLayout) { setPanelStateInternal(state); } else { if (mSlideState == PanelState.HIDDEN) { mSlideableView.setVisibility(View.VISIBLE); requestLayout(); } switch (state) { case ANCHORED: smoothSlideTo(mAnchorPoint, 0); break; case COLLAPSED: smoothSlideTo(0, 0); break; case EXPANDED: smoothSlideTo(1.0f, 0); break; case HIDDEN: int newTop = computePanelTopPosition(0.0f) + (mIsSlidingUp ? +mPanelHeight : -mPanelHeight); smoothSlideTo(computeSlideOffset(newTop), 0); break; } } }
[ "public", "void", "setPanelState", "(", "PanelState", "state", ")", "{", "// Abort any running animation, to allow state change", "if", "(", "mDragHelper", ".", "getViewDragState", "(", ")", "==", "ViewDragHelper", ".", "STATE_SETTLING", ")", "{", "Log", ".", "d", "(", "TAG", ",", "\"View is settling. Aborting animation.\"", ")", ";", "mDragHelper", ".", "abort", "(", ")", ";", "}", "if", "(", "state", "==", "null", "||", "state", "==", "PanelState", ".", "DRAGGING", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Panel state cannot be null or DRAGGING.\"", ")", ";", "}", "if", "(", "!", "isEnabled", "(", ")", "||", "(", "!", "mFirstLayout", "&&", "mSlideableView", "==", "null", ")", "||", "state", "==", "mSlideState", "||", "mSlideState", "==", "PanelState", ".", "DRAGGING", ")", "return", ";", "if", "(", "mFirstLayout", ")", "{", "setPanelStateInternal", "(", "state", ")", ";", "}", "else", "{", "if", "(", "mSlideState", "==", "PanelState", ".", "HIDDEN", ")", "{", "mSlideableView", ".", "setVisibility", "(", "View", ".", "VISIBLE", ")", ";", "requestLayout", "(", ")", ";", "}", "switch", "(", "state", ")", "{", "case", "ANCHORED", ":", "smoothSlideTo", "(", "mAnchorPoint", ",", "0", ")", ";", "break", ";", "case", "COLLAPSED", ":", "smoothSlideTo", "(", "0", ",", "0", ")", ";", "break", ";", "case", "EXPANDED", ":", "smoothSlideTo", "(", "1.0f", ",", "0", ")", ";", "break", ";", "case", "HIDDEN", ":", "int", "newTop", "=", "computePanelTopPosition", "(", "0.0f", ")", "+", "(", "mIsSlidingUp", "?", "+", "mPanelHeight", ":", "-", "mPanelHeight", ")", ";", "smoothSlideTo", "(", "computeSlideOffset", "(", "newTop", ")", ",", "0", ")", ";", "break", ";", "}", "}", "}" ]
Change panel state to the given state with @param state - new panel state
[ "Change", "panel", "state", "to", "the", "given", "state", "with" ]
45a460435b07e764138a700328836cafc1ed5c42
https://github.com/umano/AndroidSlidingUpPanel/blob/45a460435b07e764138a700328836cafc1ed5c42/library/src/main/java/com/sothree/slidinguppanel/SlidingUpPanelLayout.java#L1099-L1138
16,158
dreamhead/moco
moco-core/src/main/java/com/github/dreamhead/moco/matcher/XmlRequestMatcher.java
XmlRequestMatcher.trimNode
private void trimNode(final Node node) { NodeList children = node.getChildNodes(); for (int i = children.getLength() - 1; i >= 0; i--) { trimChild(node, children.item(i)); } }
java
private void trimNode(final Node node) { NodeList children = node.getChildNodes(); for (int i = children.getLength() - 1; i >= 0; i--) { trimChild(node, children.item(i)); } }
[ "private", "void", "trimNode", "(", "final", "Node", "node", ")", "{", "NodeList", "children", "=", "node", ".", "getChildNodes", "(", ")", ";", "for", "(", "int", "i", "=", "children", ".", "getLength", "(", ")", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "trimChild", "(", "node", ",", "children", ".", "item", "(", "i", ")", ")", ";", "}", "}" ]
Whitespace will be kept by DOM parser.
[ "Whitespace", "will", "be", "kept", "by", "DOM", "parser", "." ]
83b0fbb9c505e327de6720cff55e7b18078f2aa9
https://github.com/dreamhead/moco/blob/83b0fbb9c505e327de6720cff55e7b18078f2aa9/moco-core/src/main/java/com/github/dreamhead/moco/matcher/XmlRequestMatcher.java#L93-L98
16,159
liyiorg/weixin-popular
src/main/java/weixin/popular/util/StreamUtils.java
StreamUtils.copy
public static int copy(InputStream in, OutputStream out) throws IOException { int byteCount = 0; byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead = -1; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); byteCount += bytesRead; } out.flush(); return byteCount; }
java
public static int copy(InputStream in, OutputStream out) throws IOException { int byteCount = 0; byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead = -1; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); byteCount += bytesRead; } out.flush(); return byteCount; }
[ "public", "static", "int", "copy", "(", "InputStream", "in", ",", "OutputStream", "out", ")", "throws", "IOException", "{", "int", "byteCount", "=", "0", ";", "byte", "[", "]", "buffer", "=", "new", "byte", "[", "BUFFER_SIZE", "]", ";", "int", "bytesRead", "=", "-", "1", ";", "while", "(", "(", "bytesRead", "=", "in", ".", "read", "(", "buffer", ")", ")", "!=", "-", "1", ")", "{", "out", ".", "write", "(", "buffer", ",", "0", ",", "bytesRead", ")", ";", "byteCount", "+=", "bytesRead", ";", "}", "out", ".", "flush", "(", ")", ";", "return", "byteCount", ";", "}" ]
Copy the contents of the given InputStream to the given OutputStream. Leaves both streams open when done. @param in the InputStream to copy from @param out the OutputStream to copy to @return the number of bytes copied @throws IOException in case of I/O errors
[ "Copy", "the", "contents", "of", "the", "given", "InputStream", "to", "the", "given", "OutputStream", ".", "Leaves", "both", "streams", "open", "when", "done", "." ]
c64255292d41463bdb671938feaabf42a335d82c
https://github.com/liyiorg/weixin-popular/blob/c64255292d41463bdb671938feaabf42a335d82c/src/main/java/weixin/popular/util/StreamUtils.java#L83-L93
16,160
liyiorg/weixin-popular
src/main/java/weixin/popular/util/XMLConverUtil.java
XMLConverUtil.convertToXML
public static String convertToXML(Object object) { try { if (!JAXB_CONTEXT_MAP.containsKey(object.getClass())) { JAXB_CONTEXT_MAP.put(object.getClass(), JAXBContext.newInstance(object.getClass())); } Marshaller marshaller = JAXB_CONTEXT_MAP.get(object.getClass()).createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // 设置CDATA输出字符 marshaller.setProperty(CharacterEscapeHandler.class.getName(), new CharacterEscapeHandler() { public void escape(char[] ac, int i, int j, boolean flag, Writer writer) throws IOException { writer.write(ac, i, j); } }); StringWriter stringWriter = new StringWriter(); marshaller.marshal(object, stringWriter); return stringWriter.getBuffer().toString(); } catch (Exception e) { logger.error("", e); } return null; }
java
public static String convertToXML(Object object) { try { if (!JAXB_CONTEXT_MAP.containsKey(object.getClass())) { JAXB_CONTEXT_MAP.put(object.getClass(), JAXBContext.newInstance(object.getClass())); } Marshaller marshaller = JAXB_CONTEXT_MAP.get(object.getClass()).createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // 设置CDATA输出字符 marshaller.setProperty(CharacterEscapeHandler.class.getName(), new CharacterEscapeHandler() { public void escape(char[] ac, int i, int j, boolean flag, Writer writer) throws IOException { writer.write(ac, i, j); } }); StringWriter stringWriter = new StringWriter(); marshaller.marshal(object, stringWriter); return stringWriter.getBuffer().toString(); } catch (Exception e) { logger.error("", e); } return null; }
[ "public", "static", "String", "convertToXML", "(", "Object", "object", ")", "{", "try", "{", "if", "(", "!", "JAXB_CONTEXT_MAP", ".", "containsKey", "(", "object", ".", "getClass", "(", ")", ")", ")", "{", "JAXB_CONTEXT_MAP", ".", "put", "(", "object", ".", "getClass", "(", ")", ",", "JAXBContext", ".", "newInstance", "(", "object", ".", "getClass", "(", ")", ")", ")", ";", "}", "Marshaller", "marshaller", "=", "JAXB_CONTEXT_MAP", ".", "get", "(", "object", ".", "getClass", "(", ")", ")", ".", "createMarshaller", "(", ")", ";", "marshaller", ".", "setProperty", "(", "Marshaller", ".", "JAXB_FORMATTED_OUTPUT", ",", "true", ")", ";", "// 设置CDATA输出字符\r", "marshaller", ".", "setProperty", "(", "CharacterEscapeHandler", ".", "class", ".", "getName", "(", ")", ",", "new", "CharacterEscapeHandler", "(", ")", "{", "public", "void", "escape", "(", "char", "[", "]", "ac", ",", "int", "i", ",", "int", "j", ",", "boolean", "flag", ",", "Writer", "writer", ")", "throws", "IOException", "{", "writer", ".", "write", "(", "ac", ",", "i", ",", "j", ")", ";", "}", "}", ")", ";", "StringWriter", "stringWriter", "=", "new", "StringWriter", "(", ")", ";", "marshaller", ".", "marshal", "(", "object", ",", "stringWriter", ")", ";", "return", "stringWriter", ".", "getBuffer", "(", ")", ".", "toString", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "logger", ".", "error", "(", "\"\"", ",", "e", ")", ";", "}", "return", "null", ";", "}" ]
Object to XML @param object object @return xml
[ "Object", "to", "XML" ]
c64255292d41463bdb671938feaabf42a335d82c
https://github.com/liyiorg/weixin-popular/blob/c64255292d41463bdb671938feaabf42a335d82c/src/main/java/weixin/popular/util/XMLConverUtil.java#L141-L161
16,161
Netflix/concurrency-limits
concurrency-limits-grpc/src/main/java/com/netflix/concurrency/limits/grpc/server/GrpcServerLimiterBuilder.java
GrpcServerLimiterBuilder.partitionByHeader
public GrpcServerLimiterBuilder partitionByHeader(Metadata.Key<String> header) { return partitionResolver(context -> context.getHeaders().get(header)); }
java
public GrpcServerLimiterBuilder partitionByHeader(Metadata.Key<String> header) { return partitionResolver(context -> context.getHeaders().get(header)); }
[ "public", "GrpcServerLimiterBuilder", "partitionByHeader", "(", "Metadata", ".", "Key", "<", "String", ">", "header", ")", "{", "return", "partitionResolver", "(", "context", "->", "context", ".", "getHeaders", "(", ")", ".", "get", "(", "header", ")", ")", ";", "}" ]
Partition the limit by a request header. @return Chainable builder
[ "Partition", "the", "limit", "by", "a", "request", "header", "." ]
5ae2be4fea9848af6f63c7b5632af30c494e7373
https://github.com/Netflix/concurrency-limits/blob/5ae2be4fea9848af6f63c7b5632af30c494e7373/concurrency-limits-grpc/src/main/java/com/netflix/concurrency/limits/grpc/server/GrpcServerLimiterBuilder.java#L37-L39
16,162
Netflix/concurrency-limits
concurrency-limits-grpc/src/main/java/com/netflix/concurrency/limits/grpc/server/GrpcServerLimiterBuilder.java
GrpcServerLimiterBuilder.partitionByAttribute
public GrpcServerLimiterBuilder partitionByAttribute(Attributes.Key<String> attribute) { return partitionResolver(context -> context.getCall().getAttributes().get(attribute)); }
java
public GrpcServerLimiterBuilder partitionByAttribute(Attributes.Key<String> attribute) { return partitionResolver(context -> context.getCall().getAttributes().get(attribute)); }
[ "public", "GrpcServerLimiterBuilder", "partitionByAttribute", "(", "Attributes", ".", "Key", "<", "String", ">", "attribute", ")", "{", "return", "partitionResolver", "(", "context", "->", "context", ".", "getCall", "(", ")", ".", "getAttributes", "(", ")", ".", "get", "(", "attribute", ")", ")", ";", "}" ]
Partition the limit by a request attribute. @return Chainable builder
[ "Partition", "the", "limit", "by", "a", "request", "attribute", "." ]
5ae2be4fea9848af6f63c7b5632af30c494e7373
https://github.com/Netflix/concurrency-limits/blob/5ae2be4fea9848af6f63c7b5632af30c494e7373/concurrency-limits-grpc/src/main/java/com/netflix/concurrency/limits/grpc/server/GrpcServerLimiterBuilder.java#L45-L47
16,163
Netflix/concurrency-limits
concurrency-limits-servlet/src/main/java/com/netflix/concurrency/limits/servlet/ServletLimiterBuilder.java
ServletLimiterBuilder.partitionByHeader
public ServletLimiterBuilder partitionByHeader(String name) { return partitionResolver(request -> Optional.ofNullable(request.getHeader(name)).orElse(null)); }
java
public ServletLimiterBuilder partitionByHeader(String name) { return partitionResolver(request -> Optional.ofNullable(request.getHeader(name)).orElse(null)); }
[ "public", "ServletLimiterBuilder", "partitionByHeader", "(", "String", "name", ")", "{", "return", "partitionResolver", "(", "request", "->", "Optional", ".", "ofNullable", "(", "request", ".", "getHeader", "(", "name", ")", ")", ".", "orElse", "(", "null", ")", ")", ";", "}" ]
Partition the limit by header @return Chainable builder
[ "Partition", "the", "limit", "by", "header" ]
5ae2be4fea9848af6f63c7b5632af30c494e7373
https://github.com/Netflix/concurrency-limits/blob/5ae2be4fea9848af6f63c7b5632af30c494e7373/concurrency-limits-servlet/src/main/java/com/netflix/concurrency/limits/servlet/ServletLimiterBuilder.java#L36-L38
16,164
Netflix/concurrency-limits
concurrency-limits-servlet/src/main/java/com/netflix/concurrency/limits/servlet/ServletLimiterBuilder.java
ServletLimiterBuilder.partitionByAttribute
public ServletLimiterBuilder partitionByAttribute(String name) { return partitionResolver(request -> Optional.ofNullable(request.getAttribute(name)).map(Object::toString).orElse(null)); }
java
public ServletLimiterBuilder partitionByAttribute(String name) { return partitionResolver(request -> Optional.ofNullable(request.getAttribute(name)).map(Object::toString).orElse(null)); }
[ "public", "ServletLimiterBuilder", "partitionByAttribute", "(", "String", "name", ")", "{", "return", "partitionResolver", "(", "request", "->", "Optional", ".", "ofNullable", "(", "request", ".", "getAttribute", "(", "name", ")", ")", ".", "map", "(", "Object", "::", "toString", ")", ".", "orElse", "(", "null", ")", ")", ";", "}" ]
Partition the limit by request attribute @return Chainable builder
[ "Partition", "the", "limit", "by", "request", "attribute" ]
5ae2be4fea9848af6f63c7b5632af30c494e7373
https://github.com/Netflix/concurrency-limits/blob/5ae2be4fea9848af6f63c7b5632af30c494e7373/concurrency-limits-servlet/src/main/java/com/netflix/concurrency/limits/servlet/ServletLimiterBuilder.java#L54-L56
16,165
Netflix/concurrency-limits
concurrency-limits-servlet/src/main/java/com/netflix/concurrency/limits/servlet/ServletLimiterBuilder.java
ServletLimiterBuilder.partitionByParameter
public ServletLimiterBuilder partitionByParameter(String name) { return partitionResolver(request -> Optional.ofNullable(request.getParameter(name)).orElse(null)); }
java
public ServletLimiterBuilder partitionByParameter(String name) { return partitionResolver(request -> Optional.ofNullable(request.getParameter(name)).orElse(null)); }
[ "public", "ServletLimiterBuilder", "partitionByParameter", "(", "String", "name", ")", "{", "return", "partitionResolver", "(", "request", "->", "Optional", ".", "ofNullable", "(", "request", ".", "getParameter", "(", "name", ")", ")", ".", "orElse", "(", "null", ")", ")", ";", "}" ]
Partition the limit by request parameter @return Chainable builder
[ "Partition", "the", "limit", "by", "request", "parameter" ]
5ae2be4fea9848af6f63c7b5632af30c494e7373
https://github.com/Netflix/concurrency-limits/blob/5ae2be4fea9848af6f63c7b5632af30c494e7373/concurrency-limits-servlet/src/main/java/com/netflix/concurrency/limits/servlet/ServletLimiterBuilder.java#L62-L64
16,166
Netflix/concurrency-limits
concurrency-limits-core/src/main/java/com/netflix/concurrency/limits/limiter/BlockingLimiter.java
BlockingLimiter.wrap
public static <ContextT> BlockingLimiter<ContextT> wrap(Limiter<ContextT> delegate, Duration timeout) { Preconditions.checkArgument(timeout.compareTo(MAX_TIMEOUT) < 0, "Timeout cannot be greater than " + MAX_TIMEOUT); return new BlockingLimiter<>(delegate, timeout); }
java
public static <ContextT> BlockingLimiter<ContextT> wrap(Limiter<ContextT> delegate, Duration timeout) { Preconditions.checkArgument(timeout.compareTo(MAX_TIMEOUT) < 0, "Timeout cannot be greater than " + MAX_TIMEOUT); return new BlockingLimiter<>(delegate, timeout); }
[ "public", "static", "<", "ContextT", ">", "BlockingLimiter", "<", "ContextT", ">", "wrap", "(", "Limiter", "<", "ContextT", ">", "delegate", ",", "Duration", "timeout", ")", "{", "Preconditions", ".", "checkArgument", "(", "timeout", ".", "compareTo", "(", "MAX_TIMEOUT", ")", "<", "0", ",", "\"Timeout cannot be greater than \"", "+", "MAX_TIMEOUT", ")", ";", "return", "new", "BlockingLimiter", "<>", "(", "delegate", ",", "timeout", ")", ";", "}" ]
Wrap a limiter such that acquire will block up to a provided timeout if the limit was reached instead of return an empty listener immediately @param delegate Non-blocking limiter to wrap @param timeout Max amount of time to wait for the wait for the limit to be released. Cannot exceed {@link BlockingLimiter#MAX_TIMEOUT} @return Wrapped limiter
[ "Wrap", "a", "limiter", "such", "that", "acquire", "will", "block", "up", "to", "a", "provided", "timeout", "if", "the", "limit", "was", "reached", "instead", "of", "return", "an", "empty", "listener", "immediately" ]
5ae2be4fea9848af6f63c7b5632af30c494e7373
https://github.com/Netflix/concurrency-limits/blob/5ae2be4fea9848af6f63c7b5632af30c494e7373/concurrency-limits-core/src/main/java/com/netflix/concurrency/limits/limiter/BlockingLimiter.java#L53-L56
16,167
SonarSource/sonarqube
server/sonar-server-common/src/main/java/org/sonar/server/qualitygate/QualityGateFinder.java
QualityGateFinder.getQualityGate
public Optional<QualityGateData> getQualityGate(DbSession dbSession, OrganizationDto organization, ComponentDto component) { Optional<QualityGateData> res = dbClient.projectQgateAssociationDao().selectQGateIdByComponentId(dbSession, component.getId()) .map(qualityGateId -> dbClient.qualityGateDao().selectById(dbSession, qualityGateId)) .map(qualityGateDto -> new QualityGateData(qualityGateDto, false)); if (res.isPresent()) { return res; } return ofNullable(dbClient.qualityGateDao().selectByOrganizationAndUuid(dbSession, organization, organization.getDefaultQualityGateUuid())) .map(qualityGateDto -> new QualityGateData(qualityGateDto, true)); }
java
public Optional<QualityGateData> getQualityGate(DbSession dbSession, OrganizationDto organization, ComponentDto component) { Optional<QualityGateData> res = dbClient.projectQgateAssociationDao().selectQGateIdByComponentId(dbSession, component.getId()) .map(qualityGateId -> dbClient.qualityGateDao().selectById(dbSession, qualityGateId)) .map(qualityGateDto -> new QualityGateData(qualityGateDto, false)); if (res.isPresent()) { return res; } return ofNullable(dbClient.qualityGateDao().selectByOrganizationAndUuid(dbSession, organization, organization.getDefaultQualityGateUuid())) .map(qualityGateDto -> new QualityGateData(qualityGateDto, true)); }
[ "public", "Optional", "<", "QualityGateData", ">", "getQualityGate", "(", "DbSession", "dbSession", ",", "OrganizationDto", "organization", ",", "ComponentDto", "component", ")", "{", "Optional", "<", "QualityGateData", ">", "res", "=", "dbClient", ".", "projectQgateAssociationDao", "(", ")", ".", "selectQGateIdByComponentId", "(", "dbSession", ",", "component", ".", "getId", "(", ")", ")", ".", "map", "(", "qualityGateId", "->", "dbClient", ".", "qualityGateDao", "(", ")", ".", "selectById", "(", "dbSession", ",", "qualityGateId", ")", ")", ".", "map", "(", "qualityGateDto", "->", "new", "QualityGateData", "(", "qualityGateDto", ",", "false", ")", ")", ";", "if", "(", "res", ".", "isPresent", "(", ")", ")", "{", "return", "res", ";", "}", "return", "ofNullable", "(", "dbClient", ".", "qualityGateDao", "(", ")", ".", "selectByOrganizationAndUuid", "(", "dbSession", ",", "organization", ",", "organization", ".", "getDefaultQualityGateUuid", "(", ")", ")", ")", ".", "map", "(", "qualityGateDto", "->", "new", "QualityGateData", "(", "qualityGateDto", ",", "true", ")", ")", ";", "}" ]
Return effective quality gate of a project. It will first try to get the quality gate explicitly defined on a project, if none it will try to return default quality gate of the organization
[ "Return", "effective", "quality", "gate", "of", "a", "project", "." ]
2fffa4c2f79ae3714844d7742796e82822b6a98a
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/server/sonar-server-common/src/main/java/org/sonar/server/qualitygate/QualityGateFinder.java#L48-L57
16,168
SonarSource/sonarqube
server/sonar-server/src/main/java/org/sonar/server/plugins/ServerPluginRepository.java
ServerPluginRepository.unloadIncompatiblePlugins
private void unloadIncompatiblePlugins() { // loop as long as the previous loop ignored some plugins. That allows to support dependencies // on many levels, for example D extends C, which extends B, which requires A. If A is not installed, // then B, C and D must be ignored. That's not possible to achieve this algorithm with a single // iteration over plugins. Set<String> removedKeys = new HashSet<>(); do { removedKeys.clear(); for (PluginInfo plugin : pluginInfosByKeys.values()) { if (!isCompatible(plugin, runtime, pluginInfosByKeys)) { removedKeys.add(plugin.getKey()); } } for (String removedKey : removedKeys) { pluginInfosByKeys.remove(removedKey); } } while (!removedKeys.isEmpty()); }
java
private void unloadIncompatiblePlugins() { // loop as long as the previous loop ignored some plugins. That allows to support dependencies // on many levels, for example D extends C, which extends B, which requires A. If A is not installed, // then B, C and D must be ignored. That's not possible to achieve this algorithm with a single // iteration over plugins. Set<String> removedKeys = new HashSet<>(); do { removedKeys.clear(); for (PluginInfo plugin : pluginInfosByKeys.values()) { if (!isCompatible(plugin, runtime, pluginInfosByKeys)) { removedKeys.add(plugin.getKey()); } } for (String removedKey : removedKeys) { pluginInfosByKeys.remove(removedKey); } } while (!removedKeys.isEmpty()); }
[ "private", "void", "unloadIncompatiblePlugins", "(", ")", "{", "// loop as long as the previous loop ignored some plugins. That allows to support dependencies", "// on many levels, for example D extends C, which extends B, which requires A. If A is not installed,", "// then B, C and D must be ignored. That's not possible to achieve this algorithm with a single", "// iteration over plugins.", "Set", "<", "String", ">", "removedKeys", "=", "new", "HashSet", "<>", "(", ")", ";", "do", "{", "removedKeys", ".", "clear", "(", ")", ";", "for", "(", "PluginInfo", "plugin", ":", "pluginInfosByKeys", ".", "values", "(", ")", ")", "{", "if", "(", "!", "isCompatible", "(", "plugin", ",", "runtime", ",", "pluginInfosByKeys", ")", ")", "{", "removedKeys", ".", "add", "(", "plugin", ".", "getKey", "(", ")", ")", ";", "}", "}", "for", "(", "String", "removedKey", ":", "removedKeys", ")", "{", "pluginInfosByKeys", ".", "remove", "(", "removedKey", ")", ";", "}", "}", "while", "(", "!", "removedKeys", ".", "isEmpty", "(", ")", ")", ";", "}" ]
Removes the plugins that are not compatible with current environment.
[ "Removes", "the", "plugins", "that", "are", "not", "compatible", "with", "current", "environment", "." ]
2fffa4c2f79ae3714844d7742796e82822b6a98a
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/server/sonar-server/src/main/java/org/sonar/server/plugins/ServerPluginRepository.java#L204-L221
16,169
SonarSource/sonarqube
server/sonar-server/src/main/java/org/sonar/server/plugins/ServerPluginRepository.java
ServerPluginRepository.uninstall
public void uninstall(String pluginKey, File uninstallDir) { Set<String> uninstallKeys = new HashSet<>(); uninstallKeys.add(pluginKey); appendDependentPluginKeys(pluginKey, uninstallKeys); for (String uninstallKey : uninstallKeys) { PluginInfo info = getPluginInfo(uninstallKey); try { if (!getPluginFile(info).exists()) { LOG.info("Plugin already uninstalled: {} [{}]", info.getName(), info.getKey()); continue; } LOG.info("Uninstalling plugin {} [{}]", info.getName(), info.getKey()); File masterFile = getPluginFile(info); moveFileToDirectory(masterFile, uninstallDir, true); } catch (IOException e) { throw new IllegalStateException(format("Fail to uninstall plugin %s [%s]", info.getName(), info.getKey()), e); } } }
java
public void uninstall(String pluginKey, File uninstallDir) { Set<String> uninstallKeys = new HashSet<>(); uninstallKeys.add(pluginKey); appendDependentPluginKeys(pluginKey, uninstallKeys); for (String uninstallKey : uninstallKeys) { PluginInfo info = getPluginInfo(uninstallKey); try { if (!getPluginFile(info).exists()) { LOG.info("Plugin already uninstalled: {} [{}]", info.getName(), info.getKey()); continue; } LOG.info("Uninstalling plugin {} [{}]", info.getName(), info.getKey()); File masterFile = getPluginFile(info); moveFileToDirectory(masterFile, uninstallDir, true); } catch (IOException e) { throw new IllegalStateException(format("Fail to uninstall plugin %s [%s]", info.getName(), info.getKey()), e); } } }
[ "public", "void", "uninstall", "(", "String", "pluginKey", ",", "File", "uninstallDir", ")", "{", "Set", "<", "String", ">", "uninstallKeys", "=", "new", "HashSet", "<>", "(", ")", ";", "uninstallKeys", ".", "add", "(", "pluginKey", ")", ";", "appendDependentPluginKeys", "(", "pluginKey", ",", "uninstallKeys", ")", ";", "for", "(", "String", "uninstallKey", ":", "uninstallKeys", ")", "{", "PluginInfo", "info", "=", "getPluginInfo", "(", "uninstallKey", ")", ";", "try", "{", "if", "(", "!", "getPluginFile", "(", "info", ")", ".", "exists", "(", ")", ")", "{", "LOG", ".", "info", "(", "\"Plugin already uninstalled: {} [{}]\"", ",", "info", ".", "getName", "(", ")", ",", "info", ".", "getKey", "(", ")", ")", ";", "continue", ";", "}", "LOG", ".", "info", "(", "\"Uninstalling plugin {} [{}]\"", ",", "info", ".", "getName", "(", ")", ",", "info", ".", "getKey", "(", ")", ")", ";", "File", "masterFile", "=", "getPluginFile", "(", "info", ")", ";", "moveFileToDirectory", "(", "masterFile", ",", "uninstallDir", ",", "true", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "IllegalStateException", "(", "format", "(", "\"Fail to uninstall plugin %s [%s]\"", ",", "info", ".", "getName", "(", ")", ",", "info", ".", "getKey", "(", ")", ")", ",", "e", ")", ";", "}", "}", "}" ]
Uninstall a plugin and its dependents
[ "Uninstall", "a", "plugin", "and", "its", "dependents" ]
2fffa4c2f79ae3714844d7742796e82822b6a98a
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/server/sonar-server/src/main/java/org/sonar/server/plugins/ServerPluginRepository.java#L277-L299
16,170
SonarSource/sonarqube
server/sonar-server/src/main/java/org/sonar/server/plugins/ServerPluginRepository.java
ServerPluginRepository.appendDependentPluginKeys
private void appendDependentPluginKeys(String pluginKey, Set<String> appendTo) { for (PluginInfo otherPlugin : getPluginInfos()) { if (!otherPlugin.getKey().equals(pluginKey)) { for (PluginInfo.RequiredPlugin requirement : otherPlugin.getRequiredPlugins()) { if (requirement.getKey().equals(pluginKey)) { appendTo.add(otherPlugin.getKey()); appendDependentPluginKeys(otherPlugin.getKey(), appendTo); } } } } }
java
private void appendDependentPluginKeys(String pluginKey, Set<String> appendTo) { for (PluginInfo otherPlugin : getPluginInfos()) { if (!otherPlugin.getKey().equals(pluginKey)) { for (PluginInfo.RequiredPlugin requirement : otherPlugin.getRequiredPlugins()) { if (requirement.getKey().equals(pluginKey)) { appendTo.add(otherPlugin.getKey()); appendDependentPluginKeys(otherPlugin.getKey(), appendTo); } } } } }
[ "private", "void", "appendDependentPluginKeys", "(", "String", "pluginKey", ",", "Set", "<", "String", ">", "appendTo", ")", "{", "for", "(", "PluginInfo", "otherPlugin", ":", "getPluginInfos", "(", ")", ")", "{", "if", "(", "!", "otherPlugin", ".", "getKey", "(", ")", ".", "equals", "(", "pluginKey", ")", ")", "{", "for", "(", "PluginInfo", ".", "RequiredPlugin", "requirement", ":", "otherPlugin", ".", "getRequiredPlugins", "(", ")", ")", "{", "if", "(", "requirement", ".", "getKey", "(", ")", ".", "equals", "(", "pluginKey", ")", ")", "{", "appendTo", ".", "add", "(", "otherPlugin", ".", "getKey", "(", ")", ")", ";", "appendDependentPluginKeys", "(", "otherPlugin", ".", "getKey", "(", ")", ",", "appendTo", ")", ";", "}", "}", "}", "}", "}" ]
Appends dependent plugins, only the ones that still exist in the plugins folder.
[ "Appends", "dependent", "plugins", "only", "the", "ones", "that", "still", "exist", "in", "the", "plugins", "folder", "." ]
2fffa4c2f79ae3714844d7742796e82822b6a98a
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/server/sonar-server/src/main/java/org/sonar/server/plugins/ServerPluginRepository.java#L314-L325
16,171
SonarSource/sonarqube
server/sonar-db-dao/src/main/java/org/sonar/db/KeyLongValue.java
KeyLongValue.toMap
public static Map<String, Long> toMap(List<KeyLongValue> values) { return values .stream() .collect(uniqueIndex(KeyLongValue::getKey, KeyLongValue::getValue, values.size())); }
java
public static Map<String, Long> toMap(List<KeyLongValue> values) { return values .stream() .collect(uniqueIndex(KeyLongValue::getKey, KeyLongValue::getValue, values.size())); }
[ "public", "static", "Map", "<", "String", ",", "Long", ">", "toMap", "(", "List", "<", "KeyLongValue", ">", "values", ")", "{", "return", "values", ".", "stream", "(", ")", ".", "collect", "(", "uniqueIndex", "(", "KeyLongValue", "::", "getKey", ",", "KeyLongValue", "::", "getValue", ",", "values", ".", "size", "(", ")", ")", ")", ";", "}" ]
This method does not keep order of list.
[ "This", "method", "does", "not", "keep", "order", "of", "list", "." ]
2fffa4c2f79ae3714844d7742796e82822b6a98a
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/server/sonar-db-dao/src/main/java/org/sonar/db/KeyLongValue.java#L52-L56
16,172
SonarSource/sonarqube
server/sonar-server/src/main/java/org/sonar/server/component/ComponentUpdater.java
ComponentUpdater.removeDuplicatedProjects
private void removeDuplicatedProjects(DbSession session, String projectKey) { List<ComponentDto> duplicated = dbClient.componentDao().selectComponentsHavingSameKeyOrderedById(session, projectKey); for (int i = 1; i < duplicated.size(); i++) { dbClient.componentDao().delete(session, duplicated.get(i).getId()); } }
java
private void removeDuplicatedProjects(DbSession session, String projectKey) { List<ComponentDto> duplicated = dbClient.componentDao().selectComponentsHavingSameKeyOrderedById(session, projectKey); for (int i = 1; i < duplicated.size(); i++) { dbClient.componentDao().delete(session, duplicated.get(i).getId()); } }
[ "private", "void", "removeDuplicatedProjects", "(", "DbSession", "session", ",", "String", "projectKey", ")", "{", "List", "<", "ComponentDto", ">", "duplicated", "=", "dbClient", ".", "componentDao", "(", ")", ".", "selectComponentsHavingSameKeyOrderedById", "(", "session", ",", "projectKey", ")", ";", "for", "(", "int", "i", "=", "1", ";", "i", "<", "duplicated", ".", "size", "(", ")", ";", "i", "++", ")", "{", "dbClient", ".", "componentDao", "(", ")", ".", "delete", "(", "session", ",", "duplicated", ".", "get", "(", "i", ")", ".", "getId", "(", ")", ")", ";", "}", "}" ]
On MySQL, as PROJECTS.KEE is not unique, if the same project is provisioned multiple times, then it will be duplicated in the database. So, after creating a project, we commit, and we search in the db if their are some duplications and we remove them. SONAR-6332
[ "On", "MySQL", "as", "PROJECTS", ".", "KEE", "is", "not", "unique", "if", "the", "same", "project", "is", "provisioned", "multiple", "times", "then", "it", "will", "be", "duplicated", "in", "the", "database", ".", "So", "after", "creating", "a", "project", "we", "commit", "and", "we", "search", "in", "the", "db", "if", "their", "are", "some", "duplications", "and", "we", "remove", "them", "." ]
2fffa4c2f79ae3714844d7742796e82822b6a98a
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/server/sonar-server/src/main/java/org/sonar/server/component/ComponentUpdater.java#L150-L155
16,173
SonarSource/sonarqube
sonar-duplications/src/main/java/org/sonar/duplications/detector/suffixtree/DuplicationsCollector.java
DuplicationsCollector.endOfGroup
@Override public void endOfGroup() { ClonePart origin = null; CloneGroup.Builder builder = CloneGroup.builder().setLength(length); List<ClonePart> parts = new ArrayList<>(count); for (int[] b : blockNumbers) { Block firstBlock = text.getBlock(b[0]); Block lastBlock = text.getBlock(b[1]); ClonePart part = new ClonePart( firstBlock.getResourceId(), firstBlock.getIndexInFile(), firstBlock.getStartLine(), lastBlock.getEndLine()); // TODO Godin: maybe use FastStringComparator here ? if (originResourceId.equals(part.getResourceId())) { // part from origin if (origin == null) { origin = part; // To calculate length important to use the origin, because otherwise block may come from DB without required data builder.setLengthInUnits(lastBlock.getEndUnit() - firstBlock.getStartUnit() + 1); } else if (part.getUnitStart() < origin.getUnitStart()) { origin = part; } } parts.add(part); } Collections.sort(parts, ContainsInComparator.CLONEPART_COMPARATOR); builder.setOrigin(origin).setParts(parts); filter(builder.build()); reset(); }
java
@Override public void endOfGroup() { ClonePart origin = null; CloneGroup.Builder builder = CloneGroup.builder().setLength(length); List<ClonePart> parts = new ArrayList<>(count); for (int[] b : blockNumbers) { Block firstBlock = text.getBlock(b[0]); Block lastBlock = text.getBlock(b[1]); ClonePart part = new ClonePart( firstBlock.getResourceId(), firstBlock.getIndexInFile(), firstBlock.getStartLine(), lastBlock.getEndLine()); // TODO Godin: maybe use FastStringComparator here ? if (originResourceId.equals(part.getResourceId())) { // part from origin if (origin == null) { origin = part; // To calculate length important to use the origin, because otherwise block may come from DB without required data builder.setLengthInUnits(lastBlock.getEndUnit() - firstBlock.getStartUnit() + 1); } else if (part.getUnitStart() < origin.getUnitStart()) { origin = part; } } parts.add(part); } Collections.sort(parts, ContainsInComparator.CLONEPART_COMPARATOR); builder.setOrigin(origin).setParts(parts); filter(builder.build()); reset(); }
[ "@", "Override", "public", "void", "endOfGroup", "(", ")", "{", "ClonePart", "origin", "=", "null", ";", "CloneGroup", ".", "Builder", "builder", "=", "CloneGroup", ".", "builder", "(", ")", ".", "setLength", "(", "length", ")", ";", "List", "<", "ClonePart", ">", "parts", "=", "new", "ArrayList", "<>", "(", "count", ")", ";", "for", "(", "int", "[", "]", "b", ":", "blockNumbers", ")", "{", "Block", "firstBlock", "=", "text", ".", "getBlock", "(", "b", "[", "0", "]", ")", ";", "Block", "lastBlock", "=", "text", ".", "getBlock", "(", "b", "[", "1", "]", ")", ";", "ClonePart", "part", "=", "new", "ClonePart", "(", "firstBlock", ".", "getResourceId", "(", ")", ",", "firstBlock", ".", "getIndexInFile", "(", ")", ",", "firstBlock", ".", "getStartLine", "(", ")", ",", "lastBlock", ".", "getEndLine", "(", ")", ")", ";", "// TODO Godin: maybe use FastStringComparator here ?", "if", "(", "originResourceId", ".", "equals", "(", "part", ".", "getResourceId", "(", ")", ")", ")", "{", "// part from origin", "if", "(", "origin", "==", "null", ")", "{", "origin", "=", "part", ";", "// To calculate length important to use the origin, because otherwise block may come from DB without required data", "builder", ".", "setLengthInUnits", "(", "lastBlock", ".", "getEndUnit", "(", ")", "-", "firstBlock", ".", "getStartUnit", "(", ")", "+", "1", ")", ";", "}", "else", "if", "(", "part", ".", "getUnitStart", "(", ")", "<", "origin", ".", "getUnitStart", "(", ")", ")", "{", "origin", "=", "part", ";", "}", "}", "parts", ".", "add", "(", "part", ")", ";", "}", "Collections", ".", "sort", "(", "parts", ",", "ContainsInComparator", ".", "CLONEPART_COMPARATOR", ")", ";", "builder", ".", "setOrigin", "(", "origin", ")", ".", "setParts", "(", "parts", ")", ";", "filter", "(", "builder", ".", "build", "(", ")", ")", ";", "reset", "(", ")", ";", "}" ]
Constructs CloneGroup and saves it.
[ "Constructs", "CloneGroup", "and", "saves", "it", "." ]
2fffa4c2f79ae3714844d7742796e82822b6a98a
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/sonar-duplications/src/main/java/org/sonar/duplications/detector/suffixtree/DuplicationsCollector.java#L79-L116
16,174
SonarSource/sonarqube
server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/IssueTrackingDelegator.java
IssueTrackingDelegator.isFirstAnalysisSecondaryLongLivingBranch
private boolean isFirstAnalysisSecondaryLongLivingBranch() { if (analysisMetadataHolder.isFirstAnalysis()) { Branch branch = analysisMetadataHolder.getBranch(); return !branch.isMain() && branch.getType() == BranchType.LONG; } return false; }
java
private boolean isFirstAnalysisSecondaryLongLivingBranch() { if (analysisMetadataHolder.isFirstAnalysis()) { Branch branch = analysisMetadataHolder.getBranch(); return !branch.isMain() && branch.getType() == BranchType.LONG; } return false; }
[ "private", "boolean", "isFirstAnalysisSecondaryLongLivingBranch", "(", ")", "{", "if", "(", "analysisMetadataHolder", ".", "isFirstAnalysis", "(", ")", ")", "{", "Branch", "branch", "=", "analysisMetadataHolder", ".", "getBranch", "(", ")", ";", "return", "!", "branch", ".", "isMain", "(", ")", "&&", "branch", ".", "getType", "(", ")", "==", "BranchType", ".", "LONG", ";", "}", "return", "false", ";", "}" ]
Special case where we want to do the issue tracking with the merge branch, and copy matched issue to the current branch.
[ "Special", "case", "where", "we", "want", "to", "do", "the", "issue", "tracking", "with", "the", "merge", "branch", "and", "copy", "matched", "issue", "to", "the", "current", "branch", "." ]
2fffa4c2f79ae3714844d7742796e82822b6a98a
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/IssueTrackingDelegator.java#L64-L70
16,175
SonarSource/sonarqube
server/sonar-db-dao/src/main/java/org/sonar/db/measure/custom/CustomMeasureDao.java
CustomMeasureDao.selectByMetricKeyAndTextValue
public List<CustomMeasureDto> selectByMetricKeyAndTextValue(DbSession session, String metricKey, String textValue) { return mapper(session).selectByMetricKeyAndTextValue(metricKey, textValue); }
java
public List<CustomMeasureDto> selectByMetricKeyAndTextValue(DbSession session, String metricKey, String textValue) { return mapper(session).selectByMetricKeyAndTextValue(metricKey, textValue); }
[ "public", "List", "<", "CustomMeasureDto", ">", "selectByMetricKeyAndTextValue", "(", "DbSession", "session", ",", "String", "metricKey", ",", "String", "textValue", ")", "{", "return", "mapper", "(", "session", ")", ".", "selectByMetricKeyAndTextValue", "(", "metricKey", ",", "textValue", ")", ";", "}" ]
Used by Views plugin
[ "Used", "by", "Views", "plugin" ]
2fffa4c2f79ae3714844d7742796e82822b6a98a
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/server/sonar-db-dao/src/main/java/org/sonar/db/measure/custom/CustomMeasureDao.java#L70-L72
16,176
SonarSource/sonarqube
server/sonar-server-common/src/main/java/org/sonar/server/platform/ServerImpl.java
ServerImpl.getId
@Override @CheckForNull public String getId() { return config.get(CoreProperties.SERVER_ID).orElse(null); }
java
@Override @CheckForNull public String getId() { return config.get(CoreProperties.SERVER_ID).orElse(null); }
[ "@", "Override", "@", "CheckForNull", "public", "String", "getId", "(", ")", "{", "return", "config", ".", "get", "(", "CoreProperties", ".", "SERVER_ID", ")", ".", "orElse", "(", "null", ")", ";", "}" ]
Can be null when server is waiting for migration
[ "Can", "be", "null", "when", "server", "is", "waiting", "for", "migration" ]
2fffa4c2f79ae3714844d7742796e82822b6a98a
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/server/sonar-server-common/src/main/java/org/sonar/server/platform/ServerImpl.java#L53-L57
16,177
SonarSource/sonarqube
server/sonar-process/src/main/java/org/sonar/process/NetworkUtilsImpl.java
NetworkUtilsImpl.getNextAvailablePort
@VisibleForTesting static int getNextAvailablePort(InetAddress address, PortAllocator portAllocator) { for (int i = 0; i < PORT_MAX_TRIES; i++) { int port = portAllocator.getAvailable(address); if (isValidPort(port)) { PORTS_ALREADY_ALLOCATED.add(port); return port; } } throw new IllegalStateException("Fail to find an available port on " + address); }
java
@VisibleForTesting static int getNextAvailablePort(InetAddress address, PortAllocator portAllocator) { for (int i = 0; i < PORT_MAX_TRIES; i++) { int port = portAllocator.getAvailable(address); if (isValidPort(port)) { PORTS_ALREADY_ALLOCATED.add(port); return port; } } throw new IllegalStateException("Fail to find an available port on " + address); }
[ "@", "VisibleForTesting", "static", "int", "getNextAvailablePort", "(", "InetAddress", "address", ",", "PortAllocator", "portAllocator", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "PORT_MAX_TRIES", ";", "i", "++", ")", "{", "int", "port", "=", "portAllocator", ".", "getAvailable", "(", "address", ")", ";", "if", "(", "isValidPort", "(", "port", ")", ")", "{", "PORTS_ALREADY_ALLOCATED", ".", "add", "(", "port", ")", ";", "return", "port", ";", "}", "}", "throw", "new", "IllegalStateException", "(", "\"Fail to find an available port on \"", "+", "address", ")", ";", "}" ]
Warning - the allocated ports are kept in memory and are never clean-up. Besides the memory consumption, that means that ports already allocated are never freed. As a consequence no more than ~64512 calls to this method are allowed.
[ "Warning", "-", "the", "allocated", "ports", "are", "kept", "in", "memory", "and", "are", "never", "clean", "-", "up", ".", "Besides", "the", "memory", "consumption", "that", "means", "that", "ports", "already", "allocated", "are", "never", "freed", ".", "As", "a", "consequence", "no", "more", "than", "~64512", "calls", "to", "this", "method", "are", "allowed", "." ]
2fffa4c2f79ae3714844d7742796e82822b6a98a
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/server/sonar-process/src/main/java/org/sonar/process/NetworkUtilsImpl.java#L56-L66
16,178
SonarSource/sonarqube
server/sonar-server-common/src/main/java/org/sonar/server/rule/index/RuleIndexer.java
RuleIndexer.commitAndIndex
public void commitAndIndex(DbSession dbSession, int ruleId, OrganizationDto organization) { List<EsQueueDto> items = asList(createQueueDtoForRule(ruleId), createQueueDtoForRuleExtension(ruleId, organization)); dbClient.esQueueDao().insert(dbSession, items); dbSession.commit(); postCommit(dbSession, items); }
java
public void commitAndIndex(DbSession dbSession, int ruleId, OrganizationDto organization) { List<EsQueueDto> items = asList(createQueueDtoForRule(ruleId), createQueueDtoForRuleExtension(ruleId, organization)); dbClient.esQueueDao().insert(dbSession, items); dbSession.commit(); postCommit(dbSession, items); }
[ "public", "void", "commitAndIndex", "(", "DbSession", "dbSession", ",", "int", "ruleId", ",", "OrganizationDto", "organization", ")", "{", "List", "<", "EsQueueDto", ">", "items", "=", "asList", "(", "createQueueDtoForRule", "(", "ruleId", ")", ",", "createQueueDtoForRuleExtension", "(", "ruleId", ",", "organization", ")", ")", ";", "dbClient", ".", "esQueueDao", "(", ")", ".", "insert", "(", "dbSession", ",", "items", ")", ";", "dbSession", ".", "commit", "(", ")", ";", "postCommit", "(", "dbSession", ",", "items", ")", ";", "}" ]
Commit a change on a rule and its extension on the given organization
[ "Commit", "a", "change", "on", "a", "rule", "and", "its", "extension", "on", "the", "given", "organization" ]
2fffa4c2f79ae3714844d7742796e82822b6a98a
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/server/sonar-server-common/src/main/java/org/sonar/server/rule/index/RuleIndexer.java#L105-L110
16,179
SonarSource/sonarqube
server/sonar-server-common/src/main/java/org/sonar/server/es/SearchOptions.java
SearchOptions.setLimit
public SearchOptions setLimit(int limit) { if (limit <= 0) { this.limit = MAX_LIMIT; } else { this.limit = Math.min(limit, MAX_LIMIT); } return this; }
java
public SearchOptions setLimit(int limit) { if (limit <= 0) { this.limit = MAX_LIMIT; } else { this.limit = Math.min(limit, MAX_LIMIT); } return this; }
[ "public", "SearchOptions", "setLimit", "(", "int", "limit", ")", "{", "if", "(", "limit", "<=", "0", ")", "{", "this", ".", "limit", "=", "MAX_LIMIT", ";", "}", "else", "{", "this", ".", "limit", "=", "Math", ".", "min", "(", "limit", ",", "MAX_LIMIT", ")", ";", "}", "return", "this", ";", "}" ]
Sets the limit on the number of results to return.
[ "Sets", "the", "limit", "on", "the", "number", "of", "results", "to", "return", "." ]
2fffa4c2f79ae3714844d7742796e82822b6a98a
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/server/sonar-server-common/src/main/java/org/sonar/server/es/SearchOptions.java#L92-L99
16,180
SonarSource/sonarqube
sonar-plugin-api/src/main/java/org/sonar/api/utils/ZipUtils.java
ZipUtils.unzip
public static File unzip(File zip, File toDir) throws IOException { return unzip(zip, toDir, (Predicate<ZipEntry>) ze -> true); }
java
public static File unzip(File zip, File toDir) throws IOException { return unzip(zip, toDir, (Predicate<ZipEntry>) ze -> true); }
[ "public", "static", "File", "unzip", "(", "File", "zip", ",", "File", "toDir", ")", "throws", "IOException", "{", "return", "unzip", "(", "zip", ",", "toDir", ",", "(", "Predicate", "<", "ZipEntry", ">", ")", "ze", "->", "true", ")", ";", "}" ]
Unzip a file into a directory. The directory is created if it does not exist. @return the target directory
[ "Unzip", "a", "file", "into", "a", "directory", ".", "The", "directory", "is", "created", "if", "it", "does", "not", "exist", "." ]
2fffa4c2f79ae3714844d7742796e82822b6a98a
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/sonar-plugin-api/src/main/java/org/sonar/api/utils/ZipUtils.java#L57-L59
16,181
SonarSource/sonarqube
sonar-plugin-api/src/main/java/org/sonar/api/utils/WildcardPattern.java
WildcardPattern.match
public boolean match(String value) { value = StringUtils.removeStart(value, "/"); value = StringUtils.removeEnd(value, "/"); return pattern.matcher(value).matches(); }
java
public boolean match(String value) { value = StringUtils.removeStart(value, "/"); value = StringUtils.removeEnd(value, "/"); return pattern.matcher(value).matches(); }
[ "public", "boolean", "match", "(", "String", "value", ")", "{", "value", "=", "StringUtils", ".", "removeStart", "(", "value", ",", "\"/\"", ")", ";", "value", "=", "StringUtils", ".", "removeEnd", "(", "value", ",", "\"/\"", ")", ";", "return", "pattern", ".", "matcher", "(", "value", ")", ".", "matches", "(", ")", ";", "}" ]
Returns true if specified value matches this pattern.
[ "Returns", "true", "if", "specified", "value", "matches", "this", "pattern", "." ]
2fffa4c2f79ae3714844d7742796e82822b6a98a
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/sonar-plugin-api/src/main/java/org/sonar/api/utils/WildcardPattern.java#L142-L146
16,182
SonarSource/sonarqube
sonar-plugin-api/src/main/java/org/sonar/api/utils/WildcardPattern.java
WildcardPattern.match
public static boolean match(WildcardPattern[] patterns, String value) { for (WildcardPattern pattern : patterns) { if (pattern.match(value)) { return true; } } return false; }
java
public static boolean match(WildcardPattern[] patterns, String value) { for (WildcardPattern pattern : patterns) { if (pattern.match(value)) { return true; } } return false; }
[ "public", "static", "boolean", "match", "(", "WildcardPattern", "[", "]", "patterns", ",", "String", "value", ")", "{", "for", "(", "WildcardPattern", "pattern", ":", "patterns", ")", "{", "if", "(", "pattern", ".", "match", "(", "value", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Returns true if specified value matches one of specified patterns. @since 2.4
[ "Returns", "true", "if", "specified", "value", "matches", "one", "of", "specified", "patterns", "." ]
2fffa4c2f79ae3714844d7742796e82822b6a98a
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/sonar-plugin-api/src/main/java/org/sonar/api/utils/WildcardPattern.java#L153-L160
16,183
SonarSource/sonarqube
sonar-plugin-api/src/main/java/org/sonar/api/utils/UriReader.java
UriReader.readString
public String readString(URI uri, Charset charset) { return searchForSupportedProcessor(uri).readString(uri, charset); }
java
public String readString(URI uri, Charset charset) { return searchForSupportedProcessor(uri).readString(uri, charset); }
[ "public", "String", "readString", "(", "URI", "uri", ",", "Charset", "charset", ")", "{", "return", "searchForSupportedProcessor", "(", "uri", ")", ".", "readString", "(", "uri", ",", "charset", ")", ";", "}" ]
Reads all characters from uri, using the given character set. It throws an unchecked exception if an error occurs.
[ "Reads", "all", "characters", "from", "uri", "using", "the", "given", "character", "set", ".", "It", "throws", "an", "unchecked", "exception", "if", "an", "error", "occurs", "." ]
2fffa4c2f79ae3714844d7742796e82822b6a98a
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/sonar-plugin-api/src/main/java/org/sonar/api/utils/UriReader.java#L69-L71
16,184
SonarSource/sonarqube
sonar-plugin-api/src/main/java/org/sonar/api/utils/UriReader.java
UriReader.description
public String description(URI uri) { SchemeProcessor reader = searchForSupportedProcessor(uri); return reader.description(uri); }
java
public String description(URI uri) { SchemeProcessor reader = searchForSupportedProcessor(uri); return reader.description(uri); }
[ "public", "String", "description", "(", "URI", "uri", ")", "{", "SchemeProcessor", "reader", "=", "searchForSupportedProcessor", "(", "uri", ")", ";", "return", "reader", ".", "description", "(", "uri", ")", ";", "}" ]
Returns a detailed description of the given uri. For example HTTP URIs are completed with the configured HTTP proxy.
[ "Returns", "a", "detailed", "description", "of", "the", "given", "uri", ".", "For", "example", "HTTP", "URIs", "are", "completed", "with", "the", "configured", "HTTP", "proxy", "." ]
2fffa4c2f79ae3714844d7742796e82822b6a98a
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/sonar-plugin-api/src/main/java/org/sonar/api/utils/UriReader.java#L77-L81
16,185
SonarSource/sonarqube
server/sonar-server-common/src/main/java/org/sonar/server/qualitygate/ConditionEvaluator.java
ConditionEvaluator.evaluateCondition
private static Optional<EvaluatedCondition> evaluateCondition(Condition condition, ValueType type, Comparable value) { Comparable threshold = getThreshold(condition, type); if (reachThreshold(value, threshold, condition)) { return of(new EvaluatedCondition(condition, EvaluationStatus.ERROR, value.toString())); } return Optional.empty(); }
java
private static Optional<EvaluatedCondition> evaluateCondition(Condition condition, ValueType type, Comparable value) { Comparable threshold = getThreshold(condition, type); if (reachThreshold(value, threshold, condition)) { return of(new EvaluatedCondition(condition, EvaluationStatus.ERROR, value.toString())); } return Optional.empty(); }
[ "private", "static", "Optional", "<", "EvaluatedCondition", ">", "evaluateCondition", "(", "Condition", "condition", ",", "ValueType", "type", ",", "Comparable", "value", ")", "{", "Comparable", "threshold", "=", "getThreshold", "(", "condition", ",", "type", ")", ";", "if", "(", "reachThreshold", "(", "value", ",", "threshold", ",", "condition", ")", ")", "{", "return", "of", "(", "new", "EvaluatedCondition", "(", "condition", ",", "EvaluationStatus", ".", "ERROR", ",", "value", ".", "toString", "(", ")", ")", ")", ";", "}", "return", "Optional", ".", "empty", "(", ")", ";", "}" ]
Evaluates the error condition. Returns empty if threshold or measure value is not defined.
[ "Evaluates", "the", "error", "condition", ".", "Returns", "empty", "if", "threshold", "or", "measure", "value", "is", "not", "defined", "." ]
2fffa4c2f79ae3714844d7742796e82822b6a98a
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/server/sonar-server-common/src/main/java/org/sonar/server/qualitygate/ConditionEvaluator.java#L69-L76
16,186
SonarSource/sonarqube
server/sonar-db-dao/src/main/java/org/sonar/db/DbSessionImpl.java
DbSessionImpl.selectCursor
@Override public <T> Cursor<T> selectCursor(String statement) { return session.selectCursor(statement); }
java
@Override public <T> Cursor<T> selectCursor(String statement) { return session.selectCursor(statement); }
[ "@", "Override", "public", "<", "T", ">", "Cursor", "<", "T", ">", "selectCursor", "(", "String", "statement", ")", "{", "return", "session", ".", "selectCursor", "(", "statement", ")", ";", "}" ]
We only care about the the commit section. The rest is simply passed to its parent.
[ "We", "only", "care", "about", "the", "the", "commit", "section", ".", "The", "rest", "is", "simply", "passed", "to", "its", "parent", "." ]
2fffa4c2f79ae3714844d7742796e82822b6a98a
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/server/sonar-db-dao/src/main/java/org/sonar/db/DbSessionImpl.java#L55-L58
16,187
SonarSource/sonarqube
server/sonar-main/src/main/java/org/sonar/application/config/CommandLineParser.java
CommandLineParser.parseArguments
public static Properties parseArguments(String[] args) { Properties props = argumentsToProperties(args); // complete with only the system properties that start with "sonar." for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) { String key = entry.getKey().toString(); if (key.startsWith("sonar.")) { props.setProperty(key, entry.getValue().toString()); } } return props; }
java
public static Properties parseArguments(String[] args) { Properties props = argumentsToProperties(args); // complete with only the system properties that start with "sonar." for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) { String key = entry.getKey().toString(); if (key.startsWith("sonar.")) { props.setProperty(key, entry.getValue().toString()); } } return props; }
[ "public", "static", "Properties", "parseArguments", "(", "String", "[", "]", "args", ")", "{", "Properties", "props", "=", "argumentsToProperties", "(", "args", ")", ";", "// complete with only the system properties that start with \"sonar.\"", "for", "(", "Map", ".", "Entry", "<", "Object", ",", "Object", ">", "entry", ":", "System", ".", "getProperties", "(", ")", ".", "entrySet", "(", ")", ")", "{", "String", "key", "=", "entry", ".", "getKey", "(", ")", ".", "toString", "(", ")", ";", "if", "(", "key", ".", "startsWith", "(", "\"sonar.\"", ")", ")", "{", "props", ".", "setProperty", "(", "key", ",", "entry", ".", "getValue", "(", ")", ".", "toString", "(", ")", ")", ";", "}", "}", "return", "props", ";", "}" ]
Build properties from command-line arguments and system properties
[ "Build", "properties", "from", "command", "-", "line", "arguments", "and", "system", "properties" ]
2fffa4c2f79ae3714844d7742796e82822b6a98a
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/server/sonar-main/src/main/java/org/sonar/application/config/CommandLineParser.java#L36-L47
16,188
SonarSource/sonarqube
server/sonar-main/src/main/java/org/sonar/application/config/CommandLineParser.java
CommandLineParser.argumentsToProperties
static Properties argumentsToProperties(String[] args) { Properties props = new Properties(); for (String arg : args) { if (!arg.startsWith("-D") || !arg.contains("=")) { throw new IllegalArgumentException(String.format( "Command-line argument must start with -D, for example -Dsonar.jdbc.username=sonar. Got: %s", arg)); } String key = StringUtils.substringBefore(arg, "=").substring(2); String value = StringUtils.substringAfter(arg, "="); props.setProperty(key, value); } return props; }
java
static Properties argumentsToProperties(String[] args) { Properties props = new Properties(); for (String arg : args) { if (!arg.startsWith("-D") || !arg.contains("=")) { throw new IllegalArgumentException(String.format( "Command-line argument must start with -D, for example -Dsonar.jdbc.username=sonar. Got: %s", arg)); } String key = StringUtils.substringBefore(arg, "=").substring(2); String value = StringUtils.substringAfter(arg, "="); props.setProperty(key, value); } return props; }
[ "static", "Properties", "argumentsToProperties", "(", "String", "[", "]", "args", ")", "{", "Properties", "props", "=", "new", "Properties", "(", ")", ";", "for", "(", "String", "arg", ":", "args", ")", "{", "if", "(", "!", "arg", ".", "startsWith", "(", "\"-D\"", ")", "||", "!", "arg", ".", "contains", "(", "\"=\"", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "String", ".", "format", "(", "\"Command-line argument must start with -D, for example -Dsonar.jdbc.username=sonar. Got: %s\"", ",", "arg", ")", ")", ";", "}", "String", "key", "=", "StringUtils", ".", "substringBefore", "(", "arg", ",", "\"=\"", ")", ".", "substring", "(", "2", ")", ";", "String", "value", "=", "StringUtils", ".", "substringAfter", "(", "arg", ",", "\"=\"", ")", ";", "props", ".", "setProperty", "(", "key", ",", "value", ")", ";", "}", "return", "props", ";", "}" ]
Convert strings "-Dkey=value" to properties
[ "Convert", "strings", "-", "Dkey", "=", "value", "to", "properties" ]
2fffa4c2f79ae3714844d7742796e82822b6a98a
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/server/sonar-main/src/main/java/org/sonar/application/config/CommandLineParser.java#L52-L64
16,189
SonarSource/sonarqube
sonar-duplications/src/main/java/org/sonar/duplications/index/PackedMemoryCloneIndex.java
PackedMemoryCloneIndex.ensureCapacity
private void ensureCapacity() { if (size < resourceIds.length) { return; } int newCapacity = (resourceIds.length * 3) / 2 + 1; // Increase size of resourceIds String[] oldResourceIds = resourceIds; resourceIds = new String[newCapacity]; System.arraycopy(oldResourceIds, 0, resourceIds, 0, oldResourceIds.length); // Increase size of blockData int[] oldBlockData = blockData; blockData = new int[newCapacity * blockInts]; System.arraycopy(oldBlockData, 0, blockData, 0, oldBlockData.length); // Increase size of byResourceIndices (no need to copy old, because would be restored in method ensureSorted) resourceIdsIndex = new int[newCapacity]; sorted = false; }
java
private void ensureCapacity() { if (size < resourceIds.length) { return; } int newCapacity = (resourceIds.length * 3) / 2 + 1; // Increase size of resourceIds String[] oldResourceIds = resourceIds; resourceIds = new String[newCapacity]; System.arraycopy(oldResourceIds, 0, resourceIds, 0, oldResourceIds.length); // Increase size of blockData int[] oldBlockData = blockData; blockData = new int[newCapacity * blockInts]; System.arraycopy(oldBlockData, 0, blockData, 0, oldBlockData.length); // Increase size of byResourceIndices (no need to copy old, because would be restored in method ensureSorted) resourceIdsIndex = new int[newCapacity]; sorted = false; }
[ "private", "void", "ensureCapacity", "(", ")", "{", "if", "(", "size", "<", "resourceIds", ".", "length", ")", "{", "return", ";", "}", "int", "newCapacity", "=", "(", "resourceIds", ".", "length", "*", "3", ")", "/", "2", "+", "1", ";", "// Increase size of resourceIds", "String", "[", "]", "oldResourceIds", "=", "resourceIds", ";", "resourceIds", "=", "new", "String", "[", "newCapacity", "]", ";", "System", ".", "arraycopy", "(", "oldResourceIds", ",", "0", ",", "resourceIds", ",", "0", ",", "oldResourceIds", ".", "length", ")", ";", "// Increase size of blockData", "int", "[", "]", "oldBlockData", "=", "blockData", ";", "blockData", "=", "new", "int", "[", "newCapacity", "*", "blockInts", "]", ";", "System", ".", "arraycopy", "(", "oldBlockData", ",", "0", ",", "blockData", ",", "0", ",", "oldBlockData", ".", "length", ")", ";", "// Increase size of byResourceIndices (no need to copy old, because would be restored in method ensureSorted)", "resourceIdsIndex", "=", "new", "int", "[", "newCapacity", "]", ";", "sorted", "=", "false", ";", "}" ]
Increases the capacity, if necessary.
[ "Increases", "the", "capacity", "if", "necessary", "." ]
2fffa4c2f79ae3714844d7742796e82822b6a98a
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/sonar-duplications/src/main/java/org/sonar/duplications/index/PackedMemoryCloneIndex.java#L275-L291
16,190
SonarSource/sonarqube
sonar-duplications/src/main/java/org/sonar/duplications/index/PackedMemoryCloneIndex.java
PackedMemoryCloneIndex.ensureSorted
private void ensureSorted() { if (sorted) { return; } ensureCapacity(); DataUtils.sort(byBlockHash); for (int i = 0; i < size; i++) { resourceIdsIndex[i] = i; } DataUtils.sort(byResourceId); sorted = true; }
java
private void ensureSorted() { if (sorted) { return; } ensureCapacity(); DataUtils.sort(byBlockHash); for (int i = 0; i < size; i++) { resourceIdsIndex[i] = i; } DataUtils.sort(byResourceId); sorted = true; }
[ "private", "void", "ensureSorted", "(", ")", "{", "if", "(", "sorted", ")", "{", "return", ";", "}", "ensureCapacity", "(", ")", ";", "DataUtils", ".", "sort", "(", "byBlockHash", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "size", ";", "i", "++", ")", "{", "resourceIdsIndex", "[", "i", "]", "=", "i", ";", "}", "DataUtils", ".", "sort", "(", "byResourceId", ")", ";", "sorted", "=", "true", ";", "}" ]
Performs sorting, if necessary.
[ "Performs", "sorting", "if", "necessary", "." ]
2fffa4c2f79ae3714844d7742796e82822b6a98a
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/sonar-duplications/src/main/java/org/sonar/duplications/index/PackedMemoryCloneIndex.java#L296-L310
16,191
SonarSource/sonarqube
sonar-plugin-api/src/main/java/org/sonar/api/resources/ResourceType.java
ResourceType.getBooleanProperty
public boolean getBooleanProperty(String key) { requireNonNull(key); String value = properties.get(key); return value != null && Boolean.parseBoolean(value); }
java
public boolean getBooleanProperty(String key) { requireNonNull(key); String value = properties.get(key); return value != null && Boolean.parseBoolean(value); }
[ "public", "boolean", "getBooleanProperty", "(", "String", "key", ")", "{", "requireNonNull", "(", "key", ")", ";", "String", "value", "=", "properties", ".", "get", "(", "key", ")", ";", "return", "value", "!=", "null", "&&", "Boolean", ".", "parseBoolean", "(", "value", ")", ";", "}" ]
Returns the value of the property for this resource type. @return the Boolean value of the property. If the property hasn't been set, False is returned. @since 3.0
[ "Returns", "the", "value", "of", "the", "property", "for", "this", "resource", "type", "." ]
2fffa4c2f79ae3714844d7742796e82822b6a98a
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/sonar-plugin-api/src/main/java/org/sonar/api/resources/ResourceType.java#L117-L121
16,192
SonarSource/sonarqube
sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/AbstractSensorOptimizer.java
AbstractSensorOptimizer.shouldExecute
public boolean shouldExecute(DefaultSensorDescriptor descriptor) { if (!fsCondition(descriptor)) { LOG.debug("'{}' skipped because there is no related file in current project", descriptor.name()); return false; } if (!activeRulesCondition(descriptor)) { LOG.debug("'{}' skipped because there is no related rule activated in the quality profile", descriptor.name()); return false; } if (!settingsCondition(descriptor)) { LOG.debug("'{}' skipped because one of the required properties is missing", descriptor.name()); return false; } return true; }
java
public boolean shouldExecute(DefaultSensorDescriptor descriptor) { if (!fsCondition(descriptor)) { LOG.debug("'{}' skipped because there is no related file in current project", descriptor.name()); return false; } if (!activeRulesCondition(descriptor)) { LOG.debug("'{}' skipped because there is no related rule activated in the quality profile", descriptor.name()); return false; } if (!settingsCondition(descriptor)) { LOG.debug("'{}' skipped because one of the required properties is missing", descriptor.name()); return false; } return true; }
[ "public", "boolean", "shouldExecute", "(", "DefaultSensorDescriptor", "descriptor", ")", "{", "if", "(", "!", "fsCondition", "(", "descriptor", ")", ")", "{", "LOG", ".", "debug", "(", "\"'{}' skipped because there is no related file in current project\"", ",", "descriptor", ".", "name", "(", ")", ")", ";", "return", "false", ";", "}", "if", "(", "!", "activeRulesCondition", "(", "descriptor", ")", ")", "{", "LOG", ".", "debug", "(", "\"'{}' skipped because there is no related rule activated in the quality profile\"", ",", "descriptor", ".", "name", "(", ")", ")", ";", "return", "false", ";", "}", "if", "(", "!", "settingsCondition", "(", "descriptor", ")", ")", "{", "LOG", ".", "debug", "(", "\"'{}' skipped because one of the required properties is missing\"", ",", "descriptor", ".", "name", "(", ")", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}" ]
Decide if the given Sensor should be executed.
[ "Decide", "if", "the", "given", "Sensor", "should", "be", "executed", "." ]
2fffa4c2f79ae3714844d7742796e82822b6a98a
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/AbstractSensorOptimizer.java#L47-L61
16,193
SonarSource/sonarqube
sonar-plugin-api/src/main/java/org/sonar/api/measures/Metric.java
Metric.merge
public Metric<G> merge(final Metric with) { this.description = with.description; this.domain = with.domain; this.enabled = with.enabled; this.qualitative = with.qualitative; this.worstValue = with.worstValue; this.bestValue = with.bestValue; this.optimizedBestValue = with.optimizedBestValue; this.direction = with.direction; this.key = with.key; this.type = with.type; this.name = with.name; this.userManaged = with.userManaged; this.hidden = with.hidden; this.deleteHistoricalData = with.deleteHistoricalData; return this; }
java
public Metric<G> merge(final Metric with) { this.description = with.description; this.domain = with.domain; this.enabled = with.enabled; this.qualitative = with.qualitative; this.worstValue = with.worstValue; this.bestValue = with.bestValue; this.optimizedBestValue = with.optimizedBestValue; this.direction = with.direction; this.key = with.key; this.type = with.type; this.name = with.name; this.userManaged = with.userManaged; this.hidden = with.hidden; this.deleteHistoricalData = with.deleteHistoricalData; return this; }
[ "public", "Metric", "<", "G", ">", "merge", "(", "final", "Metric", "with", ")", "{", "this", ".", "description", "=", "with", ".", "description", ";", "this", ".", "domain", "=", "with", ".", "domain", ";", "this", ".", "enabled", "=", "with", ".", "enabled", ";", "this", ".", "qualitative", "=", "with", ".", "qualitative", ";", "this", ".", "worstValue", "=", "with", ".", "worstValue", ";", "this", ".", "bestValue", "=", "with", ".", "bestValue", ";", "this", ".", "optimizedBestValue", "=", "with", ".", "optimizedBestValue", ";", "this", ".", "direction", "=", "with", ".", "direction", ";", "this", ".", "key", "=", "with", ".", "key", ";", "this", ".", "type", "=", "with", ".", "type", ";", "this", ".", "name", "=", "with", ".", "name", ";", "this", ".", "userManaged", "=", "with", ".", "userManaged", ";", "this", ".", "hidden", "=", "with", ".", "hidden", ";", "this", ".", "deleteHistoricalData", "=", "with", ".", "deleteHistoricalData", ";", "return", "this", ";", "}" ]
Merge with fields from other metric. All fields are copied, except the id. @return this
[ "Merge", "with", "fields", "from", "other", "metric", ".", "All", "fields", "are", "copied", "except", "the", "id", "." ]
2fffa4c2f79ae3714844d7742796e82822b6a98a
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/sonar-plugin-api/src/main/java/org/sonar/api/measures/Metric.java#L533-L549
16,194
SonarSource/sonarqube
server/sonar-db-dao/src/main/java/org/sonar/db/component/SnapshotDao.java
SnapshotDao.selectFinishedByComponentUuidsAndFromDates
public List<SnapshotDto> selectFinishedByComponentUuidsAndFromDates(DbSession dbSession, List<String> componentUuids, List<Long> fromDates) { checkArgument(componentUuids.size() == fromDates.size(), "The number of components (%s) and from dates (%s) must be the same.", String.valueOf(componentUuids.size()), String.valueOf(fromDates.size())); List<ComponentUuidFromDatePair> componentUuidFromDatePairs = IntStream.range(0, componentUuids.size()) .mapToObj(i -> new ComponentUuidFromDatePair(componentUuids.get(i), fromDates.get(i))) .collect(MoreCollectors.toList(componentUuids.size())); return executeLargeInputs(componentUuidFromDatePairs, partition -> mapper(dbSession).selectFinishedByComponentUuidsAndFromDates(partition), i -> i / 2); }
java
public List<SnapshotDto> selectFinishedByComponentUuidsAndFromDates(DbSession dbSession, List<String> componentUuids, List<Long> fromDates) { checkArgument(componentUuids.size() == fromDates.size(), "The number of components (%s) and from dates (%s) must be the same.", String.valueOf(componentUuids.size()), String.valueOf(fromDates.size())); List<ComponentUuidFromDatePair> componentUuidFromDatePairs = IntStream.range(0, componentUuids.size()) .mapToObj(i -> new ComponentUuidFromDatePair(componentUuids.get(i), fromDates.get(i))) .collect(MoreCollectors.toList(componentUuids.size())); return executeLargeInputs(componentUuidFromDatePairs, partition -> mapper(dbSession).selectFinishedByComponentUuidsAndFromDates(partition), i -> i / 2); }
[ "public", "List", "<", "SnapshotDto", ">", "selectFinishedByComponentUuidsAndFromDates", "(", "DbSession", "dbSession", ",", "List", "<", "String", ">", "componentUuids", ",", "List", "<", "Long", ">", "fromDates", ")", "{", "checkArgument", "(", "componentUuids", ".", "size", "(", ")", "==", "fromDates", ".", "size", "(", ")", ",", "\"The number of components (%s) and from dates (%s) must be the same.\"", ",", "String", ".", "valueOf", "(", "componentUuids", ".", "size", "(", ")", ")", ",", "String", ".", "valueOf", "(", "fromDates", ".", "size", "(", ")", ")", ")", ";", "List", "<", "ComponentUuidFromDatePair", ">", "componentUuidFromDatePairs", "=", "IntStream", ".", "range", "(", "0", ",", "componentUuids", ".", "size", "(", ")", ")", ".", "mapToObj", "(", "i", "->", "new", "ComponentUuidFromDatePair", "(", "componentUuids", ".", "get", "(", "i", ")", ",", "fromDates", ".", "get", "(", "i", ")", ")", ")", ".", "collect", "(", "MoreCollectors", ".", "toList", "(", "componentUuids", ".", "size", "(", ")", ")", ")", ";", "return", "executeLargeInputs", "(", "componentUuidFromDatePairs", ",", "partition", "->", "mapper", "(", "dbSession", ")", ".", "selectFinishedByComponentUuidsAndFromDates", "(", "partition", ")", ",", "i", "->", "i", "/", "2", ")", ";", "}" ]
Returned finished analysis from a list of projects and dates. "Finished" analysis means that the status in the CE_ACTIVITY table is SUCCESS => the goal is to be sure that the CE task is completely finished. Note that branches analysis of projects are also returned.
[ "Returned", "finished", "analysis", "from", "a", "list", "of", "projects", "and", "dates", ".", "Finished", "analysis", "means", "that", "the", "status", "in", "the", "CE_ACTIVITY", "table", "is", "SUCCESS", "=", ">", "the", "goal", "is", "to", "be", "sure", "that", "the", "CE", "task", "is", "completely", "finished", "." ]
2fffa4c2f79ae3714844d7742796e82822b6a98a
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/server/sonar-db-dao/src/main/java/org/sonar/db/component/SnapshotDao.java#L98-L107
16,195
SonarSource/sonarqube
sonar-core/src/main/java/org/sonar/core/i18n/DefaultI18n.java
DefaultI18n.formatDateTime
@Override public String formatDateTime(Locale locale, Date date) { return DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT, locale).format(date); }
java
@Override public String formatDateTime(Locale locale, Date date) { return DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT, locale).format(date); }
[ "@", "Override", "public", "String", "formatDateTime", "(", "Locale", "locale", ",", "Date", "date", ")", "{", "return", "DateFormat", ".", "getDateTimeInstance", "(", "DateFormat", ".", "DEFAULT", ",", "DateFormat", ".", "SHORT", ",", "locale", ")", ".", "format", "(", "date", ")", ";", "}" ]
Format date for the given locale. JVM timezone is used.
[ "Format", "date", "for", "the", "given", "locale", ".", "JVM", "timezone", "is", "used", "." ]
2fffa4c2f79ae3714844d7742796e82822b6a98a
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/sonar-core/src/main/java/org/sonar/core/i18n/DefaultI18n.java#L166-L169
16,196
SonarSource/sonarqube
sonar-core/src/main/java/org/sonar/core/i18n/DefaultI18n.java
DefaultI18n.messageFromFile
String messageFromFile(Locale locale, String filename, String relatedProperty) { String result = null; String bundleBase = propertyToBundles.get(relatedProperty); if (bundleBase == null) { // this property has no translation return null; } String filePath = bundleBase.replace('.', '/'); if (!"en".equals(locale.getLanguage())) { filePath += "_" + locale.getLanguage(); } filePath += "/" + filename; InputStream input = classloader.getResourceAsStream(filePath); if (input != null) { result = readInputStream(filePath, input); } return result; }
java
String messageFromFile(Locale locale, String filename, String relatedProperty) { String result = null; String bundleBase = propertyToBundles.get(relatedProperty); if (bundleBase == null) { // this property has no translation return null; } String filePath = bundleBase.replace('.', '/'); if (!"en".equals(locale.getLanguage())) { filePath += "_" + locale.getLanguage(); } filePath += "/" + filename; InputStream input = classloader.getResourceAsStream(filePath); if (input != null) { result = readInputStream(filePath, input); } return result; }
[ "String", "messageFromFile", "(", "Locale", "locale", ",", "String", "filename", ",", "String", "relatedProperty", ")", "{", "String", "result", "=", "null", ";", "String", "bundleBase", "=", "propertyToBundles", ".", "get", "(", "relatedProperty", ")", ";", "if", "(", "bundleBase", "==", "null", ")", "{", "// this property has no translation", "return", "null", ";", "}", "String", "filePath", "=", "bundleBase", ".", "replace", "(", "'", "'", ",", "'", "'", ")", ";", "if", "(", "!", "\"en\"", ".", "equals", "(", "locale", ".", "getLanguage", "(", ")", ")", ")", "{", "filePath", "+=", "\"_\"", "+", "locale", ".", "getLanguage", "(", ")", ";", "}", "filePath", "+=", "\"/\"", "+", "filename", ";", "InputStream", "input", "=", "classloader", ".", "getResourceAsStream", "(", "filePath", ")", ";", "if", "(", "input", "!=", "null", ")", "{", "result", "=", "readInputStream", "(", "filePath", ",", "input", ")", ";", "}", "return", "result", ";", "}" ]
Only the given locale is searched. Contrary to java.util.ResourceBundle, no strategy for locating the bundle is implemented in this method.
[ "Only", "the", "given", "locale", "is", "searched", ".", "Contrary", "to", "java", ".", "util", ".", "ResourceBundle", "no", "strategy", "for", "locating", "the", "bundle", "is", "implemented", "in", "this", "method", "." ]
2fffa4c2f79ae3714844d7742796e82822b6a98a
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/sonar-core/src/main/java/org/sonar/core/i18n/DefaultI18n.java#L193-L211
16,197
SonarSource/sonarqube
sonar-plugin-api/src/main/java/org/sonar/api/ce/measure/RangeDistributionBuilder.java
RangeDistributionBuilder.add
public RangeDistributionBuilder add(Number value, int count) { if (greaterOrEqualsThan(value, bottomLimits[0])) { addValue(value, count); isEmpty = false; } return this; }
java
public RangeDistributionBuilder add(Number value, int count) { if (greaterOrEqualsThan(value, bottomLimits[0])) { addValue(value, count); isEmpty = false; } return this; }
[ "public", "RangeDistributionBuilder", "add", "(", "Number", "value", ",", "int", "count", ")", "{", "if", "(", "greaterOrEqualsThan", "(", "value", ",", "bottomLimits", "[", "0", "]", ")", ")", "{", "addValue", "(", "value", ",", "count", ")", ";", "isEmpty", "=", "false", ";", "}", "return", "this", ";", "}" ]
Increments an entry @param value the value to use to pick the entry to increment @param count the number by which to increment
[ "Increments", "an", "entry" ]
2fffa4c2f79ae3714844d7742796e82822b6a98a
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/sonar-plugin-api/src/main/java/org/sonar/api/ce/measure/RangeDistributionBuilder.java#L77-L83
16,198
SonarSource/sonarqube
server/sonar-server/src/main/java/org/sonar/server/usergroups/ws/GroupWsRef.java
GroupWsRef.fromId
static GroupWsRef fromId(int id) { checkArgument(id > -1, "Group id must be positive: %s", id); return new GroupWsRef(id, null, null); }
java
static GroupWsRef fromId(int id) { checkArgument(id > -1, "Group id must be positive: %s", id); return new GroupWsRef(id, null, null); }
[ "static", "GroupWsRef", "fromId", "(", "int", "id", ")", "{", "checkArgument", "(", "id", ">", "-", "1", ",", "\"Group id must be positive: %s\"", ",", "id", ")", ";", "return", "new", "GroupWsRef", "(", "id", ",", "null", ",", "null", ")", ";", "}" ]
Creates a reference to a group by its id. Virtual groups "Anyone" can't be returned as they can't be referenced by an id.
[ "Creates", "a", "reference", "to", "a", "group", "by", "its", "id", ".", "Virtual", "groups", "Anyone", "can", "t", "be", "returned", "as", "they", "can", "t", "be", "referenced", "by", "an", "id", "." ]
2fffa4c2f79ae3714844d7742796e82822b6a98a
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/server/sonar-server/src/main/java/org/sonar/server/usergroups/ws/GroupWsRef.java#L98-L101
16,199
SonarSource/sonarqube
sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/ScannerWsClient.java
ScannerWsClient.createErrorMessage
public static String createErrorMessage(HttpException exception) { String json = tryParseAsJsonError(exception.content()); if (json != null) { return json; } String msg = "HTTP code " + exception.code(); if (isHtml(exception.content())) { return msg; } return msg + ": " + StringUtils.left(exception.content(), MAX_ERROR_MSG_LEN); }
java
public static String createErrorMessage(HttpException exception) { String json = tryParseAsJsonError(exception.content()); if (json != null) { return json; } String msg = "HTTP code " + exception.code(); if (isHtml(exception.content())) { return msg; } return msg + ": " + StringUtils.left(exception.content(), MAX_ERROR_MSG_LEN); }
[ "public", "static", "String", "createErrorMessage", "(", "HttpException", "exception", ")", "{", "String", "json", "=", "tryParseAsJsonError", "(", "exception", ".", "content", "(", ")", ")", ";", "if", "(", "json", "!=", "null", ")", "{", "return", "json", ";", "}", "String", "msg", "=", "\"HTTP code \"", "+", "exception", ".", "code", "(", ")", ";", "if", "(", "isHtml", "(", "exception", ".", "content", "(", ")", ")", ")", "{", "return", "msg", ";", "}", "return", "msg", "+", "\": \"", "+", "StringUtils", ".", "left", "(", "exception", ".", "content", "(", ")", ",", "MAX_ERROR_MSG_LEN", ")", ";", "}" ]
Tries to form a short and relevant error message from the exception, to be displayed in the console.
[ "Tries", "to", "form", "a", "short", "and", "relevant", "error", "message", "from", "the", "exception", "to", "be", "displayed", "in", "the", "console", "." ]
2fffa4c2f79ae3714844d7742796e82822b6a98a
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/ScannerWsClient.java#L121-L133