repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
partition
stringclasses
1 value
defei/codelogger-utils
src/main/java/org/codelogger/utils/StringUtils.java
StringUtils.isBlank
public static boolean isBlank(final String source) { if (isEmpty(source)) { return true; } int strLen = source.length(); for (int i = 0; i < strLen; i++) { if (!Character.isWhitespace(source.charAt(i))) { return false; } } return true; }
java
public static boolean isBlank(final String source) { if (isEmpty(source)) { return true; } int strLen = source.length(); for (int i = 0; i < strLen; i++) { if (!Character.isWhitespace(source.charAt(i))) { return false; } } return true; }
[ "public", "static", "boolean", "isBlank", "(", "final", "String", "source", ")", "{", "if", "(", "isEmpty", "(", "source", ")", ")", "{", "return", "true", ";", "}", "int", "strLen", "=", "source", ".", "length", "(", ")", ";", "for", "(", "int", "...
Returns true if the source string is null or all characters in this string is space; false otherwise. @param source string to be tested. @return true if the source string is null or all characters in this string is space; false otherwise.
[ "Returns", "true", "if", "the", "source", "string", "is", "null", "or", "all", "characters", "in", "this", "string", "is", "space", ";", "false", "otherwise", "." ]
d906f5d217b783c7ae3e53442cd6fb87b20ecc0a
https://github.com/defei/codelogger-utils/blob/d906f5d217b783c7ae3e53442cd6fb87b20ecc0a/src/main/java/org/codelogger/utils/StringUtils.java#L52-L64
train
defei/codelogger-utils
src/main/java/org/codelogger/utils/StringUtils.java
StringUtils.indexOfIgnoreCase
public static int indexOfIgnoreCase(final String source, final String target) { int targetIndex = source.indexOf(target); if (targetIndex == INDEX_OF_NOT_FOUND) { String sourceLowerCase = source.toLowerCase(); String targetLowerCase = target.toLowerCase(); targetIndex = sourceLowerCase.indexOf(targetLowerCase); return targetIndex; } else { return targetIndex; } }
java
public static int indexOfIgnoreCase(final String source, final String target) { int targetIndex = source.indexOf(target); if (targetIndex == INDEX_OF_NOT_FOUND) { String sourceLowerCase = source.toLowerCase(); String targetLowerCase = target.toLowerCase(); targetIndex = sourceLowerCase.indexOf(targetLowerCase); return targetIndex; } else { return targetIndex; } }
[ "public", "static", "int", "indexOfIgnoreCase", "(", "final", "String", "source", ",", "final", "String", "target", ")", "{", "int", "targetIndex", "=", "source", ".", "indexOf", "(", "target", ")", ";", "if", "(", "targetIndex", "==", "INDEX_OF_NOT_FOUND", ...
Returns the index within given source string of the first occurrence of the specified target string with ignore case sensitive. @param source source string to be tested. @param target target string to be tested. @return index number if found, -1 otherwise.
[ "Returns", "the", "index", "within", "given", "source", "string", "of", "the", "first", "occurrence", "of", "the", "specified", "target", "string", "with", "ignore", "case", "sensitive", "." ]
d906f5d217b783c7ae3e53442cd6fb87b20ecc0a
https://github.com/defei/codelogger-utils/blob/d906f5d217b783c7ae3e53442cd6fb87b20ecc0a/src/main/java/org/codelogger/utils/StringUtils.java#L125-L136
train
defei/codelogger-utils
src/main/java/org/codelogger/utils/StringUtils.java
StringUtils.containsWord
public static boolean containsWord(final String text, final String word) { if (text == null || word == null) { return false; } if (text.contains(word)) { Matcher matcher = matchText(text); for (; matcher.find();) { String matchedWord = matcher.group(0); if (matchedWord.equals(word)) { return true; } } } return false; }
java
public static boolean containsWord(final String text, final String word) { if (text == null || word == null) { return false; } if (text.contains(word)) { Matcher matcher = matchText(text); for (; matcher.find();) { String matchedWord = matcher.group(0); if (matchedWord.equals(word)) { return true; } } } return false; }
[ "public", "static", "boolean", "containsWord", "(", "final", "String", "text", ",", "final", "String", "word", ")", "{", "if", "(", "text", "==", "null", "||", "word", "==", "null", ")", "{", "return", "false", ";", "}", "if", "(", "text", ".", "cont...
Returns true if given text contains given word; false otherwise. @param text string text to be tested. @param word string word to be tested. @return true if given text contains given word; false otherwise.
[ "Returns", "true", "if", "given", "text", "contains", "given", "word", ";", "false", "otherwise", "." ]
d906f5d217b783c7ae3e53442cd6fb87b20ecc0a
https://github.com/defei/codelogger-utils/blob/d906f5d217b783c7ae3e53442cd6fb87b20ecc0a/src/main/java/org/codelogger/utils/StringUtils.java#L254-L269
train
defei/codelogger-utils
src/main/java/org/codelogger/utils/StringUtils.java
StringUtils.containsWordIgnoreCase
public static boolean containsWordIgnoreCase(final String text, final String word) { if (text == null || word == null) { return false; } return containsWord(text.toLowerCase(), word.toLowerCase()); }
java
public static boolean containsWordIgnoreCase(final String text, final String word) { if (text == null || word == null) { return false; } return containsWord(text.toLowerCase(), word.toLowerCase()); }
[ "public", "static", "boolean", "containsWordIgnoreCase", "(", "final", "String", "text", ",", "final", "String", "word", ")", "{", "if", "(", "text", "==", "null", "||", "word", "==", "null", ")", "{", "return", "false", ";", "}", "return", "containsWord",...
Returns true if given text contains given word ignore case; false otherwise. @param text string text to be tested. @param word string word to be tested. @return true if given text contains given word ignore case; false otherwise.
[ "Returns", "true", "if", "given", "text", "contains", "given", "word", "ignore", "case", ";", "false", "otherwise", "." ]
d906f5d217b783c7ae3e53442cd6fb87b20ecc0a
https://github.com/defei/codelogger-utils/blob/d906f5d217b783c7ae3e53442cd6fb87b20ecc0a/src/main/java/org/codelogger/utils/StringUtils.java#L280-L286
train
defei/codelogger-utils
src/main/java/org/codelogger/utils/StringUtils.java
StringUtils.startsWithIgnoreCase
public static boolean startsWithIgnoreCase(final String source, final String target) { if (source.startsWith(target)) { return true; } if (source.length() < target.length()) { return false; } return source.substring(0, target.length()).equalsIgnoreCase(target); }
java
public static boolean startsWithIgnoreCase(final String source, final String target) { if (source.startsWith(target)) { return true; } if (source.length() < target.length()) { return false; } return source.substring(0, target.length()).equalsIgnoreCase(target); }
[ "public", "static", "boolean", "startsWithIgnoreCase", "(", "final", "String", "source", ",", "final", "String", "target", ")", "{", "if", "(", "source", ".", "startsWith", "(", "target", ")", ")", "{", "return", "true", ";", "}", "if", "(", "source", "....
Returns true if given source string start with target string ignore case sensitive; false otherwise. @param source string to be tested. @param target string to be tested. @return true if given source string start with target string ignore case sensitive; false otherwise.
[ "Returns", "true", "if", "given", "source", "string", "start", "with", "target", "string", "ignore", "case", "sensitive", ";", "false", "otherwise", "." ]
d906f5d217b783c7ae3e53442cd6fb87b20ecc0a
https://github.com/defei/codelogger-utils/blob/d906f5d217b783c7ae3e53442cd6fb87b20ecc0a/src/main/java/org/codelogger/utils/StringUtils.java#L311-L320
train
defei/codelogger-utils
src/main/java/org/codelogger/utils/StringUtils.java
StringUtils.endsWithIgnoreCase
public static boolean endsWithIgnoreCase(final String source, final String target) { if (source.endsWith(target)) { return true; } if (source.length() < target.length()) { return false; } return source.substring(source.length() - target.length()).equalsIgnoreCase(target); }
java
public static boolean endsWithIgnoreCase(final String source, final String target) { if (source.endsWith(target)) { return true; } if (source.length() < target.length()) { return false; } return source.substring(source.length() - target.length()).equalsIgnoreCase(target); }
[ "public", "static", "boolean", "endsWithIgnoreCase", "(", "final", "String", "source", ",", "final", "String", "target", ")", "{", "if", "(", "source", ".", "endsWith", "(", "target", ")", ")", "{", "return", "true", ";", "}", "if", "(", "source", ".", ...
Returns true if given source string end with target string ignore case sensitive; false otherwise. @param source string to be tested. @param target string to be tested. @return true if given source string end with target string ignore case sensitive; false otherwise.
[ "Returns", "true", "if", "given", "source", "string", "end", "with", "target", "string", "ignore", "case", "sensitive", ";", "false", "otherwise", "." ]
d906f5d217b783c7ae3e53442cd6fb87b20ecc0a
https://github.com/defei/codelogger-utils/blob/d906f5d217b783c7ae3e53442cd6fb87b20ecc0a/src/main/java/org/codelogger/utils/StringUtils.java#L331-L340
train
defei/codelogger-utils
src/main/java/org/codelogger/utils/StringUtils.java
StringUtils.getRandomString
public static String getRandomString(final int stringLength) { StringBuilder stringBuilder = getStringBuild(); for (int i = 0; i < stringLength; i++) { stringBuilder.append(getRandomAlphabetic()); } return stringBuilder.toString(); }
java
public static String getRandomString(final int stringLength) { StringBuilder stringBuilder = getStringBuild(); for (int i = 0; i < stringLength; i++) { stringBuilder.append(getRandomAlphabetic()); } return stringBuilder.toString(); }
[ "public", "static", "String", "getRandomString", "(", "final", "int", "stringLength", ")", "{", "StringBuilder", "stringBuilder", "=", "getStringBuild", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "stringLength", ";", "i", "++", ")", ...
Returns a random given length size alphabetic string. @param stringLength the length of the random string you want. @return a random given length size alphabetic string.
[ "Returns", "a", "random", "given", "length", "size", "alphabetic", "string", "." ]
d906f5d217b783c7ae3e53442cd6fb87b20ecc0a
https://github.com/defei/codelogger-utils/blob/d906f5d217b783c7ae3e53442cd6fb87b20ecc0a/src/main/java/org/codelogger/utils/StringUtils.java#L394-L401
train
defei/codelogger-utils
src/main/java/org/codelogger/utils/StringUtils.java
StringUtils.encoding
public static String encoding(final String source, final String sourceCharset, final String encodingCharset) throws IllegalArgumentException { byte[] sourceBytes; String encodeString = null; try { sourceBytes = source.getBytes(sourceCharset); encodeString = new String(sourceBytes, encodingCharset); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException(String.format("Unsupported encoding:%s or %s", sourceCharset, encodingCharset)); } return encodeString; }
java
public static String encoding(final String source, final String sourceCharset, final String encodingCharset) throws IllegalArgumentException { byte[] sourceBytes; String encodeString = null; try { sourceBytes = source.getBytes(sourceCharset); encodeString = new String(sourceBytes, encodingCharset); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException(String.format("Unsupported encoding:%s or %s", sourceCharset, encodingCharset)); } return encodeString; }
[ "public", "static", "String", "encoding", "(", "final", "String", "source", ",", "final", "String", "sourceCharset", ",", "final", "String", "encodingCharset", ")", "throws", "IllegalArgumentException", "{", "byte", "[", "]", "sourceBytes", ";", "String", "encodeS...
Return encoded string by given charset. @param source source string to be handle. @param sourceCharset source string charset name. @param encodingCharset want encoding to which charset. @return a new string has been encoded. @throws IllegalArgumentExceptionWORD_PATTERN If the named charset is not supported
[ "Return", "encoded", "string", "by", "given", "charset", "." ]
d906f5d217b783c7ae3e53442cd6fb87b20ecc0a
https://github.com/defei/codelogger-utils/blob/d906f5d217b783c7ae3e53442cd6fb87b20ecc0a/src/main/java/org/codelogger/utils/StringUtils.java#L443-L456
train
koendeschacht/bow-utils
src/main/java/be/bagofwords/util/NumUtils.java
NumUtils.getBorders
public static double[] getBorders(int numberOfBins, List<Double> counts) { Collections.sort(counts); if (!counts.isEmpty()) { List<Integer> borderInds = findBordersNaive(numberOfBins, counts); if (borderInds == null) { borderInds = findBorderIndsByRepeatedDividing(numberOfBins, counts); } double[] result = new double[borderInds.size()]; for (int i = 0; i < result.length; i++) { result[i] = counts.get(borderInds.get(i)); } return result; } else return new double[]{0.0}; }
java
public static double[] getBorders(int numberOfBins, List<Double> counts) { Collections.sort(counts); if (!counts.isEmpty()) { List<Integer> borderInds = findBordersNaive(numberOfBins, counts); if (borderInds == null) { borderInds = findBorderIndsByRepeatedDividing(numberOfBins, counts); } double[] result = new double[borderInds.size()]; for (int i = 0; i < result.length; i++) { result[i] = counts.get(borderInds.get(i)); } return result; } else return new double[]{0.0}; }
[ "public", "static", "double", "[", "]", "getBorders", "(", "int", "numberOfBins", ",", "List", "<", "Double", ">", "counts", ")", "{", "Collections", ".", "sort", "(", "counts", ")", ";", "if", "(", "!", "counts", ".", "isEmpty", "(", ")", ")", "{", ...
Carefull, this method sorts the counts list!
[ "Carefull", "this", "method", "sorts", "the", "counts", "list!" ]
f599da17cb7a40b8ffc5610a9761fa922e99d7cb
https://github.com/koendeschacht/bow-utils/blob/f599da17cb7a40b8ffc5610a9761fa922e99d7cb/src/main/java/be/bagofwords/util/NumUtils.java#L22-L36
train
wmdietl/jsr308-langtools
src/share/classes/com/sun/tools/sjavac/comp/Dependencies.java
Dependencies.getDependencies
public Map<String,Set<String>> getDependencies() { Map<String,Set<String>> new_deps = new HashMap<String,Set<String>>(); if (explicitPackages == null) return new_deps; for (Name pkg : explicitPackages) { Set<Name> set = deps.get(pkg); if (set != null) { Set<String> new_set = new_deps.get(pkg.toString()); if (new_set == null) { new_set = new HashSet<String>(); // Modules beware.... new_deps.put(":"+pkg.toString(), new_set); } for (Name d : set) { new_set.add(":"+d.toString()); } } } return new_deps; }
java
public Map<String,Set<String>> getDependencies() { Map<String,Set<String>> new_deps = new HashMap<String,Set<String>>(); if (explicitPackages == null) return new_deps; for (Name pkg : explicitPackages) { Set<Name> set = deps.get(pkg); if (set != null) { Set<String> new_set = new_deps.get(pkg.toString()); if (new_set == null) { new_set = new HashSet<String>(); // Modules beware.... new_deps.put(":"+pkg.toString(), new_set); } for (Name d : set) { new_set.add(":"+d.toString()); } } } return new_deps; }
[ "public", "Map", "<", "String", ",", "Set", "<", "String", ">", ">", "getDependencies", "(", ")", "{", "Map", "<", "String", ",", "Set", "<", "String", ">", ">", "new_deps", "=", "new", "HashMap", "<", "String", ",", "Set", "<", "String", ">", ">",...
Fetch the set of dependencies that are relevant to the compile that has just been performed. I.e. we are only interested in dependencies for classes that were explicitly compiled. @return
[ "Fetch", "the", "set", "of", "dependencies", "that", "are", "relevant", "to", "the", "compile", "that", "has", "just", "been", "performed", ".", "I", ".", "e", ".", "we", "are", "only", "interested", "in", "dependencies", "for", "classes", "that", "were", ...
8812d28c20f4de070a0dd6de1b45602431379834
https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/sjavac/comp/Dependencies.java#L91-L109
train
wmdietl/jsr308-langtools
src/share/classes/com/sun/tools/sjavac/comp/Dependencies.java
Dependencies.visitPubapi
public void visitPubapi(Element e) { Name n = ((ClassSymbol)e).fullname; Name p = ((ClassSymbol)e).packge().fullname; StringBuffer sb = publicApiPerClass.get(n); assert(sb == null); sb = new StringBuffer(); PubapiVisitor v = new PubapiVisitor(sb); v.visit(e); if (sb.length()>0) { publicApiPerClass.put(n, sb); } explicitPackages.add(p); }
java
public void visitPubapi(Element e) { Name n = ((ClassSymbol)e).fullname; Name p = ((ClassSymbol)e).packge().fullname; StringBuffer sb = publicApiPerClass.get(n); assert(sb == null); sb = new StringBuffer(); PubapiVisitor v = new PubapiVisitor(sb); v.visit(e); if (sb.length()>0) { publicApiPerClass.put(n, sb); } explicitPackages.add(p); }
[ "public", "void", "visitPubapi", "(", "Element", "e", ")", "{", "Name", "n", "=", "(", "(", "ClassSymbol", ")", "e", ")", ".", "fullname", ";", "Name", "p", "=", "(", "(", "ClassSymbol", ")", "e", ")", ".", "packge", "(", ")", ".", "fullname", ";...
Visit the api of a class and construct a pubapi string and store it into the pubapi_perclass map.
[ "Visit", "the", "api", "of", "a", "class", "and", "construct", "a", "pubapi", "string", "and", "store", "it", "into", "the", "pubapi_perclass", "map", "." ]
8812d28c20f4de070a0dd6de1b45602431379834
https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/sjavac/comp/Dependencies.java#L158-L170
train
wmdietl/jsr308-langtools
src/share/classes/com/sun/tools/sjavac/comp/Dependencies.java
Dependencies.collect
public void collect(Name currPkg, Name depPkg) { if (!currPkg.equals(depPkg)) { Set<Name> theset = deps.get(currPkg); if (theset==null) { theset = new HashSet<Name>(); deps.put(currPkg, theset); } theset.add(depPkg); } }
java
public void collect(Name currPkg, Name depPkg) { if (!currPkg.equals(depPkg)) { Set<Name> theset = deps.get(currPkg); if (theset==null) { theset = new HashSet<Name>(); deps.put(currPkg, theset); } theset.add(depPkg); } }
[ "public", "void", "collect", "(", "Name", "currPkg", ",", "Name", "depPkg", ")", "{", "if", "(", "!", "currPkg", ".", "equals", "(", "depPkg", ")", ")", "{", "Set", "<", "Name", ">", "theset", "=", "deps", ".", "get", "(", "currPkg", ")", ";", "i...
Collect a dependency. curr_pkg is marked as depending on dep_pkg.
[ "Collect", "a", "dependency", ".", "curr_pkg", "is", "marked", "as", "depending", "on", "dep_pkg", "." ]
8812d28c20f4de070a0dd6de1b45602431379834
https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/sjavac/comp/Dependencies.java#L175-L184
train
rFlex/SCJavaTools
src/main/java/me/corsin/javatools/misc/Pool.java
Pool.preload
@SuppressWarnings("unchecked") public void preload(int quantity) { Object[] objects = new Object[quantity]; for (int i = 0; i < quantity; i++) { objects[i] = this.instantiate(); } for (int i = 0; i < quantity; i++) { this.release((T)objects[i]); } }
java
@SuppressWarnings("unchecked") public void preload(int quantity) { Object[] objects = new Object[quantity]; for (int i = 0; i < quantity; i++) { objects[i] = this.instantiate(); } for (int i = 0; i < quantity; i++) { this.release((T)objects[i]); } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "void", "preload", "(", "int", "quantity", ")", "{", "Object", "[", "]", "objects", "=", "new", "Object", "[", "quantity", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "quant...
Instantiate quantity numbers of elements from the Pool and set them in the pool right away @param quantity
[ "Instantiate", "quantity", "numbers", "of", "elements", "from", "the", "Pool", "and", "set", "them", "in", "the", "pool", "right", "away" ]
6bafee99f12a6ad73265db64776edac2bab71f67
https://github.com/rFlex/SCJavaTools/blob/6bafee99f12a6ad73265db64776edac2bab71f67/src/main/java/me/corsin/javatools/misc/Pool.java#L87-L98
train
theHilikus/JRoboCom
jrobocom-core/src/main/java/com/github/thehilikus/jrobocom/timing/Delayer.java
Delayer.blockMe
private void blockMe(int cyclesToBlock) { long unblock = cycles + cyclesToBlock; BlockedEntry newEntry = new BlockedEntry(unblock); blockedCollection.add(newEntry); while (unblock > cycles) { try { newEntry.getSync().acquire(); // blocks } catch (InterruptedException exc) { log.error("[temporaryBlock] Spurious wakeup", exc); } } }
java
private void blockMe(int cyclesToBlock) { long unblock = cycles + cyclesToBlock; BlockedEntry newEntry = new BlockedEntry(unblock); blockedCollection.add(newEntry); while (unblock > cycles) { try { newEntry.getSync().acquire(); // blocks } catch (InterruptedException exc) { log.error("[temporaryBlock] Spurious wakeup", exc); } } }
[ "private", "void", "blockMe", "(", "int", "cyclesToBlock", ")", "{", "long", "unblock", "=", "cycles", "+", "cyclesToBlock", ";", "BlockedEntry", "newEntry", "=", "new", "BlockedEntry", "(", "unblock", ")", ";", "blockedCollection", ".", "add", "(", "newEntry"...
Blocks the calling thread until enough turns have elapsed @param cyclesToBlock number of ticks to block
[ "Blocks", "the", "calling", "thread", "until", "enough", "turns", "have", "elapsed" ]
0e31c1ecf1006e35f68c229ff66c37640effffac
https://github.com/theHilikus/JRoboCom/blob/0e31c1ecf1006e35f68c229ff66c37640effffac/jrobocom-core/src/main/java/com/github/thehilikus/jrobocom/timing/Delayer.java#L34-L48
train
theHilikus/JRoboCom
jrobocom-core/src/main/java/com/github/thehilikus/jrobocom/timing/Delayer.java
Delayer.tick
public void tick() { log.trace("Tick {}", cycles); cycles++; // check for robots up for unblocking for (BlockedEntry entry : blockedCollection) { if (entry.getTimeout() >= cycles) { entry.getSync().release(); } } }
java
public void tick() { log.trace("Tick {}", cycles); cycles++; // check for robots up for unblocking for (BlockedEntry entry : blockedCollection) { if (entry.getTimeout() >= cycles) { entry.getSync().release(); } } }
[ "public", "void", "tick", "(", ")", "{", "log", ".", "trace", "(", "\"Tick {}\"", ",", "cycles", ")", ";", "cycles", "++", ";", "// check for robots up for unblocking", "for", "(", "BlockedEntry", "entry", ":", "blockedCollection", ")", "{", "if", "(", "entr...
Signals one cycles has elapsed
[ "Signals", "one", "cycles", "has", "elapsed" ]
0e31c1ecf1006e35f68c229ff66c37640effffac
https://github.com/theHilikus/JRoboCom/blob/0e31c1ecf1006e35f68c229ff66c37640effffac/jrobocom-core/src/main/java/com/github/thehilikus/jrobocom/timing/Delayer.java#L53-L64
train
theHilikus/JRoboCom
jrobocom-core/src/main/java/com/github/thehilikus/jrobocom/timing/Delayer.java
Delayer.waitFor
public void waitFor(Integer clientId, int turns, String reason) { // for safety, check if we know the robot, otherwise fail if (!registered.contains(clientId)) { throw new IllegalArgumentException("Unknown robot. All robots must first register with clock"); } synchronized (waitingList) { if (waitingList.contains(clientId)) { throw new IllegalArgumentException("Client " + clientId + " is already waiting, no multithreading is allowed"); } waitingList.add(clientId); } // we are in the robot's thread log.trace("[waitFor] Blocking {} for {} turns. Reason: {}", clientId, turns, reason); blockMe(turns); log.trace("[waitFor] Unblocked {} - {}", clientId, reason); synchronized (waitingList) { waitingList.remove(clientId); } }
java
public void waitFor(Integer clientId, int turns, String reason) { // for safety, check if we know the robot, otherwise fail if (!registered.contains(clientId)) { throw new IllegalArgumentException("Unknown robot. All robots must first register with clock"); } synchronized (waitingList) { if (waitingList.contains(clientId)) { throw new IllegalArgumentException("Client " + clientId + " is already waiting, no multithreading is allowed"); } waitingList.add(clientId); } // we are in the robot's thread log.trace("[waitFor] Blocking {} for {} turns. Reason: {}", clientId, turns, reason); blockMe(turns); log.trace("[waitFor] Unblocked {} - {}", clientId, reason); synchronized (waitingList) { waitingList.remove(clientId); } }
[ "public", "void", "waitFor", "(", "Integer", "clientId", ",", "int", "turns", ",", "String", "reason", ")", "{", "// for safety, check if we know the robot, otherwise fail", "if", "(", "!", "registered", ".", "contains", "(", "clientId", ")", ")", "{", "throw", ...
Blocks the calling thread for the specified number of cycles @param clientId unique ID of the client. @param turns the number of clock ticks to block @param reason explanation for the wait
[ "Blocks", "the", "calling", "thread", "for", "the", "specified", "number", "of", "cycles" ]
0e31c1ecf1006e35f68c229ff66c37640effffac
https://github.com/theHilikus/JRoboCom/blob/0e31c1ecf1006e35f68c229ff66c37640effffac/jrobocom-core/src/main/java/com/github/thehilikus/jrobocom/timing/Delayer.java#L92-L118
train
brianwhu/xillium
gear/src/main/java/org/xillium/gear/auth/NonceShop.java
NonceShop.produce
public String produce(int size) { byte bytes[] = new byte[size]; _random.nextBytes(bytes); return Strings.toHexString(bytes); }
java
public String produce(int size) { byte bytes[] = new byte[size]; _random.nextBytes(bytes); return Strings.toHexString(bytes); }
[ "public", "String", "produce", "(", "int", "size", ")", "{", "byte", "bytes", "[", "]", "=", "new", "byte", "[", "size", "]", ";", "_random", ".", "nextBytes", "(", "bytes", ")", ";", "return", "Strings", ".", "toHexString", "(", "bytes", ")", ";", ...
Produces a nonce of an arbitrary size in bytes, which is not to be proved later. @param size the size of the nonce in bytes @return the new nonce as a hexadecimal string
[ "Produces", "a", "nonce", "of", "an", "arbitrary", "size", "in", "bytes", "which", "is", "not", "to", "be", "proved", "later", "." ]
e8dbf8cb6589fa1031a0bfcdcb58cb03d2ba7799
https://github.com/brianwhu/xillium/blob/e8dbf8cb6589fa1031a0bfcdcb58cb03d2ba7799/gear/src/main/java/org/xillium/gear/auth/NonceShop.java#L42-L46
train
brianwhu/xillium
gear/src/main/java/org/xillium/gear/auth/NonceShop.java
NonceShop.produce
public String produce(String state, long time) { Nonce nonce = new Nonce(INSTANCE, time > 0 ? time : TTL, SIZE, _random); _map.put(state + ':' + nonce.value, nonce); return nonce.value; }
java
public String produce(String state, long time) { Nonce nonce = new Nonce(INSTANCE, time > 0 ? time : TTL, SIZE, _random); _map.put(state + ':' + nonce.value, nonce); return nonce.value; }
[ "public", "String", "produce", "(", "String", "state", ",", "long", "time", ")", "{", "Nonce", "nonce", "=", "new", "Nonce", "(", "INSTANCE", ",", "time", ">", "0", "?", "time", ":", "TTL", ",", "SIZE", ",", "_random", ")", ";", "_map", ".", "put",...
Produces a nonce that is associated with the given state and is to be proved within a time limit. @param state an arbitrary state to be associated with the new nonce. @param time the TTL of the new nonce, in milliseconds. If this parameter is 0 or negative, the default TTL is used instead. @return the new nonce as a hexadecimal string
[ "Produces", "a", "nonce", "that", "is", "associated", "with", "the", "given", "state", "and", "is", "to", "be", "proved", "within", "a", "time", "limit", "." ]
e8dbf8cb6589fa1031a0bfcdcb58cb03d2ba7799
https://github.com/brianwhu/xillium/blob/e8dbf8cb6589fa1031a0bfcdcb58cb03d2ba7799/gear/src/main/java/org/xillium/gear/auth/NonceShop.java#L55-L59
train
brianwhu/xillium
gear/src/main/java/org/xillium/gear/auth/NonceShop.java
NonceShop.renew
public boolean renew(String value, String state, long time) { Nonce nonce = _map.get(state + ':' + value); if (nonce != null && !nonce.hasExpired()) { nonce.renew(time > 0 ? time : TTL); return true; } else { return false; } }
java
public boolean renew(String value, String state, long time) { Nonce nonce = _map.get(state + ':' + value); if (nonce != null && !nonce.hasExpired()) { nonce.renew(time > 0 ? time : TTL); return true; } else { return false; } }
[ "public", "boolean", "renew", "(", "String", "value", ",", "String", "state", ",", "long", "time", ")", "{", "Nonce", "nonce", "=", "_map", ".", "get", "(", "state", "+", "'", "'", "+", "value", ")", ";", "if", "(", "nonce", "!=", "null", "&&", "...
Renews a nonce. The nonce must be valid and must have not expired.
[ "Renews", "a", "nonce", ".", "The", "nonce", "must", "be", "valid", "and", "must", "have", "not", "expired", "." ]
e8dbf8cb6589fa1031a0bfcdcb58cb03d2ba7799
https://github.com/brianwhu/xillium/blob/e8dbf8cb6589fa1031a0bfcdcb58cb03d2ba7799/gear/src/main/java/org/xillium/gear/auth/NonceShop.java#L64-L72
train
brianwhu/xillium
gear/src/main/java/org/xillium/gear/auth/NonceShop.java
NonceShop.prove
public boolean prove(String value, String state) { Nonce nonce = _map.remove(state + ':' + value); return nonce != null && !nonce.hasExpired(); }
java
public boolean prove(String value, String state) { Nonce nonce = _map.remove(state + ':' + value); return nonce != null && !nonce.hasExpired(); }
[ "public", "boolean", "prove", "(", "String", "value", ",", "String", "state", ")", "{", "Nonce", "nonce", "=", "_map", ".", "remove", "(", "state", "+", "'", "'", "+", "value", ")", ";", "return", "nonce", "!=", "null", "&&", "!", "nonce", ".", "ha...
Proves a nonce and its associated state. A nonce can only be successfully proved once. @param value the nonce value @param state the state associated with the nonce. @return whether the nonce is successfully proved
[ "Proves", "a", "nonce", "and", "its", "associated", "state", ".", "A", "nonce", "can", "only", "be", "successfully", "proved", "once", "." ]
e8dbf8cb6589fa1031a0bfcdcb58cb03d2ba7799
https://github.com/brianwhu/xillium/blob/e8dbf8cb6589fa1031a0bfcdcb58cb03d2ba7799/gear/src/main/java/org/xillium/gear/auth/NonceShop.java#L81-L84
train
redlink-gmbh/redlink-java-sdk
src/main/java/io/redlink/sdk/impl/analysis/model/Enhancements.java
Enhancements.hasCategory
public boolean hasCategory(final String conceptURI) { return Iterables.any(getCategories(), new Predicate<TopicAnnotation>() { @Override public boolean apply(TopicAnnotation ta) { return ta.getTopicReference(). equals(conceptURI); } } ); }
java
public boolean hasCategory(final String conceptURI) { return Iterables.any(getCategories(), new Predicate<TopicAnnotation>() { @Override public boolean apply(TopicAnnotation ta) { return ta.getTopicReference(). equals(conceptURI); } } ); }
[ "public", "boolean", "hasCategory", "(", "final", "String", "conceptURI", ")", "{", "return", "Iterables", ".", "any", "(", "getCategories", "(", ")", ",", "new", "Predicate", "<", "TopicAnnotation", ">", "(", ")", "{", "@", "Override", "public", "boolean", ...
Returns true if the contents has been categorized with a category identified by the URI passed by parameter @param conceptURI URI of the category concept @return
[ "Returns", "true", "if", "the", "contents", "has", "been", "categorized", "with", "a", "category", "identified", "by", "the", "URI", "passed", "by", "parameter" ]
c412ff11bd80da52ade09f2483ab29cdbff5a28a
https://github.com/redlink-gmbh/redlink-java-sdk/blob/c412ff11bd80da52ade09f2483ab29cdbff5a28a/src/main/java/io/redlink/sdk/impl/analysis/model/Enhancements.java#L393-L405
train
couchbase/couchbase-lite-java-core
vendor/sqlite/src/java/com/couchbase/lite/internal/database/sqlite/SQLiteDatabase.java
SQLiteDatabase.create
public static SQLiteDatabase create(CursorFactory factory) { // This is a magic string with special meaning for SQLite. return openDatabase(com.couchbase.lite.internal.database.sqlite.SQLiteDatabaseConfiguration.MEMORY_DB_PATH, factory, CREATE_IF_NECESSARY); }
java
public static SQLiteDatabase create(CursorFactory factory) { // This is a magic string with special meaning for SQLite. return openDatabase(com.couchbase.lite.internal.database.sqlite.SQLiteDatabaseConfiguration.MEMORY_DB_PATH, factory, CREATE_IF_NECESSARY); }
[ "public", "static", "SQLiteDatabase", "create", "(", "CursorFactory", "factory", ")", "{", "// This is a magic string with special meaning for SQLite.", "return", "openDatabase", "(", "com", ".", "couchbase", ".", "lite", ".", "internal", ".", "database", ".", "sqlite",...
Create a memory backed SQLite database. Its contents will be destroyed when the database is closed. @param factory an optional factory class that is called to instantiate a cursor when query is called @return a SQLiteDatabase object, or null if the database can't be created
[ "Create", "a", "memory", "backed", "SQLite", "database", ".", "Its", "contents", "will", "be", "destroyed", "when", "the", "database", "is", "closed", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/vendor/sqlite/src/java/com/couchbase/lite/internal/database/sqlite/SQLiteDatabase.java#L836-L840
train
couchbase/couchbase-lite-java-core
vendor/sqlite/src/java/com/couchbase/lite/internal/database/sqlite/SQLiteDatabase.java
SQLiteDatabase.replace
public long replace(String table, String nullColumnHack, ContentValues initialValues) { try { return insertWithOnConflict(table, nullColumnHack, initialValues, CONFLICT_REPLACE); } catch (SQLException e) { DLog.e(TAG, "Error inserting " + initialValues, e); return -1; } }
java
public long replace(String table, String nullColumnHack, ContentValues initialValues) { try { return insertWithOnConflict(table, nullColumnHack, initialValues, CONFLICT_REPLACE); } catch (SQLException e) { DLog.e(TAG, "Error inserting " + initialValues, e); return -1; } }
[ "public", "long", "replace", "(", "String", "table", ",", "String", "nullColumnHack", ",", "ContentValues", "initialValues", ")", "{", "try", "{", "return", "insertWithOnConflict", "(", "table", ",", "nullColumnHack", ",", "initialValues", ",", "CONFLICT_REPLACE", ...
Convenience method for replacing a row in the database. @param table the table in which to replace the row @param nullColumnHack optional; may be <code>null</code>. SQL doesn't allow inserting a completely empty row without naming at least one column name. If your provided <code>initialValues</code> is empty, no column names are known and an empty row can't be inserted. If not set to null, the <code>nullColumnHack</code> parameter provides the name of nullable column name to explicitly insert a NULL into in the case where your <code>initialValues</code> is empty. @param initialValues this map contains the initial column values for the row. @return the row ID of the newly inserted row, or -1 if an error occurred
[ "Convenience", "method", "for", "replacing", "a", "row", "in", "the", "database", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/vendor/sqlite/src/java/com/couchbase/lite/internal/database/sqlite/SQLiteDatabase.java#L1369-L1377
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/BlobKey.java
BlobKey.decodeBase64Digest
private static byte[] decodeBase64Digest(String base64Digest) { String expectedPrefix = "sha1-"; if (!base64Digest.startsWith(expectedPrefix)) { throw new IllegalArgumentException(base64Digest + " did not start with " + expectedPrefix); } base64Digest = base64Digest.replaceFirst(expectedPrefix, ""); byte[] bytes = new byte[0]; try { bytes = Base64.decode(base64Digest); } catch (IOException e) { throw new IllegalArgumentException(e); } return bytes; }
java
private static byte[] decodeBase64Digest(String base64Digest) { String expectedPrefix = "sha1-"; if (!base64Digest.startsWith(expectedPrefix)) { throw new IllegalArgumentException(base64Digest + " did not start with " + expectedPrefix); } base64Digest = base64Digest.replaceFirst(expectedPrefix, ""); byte[] bytes = new byte[0]; try { bytes = Base64.decode(base64Digest); } catch (IOException e) { throw new IllegalArgumentException(e); } return bytes; }
[ "private", "static", "byte", "[", "]", "decodeBase64Digest", "(", "String", "base64Digest", ")", "{", "String", "expectedPrefix", "=", "\"sha1-\"", ";", "if", "(", "!", "base64Digest", ".", "startsWith", "(", "expectedPrefix", ")", ")", "{", "throw", "new", ...
Decode base64'd getDigest into a byte array that is suitable for use as a blob key. @param base64Digest string with base64'd getDigest, with leading "sha1-" attached. eg, "sha1-LKJ32423JK..." @return a byte[] blob key
[ "Decode", "base64", "d", "getDigest", "into", "a", "byte", "array", "that", "is", "suitable", "for", "use", "as", "a", "blob", "key", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/BlobKey.java#L60-L74
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/replicator/ReplicationInternal.java
ReplicationInternal.fireTrigger
protected void fireTrigger(final ReplicationTrigger trigger) { Log.d(Log.TAG_SYNC, "%s [fireTrigger()] => " + trigger, this); // All state machine triggers need to happen on the replicator thread synchronized (executor) { if (!executor.isShutdown()) { executor.submit(new Runnable() { @Override public void run() { try { Log.d(Log.TAG_SYNC, "firing trigger: %s", trigger); stateMachine.fire(trigger); } catch (Exception e) { Log.i(Log.TAG_SYNC, "Error in StateMachine.fire(trigger): %s", e.getMessage()); throw new RuntimeException(e); } } }); } } }
java
protected void fireTrigger(final ReplicationTrigger trigger) { Log.d(Log.TAG_SYNC, "%s [fireTrigger()] => " + trigger, this); // All state machine triggers need to happen on the replicator thread synchronized (executor) { if (!executor.isShutdown()) { executor.submit(new Runnable() { @Override public void run() { try { Log.d(Log.TAG_SYNC, "firing trigger: %s", trigger); stateMachine.fire(trigger); } catch (Exception e) { Log.i(Log.TAG_SYNC, "Error in StateMachine.fire(trigger): %s", e.getMessage()); throw new RuntimeException(e); } } }); } } }
[ "protected", "void", "fireTrigger", "(", "final", "ReplicationTrigger", "trigger", ")", "{", "Log", ".", "d", "(", "Log", ".", "TAG_SYNC", ",", "\"%s [fireTrigger()] => \"", "+", "trigger", ",", "this", ")", ";", "// All state machine triggers need to happen on the re...
Fire a trigger to the state machine
[ "Fire", "a", "trigger", "to", "the", "state", "machine" ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/replicator/ReplicationInternal.java#L228-L247
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/replicator/ReplicationInternal.java
ReplicationInternal.start
protected void start() { try { if (!db.isOpen()) { String msg = String.format(Locale.ENGLISH, "Db: %s is not open, abort replication", db); parentReplication.setLastError(new Exception(msg)); fireTrigger(ReplicationTrigger.STOP_IMMEDIATE); return; } db.addActiveReplication(parentReplication); this.authenticating = false; initSessionId(); // initialize batcher initBatcher(); // initialize authorizer / authenticator initAuthorizer(); // initialize request workers initializeRequestWorkers(); // reset lastSequence // https://github.com/couchbase/couchbase-lite-java-core/issues/1623 this.lastSequence = null; // single-shot replication if (!isContinuous()) goOnline(); // continuous mode else { if (isNetworkReachable()) goOnline(); else triggerGoOffline(); startNetworkReachabilityManager(); } } catch (Exception e) { Log.e(Log.TAG_SYNC, "%s: Exception in start()", e, this); } }
java
protected void start() { try { if (!db.isOpen()) { String msg = String.format(Locale.ENGLISH, "Db: %s is not open, abort replication", db); parentReplication.setLastError(new Exception(msg)); fireTrigger(ReplicationTrigger.STOP_IMMEDIATE); return; } db.addActiveReplication(parentReplication); this.authenticating = false; initSessionId(); // initialize batcher initBatcher(); // initialize authorizer / authenticator initAuthorizer(); // initialize request workers initializeRequestWorkers(); // reset lastSequence // https://github.com/couchbase/couchbase-lite-java-core/issues/1623 this.lastSequence = null; // single-shot replication if (!isContinuous()) goOnline(); // continuous mode else { if (isNetworkReachable()) goOnline(); else triggerGoOffline(); startNetworkReachabilityManager(); } } catch (Exception e) { Log.e(Log.TAG_SYNC, "%s: Exception in start()", e, this); } }
[ "protected", "void", "start", "(", ")", "{", "try", "{", "if", "(", "!", "db", ".", "isOpen", "(", ")", ")", "{", "String", "msg", "=", "String", ".", "format", "(", "Locale", ".", "ENGLISH", ",", "\"Db: %s is not open, abort replication\"", ",", "db", ...
Start the replication process.
[ "Start", "the", "replication", "process", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/replicator/ReplicationInternal.java#L260-L294
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/replicator/ReplicationInternal.java
ReplicationInternal.close
protected void close() { this.authenticating = false; // cancel pending futures for (Future future : pendingFutures) { future.cancel(false); CancellableRunnable runnable = cancellables.get(future); if (runnable != null) { runnable.cancel(); cancellables.remove(future); } } // shutdown ScheduledExecutorService. Without shutdown, cause thread leak if (remoteRequestExecutor != null && !remoteRequestExecutor.isShutdown()) { // Note: Time to wait is set 60 sec because RemoteRequest's socket timeout is set 60 seconds. Utils.shutdownAndAwaitTermination(remoteRequestExecutor, Replication.DEFAULT_MAX_TIMEOUT_FOR_SHUTDOWN, Replication.DEFAULT_MAX_TIMEOUT_FOR_SHUTDOWN); } // Close and remove all idle connections in the pool, clientFactory.evictAllConnectionsInPool(); }
java
protected void close() { this.authenticating = false; // cancel pending futures for (Future future : pendingFutures) { future.cancel(false); CancellableRunnable runnable = cancellables.get(future); if (runnable != null) { runnable.cancel(); cancellables.remove(future); } } // shutdown ScheduledExecutorService. Without shutdown, cause thread leak if (remoteRequestExecutor != null && !remoteRequestExecutor.isShutdown()) { // Note: Time to wait is set 60 sec because RemoteRequest's socket timeout is set 60 seconds. Utils.shutdownAndAwaitTermination(remoteRequestExecutor, Replication.DEFAULT_MAX_TIMEOUT_FOR_SHUTDOWN, Replication.DEFAULT_MAX_TIMEOUT_FOR_SHUTDOWN); } // Close and remove all idle connections in the pool, clientFactory.evictAllConnectionsInPool(); }
[ "protected", "void", "close", "(", ")", "{", "this", ".", "authenticating", "=", "false", ";", "// cancel pending futures", "for", "(", "Future", "future", ":", "pendingFutures", ")", "{", "future", ".", "cancel", "(", "false", ")", ";", "CancellableRunnable",...
Close all resources associated with this replicator.
[ "Close", "all", "resources", "associated", "with", "this", "replicator", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/replicator/ReplicationInternal.java#L318-L341
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/replicator/ReplicationInternal.java
ReplicationInternal.checkSession
@InterfaceAudience.Private protected void checkSession() { if (getAuthenticator() != null) { Authorizer auth = (Authorizer) getAuthenticator(); auth.setRemoteURL(remote); auth.setLocalUUID(db.publicUUID()); } if (getAuthenticator() != null && getAuthenticator() instanceof SessionCookieAuthorizer) { // Sync Gateway session API is at /db/_session; try that first checkSessionAtPath("_session"); } else { login(); } }
java
@InterfaceAudience.Private protected void checkSession() { if (getAuthenticator() != null) { Authorizer auth = (Authorizer) getAuthenticator(); auth.setRemoteURL(remote); auth.setLocalUUID(db.publicUUID()); } if (getAuthenticator() != null && getAuthenticator() instanceof SessionCookieAuthorizer) { // Sync Gateway session API is at /db/_session; try that first checkSessionAtPath("_session"); } else { login(); } }
[ "@", "InterfaceAudience", ".", "Private", "protected", "void", "checkSession", "(", ")", "{", "if", "(", "getAuthenticator", "(", ")", "!=", "null", ")", "{", "Authorizer", "auth", "=", "(", "Authorizer", ")", "getAuthenticator", "(", ")", ";", "auth", "."...
Before doing anything else, determine whether we have an active login session.
[ "Before", "doing", "anything", "else", "determine", "whether", "we", "have", "an", "active", "login", "session", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/replicator/ReplicationInternal.java#L434-L447
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/replicator/ReplicationInternal.java
ReplicationInternal.refreshRemoteCheckpointDoc
@InterfaceAudience.Private private void refreshRemoteCheckpointDoc() { Log.i(Log.TAG_SYNC, "%s: Refreshing remote checkpoint to get its _rev...", this); Future future = sendAsyncRequest("GET", "_local/" + remoteCheckpointDocID(), null, new RemoteRequestCompletion() { @Override public void onCompletion(RemoteRequest remoteRequest, Response httpResponse, Object result, Throwable e) { if (db == null) { Log.w(Log.TAG_SYNC, "%s: db == null while refreshing remote checkpoint. aborting", this); return; } if (e != null && Utils.getStatusFromError(e) != Status.NOT_FOUND) { Log.e(Log.TAG_SYNC, "%s: Error refreshing remote checkpoint", e, this); } else { Log.d(Log.TAG_SYNC, "%s: Refreshed remote checkpoint: %s", this, result); remoteCheckpoint = (Map<String, Object>) result; lastSequenceChanged = true; saveLastSequence(); // try saving again } } }); pendingFutures.add(future); }
java
@InterfaceAudience.Private private void refreshRemoteCheckpointDoc() { Log.i(Log.TAG_SYNC, "%s: Refreshing remote checkpoint to get its _rev...", this); Future future = sendAsyncRequest("GET", "_local/" + remoteCheckpointDocID(), null, new RemoteRequestCompletion() { @Override public void onCompletion(RemoteRequest remoteRequest, Response httpResponse, Object result, Throwable e) { if (db == null) { Log.w(Log.TAG_SYNC, "%s: db == null while refreshing remote checkpoint. aborting", this); return; } if (e != null && Utils.getStatusFromError(e) != Status.NOT_FOUND) { Log.e(Log.TAG_SYNC, "%s: Error refreshing remote checkpoint", e, this); } else { Log.d(Log.TAG_SYNC, "%s: Refreshed remote checkpoint: %s", this, result); remoteCheckpoint = (Map<String, Object>) result; lastSequenceChanged = true; saveLastSequence(); // try saving again } } }); pendingFutures.add(future); }
[ "@", "InterfaceAudience", ".", "Private", "private", "void", "refreshRemoteCheckpointDoc", "(", ")", "{", "Log", ".", "i", "(", "Log", ".", "TAG_SYNC", ",", "\"%s: Refreshing remote checkpoint to get its _rev...\"", ",", "this", ")", ";", "Future", "future", "=", ...
Variant of -fetchRemoveCheckpointDoc that's used while replication is running, to reload the checkpoint to get its current revision number, if there was an error saving it.
[ "Variant", "of", "-", "fetchRemoveCheckpointDoc", "that", "s", "used", "while", "replication", "is", "running", "to", "reload", "the", "checkpoint", "to", "get", "its", "current", "revision", "number", "if", "there", "was", "an", "error", "saving", "it", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/replicator/ReplicationInternal.java#L922-L943
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/replicator/ReplicationInternal.java
ReplicationInternal.stop
protected void stop() { this.authenticating = false; // clear batcher batcher.clear(); // set non-continuous setLifecycle(Replication.Lifecycle.ONESHOT); // cancel if middle of retry cancelRetryFuture(); // cancel all pending future tasks. while (!pendingFutures.isEmpty()) { Future future = pendingFutures.poll(); if (future != null && !future.isCancelled() && !future.isDone()) { future.cancel(true); CancellableRunnable runnable = cancellables.get(future); if (runnable != null) { runnable.cancel(); cancellables.remove(future); } } } }
java
protected void stop() { this.authenticating = false; // clear batcher batcher.clear(); // set non-continuous setLifecycle(Replication.Lifecycle.ONESHOT); // cancel if middle of retry cancelRetryFuture(); // cancel all pending future tasks. while (!pendingFutures.isEmpty()) { Future future = pendingFutures.poll(); if (future != null && !future.isCancelled() && !future.isDone()) { future.cancel(true); CancellableRunnable runnable = cancellables.get(future); if (runnable != null) { runnable.cancel(); cancellables.remove(future); } } } }
[ "protected", "void", "stop", "(", ")", "{", "this", ".", "authenticating", "=", "false", ";", "// clear batcher", "batcher", ".", "clear", "(", ")", ";", "// set non-continuous", "setLifecycle", "(", "Replication", ".", "Lifecycle", ".", "ONESHOT", ")", ";", ...
Actual work of stopping the replication process.
[ "Actual", "work", "of", "stopping", "the", "replication", "process", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/replicator/ReplicationInternal.java#L1215-L1235
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/replicator/ReplicationInternal.java
ReplicationInternal.notifyChangeListeners
private void notifyChangeListeners(final Replication.ChangeEvent changeEvent) { if (changeListenerNotifyStyle == ChangeListenerNotifyStyle.SYNC) { for (ChangeListener changeListener : changeListeners) { try { changeListener.changed(changeEvent); } catch (Exception e) { Log.e(Log.TAG_SYNC, "Unknown Error in changeListener.changed(changeEvent)", e); } } } else { // ASYNC synchronized (executor) { if (!executor.isShutdown()) { executor.submit(new Runnable() { @Override public void run() { try { for (ChangeListener changeListener : changeListeners) changeListener.changed(changeEvent); } catch (Exception e) { Log.e(Log.TAG_SYNC, "Exception notifying replication listener: %s", e, this); throw new RuntimeException(e); } } }); } } } }
java
private void notifyChangeListeners(final Replication.ChangeEvent changeEvent) { if (changeListenerNotifyStyle == ChangeListenerNotifyStyle.SYNC) { for (ChangeListener changeListener : changeListeners) { try { changeListener.changed(changeEvent); } catch (Exception e) { Log.e(Log.TAG_SYNC, "Unknown Error in changeListener.changed(changeEvent)", e); } } } else { // ASYNC synchronized (executor) { if (!executor.isShutdown()) { executor.submit(new Runnable() { @Override public void run() { try { for (ChangeListener changeListener : changeListeners) changeListener.changed(changeEvent); } catch (Exception e) { Log.e(Log.TAG_SYNC, "Exception notifying replication listener: %s", e, this); throw new RuntimeException(e); } } }); } } } }
[ "private", "void", "notifyChangeListeners", "(", "final", "Replication", ".", "ChangeEvent", "changeEvent", ")", "{", "if", "(", "changeListenerNotifyStyle", "==", "ChangeListenerNotifyStyle", ".", "SYNC", ")", "{", "for", "(", "ChangeListener", "changeListener", ":",...
Notify all change listeners of a ChangeEvent
[ "Notify", "all", "change", "listeners", "of", "a", "ChangeEvent" ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/replicator/ReplicationInternal.java#L1240-L1268
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/replicator/ReplicationInternal.java
ReplicationInternal.scheduleRetryFuture
private void scheduleRetryFuture() { Log.v(Log.TAG_SYNC, "%s: Failed to xfer; will retry in %d sec", this, RETRY_DELAY_SECONDS); synchronized (executor) { if (!executor.isShutdown()) { this.retryFuture = executor.schedule(new Runnable() { public void run() { retryIfReady(); } }, RETRY_DELAY_SECONDS, TimeUnit.SECONDS); } } }
java
private void scheduleRetryFuture() { Log.v(Log.TAG_SYNC, "%s: Failed to xfer; will retry in %d sec", this, RETRY_DELAY_SECONDS); synchronized (executor) { if (!executor.isShutdown()) { this.retryFuture = executor.schedule(new Runnable() { public void run() { retryIfReady(); } }, RETRY_DELAY_SECONDS, TimeUnit.SECONDS); } } }
[ "private", "void", "scheduleRetryFuture", "(", ")", "{", "Log", ".", "v", "(", "Log", ".", "TAG_SYNC", ",", "\"%s: Failed to xfer; will retry in %d sec\"", ",", "this", ",", "RETRY_DELAY_SECONDS", ")", ";", "synchronized", "(", "executor", ")", "{", "if", "(", ...
helper function to schedule retry future. no in iOS code.
[ "helper", "function", "to", "schedule", "retry", "future", ".", "no", "in", "iOS", "code", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/replicator/ReplicationInternal.java#L1594-L1605
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/replicator/ReplicationInternal.java
ReplicationInternal.cancelRetryFuture
private void cancelRetryFuture() { if (retryFuture != null && !retryFuture.isDone()) { retryFuture.cancel(true); } retryFuture = null; }
java
private void cancelRetryFuture() { if (retryFuture != null && !retryFuture.isDone()) { retryFuture.cancel(true); } retryFuture = null; }
[ "private", "void", "cancelRetryFuture", "(", ")", "{", "if", "(", "retryFuture", "!=", "null", "&&", "!", "retryFuture", ".", "isDone", "(", ")", ")", "{", "retryFuture", ".", "cancel", "(", "true", ")", ";", "}", "retryFuture", "=", "null", ";", "}" ]
helper function to cancel retry future. not in iOS code.
[ "helper", "function", "to", "cancel", "retry", "future", ".", "not", "in", "iOS", "code", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/replicator/ReplicationInternal.java#L1610-L1615
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/replicator/ReplicationInternal.java
ReplicationInternal.retryReplicationIfError
protected void retryReplicationIfError() { Log.d(TAG, "retryReplicationIfError() state=" + stateMachine.getState() + ", error=" + this.error + ", isContinuous()=" + isContinuous() + ", isTransientError()=" + Utils.isTransientError(this.error)); // Make sure if state is IDLE, this method should be called when state becomes IDLE if (!stateMachine.getState().equals(ReplicationState.IDLE)) return; if (this.error != null) { // IDLE_ERROR if (isContinuous()) { // 12/16/2014 - only retry if error is transient error 50x http error // It may need to retry for any kind of errors if (Utils.isTransientError(this.error)) { onBeforeScheduleRetry(); cancelRetryFuture(); scheduleRetryFuture(); } } } }
java
protected void retryReplicationIfError() { Log.d(TAG, "retryReplicationIfError() state=" + stateMachine.getState() + ", error=" + this.error + ", isContinuous()=" + isContinuous() + ", isTransientError()=" + Utils.isTransientError(this.error)); // Make sure if state is IDLE, this method should be called when state becomes IDLE if (!stateMachine.getState().equals(ReplicationState.IDLE)) return; if (this.error != null) { // IDLE_ERROR if (isContinuous()) { // 12/16/2014 - only retry if error is transient error 50x http error // It may need to retry for any kind of errors if (Utils.isTransientError(this.error)) { onBeforeScheduleRetry(); cancelRetryFuture(); scheduleRetryFuture(); } } } }
[ "protected", "void", "retryReplicationIfError", "(", ")", "{", "Log", ".", "d", "(", "TAG", ",", "\"retryReplicationIfError() state=\"", "+", "stateMachine", ".", "getState", "(", ")", "+", "\", error=\"", "+", "this", ".", "error", "+", "\", isContinuous()=\"", ...
Retry replication if previous attempt ends with error
[ "Retry", "replication", "if", "previous", "attempt", "ends", "with", "error" ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/replicator/ReplicationInternal.java#L1627-L1649
train
couchbase/couchbase-lite-java-core
vendor/sqlite/src/java/com/couchbase/lite/internal/database/sqlite/SQLiteConnection.java
SQLiteConnection.dumpUnsafe
void dumpUnsafe(Printer printer, boolean verbose) { printer.println("Connection #" + mConnectionId + ":"); if (verbose) { printer.println(" connectionPtr: 0x" + Long.toHexString(mConnectionPtr)); } printer.println(" isPrimaryConnection: " + mIsPrimaryConnection); printer.println(" onlyAllowReadOnlyOperations: " + mOnlyAllowReadOnlyOperations); mRecentOperations.dump(printer, verbose); }
java
void dumpUnsafe(Printer printer, boolean verbose) { printer.println("Connection #" + mConnectionId + ":"); if (verbose) { printer.println(" connectionPtr: 0x" + Long.toHexString(mConnectionPtr)); } printer.println(" isPrimaryConnection: " + mIsPrimaryConnection); printer.println(" onlyAllowReadOnlyOperations: " + mOnlyAllowReadOnlyOperations); mRecentOperations.dump(printer, verbose); }
[ "void", "dumpUnsafe", "(", "Printer", "printer", ",", "boolean", "verbose", ")", "{", "printer", ".", "println", "(", "\"Connection #\"", "+", "mConnectionId", "+", "\":\"", ")", ";", "if", "(", "verbose", ")", "{", "printer", ".", "println", "(", "\" con...
Dumps debugging information about this connection, in the case where the caller might not actually own the connection. This function is written so that it may be called by a thread that does not own the connection. We need to be very careful because the connection state is not synchronized. At worst, the method may return stale or slightly wrong data, however it should not crash. This is ok as it is only used for diagnostic purposes. @param printer The printer to receive the dump, not null. @param verbose True to dump more verbose information.
[ "Dumps", "debugging", "information", "about", "this", "connection", "in", "the", "case", "where", "the", "caller", "might", "not", "actually", "own", "the", "connection", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/vendor/sqlite/src/java/com/couchbase/lite/internal/database/sqlite/SQLiteConnection.java#L876-L885
train
couchbase/couchbase-lite-java-core
vendor/sqlite/src/java/com/couchbase/lite/internal/database/sqlite/SQLiteConnection.java
SQLiteConnection.collectDbStatsUnsafe
void collectDbStatsUnsafe(ArrayList<com.couchbase.lite.internal.database.sqlite.SQLiteDebug.DbStats> dbStatsList) { dbStatsList.add(getMainDbStatsUnsafe(0, 0, 0)); }
java
void collectDbStatsUnsafe(ArrayList<com.couchbase.lite.internal.database.sqlite.SQLiteDebug.DbStats> dbStatsList) { dbStatsList.add(getMainDbStatsUnsafe(0, 0, 0)); }
[ "void", "collectDbStatsUnsafe", "(", "ArrayList", "<", "com", ".", "couchbase", ".", "lite", ".", "internal", ".", "database", ".", "sqlite", ".", "SQLiteDebug", ".", "DbStats", ">", "dbStatsList", ")", "{", "dbStatsList", ".", "add", "(", "getMainDbStatsUnsaf...
Collects statistics about database connection memory usage, in the case where the caller might not actually own the connection. @return The statistics object, never null.
[ "Collects", "statistics", "about", "database", "connection", "memory", "usage", "in", "the", "case", "where", "the", "caller", "might", "not", "actually", "own", "the", "connection", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/vendor/sqlite/src/java/com/couchbase/lite/internal/database/sqlite/SQLiteConnection.java#L930-L932
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/replicator/RemoteRequest.java
RemoteRequest.execute
protected void execute() { Log.v(Log.TAG_SYNC, "%s: RemoteRequest execute() called, url: %s", this, url); executeRequest(factory.getOkHttpClient(), request()); Log.v(Log.TAG_SYNC, "%s: RemoteRequest execute() finished, url: %s", this, url); }
java
protected void execute() { Log.v(Log.TAG_SYNC, "%s: RemoteRequest execute() called, url: %s", this, url); executeRequest(factory.getOkHttpClient(), request()); Log.v(Log.TAG_SYNC, "%s: RemoteRequest execute() finished, url: %s", this, url); }
[ "protected", "void", "execute", "(", ")", "{", "Log", ".", "v", "(", "Log", ".", "TAG_SYNC", ",", "\"%s: RemoteRequest execute() called, url: %s\"", ",", "this", ",", "url", ")", ";", "executeRequest", "(", "factory", ".", "getOkHttpClient", "(", ")", ",", "...
Execute remote request
[ "Execute", "remote", "request" ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/replicator/RemoteRequest.java#L164-L168
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/replicator/RemoteRequest.java
RemoteRequest.setCompressedBody
protected RequestBody setCompressedBody(byte[] bodyBytes) { if (bodyBytes.length < MIN_JSON_LENGTH_TO_COMPRESS) return null; byte[] encodedBytes = Utils.compressByGzip(bodyBytes); if (encodedBytes == null || encodedBytes.length >= bodyBytes.length) return null; return RequestBody.create(JSON, encodedBytes); }
java
protected RequestBody setCompressedBody(byte[] bodyBytes) { if (bodyBytes.length < MIN_JSON_LENGTH_TO_COMPRESS) return null; byte[] encodedBytes = Utils.compressByGzip(bodyBytes); if (encodedBytes == null || encodedBytes.length >= bodyBytes.length) return null; return RequestBody.create(JSON, encodedBytes); }
[ "protected", "RequestBody", "setCompressedBody", "(", "byte", "[", "]", "bodyBytes", ")", "{", "if", "(", "bodyBytes", ".", "length", "<", "MIN_JSON_LENGTH_TO_COMPRESS", ")", "return", "null", ";", "byte", "[", "]", "encodedBytes", "=", "Utils", ".", "compress...
Generate gzipped body
[ "Generate", "gzipped", "body" ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/replicator/RemoteRequest.java#L242-L249
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/support/KMPMatch.java
KMPMatch.indexOf
int indexOf(byte[] data, int dataLength, byte[] pattern, int dataOffset) { int[] failure = computeFailure(pattern); int j = 0; if (data.length == 0) return -1; //final int dataLength = data.length; final int patternLength = pattern.length; for (int i = dataOffset; i < dataLength; i++) { while (j > 0 && pattern[j] != data[i]) j = failure[j - 1]; if (pattern[j] == data[i]) j++; if (j == patternLength) return i - patternLength + 1; } return -1; }
java
int indexOf(byte[] data, int dataLength, byte[] pattern, int dataOffset) { int[] failure = computeFailure(pattern); int j = 0; if (data.length == 0) return -1; //final int dataLength = data.length; final int patternLength = pattern.length; for (int i = dataOffset; i < dataLength; i++) { while (j > 0 && pattern[j] != data[i]) j = failure[j - 1]; if (pattern[j] == data[i]) j++; if (j == patternLength) return i - patternLength + 1; } return -1; }
[ "int", "indexOf", "(", "byte", "[", "]", "data", ",", "int", "dataLength", ",", "byte", "[", "]", "pattern", ",", "int", "dataOffset", ")", "{", "int", "[", "]", "failure", "=", "computeFailure", "(", "pattern", ")", ";", "int", "j", "=", "0", ";",...
Finds the first occurrence of the pattern in the text.
[ "Finds", "the", "first", "occurrence", "of", "the", "pattern", "in", "the", "text", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/support/KMPMatch.java#L23-L39
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/support/KMPMatch.java
KMPMatch.computeFailure
private static int[] computeFailure(byte[] pattern) { int[] failure = new int[pattern.length]; int j = 0; for (int i = 1; i < pattern.length; i++) { while (j > 0 && pattern[j] != pattern[i]) j = failure[j - 1]; if (pattern[j] == pattern[i]) j++; failure[i] = j; } return failure; }
java
private static int[] computeFailure(byte[] pattern) { int[] failure = new int[pattern.length]; int j = 0; for (int i = 1; i < pattern.length; i++) { while (j > 0 && pattern[j] != pattern[i]) j = failure[j - 1]; if (pattern[j] == pattern[i]) j++; failure[i] = j; } return failure; }
[ "private", "static", "int", "[", "]", "computeFailure", "(", "byte", "[", "]", "pattern", ")", "{", "int", "[", "]", "failure", "=", "new", "int", "[", "pattern", ".", "length", "]", ";", "int", "j", "=", "0", ";", "for", "(", "int", "i", "=", ...
Computes the failure function using a boot-strapping process, where the pattern is matched against itself.
[ "Computes", "the", "failure", "function", "using", "a", "boot", "-", "strapping", "process", "where", "the", "pattern", "is", "matched", "against", "itself", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/support/KMPMatch.java#L45-L56
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/Manager.java
Manager.getAllDatabaseNames
@InterfaceAudience.Public public List<String> getAllDatabaseNames() { String[] databaseFiles = directoryFile.list(new FilenameFilter() { @Override public boolean accept(File dir, String filename) { if (filename.endsWith(Manager.kDBExtension)) { return true; } return false; } }); List<String> result = new ArrayList<String>(); for (String databaseFile : databaseFiles) { String trimmed = databaseFile.substring(0, databaseFile.length() - Manager.kDBExtension.length()); String replaced = trimmed.replace(':', '/'); result.add(replaced); } Collections.sort(result); return Collections.unmodifiableList(result); }
java
@InterfaceAudience.Public public List<String> getAllDatabaseNames() { String[] databaseFiles = directoryFile.list(new FilenameFilter() { @Override public boolean accept(File dir, String filename) { if (filename.endsWith(Manager.kDBExtension)) { return true; } return false; } }); List<String> result = new ArrayList<String>(); for (String databaseFile : databaseFiles) { String trimmed = databaseFile.substring(0, databaseFile.length() - Manager.kDBExtension.length()); String replaced = trimmed.replace(':', '/'); result.add(replaced); } Collections.sort(result); return Collections.unmodifiableList(result); }
[ "@", "InterfaceAudience", ".", "Public", "public", "List", "<", "String", ">", "getAllDatabaseNames", "(", ")", "{", "String", "[", "]", "databaseFiles", "=", "directoryFile", ".", "list", "(", "new", "FilenameFilter", "(", ")", "{", "@", "Override", "public...
An array of the names of all existing databases.
[ "An", "array", "of", "the", "names", "of", "all", "existing", "databases", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/Manager.java#L227-L247
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/Manager.java
Manager.close
@InterfaceAudience.Public public void close() { synchronized (lockDatabases) { Log.d(Database.TAG, "Closing " + this); // Close all database: // Snapshot of the current open database to avoid concurrent modification as // the database will be forgotten (removed from the databases map) when it is closed: Database[] openDbs = databases.values().toArray(new Database[databases.size()]); for (Database database : openDbs) database.close(); databases.clear(); // Stop reachability: context.getNetworkReachabilityManager().stopListening(); // Shutdown ScheduledExecutorService: if (workExecutor != null && !workExecutor.isShutdown()) Utils.shutdownAndAwaitTermination(workExecutor); Log.d(Database.TAG, "Closed " + this); } }
java
@InterfaceAudience.Public public void close() { synchronized (lockDatabases) { Log.d(Database.TAG, "Closing " + this); // Close all database: // Snapshot of the current open database to avoid concurrent modification as // the database will be forgotten (removed from the databases map) when it is closed: Database[] openDbs = databases.values().toArray(new Database[databases.size()]); for (Database database : openDbs) database.close(); databases.clear(); // Stop reachability: context.getNetworkReachabilityManager().stopListening(); // Shutdown ScheduledExecutorService: if (workExecutor != null && !workExecutor.isShutdown()) Utils.shutdownAndAwaitTermination(workExecutor); Log.d(Database.TAG, "Closed " + this); } }
[ "@", "InterfaceAudience", ".", "Public", "public", "void", "close", "(", ")", "{", "synchronized", "(", "lockDatabases", ")", "{", "Log", ".", "d", "(", "Database", ".", "TAG", ",", "\"Closing \"", "+", "this", ")", ";", "// Close all database:", "// Snapsho...
Releases all resources used by the Manager instance and closes all its databases.
[ "Releases", "all", "resources", "used", "by", "the", "Manager", "instance", "and", "closes", "all", "its", "databases", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/Manager.java#L264-L286
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/Manager.java
Manager.replaceDatabase
@InterfaceAudience.Public public boolean replaceDatabase(String databaseName, String databaseDir) { Database db = getDatabase(databaseName, false); if(db == null) return false; File dir = new File(databaseDir); if(!dir.exists()){ Log.w(Database.TAG, "Database file doesn't exist at path : %s", databaseDir); return false; } if (!dir.isDirectory()) { Log.w(Database.TAG, "Database file is not a directory. " + "Use -replaceDatabaseNamed:withDatabaseFilewithAttachments:error: instead."); return false; } File destDir = new File(db.getPath()); File srcDir = new File(databaseDir); if(destDir.exists()) { if (!FileDirUtils.deleteRecursive(destDir)) { Log.w(Database.TAG, "Failed to delete file/directly: " + destDir); return false; } } try { FileDirUtils.copyFolder(srcDir, destDir); } catch (IOException e) { Log.w(Database.TAG, "Failed to copy directly from " + srcDir + " to " + destDir, e); return false; } try { db.open(); } catch (CouchbaseLiteException e) { Log.w(Database.TAG, "Failed to open database", e); return false; } /* TODO: Currently Java implementation is different from iOS, needs to catch up. if(!db.saveLocalUUIDInLocalCheckpointDocument()){ Log.w(Database.TAG, "Failed to replace UUIDs"); return false; } */ if(!db.replaceUUIDs()){ Log.w(Database.TAG, "Failed to replace UUIDs"); db.close(); return false; } // close so app can (re)open db with its preferred options: db.close(); return true; }
java
@InterfaceAudience.Public public boolean replaceDatabase(String databaseName, String databaseDir) { Database db = getDatabase(databaseName, false); if(db == null) return false; File dir = new File(databaseDir); if(!dir.exists()){ Log.w(Database.TAG, "Database file doesn't exist at path : %s", databaseDir); return false; } if (!dir.isDirectory()) { Log.w(Database.TAG, "Database file is not a directory. " + "Use -replaceDatabaseNamed:withDatabaseFilewithAttachments:error: instead."); return false; } File destDir = new File(db.getPath()); File srcDir = new File(databaseDir); if(destDir.exists()) { if (!FileDirUtils.deleteRecursive(destDir)) { Log.w(Database.TAG, "Failed to delete file/directly: " + destDir); return false; } } try { FileDirUtils.copyFolder(srcDir, destDir); } catch (IOException e) { Log.w(Database.TAG, "Failed to copy directly from " + srcDir + " to " + destDir, e); return false; } try { db.open(); } catch (CouchbaseLiteException e) { Log.w(Database.TAG, "Failed to open database", e); return false; } /* TODO: Currently Java implementation is different from iOS, needs to catch up. if(!db.saveLocalUUIDInLocalCheckpointDocument()){ Log.w(Database.TAG, "Failed to replace UUIDs"); return false; } */ if(!db.replaceUUIDs()){ Log.w(Database.TAG, "Failed to replace UUIDs"); db.close(); return false; } // close so app can (re)open db with its preferred options: db.close(); return true; }
[ "@", "InterfaceAudience", ".", "Public", "public", "boolean", "replaceDatabase", "(", "String", "databaseName", ",", "String", "databaseDir", ")", "{", "Database", "db", "=", "getDatabase", "(", "databaseName", ",", "false", ")", ";", "if", "(", "db", "==", ...
Replaces or installs a database from a file. This is primarily used to install a canned database on first launch of an app, in which case you should first check .exists to avoid replacing the database if it exists already. The canned database would have been copied into your app bundle at build time. If the database file is not a directory and has the .cblite extension, use -replaceDatabaseNamed:withDatabaseFile:withAttachments:error: instead. @param databaseName The name of the database to replace. @param databaseDir Path of the database directory that should replace it. @return YES if the database was copied, NO if an error occurred.
[ "Replaces", "or", "installs", "a", "database", "from", "a", "file", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/Manager.java#L417-L472
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/Manager.java
Manager.runAsync
@InterfaceAudience.Private public Future runAsync(String databaseName, final AsyncTask function) throws CouchbaseLiteException { final Database database = getDatabase(databaseName); return runAsync(new Runnable() { @Override public void run() { function.run(database); } }); }
java
@InterfaceAudience.Private public Future runAsync(String databaseName, final AsyncTask function) throws CouchbaseLiteException { final Database database = getDatabase(databaseName); return runAsync(new Runnable() { @Override public void run() { function.run(database); } }); }
[ "@", "InterfaceAudience", ".", "Private", "public", "Future", "runAsync", "(", "String", "databaseName", ",", "final", "AsyncTask", "function", ")", "throws", "CouchbaseLiteException", "{", "final", "Database", "database", "=", "getDatabase", "(", "databaseName", ")...
Asynchronously dispatches a callback to run on a background thread. The callback will be passed Database instance. There is not currently a known reason to use it, it may not make sense on the Android API, but it was added for the purpose of having a consistent API with iOS. @exclude
[ "Asynchronously", "dispatches", "a", "callback", "to", "run", "on", "a", "background", "thread", ".", "The", "callback", "will", "be", "passed", "Database", "instance", ".", "There", "is", "not", "currently", "a", "known", "reason", "to", "use", "it", "it", ...
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/Manager.java#L538-L547
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/replicator/RemoteBulkDownloaderRequest.java
RemoteBulkDownloaderRequest.startedPart
@Override public void startedPart(Map headers) { if (_docReader != null) throw new IllegalStateException("_docReader is already defined"); Log.v(TAG, "%s: Starting new document; headers =%s", this, headers); _docReader = new MultipartDocumentReader(db); _docReader.setHeaders(headers); _docReader.startedPart(headers); }
java
@Override public void startedPart(Map headers) { if (_docReader != null) throw new IllegalStateException("_docReader is already defined"); Log.v(TAG, "%s: Starting new document; headers =%s", this, headers); _docReader = new MultipartDocumentReader(db); _docReader.setHeaders(headers); _docReader.startedPart(headers); }
[ "@", "Override", "public", "void", "startedPart", "(", "Map", "headers", ")", "{", "if", "(", "_docReader", "!=", "null", ")", "throw", "new", "IllegalStateException", "(", "\"_docReader is already defined\"", ")", ";", "Log", ".", "v", "(", "TAG", ",", "\"%...
This method is called when a part's headers have been parsed, before its data is parsed.
[ "This", "method", "is", "called", "when", "a", "part", "s", "headers", "have", "been", "parsed", "before", "its", "data", "is", "parsed", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/replicator/RemoteBulkDownloaderRequest.java#L196-L204
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/replicator/RemoteBulkDownloaderRequest.java
RemoteBulkDownloaderRequest.finishedPart
@Override public void finishedPart() { if (_docReader == null) throw new IllegalStateException("_docReader is not defined"); _docReader.finish(); _onDocument.onDocument(_docReader.getDocumentProperties(), _docReader.getDocumentSize()); _docReader = null; Log.v(TAG, "%s: Finished document", this); }
java
@Override public void finishedPart() { if (_docReader == null) throw new IllegalStateException("_docReader is not defined"); _docReader.finish(); _onDocument.onDocument(_docReader.getDocumentProperties(), _docReader.getDocumentSize()); _docReader = null; Log.v(TAG, "%s: Finished document", this); }
[ "@", "Override", "public", "void", "finishedPart", "(", ")", "{", "if", "(", "_docReader", "==", "null", ")", "throw", "new", "IllegalStateException", "(", "\"_docReader is not defined\"", ")", ";", "_docReader", ".", "finish", "(", ")", ";", "_onDocument", "....
This method is called when a part is complete.
[ "This", "method", "is", "called", "when", "a", "part", "is", "complete", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/replicator/RemoteBulkDownloaderRequest.java#L224-L232
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/QueryRow.java
QueryRow.getDocument
@InterfaceAudience.Public public Document getDocument() { if (getDocumentId() == null) { return null; } assert (database != null); Document document = database.getDocument(getDocumentId()); document.loadCurrentRevisionFrom(this); return document; }
java
@InterfaceAudience.Public public Document getDocument() { if (getDocumentId() == null) { return null; } assert (database != null); Document document = database.getDocument(getDocumentId()); document.loadCurrentRevisionFrom(this); return document; }
[ "@", "InterfaceAudience", ".", "Public", "public", "Document", "getDocument", "(", ")", "{", "if", "(", "getDocumentId", "(", ")", "==", "null", ")", "{", "return", "null", ";", "}", "assert", "(", "database", "!=", "null", ")", ";", "Document", "documen...
The document this row was mapped from. This will be nil if a grouping was enabled in the query, because then the result rows don't correspond to individual documents.
[ "The", "document", "this", "row", "was", "mapped", "from", ".", "This", "will", "be", "nil", "if", "a", "grouping", "was", "enabled", "in", "the", "query", "because", "then", "the", "result", "rows", "don", "t", "correspond", "to", "individual", "documents...
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/QueryRow.java#L104-L113
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/QueryRow.java
QueryRow.getDocumentId
@InterfaceAudience.Public public String getDocumentId() { // Get the doc id from either the embedded document contents, or the '_id' value key. // Failing that, there's no document linking, so use the regular old _sourceDocID String docID = null; if (documentRevision != null) docID = documentRevision.getDocID(); if (docID == null) { if (value != null) { if (value instanceof Map) { Map<String, Object> props = (Map<String, Object>) value; docID = (String) props.get("_id"); } } } if (docID == null) docID = sourceDocID; return docID; }
java
@InterfaceAudience.Public public String getDocumentId() { // Get the doc id from either the embedded document contents, or the '_id' value key. // Failing that, there's no document linking, so use the regular old _sourceDocID String docID = null; if (documentRevision != null) docID = documentRevision.getDocID(); if (docID == null) { if (value != null) { if (value instanceof Map) { Map<String, Object> props = (Map<String, Object>) value; docID = (String) props.get("_id"); } } } if (docID == null) docID = sourceDocID; return docID; }
[ "@", "InterfaceAudience", ".", "Public", "public", "String", "getDocumentId", "(", ")", "{", "// Get the doc id from either the embedded document contents, or the '_id' value key.", "// Failing that, there's no document linking, so use the regular old _sourceDocID", "String", "docID", "=...
The ID of the document described by this view row. This is not necessarily the same as the document that caused this row to be emitted; see the discussion of the .sourceDocumentID property for details.
[ "The", "ID", "of", "the", "document", "described", "by", "this", "view", "row", ".", "This", "is", "not", "necessarily", "the", "same", "as", "the", "document", "that", "caused", "this", "row", "to", "be", "emitted", ";", "see", "the", "discussion", "of"...
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/QueryRow.java#L136-L154
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/QueryRow.java
QueryRow.getDocumentRevisionId
@InterfaceAudience.Public public String getDocumentRevisionId() { // Get the revision id from either the embedded document contents, // or the '_rev' or 'rev' value key: String rev = null; if (documentRevision != null) rev = documentRevision.getRevID(); if (rev == null) { if (value instanceof Map) { Map<String, Object> mapValue = (Map<String, Object>) value; rev = (String) mapValue.get("_rev"); if (rev == null) { rev = (String) mapValue.get("rev"); } } } return rev; }
java
@InterfaceAudience.Public public String getDocumentRevisionId() { // Get the revision id from either the embedded document contents, // or the '_rev' or 'rev' value key: String rev = null; if (documentRevision != null) rev = documentRevision.getRevID(); if (rev == null) { if (value instanceof Map) { Map<String, Object> mapValue = (Map<String, Object>) value; rev = (String) mapValue.get("_rev"); if (rev == null) { rev = (String) mapValue.get("rev"); } } } return rev; }
[ "@", "InterfaceAudience", ".", "Public", "public", "String", "getDocumentRevisionId", "(", ")", "{", "// Get the revision id from either the embedded document contents,", "// or the '_rev' or 'rev' value key:", "String", "rev", "=", "null", ";", "if", "(", "documentRevision", ...
The revision ID of the document this row was mapped from.
[ "The", "revision", "ID", "of", "the", "document", "this", "row", "was", "mapped", "from", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/QueryRow.java#L172-L189
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/support/action/Action.java
Action.add
public void add(final AtomicAction action) { if (action instanceof Action) { Action a = (Action)action; peforms.addAll(a.peforms); backouts.addAll(a.backouts); cleanUps.addAll(a.cleanUps); } else { add(new ActionBlock() { @Override public void execute() throws ActionException { action.perform(); } }, new ActionBlock() { @Override public void execute() throws ActionException { action.backout(); } }, new ActionBlock() { @Override public void execute() throws ActionException { action.cleanup(); } }); } }
java
public void add(final AtomicAction action) { if (action instanceof Action) { Action a = (Action)action; peforms.addAll(a.peforms); backouts.addAll(a.backouts); cleanUps.addAll(a.cleanUps); } else { add(new ActionBlock() { @Override public void execute() throws ActionException { action.perform(); } }, new ActionBlock() { @Override public void execute() throws ActionException { action.backout(); } }, new ActionBlock() { @Override public void execute() throws ActionException { action.cleanup(); } }); } }
[ "public", "void", "add", "(", "final", "AtomicAction", "action", ")", "{", "if", "(", "action", "instanceof", "Action", ")", "{", "Action", "a", "=", "(", "Action", ")", "action", ";", "peforms", ".", "addAll", "(", "a", ".", "peforms", ")", ";", "ba...
Adds an action as a step of thid one. @param action
[ "Adds", "an", "action", "as", "a", "step", "of", "thid", "one", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/support/action/Action.java#L80-L104
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/support/action/Action.java
Action.add
public void add(ActionBlock perform, ActionBlock backout, ActionBlock cleanup) { peforms.add(perform != null ? perform : nullAction); backouts.add(backout != null ? backout : nullAction); cleanUps.add(cleanup != null ? cleanup : nullAction); }
java
public void add(ActionBlock perform, ActionBlock backout, ActionBlock cleanup) { peforms.add(perform != null ? perform : nullAction); backouts.add(backout != null ? backout : nullAction); cleanUps.add(cleanup != null ? cleanup : nullAction); }
[ "public", "void", "add", "(", "ActionBlock", "perform", ",", "ActionBlock", "backout", ",", "ActionBlock", "cleanup", ")", "{", "peforms", ".", "add", "(", "perform", "!=", "null", "?", "perform", ":", "nullAction", ")", ";", "backouts", ".", "add", "(", ...
Adds an action as a step of this one. The action has three components, each optional. @param perform A block that tries to perform the action, or returns an error if it fails. (If the block fails, it should clean up; the backOut will _not_ be called!) @param backout A block that undoes the effect of the action; it will be called if a _later_ action fails, so that the system can be returned to the initial state. @param cleanup A block that performs any necessary cleanup after all actions have been performed (e.g. deleting a temporary file.)
[ "Adds", "an", "action", "as", "a", "step", "of", "this", "one", ".", "The", "action", "has", "three", "components", "each", "optional", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/support/action/Action.java#L115-L119
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/support/action/Action.java
Action.run
public void run() throws ActionException { try { perform(); try { cleanup(); // Ignore exception } catch (ActionException e) {} lastError = null; } catch (ActionException e) { // (perform: has already backed out whatever it did) lastError = e; throw e; } }
java
public void run() throws ActionException { try { perform(); try { cleanup(); // Ignore exception } catch (ActionException e) {} lastError = null; } catch (ActionException e) { // (perform: has already backed out whatever it did) lastError = e; throw e; } }
[ "public", "void", "run", "(", ")", "throws", "ActionException", "{", "try", "{", "perform", "(", ")", ";", "try", "{", "cleanup", "(", ")", ";", "// Ignore exception", "}", "catch", "(", "ActionException", "e", ")", "{", "}", "lastError", "=", "null", ...
Performs all the actions in order. If any action fails, backs out the previously performed actions in reverse order. If the actions succeeded, cleans them up in reverse order. The `lastError` property is set to the exception thrown by the failed perform block. The `failedStep` property is set to the index of the failed perform block. @throws ActionException
[ "Performs", "all", "the", "actions", "in", "order", ".", "If", "any", "action", "fails", "backs", "out", "the", "previously", "performed", "actions", "in", "reverse", "order", ".", "If", "the", "actions", "succeeded", "cleans", "them", "up", "in", "reverse",...
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/support/action/Action.java#L140-L152
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/support/action/Action.java
Action.doAction
private void doAction(List<ActionBlock> actions) throws ActionException { try { actions.get(nextStep).execute(); } catch (ActionException e) { throw e; } catch (Exception e) { throw new ActionException("Exception raised by step: " + nextStep, e); } }
java
private void doAction(List<ActionBlock> actions) throws ActionException { try { actions.get(nextStep).execute(); } catch (ActionException e) { throw e; } catch (Exception e) { throw new ActionException("Exception raised by step: " + nextStep, e); } }
[ "private", "void", "doAction", "(", "List", "<", "ActionBlock", ">", "actions", ")", "throws", "ActionException", "{", "try", "{", "actions", ".", "get", "(", "nextStep", ")", ".", "execute", "(", ")", ";", "}", "catch", "(", "ActionException", "e", ")",...
Subroutine that calls an action block from either performs, backOuts or cleanUps. @param actions @throws ActionException
[ "Subroutine", "that", "calls", "an", "action", "block", "from", "either", "performs", "backOuts", "or", "cleanUps", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/support/action/Action.java#L210-L218
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/store/SQLiteViewStore.java
SQLiteViewStore.setVersion
@Override public boolean setVersion(String version) { // Update the version column in the database. This is a little weird looking because we want // to avoid modifying the database if the version didn't change, and because the row might // not exist yet. SQLiteStorageEngine storage = store.getStorageEngine(); boolean hasView; Cursor cursor = null; try { String sql = "SELECT name, version FROM views WHERE name=?"; String[] args = {name}; cursor = storage.rawQuery(sql, args); hasView = cursor.moveToNext(); } catch (SQLException e) { Log.e(Log.TAG_VIEW, "Error querying existing view name " + name, e); return false; } finally { if (cursor != null) cursor.close(); } if (!hasView) { // no such record, so insert ContentValues insertValues = new ContentValues(); insertValues.put("name", name); insertValues.put("version", version); insertValues.put("total_docs", 0); storage.insert("views", null, insertValues); createIndex(); return true; // created new view } ContentValues updateValues = new ContentValues(); updateValues.put("version", version); updateValues.put("lastSequence", 0); updateValues.put("total_docs", 0); String[] whereArgs = {name, version}; int rowsAffected = storage.update("views", updateValues, "name=? AND version!=?", whereArgs); return (rowsAffected > 0); }
java
@Override public boolean setVersion(String version) { // Update the version column in the database. This is a little weird looking because we want // to avoid modifying the database if the version didn't change, and because the row might // not exist yet. SQLiteStorageEngine storage = store.getStorageEngine(); boolean hasView; Cursor cursor = null; try { String sql = "SELECT name, version FROM views WHERE name=?"; String[] args = {name}; cursor = storage.rawQuery(sql, args); hasView = cursor.moveToNext(); } catch (SQLException e) { Log.e(Log.TAG_VIEW, "Error querying existing view name " + name, e); return false; } finally { if (cursor != null) cursor.close(); } if (!hasView) { // no such record, so insert ContentValues insertValues = new ContentValues(); insertValues.put("name", name); insertValues.put("version", version); insertValues.put("total_docs", 0); storage.insert("views", null, insertValues); createIndex(); return true; // created new view } ContentValues updateValues = new ContentValues(); updateValues.put("version", version); updateValues.put("lastSequence", 0); updateValues.put("total_docs", 0); String[] whereArgs = {name, version}; int rowsAffected = storage.update("views", updateValues, "name=? AND version!=?", whereArgs); return (rowsAffected > 0); }
[ "@", "Override", "public", "boolean", "setVersion", "(", "String", "version", ")", "{", "// Update the version column in the database. This is a little weird looking because we want", "// to avoid modifying the database if the version didn't change, and because the row might", "// not exist ...
Updates the version of the view. A change in version means the delegate's map block has changed its semantics, so the _index should be deleted.
[ "Updates", "the", "version", "of", "the", "view", ".", "A", "change", "in", "version", "means", "the", "delegate", "s", "map", "block", "has", "changed", "its", "semantics", "so", "the", "_index", "should", "be", "deleted", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/store/SQLiteViewStore.java#L143-L185
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/store/SQLiteViewStore.java
SQLiteViewStore.getLastSequenceIndexed
@Override public long getLastSequenceIndexed() { String sql = "SELECT lastSequence FROM views WHERE name=?"; String[] args = {name}; Cursor cursor = null; long result = -1; try { cursor = store.getStorageEngine().rawQuery(sql, args); if (cursor.moveToNext()) { result = cursor.getLong(0); } } catch (Exception e) { Log.e(Log.TAG_VIEW, "Error getting last sequence indexed", e); } finally { if (cursor != null) { cursor.close(); } } return result; }
java
@Override public long getLastSequenceIndexed() { String sql = "SELECT lastSequence FROM views WHERE name=?"; String[] args = {name}; Cursor cursor = null; long result = -1; try { cursor = store.getStorageEngine().rawQuery(sql, args); if (cursor.moveToNext()) { result = cursor.getLong(0); } } catch (Exception e) { Log.e(Log.TAG_VIEW, "Error getting last sequence indexed", e); } finally { if (cursor != null) { cursor.close(); } } return result; }
[ "@", "Override", "public", "long", "getLastSequenceIndexed", "(", ")", "{", "String", "sql", "=", "\"SELECT lastSequence FROM views WHERE name=?\"", ";", "String", "[", "]", "args", "=", "{", "name", "}", ";", "Cursor", "cursor", "=", "null", ";", "long", "res...
The last sequence number that has been indexed.
[ "The", "last", "sequence", "number", "that", "has", "been", "indexed", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/store/SQLiteViewStore.java#L210-L229
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/store/SQLiteViewStore.java
SQLiteViewStore.groupTogether
private static boolean groupTogether(Object key1, Object key2, int groupLevel) { if (groupLevel == 0 || !(key1 instanceof List) || !(key2 instanceof List)) { return key1.equals(key2); } @SuppressWarnings("unchecked") List<Object> key1List = (List<Object>) key1; @SuppressWarnings("unchecked") List<Object> key2List = (List<Object>) key2; // if either key list is smaller than groupLevel and the key lists are different // sizes, they cannot be equal. if ((key1List.size() < groupLevel || key2List.size() < groupLevel) && key1List.size() != key2List.size()) { return false; } int end = Math.min(groupLevel, Math.min(key1List.size(), key2List.size())); for (int i = 0; i < end; ++i) { if (key1List.get(i) != null && !key1List.get(i).equals(key2List.get(i))) return false; else if (key1List.get(i) == null && key2List.get(i) != null) return false; } return true; }
java
private static boolean groupTogether(Object key1, Object key2, int groupLevel) { if (groupLevel == 0 || !(key1 instanceof List) || !(key2 instanceof List)) { return key1.equals(key2); } @SuppressWarnings("unchecked") List<Object> key1List = (List<Object>) key1; @SuppressWarnings("unchecked") List<Object> key2List = (List<Object>) key2; // if either key list is smaller than groupLevel and the key lists are different // sizes, they cannot be equal. if ((key1List.size() < groupLevel || key2List.size() < groupLevel) && key1List.size() != key2List.size()) { return false; } int end = Math.min(groupLevel, Math.min(key1List.size(), key2List.size())); for (int i = 0; i < end; ++i) { if (key1List.get(i) != null && !key1List.get(i).equals(key2List.get(i))) return false; else if (key1List.get(i) == null && key2List.get(i) != null) return false; } return true; }
[ "private", "static", "boolean", "groupTogether", "(", "Object", "key1", ",", "Object", "key2", ",", "int", "groupLevel", ")", "{", "if", "(", "groupLevel", "==", "0", "||", "!", "(", "key1", "instanceof", "List", ")", "||", "!", "(", "key2", "instanceof"...
Are key1 and key2 grouped together at this groupLevel?
[ "Are", "key1", "and", "key2", "grouped", "together", "at", "this", "groupLevel?" ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/store/SQLiteViewStore.java#L1109-L1133
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/store/SQLiteViewStore.java
SQLiteViewStore.groupKey
public static Object groupKey(Object key, int groupLevel) { if (groupLevel > 0 && (key instanceof List) && (((List<Object>) key).size() > groupLevel)) { return ((List<Object>) key).subList(0, groupLevel); } else { return key; } }
java
public static Object groupKey(Object key, int groupLevel) { if (groupLevel > 0 && (key instanceof List) && (((List<Object>) key).size() > groupLevel)) { return ((List<Object>) key).subList(0, groupLevel); } else { return key; } }
[ "public", "static", "Object", "groupKey", "(", "Object", "key", ",", "int", "groupLevel", ")", "{", "if", "(", "groupLevel", ">", "0", "&&", "(", "key", "instanceof", "List", ")", "&&", "(", "(", "(", "List", "<", "Object", ">", ")", "key", ")", "....
Returns the prefix of the key to use in the result row, at this groupLevel
[ "Returns", "the", "prefix", "of", "the", "key", "to", "use", "in", "the", "result", "row", "at", "this", "groupLevel" ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/store/SQLiteViewStore.java#L1138-L1144
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/View.java
View.getTotalRows
@InterfaceAudience.Public public int getTotalRows() { try { updateIndex(); } catch (CouchbaseLiteException e) { Log.e(Log.TAG_VIEW, "Update index failed when getting the total rows", e); } return getCurrentTotalRows(); }
java
@InterfaceAudience.Public public int getTotalRows() { try { updateIndex(); } catch (CouchbaseLiteException e) { Log.e(Log.TAG_VIEW, "Update index failed when getting the total rows", e); } return getCurrentTotalRows(); }
[ "@", "InterfaceAudience", ".", "Public", "public", "int", "getTotalRows", "(", ")", "{", "try", "{", "updateIndex", "(", ")", ";", "}", "catch", "(", "CouchbaseLiteException", "e", ")", "{", "Log", ".", "e", "(", "Log", ".", "TAG_VIEW", ",", "\"Update in...
Get total number of rows in the view. The view's index will be updated if needed before returning the value.
[ "Get", "total", "number", "of", "rows", "in", "the", "view", ".", "The", "view", "s", "index", "will", "be", "updated", "if", "needed", "before", "returning", "the", "value", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/View.java#L183-L191
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/View.java
View.totalValues
@InterfaceAudience.Public public static double totalValues(List<Object> values) { double total = 0; for (Object object : values) { if (object instanceof Number) { Number number = (Number) object; total += number.doubleValue(); } else { Log.w(Log.TAG_VIEW, "Warning non-numeric value found in totalValues: %s", object); } } return total; }
java
@InterfaceAudience.Public public static double totalValues(List<Object> values) { double total = 0; for (Object object : values) { if (object instanceof Number) { Number number = (Number) object; total += number.doubleValue(); } else { Log.w(Log.TAG_VIEW, "Warning non-numeric value found in totalValues: %s", object); } } return total; }
[ "@", "InterfaceAudience", ".", "Public", "public", "static", "double", "totalValues", "(", "List", "<", "Object", ">", "values", ")", "{", "double", "total", "=", "0", ";", "for", "(", "Object", "object", ":", "values", ")", "{", "if", "(", "object", "...
Utility function to use in reduce blocks. Totals an array of Numbers.
[ "Utility", "function", "to", "use", "in", "reduce", "blocks", ".", "Totals", "an", "array", "of", "Numbers", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/View.java#L234-L246
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/View.java
View.updateIndexes
@InterfaceAudience.Private protected Status updateIndexes(List<View> views) throws CouchbaseLiteException { List<ViewStore> storages = new ArrayList<ViewStore>(); for (View view : views) { storages.add(view.viewStore); } return viewStore.updateIndexes(storages); }
java
@InterfaceAudience.Private protected Status updateIndexes(List<View> views) throws CouchbaseLiteException { List<ViewStore> storages = new ArrayList<ViewStore>(); for (View view : views) { storages.add(view.viewStore); } return viewStore.updateIndexes(storages); }
[ "@", "InterfaceAudience", ".", "Private", "protected", "Status", "updateIndexes", "(", "List", "<", "View", ">", "views", ")", "throws", "CouchbaseLiteException", "{", "List", "<", "ViewStore", ">", "storages", "=", "new", "ArrayList", "<", "ViewStore", ">", "...
Update multiple view indexes at once. @param views a list of views whose index will be updated. @throws CouchbaseLiteException
[ "Update", "multiple", "view", "indexes", "at", "once", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/View.java#L316-L323
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/View.java
View.query
@InterfaceAudience.Private public List<QueryRow> query(QueryOptions options) throws CouchbaseLiteException { if (options == null) options = new QueryOptions(); if (groupOrReduce(options)) return viewStore.reducedQuery(options); else return viewStore.regularQuery(options); }
java
@InterfaceAudience.Private public List<QueryRow> query(QueryOptions options) throws CouchbaseLiteException { if (options == null) options = new QueryOptions(); if (groupOrReduce(options)) return viewStore.reducedQuery(options); else return viewStore.regularQuery(options); }
[ "@", "InterfaceAudience", ".", "Private", "public", "List", "<", "QueryRow", ">", "query", "(", "QueryOptions", "options", ")", "throws", "CouchbaseLiteException", "{", "if", "(", "options", "==", "null", ")", "options", "=", "new", "QueryOptions", "(", ")", ...
Queries the view. Does NOT first update the index. @param options The options to use. @return An array of QueryRow objects.
[ "Queries", "the", "view", ".", "Does", "NOT", "first", "update", "the", "index", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/View.java#L352-L360
train
couchbase/couchbase-lite-java-core
vendor/sqlite/src/java/com/couchbase/lite/internal/database/util/PrefixPrinter.java
PrefixPrinter.create
public static Printer create(Printer printer, String prefix) { if (prefix == null || prefix.equals("")) { return printer; } return new PrefixPrinter(printer, prefix); }
java
public static Printer create(Printer printer, String prefix) { if (prefix == null || prefix.equals("")) { return printer; } return new PrefixPrinter(printer, prefix); }
[ "public", "static", "Printer", "create", "(", "Printer", "printer", ",", "String", "prefix", ")", "{", "if", "(", "prefix", "==", "null", "||", "prefix", ".", "equals", "(", "\"\"", ")", ")", "{", "return", "printer", ";", "}", "return", "new", "Prefix...
Creates a new PrefixPrinter. <p>If prefix is null or empty, the provided printer is returned, rather than making a prefixing printer.
[ "Creates", "a", "new", "PrefixPrinter", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/vendor/sqlite/src/java/com/couchbase/lite/internal/database/util/PrefixPrinter.java#L40-L45
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/support/PersistentCookieJar.java
PersistentCookieJar.deleteCookie
public void deleteCookie(Cookie cookie) { cookies.remove(cookie.name()); deletePersistedCookie(cookie.name()); }
java
public void deleteCookie(Cookie cookie) { cookies.remove(cookie.name()); deletePersistedCookie(cookie.name()); }
[ "public", "void", "deleteCookie", "(", "Cookie", "cookie", ")", "{", "cookies", ".", "remove", "(", "cookie", ".", "name", "(", ")", ")", ";", "deletePersistedCookie", "(", "cookie", ".", "name", "(", ")", ")", ";", "}" ]
Non-standard helper method, to delete cookie @param cookie cookie to be removed
[ "Non", "-", "standard", "helper", "method", "to", "delete", "cookie" ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/support/PersistentCookieJar.java#L165-L168
train
couchbase/couchbase-lite-java-core
vendor/sqlite/src/java/com/couchbase/lite/internal/database/sqlite/SQLiteGlobal.java
SQLiteGlobal.getDefaultPageSize
public static int getDefaultPageSize() { synchronized (sLock) { if (sDefaultPageSize == 0) { try { Class clazz = Class.forName("android.os.StatFs"); Method m = clazz.getMethod("getBlockSize"); Object statFsObj = clazz.getConstructor(String.class).newInstance("/data"); Integer value = (Integer) m.invoke(statFsObj, (Object[])null); if (value != null) return value.intValue(); } catch (Exception e) { } } if (sDefaultPageSize == 0) sDefaultPageSize = 1024; return sDefaultPageSize; } }
java
public static int getDefaultPageSize() { synchronized (sLock) { if (sDefaultPageSize == 0) { try { Class clazz = Class.forName("android.os.StatFs"); Method m = clazz.getMethod("getBlockSize"); Object statFsObj = clazz.getConstructor(String.class).newInstance("/data"); Integer value = (Integer) m.invoke(statFsObj, (Object[])null); if (value != null) return value.intValue(); } catch (Exception e) { } } if (sDefaultPageSize == 0) sDefaultPageSize = 1024; return sDefaultPageSize; } }
[ "public", "static", "int", "getDefaultPageSize", "(", ")", "{", "synchronized", "(", "sLock", ")", "{", "if", "(", "sDefaultPageSize", "==", "0", ")", "{", "try", "{", "Class", "clazz", "=", "Class", ".", "forName", "(", "\"android.os.StatFs\"", ")", ";", ...
Gets the default page size to use when creating a database.
[ "Gets", "the", "default", "page", "size", "to", "use", "when", "creating", "a", "database", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/vendor/sqlite/src/java/com/couchbase/lite/internal/database/sqlite/SQLiteGlobal.java#L48-L64
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/support/SerializableCookie.java
SerializableCookie.byteArrayToHexString
private static String byteArrayToHexString(byte[] bytes) { StringBuilder sb = new StringBuilder(bytes.length * 2); for (byte element : bytes) { int v = element & 0xff; if (v < 16) { sb.append('0'); } sb.append(Integer.toHexString(v)); } return sb.toString(); }
java
private static String byteArrayToHexString(byte[] bytes) { StringBuilder sb = new StringBuilder(bytes.length * 2); for (byte element : bytes) { int v = element & 0xff; if (v < 16) { sb.append('0'); } sb.append(Integer.toHexString(v)); } return sb.toString(); }
[ "private", "static", "String", "byteArrayToHexString", "(", "byte", "[", "]", "bytes", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", "bytes", ".", "length", "*", "2", ")", ";", "for", "(", "byte", "element", ":", "bytes", ")", "{", ...
Using some super basic byte array &lt;-&gt; hex conversions so we don't have to rely on any large Base64 libraries. Can be overridden if you like! @param bytes byte array to be converted @return string containing hex values
[ "Using", "some", "super", "basic", "byte", "array", "&lt", ";", "-", "&gt", ";", "hex", "conversions", "so", "we", "don", "t", "have", "to", "rely", "on", "any", "large", "Base64", "libraries", ".", "Can", "be", "overridden", "if", "you", "like!" ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/support/SerializableCookie.java#L67-L77
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/SavedRevision.java
SavedRevision.createRevision
@InterfaceAudience.Public public SavedRevision createRevision(Map<String, Object> properties) throws CouchbaseLiteException { boolean allowConflict = false; return document.putProperties(properties, revisionInternal.getRevID(), allowConflict); }
java
@InterfaceAudience.Public public SavedRevision createRevision(Map<String, Object> properties) throws CouchbaseLiteException { boolean allowConflict = false; return document.putProperties(properties, revisionInternal.getRevID(), allowConflict); }
[ "@", "InterfaceAudience", ".", "Public", "public", "SavedRevision", "createRevision", "(", "Map", "<", "String", ",", "Object", ">", "properties", ")", "throws", "CouchbaseLiteException", "{", "boolean", "allowConflict", "=", "false", ";", "return", "document", "....
Creates and saves a new revision with the given properties. This will fail with a 412 error if the receiver is not the current revision of the document.
[ "Creates", "and", "saves", "a", "new", "revision", "with", "the", "given", "properties", ".", "This", "will", "fail", "with", "a", "412", "error", "if", "the", "receiver", "is", "not", "the", "current", "revision", "of", "the", "document", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/SavedRevision.java#L121-L125
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/SavedRevision.java
SavedRevision.getProperties
@Override @InterfaceAudience.Public public Map<String, Object> getProperties() { Map<String, Object> properties = revisionInternal.getProperties(); if (!checkedProperties) { if (properties == null) { if (loadProperties() == true) { properties = revisionInternal.getProperties(); } } checkedProperties = true; } return properties != null ? Collections.unmodifiableMap(properties) : null; }
java
@Override @InterfaceAudience.Public public Map<String, Object> getProperties() { Map<String, Object> properties = revisionInternal.getProperties(); if (!checkedProperties) { if (properties == null) { if (loadProperties() == true) { properties = revisionInternal.getProperties(); } } checkedProperties = true; } return properties != null ? Collections.unmodifiableMap(properties) : null; }
[ "@", "Override", "@", "InterfaceAudience", ".", "Public", "public", "Map", "<", "String", ",", "Object", ">", "getProperties", "(", ")", "{", "Map", "<", "String", ",", "Object", ">", "properties", "=", "revisionInternal", ".", "getProperties", "(", ")", "...
The contents of this revision of the document. Any keys in the dictionary that begin with "_", such as "_id" and "_rev", contain CouchbaseLite metadata. @return contents of this revision of the document.
[ "The", "contents", "of", "this", "revision", "of", "the", "document", ".", "Any", "keys", "in", "the", "dictionary", "that", "begin", "with", "_", "such", "as", "_id", "and", "_rev", "contain", "CouchbaseLite", "metadata", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/SavedRevision.java#L146-L159
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/support/JsonDocument.java
JsonDocument.jsonObject
public Object jsonObject() { if (json == null) { return null; } if (cached == null) { Object tmp = null; if (json[0] == '{') { tmp = new LazyJsonObject<String, Object>(json); } else if (json[0] == '[') { tmp = new LazyJsonArray<Object>(json); } else { try { // NOTE: This if-else condition is for Jackson 2.5.0 // json variable is byte[] which is from Cursor.getBlob(). // And json byte array is ended with '\0'. // '\0' causes parsing problem with Jackson 2.5.0 that we upgraded Feb 24, 2015. // We did not observe this problem with Jackson 1.9.2 that we used before. if(json.length > 0 && json[json.length - 1] == 0) { tmp = Manager.getObjectMapper().readValue(json, 0, json.length - 1, Object.class); } else { tmp = Manager.getObjectMapper().readValue(json, Object.class); } } catch (Exception e) { //cached will remain null Log.w(Database.TAG, "Exception parsing json", e); } } cached = tmp; } return cached; }
java
public Object jsonObject() { if (json == null) { return null; } if (cached == null) { Object tmp = null; if (json[0] == '{') { tmp = new LazyJsonObject<String, Object>(json); } else if (json[0] == '[') { tmp = new LazyJsonArray<Object>(json); } else { try { // NOTE: This if-else condition is for Jackson 2.5.0 // json variable is byte[] which is from Cursor.getBlob(). // And json byte array is ended with '\0'. // '\0' causes parsing problem with Jackson 2.5.0 that we upgraded Feb 24, 2015. // We did not observe this problem with Jackson 1.9.2 that we used before. if(json.length > 0 && json[json.length - 1] == 0) { tmp = Manager.getObjectMapper().readValue(json, 0, json.length - 1, Object.class); } else { tmp = Manager.getObjectMapper().readValue(json, Object.class); } } catch (Exception e) { //cached will remain null Log.w(Database.TAG, "Exception parsing json", e); } } cached = tmp; } return cached; }
[ "public", "Object", "jsonObject", "(", ")", "{", "if", "(", "json", "==", "null", ")", "{", "return", "null", ";", "}", "if", "(", "cached", "==", "null", ")", "{", "Object", "tmp", "=", "null", ";", "if", "(", "json", "[", "0", "]", "==", "'",...
values are requested
[ "values", "are", "requested" ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/support/JsonDocument.java#L37-L72
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/support/Batcher.java
Batcher.queueObjects
public void queueObjects(List<T> objects) { if (objects == null || objects.size() == 0) return; boolean readyToProcess = false; synchronized (mutex) { Log.v(Log.TAG_BATCHER, "%s: queueObjects called with %d objects (current inbox size = %d)", this, objects.size(), inbox.size()); inbox.addAll(objects); mutex.notifyAll(); if (isFlushing) { // Skip scheduling as flushing is processing all the queue objects: return; } scheduleBatchProcess(false); if (inbox.size() >= capacity && isPendingFutureReadyOrInProcessing()) readyToProcess = true; } if (readyToProcess) { // Give work executor chance to work on a scheduled task and to obtain the // mutex lock when another thread keeps adding objects to the queue fast: synchronized (processMutex) { try { processMutex.wait(5); } catch (InterruptedException e) { } } } }
java
public void queueObjects(List<T> objects) { if (objects == null || objects.size() == 0) return; boolean readyToProcess = false; synchronized (mutex) { Log.v(Log.TAG_BATCHER, "%s: queueObjects called with %d objects (current inbox size = %d)", this, objects.size(), inbox.size()); inbox.addAll(objects); mutex.notifyAll(); if (isFlushing) { // Skip scheduling as flushing is processing all the queue objects: return; } scheduleBatchProcess(false); if (inbox.size() >= capacity && isPendingFutureReadyOrInProcessing()) readyToProcess = true; } if (readyToProcess) { // Give work executor chance to work on a scheduled task and to obtain the // mutex lock when another thread keeps adding objects to the queue fast: synchronized (processMutex) { try { processMutex.wait(5); } catch (InterruptedException e) { } } } }
[ "public", "void", "queueObjects", "(", "List", "<", "T", ">", "objects", ")", "{", "if", "(", "objects", "==", "null", "||", "objects", ".", "size", "(", ")", "==", "0", ")", "return", ";", "boolean", "readyToProcess", "=", "false", ";", "synchronized"...
Adds multiple objects to the queue.
[ "Adds", "multiple", "objects", "to", "the", "queue", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/support/Batcher.java#L132-L164
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/support/Batcher.java
Batcher.flushAll
public void flushAll(boolean waitForAllToFinish) { Log.v(Log.TAG_BATCHER, "%s: flushing all objects (wait=%b)", this, waitForAllToFinish); synchronized (mutex) { isFlushing = true; unschedule(); } while (true) { ScheduledFuture future = null; synchronized (mutex) { if (inbox.size() == 0) break; // Nothing to do final List<T> toProcess = new ArrayList<T>(inbox); inbox.clear(); mutex.notifyAll(); synchronized (workExecutor) { if (!workExecutor.isShutdown()) { future = workExecutor.schedule(new Runnable() { @Override public void run() { processor.process(toProcess); synchronized (mutex) { lastProcessedTime = System.currentTimeMillis(); } } }, 0, TimeUnit.MILLISECONDS); } } } if (waitForAllToFinish) { if (future != null && !future.isDone() && !future.isCancelled()) { try { future.get(); } catch (Exception e) { Log.e(Log.TAG_BATCHER, "%s: Error while waiting for pending future " + "when flushing all items", e, this); } } } } synchronized (mutex) { isFlushing = false; } }
java
public void flushAll(boolean waitForAllToFinish) { Log.v(Log.TAG_BATCHER, "%s: flushing all objects (wait=%b)", this, waitForAllToFinish); synchronized (mutex) { isFlushing = true; unschedule(); } while (true) { ScheduledFuture future = null; synchronized (mutex) { if (inbox.size() == 0) break; // Nothing to do final List<T> toProcess = new ArrayList<T>(inbox); inbox.clear(); mutex.notifyAll(); synchronized (workExecutor) { if (!workExecutor.isShutdown()) { future = workExecutor.schedule(new Runnable() { @Override public void run() { processor.process(toProcess); synchronized (mutex) { lastProcessedTime = System.currentTimeMillis(); } } }, 0, TimeUnit.MILLISECONDS); } } } if (waitForAllToFinish) { if (future != null && !future.isDone() && !future.isCancelled()) { try { future.get(); } catch (Exception e) { Log.e(Log.TAG_BATCHER, "%s: Error while waiting for pending future " + "when flushing all items", e, this); } } } } synchronized (mutex) { isFlushing = false; } }
[ "public", "void", "flushAll", "(", "boolean", "waitForAllToFinish", ")", "{", "Log", ".", "v", "(", "Log", ".", "TAG_BATCHER", ",", "\"%s: flushing all objects (wait=%b)\"", ",", "this", ",", "waitForAllToFinish", ")", ";", "synchronized", "(", "mutex", ")", "{"...
Sends _all_ the queued objects at once to the processor block. After this method returns, all inbox objects will be processed. @param waitForAllToFinish wait until all objects are processed. If set to True, need to make sure not to call flushAll in the same WorkExecutor used by the batcher as it will result to deadlock.
[ "Sends", "_all_", "the", "queued", "objects", "at", "once", "to", "the", "processor", "block", ".", "After", "this", "method", "returns", "all", "inbox", "objects", "will", "be", "processed", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/support/Batcher.java#L181-L228
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/support/Batcher.java
Batcher.scheduleBatchProcess
private void scheduleBatchProcess(boolean immediate) { synchronized (mutex) { if (inbox.size() == 0) return; // Schedule the processing. To improve latency, if we haven't processed anything // in at least our delay time, rush these object(s) through a minimum delay: long suggestedDelay = 0; if (!immediate && inbox.size() < capacity) { // Check with the last processed time: if (System.currentTimeMillis() - lastProcessedTime < delay) suggestedDelay = delay; else { // Note: iOS schedules with 0 delay but the iOS implementation // works on the runloop which still allows the current thread // to continue queuing objects to the batcher until going out of // the runloop. Java cannot do the same so giving a small delay to // allow objects to be added to the batch if available: suggestedDelay = Math.min(SMALL_DELAY_AFTER_LONG_PAUSE, delay); } } scheduleWithDelay(suggestedDelay); } }
java
private void scheduleBatchProcess(boolean immediate) { synchronized (mutex) { if (inbox.size() == 0) return; // Schedule the processing. To improve latency, if we haven't processed anything // in at least our delay time, rush these object(s) through a minimum delay: long suggestedDelay = 0; if (!immediate && inbox.size() < capacity) { // Check with the last processed time: if (System.currentTimeMillis() - lastProcessedTime < delay) suggestedDelay = delay; else { // Note: iOS schedules with 0 delay but the iOS implementation // works on the runloop which still allows the current thread // to continue queuing objects to the batcher until going out of // the runloop. Java cannot do the same so giving a small delay to // allow objects to be added to the batch if available: suggestedDelay = Math.min(SMALL_DELAY_AFTER_LONG_PAUSE, delay); } } scheduleWithDelay(suggestedDelay); } }
[ "private", "void", "scheduleBatchProcess", "(", "boolean", "immediate", ")", "{", "synchronized", "(", "mutex", ")", "{", "if", "(", "inbox", ".", "size", "(", ")", "==", "0", ")", "return", ";", "// Schedule the processing. To improve latency, if we haven't process...
Schedule batch process based on capacity, inbox size, and last processed time. @param immediate flag to schedule the batch process immediately regardless.
[ "Schedule", "batch", "process", "based", "on", "capacity", "inbox", "size", "and", "last", "processed", "time", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/support/Batcher.java#L291-L314
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/support/Batcher.java
Batcher.scheduleWithDelay
private void scheduleWithDelay(long delay) { synchronized (mutex) { if (scheduled && delay < scheduledDelay) { if (isPendingFutureReadyOrInProcessing()) { // Ignore as there is one batch currently in processing or ready to be processed: Log.v(Log.TAG_BATCHER, "%s: scheduleWithDelay: %d ms, ignored as current batch " + "is ready or in process", this, delay); return; } unschedule(); } if (!scheduled) { scheduled = true; scheduledDelay = delay; Log.v(Log.TAG_BATCHER, "%s: scheduleWithDelay %d ms, scheduled ...", this, delay); synchronized (workExecutor) { if (!workExecutor.isShutdown()) { pendingFuture = workExecutor.schedule(new Runnable() { @Override public void run() { Log.v(Log.TAG_BATCHER, "%s: call processNow ...", this); processNow(); Log.v(Log.TAG_BATCHER, "%s: call processNow done", this); } }, scheduledDelay, TimeUnit.MILLISECONDS); } } } else Log.v(Log.TAG_BATCHER, "%s: scheduleWithDelay %d ms, ignored", this, delay); } }
java
private void scheduleWithDelay(long delay) { synchronized (mutex) { if (scheduled && delay < scheduledDelay) { if (isPendingFutureReadyOrInProcessing()) { // Ignore as there is one batch currently in processing or ready to be processed: Log.v(Log.TAG_BATCHER, "%s: scheduleWithDelay: %d ms, ignored as current batch " + "is ready or in process", this, delay); return; } unschedule(); } if (!scheduled) { scheduled = true; scheduledDelay = delay; Log.v(Log.TAG_BATCHER, "%s: scheduleWithDelay %d ms, scheduled ...", this, delay); synchronized (workExecutor) { if (!workExecutor.isShutdown()) { pendingFuture = workExecutor.schedule(new Runnable() { @Override public void run() { Log.v(Log.TAG_BATCHER, "%s: call processNow ...", this); processNow(); Log.v(Log.TAG_BATCHER, "%s: call processNow done", this); } }, scheduledDelay, TimeUnit.MILLISECONDS); } } } else Log.v(Log.TAG_BATCHER, "%s: scheduleWithDelay %d ms, ignored", this, delay); } }
[ "private", "void", "scheduleWithDelay", "(", "long", "delay", ")", "{", "synchronized", "(", "mutex", ")", "{", "if", "(", "scheduled", "&&", "delay", "<", "scheduledDelay", ")", "{", "if", "(", "isPendingFutureReadyOrInProcessing", "(", ")", ")", "{", "// I...
Schedule the batch processing with the delay. If there is one batch currently in processing, the schedule will be ignored as after the processing is done, the next batch will be rescheduled. @param delay delay to schedule the work executor to process the next batch.
[ "Schedule", "the", "batch", "processing", "with", "the", "delay", ".", "If", "there", "is", "one", "batch", "currently", "in", "processing", "the", "schedule", "will", "be", "ignored", "as", "after", "the", "processing", "is", "done", "the", "next", "batch",...
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/support/Batcher.java#L322-L353
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/support/Batcher.java
Batcher.unschedule
private void unschedule() { synchronized (mutex) { if (pendingFuture != null && !pendingFuture.isDone() && !pendingFuture.isCancelled()) { Log.v(Log.TAG_BATCHER, "%s: cancelling the pending future ...", this); pendingFuture.cancel(false); } scheduled = false; } }
java
private void unschedule() { synchronized (mutex) { if (pendingFuture != null && !pendingFuture.isDone() && !pendingFuture.isCancelled()) { Log.v(Log.TAG_BATCHER, "%s: cancelling the pending future ...", this); pendingFuture.cancel(false); } scheduled = false; } }
[ "private", "void", "unschedule", "(", ")", "{", "synchronized", "(", "mutex", ")", "{", "if", "(", "pendingFuture", "!=", "null", "&&", "!", "pendingFuture", ".", "isDone", "(", ")", "&&", "!", "pendingFuture", ".", "isCancelled", "(", ")", ")", "{", "...
Unschedule the scheduled batch processing.
[ "Unschedule", "the", "scheduled", "batch", "processing", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/support/Batcher.java#L358-L366
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/support/Batcher.java
Batcher.isPendingFutureReadyOrInProcessing
private boolean isPendingFutureReadyOrInProcessing() { synchronized (mutex) { if (pendingFuture != null && !pendingFuture.isDone() && !pendingFuture.isCancelled()) { return pendingFuture.getDelay(TimeUnit.MILLISECONDS) <= 0; } return false; } }
java
private boolean isPendingFutureReadyOrInProcessing() { synchronized (mutex) { if (pendingFuture != null && !pendingFuture.isDone() && !pendingFuture.isCancelled()) { return pendingFuture.getDelay(TimeUnit.MILLISECONDS) <= 0; } return false; } }
[ "private", "boolean", "isPendingFutureReadyOrInProcessing", "(", ")", "{", "synchronized", "(", "mutex", ")", "{", "if", "(", "pendingFuture", "!=", "null", "&&", "!", "pendingFuture", ".", "isDone", "(", ")", "&&", "!", "pendingFuture", ".", "isCancelled", "(...
Check if the current pending future is ready to be processed or in processing. @return true if the current pending future is ready to be processed or in processing. Otherwise false. Will also return false if the current pending future is done or cancelled.
[ "Check", "if", "the", "current", "pending", "future", "is", "ready", "to", "be", "processed", "or", "in", "processing", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/support/Batcher.java#L373-L380
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/support/Batcher.java
Batcher.processNow
private void processNow() { List<T> toProcess; boolean scheduleNextBatchImmediately = false; synchronized (mutex) { int count = inbox.size(); Log.v(Log.TAG_BATCHER, "%s: processNow() called, inbox size: %d", this, count); if (count == 0) return; else if (count <= capacity) { toProcess = new ArrayList<T>(inbox); inbox.clear(); } else { toProcess = new ArrayList<T>(inbox.subList(0, capacity)); for (int i = 0; i < capacity; i++) inbox.remove(0); scheduleNextBatchImmediately = true; } mutex.notifyAll(); } synchronized (processMutex) { if (toProcess != null && toProcess.size() > 0) { Log.v(Log.TAG_BATCHER, "%s: invoking processor %s with %d items", this, processor, toProcess.size()); processor.process(toProcess); } else Log.v(Log.TAG_BATCHER, "%s: nothing to process", this); synchronized (mutex) { lastProcessedTime = System.currentTimeMillis(); scheduled = false; scheduleBatchProcess(scheduleNextBatchImmediately); Log.v(Log.TAG_BATCHER, "%s: invoking processor done", this, processor, toProcess.size()); } processMutex.notifyAll(); } }
java
private void processNow() { List<T> toProcess; boolean scheduleNextBatchImmediately = false; synchronized (mutex) { int count = inbox.size(); Log.v(Log.TAG_BATCHER, "%s: processNow() called, inbox size: %d", this, count); if (count == 0) return; else if (count <= capacity) { toProcess = new ArrayList<T>(inbox); inbox.clear(); } else { toProcess = new ArrayList<T>(inbox.subList(0, capacity)); for (int i = 0; i < capacity; i++) inbox.remove(0); scheduleNextBatchImmediately = true; } mutex.notifyAll(); } synchronized (processMutex) { if (toProcess != null && toProcess.size() > 0) { Log.v(Log.TAG_BATCHER, "%s: invoking processor %s with %d items", this, processor, toProcess.size()); processor.process(toProcess); } else Log.v(Log.TAG_BATCHER, "%s: nothing to process", this); synchronized (mutex) { lastProcessedTime = System.currentTimeMillis(); scheduled = false; scheduleBatchProcess(scheduleNextBatchImmediately); Log.v(Log.TAG_BATCHER, "%s: invoking processor done", this, processor, toProcess.size()); } processMutex.notifyAll(); } }
[ "private", "void", "processNow", "(", ")", "{", "List", "<", "T", ">", "toProcess", ";", "boolean", "scheduleNextBatchImmediately", "=", "false", ";", "synchronized", "(", "mutex", ")", "{", "int", "count", "=", "inbox", ".", "size", "(", ")", ";", "Log"...
This method is called by the work executor to do the batch process. The inbox items up to the batcher capacity will be taken out to process. The next batch will be rescheduled if there are still some items left in the inbox.
[ "This", "method", "is", "called", "by", "the", "work", "executor", "to", "do", "the", "batch", "process", ".", "The", "inbox", "items", "up", "to", "the", "batcher", "capacity", "will", "be", "taken", "out", "to", "process", ".", "The", "next", "batch", ...
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/support/Batcher.java#L388-L425
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/router/Router.java
Router.getRequestHeaderContentType
private String getRequestHeaderContentType() { String contentType = getRequestHeaderValue("Content-Type"); if (contentType != null) { // remove parameter (Content-Type := type "/" subtype *[";" parameter] ) int index = contentType.indexOf(';'); if (index > 0) contentType = contentType.substring(0, index); contentType = contentType.trim(); } return contentType; }
java
private String getRequestHeaderContentType() { String contentType = getRequestHeaderValue("Content-Type"); if (contentType != null) { // remove parameter (Content-Type := type "/" subtype *[";" parameter] ) int index = contentType.indexOf(';'); if (index > 0) contentType = contentType.substring(0, index); contentType = contentType.trim(); } return contentType; }
[ "private", "String", "getRequestHeaderContentType", "(", ")", "{", "String", "contentType", "=", "getRequestHeaderValue", "(", "\"Content-Type\"", ")", ";", "if", "(", "contentType", "!=", "null", ")", "{", "// remove parameter (Content-Type := type \"/\" subtype *[\";\" pa...
get Content-Type from URLConnection
[ "get", "Content", "-", "Type", "from", "URLConnection" ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/router/Router.java#L426-L436
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/router/Router.java
Router.setResponseLocation
private void setResponseLocation(URL url) { String location = url.getPath(); String query = url.getQuery(); if (query != null) { int startOfQuery = location.indexOf(query); if (startOfQuery > 0) { location = location.substring(0, startOfQuery); } } connection.getResHeader().add("Location", location); }
java
private void setResponseLocation(URL url) { String location = url.getPath(); String query = url.getQuery(); if (query != null) { int startOfQuery = location.indexOf(query); if (startOfQuery > 0) { location = location.substring(0, startOfQuery); } } connection.getResHeader().add("Location", location); }
[ "private", "void", "setResponseLocation", "(", "URL", "url", ")", "{", "String", "location", "=", "url", ".", "getPath", "(", ")", ";", "String", "query", "=", "url", ".", "getQuery", "(", ")", ";", "if", "(", "query", "!=", "null", ")", "{", "int", ...
Router+Handlers
[ "Router", "+", "Handlers" ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/router/Router.java#L779-L789
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/router/Router.java
Router.convertCBLQueryRowsToMaps
private static void convertCBLQueryRowsToMaps(Map<String, Object> allDocsResult) { List<Map<String, Object>> rowsAsMaps = new ArrayList<Map<String, Object>>(); List<QueryRow> rows = (List<QueryRow>) allDocsResult.get("rows"); if (rows != null) { for (QueryRow row : rows) { rowsAsMaps.add(row.asJSONDictionary()); } } allDocsResult.put("rows", rowsAsMaps); }
java
private static void convertCBLQueryRowsToMaps(Map<String, Object> allDocsResult) { List<Map<String, Object>> rowsAsMaps = new ArrayList<Map<String, Object>>(); List<QueryRow> rows = (List<QueryRow>) allDocsResult.get("rows"); if (rows != null) { for (QueryRow row : rows) { rowsAsMaps.add(row.asJSONDictionary()); } } allDocsResult.put("rows", rowsAsMaps); }
[ "private", "static", "void", "convertCBLQueryRowsToMaps", "(", "Map", "<", "String", ",", "Object", ">", "allDocsResult", ")", "{", "List", "<", "Map", "<", "String", ",", "Object", ">", ">", "rowsAsMaps", "=", "new", "ArrayList", "<", "Map", "<", "String"...
This is a hack to deal with the fact that there is currently no custom serializer for QueryRow. Instead, just convert everything to generic Maps.
[ "This", "is", "a", "hack", "to", "deal", "with", "the", "fact", "that", "there", "is", "currently", "no", "custom", "serializer", "for", "QueryRow", ".", "Instead", "just", "convert", "everything", "to", "generic", "Maps", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/router/Router.java#L1196-L1205
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/router/Router.java
Router.changed
@Override public void changed(Database.ChangeEvent event) { synchronized (changesLock) { if (isTimeout) return; lastChangesTimestamp = System.currentTimeMillis(); // Stop timeout timer: stopTimeout(); // In race condition, new doc or update doc is fired before starting to observe the // DatabaseChangeEvent, it allows to skip few document changes with /_changes REST API. // Make sure all document changes are tread by /_changes REST API. if (!filled) { filled = true; RevisionList changes = db.changesSince(changesSince, changesOptions, changesFilter, changesFilterParams); if (changes.size() > 0) { sendLongpollChanges(changes, changesSince); return; } } List<RevisionInternal> revs = new ArrayList<RevisionInternal>(); List<DocumentChange> changes = event.getChanges(); for (DocumentChange change : changes) { RevisionInternal rev = change.getAddedRevision(); if (rev == null) continue; String winningRevID = change.getWinningRevisionID(); if (!this.changesIncludesConflicts) { if (winningRevID == null) continue; // // this change doesn't affect the winning rev ID, no need to send it else if (!winningRevID.equals(rev.getRevID())) { // This rev made a _different_ rev current, so substitute that one. // We need to emit the current sequence # in the feed, so put it in the rev. // This isn't correct internally (this is an old rev so it has an older sequence) // but consumers of the _changes feed don't care about the internal state. RevisionInternal mRev = db.getDocument(rev.getDocID(), winningRevID, changesIncludesDocs); mRev.setSequence(rev.getSequence()); rev = mRev; } } if (!event.getSource().runFilter(changesFilter, changesFilterParams, rev)) continue; if (longpoll) { revs.add(rev); } else { Log.d(TAG, "Router: Sending continuous change chunk"); sendContinuousChange(rev); } timeoutLastSeqence = rev.getSequence(); } if (longpoll && revs.size() > 0) sendLongpollChanges(revs, changesSince); else // Restart timeout timer for continuous feed request: startTimeout(); } }
java
@Override public void changed(Database.ChangeEvent event) { synchronized (changesLock) { if (isTimeout) return; lastChangesTimestamp = System.currentTimeMillis(); // Stop timeout timer: stopTimeout(); // In race condition, new doc or update doc is fired before starting to observe the // DatabaseChangeEvent, it allows to skip few document changes with /_changes REST API. // Make sure all document changes are tread by /_changes REST API. if (!filled) { filled = true; RevisionList changes = db.changesSince(changesSince, changesOptions, changesFilter, changesFilterParams); if (changes.size() > 0) { sendLongpollChanges(changes, changesSince); return; } } List<RevisionInternal> revs = new ArrayList<RevisionInternal>(); List<DocumentChange> changes = event.getChanges(); for (DocumentChange change : changes) { RevisionInternal rev = change.getAddedRevision(); if (rev == null) continue; String winningRevID = change.getWinningRevisionID(); if (!this.changesIncludesConflicts) { if (winningRevID == null) continue; // // this change doesn't affect the winning rev ID, no need to send it else if (!winningRevID.equals(rev.getRevID())) { // This rev made a _different_ rev current, so substitute that one. // We need to emit the current sequence # in the feed, so put it in the rev. // This isn't correct internally (this is an old rev so it has an older sequence) // but consumers of the _changes feed don't care about the internal state. RevisionInternal mRev = db.getDocument(rev.getDocID(), winningRevID, changesIncludesDocs); mRev.setSequence(rev.getSequence()); rev = mRev; } } if (!event.getSource().runFilter(changesFilter, changesFilterParams, rev)) continue; if (longpoll) { revs.add(rev); } else { Log.d(TAG, "Router: Sending continuous change chunk"); sendContinuousChange(rev); } timeoutLastSeqence = rev.getSequence(); } if (longpoll && revs.size() > 0) sendLongpollChanges(revs, changesSince); else // Restart timeout timer for continuous feed request: startTimeout(); } }
[ "@", "Override", "public", "void", "changed", "(", "Database", ".", "ChangeEvent", "event", ")", "{", "synchronized", "(", "changesLock", ")", "{", "if", "(", "isTimeout", ")", "return", ";", "lastChangesTimestamp", "=", "System", ".", "currentTimeMillis", "("...
Implementation of ChangeListener
[ "Implementation", "of", "ChangeListener" ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/router/Router.java#L1728-L1792
train
couchbase/couchbase-lite-java-core
vendor/sqlite/src/java/com/couchbase/lite/internal/database/CancellationSignal.java
CancellationSignal.cancel
public void cancel() { final OnCancelListener listener; synchronized (this) { if (mIsCanceled) { return; } mIsCanceled = true; mCancelInProgress = true; listener = mOnCancelListener; } try { if (listener != null) { listener.onCancel(); } } finally { synchronized (this) { mCancelInProgress = false; notifyAll(); } } }
java
public void cancel() { final OnCancelListener listener; synchronized (this) { if (mIsCanceled) { return; } mIsCanceled = true; mCancelInProgress = true; listener = mOnCancelListener; } try { if (listener != null) { listener.onCancel(); } } finally { synchronized (this) { mCancelInProgress = false; notifyAll(); } } }
[ "public", "void", "cancel", "(", ")", "{", "final", "OnCancelListener", "listener", ";", "synchronized", "(", "this", ")", "{", "if", "(", "mIsCanceled", ")", "{", "return", ";", "}", "mIsCanceled", "=", "true", ";", "mCancelInProgress", "=", "true", ";", ...
Cancels the operation and signals the cancellation listener. If the operation has not yet started, then it will be canceled as soon as it does.
[ "Cancels", "the", "operation", "and", "signals", "the", "cancellation", "listener", ".", "If", "the", "operation", "has", "not", "yet", "started", "then", "it", "will", "be", "canceled", "as", "soon", "as", "it", "does", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/vendor/sqlite/src/java/com/couchbase/lite/internal/database/CancellationSignal.java#L64-L85
train
couchbase/couchbase-lite-java-core
vendor/sqlite/src/java/com/couchbase/lite/internal/database/CancellationSignal.java
CancellationSignal.setOnCancelListener
public void setOnCancelListener(OnCancelListener listener) { synchronized (this) { waitForCancelFinishedLocked(); if (mOnCancelListener == listener) { return; } mOnCancelListener = listener; if (!mIsCanceled || listener == null) { return; } } listener.onCancel(); }
java
public void setOnCancelListener(OnCancelListener listener) { synchronized (this) { waitForCancelFinishedLocked(); if (mOnCancelListener == listener) { return; } mOnCancelListener = listener; if (!mIsCanceled || listener == null) { return; } } listener.onCancel(); }
[ "public", "void", "setOnCancelListener", "(", "OnCancelListener", "listener", ")", "{", "synchronized", "(", "this", ")", "{", "waitForCancelFinishedLocked", "(", ")", ";", "if", "(", "mOnCancelListener", "==", "listener", ")", "{", "return", ";", "}", "mOnCance...
Sets the cancellation listener to be called when canceled. This method is intended to be used by the recipient of a cancellation signal such as a database or a content provider to handle cancellation requests while performing a long-running operation. This method is not intended to be used by applications themselves. If {@link CancellationSignal#cancel} has already been called, then the provided listener is invoked immediately. This method is guaranteed that the listener will not be called after it has been removed. @param listener The cancellation listener, or null to remove the current listener.
[ "Sets", "the", "cancellation", "listener", "to", "be", "called", "when", "canceled", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/vendor/sqlite/src/java/com/couchbase/lite/internal/database/CancellationSignal.java#L103-L116
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/LiveQuery.java
LiveQuery.waitForRows
@InterfaceAudience.Public public void waitForRows() throws CouchbaseLiteException { start(); while (true) { try { queryFuture.get(); break; } catch (InterruptedException e) { continue; } catch (Exception e) { lastError = e; throw new CouchbaseLiteException(e, Status.INTERNAL_SERVER_ERROR); } } }
java
@InterfaceAudience.Public public void waitForRows() throws CouchbaseLiteException { start(); while (true) { try { queryFuture.get(); break; } catch (InterruptedException e) { continue; } catch (Exception e) { lastError = e; throw new CouchbaseLiteException(e, Status.INTERNAL_SERVER_ERROR); } } }
[ "@", "InterfaceAudience", ".", "Public", "public", "void", "waitForRows", "(", ")", "throws", "CouchbaseLiteException", "{", "start", "(", ")", ";", "while", "(", "true", ")", "{", "try", "{", "queryFuture", ".", "get", "(", ")", ";", "break", ";", "}", ...
Blocks until the intial async query finishes. After this call either .rows or .error will be non-nil. TODO: It seems that implementation of waitForRows() is not correct. Should fix this!!! https://github.com/couchbase/couchbase-lite-java-core/issues/647
[ "Blocks", "until", "the", "intial", "async", "query", "finishes", ".", "After", "this", "call", "either", ".", "rows", "or", ".", "error", "will", "be", "non", "-", "nil", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/LiveQuery.java#L148-L163
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/LiveQuery.java
LiveQuery.getRows
@InterfaceAudience.Public public QueryEnumerator getRows() { start(); if (rows == null) { return null; } else { // Have to return a copy because the enumeration has to start at item #0 every time return new QueryEnumerator(rows); } }
java
@InterfaceAudience.Public public QueryEnumerator getRows() { start(); if (rows == null) { return null; } else { // Have to return a copy because the enumeration has to start at item #0 every time return new QueryEnumerator(rows); } }
[ "@", "InterfaceAudience", ".", "Public", "public", "QueryEnumerator", "getRows", "(", ")", "{", "start", "(", ")", ";", "if", "(", "rows", "==", "null", ")", "{", "return", "null", ";", "}", "else", "{", "// Have to return a copy because the enumeration has to s...
Gets the results of the Query. The value will be null until the initial Query completes.
[ "Gets", "the", "results", "of", "the", "Query", ".", "The", "value", "will", "be", "null", "until", "the", "initial", "Query", "completes", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/LiveQuery.java#L168-L178
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/Document.java
Document.getCurrentRevision
@InterfaceAudience.Public public SavedRevision getCurrentRevision() { if (currentRevision == null) currentRevision = getRevision(null); return currentRevision; }
java
@InterfaceAudience.Public public SavedRevision getCurrentRevision() { if (currentRevision == null) currentRevision = getRevision(null); return currentRevision; }
[ "@", "InterfaceAudience", ".", "Public", "public", "SavedRevision", "getCurrentRevision", "(", ")", "{", "if", "(", "currentRevision", "==", "null", ")", "currentRevision", "=", "getRevision", "(", "null", ")", ";", "return", "currentRevision", ";", "}" ]
Get the current revision
[ "Get", "the", "current", "revision" ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/Document.java#L203-L208
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/Document.java
Document.getProperties
@InterfaceAudience.Public public Map<String, Object> getProperties() { return getCurrentRevision() == null ? null : getCurrentRevision().getProperties(); }
java
@InterfaceAudience.Public public Map<String, Object> getProperties() { return getCurrentRevision() == null ? null : getCurrentRevision().getProperties(); }
[ "@", "InterfaceAudience", ".", "Public", "public", "Map", "<", "String", ",", "Object", ">", "getProperties", "(", ")", "{", "return", "getCurrentRevision", "(", ")", "==", "null", "?", "null", ":", "getCurrentRevision", "(", ")", ".", "getProperties", "(", ...
The contents of the current revision of the document. This is shorthand for self.currentRevision.properties. Any keys in the dictionary that begin with "_", such as "_id" and "_rev", contain CouchbaseLite metadata. @return contents of the current revision of the document. null if currentRevision is null
[ "The", "contents", "of", "the", "current", "revision", "of", "the", "document", ".", "This", "is", "shorthand", "for", "self", ".", "currentRevision", ".", "properties", ".", "Any", "keys", "in", "the", "dictionary", "that", "begin", "with", "_", "such", "...
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/Document.java#L254-L257
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/Document.java
Document.delete
@InterfaceAudience.Public public boolean delete() throws CouchbaseLiteException { return getCurrentRevision() == null ? false : getCurrentRevision().deleteDocument() != null; }
java
@InterfaceAudience.Public public boolean delete() throws CouchbaseLiteException { return getCurrentRevision() == null ? false : getCurrentRevision().deleteDocument() != null; }
[ "@", "InterfaceAudience", ".", "Public", "public", "boolean", "delete", "(", ")", "throws", "CouchbaseLiteException", "{", "return", "getCurrentRevision", "(", ")", "==", "null", "?", "false", ":", "getCurrentRevision", "(", ")", ".", "deleteDocument", "(", ")",...
Deletes this document by adding a deletion revision. This will be replicated to other databases. @return boolean to indicate whether deleted or not @throws CouchbaseLiteException
[ "Deletes", "this", "document", "by", "adding", "a", "deletion", "revision", ".", "This", "will", "be", "replicated", "to", "other", "databases", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/Document.java#L277-L280
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/Document.java
Document.purge
@InterfaceAudience.Public public void purge() throws CouchbaseLiteException { Map<String, List<String>> docsToRevs = new HashMap<String, List<String>>(); List<String> revs = new ArrayList<String>(); revs.add("*"); docsToRevs.put(documentId, revs); database.purgeRevisions(docsToRevs); database.removeDocumentFromCache(this); }
java
@InterfaceAudience.Public public void purge() throws CouchbaseLiteException { Map<String, List<String>> docsToRevs = new HashMap<String, List<String>>(); List<String> revs = new ArrayList<String>(); revs.add("*"); docsToRevs.put(documentId, revs); database.purgeRevisions(docsToRevs); database.removeDocumentFromCache(this); }
[ "@", "InterfaceAudience", ".", "Public", "public", "void", "purge", "(", ")", "throws", "CouchbaseLiteException", "{", "Map", "<", "String", ",", "List", "<", "String", ">", ">", "docsToRevs", "=", "new", "HashMap", "<", "String", ",", "List", "<", "String...
Purges this document from the database; this is more than deletion, it forgets entirely about it. The purge will NOT be replicated to other databases. @throws CouchbaseLiteException
[ "Purges", "this", "document", "from", "the", "database", ";", "this", "is", "more", "than", "deletion", "it", "forgets", "entirely", "about", "it", ".", "The", "purge", "will", "NOT", "be", "replicated", "to", "other", "databases", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/Document.java#L289-L297
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/Document.java
Document.getRevision
@InterfaceAudience.Public public SavedRevision getRevision(String revID) { if (revID != null && currentRevision != null && revID.equals(currentRevision.getId())) return currentRevision; RevisionInternal revisionInternal = database.getDocument(getId(), revID, true); return getRevisionFromRev(revisionInternal); }
java
@InterfaceAudience.Public public SavedRevision getRevision(String revID) { if (revID != null && currentRevision != null && revID.equals(currentRevision.getId())) return currentRevision; RevisionInternal revisionInternal = database.getDocument(getId(), revID, true); return getRevisionFromRev(revisionInternal); }
[ "@", "InterfaceAudience", ".", "Public", "public", "SavedRevision", "getRevision", "(", "String", "revID", ")", "{", "if", "(", "revID", "!=", "null", "&&", "currentRevision", "!=", "null", "&&", "revID", ".", "equals", "(", "currentRevision", ".", "getId", ...
The revision with the specified ID. @param revID the revision ID @return the SavedRevision object
[ "The", "revision", "with", "the", "specified", "ID", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/Document.java#L305-L311
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/Attachment.java
Attachment.getLength
@InterfaceAudience.Public public long getLength() { Number length = (Number) metadata.get("length"); if (length != null) { return length.longValue(); } else { return 0; } }
java
@InterfaceAudience.Public public long getLength() { Number length = (Number) metadata.get("length"); if (length != null) { return length.longValue(); } else { return 0; } }
[ "@", "InterfaceAudience", ".", "Public", "public", "long", "getLength", "(", ")", "{", "Number", "length", "=", "(", "Number", ")", "metadata", ".", "get", "(", "\"length\"", ")", ";", "if", "(", "length", "!=", "null", ")", "{", "return", "length", "....
Get the length in bytes of the contents.
[ "Get", "the", "length", "in", "bytes", "of", "the", "contents", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/Attachment.java#L154-L162
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/Attachment.java
Attachment.installAttachmentBodies
@InterfaceAudience.Private protected static Map<String, Object> installAttachmentBodies(Map<String, Object> attachments, Database database) throws CouchbaseLiteException { Map<String, Object> updatedAttachments = new HashMap<String, Object>(); for (String name : attachments.keySet()) { Object value = attachments.get(name); if (value instanceof Attachment) { Attachment attachment = (Attachment) value; Map<String, Object> metadataMutable = new HashMap<String, Object>(); metadataMutable.putAll(attachment.getMetadata()); InputStream body = attachment.getBodyIfNew(); if (body != null) { // Copy attachment body into the database's blob store: BlobStoreWriter writer; try { writer = blobStoreWriterForBody(body, database); } catch (Exception e) { throw new CouchbaseLiteException(e.getMessage(), Status.ATTACHMENT_ERROR); } metadataMutable.put("length", writer.getLength()); metadataMutable.put("digest", writer.mD5DigestString()); metadataMutable.put("follows", true); database.rememberAttachmentWriter(writer); } updatedAttachments.put(name, metadataMutable); } else if (value instanceof AttachmentInternal) { throw new IllegalArgumentException("AttachmentInternal objects not expected here. Could indicate a bug"); } else if (value != null) { updatedAttachments.put(name, value); } } return updatedAttachments; }
java
@InterfaceAudience.Private protected static Map<String, Object> installAttachmentBodies(Map<String, Object> attachments, Database database) throws CouchbaseLiteException { Map<String, Object> updatedAttachments = new HashMap<String, Object>(); for (String name : attachments.keySet()) { Object value = attachments.get(name); if (value instanceof Attachment) { Attachment attachment = (Attachment) value; Map<String, Object> metadataMutable = new HashMap<String, Object>(); metadataMutable.putAll(attachment.getMetadata()); InputStream body = attachment.getBodyIfNew(); if (body != null) { // Copy attachment body into the database's blob store: BlobStoreWriter writer; try { writer = blobStoreWriterForBody(body, database); } catch (Exception e) { throw new CouchbaseLiteException(e.getMessage(), Status.ATTACHMENT_ERROR); } metadataMutable.put("length", writer.getLength()); metadataMutable.put("digest", writer.mD5DigestString()); metadataMutable.put("follows", true); database.rememberAttachmentWriter(writer); } updatedAttachments.put(name, metadataMutable); } else if (value instanceof AttachmentInternal) { throw new IllegalArgumentException("AttachmentInternal objects not expected here. Could indicate a bug"); } else if (value != null) { updatedAttachments.put(name, value); } } return updatedAttachments; }
[ "@", "InterfaceAudience", ".", "Private", "protected", "static", "Map", "<", "String", ",", "Object", ">", "installAttachmentBodies", "(", "Map", "<", "String", ",", "Object", ">", "attachments", ",", "Database", "database", ")", "throws", "CouchbaseLiteException"...
Goes through an _attachments dictionary and replaces any values that are Attachment objects with proper JSON metadata dicts. It registers the attachment bodies with the blob store and sets the metadata 'getDigest' and 'follows' properties accordingly.
[ "Goes", "through", "an", "_attachments", "dictionary", "and", "replaces", "any", "values", "that", "are", "Attachment", "objects", "with", "proper", "JSON", "metadata", "dicts", ".", "It", "registers", "the", "attachment", "bodies", "with", "the", "blob", "store...
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/Attachment.java#L192-L225
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/replicator/PusherInternal.java
PusherInternal.initSupportExecutor
private void initSupportExecutor() { if (supportExecutor == null || supportExecutor.isShutdown()) { supportExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() { @Override public Thread newThread(Runnable r) { String maskedRemote = URLUtils.sanitizeURL(remote); return new Thread(r, "CBLPusherSupportExecutor-" + maskedRemote); } }); } }
java
private void initSupportExecutor() { if (supportExecutor == null || supportExecutor.isShutdown()) { supportExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() { @Override public Thread newThread(Runnable r) { String maskedRemote = URLUtils.sanitizeURL(remote); return new Thread(r, "CBLPusherSupportExecutor-" + maskedRemote); } }); } }
[ "private", "void", "initSupportExecutor", "(", ")", "{", "if", "(", "supportExecutor", "==", "null", "||", "supportExecutor", ".", "isShutdown", "(", ")", ")", "{", "supportExecutor", "=", "Executors", ".", "newSingleThreadExecutor", "(", "new", "ThreadFactory", ...
create single thread supportExecutor for push replication
[ "create", "single", "thread", "supportExecutor", "for", "push", "replication" ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/replicator/PusherInternal.java#L126-L136
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/Revision.java
Revision.getAttachmentNames
@InterfaceAudience.Public public List<String> getAttachmentNames() { Map<String, Object> attachmentMetadata = getAttachmentMetadata(); if (attachmentMetadata == null) { return new ArrayList<String>(); } return new ArrayList<String>(attachmentMetadata.keySet()); }
java
@InterfaceAudience.Public public List<String> getAttachmentNames() { Map<String, Object> attachmentMetadata = getAttachmentMetadata(); if (attachmentMetadata == null) { return new ArrayList<String>(); } return new ArrayList<String>(attachmentMetadata.keySet()); }
[ "@", "InterfaceAudience", ".", "Public", "public", "List", "<", "String", ">", "getAttachmentNames", "(", ")", "{", "Map", "<", "String", ",", "Object", ">", "attachmentMetadata", "=", "getAttachmentMetadata", "(", ")", ";", "if", "(", "attachmentMetadata", "=...
The names of all attachments
[ "The", "names", "of", "all", "attachments" ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/Revision.java#L133-L140
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/Revision.java
Revision.getAttachments
@InterfaceAudience.Public public List<Attachment> getAttachments() { Map<String, Object> attachmentMetadata = getAttachmentMetadata(); if (attachmentMetadata == null) { return new ArrayList<Attachment>(); } List<Attachment> result = new ArrayList<Attachment>(attachmentMetadata.size()); for (Map.Entry<String, Object> entry : attachmentMetadata.entrySet()) { Attachment attachment = toAttachment(entry.getKey(), entry.getValue()); if (attachment != null) { result.add(attachment); } } return result; }
java
@InterfaceAudience.Public public List<Attachment> getAttachments() { Map<String, Object> attachmentMetadata = getAttachmentMetadata(); if (attachmentMetadata == null) { return new ArrayList<Attachment>(); } List<Attachment> result = new ArrayList<Attachment>(attachmentMetadata.size()); for (Map.Entry<String, Object> entry : attachmentMetadata.entrySet()) { Attachment attachment = toAttachment(entry.getKey(), entry.getValue()); if (attachment != null) { result.add(attachment); } } return result; }
[ "@", "InterfaceAudience", ".", "Public", "public", "List", "<", "Attachment", ">", "getAttachments", "(", ")", "{", "Map", "<", "String", ",", "Object", ">", "attachmentMetadata", "=", "getAttachmentMetadata", "(", ")", ";", "if", "(", "attachmentMetadata", "=...
All attachments, as Attachment objects.
[ "All", "attachments", "as", "Attachment", "objects", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/Revision.java#L145-L159
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/UnsavedRevision.java
UnsavedRevision.setUserProperties
@InterfaceAudience.Public public void setUserProperties(Map<String, Object> userProperties) { Map<String, Object> newProps = new HashMap<String, Object>(); newProps.putAll(userProperties); for (String key : properties.keySet()) { if (key.startsWith("_")) { newProps.put(key, properties.get(key)); // Preserve metadata properties } } properties = newProps; }
java
@InterfaceAudience.Public public void setUserProperties(Map<String, Object> userProperties) { Map<String, Object> newProps = new HashMap<String, Object>(); newProps.putAll(userProperties); for (String key : properties.keySet()) { if (key.startsWith("_")) { newProps.put(key, properties.get(key)); // Preserve metadata properties } } properties = newProps; }
[ "@", "InterfaceAudience", ".", "Public", "public", "void", "setUserProperties", "(", "Map", "<", "String", ",", "Object", ">", "userProperties", ")", "{", "Map", "<", "String", ",", "Object", ">", "newProps", "=", "new", "HashMap", "<", "String", ",", "Obj...
Sets the userProperties of the Revision. Set replaces all properties except for those with keys prefixed with '_'.
[ "Sets", "the", "userProperties", "of", "the", "Revision", ".", "Set", "replaces", "all", "properties", "except", "for", "those", "with", "keys", "prefixed", "with", "_", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/UnsavedRevision.java#L148-L158
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/UnsavedRevision.java
UnsavedRevision.addAttachment
@InterfaceAudience.Private protected void addAttachment(Attachment attachment, String name) { Map<String, Object> attachments = (Map<String, Object>) properties.get("_attachments"); if (attachments == null) { attachments = new HashMap<String, Object>(); } attachments.put(name, attachment); properties.put("_attachments", attachments); if (attachment != null) { attachment.setName(name); } }
java
@InterfaceAudience.Private protected void addAttachment(Attachment attachment, String name) { Map<String, Object> attachments = (Map<String, Object>) properties.get("_attachments"); if (attachments == null) { attachments = new HashMap<String, Object>(); } attachments.put(name, attachment); properties.put("_attachments", attachments); if (attachment != null) { attachment.setName(name); } }
[ "@", "InterfaceAudience", ".", "Private", "protected", "void", "addAttachment", "(", "Attachment", "attachment", ",", "String", "name", ")", "{", "Map", "<", "String", ",", "Object", ">", "attachments", "=", "(", "Map", "<", "String", ",", "Object", ">", "...
Creates or updates an attachment. The attachment data will be written to the database when the revision is saved. @param attachment A newly-created Attachment (not yet associated with any revision) @param name The attachment name.
[ "Creates", "or", "updates", "an", "attachment", ".", "The", "attachment", "data", "will", "be", "written", "to", "the", "database", "when", "the", "revision", "is", "saved", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/UnsavedRevision.java#L237-L248
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/replicator/PullerInternal.java
PullerInternal.beginReplicating
protected void beginReplicating() { Log.v(TAG, "submit startReplicating()"); executor.submit(new Runnable() { @Override public void run() { if (isRunning()) { Log.v(TAG, "start startReplicating()"); initPendingSequences(); initDownloadsToInsert(); startChangeTracker(); } // start replicator ... } }); }
java
protected void beginReplicating() { Log.v(TAG, "submit startReplicating()"); executor.submit(new Runnable() { @Override public void run() { if (isRunning()) { Log.v(TAG, "start startReplicating()"); initPendingSequences(); initDownloadsToInsert(); startChangeTracker(); } // start replicator ... } }); }
[ "protected", "void", "beginReplicating", "(", ")", "{", "Log", ".", "v", "(", "TAG", ",", "\"submit startReplicating()\"", ")", ";", "executor", ".", "submit", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{"...
Actual work of starting the replication process.
[ "Actual", "work", "of", "starting", "the", "replication", "process", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/replicator/PullerInternal.java#L110-L124
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/replicator/PullerInternal.java
PullerInternal.processInbox
@Override @InterfaceAudience.Private protected void processInbox(RevisionList inbox) { Log.d(TAG, "processInbox called"); if (db == null || !db.isOpen()) { Log.w(Log.TAG_SYNC, "%s: Database is null or closed. Unable to continue. db name is %s.", this, db.getName()); return; } if (canBulkGet == null) { canBulkGet = serverIsSyncGatewayVersion("0.81"); } // Ask the local database which of the revs are not known to it: String lastInboxSequence = ((PulledRevision) inbox.get(inbox.size() - 1)).getRemoteSequenceID(); int numRevisionsRemoved = 0; try { // findMissingRevisions is the local equivalent of _revs_diff. it looks at the // array of revisions in "inbox" and removes the ones that already exist. // So whatever's left in 'inbox' // afterwards are the revisions that need to be downloaded. numRevisionsRemoved = db.findMissingRevisions(inbox); } catch (SQLException e) { Log.e(TAG, String.format(Locale.ENGLISH, "%s failed to look up local revs", this), e); inbox = null; } //introducing this to java version since inbox may now be null everywhere int inboxCount = 0; if (inbox != null) { inboxCount = inbox.size(); } if (numRevisionsRemoved > 0) { Log.v(TAG, "%s: processInbox() setting changesCount to: %s", this, getChangesCount().get() - numRevisionsRemoved); // May decrease the changesCount, to account for the revisions we just found out we don't need to get. addToChangesCount(-1 * numRevisionsRemoved); } if (inboxCount == 0) { // Nothing to do. Just bump the lastSequence. Log.d(TAG, "%s no new remote revisions to fetch. add lastInboxSequence (%s) to pendingSequences (%s)", this, lastInboxSequence, pendingSequences); long seq = pendingSequences.addValue(lastInboxSequence); pendingSequences.removeSequence(seq); setLastSequence(pendingSequences.getCheckpointedValue()); pauseOrResume(); return; } Log.v(TAG, "%s: fetching %s remote revisions...", this, inboxCount); // Dump the revs into the queue of revs to pull from the remote db: for (int i = 0; i < inbox.size(); i++) { PulledRevision rev = (PulledRevision) inbox.get(i); if (canBulkGet || (rev.getGeneration() == 1 && !rev.isDeleted() && !rev.isConflicted())) { bulkRevsToPull.add(rev); } else { queueRemoteRevision(rev); } rev.setSequence(pendingSequences.addValue(rev.getRemoteSequenceID())); } pullRemoteRevisions(); pauseOrResume(); }
java
@Override @InterfaceAudience.Private protected void processInbox(RevisionList inbox) { Log.d(TAG, "processInbox called"); if (db == null || !db.isOpen()) { Log.w(Log.TAG_SYNC, "%s: Database is null or closed. Unable to continue. db name is %s.", this, db.getName()); return; } if (canBulkGet == null) { canBulkGet = serverIsSyncGatewayVersion("0.81"); } // Ask the local database which of the revs are not known to it: String lastInboxSequence = ((PulledRevision) inbox.get(inbox.size() - 1)).getRemoteSequenceID(); int numRevisionsRemoved = 0; try { // findMissingRevisions is the local equivalent of _revs_diff. it looks at the // array of revisions in "inbox" and removes the ones that already exist. // So whatever's left in 'inbox' // afterwards are the revisions that need to be downloaded. numRevisionsRemoved = db.findMissingRevisions(inbox); } catch (SQLException e) { Log.e(TAG, String.format(Locale.ENGLISH, "%s failed to look up local revs", this), e); inbox = null; } //introducing this to java version since inbox may now be null everywhere int inboxCount = 0; if (inbox != null) { inboxCount = inbox.size(); } if (numRevisionsRemoved > 0) { Log.v(TAG, "%s: processInbox() setting changesCount to: %s", this, getChangesCount().get() - numRevisionsRemoved); // May decrease the changesCount, to account for the revisions we just found out we don't need to get. addToChangesCount(-1 * numRevisionsRemoved); } if (inboxCount == 0) { // Nothing to do. Just bump the lastSequence. Log.d(TAG, "%s no new remote revisions to fetch. add lastInboxSequence (%s) to pendingSequences (%s)", this, lastInboxSequence, pendingSequences); long seq = pendingSequences.addValue(lastInboxSequence); pendingSequences.removeSequence(seq); setLastSequence(pendingSequences.getCheckpointedValue()); pauseOrResume(); return; } Log.v(TAG, "%s: fetching %s remote revisions...", this, inboxCount); // Dump the revs into the queue of revs to pull from the remote db: for (int i = 0; i < inbox.size(); i++) { PulledRevision rev = (PulledRevision) inbox.get(i); if (canBulkGet || (rev.getGeneration() == 1 && !rev.isDeleted() && !rev.isConflicted())) { bulkRevsToPull.add(rev); } else { queueRemoteRevision(rev); } rev.setSequence(pendingSequences.addValue(rev.getRemoteSequenceID())); } pullRemoteRevisions(); pauseOrResume(); }
[ "@", "Override", "@", "InterfaceAudience", ".", "Private", "protected", "void", "processInbox", "(", "RevisionList", "inbox", ")", "{", "Log", ".", "d", "(", "TAG", ",", "\"processInbox called\"", ")", ";", "if", "(", "db", "==", "null", "||", "!", "db", ...
Process a bunch of remote revisions from the _changes feed at once
[ "Process", "a", "bunch", "of", "remote", "revisions", "from", "the", "_changes", "feed", "at", "once" ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/replicator/PullerInternal.java#L194-L262
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/replicator/PullerInternal.java
PullerInternal.pullBulkRevisions
protected void pullBulkRevisions(List<RevisionInternal> bulkRevs) { int nRevs = bulkRevs.size(); if (nRevs == 0) { return; } Log.d(TAG, "%s bulk-fetching %d remote revisions...", this, nRevs); Log.d(TAG, "%s bulk-fetching remote revisions: %s", this, bulkRevs); if (!canBulkGet) { pullBulkWithAllDocs(bulkRevs); return; } Log.v(TAG, "%s: POST _bulk_get", this); final List<RevisionInternal> remainingRevs = new ArrayList<RevisionInternal>(bulkRevs); ++httpConnectionCount; final RemoteBulkDownloaderRequest downloader; try { downloader = new RemoteBulkDownloaderRequest( clientFactory, remote, true, bulkRevs, db, this.requestHeaders, new RemoteBulkDownloaderRequest.BulkDownloaderDocument() { public void onDocument(Map<String, Object> props, long size) { // Got a revision! // Find the matching revision in 'remainingRevs' and get its sequence: RevisionInternal rev; if (props.get("_id") != null) { rev = new RevisionInternal(props, size); } else { rev = new RevisionInternal((String) props.get("id"), (String) props.get("rev"), false); } int pos = remainingRevs.indexOf(rev); if (pos > -1) { rev.setSequence(remainingRevs.get(pos).getSequence()); remainingRevs.remove(pos); } else { Log.w(TAG, "%s : Received unexpected rev rev", this); } if (props.get("_id") != null) { // Add to batcher ... eventually it will be fed to -insertRevisions:. queueDownloadedRevision(rev); } else { Status status = statusFromBulkDocsResponseItem(props); Throwable err = new CouchbaseLiteException(status); revisionFailed(rev, err); } } }, new RemoteRequestCompletion() { public void onCompletion(RemoteRequest remoteRequest, Response httpResponse, Object result, Throwable e) { // The entire _bulk_get is finished: if (e != null) { setError(e); completedChangesCount.addAndGet(remainingRevs.size()); } --httpConnectionCount; // Start another task if there are still revisions waiting to be pulled: pullRemoteRevisions(); if (cancellables != null && cancellables.values() != null && remoteRequest != null) cancellables.values().remove(remoteRequest); } } ); } catch (Exception e) { Log.e(TAG, "%s: pullBulkRevisions Exception: %s", this, e); return; } downloader.setAuthenticator(getAuthenticator()); // set compressed request - gzip downloader.setCompressedRequest(canSendCompressedRequests()); synchronized (remoteRequestExecutor) { if (!remoteRequestExecutor.isShutdown()) { Future future = remoteRequestExecutor.submit(downloader); pendingFutures.add(future); cancellables.put(future, downloader); } } }
java
protected void pullBulkRevisions(List<RevisionInternal> bulkRevs) { int nRevs = bulkRevs.size(); if (nRevs == 0) { return; } Log.d(TAG, "%s bulk-fetching %d remote revisions...", this, nRevs); Log.d(TAG, "%s bulk-fetching remote revisions: %s", this, bulkRevs); if (!canBulkGet) { pullBulkWithAllDocs(bulkRevs); return; } Log.v(TAG, "%s: POST _bulk_get", this); final List<RevisionInternal> remainingRevs = new ArrayList<RevisionInternal>(bulkRevs); ++httpConnectionCount; final RemoteBulkDownloaderRequest downloader; try { downloader = new RemoteBulkDownloaderRequest( clientFactory, remote, true, bulkRevs, db, this.requestHeaders, new RemoteBulkDownloaderRequest.BulkDownloaderDocument() { public void onDocument(Map<String, Object> props, long size) { // Got a revision! // Find the matching revision in 'remainingRevs' and get its sequence: RevisionInternal rev; if (props.get("_id") != null) { rev = new RevisionInternal(props, size); } else { rev = new RevisionInternal((String) props.get("id"), (String) props.get("rev"), false); } int pos = remainingRevs.indexOf(rev); if (pos > -1) { rev.setSequence(remainingRevs.get(pos).getSequence()); remainingRevs.remove(pos); } else { Log.w(TAG, "%s : Received unexpected rev rev", this); } if (props.get("_id") != null) { // Add to batcher ... eventually it will be fed to -insertRevisions:. queueDownloadedRevision(rev); } else { Status status = statusFromBulkDocsResponseItem(props); Throwable err = new CouchbaseLiteException(status); revisionFailed(rev, err); } } }, new RemoteRequestCompletion() { public void onCompletion(RemoteRequest remoteRequest, Response httpResponse, Object result, Throwable e) { // The entire _bulk_get is finished: if (e != null) { setError(e); completedChangesCount.addAndGet(remainingRevs.size()); } --httpConnectionCount; // Start another task if there are still revisions waiting to be pulled: pullRemoteRevisions(); if (cancellables != null && cancellables.values() != null && remoteRequest != null) cancellables.values().remove(remoteRequest); } } ); } catch (Exception e) { Log.e(TAG, "%s: pullBulkRevisions Exception: %s", this, e); return; } downloader.setAuthenticator(getAuthenticator()); // set compressed request - gzip downloader.setCompressedRequest(canSendCompressedRequests()); synchronized (remoteRequestExecutor) { if (!remoteRequestExecutor.isShutdown()) { Future future = remoteRequestExecutor.submit(downloader); pendingFutures.add(future); cancellables.put(future, downloader); } } }
[ "protected", "void", "pullBulkRevisions", "(", "List", "<", "RevisionInternal", ">", "bulkRevs", ")", "{", "int", "nRevs", "=", "bulkRevs", ".", "size", "(", ")", ";", "if", "(", "nRevs", "==", "0", ")", "{", "return", ";", "}", "Log", ".", "d", "(",...
Get a bunch of revisions in one bulk request. Will use _bulk_get if possible.
[ "Get", "a", "bunch", "of", "revisions", "in", "one", "bulk", "request", ".", "Will", "use", "_bulk_get", "if", "possible", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/replicator/PullerInternal.java#L314-L404
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/replicator/PullerInternal.java
PullerInternal.queueDownloadedRevision
private void queueDownloadedRevision(RevisionInternal rev) { if (revisionBodyTransformationBlock != null) { // Add 'file' properties to attachments pointing to their bodies: for (Map.Entry<String, Map<String, Object>> entry : ( (Map<String, Map<String, Object>>) rev.getProperties().get("_attachments")).entrySet()) { String name = entry.getKey(); Map<String, Object> attachment = entry.getValue(); attachment.remove("file"); if (attachment.get("follows") != null && attachment.get("data") == null) { String filePath = db.fileForAttachmentDict(attachment).getPath(); if (filePath != null) attachment.put("file", filePath); } } RevisionInternal xformed = transformRevision(rev); if (xformed == null) { Log.v(TAG, "%s: Transformer rejected revision %s", this, rev); pendingSequences.removeSequence(rev.getSequence()); lastSequence = pendingSequences.getCheckpointedValue(); pauseOrResume(); return; } rev = xformed; // Clean up afterwards Map<String, Map<String, Object>> attachments = (Map<String, Map<String, Object>>) rev.getProperties().get("_attachments"); for (Map.Entry<String, Map<String, Object>> entry : attachments.entrySet()) { Map<String, Object> attachment = entry.getValue(); attachment.remove("file"); } } // NOTE: should not/not necessary to call Body.compact() // new RevisionInternal(Map<string, Object>) creates Body instance only // with `object`. Serializing object to json causes two unnecessary // JSON serializations. if (rev.getBody() != null) queuedMemorySize.addAndGet(rev.getBody().getSize()); downloadsToInsert.queueObject(rev); // if queue memory size is more than maximum, force flush the queue. if (queuedMemorySize.get() > MAX_QUEUE_MEMORY_SIZE) { Log.d(TAG, "Flushing queued memory size at: " + queuedMemorySize); downloadsToInsert.flushAllAndWait(); } }
java
private void queueDownloadedRevision(RevisionInternal rev) { if (revisionBodyTransformationBlock != null) { // Add 'file' properties to attachments pointing to their bodies: for (Map.Entry<String, Map<String, Object>> entry : ( (Map<String, Map<String, Object>>) rev.getProperties().get("_attachments")).entrySet()) { String name = entry.getKey(); Map<String, Object> attachment = entry.getValue(); attachment.remove("file"); if (attachment.get("follows") != null && attachment.get("data") == null) { String filePath = db.fileForAttachmentDict(attachment).getPath(); if (filePath != null) attachment.put("file", filePath); } } RevisionInternal xformed = transformRevision(rev); if (xformed == null) { Log.v(TAG, "%s: Transformer rejected revision %s", this, rev); pendingSequences.removeSequence(rev.getSequence()); lastSequence = pendingSequences.getCheckpointedValue(); pauseOrResume(); return; } rev = xformed; // Clean up afterwards Map<String, Map<String, Object>> attachments = (Map<String, Map<String, Object>>) rev.getProperties().get("_attachments"); for (Map.Entry<String, Map<String, Object>> entry : attachments.entrySet()) { Map<String, Object> attachment = entry.getValue(); attachment.remove("file"); } } // NOTE: should not/not necessary to call Body.compact() // new RevisionInternal(Map<string, Object>) creates Body instance only // with `object`. Serializing object to json causes two unnecessary // JSON serializations. if (rev.getBody() != null) queuedMemorySize.addAndGet(rev.getBody().getSize()); downloadsToInsert.queueObject(rev); // if queue memory size is more than maximum, force flush the queue. if (queuedMemorySize.get() > MAX_QUEUE_MEMORY_SIZE) { Log.d(TAG, "Flushing queued memory size at: " + queuedMemorySize); downloadsToInsert.flushAllAndWait(); } }
[ "private", "void", "queueDownloadedRevision", "(", "RevisionInternal", "rev", ")", "{", "if", "(", "revisionBodyTransformationBlock", "!=", "null", ")", "{", "// Add 'file' properties to attachments pointing to their bodies:", "for", "(", "Map", ".", "Entry", "<", "String...
This invokes the tranformation block if one is installed and queues the resulting CBL_Revision
[ "This", "invokes", "the", "tranformation", "block", "if", "one", "is", "installed", "and", "queues", "the", "resulting", "CBL_Revision" ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/replicator/PullerInternal.java#L433-L484
train
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/replicator/PullerInternal.java
PullerInternal.pullBulkWithAllDocs
protected void pullBulkWithAllDocs(final List<RevisionInternal> bulkRevs) { // http://wiki.apache.org/couchdb/HTTP_Bulk_Document_API ++httpConnectionCount; final RevisionList remainingRevs = new RevisionList(bulkRevs); Collection<String> keys = CollectionUtils.transform(bulkRevs, new CollectionUtils.Functor<RevisionInternal, String>() { public String invoke(RevisionInternal rev) { return rev.getDocID(); } } ); Map<String, Object> body = new HashMap<String, Object>(); body.put("keys", keys); Future future = sendAsyncRequest("POST", "_all_docs?include_docs=true", body, new RemoteRequestCompletion() { public void onCompletion(RemoteRequest remoteRequest, Response httpResponse, Object result, Throwable e) { Map<String, Object> res = (Map<String, Object>) result; if (e != null) { setError(e); // TODO: There is a known bug caused by the line below, which is // TODO: causing testMockSinglePullCouchDb to fail when running on a Nexus5 device. // TODO: (the batching behavior is different in that case) // TODO: See https://github.com/couchbase/couchbase-lite-java-core/issues/271 // completedChangesCount.addAndGet(bulkRevs.size()); } else { // Process the resulting rows' documents. // We only add a document if it doesn't have attachments, and if its // revID matches the one we asked for. List<Map<String, Object>> rows = (List<Map<String, Object>>) res.get("rows"); Log.v(TAG, "%s checking %d bulk-fetched remote revisions", this, rows.size()); for (Map<String, Object> row : rows) { Map<String, Object> doc = (Map<String, Object>) row.get("doc"); if (doc != null && doc.get("_attachments") == null) { RevisionInternal rev = new RevisionInternal(doc); RevisionInternal removedRev = remainingRevs.removeAndReturnRev(rev); if (removedRev != null) { rev.setSequence(removedRev.getSequence()); queueDownloadedRevision(rev); } } else { Status status = statusFromBulkDocsResponseItem(row); if (status.isError() && row.containsKey("key") && row.get("key") != null) { RevisionInternal rev = remainingRevs.revWithDocId((String) row.get("key")); if (rev != null) { remainingRevs.remove(rev); revisionFailed(rev, new CouchbaseLiteException(status)); } } } } } // Any leftover revisions that didn't get matched will be fetched individually: if (remainingRevs.size() > 0) { Log.v(TAG, "%s bulk-fetch didn't work for %d of %d revs; getting individually", this, remainingRevs.size(), bulkRevs.size()); for (RevisionInternal rev : remainingRevs) { queueRemoteRevision(rev); } pullRemoteRevisions(); } --httpConnectionCount; // Start another task if there are still revisions waiting to be pulled: pullRemoteRevisions(); } }); pendingFutures.add(future); }
java
protected void pullBulkWithAllDocs(final List<RevisionInternal> bulkRevs) { // http://wiki.apache.org/couchdb/HTTP_Bulk_Document_API ++httpConnectionCount; final RevisionList remainingRevs = new RevisionList(bulkRevs); Collection<String> keys = CollectionUtils.transform(bulkRevs, new CollectionUtils.Functor<RevisionInternal, String>() { public String invoke(RevisionInternal rev) { return rev.getDocID(); } } ); Map<String, Object> body = new HashMap<String, Object>(); body.put("keys", keys); Future future = sendAsyncRequest("POST", "_all_docs?include_docs=true", body, new RemoteRequestCompletion() { public void onCompletion(RemoteRequest remoteRequest, Response httpResponse, Object result, Throwable e) { Map<String, Object> res = (Map<String, Object>) result; if (e != null) { setError(e); // TODO: There is a known bug caused by the line below, which is // TODO: causing testMockSinglePullCouchDb to fail when running on a Nexus5 device. // TODO: (the batching behavior is different in that case) // TODO: See https://github.com/couchbase/couchbase-lite-java-core/issues/271 // completedChangesCount.addAndGet(bulkRevs.size()); } else { // Process the resulting rows' documents. // We only add a document if it doesn't have attachments, and if its // revID matches the one we asked for. List<Map<String, Object>> rows = (List<Map<String, Object>>) res.get("rows"); Log.v(TAG, "%s checking %d bulk-fetched remote revisions", this, rows.size()); for (Map<String, Object> row : rows) { Map<String, Object> doc = (Map<String, Object>) row.get("doc"); if (doc != null && doc.get("_attachments") == null) { RevisionInternal rev = new RevisionInternal(doc); RevisionInternal removedRev = remainingRevs.removeAndReturnRev(rev); if (removedRev != null) { rev.setSequence(removedRev.getSequence()); queueDownloadedRevision(rev); } } else { Status status = statusFromBulkDocsResponseItem(row); if (status.isError() && row.containsKey("key") && row.get("key") != null) { RevisionInternal rev = remainingRevs.revWithDocId((String) row.get("key")); if (rev != null) { remainingRevs.remove(rev); revisionFailed(rev, new CouchbaseLiteException(status)); } } } } } // Any leftover revisions that didn't get matched will be fetched individually: if (remainingRevs.size() > 0) { Log.v(TAG, "%s bulk-fetch didn't work for %d of %d revs; getting individually", this, remainingRevs.size(), bulkRevs.size()); for (RevisionInternal rev : remainingRevs) { queueRemoteRevision(rev); } pullRemoteRevisions(); } --httpConnectionCount; // Start another task if there are still revisions waiting to be pulled: pullRemoteRevisions(); } }); pendingFutures.add(future); }
[ "protected", "void", "pullBulkWithAllDocs", "(", "final", "List", "<", "RevisionInternal", ">", "bulkRevs", ")", "{", "// http://wiki.apache.org/couchdb/HTTP_Bulk_Document_API", "++", "httpConnectionCount", ";", "final", "RevisionList", "remainingRevs", "=", "new", "Revisio...
This is compatible with CouchDB, but it only works for revs of generation 1 without attachments.
[ "This", "is", "compatible", "with", "CouchDB", "but", "it", "only", "works", "for", "revs", "of", "generation", "1", "without", "attachments", "." ]
3b275642e2d2f231fd155ad9def9c5e9eff3118e
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/replicator/PullerInternal.java#L489-L570
train