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
sequence
docstring
stringlengths
3
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
105
339
164,400
randomizedtesting/randomizedtesting
junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/listeners/TextReport.java
TextReport.emitStatusLine
private void emitStatusLine(AggregatedResultEvent result, TestStatus status, long timeMillis) throws IOException { final StringBuilder line = new StringBuilder(); line.append(shortTimestamp(result.getStartTimestamp())); line.append(Strings.padEnd(statusNames.get(status), 8, ' ')); line.append(formatDurationInSeconds(timeMillis)); if (forkedJvmCount > 1) { line.append(String.format(Locale.ROOT, jvmIdFormat, result.getSlave().id)); } line.append(" | "); line.append(formatDescription(result.getDescription())); if (!result.isSuccessful()) { line.append(FAILURE_MARKER); } line.append("\n"); if (showThrowable) { // GH-82 (cause for ignored tests). if (status == TestStatus.IGNORED && result instanceof AggregatedTestResultEvent) { final StringWriter sw = new StringWriter(); PrefixedWriter pos = new PrefixedWriter(indent, sw, DEFAULT_MAX_LINE_WIDTH); pos.write("Cause: "); pos.write(((AggregatedTestResultEvent) result).getCauseForIgnored()); pos.completeLine(); line.append(sw.toString()); } final List<FailureMirror> failures = result.getFailures(); if (!failures.isEmpty()) { final StringWriter sw = new StringWriter(); PrefixedWriter pos = new PrefixedWriter(indent, sw, DEFAULT_MAX_LINE_WIDTH); int count = 0; for (FailureMirror fm : failures) { count++; if (fm.isAssumptionViolation()) { pos.write(String.format(Locale.ROOT, "Assumption #%d: %s", count, MoreObjects.firstNonNull(fm.getMessage(), "(no message)"))); } else { pos.write(String.format(Locale.ROOT, "Throwable #%d: %s", count, showStackTraces ? filterStackTrace(fm.getTrace()) : fm.getThrowableString())); } } pos.completeLine(); if (sw.getBuffer().length() > 0) { line.append(sw.toString()); } } } logShort(line); }
java
private void emitStatusLine(AggregatedResultEvent result, TestStatus status, long timeMillis) throws IOException { final StringBuilder line = new StringBuilder(); line.append(shortTimestamp(result.getStartTimestamp())); line.append(Strings.padEnd(statusNames.get(status), 8, ' ')); line.append(formatDurationInSeconds(timeMillis)); if (forkedJvmCount > 1) { line.append(String.format(Locale.ROOT, jvmIdFormat, result.getSlave().id)); } line.append(" | "); line.append(formatDescription(result.getDescription())); if (!result.isSuccessful()) { line.append(FAILURE_MARKER); } line.append("\n"); if (showThrowable) { // GH-82 (cause for ignored tests). if (status == TestStatus.IGNORED && result instanceof AggregatedTestResultEvent) { final StringWriter sw = new StringWriter(); PrefixedWriter pos = new PrefixedWriter(indent, sw, DEFAULT_MAX_LINE_WIDTH); pos.write("Cause: "); pos.write(((AggregatedTestResultEvent) result).getCauseForIgnored()); pos.completeLine(); line.append(sw.toString()); } final List<FailureMirror> failures = result.getFailures(); if (!failures.isEmpty()) { final StringWriter sw = new StringWriter(); PrefixedWriter pos = new PrefixedWriter(indent, sw, DEFAULT_MAX_LINE_WIDTH); int count = 0; for (FailureMirror fm : failures) { count++; if (fm.isAssumptionViolation()) { pos.write(String.format(Locale.ROOT, "Assumption #%d: %s", count, MoreObjects.firstNonNull(fm.getMessage(), "(no message)"))); } else { pos.write(String.format(Locale.ROOT, "Throwable #%d: %s", count, showStackTraces ? filterStackTrace(fm.getTrace()) : fm.getThrowableString())); } } pos.completeLine(); if (sw.getBuffer().length() > 0) { line.append(sw.toString()); } } } logShort(line); }
[ "private", "void", "emitStatusLine", "(", "AggregatedResultEvent", "result", ",", "TestStatus", "status", ",", "long", "timeMillis", ")", "throws", "IOException", "{", "final", "StringBuilder", "line", "=", "new", "StringBuilder", "(", ")", ";", "line", ".", "append", "(", "shortTimestamp", "(", "result", ".", "getStartTimestamp", "(", ")", ")", ")", ";", "line", ".", "append", "(", "Strings", ".", "padEnd", "(", "statusNames", ".", "get", "(", "status", ")", ",", "8", ",", "'", "'", ")", ")", ";", "line", ".", "append", "(", "formatDurationInSeconds", "(", "timeMillis", ")", ")", ";", "if", "(", "forkedJvmCount", ">", "1", ")", "{", "line", ".", "append", "(", "String", ".", "format", "(", "Locale", ".", "ROOT", ",", "jvmIdFormat", ",", "result", ".", "getSlave", "(", ")", ".", "id", ")", ")", ";", "}", "line", ".", "append", "(", "\" | \"", ")", ";", "line", ".", "append", "(", "formatDescription", "(", "result", ".", "getDescription", "(", ")", ")", ")", ";", "if", "(", "!", "result", ".", "isSuccessful", "(", ")", ")", "{", "line", ".", "append", "(", "FAILURE_MARKER", ")", ";", "}", "line", ".", "append", "(", "\"\\n\"", ")", ";", "if", "(", "showThrowable", ")", "{", "// GH-82 (cause for ignored tests). ", "if", "(", "status", "==", "TestStatus", ".", "IGNORED", "&&", "result", "instanceof", "AggregatedTestResultEvent", ")", "{", "final", "StringWriter", "sw", "=", "new", "StringWriter", "(", ")", ";", "PrefixedWriter", "pos", "=", "new", "PrefixedWriter", "(", "indent", ",", "sw", ",", "DEFAULT_MAX_LINE_WIDTH", ")", ";", "pos", ".", "write", "(", "\"Cause: \"", ")", ";", "pos", ".", "write", "(", "(", "(", "AggregatedTestResultEvent", ")", "result", ")", ".", "getCauseForIgnored", "(", ")", ")", ";", "pos", ".", "completeLine", "(", ")", ";", "line", ".", "append", "(", "sw", ".", "toString", "(", ")", ")", ";", "}", "final", "List", "<", "FailureMirror", ">", "failures", "=", "result", ".", "getFailures", "(", ")", ";", "if", "(", "!", "failures", ".", "isEmpty", "(", ")", ")", "{", "final", "StringWriter", "sw", "=", "new", "StringWriter", "(", ")", ";", "PrefixedWriter", "pos", "=", "new", "PrefixedWriter", "(", "indent", ",", "sw", ",", "DEFAULT_MAX_LINE_WIDTH", ")", ";", "int", "count", "=", "0", ";", "for", "(", "FailureMirror", "fm", ":", "failures", ")", "{", "count", "++", ";", "if", "(", "fm", ".", "isAssumptionViolation", "(", ")", ")", "{", "pos", ".", "write", "(", "String", ".", "format", "(", "Locale", ".", "ROOT", ",", "\"Assumption #%d: %s\"", ",", "count", ",", "MoreObjects", ".", "firstNonNull", "(", "fm", ".", "getMessage", "(", ")", ",", "\"(no message)\"", ")", ")", ")", ";", "}", "else", "{", "pos", ".", "write", "(", "String", ".", "format", "(", "Locale", ".", "ROOT", ",", "\"Throwable #%d: %s\"", ",", "count", ",", "showStackTraces", "?", "filterStackTrace", "(", "fm", ".", "getTrace", "(", ")", ")", ":", "fm", ".", "getThrowableString", "(", ")", ")", ")", ";", "}", "}", "pos", ".", "completeLine", "(", ")", ";", "if", "(", "sw", ".", "getBuffer", "(", ")", ".", "length", "(", ")", ">", "0", ")", "{", "line", ".", "append", "(", "sw", ".", "toString", "(", ")", ")", ";", "}", "}", "}", "logShort", "(", "line", ")", ";", "}" ]
Emit status line for an aggregated event.
[ "Emit", "status", "line", "for", "an", "aggregated", "event", "." ]
85a0c7eff5d03d98da4d1f9502a11af74d26478a
https://github.com/randomizedtesting/randomizedtesting/blob/85a0c7eff5d03d98da4d1f9502a11af74d26478a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/listeners/TextReport.java#L608-L662
164,401
randomizedtesting/randomizedtesting
junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/listeners/TextReport.java
TextReport.logShort
private void logShort(CharSequence message, boolean trim) throws IOException { int length = message.length(); if (trim) { while (length > 0 && Character.isWhitespace(message.charAt(length - 1))) { length--; } } char [] chars = new char [length + 1]; for (int i = 0; i < length; i++) { chars[i] = message.charAt(i); } chars[length] = '\n'; output.write(chars); }
java
private void logShort(CharSequence message, boolean trim) throws IOException { int length = message.length(); if (trim) { while (length > 0 && Character.isWhitespace(message.charAt(length - 1))) { length--; } } char [] chars = new char [length + 1]; for (int i = 0; i < length; i++) { chars[i] = message.charAt(i); } chars[length] = '\n'; output.write(chars); }
[ "private", "void", "logShort", "(", "CharSequence", "message", ",", "boolean", "trim", ")", "throws", "IOException", "{", "int", "length", "=", "message", ".", "length", "(", ")", ";", "if", "(", "trim", ")", "{", "while", "(", "length", ">", "0", "&&", "Character", ".", "isWhitespace", "(", "message", ".", "charAt", "(", "length", "-", "1", ")", ")", ")", "{", "length", "--", ";", "}", "}", "char", "[", "]", "chars", "=", "new", "char", "[", "length", "+", "1", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "chars", "[", "i", "]", "=", "message", ".", "charAt", "(", "i", ")", ";", "}", "chars", "[", "length", "]", "=", "'", "'", ";", "output", ".", "write", "(", "chars", ")", ";", "}" ]
Log a message line to the output.
[ "Log", "a", "message", "line", "to", "the", "output", "." ]
85a0c7eff5d03d98da4d1f9502a11af74d26478a
https://github.com/randomizedtesting/randomizedtesting/blob/85a0c7eff5d03d98da4d1f9502a11af74d26478a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/listeners/TextReport.java#L677-L692
164,402
randomizedtesting/randomizedtesting
junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/aggregated/AggregatedSuiteResultEvent.java
AggregatedSuiteResultEvent.getIgnoredCount
public int getIgnoredCount() { int count = 0; for (AggregatedTestResultEvent t : getTests()) { if (t.getStatus() == TestStatus.IGNORED || t.getStatus() == TestStatus.IGNORED_ASSUMPTION) { count++; } } return count; }
java
public int getIgnoredCount() { int count = 0; for (AggregatedTestResultEvent t : getTests()) { if (t.getStatus() == TestStatus.IGNORED || t.getStatus() == TestStatus.IGNORED_ASSUMPTION) { count++; } } return count; }
[ "public", "int", "getIgnoredCount", "(", ")", "{", "int", "count", "=", "0", ";", "for", "(", "AggregatedTestResultEvent", "t", ":", "getTests", "(", ")", ")", "{", "if", "(", "t", ".", "getStatus", "(", ")", "==", "TestStatus", ".", "IGNORED", "||", "t", ".", "getStatus", "(", ")", "==", "TestStatus", ".", "IGNORED_ASSUMPTION", ")", "{", "count", "++", ";", "}", "}", "return", "count", ";", "}" ]
Return the number of ignored or assumption-ignored tests.
[ "Return", "the", "number", "of", "ignored", "or", "assumption", "-", "ignored", "tests", "." ]
85a0c7eff5d03d98da4d1f9502a11af74d26478a
https://github.com/randomizedtesting/randomizedtesting/blob/85a0c7eff5d03d98da4d1f9502a11af74d26478a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/events/aggregated/AggregatedSuiteResultEvent.java#L153-L162
164,403
randomizedtesting/randomizedtesting
junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/listeners/antxml/AntXmlReport.java
AntXmlReport.onQuit
@Subscribe public void onQuit(AggregatedQuitEvent e) { if (summaryFile != null) { try { Persister persister = new Persister(); persister.write(new MavenFailsafeSummaryModel(summaryListener.getResult()), summaryFile); } catch (Exception x) { junit4.log("Could not serialize summary report.", x, Project.MSG_WARN); } } }
java
@Subscribe public void onQuit(AggregatedQuitEvent e) { if (summaryFile != null) { try { Persister persister = new Persister(); persister.write(new MavenFailsafeSummaryModel(summaryListener.getResult()), summaryFile); } catch (Exception x) { junit4.log("Could not serialize summary report.", x, Project.MSG_WARN); } } }
[ "@", "Subscribe", "public", "void", "onQuit", "(", "AggregatedQuitEvent", "e", ")", "{", "if", "(", "summaryFile", "!=", "null", ")", "{", "try", "{", "Persister", "persister", "=", "new", "Persister", "(", ")", ";", "persister", ".", "write", "(", "new", "MavenFailsafeSummaryModel", "(", "summaryListener", ".", "getResult", "(", ")", ")", ",", "summaryFile", ")", ";", "}", "catch", "(", "Exception", "x", ")", "{", "junit4", ".", "log", "(", "\"Could not serialize summary report.\"", ",", "x", ",", "Project", ".", "MSG_WARN", ")", ";", "}", "}", "}" ]
Write the summary file, if requested.
[ "Write", "the", "summary", "file", "if", "requested", "." ]
85a0c7eff5d03d98da4d1f9502a11af74d26478a
https://github.com/randomizedtesting/randomizedtesting/blob/85a0c7eff5d03d98da4d1f9502a11af74d26478a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/listeners/antxml/AntXmlReport.java#L136-L146
164,404
randomizedtesting/randomizedtesting
junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/listeners/antxml/AntXmlReport.java
AntXmlReport.onSuiteResult
@Subscribe public void onSuiteResult(AggregatedSuiteResultEvent e) { // Calculate summaries. summaryListener.suiteSummary(e); Description suiteDescription = e.getDescription(); String displayName = suiteDescription.getDisplayName(); if (displayName.trim().isEmpty()) { junit4.log("Could not emit XML report for suite (null description).", Project.MSG_WARN); return; } if (!suiteCounts.containsKey(displayName)) { suiteCounts.put(displayName, 1); } else { int newCount = suiteCounts.get(displayName) + 1; suiteCounts.put(displayName, newCount); if (!ignoreDuplicateSuites && newCount == 2) { junit4.log("Duplicate suite name used with XML reports: " + displayName + ". This may confuse tools that process XML reports. " + "Set 'ignoreDuplicateSuites' to true to skip this message.", Project.MSG_WARN); } displayName = displayName + "-" + newCount; } try { File reportFile = new File(dir, "TEST-" + displayName + ".xml"); RegistryMatcher rm = new RegistryMatcher(); rm.bind(String.class, new XmlStringTransformer()); Persister persister = new Persister(rm); persister.write(buildModel(e), reportFile); } catch (Exception x) { junit4.log("Could not serialize report for suite " + displayName + ": " + x.toString(), x, Project.MSG_WARN); } }
java
@Subscribe public void onSuiteResult(AggregatedSuiteResultEvent e) { // Calculate summaries. summaryListener.suiteSummary(e); Description suiteDescription = e.getDescription(); String displayName = suiteDescription.getDisplayName(); if (displayName.trim().isEmpty()) { junit4.log("Could not emit XML report for suite (null description).", Project.MSG_WARN); return; } if (!suiteCounts.containsKey(displayName)) { suiteCounts.put(displayName, 1); } else { int newCount = suiteCounts.get(displayName) + 1; suiteCounts.put(displayName, newCount); if (!ignoreDuplicateSuites && newCount == 2) { junit4.log("Duplicate suite name used with XML reports: " + displayName + ". This may confuse tools that process XML reports. " + "Set 'ignoreDuplicateSuites' to true to skip this message.", Project.MSG_WARN); } displayName = displayName + "-" + newCount; } try { File reportFile = new File(dir, "TEST-" + displayName + ".xml"); RegistryMatcher rm = new RegistryMatcher(); rm.bind(String.class, new XmlStringTransformer()); Persister persister = new Persister(rm); persister.write(buildModel(e), reportFile); } catch (Exception x) { junit4.log("Could not serialize report for suite " + displayName + ": " + x.toString(), x, Project.MSG_WARN); } }
[ "@", "Subscribe", "public", "void", "onSuiteResult", "(", "AggregatedSuiteResultEvent", "e", ")", "{", "// Calculate summaries.", "summaryListener", ".", "suiteSummary", "(", "e", ")", ";", "Description", "suiteDescription", "=", "e", ".", "getDescription", "(", ")", ";", "String", "displayName", "=", "suiteDescription", ".", "getDisplayName", "(", ")", ";", "if", "(", "displayName", ".", "trim", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "junit4", ".", "log", "(", "\"Could not emit XML report for suite (null description).\"", ",", "Project", ".", "MSG_WARN", ")", ";", "return", ";", "}", "if", "(", "!", "suiteCounts", ".", "containsKey", "(", "displayName", ")", ")", "{", "suiteCounts", ".", "put", "(", "displayName", ",", "1", ")", ";", "}", "else", "{", "int", "newCount", "=", "suiteCounts", ".", "get", "(", "displayName", ")", "+", "1", ";", "suiteCounts", ".", "put", "(", "displayName", ",", "newCount", ")", ";", "if", "(", "!", "ignoreDuplicateSuites", "&&", "newCount", "==", "2", ")", "{", "junit4", ".", "log", "(", "\"Duplicate suite name used with XML reports: \"", "+", "displayName", "+", "\". This may confuse tools that process XML reports. \"", "+", "\"Set 'ignoreDuplicateSuites' to true to skip this message.\"", ",", "Project", ".", "MSG_WARN", ")", ";", "}", "displayName", "=", "displayName", "+", "\"-\"", "+", "newCount", ";", "}", "try", "{", "File", "reportFile", "=", "new", "File", "(", "dir", ",", "\"TEST-\"", "+", "displayName", "+", "\".xml\"", ")", ";", "RegistryMatcher", "rm", "=", "new", "RegistryMatcher", "(", ")", ";", "rm", ".", "bind", "(", "String", ".", "class", ",", "new", "XmlStringTransformer", "(", ")", ")", ";", "Persister", "persister", "=", "new", "Persister", "(", "rm", ")", ";", "persister", ".", "write", "(", "buildModel", "(", "e", ")", ",", "reportFile", ")", ";", "}", "catch", "(", "Exception", "x", ")", "{", "junit4", ".", "log", "(", "\"Could not serialize report for suite \"", "+", "displayName", "+", "\": \"", "+", "x", ".", "toString", "(", ")", ",", "x", ",", "Project", ".", "MSG_WARN", ")", ";", "}", "}" ]
Emit information about all of suite's tests.
[ "Emit", "information", "about", "all", "of", "suite", "s", "tests", "." ]
85a0c7eff5d03d98da4d1f9502a11af74d26478a
https://github.com/randomizedtesting/randomizedtesting/blob/85a0c7eff5d03d98da4d1f9502a11af74d26478a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/listeners/antxml/AntXmlReport.java#L151-L187
164,405
randomizedtesting/randomizedtesting
junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/listeners/antxml/AntXmlReport.java
AntXmlReport.buildModel
private TestSuiteModel buildModel(AggregatedSuiteResultEvent e) throws IOException { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ROOT); TestSuiteModel suite = new TestSuiteModel(); suite.hostname = "nohost.nodomain"; suite.name = e.getDescription().getDisplayName(); suite.properties = buildModel(e.getSlave().getSystemProperties()); suite.time = e.getExecutionTime() / 1000.0; suite.timestamp = df.format(new Date(e.getStartTimestamp())); suite.testcases = buildModel(e.getTests()); suite.tests = suite.testcases.size(); if (mavenExtensions) { suite.skipped = 0; } // Suite-level failures and errors are simulated as test cases. for (FailureMirror m : e.getFailures()) { TestCaseModel model = new TestCaseModel(); model.classname = "junit.framework.TestSuite"; // empirical ANT output. model.name = applyFilters(m.getDescription().getClassName()); model.time = 0; if (m.isAssertionViolation()) { model.failures.add(buildModel(m)); } else { model.errors.add(buildModel(m)); } suite.testcases.add(model); } // Calculate test numbers that match limited view (no ignored tests, // faked suite-level errors). for (TestCaseModel tc : suite.testcases) { suite.errors += tc.errors.size(); suite.failures += tc.failures.size(); if (mavenExtensions && tc.skipped != null) { suite.skipped += 1; } } StringWriter sysout = new StringWriter(); StringWriter syserr = new StringWriter(); if (outputStreams) { e.getSlave().decodeStreams(e.getEventStream(), sysout, syserr); } suite.sysout = sysout.toString(); suite.syserr = syserr.toString(); return suite; }
java
private TestSuiteModel buildModel(AggregatedSuiteResultEvent e) throws IOException { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ROOT); TestSuiteModel suite = new TestSuiteModel(); suite.hostname = "nohost.nodomain"; suite.name = e.getDescription().getDisplayName(); suite.properties = buildModel(e.getSlave().getSystemProperties()); suite.time = e.getExecutionTime() / 1000.0; suite.timestamp = df.format(new Date(e.getStartTimestamp())); suite.testcases = buildModel(e.getTests()); suite.tests = suite.testcases.size(); if (mavenExtensions) { suite.skipped = 0; } // Suite-level failures and errors are simulated as test cases. for (FailureMirror m : e.getFailures()) { TestCaseModel model = new TestCaseModel(); model.classname = "junit.framework.TestSuite"; // empirical ANT output. model.name = applyFilters(m.getDescription().getClassName()); model.time = 0; if (m.isAssertionViolation()) { model.failures.add(buildModel(m)); } else { model.errors.add(buildModel(m)); } suite.testcases.add(model); } // Calculate test numbers that match limited view (no ignored tests, // faked suite-level errors). for (TestCaseModel tc : suite.testcases) { suite.errors += tc.errors.size(); suite.failures += tc.failures.size(); if (mavenExtensions && tc.skipped != null) { suite.skipped += 1; } } StringWriter sysout = new StringWriter(); StringWriter syserr = new StringWriter(); if (outputStreams) { e.getSlave().decodeStreams(e.getEventStream(), sysout, syserr); } suite.sysout = sysout.toString(); suite.syserr = syserr.toString(); return suite; }
[ "private", "TestSuiteModel", "buildModel", "(", "AggregatedSuiteResultEvent", "e", ")", "throws", "IOException", "{", "SimpleDateFormat", "df", "=", "new", "SimpleDateFormat", "(", "\"yyyy-MM-dd'T'HH:mm:ss\"", ",", "Locale", ".", "ROOT", ")", ";", "TestSuiteModel", "suite", "=", "new", "TestSuiteModel", "(", ")", ";", "suite", ".", "hostname", "=", "\"nohost.nodomain\"", ";", "suite", ".", "name", "=", "e", ".", "getDescription", "(", ")", ".", "getDisplayName", "(", ")", ";", "suite", ".", "properties", "=", "buildModel", "(", "e", ".", "getSlave", "(", ")", ".", "getSystemProperties", "(", ")", ")", ";", "suite", ".", "time", "=", "e", ".", "getExecutionTime", "(", ")", "/", "1000.0", ";", "suite", ".", "timestamp", "=", "df", ".", "format", "(", "new", "Date", "(", "e", ".", "getStartTimestamp", "(", ")", ")", ")", ";", "suite", ".", "testcases", "=", "buildModel", "(", "e", ".", "getTests", "(", ")", ")", ";", "suite", ".", "tests", "=", "suite", ".", "testcases", ".", "size", "(", ")", ";", "if", "(", "mavenExtensions", ")", "{", "suite", ".", "skipped", "=", "0", ";", "}", "// Suite-level failures and errors are simulated as test cases.", "for", "(", "FailureMirror", "m", ":", "e", ".", "getFailures", "(", ")", ")", "{", "TestCaseModel", "model", "=", "new", "TestCaseModel", "(", ")", ";", "model", ".", "classname", "=", "\"junit.framework.TestSuite\"", ";", "// empirical ANT output.", "model", ".", "name", "=", "applyFilters", "(", "m", ".", "getDescription", "(", ")", ".", "getClassName", "(", ")", ")", ";", "model", ".", "time", "=", "0", ";", "if", "(", "m", ".", "isAssertionViolation", "(", ")", ")", "{", "model", ".", "failures", ".", "add", "(", "buildModel", "(", "m", ")", ")", ";", "}", "else", "{", "model", ".", "errors", ".", "add", "(", "buildModel", "(", "m", ")", ")", ";", "}", "suite", ".", "testcases", ".", "add", "(", "model", ")", ";", "}", "// Calculate test numbers that match limited view (no ignored tests, ", "// faked suite-level errors).", "for", "(", "TestCaseModel", "tc", ":", "suite", ".", "testcases", ")", "{", "suite", ".", "errors", "+=", "tc", ".", "errors", ".", "size", "(", ")", ";", "suite", ".", "failures", "+=", "tc", ".", "failures", ".", "size", "(", ")", ";", "if", "(", "mavenExtensions", "&&", "tc", ".", "skipped", "!=", "null", ")", "{", "suite", ".", "skipped", "+=", "1", ";", "}", "}", "StringWriter", "sysout", "=", "new", "StringWriter", "(", ")", ";", "StringWriter", "syserr", "=", "new", "StringWriter", "(", ")", ";", "if", "(", "outputStreams", ")", "{", "e", ".", "getSlave", "(", ")", ".", "decodeStreams", "(", "e", ".", "getEventStream", "(", ")", ",", "sysout", ",", "syserr", ")", ";", "}", "suite", ".", "sysout", "=", "sysout", ".", "toString", "(", ")", ";", "suite", ".", "syserr", "=", "syserr", ".", "toString", "(", ")", ";", "return", "suite", ";", "}" ]
Build data model for serialization.
[ "Build", "data", "model", "for", "serialization", "." ]
85a0c7eff5d03d98da4d1f9502a11af74d26478a
https://github.com/randomizedtesting/randomizedtesting/blob/85a0c7eff5d03d98da4d1f9502a11af74d26478a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/listeners/antxml/AntXmlReport.java#L192-L242
164,406
randomizedtesting/randomizedtesting
junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/listeners/antxml/AntXmlReport.java
AntXmlReport.applyFilters
private String applyFilters(String methodName) { if (filters.isEmpty()) { return methodName; } Reader in = new StringReader(methodName); for (TokenFilter tf : filters) { in = tf.chain(in); } try { return CharStreams.toString(in); } catch (IOException e) { junit4.log("Could not apply filters to " + methodName + ": " + Throwables.getStackTraceAsString(e), Project.MSG_WARN); return methodName; } }
java
private String applyFilters(String methodName) { if (filters.isEmpty()) { return methodName; } Reader in = new StringReader(methodName); for (TokenFilter tf : filters) { in = tf.chain(in); } try { return CharStreams.toString(in); } catch (IOException e) { junit4.log("Could not apply filters to " + methodName + ": " + Throwables.getStackTraceAsString(e), Project.MSG_WARN); return methodName; } }
[ "private", "String", "applyFilters", "(", "String", "methodName", ")", "{", "if", "(", "filters", ".", "isEmpty", "(", ")", ")", "{", "return", "methodName", ";", "}", "Reader", "in", "=", "new", "StringReader", "(", "methodName", ")", ";", "for", "(", "TokenFilter", "tf", ":", "filters", ")", "{", "in", "=", "tf", ".", "chain", "(", "in", ")", ";", "}", "try", "{", "return", "CharStreams", ".", "toString", "(", "in", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "junit4", ".", "log", "(", "\"Could not apply filters to \"", "+", "methodName", "+", "\": \"", "+", "Throwables", ".", "getStackTraceAsString", "(", "e", ")", ",", "Project", ".", "MSG_WARN", ")", ";", "return", "methodName", ";", "}", "}" ]
Apply filters to a method name. @param methodName
[ "Apply", "filters", "to", "a", "method", "name", "." ]
85a0c7eff5d03d98da4d1f9502a11af74d26478a
https://github.com/randomizedtesting/randomizedtesting/blob/85a0c7eff5d03d98da4d1f9502a11af74d26478a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/listeners/antxml/AntXmlReport.java#L285-L302
164,407
randomizedtesting/randomizedtesting
junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/LocalSlaveStreamHandler.java
LocalSlaveStreamHandler.pumpEvents
void pumpEvents(InputStream eventStream) { try { Deserializer deserializer = new Deserializer(eventStream, refLoader); IEvent event = null; while ((event = deserializer.deserialize()) != null) { switch (event.getType()) { case APPEND_STDERR: case APPEND_STDOUT: // Ignore these two on activity heartbeats. GH-117 break; default: lastActivity = System.currentTimeMillis(); break; } try { switch (event.getType()) { case QUIT: eventBus.post(event); return; case IDLE: eventBus.post(new SlaveIdle(stdinWriter)); break; case BOOTSTRAP: clientCharset = Charset.forName(((BootstrapEvent) event).getDefaultCharsetName()); stdinWriter = new OutputStreamWriter(stdin, clientCharset); eventBus.post(event); break; case APPEND_STDERR: case APPEND_STDOUT: assert streamsBuffer.getFilePointer() == streamsBuffer.length(); final long bufferStart = streamsBuffer.getFilePointer(); IStreamEvent streamEvent = (IStreamEvent) event; streamEvent.copyTo(streamsBufferWrapper); final long bufferEnd = streamsBuffer.getFilePointer(); event = new OnDiskStreamEvent(event.getType(), streamsBuffer, bufferStart, bufferEnd); eventBus.post(event); break; default: eventBus.post(event); } } catch (Throwable t) { warnStream.println("Event bus dispatch error: " + t.toString()); t.printStackTrace(warnStream); } } lastActivity = null; } catch (Throwable e) { if (!stopping) { warnStream.println("Event stream error: " + e.toString()); e.printStackTrace(warnStream); } } }
java
void pumpEvents(InputStream eventStream) { try { Deserializer deserializer = new Deserializer(eventStream, refLoader); IEvent event = null; while ((event = deserializer.deserialize()) != null) { switch (event.getType()) { case APPEND_STDERR: case APPEND_STDOUT: // Ignore these two on activity heartbeats. GH-117 break; default: lastActivity = System.currentTimeMillis(); break; } try { switch (event.getType()) { case QUIT: eventBus.post(event); return; case IDLE: eventBus.post(new SlaveIdle(stdinWriter)); break; case BOOTSTRAP: clientCharset = Charset.forName(((BootstrapEvent) event).getDefaultCharsetName()); stdinWriter = new OutputStreamWriter(stdin, clientCharset); eventBus.post(event); break; case APPEND_STDERR: case APPEND_STDOUT: assert streamsBuffer.getFilePointer() == streamsBuffer.length(); final long bufferStart = streamsBuffer.getFilePointer(); IStreamEvent streamEvent = (IStreamEvent) event; streamEvent.copyTo(streamsBufferWrapper); final long bufferEnd = streamsBuffer.getFilePointer(); event = new OnDiskStreamEvent(event.getType(), streamsBuffer, bufferStart, bufferEnd); eventBus.post(event); break; default: eventBus.post(event); } } catch (Throwable t) { warnStream.println("Event bus dispatch error: " + t.toString()); t.printStackTrace(warnStream); } } lastActivity = null; } catch (Throwable e) { if (!stopping) { warnStream.println("Event stream error: " + e.toString()); e.printStackTrace(warnStream); } } }
[ "void", "pumpEvents", "(", "InputStream", "eventStream", ")", "{", "try", "{", "Deserializer", "deserializer", "=", "new", "Deserializer", "(", "eventStream", ",", "refLoader", ")", ";", "IEvent", "event", "=", "null", ";", "while", "(", "(", "event", "=", "deserializer", ".", "deserialize", "(", ")", ")", "!=", "null", ")", "{", "switch", "(", "event", ".", "getType", "(", ")", ")", "{", "case", "APPEND_STDERR", ":", "case", "APPEND_STDOUT", ":", "// Ignore these two on activity heartbeats. GH-117", "break", ";", "default", ":", "lastActivity", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "break", ";", "}", "try", "{", "switch", "(", "event", ".", "getType", "(", ")", ")", "{", "case", "QUIT", ":", "eventBus", ".", "post", "(", "event", ")", ";", "return", ";", "case", "IDLE", ":", "eventBus", ".", "post", "(", "new", "SlaveIdle", "(", "stdinWriter", ")", ")", ";", "break", ";", "case", "BOOTSTRAP", ":", "clientCharset", "=", "Charset", ".", "forName", "(", "(", "(", "BootstrapEvent", ")", "event", ")", ".", "getDefaultCharsetName", "(", ")", ")", ";", "stdinWriter", "=", "new", "OutputStreamWriter", "(", "stdin", ",", "clientCharset", ")", ";", "eventBus", ".", "post", "(", "event", ")", ";", "break", ";", "case", "APPEND_STDERR", ":", "case", "APPEND_STDOUT", ":", "assert", "streamsBuffer", ".", "getFilePointer", "(", ")", "==", "streamsBuffer", ".", "length", "(", ")", ";", "final", "long", "bufferStart", "=", "streamsBuffer", ".", "getFilePointer", "(", ")", ";", "IStreamEvent", "streamEvent", "=", "(", "IStreamEvent", ")", "event", ";", "streamEvent", ".", "copyTo", "(", "streamsBufferWrapper", ")", ";", "final", "long", "bufferEnd", "=", "streamsBuffer", ".", "getFilePointer", "(", ")", ";", "event", "=", "new", "OnDiskStreamEvent", "(", "event", ".", "getType", "(", ")", ",", "streamsBuffer", ",", "bufferStart", ",", "bufferEnd", ")", ";", "eventBus", ".", "post", "(", "event", ")", ";", "break", ";", "default", ":", "eventBus", ".", "post", "(", "event", ")", ";", "}", "}", "catch", "(", "Throwable", "t", ")", "{", "warnStream", ".", "println", "(", "\"Event bus dispatch error: \"", "+", "t", ".", "toString", "(", ")", ")", ";", "t", ".", "printStackTrace", "(", "warnStream", ")", ";", "}", "}", "lastActivity", "=", "null", ";", "}", "catch", "(", "Throwable", "e", ")", "{", "if", "(", "!", "stopping", ")", "{", "warnStream", ".", "println", "(", "\"Event stream error: \"", "+", "e", ".", "toString", "(", ")", ")", ";", "e", ".", "printStackTrace", "(", "warnStream", ")", ";", "}", "}", "}" ]
Pump events from event stream.
[ "Pump", "events", "from", "event", "stream", "." ]
85a0c7eff5d03d98da4d1f9502a11af74d26478a
https://github.com/randomizedtesting/randomizedtesting/blob/85a0c7eff5d03d98da4d1f9502a11af74d26478a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/LocalSlaveStreamHandler.java#L215-L274
164,408
randomizedtesting/randomizedtesting
junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/listeners/ExecutionTimesReport.java
ExecutionTimesReport.onSuiteResult
@Subscribe public void onSuiteResult(AggregatedSuiteResultEvent e) { long millis = e.getExecutionTime(); String suiteName = e.getDescription().getDisplayName(); List<Long> values = hints.get(suiteName); if (values == null) { hints.put(suiteName, values = new ArrayList<>()); } values.add(millis); while (values.size() > historyLength) values.remove(0); }
java
@Subscribe public void onSuiteResult(AggregatedSuiteResultEvent e) { long millis = e.getExecutionTime(); String suiteName = e.getDescription().getDisplayName(); List<Long> values = hints.get(suiteName); if (values == null) { hints.put(suiteName, values = new ArrayList<>()); } values.add(millis); while (values.size() > historyLength) values.remove(0); }
[ "@", "Subscribe", "public", "void", "onSuiteResult", "(", "AggregatedSuiteResultEvent", "e", ")", "{", "long", "millis", "=", "e", ".", "getExecutionTime", "(", ")", ";", "String", "suiteName", "=", "e", ".", "getDescription", "(", ")", ".", "getDisplayName", "(", ")", ";", "List", "<", "Long", ">", "values", "=", "hints", ".", "get", "(", "suiteName", ")", ";", "if", "(", "values", "==", "null", ")", "{", "hints", ".", "put", "(", "suiteName", ",", "values", "=", "new", "ArrayList", "<>", "(", ")", ")", ";", "}", "values", ".", "add", "(", "millis", ")", ";", "while", "(", "values", ".", "size", "(", ")", ">", "historyLength", ")", "values", ".", "remove", "(", "0", ")", ";", "}" ]
Remember execution time for all executed suites.
[ "Remember", "execution", "time", "for", "all", "executed", "suites", "." ]
85a0c7eff5d03d98da4d1f9502a11af74d26478a
https://github.com/randomizedtesting/randomizedtesting/blob/85a0c7eff5d03d98da4d1f9502a11af74d26478a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/listeners/ExecutionTimesReport.java#L83-L95
164,409
randomizedtesting/randomizedtesting
junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/listeners/ExecutionTimesReport.java
ExecutionTimesReport.onEnd
@Subscribe public void onEnd(AggregatedQuitEvent e) { try { writeHints(hintsFile, hints); } catch (IOException exception) { outer.log("Could not write back the hints file.", exception, Project.MSG_ERR); } }
java
@Subscribe public void onEnd(AggregatedQuitEvent e) { try { writeHints(hintsFile, hints); } catch (IOException exception) { outer.log("Could not write back the hints file.", exception, Project.MSG_ERR); } }
[ "@", "Subscribe", "public", "void", "onEnd", "(", "AggregatedQuitEvent", "e", ")", "{", "try", "{", "writeHints", "(", "hintsFile", ",", "hints", ")", ";", "}", "catch", "(", "IOException", "exception", ")", "{", "outer", ".", "log", "(", "\"Could not write back the hints file.\"", ",", "exception", ",", "Project", ".", "MSG_ERR", ")", ";", "}", "}" ]
Write back to hints file.
[ "Write", "back", "to", "hints", "file", "." ]
85a0c7eff5d03d98da4d1f9502a11af74d26478a
https://github.com/randomizedtesting/randomizedtesting/blob/85a0c7eff5d03d98da4d1f9502a11af74d26478a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/listeners/ExecutionTimesReport.java#L100-L107
164,410
randomizedtesting/randomizedtesting
junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/listeners/ExecutionTimesReport.java
ExecutionTimesReport.readHints
public static Map<String,List<Long>> readHints(File hints) throws IOException { Map<String,List<Long>> result = new HashMap<>(); InputStream is = new FileInputStream(hints); mergeHints(is, result); return result; }
java
public static Map<String,List<Long>> readHints(File hints) throws IOException { Map<String,List<Long>> result = new HashMap<>(); InputStream is = new FileInputStream(hints); mergeHints(is, result); return result; }
[ "public", "static", "Map", "<", "String", ",", "List", "<", "Long", ">", ">", "readHints", "(", "File", "hints", ")", "throws", "IOException", "{", "Map", "<", "String", ",", "List", "<", "Long", ">", ">", "result", "=", "new", "HashMap", "<>", "(", ")", ";", "InputStream", "is", "=", "new", "FileInputStream", "(", "hints", ")", ";", "mergeHints", "(", "is", ",", "result", ")", ";", "return", "result", ";", "}" ]
Read hints from a file.
[ "Read", "hints", "from", "a", "file", "." ]
85a0c7eff5d03d98da4d1f9502a11af74d26478a
https://github.com/randomizedtesting/randomizedtesting/blob/85a0c7eff5d03d98da4d1f9502a11af74d26478a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/listeners/ExecutionTimesReport.java#L137-L142
164,411
randomizedtesting/randomizedtesting
junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/listeners/ExecutionTimesReport.java
ExecutionTimesReport.mergeHints
public static void mergeHints(InputStream is, Map<String,List<Long>> hints) throws IOException { final BufferedReader reader = new BufferedReader( new InputStreamReader(is, Charsets.UTF_8)); String line; while ((line = reader.readLine()) != null) { line = line.trim(); if (line.isEmpty() || line.startsWith("#")) continue; final int equals = line.indexOf('='); if (equals <= 0) { throw new IOException("No '=' character on a non-comment line?: " + line); } else { String key = line.substring(0, equals); List<Long> values = hints.get(key); if (values == null) { hints.put(key, values = new ArrayList<>()); } for (String v : line.substring(equals + 1).split("[\\,]")) { if (!v.isEmpty()) values.add(Long.parseLong(v)); } } } }
java
public static void mergeHints(InputStream is, Map<String,List<Long>> hints) throws IOException { final BufferedReader reader = new BufferedReader( new InputStreamReader(is, Charsets.UTF_8)); String line; while ((line = reader.readLine()) != null) { line = line.trim(); if (line.isEmpty() || line.startsWith("#")) continue; final int equals = line.indexOf('='); if (equals <= 0) { throw new IOException("No '=' character on a non-comment line?: " + line); } else { String key = line.substring(0, equals); List<Long> values = hints.get(key); if (values == null) { hints.put(key, values = new ArrayList<>()); } for (String v : line.substring(equals + 1).split("[\\,]")) { if (!v.isEmpty()) values.add(Long.parseLong(v)); } } } }
[ "public", "static", "void", "mergeHints", "(", "InputStream", "is", ",", "Map", "<", "String", ",", "List", "<", "Long", ">", ">", "hints", ")", "throws", "IOException", "{", "final", "BufferedReader", "reader", "=", "new", "BufferedReader", "(", "new", "InputStreamReader", "(", "is", ",", "Charsets", ".", "UTF_8", ")", ")", ";", "String", "line", ";", "while", "(", "(", "line", "=", "reader", ".", "readLine", "(", ")", ")", "!=", "null", ")", "{", "line", "=", "line", ".", "trim", "(", ")", ";", "if", "(", "line", ".", "isEmpty", "(", ")", "||", "line", ".", "startsWith", "(", "\"#\"", ")", ")", "continue", ";", "final", "int", "equals", "=", "line", ".", "indexOf", "(", "'", "'", ")", ";", "if", "(", "equals", "<=", "0", ")", "{", "throw", "new", "IOException", "(", "\"No '=' character on a non-comment line?: \"", "+", "line", ")", ";", "}", "else", "{", "String", "key", "=", "line", ".", "substring", "(", "0", ",", "equals", ")", ";", "List", "<", "Long", ">", "values", "=", "hints", ".", "get", "(", "key", ")", ";", "if", "(", "values", "==", "null", ")", "{", "hints", ".", "put", "(", "key", ",", "values", "=", "new", "ArrayList", "<>", "(", ")", ")", ";", "}", "for", "(", "String", "v", ":", "line", ".", "substring", "(", "equals", "+", "1", ")", ".", "split", "(", "\"[\\\\,]\"", ")", ")", "{", "if", "(", "!", "v", ".", "isEmpty", "(", ")", ")", "values", ".", "add", "(", "Long", ".", "parseLong", "(", "v", ")", ")", ";", "}", "}", "}", "}" ]
Read hints from a file and merge with the given hints map.
[ "Read", "hints", "from", "a", "file", "and", "merge", "with", "the", "given", "hints", "map", "." ]
85a0c7eff5d03d98da4d1f9502a11af74d26478a
https://github.com/randomizedtesting/randomizedtesting/blob/85a0c7eff5d03d98da4d1f9502a11af74d26478a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/listeners/ExecutionTimesReport.java#L147-L171
164,412
randomizedtesting/randomizedtesting
junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/listeners/ExecutionTimesReport.java
ExecutionTimesReport.writeHints
public static void writeHints(File file, Map<String,List<Long>> hints) throws IOException { Closer closer = Closer.create(); try { BufferedWriter w = closer.register(Files.newWriter(file, Charsets.UTF_8)); if (!(hints instanceof SortedMap)) { hints = new TreeMap<String,List<Long>>(hints); } Joiner joiner = Joiner.on(','); for (Map.Entry<String,List<Long>> e : hints.entrySet()) { w.write(e.getKey()); w.write("="); joiner.appendTo(w, e.getValue()); w.write("\n"); } } catch (Throwable t) { throw closer.rethrow(t); } finally { closer.close(); } }
java
public static void writeHints(File file, Map<String,List<Long>> hints) throws IOException { Closer closer = Closer.create(); try { BufferedWriter w = closer.register(Files.newWriter(file, Charsets.UTF_8)); if (!(hints instanceof SortedMap)) { hints = new TreeMap<String,List<Long>>(hints); } Joiner joiner = Joiner.on(','); for (Map.Entry<String,List<Long>> e : hints.entrySet()) { w.write(e.getKey()); w.write("="); joiner.appendTo(w, e.getValue()); w.write("\n"); } } catch (Throwable t) { throw closer.rethrow(t); } finally { closer.close(); } }
[ "public", "static", "void", "writeHints", "(", "File", "file", ",", "Map", "<", "String", ",", "List", "<", "Long", ">", ">", "hints", ")", "throws", "IOException", "{", "Closer", "closer", "=", "Closer", ".", "create", "(", ")", ";", "try", "{", "BufferedWriter", "w", "=", "closer", ".", "register", "(", "Files", ".", "newWriter", "(", "file", ",", "Charsets", ".", "UTF_8", ")", ")", ";", "if", "(", "!", "(", "hints", "instanceof", "SortedMap", ")", ")", "{", "hints", "=", "new", "TreeMap", "<", "String", ",", "List", "<", "Long", ">", ">", "(", "hints", ")", ";", "}", "Joiner", "joiner", "=", "Joiner", ".", "on", "(", "'", "'", ")", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "List", "<", "Long", ">", ">", "e", ":", "hints", ".", "entrySet", "(", ")", ")", "{", "w", ".", "write", "(", "e", ".", "getKey", "(", ")", ")", ";", "w", ".", "write", "(", "\"=\"", ")", ";", "joiner", ".", "appendTo", "(", "w", ",", "e", ".", "getValue", "(", ")", ")", ";", "w", ".", "write", "(", "\"\\n\"", ")", ";", "}", "}", "catch", "(", "Throwable", "t", ")", "{", "throw", "closer", ".", "rethrow", "(", "t", ")", ";", "}", "finally", "{", "closer", ".", "close", "(", ")", ";", "}", "}" ]
Writes back hints file.
[ "Writes", "back", "hints", "file", "." ]
85a0c7eff5d03d98da4d1f9502a11af74d26478a
https://github.com/randomizedtesting/randomizedtesting/blob/85a0c7eff5d03d98da4d1f9502a11af74d26478a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/listeners/ExecutionTimesReport.java#L176-L196
164,413
randomizedtesting/randomizedtesting
junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/slave/SlaveMain.java
SlaveMain.readArgsFile
private static String[] readArgsFile(String argsFile) throws IOException { final ArrayList<String> lines = new ArrayList<String>(); final BufferedReader reader = new BufferedReader( new InputStreamReader( new FileInputStream(argsFile), "UTF-8")); try { String line; while ((line = reader.readLine()) != null) { line = line.trim(); if (!line.isEmpty() && !line.startsWith("#")) { lines.add(line); } } } finally { reader.close(); } return lines.toArray(new String [lines.size()]); }
java
private static String[] readArgsFile(String argsFile) throws IOException { final ArrayList<String> lines = new ArrayList<String>(); final BufferedReader reader = new BufferedReader( new InputStreamReader( new FileInputStream(argsFile), "UTF-8")); try { String line; while ((line = reader.readLine()) != null) { line = line.trim(); if (!line.isEmpty() && !line.startsWith("#")) { lines.add(line); } } } finally { reader.close(); } return lines.toArray(new String [lines.size()]); }
[ "private", "static", "String", "[", "]", "readArgsFile", "(", "String", "argsFile", ")", "throws", "IOException", "{", "final", "ArrayList", "<", "String", ">", "lines", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "final", "BufferedReader", "reader", "=", "new", "BufferedReader", "(", "new", "InputStreamReader", "(", "new", "FileInputStream", "(", "argsFile", ")", ",", "\"UTF-8\"", ")", ")", ";", "try", "{", "String", "line", ";", "while", "(", "(", "line", "=", "reader", ".", "readLine", "(", ")", ")", "!=", "null", ")", "{", "line", "=", "line", ".", "trim", "(", ")", ";", "if", "(", "!", "line", ".", "isEmpty", "(", ")", "&&", "!", "line", ".", "startsWith", "(", "\"#\"", ")", ")", "{", "lines", ".", "add", "(", "line", ")", ";", "}", "}", "}", "finally", "{", "reader", ".", "close", "(", ")", ";", "}", "return", "lines", ".", "toArray", "(", "new", "String", "[", "lines", ".", "size", "(", ")", "]", ")", ";", "}" ]
Read arguments from a file. Newline delimited, UTF-8 encoded. No fanciness to avoid dependencies.
[ "Read", "arguments", "from", "a", "file", ".", "Newline", "delimited", "UTF", "-", "8", "encoded", ".", "No", "fanciness", "to", "avoid", "dependencies", "." ]
85a0c7eff5d03d98da4d1f9502a11af74d26478a
https://github.com/randomizedtesting/randomizedtesting/blob/85a0c7eff5d03d98da4d1f9502a11af74d26478a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/slave/SlaveMain.java#L448-L465
164,414
randomizedtesting/randomizedtesting
junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/slave/SlaveMain.java
SlaveMain.redirectStreams
@SuppressForbidden("legitimate sysstreams.") private static void redirectStreams(final Serializer serializer, final boolean flushFrequently) { final PrintStream origSysOut = System.out; final PrintStream origSysErr = System.err; // Set warnings stream to System.err. warnings = System.err; AccessController.doPrivileged(new PrivilegedAction<Void>() { @SuppressForbidden("legitimate PrintStream with default charset.") @Override public Void run() { System.setOut(new PrintStream(new BufferedOutputStream(new ChunkedStream() { @Override public void write(byte[] b, int off, int len) throws IOException { if (multiplexStdStreams) { origSysOut.write(b, off, len); } serializer.serialize(new AppendStdOutEvent(b, off, len)); if (flushFrequently) serializer.flush(); } }))); System.setErr(new PrintStream(new BufferedOutputStream(new ChunkedStream() { @Override public void write(byte[] b, int off, int len) throws IOException { if (multiplexStdStreams) { origSysErr.write(b, off, len); } serializer.serialize(new AppendStdErrEvent(b, off, len)); if (flushFrequently) serializer.flush(); } }))); return null; } }); }
java
@SuppressForbidden("legitimate sysstreams.") private static void redirectStreams(final Serializer serializer, final boolean flushFrequently) { final PrintStream origSysOut = System.out; final PrintStream origSysErr = System.err; // Set warnings stream to System.err. warnings = System.err; AccessController.doPrivileged(new PrivilegedAction<Void>() { @SuppressForbidden("legitimate PrintStream with default charset.") @Override public Void run() { System.setOut(new PrintStream(new BufferedOutputStream(new ChunkedStream() { @Override public void write(byte[] b, int off, int len) throws IOException { if (multiplexStdStreams) { origSysOut.write(b, off, len); } serializer.serialize(new AppendStdOutEvent(b, off, len)); if (flushFrequently) serializer.flush(); } }))); System.setErr(new PrintStream(new BufferedOutputStream(new ChunkedStream() { @Override public void write(byte[] b, int off, int len) throws IOException { if (multiplexStdStreams) { origSysErr.write(b, off, len); } serializer.serialize(new AppendStdErrEvent(b, off, len)); if (flushFrequently) serializer.flush(); } }))); return null; } }); }
[ "@", "SuppressForbidden", "(", "\"legitimate sysstreams.\"", ")", "private", "static", "void", "redirectStreams", "(", "final", "Serializer", "serializer", ",", "final", "boolean", "flushFrequently", ")", "{", "final", "PrintStream", "origSysOut", "=", "System", ".", "out", ";", "final", "PrintStream", "origSysErr", "=", "System", ".", "err", ";", "// Set warnings stream to System.err.", "warnings", "=", "System", ".", "err", ";", "AccessController", ".", "doPrivileged", "(", "new", "PrivilegedAction", "<", "Void", ">", "(", ")", "{", "@", "SuppressForbidden", "(", "\"legitimate PrintStream with default charset.\"", ")", "@", "Override", "public", "Void", "run", "(", ")", "{", "System", ".", "setOut", "(", "new", "PrintStream", "(", "new", "BufferedOutputStream", "(", "new", "ChunkedStream", "(", ")", "{", "@", "Override", "public", "void", "write", "(", "byte", "[", "]", "b", ",", "int", "off", ",", "int", "len", ")", "throws", "IOException", "{", "if", "(", "multiplexStdStreams", ")", "{", "origSysOut", ".", "write", "(", "b", ",", "off", ",", "len", ")", ";", "}", "serializer", ".", "serialize", "(", "new", "AppendStdOutEvent", "(", "b", ",", "off", ",", "len", ")", ")", ";", "if", "(", "flushFrequently", ")", "serializer", ".", "flush", "(", ")", ";", "}", "}", ")", ")", ")", ";", "System", ".", "setErr", "(", "new", "PrintStream", "(", "new", "BufferedOutputStream", "(", "new", "ChunkedStream", "(", ")", "{", "@", "Override", "public", "void", "write", "(", "byte", "[", "]", "b", ",", "int", "off", ",", "int", "len", ")", "throws", "IOException", "{", "if", "(", "multiplexStdStreams", ")", "{", "origSysErr", ".", "write", "(", "b", ",", "off", ",", "len", ")", ";", "}", "serializer", ".", "serialize", "(", "new", "AppendStdErrEvent", "(", "b", ",", "off", ",", "len", ")", ")", ";", "if", "(", "flushFrequently", ")", "serializer", ".", "flush", "(", ")", ";", "}", "}", ")", ")", ")", ";", "return", "null", ";", "}", "}", ")", ";", "}" ]
Redirect standard streams so that the output can be passed to listeners.
[ "Redirect", "standard", "streams", "so", "that", "the", "output", "can", "be", "passed", "to", "listeners", "." ]
85a0c7eff5d03d98da4d1f9502a11af74d26478a
https://github.com/randomizedtesting/randomizedtesting/blob/85a0c7eff5d03d98da4d1f9502a11af74d26478a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/slave/SlaveMain.java#L470-L505
164,415
randomizedtesting/randomizedtesting
junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/slave/SlaveMain.java
SlaveMain.warn
@SuppressForbidden("legitimate sysstreams.") public static void warn(String message, Throwable t) { PrintStream w = (warnings == null ? System.err : warnings); try { w.print("WARN: "); w.print(message); if (t != null) { w.print(" -> "); try { t.printStackTrace(w); } catch (OutOfMemoryError e) { // Ignore, OOM. w.print(t.getClass().getName()); w.print(": "); w.print(t.getMessage()); w.println(" (stack unavailable; OOM)"); } } else { w.println(); } w.flush(); } catch (OutOfMemoryError t2) { w.println("ERROR: Couldn't even serialize a warning (out of memory)."); } catch (Throwable t2) { // Can't do anything, really. Probably an OOM? w.println("ERROR: Couldn't even serialize a warning."); } }
java
@SuppressForbidden("legitimate sysstreams.") public static void warn(String message, Throwable t) { PrintStream w = (warnings == null ? System.err : warnings); try { w.print("WARN: "); w.print(message); if (t != null) { w.print(" -> "); try { t.printStackTrace(w); } catch (OutOfMemoryError e) { // Ignore, OOM. w.print(t.getClass().getName()); w.print(": "); w.print(t.getMessage()); w.println(" (stack unavailable; OOM)"); } } else { w.println(); } w.flush(); } catch (OutOfMemoryError t2) { w.println("ERROR: Couldn't even serialize a warning (out of memory)."); } catch (Throwable t2) { // Can't do anything, really. Probably an OOM? w.println("ERROR: Couldn't even serialize a warning."); } }
[ "@", "SuppressForbidden", "(", "\"legitimate sysstreams.\"", ")", "public", "static", "void", "warn", "(", "String", "message", ",", "Throwable", "t", ")", "{", "PrintStream", "w", "=", "(", "warnings", "==", "null", "?", "System", ".", "err", ":", "warnings", ")", ";", "try", "{", "w", ".", "print", "(", "\"WARN: \"", ")", ";", "w", ".", "print", "(", "message", ")", ";", "if", "(", "t", "!=", "null", ")", "{", "w", ".", "print", "(", "\" -> \"", ")", ";", "try", "{", "t", ".", "printStackTrace", "(", "w", ")", ";", "}", "catch", "(", "OutOfMemoryError", "e", ")", "{", "// Ignore, OOM.", "w", ".", "print", "(", "t", ".", "getClass", "(", ")", ".", "getName", "(", ")", ")", ";", "w", ".", "print", "(", "\": \"", ")", ";", "w", ".", "print", "(", "t", ".", "getMessage", "(", ")", ")", ";", "w", ".", "println", "(", "\" (stack unavailable; OOM)\"", ")", ";", "}", "}", "else", "{", "w", ".", "println", "(", ")", ";", "}", "w", ".", "flush", "(", ")", ";", "}", "catch", "(", "OutOfMemoryError", "t2", ")", "{", "w", ".", "println", "(", "\"ERROR: Couldn't even serialize a warning (out of memory).\"", ")", ";", "}", "catch", "(", "Throwable", "t2", ")", "{", "// Can't do anything, really. Probably an OOM?", "w", ".", "println", "(", "\"ERROR: Couldn't even serialize a warning.\"", ")", ";", "}", "}" ]
Warning emitter. Uses whatever alternative non-event communication channel is.
[ "Warning", "emitter", ".", "Uses", "whatever", "alternative", "non", "-", "event", "communication", "channel", "is", "." ]
85a0c7eff5d03d98da4d1f9502a11af74d26478a
https://github.com/randomizedtesting/randomizedtesting/blob/85a0c7eff5d03d98da4d1f9502a11af74d26478a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/slave/SlaveMain.java#L510-L537
164,416
randomizedtesting/randomizedtesting
junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/slave/SlaveMain.java
SlaveMain.instantiateRunListeners
private ArrayList<RunListener> instantiateRunListeners() throws Exception { ArrayList<RunListener> instances = new ArrayList<>(); if (runListeners != null) { for (String className : Arrays.asList(runListeners.split(","))) { instances.add((RunListener) this.instantiate(className).newInstance()); } } return instances; }
java
private ArrayList<RunListener> instantiateRunListeners() throws Exception { ArrayList<RunListener> instances = new ArrayList<>(); if (runListeners != null) { for (String className : Arrays.asList(runListeners.split(","))) { instances.add((RunListener) this.instantiate(className).newInstance()); } } return instances; }
[ "private", "ArrayList", "<", "RunListener", ">", "instantiateRunListeners", "(", ")", "throws", "Exception", "{", "ArrayList", "<", "RunListener", ">", "instances", "=", "new", "ArrayList", "<>", "(", ")", ";", "if", "(", "runListeners", "!=", "null", ")", "{", "for", "(", "String", "className", ":", "Arrays", ".", "asList", "(", "runListeners", ".", "split", "(", "\",\"", ")", ")", ")", "{", "instances", ".", "add", "(", "(", "RunListener", ")", "this", ".", "instantiate", "(", "className", ")", ".", "newInstance", "(", ")", ")", ";", "}", "}", "return", "instances", ";", "}" ]
Generates JUnit 4 RunListener instances for any user defined RunListeners
[ "Generates", "JUnit", "4", "RunListener", "instances", "for", "any", "user", "defined", "RunListeners" ]
85a0c7eff5d03d98da4d1f9502a11af74d26478a
https://github.com/randomizedtesting/randomizedtesting/blob/85a0c7eff5d03d98da4d1f9502a11af74d26478a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/slave/SlaveMain.java#L542-L552
164,417
randomizedtesting/randomizedtesting
junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/balancers/ExecutionTimeBalancer.java
ExecutionTimeBalancer.assign
@Override public List<Assignment> assign(Collection<String> suiteNames, int slaves, long seed) { // Read hints first. final Map<String,List<Long>> hints = ExecutionTimesReport.mergeHints(resources, suiteNames); // Preprocess and sort costs. Take the median for each suite's measurements as the // weight to avoid extreme measurements from screwing up the average. final List<SuiteHint> costs = new ArrayList<>(); for (String suiteName : suiteNames) { final List<Long> suiteHint = hints.get(suiteName); if (suiteHint != null) { // Take the median for each suite's measurements as the weight // to avoid extreme measurements from screwing up the average. Collections.sort(suiteHint); final Long median = suiteHint.get(suiteHint.size() / 2); costs.add(new SuiteHint(suiteName, median)); } } Collections.sort(costs, SuiteHint.DESCENDING_BY_WEIGHT); // Apply the assignment heuristic. final PriorityQueue<SlaveLoad> pq = new PriorityQueue<SlaveLoad>( slaves, SlaveLoad.ASCENDING_BY_ESTIMATED_FINISH); for (int i = 0; i < slaves; i++) { pq.add(new SlaveLoad(i)); } final List<Assignment> assignments = new ArrayList<>(); for (SuiteHint hint : costs) { SlaveLoad slave = pq.remove(); slave.estimatedFinish += hint.cost; pq.add(slave); owner.log("Expected execution time for " + hint.suiteName + ": " + Duration.toHumanDuration(hint.cost), Project.MSG_DEBUG); assignments.add(new Assignment(hint.suiteName, slave.id, (int) hint.cost)); } // Dump estimated execution times. TreeMap<Integer, SlaveLoad> ordered = new TreeMap<Integer, SlaveLoad>(); while (!pq.isEmpty()) { SlaveLoad slave = pq.remove(); ordered.put(slave.id, slave); } for (Integer id : ordered.keySet()) { final SlaveLoad slave = ordered.get(id); owner.log(String.format(Locale.ROOT, "Expected execution time on JVM J%d: %8.2fs", slave.id, slave.estimatedFinish / 1000.0f), verbose ? Project.MSG_INFO : Project.MSG_DEBUG); } return assignments; }
java
@Override public List<Assignment> assign(Collection<String> suiteNames, int slaves, long seed) { // Read hints first. final Map<String,List<Long>> hints = ExecutionTimesReport.mergeHints(resources, suiteNames); // Preprocess and sort costs. Take the median for each suite's measurements as the // weight to avoid extreme measurements from screwing up the average. final List<SuiteHint> costs = new ArrayList<>(); for (String suiteName : suiteNames) { final List<Long> suiteHint = hints.get(suiteName); if (suiteHint != null) { // Take the median for each suite's measurements as the weight // to avoid extreme measurements from screwing up the average. Collections.sort(suiteHint); final Long median = suiteHint.get(suiteHint.size() / 2); costs.add(new SuiteHint(suiteName, median)); } } Collections.sort(costs, SuiteHint.DESCENDING_BY_WEIGHT); // Apply the assignment heuristic. final PriorityQueue<SlaveLoad> pq = new PriorityQueue<SlaveLoad>( slaves, SlaveLoad.ASCENDING_BY_ESTIMATED_FINISH); for (int i = 0; i < slaves; i++) { pq.add(new SlaveLoad(i)); } final List<Assignment> assignments = new ArrayList<>(); for (SuiteHint hint : costs) { SlaveLoad slave = pq.remove(); slave.estimatedFinish += hint.cost; pq.add(slave); owner.log("Expected execution time for " + hint.suiteName + ": " + Duration.toHumanDuration(hint.cost), Project.MSG_DEBUG); assignments.add(new Assignment(hint.suiteName, slave.id, (int) hint.cost)); } // Dump estimated execution times. TreeMap<Integer, SlaveLoad> ordered = new TreeMap<Integer, SlaveLoad>(); while (!pq.isEmpty()) { SlaveLoad slave = pq.remove(); ordered.put(slave.id, slave); } for (Integer id : ordered.keySet()) { final SlaveLoad slave = ordered.get(id); owner.log(String.format(Locale.ROOT, "Expected execution time on JVM J%d: %8.2fs", slave.id, slave.estimatedFinish / 1000.0f), verbose ? Project.MSG_INFO : Project.MSG_DEBUG); } return assignments; }
[ "@", "Override", "public", "List", "<", "Assignment", ">", "assign", "(", "Collection", "<", "String", ">", "suiteNames", ",", "int", "slaves", ",", "long", "seed", ")", "{", "// Read hints first.", "final", "Map", "<", "String", ",", "List", "<", "Long", ">", ">", "hints", "=", "ExecutionTimesReport", ".", "mergeHints", "(", "resources", ",", "suiteNames", ")", ";", "// Preprocess and sort costs. Take the median for each suite's measurements as the ", "// weight to avoid extreme measurements from screwing up the average.", "final", "List", "<", "SuiteHint", ">", "costs", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "String", "suiteName", ":", "suiteNames", ")", "{", "final", "List", "<", "Long", ">", "suiteHint", "=", "hints", ".", "get", "(", "suiteName", ")", ";", "if", "(", "suiteHint", "!=", "null", ")", "{", "// Take the median for each suite's measurements as the weight", "// to avoid extreme measurements from screwing up the average.", "Collections", ".", "sort", "(", "suiteHint", ")", ";", "final", "Long", "median", "=", "suiteHint", ".", "get", "(", "suiteHint", ".", "size", "(", ")", "/", "2", ")", ";", "costs", ".", "add", "(", "new", "SuiteHint", "(", "suiteName", ",", "median", ")", ")", ";", "}", "}", "Collections", ".", "sort", "(", "costs", ",", "SuiteHint", ".", "DESCENDING_BY_WEIGHT", ")", ";", "// Apply the assignment heuristic.", "final", "PriorityQueue", "<", "SlaveLoad", ">", "pq", "=", "new", "PriorityQueue", "<", "SlaveLoad", ">", "(", "slaves", ",", "SlaveLoad", ".", "ASCENDING_BY_ESTIMATED_FINISH", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "slaves", ";", "i", "++", ")", "{", "pq", ".", "add", "(", "new", "SlaveLoad", "(", "i", ")", ")", ";", "}", "final", "List", "<", "Assignment", ">", "assignments", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "SuiteHint", "hint", ":", "costs", ")", "{", "SlaveLoad", "slave", "=", "pq", ".", "remove", "(", ")", ";", "slave", ".", "estimatedFinish", "+=", "hint", ".", "cost", ";", "pq", ".", "add", "(", "slave", ")", ";", "owner", ".", "log", "(", "\"Expected execution time for \"", "+", "hint", ".", "suiteName", "+", "\": \"", "+", "Duration", ".", "toHumanDuration", "(", "hint", ".", "cost", ")", ",", "Project", ".", "MSG_DEBUG", ")", ";", "assignments", ".", "add", "(", "new", "Assignment", "(", "hint", ".", "suiteName", ",", "slave", ".", "id", ",", "(", "int", ")", "hint", ".", "cost", ")", ")", ";", "}", "// Dump estimated execution times.", "TreeMap", "<", "Integer", ",", "SlaveLoad", ">", "ordered", "=", "new", "TreeMap", "<", "Integer", ",", "SlaveLoad", ">", "(", ")", ";", "while", "(", "!", "pq", ".", "isEmpty", "(", ")", ")", "{", "SlaveLoad", "slave", "=", "pq", ".", "remove", "(", ")", ";", "ordered", ".", "put", "(", "slave", ".", "id", ",", "slave", ")", ";", "}", "for", "(", "Integer", "id", ":", "ordered", ".", "keySet", "(", ")", ")", "{", "final", "SlaveLoad", "slave", "=", "ordered", ".", "get", "(", "id", ")", ";", "owner", ".", "log", "(", "String", ".", "format", "(", "Locale", ".", "ROOT", ",", "\"Expected execution time on JVM J%d: %8.2fs\"", ",", "slave", ".", "id", ",", "slave", ".", "estimatedFinish", "/", "1000.0f", ")", ",", "verbose", "?", "Project", ".", "MSG_INFO", ":", "Project", ".", "MSG_DEBUG", ")", ";", "}", "return", "assignments", ";", "}" ]
Assign based on execution time history. The algorithm is a greedy heuristic assigning the longest remaining test to the slave with the shortest-completion time so far. This is not optimal but fast and provides a decent average assignment.
[ "Assign", "based", "on", "execution", "time", "history", ".", "The", "algorithm", "is", "a", "greedy", "heuristic", "assigning", "the", "longest", "remaining", "test", "to", "the", "slave", "with", "the", "shortest", "-", "completion", "time", "so", "far", ".", "This", "is", "not", "optimal", "but", "fast", "and", "provides", "a", "decent", "average", "assignment", "." ]
85a0c7eff5d03d98da4d1f9502a11af74d26478a
https://github.com/randomizedtesting/randomizedtesting/blob/85a0c7eff5d03d98da4d1f9502a11af74d26478a/junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/balancers/ExecutionTimeBalancer.java#L76-L132
164,418
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/internal/views/PaginationToken.java
PaginationToken.mergeTokenAndQueryParameters
static <K, V> PageMetadata<K, V> mergeTokenAndQueryParameters(String paginationToken, final ViewQueryParameters<K, V> initialParameters) { // Decode the base64 token into JSON String json = new String(Base64.decodeBase64(paginationToken), Charset.forName("UTF-8")); // Get a suitable Gson, we need any adapter registered for the K key type Gson paginationTokenGson = getGsonWithKeyAdapter(initialParameters); // Deserialize the pagination token JSON, using the appropriate K, V types PaginationToken token = paginationTokenGson.fromJson(json, PaginationToken.class); // Create new query parameters using the initial ViewQueryParameters as a starting point. ViewQueryParameters<K, V> tokenPageParameters = initialParameters.copy(); // Merge the values from the token into the new query parameters tokenPageParameters.descending = token.descending; tokenPageParameters.endkey = token.endkey; tokenPageParameters.endkey_docid = token.endkey_docid; tokenPageParameters.inclusive_end = token.inclusive_end; tokenPageParameters.startkey = token.startkey; tokenPageParameters.startkey_docid = token.startkey_docid; return new PageMetadata<K, V>(token.direction, token .pageNumber, tokenPageParameters); }
java
static <K, V> PageMetadata<K, V> mergeTokenAndQueryParameters(String paginationToken, final ViewQueryParameters<K, V> initialParameters) { // Decode the base64 token into JSON String json = new String(Base64.decodeBase64(paginationToken), Charset.forName("UTF-8")); // Get a suitable Gson, we need any adapter registered for the K key type Gson paginationTokenGson = getGsonWithKeyAdapter(initialParameters); // Deserialize the pagination token JSON, using the appropriate K, V types PaginationToken token = paginationTokenGson.fromJson(json, PaginationToken.class); // Create new query parameters using the initial ViewQueryParameters as a starting point. ViewQueryParameters<K, V> tokenPageParameters = initialParameters.copy(); // Merge the values from the token into the new query parameters tokenPageParameters.descending = token.descending; tokenPageParameters.endkey = token.endkey; tokenPageParameters.endkey_docid = token.endkey_docid; tokenPageParameters.inclusive_end = token.inclusive_end; tokenPageParameters.startkey = token.startkey; tokenPageParameters.startkey_docid = token.startkey_docid; return new PageMetadata<K, V>(token.direction, token .pageNumber, tokenPageParameters); }
[ "static", "<", "K", ",", "V", ">", "PageMetadata", "<", "K", ",", "V", ">", "mergeTokenAndQueryParameters", "(", "String", "paginationToken", ",", "final", "ViewQueryParameters", "<", "K", ",", "V", ">", "initialParameters", ")", "{", "// Decode the base64 token into JSON", "String", "json", "=", "new", "String", "(", "Base64", ".", "decodeBase64", "(", "paginationToken", ")", ",", "Charset", ".", "forName", "(", "\"UTF-8\"", ")", ")", ";", "// Get a suitable Gson, we need any adapter registered for the K key type", "Gson", "paginationTokenGson", "=", "getGsonWithKeyAdapter", "(", "initialParameters", ")", ";", "// Deserialize the pagination token JSON, using the appropriate K, V types", "PaginationToken", "token", "=", "paginationTokenGson", ".", "fromJson", "(", "json", ",", "PaginationToken", ".", "class", ")", ";", "// Create new query parameters using the initial ViewQueryParameters as a starting point.", "ViewQueryParameters", "<", "K", ",", "V", ">", "tokenPageParameters", "=", "initialParameters", ".", "copy", "(", ")", ";", "// Merge the values from the token into the new query parameters", "tokenPageParameters", ".", "descending", "=", "token", ".", "descending", ";", "tokenPageParameters", ".", "endkey", "=", "token", ".", "endkey", ";", "tokenPageParameters", ".", "endkey_docid", "=", "token", ".", "endkey_docid", ";", "tokenPageParameters", ".", "inclusive_end", "=", "token", ".", "inclusive_end", ";", "tokenPageParameters", ".", "startkey", "=", "token", ".", "startkey", ";", "tokenPageParameters", ".", "startkey_docid", "=", "token", ".", "startkey_docid", ";", "return", "new", "PageMetadata", "<", "K", ",", "V", ">", "(", "token", ".", "direction", ",", "token", ".", "pageNumber", ",", "tokenPageParameters", ")", ";", "}" ]
Generate a PageMetadata object for the page represented by the specified pagination token. @param paginationToken opaque pagination token @param initialParameters the initial view query parameters (i.e. for the page 1 request). @param <K> the view key type @param <V> the view value type @return PageMetadata object for the given page
[ "Generate", "a", "PageMetadata", "object", "for", "the", "page", "represented", "by", "the", "specified", "pagination", "token", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/internal/views/PaginationToken.java#L77-L102
164,419
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/internal/views/PaginationToken.java
PaginationToken.tokenize
static String tokenize(PageMetadata<?, ?> pageMetadata) { try { Gson g = getGsonWithKeyAdapter(pageMetadata.pageRequestParameters); return new String(Base64.encodeBase64URLSafe(g.toJson(new PaginationToken (pageMetadata)).getBytes("UTF-8")), Charset.forName("UTF-8")); } catch (UnsupportedEncodingException e) { //all JVMs should support UTF-8 throw new RuntimeException(e); } }
java
static String tokenize(PageMetadata<?, ?> pageMetadata) { try { Gson g = getGsonWithKeyAdapter(pageMetadata.pageRequestParameters); return new String(Base64.encodeBase64URLSafe(g.toJson(new PaginationToken (pageMetadata)).getBytes("UTF-8")), Charset.forName("UTF-8")); } catch (UnsupportedEncodingException e) { //all JVMs should support UTF-8 throw new RuntimeException(e); } }
[ "static", "String", "tokenize", "(", "PageMetadata", "<", "?", ",", "?", ">", "pageMetadata", ")", "{", "try", "{", "Gson", "g", "=", "getGsonWithKeyAdapter", "(", "pageMetadata", ".", "pageRequestParameters", ")", ";", "return", "new", "String", "(", "Base64", ".", "encodeBase64URLSafe", "(", "g", ".", "toJson", "(", "new", "PaginationToken", "(", "pageMetadata", ")", ")", ".", "getBytes", "(", "\"UTF-8\"", ")", ")", ",", "Charset", ".", "forName", "(", "\"UTF-8\"", ")", ")", ";", "}", "catch", "(", "UnsupportedEncodingException", "e", ")", "{", "//all JVMs should support UTF-8", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}" ]
Generate an opaque pagination token from the supplied PageMetadata. @param pageMetadata page metadata of the page for which the token should be generated @return opaque pagination token
[ "Generate", "an", "opaque", "pagination", "token", "from", "the", "supplied", "PageMetadata", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/internal/views/PaginationToken.java#L110-L120
164,420
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/model/FindByIndexOptions.java
FindByIndexOptions.useIndex
public FindByIndexOptions useIndex(String designDocument, String indexName) { assertNotNull(designDocument, "designDocument"); assertNotNull(indexName, "indexName"); JsonArray index = new JsonArray(); index.add(new JsonPrimitive(designDocument)); index.add(new JsonPrimitive(indexName)); this.useIndex = index; return this; }
java
public FindByIndexOptions useIndex(String designDocument, String indexName) { assertNotNull(designDocument, "designDocument"); assertNotNull(indexName, "indexName"); JsonArray index = new JsonArray(); index.add(new JsonPrimitive(designDocument)); index.add(new JsonPrimitive(indexName)); this.useIndex = index; return this; }
[ "public", "FindByIndexOptions", "useIndex", "(", "String", "designDocument", ",", "String", "indexName", ")", "{", "assertNotNull", "(", "designDocument", ",", "\"designDocument\"", ")", ";", "assertNotNull", "(", "indexName", ",", "\"indexName\"", ")", ";", "JsonArray", "index", "=", "new", "JsonArray", "(", ")", ";", "index", ".", "add", "(", "new", "JsonPrimitive", "(", "designDocument", ")", ")", ";", "index", ".", "add", "(", "new", "JsonPrimitive", "(", "indexName", ")", ")", ";", "this", ".", "useIndex", "=", "index", ";", "return", "this", ";", "}" ]
Specify a specific index to run the query against @param designDocument set the design document to use @param indexName set the index name to use @return this to set additional options
[ "Specify", "a", "specific", "index", "to", "run", "the", "query", "against" ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/model/FindByIndexOptions.java#L128-L136
164,421
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/internal/query/InternalIndex.java
InternalIndex.getPartialFilterSelector
@Override public String getPartialFilterSelector() { return (def.selector != null) ? def.selector.toString() : null; }
java
@Override public String getPartialFilterSelector() { return (def.selector != null) ? def.selector.toString() : null; }
[ "@", "Override", "public", "String", "getPartialFilterSelector", "(", ")", "{", "return", "(", "def", ".", "selector", "!=", "null", ")", "?", "def", ".", "selector", ".", "toString", "(", ")", ":", "null", ";", "}" ]
Get the JSON string representation of the selector configured for this index. @return selector JSON as string
[ "Get", "the", "JSON", "string", "representation", "of", "the", "selector", "configured", "for", "this", "index", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/internal/query/InternalIndex.java#L74-L77
164,422
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/Replication.java
Replication.trigger
public com.cloudant.client.api.model.ReplicationResult trigger() { ReplicationResult couchDbReplicationResult = replication.trigger(); com.cloudant.client.api.model.ReplicationResult replicationResult = new com.cloudant .client.api.model.ReplicationResult(couchDbReplicationResult); return replicationResult; }
java
public com.cloudant.client.api.model.ReplicationResult trigger() { ReplicationResult couchDbReplicationResult = replication.trigger(); com.cloudant.client.api.model.ReplicationResult replicationResult = new com.cloudant .client.api.model.ReplicationResult(couchDbReplicationResult); return replicationResult; }
[ "public", "com", ".", "cloudant", ".", "client", ".", "api", ".", "model", ".", "ReplicationResult", "trigger", "(", ")", "{", "ReplicationResult", "couchDbReplicationResult", "=", "replication", ".", "trigger", "(", ")", ";", "com", ".", "cloudant", ".", "client", ".", "api", ".", "model", ".", "ReplicationResult", "replicationResult", "=", "new", "com", ".", "cloudant", ".", "client", ".", "api", ".", "model", ".", "ReplicationResult", "(", "couchDbReplicationResult", ")", ";", "return", "replicationResult", ";", "}" ]
Triggers a replication request, blocks while the replication is in progress. @return ReplicationResult encapsulating the result
[ "Triggers", "a", "replication", "request", "blocks", "while", "the", "replication", "is", "in", "progress", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/Replication.java#L58-L63
164,423
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/Replication.java
Replication.queryParams
public Replication queryParams(Map<String, Object> queryParams) { this.replication = replication.queryParams(queryParams); return this; }
java
public Replication queryParams(Map<String, Object> queryParams) { this.replication = replication.queryParams(queryParams); return this; }
[ "public", "Replication", "queryParams", "(", "Map", "<", "String", ",", "Object", ">", "queryParams", ")", "{", "this", ".", "replication", "=", "replication", ".", "queryParams", "(", "queryParams", ")", ";", "return", "this", ";", "}" ]
Specify additional query parameters to be passed to the filter function. @param queryParams map of key-value parameters @return this Replication instance to set more options or trigger the replication
[ "Specify", "additional", "query", "parameters", "to", "be", "passed", "to", "the", "filter", "function", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/Replication.java#L131-L134
164,424
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/Replication.java
Replication.targetOauth
public Replication targetOauth(String consumerSecret, String consumerKey, String tokenSecret, String token) { this.replication = replication.targetOauth(consumerSecret, consumerKey, tokenSecret, token); return this; }
java
public Replication targetOauth(String consumerSecret, String consumerKey, String tokenSecret, String token) { this.replication = replication.targetOauth(consumerSecret, consumerKey, tokenSecret, token); return this; }
[ "public", "Replication", "targetOauth", "(", "String", "consumerSecret", ",", "String", "consumerKey", ",", "String", "tokenSecret", ",", "String", "token", ")", "{", "this", ".", "replication", "=", "replication", ".", "targetOauth", "(", "consumerSecret", ",", "consumerKey", ",", "tokenSecret", ",", "token", ")", ";", "return", "this", ";", "}" ]
Set OAuth 1 authentication credentials for the replication target @param consumerSecret client secret @param consumerKey client identifier @param tokenSecret OAuth server token secret @param token OAuth server issued token @return this Replication instance to set more options or trigger the replication
[ "Set", "OAuth", "1", "authentication", "credentials", "for", "the", "replication", "target" ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/Replication.java#L220-L225
164,425
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/CloudantClient.java
CloudantClient.getActiveTasks
public List<Task> getActiveTasks() { InputStream response = null; URI uri = new URIBase(getBaseUri()).path("_active_tasks").build(); try { response = couchDbClient.get(uri); return getResponseList(response, couchDbClient.getGson(), DeserializationTypes.TASKS); } finally { close(response); } }
java
public List<Task> getActiveTasks() { InputStream response = null; URI uri = new URIBase(getBaseUri()).path("_active_tasks").build(); try { response = couchDbClient.get(uri); return getResponseList(response, couchDbClient.getGson(), DeserializationTypes.TASKS); } finally { close(response); } }
[ "public", "List", "<", "Task", ">", "getActiveTasks", "(", ")", "{", "InputStream", "response", "=", "null", ";", "URI", "uri", "=", "new", "URIBase", "(", "getBaseUri", "(", ")", ")", ".", "path", "(", "\"_active_tasks\"", ")", ".", "build", "(", ")", ";", "try", "{", "response", "=", "couchDbClient", ".", "get", "(", "uri", ")", ";", "return", "getResponseList", "(", "response", ",", "couchDbClient", ".", "getGson", "(", ")", ",", "DeserializationTypes", ".", "TASKS", ")", ";", "}", "finally", "{", "close", "(", "response", ")", ";", "}", "}" ]
Get the list of active tasks from the server. @return List of tasks @see <a href="https://console.bluemix.net/docs/services/Cloudant/api/active_tasks.html"> Active tasks</a>
[ "Get", "the", "list", "of", "active", "tasks", "from", "the", "server", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/CloudantClient.java#L180-L189
164,426
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/CloudantClient.java
CloudantClient.getMembership
public Membership getMembership() { URI uri = new URIBase(getBaseUri()).path("_membership").build(); Membership membership = couchDbClient.get(uri, Membership.class); return membership; }
java
public Membership getMembership() { URI uri = new URIBase(getBaseUri()).path("_membership").build(); Membership membership = couchDbClient.get(uri, Membership.class); return membership; }
[ "public", "Membership", "getMembership", "(", ")", "{", "URI", "uri", "=", "new", "URIBase", "(", "getBaseUri", "(", ")", ")", ".", "path", "(", "\"_membership\"", ")", ".", "build", "(", ")", ";", "Membership", "membership", "=", "couchDbClient", ".", "get", "(", "uri", ",", "Membership", ".", "class", ")", ";", "return", "membership", ";", "}" ]
Get the list of all nodes and the list of active nodes in the cluster. @return Membership object encapsulating lists of all nodes and the cluster nodes @see <a href="https://console.bluemix.net/docs/services/Cloudant/api/advanced.html#-get-_membership-"> _membership</a>
[ "Get", "the", "list", "of", "all", "nodes", "and", "the", "list", "of", "active", "nodes", "in", "the", "cluster", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/CloudantClient.java#L199-L204
164,427
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/Changes.java
Changes.getChanges
public ChangesResult getChanges() { final URI uri = this.databaseHelper.changesUri("feed", "normal"); return client.get(uri, ChangesResult.class); }
java
public ChangesResult getChanges() { final URI uri = this.databaseHelper.changesUri("feed", "normal"); return client.get(uri, ChangesResult.class); }
[ "public", "ChangesResult", "getChanges", "(", ")", "{", "final", "URI", "uri", "=", "this", ".", "databaseHelper", ".", "changesUri", "(", "\"feed\"", ",", "\"normal\"", ")", ";", "return", "client", ".", "get", "(", "uri", ",", "ChangesResult", ".", "class", ")", ";", "}" ]
Requests Change notifications of feed type normal. @return {@link ChangesResult} encapsulating the normal feed changes
[ "Requests", "Change", "notifications", "of", "feed", "type", "normal", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/Changes.java#L151-L154
164,428
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/Changes.java
Changes.parameter
public Changes parameter(String name, String value) { this.databaseHelper.query(name, value); return this; }
java
public Changes parameter(String name, String value) { this.databaseHelper.query(name, value); return this; }
[ "public", "Changes", "parameter", "(", "String", "name", ",", "String", "value", ")", "{", "this", ".", "databaseHelper", ".", "query", "(", "name", ",", "value", ")", ";", "return", "this", ";", "}" ]
Add a custom query parameter to the _changes request. Useful for specifying extra parameters to a filter function for example. @param name the name of the query parameter @param value the value of the query parameter @return this Changes instance @since 2.5.0
[ "Add", "a", "custom", "query", "parameter", "to", "the", "_changes", "request", ".", "Useful", "for", "specifying", "extra", "parameters", "to", "a", "filter", "function", "for", "example", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/Changes.java#L255-L258
164,429
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/Changes.java
Changes.readNextRow
private boolean readNextRow() { while (!stop) { String row = getLineWrapped(); // end of stream - null indicates end of stream before we see last_seq which shouldn't // be possible but we should handle it if (row == null || row.startsWith("{\"last_seq\":")) { terminate(); return false; } else if (row.isEmpty()) { // heartbeat continue; } setNextRow(gson.fromJson(row, ChangesResult.Row.class)); return true; } // we were stopped, end of changes feed terminate(); return false; }
java
private boolean readNextRow() { while (!stop) { String row = getLineWrapped(); // end of stream - null indicates end of stream before we see last_seq which shouldn't // be possible but we should handle it if (row == null || row.startsWith("{\"last_seq\":")) { terminate(); return false; } else if (row.isEmpty()) { // heartbeat continue; } setNextRow(gson.fromJson(row, ChangesResult.Row.class)); return true; } // we were stopped, end of changes feed terminate(); return false; }
[ "private", "boolean", "readNextRow", "(", ")", "{", "while", "(", "!", "stop", ")", "{", "String", "row", "=", "getLineWrapped", "(", ")", ";", "// end of stream - null indicates end of stream before we see last_seq which shouldn't", "// be possible but we should handle it", "if", "(", "row", "==", "null", "||", "row", ".", "startsWith", "(", "\"{\\\"last_seq\\\":\"", ")", ")", "{", "terminate", "(", ")", ";", "return", "false", ";", "}", "else", "if", "(", "row", ".", "isEmpty", "(", ")", ")", "{", "// heartbeat", "continue", ";", "}", "setNextRow", "(", "gson", ".", "fromJson", "(", "row", ",", "ChangesResult", ".", "Row", ".", "class", ")", ")", ";", "return", "true", ";", "}", "// we were stopped, end of changes feed", "terminate", "(", ")", ";", "return", "false", ";", "}" ]
Reads and sets the next feed in the stream.
[ "Reads", "and", "sets", "the", "next", "feed", "in", "the", "stream", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/Changes.java#L265-L283
164,430
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/Database.java
Database.getShards
public List<Shard> getShards() { InputStream response = null; try { response = client.couchDbClient.get(new DatabaseURIHelper(db.getDBUri()).path("_shards") .build()); return getResponseList(response, client.getGson(), DeserializationTypes.SHARDS); } finally { close(response); } }
java
public List<Shard> getShards() { InputStream response = null; try { response = client.couchDbClient.get(new DatabaseURIHelper(db.getDBUri()).path("_shards") .build()); return getResponseList(response, client.getGson(), DeserializationTypes.SHARDS); } finally { close(response); } }
[ "public", "List", "<", "Shard", ">", "getShards", "(", ")", "{", "InputStream", "response", "=", "null", ";", "try", "{", "response", "=", "client", ".", "couchDbClient", ".", "get", "(", "new", "DatabaseURIHelper", "(", "db", ".", "getDBUri", "(", ")", ")", ".", "path", "(", "\"_shards\"", ")", ".", "build", "(", ")", ")", ";", "return", "getResponseList", "(", "response", ",", "client", ".", "getGson", "(", ")", ",", "DeserializationTypes", ".", "SHARDS", ")", ";", "}", "finally", "{", "close", "(", "response", ")", ";", "}", "}" ]
Get info about the shards in the database. @return List of shards @see <a href="https://console.bluemix.net/docs/services/Cloudant/api/advanced.html#-get-database-_shards-" target="_blank">_shards</a>
[ "Get", "info", "about", "the", "shards", "in", "the", "database", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/Database.java#L244-L253
164,431
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/Database.java
Database.getShard
public Shard getShard(String docId) { assertNotEmpty(docId, "docId"); return client.couchDbClient.get(new DatabaseURIHelper(db.getDBUri()).path("_shards") .path(docId).build(), Shard.class); }
java
public Shard getShard(String docId) { assertNotEmpty(docId, "docId"); return client.couchDbClient.get(new DatabaseURIHelper(db.getDBUri()).path("_shards") .path(docId).build(), Shard.class); }
[ "public", "Shard", "getShard", "(", "String", "docId", ")", "{", "assertNotEmpty", "(", "docId", ",", "\"docId\"", ")", ";", "return", "client", ".", "couchDbClient", ".", "get", "(", "new", "DatabaseURIHelper", "(", "db", ".", "getDBUri", "(", ")", ")", ".", "path", "(", "\"_shards\"", ")", ".", "path", "(", "docId", ")", ".", "build", "(", ")", ",", "Shard", ".", "class", ")", ";", "}" ]
Get info about the shard a document belongs to. @param docId document ID @return Shard info @see <a href="https://console.bluemix.net/docs/services/Cloudant/api/advanced.html#-get-database-_shards-" target="_blank">_shards</a>
[ "Get", "info", "about", "the", "shard", "a", "document", "belongs", "to", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/Database.java#L264-L269
164,432
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/Database.java
Database.findByIndex
@Deprecated public <T> List<T> findByIndex(String selectorJson, Class<T> classOfT) { return findByIndex(selectorJson, classOfT, new FindByIndexOptions()); }
java
@Deprecated public <T> List<T> findByIndex(String selectorJson, Class<T> classOfT) { return findByIndex(selectorJson, classOfT, new FindByIndexOptions()); }
[ "@", "Deprecated", "public", "<", "T", ">", "List", "<", "T", ">", "findByIndex", "(", "String", "selectorJson", ",", "Class", "<", "T", ">", "classOfT", ")", "{", "return", "findByIndex", "(", "selectorJson", ",", "classOfT", ",", "new", "FindByIndexOptions", "(", ")", ")", ";", "}" ]
Find documents using an index @param selectorJson String representation of a JSON object describing criteria used to select documents. For example: {@code "{ \"selector\": {<your data here>} }"}. @param classOfT The class of Java objects to be returned @param <T> the type of the Java object to be returned @return List of classOfT objects @see #findByIndex(String, Class, FindByIndexOptions) @see <a href="https://console.bluemix.net/docs/services/Cloudant/api/cloudant_query.html#selector-syntax" target="_blank">selector syntax</a> @deprecated Use {@link #query(String, Class)} instead
[ "Find", "documents", "using", "an", "index" ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/Database.java#L419-L422
164,433
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/Database.java
Database.query
public <T> QueryResult<T> query(String partitionKey, String query, final Class<T> classOfT) { URI uri = new DatabaseURIHelper(db.getDBUri()).partition(partitionKey).path("_find").build(); return this.query(uri, query, classOfT); }
java
public <T> QueryResult<T> query(String partitionKey, String query, final Class<T> classOfT) { URI uri = new DatabaseURIHelper(db.getDBUri()).partition(partitionKey).path("_find").build(); return this.query(uri, query, classOfT); }
[ "public", "<", "T", ">", "QueryResult", "<", "T", ">", "query", "(", "String", "partitionKey", ",", "String", "query", ",", "final", "Class", "<", "T", ">", "classOfT", ")", "{", "URI", "uri", "=", "new", "DatabaseURIHelper", "(", "db", ".", "getDBUri", "(", ")", ")", ".", "partition", "(", "partitionKey", ")", ".", "path", "(", "\"_find\"", ")", ".", "build", "(", ")", ";", "return", "this", ".", "query", "(", "uri", ",", "query", ",", "classOfT", ")", ";", "}" ]
Execute a partitioned query using an index and a query selector. Only available in partitioned databases. To verify a database is partitioned call {@link Database#info()} and check that {@link DbInfo.Props#getPartitioned()} returns {@code true}. <p>Example usage:</p> <pre> {@code // Query database partition 'Coppola'. QueryResult<Movie> movies = db.query("Coppola", new QueryBuilder(and( gt("Movie_year", 1960), eq("Person_name", "Al Pacino"))). fields("Movie_name", "Movie_year"). build(), Movie.class); } </pre> @param partitionKey Database partition to query. @param query String representation of a JSON object describing criteria used to select documents. @param classOfT The class of Java objects to be returned in the {@code docs} field of result. @param <T> The type of the Java object to be returned in the {@code docs} field of result. @return A {@link QueryResult} object, containing the documents matching the query in the {@code docs} field. @see com.cloudant.client.api.Database#query(String, Class)
[ "Execute", "a", "partitioned", "query", "using", "an", "index", "and", "a", "query", "selector", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/Database.java#L531-L534
164,434
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/Database.java
Database.listIndexes
public Indexes listIndexes() { URI uri = new DatabaseURIHelper(db.getDBUri()).path("_index").build(); return client.couchDbClient.get(uri, Indexes.class); }
java
public Indexes listIndexes() { URI uri = new DatabaseURIHelper(db.getDBUri()).path("_index").build(); return client.couchDbClient.get(uri, Indexes.class); }
[ "public", "Indexes", "listIndexes", "(", ")", "{", "URI", "uri", "=", "new", "DatabaseURIHelper", "(", "db", ".", "getDBUri", "(", ")", ")", ".", "path", "(", "\"_index\"", ")", ".", "build", "(", ")", ";", "return", "client", ".", "couchDbClient", ".", "get", "(", "uri", ",", "Indexes", ".", "class", ")", ";", "}" ]
List the indexes in the database. The returned object allows for listing indexes by type. @return indexes object with methods for getting indexes of a particular type
[ "List", "the", "indexes", "in", "the", "database", ".", "The", "returned", "object", "allows", "for", "listing", "indexes", "by", "type", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/Database.java#L582-L585
164,435
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/Database.java
Database.deleteIndex
public void deleteIndex(String indexName, String designDocId, String type) { assertNotEmpty(indexName, "indexName"); assertNotEmpty(designDocId, "designDocId"); assertNotNull(type, "type"); if (!designDocId.startsWith("_design")) { designDocId = "_design/" + designDocId; } URI uri = new DatabaseURIHelper(db.getDBUri()).path("_index").path(designDocId) .path(type).path(indexName).build(); InputStream response = null; try { HttpConnection connection = Http.DELETE(uri); response = client.couchDbClient.executeToInputStream(connection); getResponse(response, Response.class, client.getGson()); } finally { close(response); } }
java
public void deleteIndex(String indexName, String designDocId, String type) { assertNotEmpty(indexName, "indexName"); assertNotEmpty(designDocId, "designDocId"); assertNotNull(type, "type"); if (!designDocId.startsWith("_design")) { designDocId = "_design/" + designDocId; } URI uri = new DatabaseURIHelper(db.getDBUri()).path("_index").path(designDocId) .path(type).path(indexName).build(); InputStream response = null; try { HttpConnection connection = Http.DELETE(uri); response = client.couchDbClient.executeToInputStream(connection); getResponse(response, Response.class, client.getGson()); } finally { close(response); } }
[ "public", "void", "deleteIndex", "(", "String", "indexName", ",", "String", "designDocId", ",", "String", "type", ")", "{", "assertNotEmpty", "(", "indexName", ",", "\"indexName\"", ")", ";", "assertNotEmpty", "(", "designDocId", ",", "\"designDocId\"", ")", ";", "assertNotNull", "(", "type", ",", "\"type\"", ")", ";", "if", "(", "!", "designDocId", ".", "startsWith", "(", "\"_design\"", ")", ")", "{", "designDocId", "=", "\"_design/\"", "+", "designDocId", ";", "}", "URI", "uri", "=", "new", "DatabaseURIHelper", "(", "db", ".", "getDBUri", "(", ")", ")", ".", "path", "(", "\"_index\"", ")", ".", "path", "(", "designDocId", ")", ".", "path", "(", "type", ")", ".", "path", "(", "indexName", ")", ".", "build", "(", ")", ";", "InputStream", "response", "=", "null", ";", "try", "{", "HttpConnection", "connection", "=", "Http", ".", "DELETE", "(", "uri", ")", ";", "response", "=", "client", ".", "couchDbClient", ".", "executeToInputStream", "(", "connection", ")", ";", "getResponse", "(", "response", ",", "Response", ".", "class", ",", "client", ".", "getGson", "(", ")", ")", ";", "}", "finally", "{", "close", "(", "response", ")", ";", "}", "}" ]
Delete an index with the specified name and type in the given design document. @param indexName name of the index @param designDocId ID of the design doc (the _design prefix will be added if not present) @param type type of the index, valid values or "text" or "json"
[ "Delete", "an", "index", "with", "the", "specified", "name", "and", "type", "in", "the", "given", "design", "document", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/Database.java#L604-L621
164,436
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/Database.java
Database.find
public <T> T find(Class<T> classType, String id) { return db.find(classType, id); }
java
public <T> T find(Class<T> classType, String id) { return db.find(classType, id); }
[ "public", "<", "T", ">", "T", "find", "(", "Class", "<", "T", ">", "classType", ",", "String", "id", ")", "{", "return", "db", ".", "find", "(", "classType", ",", "id", ")", ";", "}" ]
Retrieve the document with the specified ID from the database and deserialize to an instance of the POJO of type T. @param <T> object type @param classType the class of type T @param id the document id @return an object of type T @throws NoDocumentException if the document is not found in the database @see #find(Class, String, String) @see <a href="https://console.bluemix.net/docs/services/Cloudant/api/document.html#read" target="_blank">Documents - read</a>
[ "Retrieve", "the", "document", "with", "the", "specified", "ID", "from", "the", "database", "and", "deserialize", "to", "an", "instance", "of", "the", "POJO", "of", "type", "T", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/Database.java#L751-L753
164,437
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/Database.java
Database.info
public DbInfo info() { return client.couchDbClient.get(new DatabaseURIHelper(db.getDBUri()).getDatabaseUri(), DbInfo.class); }
java
public DbInfo info() { return client.couchDbClient.get(new DatabaseURIHelper(db.getDBUri()).getDatabaseUri(), DbInfo.class); }
[ "public", "DbInfo", "info", "(", ")", "{", "return", "client", ".", "couchDbClient", ".", "get", "(", "new", "DatabaseURIHelper", "(", "db", ".", "getDBUri", "(", ")", ")", ".", "getDatabaseUri", "(", ")", ",", "DbInfo", ".", "class", ")", ";", "}" ]
Get information about this database. @return DbInfo encapsulating the database info @see <a href="https://console.bluemix.net/docs/services/Cloudant/api/database.html#getting-database-details" target="_blank">Databases - read</a>
[ "Get", "information", "about", "this", "database", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/Database.java#L1399-L1402
164,438
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/Database.java
Database.partitionInfo
public PartitionInfo partitionInfo(String partitionKey) { if (partitionKey == null) { throw new UnsupportedOperationException("Cannot get partition information for null partition key."); } URI uri = new DatabaseURIHelper(db.getDBUri()).partition(partitionKey).build(); return client.couchDbClient.get(uri, PartitionInfo.class); }
java
public PartitionInfo partitionInfo(String partitionKey) { if (partitionKey == null) { throw new UnsupportedOperationException("Cannot get partition information for null partition key."); } URI uri = new DatabaseURIHelper(db.getDBUri()).partition(partitionKey).build(); return client.couchDbClient.get(uri, PartitionInfo.class); }
[ "public", "PartitionInfo", "partitionInfo", "(", "String", "partitionKey", ")", "{", "if", "(", "partitionKey", "==", "null", ")", "{", "throw", "new", "UnsupportedOperationException", "(", "\"Cannot get partition information for null partition key.\"", ")", ";", "}", "URI", "uri", "=", "new", "DatabaseURIHelper", "(", "db", ".", "getDBUri", "(", ")", ")", ".", "partition", "(", "partitionKey", ")", ".", "build", "(", ")", ";", "return", "client", ".", "couchDbClient", ".", "get", "(", "uri", ",", "PartitionInfo", ".", "class", ")", ";", "}" ]
Get information about a partition in this database. @param partitionKey database partition key @return {@link com.cloudant.client.api.model.PartitionInfo} encapsulating the database partition info. @throws UnsupportedOperationException if called with {@code null} partition key.
[ "Get", "information", "about", "a", "partition", "in", "this", "database", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/Database.java#L1411-L1417
164,439
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/query/Expression.java
Expression.type
public static Expression type(String lhs, Type rhs) { return new Expression(lhs, "$type", rhs.toString()); }
java
public static Expression type(String lhs, Type rhs) { return new Expression(lhs, "$type", rhs.toString()); }
[ "public", "static", "Expression", "type", "(", "String", "lhs", ",", "Type", "rhs", ")", "{", "return", "new", "Expression", "(", "lhs", ",", "\"$type\"", ",", "rhs", ".", "toString", "(", ")", ")", ";", "}" ]
Check the document field's type and object @param lhs The field to check @param rhs The type @return Expression: lhs $type rhs
[ "Check", "the", "document", "field", "s", "type", "and", "object" ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/query/Expression.java#L121-L123
164,440
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/query/PredicateExpression.java
PredicateExpression.nin
public static PredicateExpression nin(Object... rhs) { PredicateExpression ex = new PredicateExpression("$nin", rhs); if (rhs.length == 1) { ex.single = true; } return ex; }
java
public static PredicateExpression nin(Object... rhs) { PredicateExpression ex = new PredicateExpression("$nin", rhs); if (rhs.length == 1) { ex.single = true; } return ex; }
[ "public", "static", "PredicateExpression", "nin", "(", "Object", "...", "rhs", ")", "{", "PredicateExpression", "ex", "=", "new", "PredicateExpression", "(", "\"$nin\"", ",", "rhs", ")", ";", "if", "(", "rhs", ".", "length", "==", "1", ")", "{", "ex", ".", "single", "=", "true", ";", "}", "return", "ex", ";", "}" ]
The document field must not exist in the list provided @param rhs The argument - one or more values @return PredicateExpression: $nin rhs
[ "The", "document", "field", "must", "not", "exist", "in", "the", "list", "provided" ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/query/PredicateExpression.java#L131-L137
164,441
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/query/PredicateExpression.java
PredicateExpression.all
public static PredicateExpression all(Object... rhs) { PredicateExpression ex = new PredicateExpression( "$all", rhs); if (rhs.length == 1) { ex.single = true; } return ex; }
java
public static PredicateExpression all(Object... rhs) { PredicateExpression ex = new PredicateExpression( "$all", rhs); if (rhs.length == 1) { ex.single = true; } return ex; }
[ "public", "static", "PredicateExpression", "all", "(", "Object", "...", "rhs", ")", "{", "PredicateExpression", "ex", "=", "new", "PredicateExpression", "(", "\"$all\"", ",", "rhs", ")", ";", "if", "(", "rhs", ".", "length", "==", "1", ")", "{", "ex", ".", "single", "=", "true", ";", "}", "return", "ex", ";", "}" ]
Matches an array value if it contains all the elements of the argument array @param rhs The arguments @return PredicateExpression: $all rhs
[ "Matches", "an", "array", "value", "if", "it", "contains", "all", "the", "elements", "of", "the", "argument", "array" ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/query/PredicateExpression.java#L176-L182
164,442
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/Replication.java
Replication.trigger
public ReplicationResult trigger() { assertNotEmpty(source, "Source"); assertNotEmpty(target, "Target"); InputStream response = null; try { JsonObject json = createJson(); if (log.isLoggable(Level.FINE)) { log.fine(json.toString()); } final URI uri = new DatabaseURIHelper(client.getBaseUri()).path("_replicate").build(); response = client.post(uri, json.toString()); final InputStreamReader reader = new InputStreamReader(response, "UTF-8"); return client.getGson().fromJson(reader, ReplicationResult.class); } catch (UnsupportedEncodingException e) { // This should never happen as every implementation of the java platform is required // to support UTF-8. throw new RuntimeException(e); } finally { close(response); } }
java
public ReplicationResult trigger() { assertNotEmpty(source, "Source"); assertNotEmpty(target, "Target"); InputStream response = null; try { JsonObject json = createJson(); if (log.isLoggable(Level.FINE)) { log.fine(json.toString()); } final URI uri = new DatabaseURIHelper(client.getBaseUri()).path("_replicate").build(); response = client.post(uri, json.toString()); final InputStreamReader reader = new InputStreamReader(response, "UTF-8"); return client.getGson().fromJson(reader, ReplicationResult.class); } catch (UnsupportedEncodingException e) { // This should never happen as every implementation of the java platform is required // to support UTF-8. throw new RuntimeException(e); } finally { close(response); } }
[ "public", "ReplicationResult", "trigger", "(", ")", "{", "assertNotEmpty", "(", "source", ",", "\"Source\"", ")", ";", "assertNotEmpty", "(", "target", ",", "\"Target\"", ")", ";", "InputStream", "response", "=", "null", ";", "try", "{", "JsonObject", "json", "=", "createJson", "(", ")", ";", "if", "(", "log", ".", "isLoggable", "(", "Level", ".", "FINE", ")", ")", "{", "log", ".", "fine", "(", "json", ".", "toString", "(", ")", ")", ";", "}", "final", "URI", "uri", "=", "new", "DatabaseURIHelper", "(", "client", ".", "getBaseUri", "(", ")", ")", ".", "path", "(", "\"_replicate\"", ")", ".", "build", "(", ")", ";", "response", "=", "client", ".", "post", "(", "uri", ",", "json", ".", "toString", "(", ")", ")", ";", "final", "InputStreamReader", "reader", "=", "new", "InputStreamReader", "(", "response", ",", "\"UTF-8\"", ")", ";", "return", "client", ".", "getGson", "(", ")", ".", "fromJson", "(", "reader", ",", "ReplicationResult", ".", "class", ")", ";", "}", "catch", "(", "UnsupportedEncodingException", "e", ")", "{", "// This should never happen as every implementation of the java platform is required", "// to support UTF-8.", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "finally", "{", "close", "(", "response", ")", ";", "}", "}" ]
Triggers a replication request.
[ "Triggers", "a", "replication", "request", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/Replication.java#L102-L123
164,443
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/Replication.java
Replication.targetOauth
public Replication targetOauth(String consumerSecret, String consumerKey, String tokenSecret, String token) { targetOauth = new JsonObject(); this.consumerSecret = consumerSecret; this.consumerKey = consumerKey; this.tokenSecret = tokenSecret; this.token = token; return this; }
java
public Replication targetOauth(String consumerSecret, String consumerKey, String tokenSecret, String token) { targetOauth = new JsonObject(); this.consumerSecret = consumerSecret; this.consumerKey = consumerKey; this.tokenSecret = tokenSecret; this.token = token; return this; }
[ "public", "Replication", "targetOauth", "(", "String", "consumerSecret", ",", "String", "consumerKey", ",", "String", "tokenSecret", ",", "String", "token", ")", "{", "targetOauth", "=", "new", "JsonObject", "(", ")", ";", "this", ".", "consumerSecret", "=", "consumerSecret", ";", "this", ".", "consumerKey", "=", "consumerKey", ";", "this", ".", "tokenSecret", "=", "tokenSecret", ";", "this", ".", "token", "=", "token", ";", "return", "this", ";", "}" ]
Authenticate with the target database using OAuth. @param consumerSecret consumer secret @param consumerKey consumer key @param tokenSecret token secret @param token token @return this Replication instance to set more options @deprecated OAuth 1.0 implementation has been <a href="http://docs.couchdb.org/en/stable/whatsnew/2.1.html?highlight=oauth#upgrade-notes" target="_blank">removed in CouchDB 2.1</a>
[ "Authenticate", "with", "the", "target", "database", "using", "OAuth", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/Replication.java#L206-L214
164,444
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/internal/CouchDbUtil.java
CouchDbUtil.createPost
public static HttpConnection createPost(URI uri, String body, String contentType) { HttpConnection connection = Http.POST(uri, "application/json"); if(body != null) { setEntity(connection, body, contentType); } return connection; }
java
public static HttpConnection createPost(URI uri, String body, String contentType) { HttpConnection connection = Http.POST(uri, "application/json"); if(body != null) { setEntity(connection, body, contentType); } return connection; }
[ "public", "static", "HttpConnection", "createPost", "(", "URI", "uri", ",", "String", "body", ",", "String", "contentType", ")", "{", "HttpConnection", "connection", "=", "Http", ".", "POST", "(", "uri", ",", "\"application/json\"", ")", ";", "if", "(", "body", "!=", "null", ")", "{", "setEntity", "(", "connection", ",", "body", ",", "contentType", ")", ";", "}", "return", "connection", ";", "}" ]
create a HTTP POST request. @return {@link HttpConnection}
[ "create", "a", "HTTP", "POST", "request", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/internal/CouchDbUtil.java#L181-L187
164,445
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/internal/CouchDbUtil.java
CouchDbUtil.setEntity
public static void setEntity(HttpConnection connnection, String body, String contentType) { connnection.requestProperties.put("Content-type", contentType); connnection.setRequestBody(body); }
java
public static void setEntity(HttpConnection connnection, String body, String contentType) { connnection.requestProperties.put("Content-type", contentType); connnection.setRequestBody(body); }
[ "public", "static", "void", "setEntity", "(", "HttpConnection", "connnection", ",", "String", "body", ",", "String", "contentType", ")", "{", "connnection", ".", "requestProperties", ".", "put", "(", "\"Content-type\"", ",", "contentType", ")", ";", "connnection", ".", "setRequestBody", "(", "body", ")", ";", "}" ]
Sets a JSON String as a request entity. @param connnection The request of {@link HttpConnection} @param body The JSON String to set.
[ "Sets", "a", "JSON", "String", "as", "a", "request", "entity", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/internal/CouchDbUtil.java#L195-L198
164,446
cloudant/java-cloudant
cloudant-http/src/main/java/com/cloudant/http/HttpConnectionInterceptorContext.java
HttpConnectionInterceptorContext.setState
public <T> void setState(HttpConnectionInterceptor interceptor, String stateName, T stateObjectToStore) { Map<String, Object> state = interceptorStates.get(interceptor); if (state == null) { interceptorStates.put(interceptor, (state = new ConcurrentHashMap<String, Object>())); } state.put(stateName, stateObjectToStore); }
java
public <T> void setState(HttpConnectionInterceptor interceptor, String stateName, T stateObjectToStore) { Map<String, Object> state = interceptorStates.get(interceptor); if (state == null) { interceptorStates.put(interceptor, (state = new ConcurrentHashMap<String, Object>())); } state.put(stateName, stateObjectToStore); }
[ "public", "<", "T", ">", "void", "setState", "(", "HttpConnectionInterceptor", "interceptor", ",", "String", "stateName", ",", "T", "stateObjectToStore", ")", "{", "Map", "<", "String", ",", "Object", ">", "state", "=", "interceptorStates", ".", "get", "(", "interceptor", ")", ";", "if", "(", "state", "==", "null", ")", "{", "interceptorStates", ".", "put", "(", "interceptor", ",", "(", "state", "=", "new", "ConcurrentHashMap", "<", "String", ",", "Object", ">", "(", ")", ")", ")", ";", "}", "state", ".", "put", "(", "stateName", ",", "stateObjectToStore", ")", ";", "}" ]
Store some state on this request context associated with the specified interceptor instance. Used where a single interceptor instance needs to associate state with each HTTP request. @param interceptor the interceptor instance @param stateName the key to store the state object under @param stateObjectToStore the state object to store @param <T> the type of the state object to store @see #getState(HttpConnectionInterceptor, String, Class) @since 2.6.0
[ "Store", "some", "state", "on", "this", "request", "context", "associated", "with", "the", "specified", "interceptor", "instance", ".", "Used", "where", "a", "single", "interceptor", "instance", "needs", "to", "associate", "state", "with", "each", "HTTP", "request", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-http/src/main/java/com/cloudant/http/HttpConnectionInterceptorContext.java#L84-L91
164,447
cloudant/java-cloudant
cloudant-http/src/main/java/com/cloudant/http/HttpConnectionInterceptorContext.java
HttpConnectionInterceptorContext.getState
public <T> T getState(HttpConnectionInterceptor interceptor, String stateName, Class<T> stateType) { Map<String, Object> state = interceptorStates.get(interceptor); if (state != null) { return stateType.cast(state.get(stateName)); } else { return null; } }
java
public <T> T getState(HttpConnectionInterceptor interceptor, String stateName, Class<T> stateType) { Map<String, Object> state = interceptorStates.get(interceptor); if (state != null) { return stateType.cast(state.get(stateName)); } else { return null; } }
[ "public", "<", "T", ">", "T", "getState", "(", "HttpConnectionInterceptor", "interceptor", ",", "String", "stateName", ",", "Class", "<", "T", ">", "stateType", ")", "{", "Map", "<", "String", ",", "Object", ">", "state", "=", "interceptorStates", ".", "get", "(", "interceptor", ")", ";", "if", "(", "state", "!=", "null", ")", "{", "return", "stateType", ".", "cast", "(", "state", ".", "get", "(", "stateName", ")", ")", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Retrieve the state object associated with the specified interceptor instance and property name on this request context. @param interceptor the interceptor instance @param stateName the name key that the state object was stored under @param stateType class of the type the stored state should be returned as @param <T> the type the stored state should be returned as @return the stored state object @see #setState(HttpConnectionInterceptor, String, Object) @since 2.6.0
[ "Retrieve", "the", "state", "object", "associated", "with", "the", "specified", "interceptor", "instance", "and", "property", "name", "on", "this", "request", "context", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-http/src/main/java/com/cloudant/http/HttpConnectionInterceptorContext.java#L105-L113
164,448
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/DesignDocumentManager.java
DesignDocumentManager.get
public DesignDocument get(String id) { assertNotEmpty(id, "id"); return db.find(DesignDocument.class, ensureDesignPrefix(id)); }
java
public DesignDocument get(String id) { assertNotEmpty(id, "id"); return db.find(DesignDocument.class, ensureDesignPrefix(id)); }
[ "public", "DesignDocument", "get", "(", "String", "id", ")", "{", "assertNotEmpty", "(", "id", ",", "\"id\"", ")", ";", "return", "db", ".", "find", "(", "DesignDocument", ".", "class", ",", "ensureDesignPrefix", "(", "id", ")", ")", ";", "}" ]
Gets a design document from the database. @param id the design document id (optionally prefixed with "_design/") @return {@link DesignDocument}
[ "Gets", "a", "design", "document", "from", "the", "database", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/DesignDocumentManager.java#L149-L152
164,449
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/DesignDocumentManager.java
DesignDocumentManager.get
public DesignDocument get(String id, String rev) { assertNotEmpty(id, "id"); assertNotEmpty(id, "rev"); return db.find(DesignDocument.class, ensureDesignPrefix(id), rev); }
java
public DesignDocument get(String id, String rev) { assertNotEmpty(id, "id"); assertNotEmpty(id, "rev"); return db.find(DesignDocument.class, ensureDesignPrefix(id), rev); }
[ "public", "DesignDocument", "get", "(", "String", "id", ",", "String", "rev", ")", "{", "assertNotEmpty", "(", "id", ",", "\"id\"", ")", ";", "assertNotEmpty", "(", "id", ",", "\"rev\"", ")", ";", "return", "db", ".", "find", "(", "DesignDocument", ".", "class", ",", "ensureDesignPrefix", "(", "id", ")", ",", "rev", ")", ";", "}" ]
Gets a design document using the id and revision from the database. @param id the document id (optionally prefixed with "_design/") @param rev the document revision @return {@link DesignDocument}
[ "Gets", "a", "design", "document", "using", "the", "id", "and", "revision", "from", "the", "database", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/DesignDocumentManager.java#L161-L165
164,450
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/DesignDocumentManager.java
DesignDocumentManager.remove
public Response remove(String id) { assertNotEmpty(id, "id"); id = ensureDesignPrefix(id); String revision = null; // Get the revision ID from ETag, removing leading and trailing " revision = client.executeRequest(Http.HEAD(new DatabaseURIHelper(db.getDBUri() ).documentUri(id))).getConnection().getHeaderField("ETag"); if (revision != null) { revision = revision.substring(1, revision.length() - 1); return db.remove(id, revision); } else { throw new CouchDbException("No ETag header found for design document with id " + id); } }
java
public Response remove(String id) { assertNotEmpty(id, "id"); id = ensureDesignPrefix(id); String revision = null; // Get the revision ID from ETag, removing leading and trailing " revision = client.executeRequest(Http.HEAD(new DatabaseURIHelper(db.getDBUri() ).documentUri(id))).getConnection().getHeaderField("ETag"); if (revision != null) { revision = revision.substring(1, revision.length() - 1); return db.remove(id, revision); } else { throw new CouchDbException("No ETag header found for design document with id " + id); } }
[ "public", "Response", "remove", "(", "String", "id", ")", "{", "assertNotEmpty", "(", "id", ",", "\"id\"", ")", ";", "id", "=", "ensureDesignPrefix", "(", "id", ")", ";", "String", "revision", "=", "null", ";", "// Get the revision ID from ETag, removing leading and trailing \"\r", "revision", "=", "client", ".", "executeRequest", "(", "Http", ".", "HEAD", "(", "new", "DatabaseURIHelper", "(", "db", ".", "getDBUri", "(", ")", ")", ".", "documentUri", "(", "id", ")", ")", ")", ".", "getConnection", "(", ")", ".", "getHeaderField", "(", "\"ETag\"", ")", ";", "if", "(", "revision", "!=", "null", ")", "{", "revision", "=", "revision", ".", "substring", "(", "1", ",", "revision", ".", "length", "(", ")", "-", "1", ")", ";", "return", "db", ".", "remove", "(", "id", ",", "revision", ")", ";", "}", "else", "{", "throw", "new", "CouchDbException", "(", "\"No ETag header found for design document with id \"", "+", "id", ")", ";", "}", "}" ]
Removes a design document from the database. @param id the document id (optionally prefixed with "_design/") @return {@link DesignDocument}
[ "Removes", "a", "design", "document", "from", "the", "database", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/DesignDocumentManager.java#L173-L186
164,451
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/DesignDocumentManager.java
DesignDocumentManager.remove
public Response remove(String id, String rev) { assertNotEmpty(id, "id"); assertNotEmpty(id, "rev"); return db.remove(ensureDesignPrefix(id), rev); }
java
public Response remove(String id, String rev) { assertNotEmpty(id, "id"); assertNotEmpty(id, "rev"); return db.remove(ensureDesignPrefix(id), rev); }
[ "public", "Response", "remove", "(", "String", "id", ",", "String", "rev", ")", "{", "assertNotEmpty", "(", "id", ",", "\"id\"", ")", ";", "assertNotEmpty", "(", "id", ",", "\"rev\"", ")", ";", "return", "db", ".", "remove", "(", "ensureDesignPrefix", "(", "id", ")", ",", "rev", ")", ";", "}" ]
Removes a design document using the id and rev from the database. @param id the document id (optionally prefixed with "_design/") @param rev the document revision @return {@link DesignDocument}
[ "Removes", "a", "design", "document", "using", "the", "id", "and", "rev", "from", "the", "database", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/DesignDocumentManager.java#L195-L200
164,452
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/DesignDocumentManager.java
DesignDocumentManager.remove
public Response remove(DesignDocument designDocument) { assertNotEmpty(designDocument, "DesignDocument"); ensureDesignPrefixObject(designDocument); return db.remove(designDocument); }
java
public Response remove(DesignDocument designDocument) { assertNotEmpty(designDocument, "DesignDocument"); ensureDesignPrefixObject(designDocument); return db.remove(designDocument); }
[ "public", "Response", "remove", "(", "DesignDocument", "designDocument", ")", "{", "assertNotEmpty", "(", "designDocument", ",", "\"DesignDocument\"", ")", ";", "ensureDesignPrefixObject", "(", "designDocument", ")", ";", "return", "db", ".", "remove", "(", "designDocument", ")", ";", "}" ]
Removes a design document using DesignDocument object from the database. @param designDocument the design document object to be removed @return {@link DesignDocument}
[ "Removes", "a", "design", "document", "using", "DesignDocument", "object", "from", "the", "database", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/DesignDocumentManager.java#L208-L212
164,453
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/DesignDocumentManager.java
DesignDocumentManager.list
public List<DesignDocument> list() throws IOException { return db.getAllDocsRequestBuilder() .startKey("_design/") .endKey("_design0") .inclusiveEnd(false) .includeDocs(true) .build() .getResponse().getDocsAs(DesignDocument.class); }
java
public List<DesignDocument> list() throws IOException { return db.getAllDocsRequestBuilder() .startKey("_design/") .endKey("_design0") .inclusiveEnd(false) .includeDocs(true) .build() .getResponse().getDocsAs(DesignDocument.class); }
[ "public", "List", "<", "DesignDocument", ">", "list", "(", ")", "throws", "IOException", "{", "return", "db", ".", "getAllDocsRequestBuilder", "(", ")", ".", "startKey", "(", "\"_design/\"", ")", ".", "endKey", "(", "\"_design0\"", ")", ".", "inclusiveEnd", "(", "false", ")", ".", "includeDocs", "(", "true", ")", ".", "build", "(", ")", ".", "getResponse", "(", ")", ".", "getDocsAs", "(", "DesignDocument", ".", "class", ")", ";", "}" ]
Performs a query to retrieve all the design documents defined in the database. @return a list of the design documents from the database @throws IOException if there was an error communicating with the server @since 2.5.0
[ "Performs", "a", "query", "to", "retrieve", "all", "the", "design", "documents", "defined", "in", "the", "database", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/DesignDocumentManager.java#L221-L229
164,454
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/DesignDocumentManager.java
DesignDocumentManager.fromDirectory
public static List<DesignDocument> fromDirectory(File directory) throws FileNotFoundException { List<DesignDocument> designDocuments = new ArrayList<DesignDocument>(); if (directory.isDirectory()) { Collection<File> files = FileUtils.listFiles(directory, null, true); for (File designDocFile : files) { designDocuments.add(fromFile(designDocFile)); } } else { designDocuments.add(fromFile(directory)); } return designDocuments; }
java
public static List<DesignDocument> fromDirectory(File directory) throws FileNotFoundException { List<DesignDocument> designDocuments = new ArrayList<DesignDocument>(); if (directory.isDirectory()) { Collection<File> files = FileUtils.listFiles(directory, null, true); for (File designDocFile : files) { designDocuments.add(fromFile(designDocFile)); } } else { designDocuments.add(fromFile(directory)); } return designDocuments; }
[ "public", "static", "List", "<", "DesignDocument", ">", "fromDirectory", "(", "File", "directory", ")", "throws", "FileNotFoundException", "{", "List", "<", "DesignDocument", ">", "designDocuments", "=", "new", "ArrayList", "<", "DesignDocument", ">", "(", ")", ";", "if", "(", "directory", ".", "isDirectory", "(", ")", ")", "{", "Collection", "<", "File", ">", "files", "=", "FileUtils", ".", "listFiles", "(", "directory", ",", "null", ",", "true", ")", ";", "for", "(", "File", "designDocFile", ":", "files", ")", "{", "designDocuments", ".", "add", "(", "fromFile", "(", "designDocFile", ")", ")", ";", "}", "}", "else", "{", "designDocuments", ".", "add", "(", "fromFile", "(", "directory", ")", ")", ";", "}", "return", "designDocuments", ";", "}" ]
Deserialize a directory of javascript design documents to a List of DesignDocument objects. @param directory the directory containing javascript files @return {@link DesignDocument} @throws FileNotFoundException if the file does not exist or cannot be read
[ "Deserialize", "a", "directory", "of", "javascript", "design", "documents", "to", "a", "List", "of", "DesignDocument", "objects", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/DesignDocumentManager.java#L238-L249
164,455
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/DesignDocumentManager.java
DesignDocumentManager.fromFile
public static DesignDocument fromFile(File file) throws FileNotFoundException { assertNotEmpty(file, "Design js file"); DesignDocument designDocument; Gson gson = new Gson(); InputStreamReader reader = null; try { reader = new InputStreamReader(new FileInputStream(file),"UTF-8"); //Deserialize JS file contents into DesignDocument object designDocument = gson.fromJson(reader, DesignDocument.class); return designDocument; } catch (UnsupportedEncodingException e) { //UTF-8 should be supported on all JVMs throw new RuntimeException(e); } finally { IOUtils.closeQuietly(reader); } }
java
public static DesignDocument fromFile(File file) throws FileNotFoundException { assertNotEmpty(file, "Design js file"); DesignDocument designDocument; Gson gson = new Gson(); InputStreamReader reader = null; try { reader = new InputStreamReader(new FileInputStream(file),"UTF-8"); //Deserialize JS file contents into DesignDocument object designDocument = gson.fromJson(reader, DesignDocument.class); return designDocument; } catch (UnsupportedEncodingException e) { //UTF-8 should be supported on all JVMs throw new RuntimeException(e); } finally { IOUtils.closeQuietly(reader); } }
[ "public", "static", "DesignDocument", "fromFile", "(", "File", "file", ")", "throws", "FileNotFoundException", "{", "assertNotEmpty", "(", "file", ",", "\"Design js file\"", ")", ";", "DesignDocument", "designDocument", ";", "Gson", "gson", "=", "new", "Gson", "(", ")", ";", "InputStreamReader", "reader", "=", "null", ";", "try", "{", "reader", "=", "new", "InputStreamReader", "(", "new", "FileInputStream", "(", "file", ")", ",", "\"UTF-8\"", ")", ";", "//Deserialize JS file contents into DesignDocument object\r", "designDocument", "=", "gson", ".", "fromJson", "(", "reader", ",", "DesignDocument", ".", "class", ")", ";", "return", "designDocument", ";", "}", "catch", "(", "UnsupportedEncodingException", "e", ")", "{", "//UTF-8 should be supported on all JVMs\r", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "finally", "{", "IOUtils", ".", "closeQuietly", "(", "reader", ")", ";", "}", "}" ]
Deserialize a javascript design document file to a DesignDocument object. @param file the design document javascript file (UTF-8 encoded) @return {@link DesignDocument} @throws FileNotFoundException if the file does not exist or cannot be read
[ "Deserialize", "a", "javascript", "design", "document", "file", "to", "a", "DesignDocument", "object", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/DesignDocumentManager.java#L258-L274
164,456
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/internal/views/PageMetadata.java
PageMetadata.forwardPaginationQueryParameters
static <K, V> ViewQueryParameters<K, V> forwardPaginationQueryParameters (ViewQueryParameters<K, V> initialQueryParameters, K startkey, String startkey_docid) { // Copy the initial query parameters ViewQueryParameters<K, V> pageParameters = initialQueryParameters.copy(); // Now override with the start keys provided pageParameters.setStartKey(startkey); pageParameters.setStartKeyDocId(startkey_docid); return pageParameters; }
java
static <K, V> ViewQueryParameters<K, V> forwardPaginationQueryParameters (ViewQueryParameters<K, V> initialQueryParameters, K startkey, String startkey_docid) { // Copy the initial query parameters ViewQueryParameters<K, V> pageParameters = initialQueryParameters.copy(); // Now override with the start keys provided pageParameters.setStartKey(startkey); pageParameters.setStartKeyDocId(startkey_docid); return pageParameters; }
[ "static", "<", "K", ",", "V", ">", "ViewQueryParameters", "<", "K", ",", "V", ">", "forwardPaginationQueryParameters", "(", "ViewQueryParameters", "<", "K", ",", "V", ">", "initialQueryParameters", ",", "K", "startkey", ",", "String", "startkey_docid", ")", "{", "// Copy the initial query parameters", "ViewQueryParameters", "<", "K", ",", "V", ">", "pageParameters", "=", "initialQueryParameters", ".", "copy", "(", ")", ";", "// Now override with the start keys provided", "pageParameters", ".", "setStartKey", "(", "startkey", ")", ";", "pageParameters", ".", "setStartKeyDocId", "(", "startkey_docid", ")", ";", "return", "pageParameters", ";", "}" ]
Generate query parameters for a forward page with the specified start key. @param initialQueryParameters page 1 query parameters @param startkey the startkey for the forward page @param startkey_docid the doc id for the startkey (in case of duplicate keys) @param <K> the view key type @param <V> the view value type @return the query parameters for the forward page
[ "Generate", "query", "parameters", "for", "a", "forward", "page", "with", "the", "specified", "start", "key", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/internal/views/PageMetadata.java#L78-L89
164,457
cloudant/java-cloudant
cloudant-http/src/main/java/com/cloudant/http/Http.java
Http.connect
public static HttpConnection connect(String requestMethod, URL url, String contentType) { return new HttpConnection(requestMethod, url, contentType); }
java
public static HttpConnection connect(String requestMethod, URL url, String contentType) { return new HttpConnection(requestMethod, url, contentType); }
[ "public", "static", "HttpConnection", "connect", "(", "String", "requestMethod", ",", "URL", "url", ",", "String", "contentType", ")", "{", "return", "new", "HttpConnection", "(", "requestMethod", ",", "url", ",", "contentType", ")", ";", "}" ]
low level http operations
[ "low", "level", "http", "operations" ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-http/src/main/java/com/cloudant/http/Http.java#L87-L91
164,458
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/internal/query/Builder.java
Builder.partialFilterSelector
public B partialFilterSelector(Selector selector) { instance.def.selector = Helpers.getJsonObjectFromSelector(selector); return returnThis(); }
java
public B partialFilterSelector(Selector selector) { instance.def.selector = Helpers.getJsonObjectFromSelector(selector); return returnThis(); }
[ "public", "B", "partialFilterSelector", "(", "Selector", "selector", ")", "{", "instance", ".", "def", ".", "selector", "=", "Helpers", ".", "getJsonObjectFromSelector", "(", "selector", ")", ";", "return", "returnThis", "(", ")", ";", "}" ]
Configure a selector to choose documents that should be added to the index.
[ "Configure", "a", "selector", "to", "choose", "documents", "that", "should", "be", "added", "to", "the", "index", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/internal/query/Builder.java#L69-L72
164,459
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/internal/query/Builder.java
Builder.fields
protected B fields(List<F> fields) { if (instance.def.fields == null) { instance.def.fields = new ArrayList<F>(fields.size()); } instance.def.fields.addAll(fields); return returnThis(); }
java
protected B fields(List<F> fields) { if (instance.def.fields == null) { instance.def.fields = new ArrayList<F>(fields.size()); } instance.def.fields.addAll(fields); return returnThis(); }
[ "protected", "B", "fields", "(", "List", "<", "F", ">", "fields", ")", "{", "if", "(", "instance", ".", "def", ".", "fields", "==", "null", ")", "{", "instance", ".", "def", ".", "fields", "=", "new", "ArrayList", "<", "F", ">", "(", "fields", ".", "size", "(", ")", ")", ";", "}", "instance", ".", "def", ".", "fields", ".", "addAll", "(", "fields", ")", ";", "return", "returnThis", "(", ")", ";", "}" ]
Add fields to the text index configuration. @param fields the {@link TextIndex.Field} configurations to add @return the builder for chaining
[ "Add", "fields", "to", "the", "text", "index", "configuration", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/internal/query/Builder.java#L80-L86
164,460
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDbClient.java
CouchDbClient.schedulerDoc
public SchedulerDocsResponse.Doc schedulerDoc(String docId) { assertNotEmpty(docId, "docId"); return this.get(new DatabaseURIHelper(getBaseUri()). path("_scheduler").path("docs").path("_replicator").path(docId).build(), SchedulerDocsResponse.Doc.class); }
java
public SchedulerDocsResponse.Doc schedulerDoc(String docId) { assertNotEmpty(docId, "docId"); return this.get(new DatabaseURIHelper(getBaseUri()). path("_scheduler").path("docs").path("_replicator").path(docId).build(), SchedulerDocsResponse.Doc.class); }
[ "public", "SchedulerDocsResponse", ".", "Doc", "schedulerDoc", "(", "String", "docId", ")", "{", "assertNotEmpty", "(", "docId", ",", "\"docId\"", ")", ";", "return", "this", ".", "get", "(", "new", "DatabaseURIHelper", "(", "getBaseUri", "(", ")", ")", ".", "path", "(", "\"_scheduler\"", ")", ".", "path", "(", "\"docs\"", ")", ".", "path", "(", "\"_replicator\"", ")", ".", "path", "(", "docId", ")", ".", "build", "(", ")", ",", "SchedulerDocsResponse", ".", "Doc", ".", "class", ")", ";", "}" ]
Get replication document state for a given replication document ID. @param docId The replication document ID @return Replication document for {@code docId}
[ "Get", "replication", "document", "state", "for", "a", "given", "replication", "document", "ID", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDbClient.java#L332-L337
164,461
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDbClient.java
CouchDbClient.uuids
public List<String> uuids(long count) { final URI uri = new URIBase(clientUri).path("_uuids").query("count", count).build(); final JsonObject json = get(uri, JsonObject.class); return getGson().fromJson(json.get("uuids").toString(), DeserializationTypes.STRINGS); }
java
public List<String> uuids(long count) { final URI uri = new URIBase(clientUri).path("_uuids").query("count", count).build(); final JsonObject json = get(uri, JsonObject.class); return getGson().fromJson(json.get("uuids").toString(), DeserializationTypes.STRINGS); }
[ "public", "List", "<", "String", ">", "uuids", "(", "long", "count", ")", "{", "final", "URI", "uri", "=", "new", "URIBase", "(", "clientUri", ")", ".", "path", "(", "\"_uuids\"", ")", ".", "query", "(", "\"count\"", ",", "count", ")", ".", "build", "(", ")", ";", "final", "JsonObject", "json", "=", "get", "(", "uri", ",", "JsonObject", ".", "class", ")", ";", "return", "getGson", "(", ")", ".", "fromJson", "(", "json", ".", "get", "(", "\"uuids\"", ")", ".", "toString", "(", ")", ",", "DeserializationTypes", ".", "STRINGS", ")", ";", "}" ]
Request a database sends a list of UUIDs. @param count The count of UUIDs.
[ "Request", "a", "database", "sends", "a", "list", "of", "UUIDs", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDbClient.java#L344-L348
164,462
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDbClient.java
CouchDbClient.executeToResponse
public Response executeToResponse(HttpConnection connection) { InputStream is = null; try { is = this.executeToInputStream(connection); Response response = getResponse(is, Response.class, getGson()); response.setStatusCode(connection.getConnection().getResponseCode()); response.setReason(connection.getConnection().getResponseMessage()); return response; } catch (IOException e) { throw new CouchDbException("Error retrieving response code or message.", e); } finally { close(is); } }
java
public Response executeToResponse(HttpConnection connection) { InputStream is = null; try { is = this.executeToInputStream(connection); Response response = getResponse(is, Response.class, getGson()); response.setStatusCode(connection.getConnection().getResponseCode()); response.setReason(connection.getConnection().getResponseMessage()); return response; } catch (IOException e) { throw new CouchDbException("Error retrieving response code or message.", e); } finally { close(is); } }
[ "public", "Response", "executeToResponse", "(", "HttpConnection", "connection", ")", "{", "InputStream", "is", "=", "null", ";", "try", "{", "is", "=", "this", ".", "executeToInputStream", "(", "connection", ")", ";", "Response", "response", "=", "getResponse", "(", "is", ",", "Response", ".", "class", ",", "getGson", "(", ")", ")", ";", "response", ".", "setStatusCode", "(", "connection", ".", "getConnection", "(", ")", ".", "getResponseCode", "(", ")", ")", ";", "response", ".", "setReason", "(", "connection", ".", "getConnection", "(", ")", ".", "getResponseMessage", "(", ")", ")", ";", "return", "response", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "CouchDbException", "(", "\"Error retrieving response code or message.\"", ",", "e", ")", ";", "}", "finally", "{", "close", "(", "is", ")", ";", "}", "}" ]
Executes a HTTP request and parses the JSON response into a Response instance. @param connection The HTTP request to execute. @return Response object of the deserialized JSON response
[ "Executes", "a", "HTTP", "request", "and", "parses", "the", "JSON", "response", "into", "a", "Response", "instance", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDbClient.java#L356-L369
164,463
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDbClient.java
CouchDbClient.delete
Response delete(URI uri) { HttpConnection connection = Http.DELETE(uri); return executeToResponse(connection); }
java
Response delete(URI uri) { HttpConnection connection = Http.DELETE(uri); return executeToResponse(connection); }
[ "Response", "delete", "(", "URI", "uri", ")", "{", "HttpConnection", "connection", "=", "Http", ".", "DELETE", "(", "uri", ")", ";", "return", "executeToResponse", "(", "connection", ")", ";", "}" ]
Performs a HTTP DELETE request. @return {@link Response}
[ "Performs", "a", "HTTP", "DELETE", "request", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDbClient.java#L376-L379
164,464
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDbClient.java
CouchDbClient.get
public <T> T get(URI uri, Class<T> classType) { HttpConnection connection = Http.GET(uri); InputStream response = executeToInputStream(connection); try { return getResponse(response, classType, getGson()); } finally { close(response); } }
java
public <T> T get(URI uri, Class<T> classType) { HttpConnection connection = Http.GET(uri); InputStream response = executeToInputStream(connection); try { return getResponse(response, classType, getGson()); } finally { close(response); } }
[ "public", "<", "T", ">", "T", "get", "(", "URI", "uri", ",", "Class", "<", "T", ">", "classType", ")", "{", "HttpConnection", "connection", "=", "Http", ".", "GET", "(", "uri", ")", ";", "InputStream", "response", "=", "executeToInputStream", "(", "connection", ")", ";", "try", "{", "return", "getResponse", "(", "response", ",", "classType", ",", "getGson", "(", ")", ")", ";", "}", "finally", "{", "close", "(", "response", ")", ";", "}", "}" ]
Performs a HTTP GET request. @return Class type of object T (i.e. {@link Response}
[ "Performs", "a", "HTTP", "GET", "request", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDbClient.java#L397-L405
164,465
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDbClient.java
CouchDbClient.put
Response put(URI uri, InputStream instream, String contentType) { HttpConnection connection = Http.PUT(uri, contentType); connection.setRequestBody(instream); return executeToResponse(connection); }
java
Response put(URI uri, InputStream instream, String contentType) { HttpConnection connection = Http.PUT(uri, contentType); connection.setRequestBody(instream); return executeToResponse(connection); }
[ "Response", "put", "(", "URI", "uri", ",", "InputStream", "instream", ",", "String", "contentType", ")", "{", "HttpConnection", "connection", "=", "Http", ".", "PUT", "(", "uri", ",", "contentType", ")", ";", "connection", ".", "setRequestBody", "(", "instream", ")", ";", "return", "executeToResponse", "(", "connection", ")", ";", "}" ]
Performs a HTTP PUT request, saves an attachment. @return {@link Response}
[ "Performs", "a", "HTTP", "PUT", "request", "saves", "an", "attachment", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDbClient.java#L445-L451
164,466
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDbClient.java
CouchDbClient.execute
public HttpConnection execute(HttpConnection connection) { //set our HttpUrlFactory on the connection connection.connectionFactory = factory; // all CouchClient requests want to receive application/json responses connection.requestProperties.put("Accept", "application/json"); connection.responseInterceptors.addAll(this.responseInterceptors); connection.requestInterceptors.addAll(this.requestInterceptors); InputStream es = null; // error stream - response from server for a 500 etc // first try to execute our request and get the input stream with the server's response // we want to catch IOException because HttpUrlConnection throws these for non-success // responses (eg 404 throws a FileNotFoundException) but we need to map to our own // specific exceptions try { try { connection = connection.execute(); } catch (HttpConnectionInterceptorException e) { CouchDbException exception = new CouchDbException(connection.getConnection() .getResponseMessage(), connection.getConnection().getResponseCode()); if (e.deserialize) { try { JsonObject errorResponse = new Gson().fromJson(e.error, JsonObject .class); exception.error = getAsString(errorResponse, "error"); exception.reason = getAsString(errorResponse, "reason"); } catch (JsonParseException jpe) { exception.error = e.error; } } else { exception.error = e.error; exception.reason = e.reason; } throw exception; } int code = connection.getConnection().getResponseCode(); String response = connection.getConnection().getResponseMessage(); // everything ok? return the stream if (code / 100 == 2) { // success [200,299] return connection; } else { final CouchDbException ex; switch (code) { case HttpURLConnection.HTTP_NOT_FOUND: //404 ex = new NoDocumentException(response); break; case HttpURLConnection.HTTP_CONFLICT: //409 ex = new DocumentConflictException(response); break; case HttpURLConnection.HTTP_PRECON_FAILED: //412 ex = new PreconditionFailedException(response); break; case 429: // If a Replay429Interceptor is present it will check for 429 and retry at // intervals. If the retries do not succeed or no 429 replay was configured // we end up here and throw a TooManyRequestsException. ex = new TooManyRequestsException(response); break; default: ex = new CouchDbException(response, code); break; } es = connection.getConnection().getErrorStream(); //if there is an error stream try to deserialize into the typed exception if (es != null) { try { //read the error stream into memory byte[] errorResponse = IOUtils.toByteArray(es); Class<? extends CouchDbException> exceptionClass = ex.getClass(); //treat the error as JSON and try to deserialize try { // Register an InstanceCreator that returns the existing exception so // we can just populate the fields, but not ignore the constructor. // Uses a new Gson so we don't accidentally recycle an exception. Gson g = new GsonBuilder().registerTypeAdapter(exceptionClass, new CouchDbExceptionInstanceCreator(ex)).create(); // Now populate the exception with the error/reason other info from JSON g.fromJson(new InputStreamReader(new ByteArrayInputStream (errorResponse), "UTF-8"), exceptionClass); } catch (JsonParseException e) { // The error stream was not JSON so just set the string content as the // error field on ex before we throw it ex.error = new String(errorResponse, "UTF-8"); } } finally { close(es); } } ex.setUrl(connection.url.toString()); throw ex; } } catch (IOException ioe) { CouchDbException ex = new CouchDbException("Error retrieving server response", ioe); ex.setUrl(connection.url.toString()); throw ex; } }
java
public HttpConnection execute(HttpConnection connection) { //set our HttpUrlFactory on the connection connection.connectionFactory = factory; // all CouchClient requests want to receive application/json responses connection.requestProperties.put("Accept", "application/json"); connection.responseInterceptors.addAll(this.responseInterceptors); connection.requestInterceptors.addAll(this.requestInterceptors); InputStream es = null; // error stream - response from server for a 500 etc // first try to execute our request and get the input stream with the server's response // we want to catch IOException because HttpUrlConnection throws these for non-success // responses (eg 404 throws a FileNotFoundException) but we need to map to our own // specific exceptions try { try { connection = connection.execute(); } catch (HttpConnectionInterceptorException e) { CouchDbException exception = new CouchDbException(connection.getConnection() .getResponseMessage(), connection.getConnection().getResponseCode()); if (e.deserialize) { try { JsonObject errorResponse = new Gson().fromJson(e.error, JsonObject .class); exception.error = getAsString(errorResponse, "error"); exception.reason = getAsString(errorResponse, "reason"); } catch (JsonParseException jpe) { exception.error = e.error; } } else { exception.error = e.error; exception.reason = e.reason; } throw exception; } int code = connection.getConnection().getResponseCode(); String response = connection.getConnection().getResponseMessage(); // everything ok? return the stream if (code / 100 == 2) { // success [200,299] return connection; } else { final CouchDbException ex; switch (code) { case HttpURLConnection.HTTP_NOT_FOUND: //404 ex = new NoDocumentException(response); break; case HttpURLConnection.HTTP_CONFLICT: //409 ex = new DocumentConflictException(response); break; case HttpURLConnection.HTTP_PRECON_FAILED: //412 ex = new PreconditionFailedException(response); break; case 429: // If a Replay429Interceptor is present it will check for 429 and retry at // intervals. If the retries do not succeed or no 429 replay was configured // we end up here and throw a TooManyRequestsException. ex = new TooManyRequestsException(response); break; default: ex = new CouchDbException(response, code); break; } es = connection.getConnection().getErrorStream(); //if there is an error stream try to deserialize into the typed exception if (es != null) { try { //read the error stream into memory byte[] errorResponse = IOUtils.toByteArray(es); Class<? extends CouchDbException> exceptionClass = ex.getClass(); //treat the error as JSON and try to deserialize try { // Register an InstanceCreator that returns the existing exception so // we can just populate the fields, but not ignore the constructor. // Uses a new Gson so we don't accidentally recycle an exception. Gson g = new GsonBuilder().registerTypeAdapter(exceptionClass, new CouchDbExceptionInstanceCreator(ex)).create(); // Now populate the exception with the error/reason other info from JSON g.fromJson(new InputStreamReader(new ByteArrayInputStream (errorResponse), "UTF-8"), exceptionClass); } catch (JsonParseException e) { // The error stream was not JSON so just set the string content as the // error field on ex before we throw it ex.error = new String(errorResponse, "UTF-8"); } } finally { close(es); } } ex.setUrl(connection.url.toString()); throw ex; } } catch (IOException ioe) { CouchDbException ex = new CouchDbException("Error retrieving server response", ioe); ex.setUrl(connection.url.toString()); throw ex; } }
[ "public", "HttpConnection", "execute", "(", "HttpConnection", "connection", ")", "{", "//set our HttpUrlFactory on the connection", "connection", ".", "connectionFactory", "=", "factory", ";", "// all CouchClient requests want to receive application/json responses", "connection", ".", "requestProperties", ".", "put", "(", "\"Accept\"", ",", "\"application/json\"", ")", ";", "connection", ".", "responseInterceptors", ".", "addAll", "(", "this", ".", "responseInterceptors", ")", ";", "connection", ".", "requestInterceptors", ".", "addAll", "(", "this", ".", "requestInterceptors", ")", ";", "InputStream", "es", "=", "null", ";", "// error stream - response from server for a 500 etc", "// first try to execute our request and get the input stream with the server's response", "// we want to catch IOException because HttpUrlConnection throws these for non-success", "// responses (eg 404 throws a FileNotFoundException) but we need to map to our own", "// specific exceptions", "try", "{", "try", "{", "connection", "=", "connection", ".", "execute", "(", ")", ";", "}", "catch", "(", "HttpConnectionInterceptorException", "e", ")", "{", "CouchDbException", "exception", "=", "new", "CouchDbException", "(", "connection", ".", "getConnection", "(", ")", ".", "getResponseMessage", "(", ")", ",", "connection", ".", "getConnection", "(", ")", ".", "getResponseCode", "(", ")", ")", ";", "if", "(", "e", ".", "deserialize", ")", "{", "try", "{", "JsonObject", "errorResponse", "=", "new", "Gson", "(", ")", ".", "fromJson", "(", "e", ".", "error", ",", "JsonObject", ".", "class", ")", ";", "exception", ".", "error", "=", "getAsString", "(", "errorResponse", ",", "\"error\"", ")", ";", "exception", ".", "reason", "=", "getAsString", "(", "errorResponse", ",", "\"reason\"", ")", ";", "}", "catch", "(", "JsonParseException", "jpe", ")", "{", "exception", ".", "error", "=", "e", ".", "error", ";", "}", "}", "else", "{", "exception", ".", "error", "=", "e", ".", "error", ";", "exception", ".", "reason", "=", "e", ".", "reason", ";", "}", "throw", "exception", ";", "}", "int", "code", "=", "connection", ".", "getConnection", "(", ")", ".", "getResponseCode", "(", ")", ";", "String", "response", "=", "connection", ".", "getConnection", "(", ")", ".", "getResponseMessage", "(", ")", ";", "// everything ok? return the stream", "if", "(", "code", "/", "100", "==", "2", ")", "{", "// success [200,299]", "return", "connection", ";", "}", "else", "{", "final", "CouchDbException", "ex", ";", "switch", "(", "code", ")", "{", "case", "HttpURLConnection", ".", "HTTP_NOT_FOUND", ":", "//404", "ex", "=", "new", "NoDocumentException", "(", "response", ")", ";", "break", ";", "case", "HttpURLConnection", ".", "HTTP_CONFLICT", ":", "//409", "ex", "=", "new", "DocumentConflictException", "(", "response", ")", ";", "break", ";", "case", "HttpURLConnection", ".", "HTTP_PRECON_FAILED", ":", "//412", "ex", "=", "new", "PreconditionFailedException", "(", "response", ")", ";", "break", ";", "case", "429", ":", "// If a Replay429Interceptor is present it will check for 429 and retry at", "// intervals. If the retries do not succeed or no 429 replay was configured", "// we end up here and throw a TooManyRequestsException.", "ex", "=", "new", "TooManyRequestsException", "(", "response", ")", ";", "break", ";", "default", ":", "ex", "=", "new", "CouchDbException", "(", "response", ",", "code", ")", ";", "break", ";", "}", "es", "=", "connection", ".", "getConnection", "(", ")", ".", "getErrorStream", "(", ")", ";", "//if there is an error stream try to deserialize into the typed exception", "if", "(", "es", "!=", "null", ")", "{", "try", "{", "//read the error stream into memory", "byte", "[", "]", "errorResponse", "=", "IOUtils", ".", "toByteArray", "(", "es", ")", ";", "Class", "<", "?", "extends", "CouchDbException", ">", "exceptionClass", "=", "ex", ".", "getClass", "(", ")", ";", "//treat the error as JSON and try to deserialize", "try", "{", "// Register an InstanceCreator that returns the existing exception so", "// we can just populate the fields, but not ignore the constructor.", "// Uses a new Gson so we don't accidentally recycle an exception.", "Gson", "g", "=", "new", "GsonBuilder", "(", ")", ".", "registerTypeAdapter", "(", "exceptionClass", ",", "new", "CouchDbExceptionInstanceCreator", "(", "ex", ")", ")", ".", "create", "(", ")", ";", "// Now populate the exception with the error/reason other info from JSON", "g", ".", "fromJson", "(", "new", "InputStreamReader", "(", "new", "ByteArrayInputStream", "(", "errorResponse", ")", ",", "\"UTF-8\"", ")", ",", "exceptionClass", ")", ";", "}", "catch", "(", "JsonParseException", "e", ")", "{", "// The error stream was not JSON so just set the string content as the", "// error field on ex before we throw it", "ex", ".", "error", "=", "new", "String", "(", "errorResponse", ",", "\"UTF-8\"", ")", ";", "}", "}", "finally", "{", "close", "(", "es", ")", ";", "}", "}", "ex", ".", "setUrl", "(", "connection", ".", "url", ".", "toString", "(", ")", ")", ";", "throw", "ex", ";", "}", "}", "catch", "(", "IOException", "ioe", ")", "{", "CouchDbException", "ex", "=", "new", "CouchDbException", "(", "\"Error retrieving server response\"", ",", "ioe", ")", ";", "ex", ".", "setUrl", "(", "connection", ".", "url", ".", "toString", "(", ")", ")", ";", "throw", "ex", ";", "}", "}" ]
Execute a HTTP request and handle common error cases. @param connection the HttpConnection request to execute @return the executed HttpConnection @throws CouchDbException for HTTP error codes or if an IOException was thrown
[ "Execute", "a", "HTTP", "request", "and", "handle", "common", "error", "cases", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDbClient.java#L535-L634
164,467
cloudant/java-cloudant
cloudant-http/src/main/java/com/cloudant/http/internal/interceptors/UserAgentInterceptor.java
UserAgentInterceptor.loadUA
private static String loadUA(ClassLoader loader, String filename){ String ua = "cloudant-http"; String version = "unknown"; final InputStream propStream = loader.getResourceAsStream(filename); final Properties properties = new Properties(); try { if (propStream != null) { try { properties.load(propStream); } finally { propStream.close(); } } ua = properties.getProperty("user.agent.name", ua); version = properties.getProperty("user.agent.version", version); } catch (IOException e) { // Swallow exception and use default values. } return String.format(Locale.ENGLISH, "%s/%s", ua,version); }
java
private static String loadUA(ClassLoader loader, String filename){ String ua = "cloudant-http"; String version = "unknown"; final InputStream propStream = loader.getResourceAsStream(filename); final Properties properties = new Properties(); try { if (propStream != null) { try { properties.load(propStream); } finally { propStream.close(); } } ua = properties.getProperty("user.agent.name", ua); version = properties.getProperty("user.agent.version", version); } catch (IOException e) { // Swallow exception and use default values. } return String.format(Locale.ENGLISH, "%s/%s", ua,version); }
[ "private", "static", "String", "loadUA", "(", "ClassLoader", "loader", ",", "String", "filename", ")", "{", "String", "ua", "=", "\"cloudant-http\"", ";", "String", "version", "=", "\"unknown\"", ";", "final", "InputStream", "propStream", "=", "loader", ".", "getResourceAsStream", "(", "filename", ")", ";", "final", "Properties", "properties", "=", "new", "Properties", "(", ")", ";", "try", "{", "if", "(", "propStream", "!=", "null", ")", "{", "try", "{", "properties", ".", "load", "(", "propStream", ")", ";", "}", "finally", "{", "propStream", ".", "close", "(", ")", ";", "}", "}", "ua", "=", "properties", ".", "getProperty", "(", "\"user.agent.name\"", ",", "ua", ")", ";", "version", "=", "properties", ".", "getProperty", "(", "\"user.agent.version\"", ",", "version", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "// Swallow exception and use default values.", "}", "return", "String", ".", "format", "(", "Locale", ".", "ENGLISH", ",", "\"%s/%s\"", ",", "ua", ",", "version", ")", ";", "}" ]
Loads the properties file using the classloader provided. Creating a string from the properties "user.agent.name" and "user.agent.version". @param loader The class loader to use to load the resource. @param filename The name of the file to load. @return A string that represents the first part of the UA string eg java-cloudant/2.6.1
[ "Loads", "the", "properties", "file", "using", "the", "classloader", "provided", ".", "Creating", "a", "string", "from", "the", "properties", "user", ".", "agent", ".", "name", "and", "user", ".", "agent", ".", "version", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-http/src/main/java/com/cloudant/http/internal/interceptors/UserAgentInterceptor.java#L73-L93
164,468
cloudant/java-cloudant
cloudant-http/src/main/java/com/cloudant/http/internal/interceptors/IamCookieInterceptor.java
IamCookieInterceptor.getBearerToken
private String getBearerToken(HttpConnectionInterceptorContext context) { final AtomicReference<String> iamTokenResponse = new AtomicReference<String>(); boolean result = super.requestCookie(context, iamServerUrl, iamTokenRequestBody, "application/x-www-form-urlencoded", "application/json", new StoreBearerCallable(iamTokenResponse)); if (result) { return iamTokenResponse.get(); } else { return null; } }
java
private String getBearerToken(HttpConnectionInterceptorContext context) { final AtomicReference<String> iamTokenResponse = new AtomicReference<String>(); boolean result = super.requestCookie(context, iamServerUrl, iamTokenRequestBody, "application/x-www-form-urlencoded", "application/json", new StoreBearerCallable(iamTokenResponse)); if (result) { return iamTokenResponse.get(); } else { return null; } }
[ "private", "String", "getBearerToken", "(", "HttpConnectionInterceptorContext", "context", ")", "{", "final", "AtomicReference", "<", "String", ">", "iamTokenResponse", "=", "new", "AtomicReference", "<", "String", ">", "(", ")", ";", "boolean", "result", "=", "super", ".", "requestCookie", "(", "context", ",", "iamServerUrl", ",", "iamTokenRequestBody", ",", "\"application/x-www-form-urlencoded\"", ",", "\"application/json\"", ",", "new", "StoreBearerCallable", "(", "iamTokenResponse", ")", ")", ";", "if", "(", "result", ")", "{", "return", "iamTokenResponse", ".", "get", "(", ")", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
get bearer token returned by IAM in JSON format
[ "get", "bearer", "token", "returned", "by", "IAM", "in", "JSON", "format" ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-http/src/main/java/com/cloudant/http/internal/interceptors/IamCookieInterceptor.java#L90-L100
164,469
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/query/QueryBuilder.java
QueryBuilder.useIndex
public QueryBuilder useIndex(String designDocument, String indexName) { useIndex = new String[]{designDocument, indexName}; return this; }
java
public QueryBuilder useIndex(String designDocument, String indexName) { useIndex = new String[]{designDocument, indexName}; return this; }
[ "public", "QueryBuilder", "useIndex", "(", "String", "designDocument", ",", "String", "indexName", ")", "{", "useIndex", "=", "new", "String", "[", "]", "{", "designDocument", ",", "indexName", "}", ";", "return", "this", ";", "}" ]
Instruct a query to use a specific index. @param designDocument Design document to use. @param indexName Index name to use. @return {@code QueryBuilder} object for method chaining.
[ "Instruct", "a", "query", "to", "use", "a", "specific", "index", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/query/QueryBuilder.java#L183-L186
164,470
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/query/QueryBuilder.java
QueryBuilder.quoteSort
private static String quoteSort(Sort[] sort) { LinkedList<String> sorts = new LinkedList<String>(); for (Sort pair : sort) { sorts.add(String.format("{%s: %s}", Helpers.quote(pair.getName()), Helpers.quote(pair.getOrder().toString()))); } return sorts.toString(); }
java
private static String quoteSort(Sort[] sort) { LinkedList<String> sorts = new LinkedList<String>(); for (Sort pair : sort) { sorts.add(String.format("{%s: %s}", Helpers.quote(pair.getName()), Helpers.quote(pair.getOrder().toString()))); } return sorts.toString(); }
[ "private", "static", "String", "quoteSort", "(", "Sort", "[", "]", "sort", ")", "{", "LinkedList", "<", "String", ">", "sorts", "=", "new", "LinkedList", "<", "String", ">", "(", ")", ";", "for", "(", "Sort", "pair", ":", "sort", ")", "{", "sorts", ".", "add", "(", "String", ".", "format", "(", "\"{%s: %s}\"", ",", "Helpers", ".", "quote", "(", "pair", ".", "getName", "(", ")", ")", ",", "Helpers", ".", "quote", "(", "pair", ".", "getOrder", "(", ")", ".", "toString", "(", ")", ")", ")", ")", ";", "}", "return", "sorts", ".", "toString", "(", ")", ";", "}" ]
sorts are a bit more awkward and need a helper...
[ "sorts", "are", "a", "bit", "more", "awkward", "and", "need", "a", "helper", "..." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/query/QueryBuilder.java#L240-L246
164,471
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/views/ViewRequestBuilder.java
ViewRequestBuilder.newMultipleRequest
public <K, V> MultipleRequestBuilder<K, V> newMultipleRequest(Key.Type<K> keyType, Class<V> valueType) { return new MultipleRequestBuilderImpl<K, V>(newViewRequestParameters(keyType.getType(), valueType)); }
java
public <K, V> MultipleRequestBuilder<K, V> newMultipleRequest(Key.Type<K> keyType, Class<V> valueType) { return new MultipleRequestBuilderImpl<K, V>(newViewRequestParameters(keyType.getType(), valueType)); }
[ "public", "<", "K", ",", "V", ">", "MultipleRequestBuilder", "<", "K", ",", "V", ">", "newMultipleRequest", "(", "Key", ".", "Type", "<", "K", ">", "keyType", ",", "Class", "<", "V", ">", "valueType", ")", "{", "return", "new", "MultipleRequestBuilderImpl", "<", "K", ",", "V", ">", "(", "newViewRequestParameters", "(", "keyType", ".", "getType", "(", ")", ",", "valueType", ")", ")", ";", "}" ]
Create a new builder for multiple unpaginated requests on the view. @param keyType {@link com.cloudant.client.api.views.Key.Type} of the key emitted by the view @param valueType class of the type of value emitted by the view @param <K> type of key emitted by the view @param <V> type of value emitted by the view @return a new {@link MultipleRequestBuilder} for the database view specified by this ViewRequestBuilder
[ "Create", "a", "new", "builder", "for", "multiple", "unpaginated", "requests", "on", "the", "view", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/views/ViewRequestBuilder.java#L118-L122
164,472
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDatabaseBase.java
CouchDatabaseBase.find
public <T> T find(Class<T> classType, String id, String rev) { assertNotEmpty(classType, "Class"); assertNotEmpty(id, "id"); assertNotEmpty(id, "rev"); final URI uri = new DatabaseURIHelper(dbUri).documentUri(id, "rev", rev); return couchDbClient.get(uri, classType); }
java
public <T> T find(Class<T> classType, String id, String rev) { assertNotEmpty(classType, "Class"); assertNotEmpty(id, "id"); assertNotEmpty(id, "rev"); final URI uri = new DatabaseURIHelper(dbUri).documentUri(id, "rev", rev); return couchDbClient.get(uri, classType); }
[ "public", "<", "T", ">", "T", "find", "(", "Class", "<", "T", ">", "classType", ",", "String", "id", ",", "String", "rev", ")", "{", "assertNotEmpty", "(", "classType", ",", "\"Class\"", ")", ";", "assertNotEmpty", "(", "id", ",", "\"id\"", ")", ";", "assertNotEmpty", "(", "id", ",", "\"rev\"", ")", ";", "final", "URI", "uri", "=", "new", "DatabaseURIHelper", "(", "dbUri", ")", ".", "documentUri", "(", "id", ",", "\"rev\"", ",", "rev", ")", ";", "return", "couchDbClient", ".", "get", "(", "uri", ",", "classType", ")", ";", "}" ]
Finds an Object of the specified type. @param <T> Object type. @param classType The class of type T. @param id The document _id field. @param rev The document _rev field. @return An object of type T. @throws NoDocumentException If the document is not found in the database.
[ "Finds", "an", "Object", "of", "the", "specified", "type", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDatabaseBase.java#L115-L121
164,473
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDatabaseBase.java
CouchDatabaseBase.contains
public boolean contains(String id) { assertNotEmpty(id, "id"); InputStream response = null; try { response = couchDbClient.head(new DatabaseURIHelper(dbUri).documentUri(id)); } catch (NoDocumentException e) { return false; } finally { close(response); } return true; }
java
public boolean contains(String id) { assertNotEmpty(id, "id"); InputStream response = null; try { response = couchDbClient.head(new DatabaseURIHelper(dbUri).documentUri(id)); } catch (NoDocumentException e) { return false; } finally { close(response); } return true; }
[ "public", "boolean", "contains", "(", "String", "id", ")", "{", "assertNotEmpty", "(", "id", ",", "\"id\"", ")", ";", "InputStream", "response", "=", "null", ";", "try", "{", "response", "=", "couchDbClient", ".", "head", "(", "new", "DatabaseURIHelper", "(", "dbUri", ")", ".", "documentUri", "(", "id", ")", ")", ";", "}", "catch", "(", "NoDocumentException", "e", ")", "{", "return", "false", ";", "}", "finally", "{", "close", "(", "response", ")", ";", "}", "return", "true", ";", "}" ]
Checks if a document exist in the database. @param id The document _id field. @return true If the document is found, false otherwise.
[ "Checks", "if", "a", "document", "exist", "in", "the", "database", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDatabaseBase.java#L173-L184
164,474
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDatabaseBase.java
CouchDatabaseBase.bulk
public List<Response> bulk(List<?> objects, boolean allOrNothing) { assertNotEmpty(objects, "objects"); InputStream responseStream = null; HttpConnection connection; try { final JsonObject jsonObject = new JsonObject(); if(allOrNothing) { jsonObject.addProperty("all_or_nothing", true); } final URI uri = new DatabaseURIHelper(dbUri).bulkDocsUri(); jsonObject.add("docs", getGson().toJsonTree(objects)); connection = Http.POST(uri, "application/json"); if (jsonObject.toString().length() != 0) { connection.setRequestBody(jsonObject.toString()); } couchDbClient.execute(connection); responseStream = connection.responseAsInputStream(); List<Response> bulkResponses = getResponseList(responseStream, getGson(), DeserializationTypes.LC_RESPONSES); for(Response response : bulkResponses) { response.setStatusCode(connection.getConnection().getResponseCode()); } return bulkResponses; } catch (IOException e) { throw new CouchDbException("Error retrieving response input stream.", e); } finally { close(responseStream); } }
java
public List<Response> bulk(List<?> objects, boolean allOrNothing) { assertNotEmpty(objects, "objects"); InputStream responseStream = null; HttpConnection connection; try { final JsonObject jsonObject = new JsonObject(); if(allOrNothing) { jsonObject.addProperty("all_or_nothing", true); } final URI uri = new DatabaseURIHelper(dbUri).bulkDocsUri(); jsonObject.add("docs", getGson().toJsonTree(objects)); connection = Http.POST(uri, "application/json"); if (jsonObject.toString().length() != 0) { connection.setRequestBody(jsonObject.toString()); } couchDbClient.execute(connection); responseStream = connection.responseAsInputStream(); List<Response> bulkResponses = getResponseList(responseStream, getGson(), DeserializationTypes.LC_RESPONSES); for(Response response : bulkResponses) { response.setStatusCode(connection.getConnection().getResponseCode()); } return bulkResponses; } catch (IOException e) { throw new CouchDbException("Error retrieving response input stream.", e); } finally { close(responseStream); } }
[ "public", "List", "<", "Response", ">", "bulk", "(", "List", "<", "?", ">", "objects", ",", "boolean", "allOrNothing", ")", "{", "assertNotEmpty", "(", "objects", ",", "\"objects\"", ")", ";", "InputStream", "responseStream", "=", "null", ";", "HttpConnection", "connection", ";", "try", "{", "final", "JsonObject", "jsonObject", "=", "new", "JsonObject", "(", ")", ";", "if", "(", "allOrNothing", ")", "{", "jsonObject", ".", "addProperty", "(", "\"all_or_nothing\"", ",", "true", ")", ";", "}", "final", "URI", "uri", "=", "new", "DatabaseURIHelper", "(", "dbUri", ")", ".", "bulkDocsUri", "(", ")", ";", "jsonObject", ".", "add", "(", "\"docs\"", ",", "getGson", "(", ")", ".", "toJsonTree", "(", "objects", ")", ")", ";", "connection", "=", "Http", ".", "POST", "(", "uri", ",", "\"application/json\"", ")", ";", "if", "(", "jsonObject", ".", "toString", "(", ")", ".", "length", "(", ")", "!=", "0", ")", "{", "connection", ".", "setRequestBody", "(", "jsonObject", ".", "toString", "(", ")", ")", ";", "}", "couchDbClient", ".", "execute", "(", "connection", ")", ";", "responseStream", "=", "connection", ".", "responseAsInputStream", "(", ")", ";", "List", "<", "Response", ">", "bulkResponses", "=", "getResponseList", "(", "responseStream", ",", "getGson", "(", ")", ",", "DeserializationTypes", ".", "LC_RESPONSES", ")", ";", "for", "(", "Response", "response", ":", "bulkResponses", ")", "{", "response", ".", "setStatusCode", "(", "connection", ".", "getConnection", "(", ")", ".", "getResponseCode", "(", ")", ")", ";", "}", "return", "bulkResponses", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "CouchDbException", "(", "\"Error retrieving response input stream.\"", ",", "e", ")", ";", "}", "finally", "{", "close", "(", "responseStream", ")", ";", "}", "}" ]
Performs a Bulk Documents insert request. @param objects The {@link List} of objects. @param allOrNothing Indicates whether the request has <tt>all-or-nothing</tt> semantics. @return {@code List<Response>} Containing the resulted entries.
[ "Performs", "a", "Bulk", "Documents", "insert", "request", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDatabaseBase.java#L269-L298
164,475
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/Search.java
Search.query
public <T> List<T> query(String query, Class<T> classOfT) { InputStream instream = null; List<T> result = new ArrayList<T>(); try { Reader reader = new InputStreamReader(instream = queryForStream(query), "UTF-8"); JsonObject json = new JsonParser().parse(reader).getAsJsonObject(); if (json.has("rows")) { if (!includeDocs) { log.warning("includeDocs set to false and attempting to retrieve doc. " + "null object will be returned"); } for (JsonElement e : json.getAsJsonArray("rows")) { result.add(jsonToObject(client.getGson(), e, "doc", classOfT)); } } else { log.warning("No ungrouped result available. Use queryGroups() if grouping set"); } return result; } catch (UnsupportedEncodingException e1) { // This should never happen as every implementation of the java platform is required // to support UTF-8. throw new RuntimeException(e1); } finally { close(instream); } }
java
public <T> List<T> query(String query, Class<T> classOfT) { InputStream instream = null; List<T> result = new ArrayList<T>(); try { Reader reader = new InputStreamReader(instream = queryForStream(query), "UTF-8"); JsonObject json = new JsonParser().parse(reader).getAsJsonObject(); if (json.has("rows")) { if (!includeDocs) { log.warning("includeDocs set to false and attempting to retrieve doc. " + "null object will be returned"); } for (JsonElement e : json.getAsJsonArray("rows")) { result.add(jsonToObject(client.getGson(), e, "doc", classOfT)); } } else { log.warning("No ungrouped result available. Use queryGroups() if grouping set"); } return result; } catch (UnsupportedEncodingException e1) { // This should never happen as every implementation of the java platform is required // to support UTF-8. throw new RuntimeException(e1); } finally { close(instream); } }
[ "public", "<", "T", ">", "List", "<", "T", ">", "query", "(", "String", "query", ",", "Class", "<", "T", ">", "classOfT", ")", "{", "InputStream", "instream", "=", "null", ";", "List", "<", "T", ">", "result", "=", "new", "ArrayList", "<", "T", ">", "(", ")", ";", "try", "{", "Reader", "reader", "=", "new", "InputStreamReader", "(", "instream", "=", "queryForStream", "(", "query", ")", ",", "\"UTF-8\"", ")", ";", "JsonObject", "json", "=", "new", "JsonParser", "(", ")", ".", "parse", "(", "reader", ")", ".", "getAsJsonObject", "(", ")", ";", "if", "(", "json", ".", "has", "(", "\"rows\"", ")", ")", "{", "if", "(", "!", "includeDocs", ")", "{", "log", ".", "warning", "(", "\"includeDocs set to false and attempting to retrieve doc. \"", "+", "\"null object will be returned\"", ")", ";", "}", "for", "(", "JsonElement", "e", ":", "json", ".", "getAsJsonArray", "(", "\"rows\"", ")", ")", "{", "result", ".", "add", "(", "jsonToObject", "(", "client", ".", "getGson", "(", ")", ",", "e", ",", "\"doc\"", ",", "classOfT", ")", ")", ";", "}", "}", "else", "{", "log", ".", "warning", "(", "\"No ungrouped result available. Use queryGroups() if grouping set\"", ")", ";", "}", "return", "result", ";", "}", "catch", "(", "UnsupportedEncodingException", "e1", ")", "{", "// This should never happen as every implementation of the java platform is required\r", "// to support UTF-8.\r", "throw", "new", "RuntimeException", "(", "e1", ")", ";", "}", "finally", "{", "close", "(", "instream", ")", ";", "}", "}" ]
Queries a Search Index and returns ungrouped results. In case the query used grouping, an empty list is returned @param <T> Object type T @param query the Lucene query to be passed to the Search index @param classOfT The class of type T @return The result of the search query as a {@code List<T> }
[ "Queries", "a", "Search", "Index", "and", "returns", "ungrouped", "results", ".", "In", "case", "the", "query", "used", "grouping", "an", "empty", "list", "is", "returned" ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/Search.java#L141-L166
164,476
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/Search.java
Search.queryGroups
public <T> Map<String, List<T>> queryGroups(String query, Class<T> classOfT) { InputStream instream = null; try { Reader reader = new InputStreamReader(instream = queryForStream(query), "UTF-8"); JsonObject json = new JsonParser().parse(reader).getAsJsonObject(); Map<String, List<T>> result = new LinkedHashMap<String, List<T>>(); if (json.has("groups")) { for (JsonElement e : json.getAsJsonArray("groups")) { String groupName = e.getAsJsonObject().get("by").getAsString(); List<T> orows = new ArrayList<T>(); if (!includeDocs) { log.warning("includeDocs set to false and attempting to retrieve doc. " + "null object will be returned"); } for (JsonElement rows : e.getAsJsonObject().getAsJsonArray("rows")) { orows.add(jsonToObject(client.getGson(), rows, "doc", classOfT)); } result.put(groupName, orows); }// end for(groups) }// end hasgroups else { log.warning("No grouped results available. Use query() if non grouped query"); } return result; } catch (UnsupportedEncodingException e1) { // This should never happen as every implementation of the java platform is required // to support UTF-8. throw new RuntimeException(e1); } finally { close(instream); } }
java
public <T> Map<String, List<T>> queryGroups(String query, Class<T> classOfT) { InputStream instream = null; try { Reader reader = new InputStreamReader(instream = queryForStream(query), "UTF-8"); JsonObject json = new JsonParser().parse(reader).getAsJsonObject(); Map<String, List<T>> result = new LinkedHashMap<String, List<T>>(); if (json.has("groups")) { for (JsonElement e : json.getAsJsonArray("groups")) { String groupName = e.getAsJsonObject().get("by").getAsString(); List<T> orows = new ArrayList<T>(); if (!includeDocs) { log.warning("includeDocs set to false and attempting to retrieve doc. " + "null object will be returned"); } for (JsonElement rows : e.getAsJsonObject().getAsJsonArray("rows")) { orows.add(jsonToObject(client.getGson(), rows, "doc", classOfT)); } result.put(groupName, orows); }// end for(groups) }// end hasgroups else { log.warning("No grouped results available. Use query() if non grouped query"); } return result; } catch (UnsupportedEncodingException e1) { // This should never happen as every implementation of the java platform is required // to support UTF-8. throw new RuntimeException(e1); } finally { close(instream); } }
[ "public", "<", "T", ">", "Map", "<", "String", ",", "List", "<", "T", ">", ">", "queryGroups", "(", "String", "query", ",", "Class", "<", "T", ">", "classOfT", ")", "{", "InputStream", "instream", "=", "null", ";", "try", "{", "Reader", "reader", "=", "new", "InputStreamReader", "(", "instream", "=", "queryForStream", "(", "query", ")", ",", "\"UTF-8\"", ")", ";", "JsonObject", "json", "=", "new", "JsonParser", "(", ")", ".", "parse", "(", "reader", ")", ".", "getAsJsonObject", "(", ")", ";", "Map", "<", "String", ",", "List", "<", "T", ">", ">", "result", "=", "new", "LinkedHashMap", "<", "String", ",", "List", "<", "T", ">", ">", "(", ")", ";", "if", "(", "json", ".", "has", "(", "\"groups\"", ")", ")", "{", "for", "(", "JsonElement", "e", ":", "json", ".", "getAsJsonArray", "(", "\"groups\"", ")", ")", "{", "String", "groupName", "=", "e", ".", "getAsJsonObject", "(", ")", ".", "get", "(", "\"by\"", ")", ".", "getAsString", "(", ")", ";", "List", "<", "T", ">", "orows", "=", "new", "ArrayList", "<", "T", ">", "(", ")", ";", "if", "(", "!", "includeDocs", ")", "{", "log", ".", "warning", "(", "\"includeDocs set to false and attempting to retrieve doc. \"", "+", "\"null object will be returned\"", ")", ";", "}", "for", "(", "JsonElement", "rows", ":", "e", ".", "getAsJsonObject", "(", ")", ".", "getAsJsonArray", "(", "\"rows\"", ")", ")", "{", "orows", ".", "add", "(", "jsonToObject", "(", "client", ".", "getGson", "(", ")", ",", "rows", ",", "\"doc\"", ",", "classOfT", ")", ")", ";", "}", "result", ".", "put", "(", "groupName", ",", "orows", ")", ";", "}", "// end for(groups)\r", "}", "// end hasgroups\r", "else", "{", "log", ".", "warning", "(", "\"No grouped results available. Use query() if non grouped query\"", ")", ";", "}", "return", "result", ";", "}", "catch", "(", "UnsupportedEncodingException", "e1", ")", "{", "// This should never happen as every implementation of the java platform is required\r", "// to support UTF-8.\r", "throw", "new", "RuntimeException", "(", "e1", ")", ";", "}", "finally", "{", "close", "(", "instream", ")", ";", "}", "}" ]
Queries a Search Index and returns grouped results in a map where key of the map is the groupName. In case the query didnt use grouping, an empty map is returned @param <T> Object type T @param query the Lucene query to be passed to the Search index @param classOfT The class of type T @return The result of the grouped search query as a ordered {@code Map<String,T> }
[ "Queries", "a", "Search", "Index", "and", "returns", "grouped", "results", "in", "a", "map", "where", "key", "of", "the", "map", "is", "the", "groupName", ".", "In", "case", "the", "query", "didnt", "use", "grouping", "an", "empty", "map", "is", "returned" ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/Search.java#L178-L209
164,477
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/Search.java
Search.groupField
public Search groupField(String fieldName, boolean isNumber) { assertNotEmpty(fieldName, "fieldName"); if (isNumber) { databaseHelper.query("group_field", fieldName + "<number>"); } else { databaseHelper.query("group_field", fieldName); } return this; }
java
public Search groupField(String fieldName, boolean isNumber) { assertNotEmpty(fieldName, "fieldName"); if (isNumber) { databaseHelper.query("group_field", fieldName + "<number>"); } else { databaseHelper.query("group_field", fieldName); } return this; }
[ "public", "Search", "groupField", "(", "String", "fieldName", ",", "boolean", "isNumber", ")", "{", "assertNotEmpty", "(", "fieldName", ",", "\"fieldName\"", ")", ";", "if", "(", "isNumber", ")", "{", "databaseHelper", ".", "query", "(", "\"group_field\"", ",", "fieldName", "+", "\"<number>\"", ")", ";", "}", "else", "{", "databaseHelper", ".", "query", "(", "\"group_field\"", ",", "fieldName", ")", ";", "}", "return", "this", ";", "}" ]
Group results by the specified field. @param fieldName by which to group results @param isNumber whether field isNumeric. @return this for additional parameter setting or to query
[ "Group", "results", "by", "the", "specified", "field", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/Search.java#L301-L309
164,478
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/Search.java
Search.counts
public Search counts(String[] countsfields) { assert (countsfields.length > 0); JsonArray countsJsonArray = new JsonArray(); for(String countsfield : countsfields) { JsonPrimitive element = new JsonPrimitive(countsfield); countsJsonArray.add(element); } databaseHelper.query("counts", countsJsonArray); return this; }
java
public Search counts(String[] countsfields) { assert (countsfields.length > 0); JsonArray countsJsonArray = new JsonArray(); for(String countsfield : countsfields) { JsonPrimitive element = new JsonPrimitive(countsfield); countsJsonArray.add(element); } databaseHelper.query("counts", countsJsonArray); return this; }
[ "public", "Search", "counts", "(", "String", "[", "]", "countsfields", ")", "{", "assert", "(", "countsfields", ".", "length", ">", "0", ")", ";", "JsonArray", "countsJsonArray", "=", "new", "JsonArray", "(", ")", ";", "for", "(", "String", "countsfield", ":", "countsfields", ")", "{", "JsonPrimitive", "element", "=", "new", "JsonPrimitive", "(", "countsfield", ")", ";", "countsJsonArray", ".", "add", "(", "element", ")", ";", "}", "databaseHelper", ".", "query", "(", "\"counts\"", ",", "countsJsonArray", ")", ";", "return", "this", ";", "}" ]
Array of fieldNames for which counts should be produced @param countsfields array of the field names @return this for additional parameter setting or to query
[ "Array", "of", "fieldNames", "for", "which", "counts", "should", "be", "produced" ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/Search.java#L358-L367
164,479
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/query/Indexes.java
Indexes.allIndexes
public List<Index<Field>> allIndexes() { List<Index<Field>> indexesOfAnyType = new ArrayList<Index<Field>>(); indexesOfAnyType.addAll(listIndexType(null, ListableIndex.class)); return indexesOfAnyType; }
java
public List<Index<Field>> allIndexes() { List<Index<Field>> indexesOfAnyType = new ArrayList<Index<Field>>(); indexesOfAnyType.addAll(listIndexType(null, ListableIndex.class)); return indexesOfAnyType; }
[ "public", "List", "<", "Index", "<", "Field", ">", ">", "allIndexes", "(", ")", "{", "List", "<", "Index", "<", "Field", ">>", "indexesOfAnyType", "=", "new", "ArrayList", "<", "Index", "<", "Field", ">", ">", "(", ")", ";", "indexesOfAnyType", ".", "addAll", "(", "listIndexType", "(", "null", ",", "ListableIndex", ".", "class", ")", ")", ";", "return", "indexesOfAnyType", ";", "}" ]
All the indexes defined in the database. Type widening means that the returned Index objects are limited to the name, design document and type of the index and the names of the fields. @return a list of defined indexes with name, design document, type and field names.
[ "All", "the", "indexes", "defined", "in", "the", "database", ".", "Type", "widening", "means", "that", "the", "returned", "Index", "objects", "are", "limited", "to", "the", "name", "design", "document", "and", "type", "of", "the", "index", "and", "the", "names", "of", "the", "fields", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/query/Indexes.java#L53-L57
164,480
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/query/Indexes.java
Indexes.listIndexType
private <T extends Index> List<T> listIndexType(String type, Class<T> modelType) { List<T> indexesOfType = new ArrayList<T>(); Gson g = new Gson(); for (JsonElement index : indexes) { if (index.isJsonObject()) { JsonObject indexDefinition = index.getAsJsonObject(); JsonElement indexType = indexDefinition.get("type"); if (indexType != null && indexType.isJsonPrimitive()) { JsonPrimitive indexTypePrimitive = indexType.getAsJsonPrimitive(); if (type == null || (indexTypePrimitive.isString() && indexTypePrimitive .getAsString().equals(type))) { indexesOfType.add(g.fromJson(indexDefinition, modelType)); } } } } return indexesOfType; }
java
private <T extends Index> List<T> listIndexType(String type, Class<T> modelType) { List<T> indexesOfType = new ArrayList<T>(); Gson g = new Gson(); for (JsonElement index : indexes) { if (index.isJsonObject()) { JsonObject indexDefinition = index.getAsJsonObject(); JsonElement indexType = indexDefinition.get("type"); if (indexType != null && indexType.isJsonPrimitive()) { JsonPrimitive indexTypePrimitive = indexType.getAsJsonPrimitive(); if (type == null || (indexTypePrimitive.isString() && indexTypePrimitive .getAsString().equals(type))) { indexesOfType.add(g.fromJson(indexDefinition, modelType)); } } } } return indexesOfType; }
[ "private", "<", "T", "extends", "Index", ">", "List", "<", "T", ">", "listIndexType", "(", "String", "type", ",", "Class", "<", "T", ">", "modelType", ")", "{", "List", "<", "T", ">", "indexesOfType", "=", "new", "ArrayList", "<", "T", ">", "(", ")", ";", "Gson", "g", "=", "new", "Gson", "(", ")", ";", "for", "(", "JsonElement", "index", ":", "indexes", ")", "{", "if", "(", "index", ".", "isJsonObject", "(", ")", ")", "{", "JsonObject", "indexDefinition", "=", "index", ".", "getAsJsonObject", "(", ")", ";", "JsonElement", "indexType", "=", "indexDefinition", ".", "get", "(", "\"type\"", ")", ";", "if", "(", "indexType", "!=", "null", "&&", "indexType", ".", "isJsonPrimitive", "(", ")", ")", "{", "JsonPrimitive", "indexTypePrimitive", "=", "indexType", ".", "getAsJsonPrimitive", "(", ")", ";", "if", "(", "type", "==", "null", "||", "(", "indexTypePrimitive", ".", "isString", "(", ")", "&&", "indexTypePrimitive", ".", "getAsString", "(", ")", ".", "equals", "(", "type", ")", ")", ")", "{", "indexesOfType", ".", "add", "(", "g", ".", "fromJson", "(", "indexDefinition", ",", "modelType", ")", ")", ";", "}", "}", "}", "}", "return", "indexesOfType", ";", "}" ]
Utility to list indexes of a given type. @param type the type of index to list, null means all types @param modelType the class to deserialize the index into @param <T> the type of the index @return the list of indexes of the specified type
[ "Utility", "to", "list", "indexes", "of", "a", "given", "type", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/query/Indexes.java#L67-L84
164,481
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/internal/URIBaseMethods.java
URIBaseMethods.encodePath
String encodePath(String in) { try { String encodedString = HierarchicalUriComponents.encodeUriComponent(in, "UTF-8", HierarchicalUriComponents.Type.PATH_SEGMENT); if (encodedString.startsWith(_design_prefix_encoded) || encodedString.startsWith(_local_prefix_encoded)) { // we replaced the first slash in the design or local doc URL, which we shouldn't // so let's put it back return encodedString.replaceFirst("%2F", "/"); } else { return encodedString; } } catch (UnsupportedEncodingException uee) { // This should never happen as every implementation of the java platform is required // to support UTF-8. throw new RuntimeException( "Couldn't encode ID " + in, uee); } }
java
String encodePath(String in) { try { String encodedString = HierarchicalUriComponents.encodeUriComponent(in, "UTF-8", HierarchicalUriComponents.Type.PATH_SEGMENT); if (encodedString.startsWith(_design_prefix_encoded) || encodedString.startsWith(_local_prefix_encoded)) { // we replaced the first slash in the design or local doc URL, which we shouldn't // so let's put it back return encodedString.replaceFirst("%2F", "/"); } else { return encodedString; } } catch (UnsupportedEncodingException uee) { // This should never happen as every implementation of the java platform is required // to support UTF-8. throw new RuntimeException( "Couldn't encode ID " + in, uee); } }
[ "String", "encodePath", "(", "String", "in", ")", "{", "try", "{", "String", "encodedString", "=", "HierarchicalUriComponents", ".", "encodeUriComponent", "(", "in", ",", "\"UTF-8\"", ",", "HierarchicalUriComponents", ".", "Type", ".", "PATH_SEGMENT", ")", ";", "if", "(", "encodedString", ".", "startsWith", "(", "_design_prefix_encoded", ")", "||", "encodedString", ".", "startsWith", "(", "_local_prefix_encoded", ")", ")", "{", "// we replaced the first slash in the design or local doc URL, which we shouldn't", "// so let's put it back", "return", "encodedString", ".", "replaceFirst", "(", "\"%2F\"", ",", "\"/\"", ")", ";", "}", "else", "{", "return", "encodedString", ";", "}", "}", "catch", "(", "UnsupportedEncodingException", "uee", ")", "{", "// This should never happen as every implementation of the java platform is required", "// to support UTF-8.", "throw", "new", "RuntimeException", "(", "\"Couldn't encode ID \"", "+", "in", ",", "uee", ")", ";", "}", "}" ]
Encode a path in a manner suitable for a GET request @param in The path to encode, eg "a/document" @return The encoded path eg "a%2Fdocument"
[ "Encode", "a", "path", "in", "a", "manner", "suitable", "for", "a", "GET", "request" ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/internal/URIBaseMethods.java#L92-L111
164,482
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/internal/URIBaseMethods.java
URIBaseMethods.build
public URI build() { try { String uriString = String.format("%s%s", baseUri.toASCIIString(), (path.isEmpty() ? "" : path)); if(qParams != null && qParams.size() > 0) { //Add queries together if both exist if(!completeQuery.isEmpty()) { uriString = String.format("%s?%s&%s", uriString, getJoinedQuery(qParams.getParams()), completeQuery); } else { uriString = String.format("%s?%s", uriString, getJoinedQuery(qParams.getParams())); } } else if(!completeQuery.isEmpty()) { uriString = String.format("%s?%s", uriString, completeQuery); } return new URI(uriString); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } }
java
public URI build() { try { String uriString = String.format("%s%s", baseUri.toASCIIString(), (path.isEmpty() ? "" : path)); if(qParams != null && qParams.size() > 0) { //Add queries together if both exist if(!completeQuery.isEmpty()) { uriString = String.format("%s?%s&%s", uriString, getJoinedQuery(qParams.getParams()), completeQuery); } else { uriString = String.format("%s?%s", uriString, getJoinedQuery(qParams.getParams())); } } else if(!completeQuery.isEmpty()) { uriString = String.format("%s?%s", uriString, completeQuery); } return new URI(uriString); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } }
[ "public", "URI", "build", "(", ")", "{", "try", "{", "String", "uriString", "=", "String", ".", "format", "(", "\"%s%s\"", ",", "baseUri", ".", "toASCIIString", "(", ")", ",", "(", "path", ".", "isEmpty", "(", ")", "?", "\"\"", ":", "path", ")", ")", ";", "if", "(", "qParams", "!=", "null", "&&", "qParams", ".", "size", "(", ")", ">", "0", ")", "{", "//Add queries together if both exist", "if", "(", "!", "completeQuery", ".", "isEmpty", "(", ")", ")", "{", "uriString", "=", "String", ".", "format", "(", "\"%s?%s&%s\"", ",", "uriString", ",", "getJoinedQuery", "(", "qParams", ".", "getParams", "(", ")", ")", ",", "completeQuery", ")", ";", "}", "else", "{", "uriString", "=", "String", ".", "format", "(", "\"%s?%s\"", ",", "uriString", ",", "getJoinedQuery", "(", "qParams", ".", "getParams", "(", ")", ")", ")", ";", "}", "}", "else", "if", "(", "!", "completeQuery", ".", "isEmpty", "(", ")", ")", "{", "uriString", "=", "String", ".", "format", "(", "\"%s?%s\"", ",", "uriString", ",", "completeQuery", ")", ";", "}", "return", "new", "URI", "(", "uriString", ")", ";", "}", "catch", "(", "URISyntaxException", "e", ")", "{", "throw", "new", "IllegalArgumentException", "(", "e", ")", ";", "}", "}" ]
Build and return the complete URI containing values such as the document ID, attachment ID, and query syntax.
[ "Build", "and", "return", "the", "complete", "URI", "containing", "values", "such", "as", "the", "document", "ID", "attachment", "ID", "and", "query", "syntax", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/internal/URIBaseMethods.java#L117-L139
164,483
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/ClientBuilder.java
ClientBuilder.account
public static ClientBuilder account(String account) { logger.config("Account: " + account); return ClientBuilder.url( convertStringToURL(String.format("https://%s.cloudant.com", account))); }
java
public static ClientBuilder account(String account) { logger.config("Account: " + account); return ClientBuilder.url( convertStringToURL(String.format("https://%s.cloudant.com", account))); }
[ "public", "static", "ClientBuilder", "account", "(", "String", "account", ")", "{", "logger", ".", "config", "(", "\"Account: \"", "+", "account", ")", ";", "return", "ClientBuilder", ".", "url", "(", "convertStringToURL", "(", "String", ".", "format", "(", "\"https://%s.cloudant.com\"", ",", "account", ")", ")", ")", ";", "}" ]
Constructs a new ClientBuilder for building a CloudantClient instance to connect to the Cloudant server with the specified account. @param account the Cloudant account name to connect to e.g. "example" is the account name for the "example.cloudant.com" endpoint @return a new ClientBuilder for the account @throws IllegalArgumentException if the specified account name forms an invalid endpoint URL
[ "Constructs", "a", "new", "ClientBuilder", "for", "building", "a", "CloudantClient", "instance", "to", "connect", "to", "the", "Cloudant", "server", "with", "the", "specified", "account", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/ClientBuilder.java#L184-L188
164,484
cloudant/java-cloudant
cloudant-http/src/main/java/com/cloudant/http/HttpConnection.java
HttpConnection.setRequestBody
public HttpConnection setRequestBody(final String input) { try { final byte[] inputBytes = input.getBytes("UTF-8"); return setRequestBody(inputBytes); } catch (UnsupportedEncodingException e) { // This should never happen as every implementation of the java platform is required // to support UTF-8. throw new RuntimeException(e); } }
java
public HttpConnection setRequestBody(final String input) { try { final byte[] inputBytes = input.getBytes("UTF-8"); return setRequestBody(inputBytes); } catch (UnsupportedEncodingException e) { // This should never happen as every implementation of the java platform is required // to support UTF-8. throw new RuntimeException(e); } }
[ "public", "HttpConnection", "setRequestBody", "(", "final", "String", "input", ")", "{", "try", "{", "final", "byte", "[", "]", "inputBytes", "=", "input", ".", "getBytes", "(", "\"UTF-8\"", ")", ";", "return", "setRequestBody", "(", "inputBytes", ")", ";", "}", "catch", "(", "UnsupportedEncodingException", "e", ")", "{", "// This should never happen as every implementation of the java platform is required", "// to support UTF-8.", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}" ]
Set the String of request body data to be sent to the server. @param input String of request body data to be sent to the server @return an {@link HttpConnection} for method chaining
[ "Set", "the", "String", "of", "request", "body", "data", "to", "be", "sent", "to", "the", "server", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-http/src/main/java/com/cloudant/http/HttpConnection.java#L156-L165
164,485
cloudant/java-cloudant
cloudant-http/src/main/java/com/cloudant/http/HttpConnection.java
HttpConnection.setRequestBody
public HttpConnection setRequestBody(final InputStream input, final long inputLength) { try { return setRequestBody(new InputStreamWrappingGenerator(input, inputLength), inputLength); } catch (IOException e) { logger.log(Level.SEVERE, "Error copying input stream for request body", e); throw new RuntimeException(e); } }
java
public HttpConnection setRequestBody(final InputStream input, final long inputLength) { try { return setRequestBody(new InputStreamWrappingGenerator(input, inputLength), inputLength); } catch (IOException e) { logger.log(Level.SEVERE, "Error copying input stream for request body", e); throw new RuntimeException(e); } }
[ "public", "HttpConnection", "setRequestBody", "(", "final", "InputStream", "input", ",", "final", "long", "inputLength", ")", "{", "try", "{", "return", "setRequestBody", "(", "new", "InputStreamWrappingGenerator", "(", "input", ",", "inputLength", ")", ",", "inputLength", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "logger", ".", "log", "(", "Level", ".", "SEVERE", ",", "\"Error copying input stream for request body\"", ",", "e", ")", ";", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}" ]
Set the InputStream of request body data, of known length, to be sent to the server. @param input InputStream of request body data to be sent to the server @param inputLength Length of request body data to be sent to the server, in bytes @return an {@link HttpConnection} for method chaining @deprecated Use {@link #setRequestBody(InputStreamGenerator, long)}
[ "Set", "the", "InputStream", "of", "request", "body", "data", "of", "known", "length", "to", "be", "sent", "to", "the", "server", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-http/src/main/java/com/cloudant/http/HttpConnection.java#L197-L205
164,486
cloudant/java-cloudant
cloudant-http/src/main/java/com/cloudant/http/HttpConnection.java
HttpConnection.getLogRequestIdentifier
private String getLogRequestIdentifier() { if (logIdentifier == null) { logIdentifier = String.format("%s-%s %s %s", Integer.toHexString(hashCode()), numberOfRetries, connection.getRequestMethod(), connection.getURL()); } return logIdentifier; }
java
private String getLogRequestIdentifier() { if (logIdentifier == null) { logIdentifier = String.format("%s-%s %s %s", Integer.toHexString(hashCode()), numberOfRetries, connection.getRequestMethod(), connection.getURL()); } return logIdentifier; }
[ "private", "String", "getLogRequestIdentifier", "(", ")", "{", "if", "(", "logIdentifier", "==", "null", ")", "{", "logIdentifier", "=", "String", ".", "format", "(", "\"%s-%s %s %s\"", ",", "Integer", ".", "toHexString", "(", "hashCode", "(", ")", ")", ",", "numberOfRetries", ",", "connection", ".", "getRequestMethod", "(", ")", ",", "connection", ".", "getURL", "(", ")", ")", ";", "}", "return", "logIdentifier", ";", "}" ]
Get a prefix for the log message to help identify which request is which and which responses belong to which requests.
[ "Get", "a", "prefix", "for", "the", "log", "message", "to", "help", "identify", "which", "request", "is", "which", "and", "which", "responses", "belong", "to", "which", "requests", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-http/src/main/java/com/cloudant/http/HttpConnection.java#L548-L554
164,487
tcurdt/jdeb
src/main/java/org/vafer/jdeb/signing/PGPSigner.java
PGPSigner.getSecretKey
private PGPSecretKey getSecretKey(InputStream input, String keyId) throws IOException, PGPException { PGPSecretKeyRingCollection keyrings = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(input), new JcaKeyFingerprintCalculator()); Iterator rIt = keyrings.getKeyRings(); while (rIt.hasNext()) { PGPSecretKeyRing kRing = (PGPSecretKeyRing) rIt.next(); Iterator kIt = kRing.getSecretKeys(); while (kIt.hasNext()) { PGPSecretKey key = (PGPSecretKey) kIt.next(); if (key.isSigningKey() && String.format("%08x", key.getKeyID() & 0xFFFFFFFFL).equals(keyId.toLowerCase())) { return key; } } } return null; }
java
private PGPSecretKey getSecretKey(InputStream input, String keyId) throws IOException, PGPException { PGPSecretKeyRingCollection keyrings = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(input), new JcaKeyFingerprintCalculator()); Iterator rIt = keyrings.getKeyRings(); while (rIt.hasNext()) { PGPSecretKeyRing kRing = (PGPSecretKeyRing) rIt.next(); Iterator kIt = kRing.getSecretKeys(); while (kIt.hasNext()) { PGPSecretKey key = (PGPSecretKey) kIt.next(); if (key.isSigningKey() && String.format("%08x", key.getKeyID() & 0xFFFFFFFFL).equals(keyId.toLowerCase())) { return key; } } } return null; }
[ "private", "PGPSecretKey", "getSecretKey", "(", "InputStream", "input", ",", "String", "keyId", ")", "throws", "IOException", ",", "PGPException", "{", "PGPSecretKeyRingCollection", "keyrings", "=", "new", "PGPSecretKeyRingCollection", "(", "PGPUtil", ".", "getDecoderStream", "(", "input", ")", ",", "new", "JcaKeyFingerprintCalculator", "(", ")", ")", ";", "Iterator", "rIt", "=", "keyrings", ".", "getKeyRings", "(", ")", ";", "while", "(", "rIt", ".", "hasNext", "(", ")", ")", "{", "PGPSecretKeyRing", "kRing", "=", "(", "PGPSecretKeyRing", ")", "rIt", ".", "next", "(", ")", ";", "Iterator", "kIt", "=", "kRing", ".", "getSecretKeys", "(", ")", ";", "while", "(", "kIt", ".", "hasNext", "(", ")", ")", "{", "PGPSecretKey", "key", "=", "(", "PGPSecretKey", ")", "kIt", ".", "next", "(", ")", ";", "if", "(", "key", ".", "isSigningKey", "(", ")", "&&", "String", ".", "format", "(", "\"%08x\"", ",", "key", ".", "getKeyID", "(", ")", "&", "0xFFFFFFFF", "L", ")", ".", "equals", "(", "keyId", ".", "toLowerCase", "(", ")", ")", ")", "{", "return", "key", ";", "}", "}", "}", "return", "null", ";", "}" ]
Returns the secret key matching the specified identifier. @param input the input stream containing the keyring collection @param keyId the 4 bytes identifier of the key
[ "Returns", "the", "secret", "key", "matching", "the", "specified", "identifier", "." ]
b899a7b1b3391356aafc491ab601f258961f67f0
https://github.com/tcurdt/jdeb/blob/b899a7b1b3391356aafc491ab601f258961f67f0/src/main/java/org/vafer/jdeb/signing/PGPSigner.java#L136-L155
164,488
tcurdt/jdeb
src/main/java/org/vafer/jdeb/signing/PGPSigner.java
PGPSigner.trim
private String trim(String line) { char[] chars = line.toCharArray(); int len = chars.length; while (len > 0) { if (!Character.isWhitespace(chars[len - 1])) { break; } len--; } return line.substring(0, len); }
java
private String trim(String line) { char[] chars = line.toCharArray(); int len = chars.length; while (len > 0) { if (!Character.isWhitespace(chars[len - 1])) { break; } len--; } return line.substring(0, len); }
[ "private", "String", "trim", "(", "String", "line", ")", "{", "char", "[", "]", "chars", "=", "line", ".", "toCharArray", "(", ")", ";", "int", "len", "=", "chars", ".", "length", ";", "while", "(", "len", ">", "0", ")", "{", "if", "(", "!", "Character", ".", "isWhitespace", "(", "chars", "[", "len", "-", "1", "]", ")", ")", "{", "break", ";", "}", "len", "--", ";", "}", "return", "line", ".", "substring", "(", "0", ",", "len", ")", ";", "}" ]
Trim the trailing spaces. @param line
[ "Trim", "the", "trailing", "spaces", "." ]
b899a7b1b3391356aafc491ab601f258961f67f0
https://github.com/tcurdt/jdeb/blob/b899a7b1b3391356aafc491ab601f258961f67f0/src/main/java/org/vafer/jdeb/signing/PGPSigner.java#L162-L174
164,489
tcurdt/jdeb
src/main/java/org/vafer/jdeb/DebMaker.java
DebMaker.validate
public void validate() throws PackagingException { if (control == null || !control.isDirectory()) { throw new PackagingException("The 'control' attribute doesn't point to a directory. " + control); } if (changesIn != null) { if (changesIn.exists() && (!changesIn.isFile() || !changesIn.canRead())) { throw new PackagingException("The 'changesIn' setting needs to point to a readable file. " + changesIn + " was not found/readable."); } if (changesOut != null && !isWritableFile(changesOut)) { throw new PackagingException("Cannot write the output for 'changesOut' to " + changesOut); } if (changesSave != null && !isWritableFile(changesSave)) { throw new PackagingException("Cannot write the output for 'changesSave' to " + changesSave); } } else { if (changesOut != null || changesSave != null) { throw new PackagingException("The 'changesOut' or 'changesSave' settings may only be used when there is a 'changesIn' specified."); } } if (Compression.toEnum(compression) == null) { throw new PackagingException("The compression method '" + compression + "' is not supported (expected 'none', 'gzip', 'bzip2' or 'xz')"); } if (deb == null) { throw new PackagingException("You need to specify where the deb file is supposed to be created."); } getDigestCode(digest); }
java
public void validate() throws PackagingException { if (control == null || !control.isDirectory()) { throw new PackagingException("The 'control' attribute doesn't point to a directory. " + control); } if (changesIn != null) { if (changesIn.exists() && (!changesIn.isFile() || !changesIn.canRead())) { throw new PackagingException("The 'changesIn' setting needs to point to a readable file. " + changesIn + " was not found/readable."); } if (changesOut != null && !isWritableFile(changesOut)) { throw new PackagingException("Cannot write the output for 'changesOut' to " + changesOut); } if (changesSave != null && !isWritableFile(changesSave)) { throw new PackagingException("Cannot write the output for 'changesSave' to " + changesSave); } } else { if (changesOut != null || changesSave != null) { throw new PackagingException("The 'changesOut' or 'changesSave' settings may only be used when there is a 'changesIn' specified."); } } if (Compression.toEnum(compression) == null) { throw new PackagingException("The compression method '" + compression + "' is not supported (expected 'none', 'gzip', 'bzip2' or 'xz')"); } if (deb == null) { throw new PackagingException("You need to specify where the deb file is supposed to be created."); } getDigestCode(digest); }
[ "public", "void", "validate", "(", ")", "throws", "PackagingException", "{", "if", "(", "control", "==", "null", "||", "!", "control", ".", "isDirectory", "(", ")", ")", "{", "throw", "new", "PackagingException", "(", "\"The 'control' attribute doesn't point to a directory. \"", "+", "control", ")", ";", "}", "if", "(", "changesIn", "!=", "null", ")", "{", "if", "(", "changesIn", ".", "exists", "(", ")", "&&", "(", "!", "changesIn", ".", "isFile", "(", ")", "||", "!", "changesIn", ".", "canRead", "(", ")", ")", ")", "{", "throw", "new", "PackagingException", "(", "\"The 'changesIn' setting needs to point to a readable file. \"", "+", "changesIn", "+", "\" was not found/readable.\"", ")", ";", "}", "if", "(", "changesOut", "!=", "null", "&&", "!", "isWritableFile", "(", "changesOut", ")", ")", "{", "throw", "new", "PackagingException", "(", "\"Cannot write the output for 'changesOut' to \"", "+", "changesOut", ")", ";", "}", "if", "(", "changesSave", "!=", "null", "&&", "!", "isWritableFile", "(", "changesSave", ")", ")", "{", "throw", "new", "PackagingException", "(", "\"Cannot write the output for 'changesSave' to \"", "+", "changesSave", ")", ";", "}", "}", "else", "{", "if", "(", "changesOut", "!=", "null", "||", "changesSave", "!=", "null", ")", "{", "throw", "new", "PackagingException", "(", "\"The 'changesOut' or 'changesSave' settings may only be used when there is a 'changesIn' specified.\"", ")", ";", "}", "}", "if", "(", "Compression", ".", "toEnum", "(", "compression", ")", "==", "null", ")", "{", "throw", "new", "PackagingException", "(", "\"The compression method '\"", "+", "compression", "+", "\"' is not supported (expected 'none', 'gzip', 'bzip2' or 'xz')\"", ")", ";", "}", "if", "(", "deb", "==", "null", ")", "{", "throw", "new", "PackagingException", "(", "\"You need to specify where the deb file is supposed to be created.\"", ")", ";", "}", "getDigestCode", "(", "digest", ")", ";", "}" ]
Validates the input parameters.
[ "Validates", "the", "input", "parameters", "." ]
b899a7b1b3391356aafc491ab601f258961f67f0
https://github.com/tcurdt/jdeb/blob/b899a7b1b3391356aafc491ab601f258961f67f0/src/main/java/org/vafer/jdeb/DebMaker.java#L248-L282
164,490
tcurdt/jdeb
src/main/java/org/vafer/jdeb/debian/ControlFile.java
ControlFile.getUserDefinedFieldName
protected String getUserDefinedFieldName(String field) { int index = field.indexOf('-'); char letter = getUserDefinedFieldLetter(); for (int i = 0; i < index; ++i) { if (field.charAt(i) == letter) { return field.substring(index + 1); } } return null; }
java
protected String getUserDefinedFieldName(String field) { int index = field.indexOf('-'); char letter = getUserDefinedFieldLetter(); for (int i = 0; i < index; ++i) { if (field.charAt(i) == letter) { return field.substring(index + 1); } } return null; }
[ "protected", "String", "getUserDefinedFieldName", "(", "String", "field", ")", "{", "int", "index", "=", "field", ".", "indexOf", "(", "'", "'", ")", ";", "char", "letter", "=", "getUserDefinedFieldLetter", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "index", ";", "++", "i", ")", "{", "if", "(", "field", ".", "charAt", "(", "i", ")", "==", "letter", ")", "{", "return", "field", ".", "substring", "(", "index", "+", "1", ")", ";", "}", "}", "return", "null", ";", "}" ]
Returns the user defined field without its prefix. @param field the name of the user defined field @return the user defined field without the prefix, or null if the fields doesn't apply to this control file. @since 1.1
[ "Returns", "the", "user", "defined", "field", "without", "its", "prefix", "." ]
b899a7b1b3391356aafc491ab601f258961f67f0
https://github.com/tcurdt/jdeb/blob/b899a7b1b3391356aafc491ab601f258961f67f0/src/main/java/org/vafer/jdeb/debian/ControlFile.java#L216-L227
164,491
tcurdt/jdeb
src/main/java/org/vafer/jdeb/utils/Utils.java
Utils.replaceVariables
public static String replaceVariables( final VariableResolver pResolver, final String pExpression, final String pOpen, final String pClose ) { final char[] open = pOpen.toCharArray(); final char[] close = pClose.toCharArray(); final StringBuilder out = new StringBuilder(); StringBuilder sb = new StringBuilder(); char[] last = null; int wo = 0; int wc = 0; int level = 0; for (char c : pExpression.toCharArray()) { if (c == open[wo]) { if (wc > 0) { sb.append(close, 0, wc); } wc = 0; wo++; if (open.length == wo) { // found open if (last == open) { out.append(open); } level++; out.append(sb); sb = new StringBuilder(); wo = 0; last = open; } } else if (c == close[wc]) { if (wo > 0) { sb.append(open, 0, wo); } wo = 0; wc++; if (close.length == wc) { // found close if (last == open) { final String variable = pResolver.get(sb.toString()); if (variable != null) { out.append(variable); } else { out.append(open); out.append(sb); out.append(close); } } else { out.append(sb); out.append(close); } sb = new StringBuilder(); level--; wc = 0; last = close; } } else { if (wo > 0) { sb.append(open, 0, wo); } if (wc > 0) { sb.append(close, 0, wc); } sb.append(c); wo = wc = 0; } } if (wo > 0) { sb.append(open, 0, wo); } if (wc > 0) { sb.append(close, 0, wc); } if (level > 0) { out.append(open); } out.append(sb); return out.toString(); }
java
public static String replaceVariables( final VariableResolver pResolver, final String pExpression, final String pOpen, final String pClose ) { final char[] open = pOpen.toCharArray(); final char[] close = pClose.toCharArray(); final StringBuilder out = new StringBuilder(); StringBuilder sb = new StringBuilder(); char[] last = null; int wo = 0; int wc = 0; int level = 0; for (char c : pExpression.toCharArray()) { if (c == open[wo]) { if (wc > 0) { sb.append(close, 0, wc); } wc = 0; wo++; if (open.length == wo) { // found open if (last == open) { out.append(open); } level++; out.append(sb); sb = new StringBuilder(); wo = 0; last = open; } } else if (c == close[wc]) { if (wo > 0) { sb.append(open, 0, wo); } wo = 0; wc++; if (close.length == wc) { // found close if (last == open) { final String variable = pResolver.get(sb.toString()); if (variable != null) { out.append(variable); } else { out.append(open); out.append(sb); out.append(close); } } else { out.append(sb); out.append(close); } sb = new StringBuilder(); level--; wc = 0; last = close; } } else { if (wo > 0) { sb.append(open, 0, wo); } if (wc > 0) { sb.append(close, 0, wc); } sb.append(c); wo = wc = 0; } } if (wo > 0) { sb.append(open, 0, wo); } if (wc > 0) { sb.append(close, 0, wc); } if (level > 0) { out.append(open); } out.append(sb); return out.toString(); }
[ "public", "static", "String", "replaceVariables", "(", "final", "VariableResolver", "pResolver", ",", "final", "String", "pExpression", ",", "final", "String", "pOpen", ",", "final", "String", "pClose", ")", "{", "final", "char", "[", "]", "open", "=", "pOpen", ".", "toCharArray", "(", ")", ";", "final", "char", "[", "]", "close", "=", "pClose", ".", "toCharArray", "(", ")", ";", "final", "StringBuilder", "out", "=", "new", "StringBuilder", "(", ")", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "char", "[", "]", "last", "=", "null", ";", "int", "wo", "=", "0", ";", "int", "wc", "=", "0", ";", "int", "level", "=", "0", ";", "for", "(", "char", "c", ":", "pExpression", ".", "toCharArray", "(", ")", ")", "{", "if", "(", "c", "==", "open", "[", "wo", "]", ")", "{", "if", "(", "wc", ">", "0", ")", "{", "sb", ".", "append", "(", "close", ",", "0", ",", "wc", ")", ";", "}", "wc", "=", "0", ";", "wo", "++", ";", "if", "(", "open", ".", "length", "==", "wo", ")", "{", "// found open", "if", "(", "last", "==", "open", ")", "{", "out", ".", "append", "(", "open", ")", ";", "}", "level", "++", ";", "out", ".", "append", "(", "sb", ")", ";", "sb", "=", "new", "StringBuilder", "(", ")", ";", "wo", "=", "0", ";", "last", "=", "open", ";", "}", "}", "else", "if", "(", "c", "==", "close", "[", "wc", "]", ")", "{", "if", "(", "wo", ">", "0", ")", "{", "sb", ".", "append", "(", "open", ",", "0", ",", "wo", ")", ";", "}", "wo", "=", "0", ";", "wc", "++", ";", "if", "(", "close", ".", "length", "==", "wc", ")", "{", "// found close", "if", "(", "last", "==", "open", ")", "{", "final", "String", "variable", "=", "pResolver", ".", "get", "(", "sb", ".", "toString", "(", ")", ")", ";", "if", "(", "variable", "!=", "null", ")", "{", "out", ".", "append", "(", "variable", ")", ";", "}", "else", "{", "out", ".", "append", "(", "open", ")", ";", "out", ".", "append", "(", "sb", ")", ";", "out", ".", "append", "(", "close", ")", ";", "}", "}", "else", "{", "out", ".", "append", "(", "sb", ")", ";", "out", ".", "append", "(", "close", ")", ";", "}", "sb", "=", "new", "StringBuilder", "(", ")", ";", "level", "--", ";", "wc", "=", "0", ";", "last", "=", "close", ";", "}", "}", "else", "{", "if", "(", "wo", ">", "0", ")", "{", "sb", ".", "append", "(", "open", ",", "0", ",", "wo", ")", ";", "}", "if", "(", "wc", ">", "0", ")", "{", "sb", ".", "append", "(", "close", ",", "0", ",", "wc", ")", ";", "}", "sb", ".", "append", "(", "c", ")", ";", "wo", "=", "wc", "=", "0", ";", "}", "}", "if", "(", "wo", ">", "0", ")", "{", "sb", ".", "append", "(", "open", ",", "0", ",", "wo", ")", ";", "}", "if", "(", "wc", ">", "0", ")", "{", "sb", ".", "append", "(", "close", ",", "0", ",", "wc", ")", ";", "}", "if", "(", "level", ">", "0", ")", "{", "out", ".", "append", "(", "open", ")", ";", "}", "out", ".", "append", "(", "sb", ")", ";", "return", "out", ".", "toString", "(", ")", ";", "}" ]
Substitute the variables in the given expression with the values from the resolver @param pResolver @param pExpression
[ "Substitute", "the", "variables", "in", "the", "given", "expression", "with", "the", "values", "from", "the", "resolver" ]
b899a7b1b3391356aafc491ab601f258961f67f0
https://github.com/tcurdt/jdeb/blob/b899a7b1b3391356aafc491ab601f258961f67f0/src/main/java/org/vafer/jdeb/utils/Utils.java#L129-L213
164,492
tcurdt/jdeb
src/main/java/org/vafer/jdeb/utils/Utils.java
Utils.toUnixLineEndings
public static byte[] toUnixLineEndings( InputStream input ) throws IOException { String encoding = "ISO-8859-1"; FixCrLfFilter filter = new FixCrLfFilter(new InputStreamReader(input, encoding)); filter.setEol(FixCrLfFilter.CrLf.newInstance("unix")); ByteArrayOutputStream filteredFile = new ByteArrayOutputStream(); Utils.copy(new ReaderInputStream(filter, encoding), filteredFile); return filteredFile.toByteArray(); }
java
public static byte[] toUnixLineEndings( InputStream input ) throws IOException { String encoding = "ISO-8859-1"; FixCrLfFilter filter = new FixCrLfFilter(new InputStreamReader(input, encoding)); filter.setEol(FixCrLfFilter.CrLf.newInstance("unix")); ByteArrayOutputStream filteredFile = new ByteArrayOutputStream(); Utils.copy(new ReaderInputStream(filter, encoding), filteredFile); return filteredFile.toByteArray(); }
[ "public", "static", "byte", "[", "]", "toUnixLineEndings", "(", "InputStream", "input", ")", "throws", "IOException", "{", "String", "encoding", "=", "\"ISO-8859-1\"", ";", "FixCrLfFilter", "filter", "=", "new", "FixCrLfFilter", "(", "new", "InputStreamReader", "(", "input", ",", "encoding", ")", ")", ";", "filter", ".", "setEol", "(", "FixCrLfFilter", ".", "CrLf", ".", "newInstance", "(", "\"unix\"", ")", ")", ";", "ByteArrayOutputStream", "filteredFile", "=", "new", "ByteArrayOutputStream", "(", ")", ";", "Utils", ".", "copy", "(", "new", "ReaderInputStream", "(", "filter", ",", "encoding", ")", ",", "filteredFile", ")", ";", "return", "filteredFile", ".", "toByteArray", "(", ")", ";", "}" ]
Replaces new line delimiters in the input stream with the Unix line feed. @param input
[ "Replaces", "new", "line", "delimiters", "in", "the", "input", "stream", "with", "the", "Unix", "line", "feed", "." ]
b899a7b1b3391356aafc491ab601f258961f67f0
https://github.com/tcurdt/jdeb/blob/b899a7b1b3391356aafc491ab601f258961f67f0/src/main/java/org/vafer/jdeb/utils/Utils.java#L220-L229
164,493
tcurdt/jdeb
src/main/java/org/vafer/jdeb/utils/Utils.java
Utils.movePath
public static String movePath( final String file, final String target ) { final String name = new File(file).getName(); return target.endsWith("/") ? target + name : target + '/' + name; }
java
public static String movePath( final String file, final String target ) { final String name = new File(file).getName(); return target.endsWith("/") ? target + name : target + '/' + name; }
[ "public", "static", "String", "movePath", "(", "final", "String", "file", ",", "final", "String", "target", ")", "{", "final", "String", "name", "=", "new", "File", "(", "file", ")", ".", "getName", "(", ")", ";", "return", "target", ".", "endsWith", "(", "\"/\"", ")", "?", "target", "+", "name", ":", "target", "+", "'", "'", "+", "name", ";", "}" ]
Construct new path by replacing file directory part. No files are actually modified. @param file path to move @param target new path directory
[ "Construct", "new", "path", "by", "replacing", "file", "directory", "part", ".", "No", "files", "are", "actually", "modified", "." ]
b899a7b1b3391356aafc491ab601f258961f67f0
https://github.com/tcurdt/jdeb/blob/b899a7b1b3391356aafc491ab601f258961f67f0/src/main/java/org/vafer/jdeb/utils/Utils.java#L299-L303
164,494
tcurdt/jdeb
src/main/java/org/vafer/jdeb/utils/Utils.java
Utils.lookupIfEmpty
public static String lookupIfEmpty( final String value, final Map<String, String> props, final String key ) { return value != null ? value : props.get(key); }
java
public static String lookupIfEmpty( final String value, final Map<String, String> props, final String key ) { return value != null ? value : props.get(key); }
[ "public", "static", "String", "lookupIfEmpty", "(", "final", "String", "value", ",", "final", "Map", "<", "String", ",", "String", ">", "props", ",", "final", "String", "key", ")", "{", "return", "value", "!=", "null", "?", "value", ":", "props", ".", "get", "(", "key", ")", ";", "}" ]
Extracts value from map if given value is null. @param value current value @param props properties to extract value from @param key property name to extract @return initial value or value extracted from map
[ "Extracts", "value", "from", "map", "if", "given", "value", "is", "null", "." ]
b899a7b1b3391356aafc491ab601f258961f67f0
https://github.com/tcurdt/jdeb/blob/b899a7b1b3391356aafc491ab601f258961f67f0/src/main/java/org/vafer/jdeb/utils/Utils.java#L312-L316
164,495
tcurdt/jdeb
src/main/java/org/vafer/jdeb/utils/Utils.java
Utils.getKnownPGPSecureRingLocations
public static Collection<String> getKnownPGPSecureRingLocations() { final LinkedHashSet<String> locations = new LinkedHashSet<String>(); final String os = System.getProperty("os.name"); final boolean runOnWindows = os == null || os.toLowerCase().contains("win"); if (runOnWindows) { // The user's roaming profile on Windows, via environment final String windowsRoaming = System.getenv("APPDATA"); if (windowsRoaming != null) { locations.add(joinLocalPath(windowsRoaming, "gnupg", "secring.gpg")); } // The user's local profile on Windows, via environment final String windowsLocal = System.getenv("LOCALAPPDATA"); if (windowsLocal != null) { locations.add(joinLocalPath(windowsLocal, "gnupg", "secring.gpg")); } // The Windows installation directory final String windir = System.getProperty("WINDIR"); if (windir != null) { // Local Profile on Windows 98 and ME locations.add(joinLocalPath(windir, "Application Data", "gnupg", "secring.gpg")); } } final String home = System.getProperty("user.home"); if (home != null && runOnWindows) { // These are for various flavours of Windows // if the environment variables above have failed // Roaming profile on Vista and later locations.add(joinLocalPath(home, "AppData", "Roaming", "gnupg", "secring.gpg")); // Local profile on Vista and later locations.add(joinLocalPath(home, "AppData", "Local", "gnupg", "secring.gpg")); // Roaming profile on 2000 and XP locations.add(joinLocalPath(home, "Application Data", "gnupg", "secring.gpg")); // Local profile on 2000 and XP locations.add(joinLocalPath(home, "Local Settings", "Application Data", "gnupg", "secring.gpg")); } // *nix, including OS X if (home != null) { locations.add(joinLocalPath(home, ".gnupg", "secring.gpg")); } return locations; }
java
public static Collection<String> getKnownPGPSecureRingLocations() { final LinkedHashSet<String> locations = new LinkedHashSet<String>(); final String os = System.getProperty("os.name"); final boolean runOnWindows = os == null || os.toLowerCase().contains("win"); if (runOnWindows) { // The user's roaming profile on Windows, via environment final String windowsRoaming = System.getenv("APPDATA"); if (windowsRoaming != null) { locations.add(joinLocalPath(windowsRoaming, "gnupg", "secring.gpg")); } // The user's local profile on Windows, via environment final String windowsLocal = System.getenv("LOCALAPPDATA"); if (windowsLocal != null) { locations.add(joinLocalPath(windowsLocal, "gnupg", "secring.gpg")); } // The Windows installation directory final String windir = System.getProperty("WINDIR"); if (windir != null) { // Local Profile on Windows 98 and ME locations.add(joinLocalPath(windir, "Application Data", "gnupg", "secring.gpg")); } } final String home = System.getProperty("user.home"); if (home != null && runOnWindows) { // These are for various flavours of Windows // if the environment variables above have failed // Roaming profile on Vista and later locations.add(joinLocalPath(home, "AppData", "Roaming", "gnupg", "secring.gpg")); // Local profile on Vista and later locations.add(joinLocalPath(home, "AppData", "Local", "gnupg", "secring.gpg")); // Roaming profile on 2000 and XP locations.add(joinLocalPath(home, "Application Data", "gnupg", "secring.gpg")); // Local profile on 2000 and XP locations.add(joinLocalPath(home, "Local Settings", "Application Data", "gnupg", "secring.gpg")); } // *nix, including OS X if (home != null) { locations.add(joinLocalPath(home, ".gnupg", "secring.gpg")); } return locations; }
[ "public", "static", "Collection", "<", "String", ">", "getKnownPGPSecureRingLocations", "(", ")", "{", "final", "LinkedHashSet", "<", "String", ">", "locations", "=", "new", "LinkedHashSet", "<", "String", ">", "(", ")", ";", "final", "String", "os", "=", "System", ".", "getProperty", "(", "\"os.name\"", ")", ";", "final", "boolean", "runOnWindows", "=", "os", "==", "null", "||", "os", ".", "toLowerCase", "(", ")", ".", "contains", "(", "\"win\"", ")", ";", "if", "(", "runOnWindows", ")", "{", "// The user's roaming profile on Windows, via environment", "final", "String", "windowsRoaming", "=", "System", ".", "getenv", "(", "\"APPDATA\"", ")", ";", "if", "(", "windowsRoaming", "!=", "null", ")", "{", "locations", ".", "add", "(", "joinLocalPath", "(", "windowsRoaming", ",", "\"gnupg\"", ",", "\"secring.gpg\"", ")", ")", ";", "}", "// The user's local profile on Windows, via environment", "final", "String", "windowsLocal", "=", "System", ".", "getenv", "(", "\"LOCALAPPDATA\"", ")", ";", "if", "(", "windowsLocal", "!=", "null", ")", "{", "locations", ".", "add", "(", "joinLocalPath", "(", "windowsLocal", ",", "\"gnupg\"", ",", "\"secring.gpg\"", ")", ")", ";", "}", "// The Windows installation directory", "final", "String", "windir", "=", "System", ".", "getProperty", "(", "\"WINDIR\"", ")", ";", "if", "(", "windir", "!=", "null", ")", "{", "// Local Profile on Windows 98 and ME", "locations", ".", "add", "(", "joinLocalPath", "(", "windir", ",", "\"Application Data\"", ",", "\"gnupg\"", ",", "\"secring.gpg\"", ")", ")", ";", "}", "}", "final", "String", "home", "=", "System", ".", "getProperty", "(", "\"user.home\"", ")", ";", "if", "(", "home", "!=", "null", "&&", "runOnWindows", ")", "{", "// These are for various flavours of Windows", "// if the environment variables above have failed", "// Roaming profile on Vista and later", "locations", ".", "add", "(", "joinLocalPath", "(", "home", ",", "\"AppData\"", ",", "\"Roaming\"", ",", "\"gnupg\"", ",", "\"secring.gpg\"", ")", ")", ";", "// Local profile on Vista and later", "locations", ".", "add", "(", "joinLocalPath", "(", "home", ",", "\"AppData\"", ",", "\"Local\"", ",", "\"gnupg\"", ",", "\"secring.gpg\"", ")", ")", ";", "// Roaming profile on 2000 and XP", "locations", ".", "add", "(", "joinLocalPath", "(", "home", ",", "\"Application Data\"", ",", "\"gnupg\"", ",", "\"secring.gpg\"", ")", ")", ";", "// Local profile on 2000 and XP", "locations", ".", "add", "(", "joinLocalPath", "(", "home", ",", "\"Local Settings\"", ",", "\"Application Data\"", ",", "\"gnupg\"", ",", "\"secring.gpg\"", ")", ")", ";", "}", "// *nix, including OS X", "if", "(", "home", "!=", "null", ")", "{", "locations", ".", "add", "(", "joinLocalPath", "(", "home", ",", "\".gnupg\"", ",", "\"secring.gpg\"", ")", ")", ";", "}", "return", "locations", ";", "}" ]
Get the known locations where the secure keyring can be located. Looks through known locations of the GNU PG secure keyring. @return The location of the PGP secure keyring if it was found, null otherwise
[ "Get", "the", "known", "locations", "where", "the", "secure", "keyring", "can", "be", "located", ".", "Looks", "through", "known", "locations", "of", "the", "GNU", "PG", "secure", "keyring", "." ]
b899a7b1b3391356aafc491ab601f258961f67f0
https://github.com/tcurdt/jdeb/blob/b899a7b1b3391356aafc491ab601f258961f67f0/src/main/java/org/vafer/jdeb/utils/Utils.java#L325-L374
164,496
tcurdt/jdeb
src/main/java/org/vafer/jdeb/utils/Utils.java
Utils.guessKeyRingFile
public static File guessKeyRingFile() throws FileNotFoundException { final Collection<String> possibleLocations = getKnownPGPSecureRingLocations(); for (final String location : possibleLocations) { final File candidate = new File(location); if (candidate.exists()) { return candidate; } } final StringBuilder message = new StringBuilder("Could not locate secure keyring, locations tried: "); final Iterator<String> it = possibleLocations.iterator(); while (it.hasNext()) { message.append(it.next()); if (it.hasNext()) { message.append(", "); } } throw new FileNotFoundException(message.toString()); }
java
public static File guessKeyRingFile() throws FileNotFoundException { final Collection<String> possibleLocations = getKnownPGPSecureRingLocations(); for (final String location : possibleLocations) { final File candidate = new File(location); if (candidate.exists()) { return candidate; } } final StringBuilder message = new StringBuilder("Could not locate secure keyring, locations tried: "); final Iterator<String> it = possibleLocations.iterator(); while (it.hasNext()) { message.append(it.next()); if (it.hasNext()) { message.append(", "); } } throw new FileNotFoundException(message.toString()); }
[ "public", "static", "File", "guessKeyRingFile", "(", ")", "throws", "FileNotFoundException", "{", "final", "Collection", "<", "String", ">", "possibleLocations", "=", "getKnownPGPSecureRingLocations", "(", ")", ";", "for", "(", "final", "String", "location", ":", "possibleLocations", ")", "{", "final", "File", "candidate", "=", "new", "File", "(", "location", ")", ";", "if", "(", "candidate", ".", "exists", "(", ")", ")", "{", "return", "candidate", ";", "}", "}", "final", "StringBuilder", "message", "=", "new", "StringBuilder", "(", "\"Could not locate secure keyring, locations tried: \"", ")", ";", "final", "Iterator", "<", "String", ">", "it", "=", "possibleLocations", ".", "iterator", "(", ")", ";", "while", "(", "it", ".", "hasNext", "(", ")", ")", "{", "message", ".", "append", "(", "it", ".", "next", "(", ")", ")", ";", "if", "(", "it", ".", "hasNext", "(", ")", ")", "{", "message", ".", "append", "(", "\", \"", ")", ";", "}", "}", "throw", "new", "FileNotFoundException", "(", "message", ".", "toString", "(", ")", ")", ";", "}" ]
Tries to guess location of the user secure keyring using various heuristics. @return path to the keyring file @throws FileNotFoundException if no keyring file found
[ "Tries", "to", "guess", "location", "of", "the", "user", "secure", "keyring", "using", "various", "heuristics", "." ]
b899a7b1b3391356aafc491ab601f258961f67f0
https://github.com/tcurdt/jdeb/blob/b899a7b1b3391356aafc491ab601f258961f67f0/src/main/java/org/vafer/jdeb/utils/Utils.java#L383-L400
164,497
tcurdt/jdeb
src/main/java/org/vafer/jdeb/utils/Utils.java
Utils.defaultString
public static String defaultString(final String str, final String fallback) { return isNullOrEmpty(str) ? fallback : str; }
java
public static String defaultString(final String str, final String fallback) { return isNullOrEmpty(str) ? fallback : str; }
[ "public", "static", "String", "defaultString", "(", "final", "String", "str", ",", "final", "String", "fallback", ")", "{", "return", "isNullOrEmpty", "(", "str", ")", "?", "fallback", ":", "str", ";", "}" ]
Return fallback if first string is null or empty
[ "Return", "fallback", "if", "first", "string", "is", "null", "or", "empty" ]
b899a7b1b3391356aafc491ab601f258961f67f0
https://github.com/tcurdt/jdeb/blob/b899a7b1b3391356aafc491ab601f258961f67f0/src/main/java/org/vafer/jdeb/utils/Utils.java#L412-L414
164,498
tcurdt/jdeb
src/main/java/org/vafer/jdeb/producers/Producers.java
Producers.defaultFileEntryWithName
static TarArchiveEntry defaultFileEntryWithName( final String fileName ) { TarArchiveEntry entry = new TarArchiveEntry(fileName, true); entry.setUserId(ROOT_UID); entry.setUserName(ROOT_NAME); entry.setGroupId(ROOT_UID); entry.setGroupName(ROOT_NAME); entry.setMode(TarArchiveEntry.DEFAULT_FILE_MODE); return entry; }
java
static TarArchiveEntry defaultFileEntryWithName( final String fileName ) { TarArchiveEntry entry = new TarArchiveEntry(fileName, true); entry.setUserId(ROOT_UID); entry.setUserName(ROOT_NAME); entry.setGroupId(ROOT_UID); entry.setGroupName(ROOT_NAME); entry.setMode(TarArchiveEntry.DEFAULT_FILE_MODE); return entry; }
[ "static", "TarArchiveEntry", "defaultFileEntryWithName", "(", "final", "String", "fileName", ")", "{", "TarArchiveEntry", "entry", "=", "new", "TarArchiveEntry", "(", "fileName", ",", "true", ")", ";", "entry", ".", "setUserId", "(", "ROOT_UID", ")", ";", "entry", ".", "setUserName", "(", "ROOT_NAME", ")", ";", "entry", ".", "setGroupId", "(", "ROOT_UID", ")", ";", "entry", ".", "setGroupName", "(", "ROOT_NAME", ")", ";", "entry", ".", "setMode", "(", "TarArchiveEntry", ".", "DEFAULT_FILE_MODE", ")", ";", "return", "entry", ";", "}" ]
Creates a tar file entry with defaults parameters. @param fileName the entry name @return file entry with reasonable defaults
[ "Creates", "a", "tar", "file", "entry", "with", "defaults", "parameters", "." ]
b899a7b1b3391356aafc491ab601f258961f67f0
https://github.com/tcurdt/jdeb/blob/b899a7b1b3391356aafc491ab601f258961f67f0/src/main/java/org/vafer/jdeb/producers/Producers.java#L42-L50
164,499
tcurdt/jdeb
src/main/java/org/vafer/jdeb/producers/Producers.java
Producers.defaultDirEntryWithName
static TarArchiveEntry defaultDirEntryWithName( final String dirName ) { TarArchiveEntry entry = new TarArchiveEntry(dirName, true); entry.setUserId(ROOT_UID); entry.setUserName(ROOT_NAME); entry.setGroupId(ROOT_UID); entry.setGroupName(ROOT_NAME); entry.setMode(TarArchiveEntry.DEFAULT_DIR_MODE); return entry; }
java
static TarArchiveEntry defaultDirEntryWithName( final String dirName ) { TarArchiveEntry entry = new TarArchiveEntry(dirName, true); entry.setUserId(ROOT_UID); entry.setUserName(ROOT_NAME); entry.setGroupId(ROOT_UID); entry.setGroupName(ROOT_NAME); entry.setMode(TarArchiveEntry.DEFAULT_DIR_MODE); return entry; }
[ "static", "TarArchiveEntry", "defaultDirEntryWithName", "(", "final", "String", "dirName", ")", "{", "TarArchiveEntry", "entry", "=", "new", "TarArchiveEntry", "(", "dirName", ",", "true", ")", ";", "entry", ".", "setUserId", "(", "ROOT_UID", ")", ";", "entry", ".", "setUserName", "(", "ROOT_NAME", ")", ";", "entry", ".", "setGroupId", "(", "ROOT_UID", ")", ";", "entry", ".", "setGroupName", "(", "ROOT_NAME", ")", ";", "entry", ".", "setMode", "(", "TarArchiveEntry", ".", "DEFAULT_DIR_MODE", ")", ";", "return", "entry", ";", "}" ]
Creates a tar directory entry with defaults parameters. @param dirName the directory name @return dir entry with reasonable defaults
[ "Creates", "a", "tar", "directory", "entry", "with", "defaults", "parameters", "." ]
b899a7b1b3391356aafc491ab601f258961f67f0
https://github.com/tcurdt/jdeb/blob/b899a7b1b3391356aafc491ab601f258961f67f0/src/main/java/org/vafer/jdeb/producers/Producers.java#L57-L65