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
Stratio/stratio-cassandra
src/java/org/apache/cassandra/utils/concurrent/Refs.java
Refs.releaseIfHolds
public boolean releaseIfHolds(T referenced) { Ref ref = references.remove(referenced); if (ref != null) ref.release(); return ref != null; }
java
public boolean releaseIfHolds(T referenced) { Ref ref = references.remove(referenced); if (ref != null) ref.release(); return ref != null; }
[ "public", "boolean", "releaseIfHolds", "(", "T", "referenced", ")", "{", "Ref", "ref", "=", "references", ".", "remove", "(", "referenced", ")", ";", "if", "(", "ref", "!=", "null", ")", "ref", ".", "release", "(", ")", ";", "return", "ref", "!=", "n...
Release the retained Ref to the provided object, if held, return false otherwise @param referenced the object we retain a Ref to @return return true if we held a reference to the object, and false otherwise
[ "Release", "the", "retained", "Ref", "to", "the", "provided", "object", "if", "held", "return", "false", "otherwise" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/utils/concurrent/Refs.java#L83-L89
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/utils/concurrent/Refs.java
Refs.release
public void release(Collection<T> release) { List<Ref<T>> refs = new ArrayList<>(); List<T> notPresent = null; for (T obj : release) { Ref<T> ref = references.remove(obj); if (ref == null) { if (notPresent == null) notPresent = new ArrayList<>(); notPresent.add(obj); } else { refs.add(ref); } } IllegalStateException notPresentFail = null; if (notPresent != null) { notPresentFail = new IllegalStateException("Could not release references to " + notPresent + " as references to these objects were not held"); notPresentFail.fillInStackTrace(); } try { release(refs); } catch (Throwable t) { if (notPresentFail != null) t.addSuppressed(notPresentFail); } if (notPresentFail != null) throw notPresentFail; }
java
public void release(Collection<T> release) { List<Ref<T>> refs = new ArrayList<>(); List<T> notPresent = null; for (T obj : release) { Ref<T> ref = references.remove(obj); if (ref == null) { if (notPresent == null) notPresent = new ArrayList<>(); notPresent.add(obj); } else { refs.add(ref); } } IllegalStateException notPresentFail = null; if (notPresent != null) { notPresentFail = new IllegalStateException("Could not release references to " + notPresent + " as references to these objects were not held"); notPresentFail.fillInStackTrace(); } try { release(refs); } catch (Throwable t) { if (notPresentFail != null) t.addSuppressed(notPresentFail); } if (notPresentFail != null) throw notPresentFail; }
[ "public", "void", "release", "(", "Collection", "<", "T", ">", "release", ")", "{", "List", "<", "Ref", "<", "T", ">>", "refs", "=", "new", "ArrayList", "<>", "(", ")", ";", "List", "<", "T", ">", "notPresent", "=", "null", ";", "for", "(", "T", ...
Release a retained Ref to all of the provided objects; if any is not held, an exception will be thrown @param release
[ "Release", "a", "retained", "Ref", "to", "all", "of", "the", "provided", "objects", ";", "if", "any", "is", "not", "held", "an", "exception", "will", "be", "thrown" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/utils/concurrent/Refs.java#L95-L132
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/utils/concurrent/Refs.java
Refs.tryRef
public boolean tryRef(T t) { Ref<T> ref = t.tryRef(); if (ref == null) return false; ref = references.put(t, ref); if (ref != null) ref.release(); // release dup return true; }
java
public boolean tryRef(T t) { Ref<T> ref = t.tryRef(); if (ref == null) return false; ref = references.put(t, ref); if (ref != null) ref.release(); // release dup return true; }
[ "public", "boolean", "tryRef", "(", "T", "t", ")", "{", "Ref", "<", "T", ">", "ref", "=", "t", ".", "tryRef", "(", ")", ";", "if", "(", "ref", "==", "null", ")", "return", "false", ";", "ref", "=", "references", ".", "put", "(", "t", ",", "re...
Attempt to take a reference to the provided object; if it has already been released, null will be returned @param t object to acquire a reference to @return true iff success
[ "Attempt", "to", "take", "a", "reference", "to", "the", "provided", "object", ";", "if", "it", "has", "already", "been", "released", "null", "will", "be", "returned" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/utils/concurrent/Refs.java#L139-L148
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/utils/concurrent/Refs.java
Refs.addAll
public Refs<T> addAll(Refs<T> add) { List<Ref<T>> overlap = new ArrayList<>(); for (Map.Entry<T, Ref<T>> e : add.references.entrySet()) { if (this.references.containsKey(e.getKey())) overlap.add(e.getValue()); else this.references.put(e.getKey(), e.getValue()); } add.references.clear(); release(overlap); return this; }
java
public Refs<T> addAll(Refs<T> add) { List<Ref<T>> overlap = new ArrayList<>(); for (Map.Entry<T, Ref<T>> e : add.references.entrySet()) { if (this.references.containsKey(e.getKey())) overlap.add(e.getValue()); else this.references.put(e.getKey(), e.getValue()); } add.references.clear(); release(overlap); return this; }
[ "public", "Refs", "<", "T", ">", "addAll", "(", "Refs", "<", "T", ">", "add", ")", "{", "List", "<", "Ref", "<", "T", ">>", "overlap", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "Map", ".", "Entry", "<", "T", ",", "Ref", "<", ...
Merge two sets of references, ensuring only one reference is retained between the two sets
[ "Merge", "two", "sets", "of", "references", "ensuring", "only", "one", "reference", "is", "retained", "between", "the", "two", "sets" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/utils/concurrent/Refs.java#L163-L176
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/utils/concurrent/Refs.java
Refs.tryRef
public static <T extends RefCounted<T>> Refs<T> tryRef(Iterable<T> reference) { HashMap<T, Ref<T>> refs = new HashMap<>(); for (T rc : reference) { Ref<T> ref = rc.tryRef(); if (ref == null) { release(refs.values()); return null; } refs.put(rc, ref); } return new Refs<T>(refs); }
java
public static <T extends RefCounted<T>> Refs<T> tryRef(Iterable<T> reference) { HashMap<T, Ref<T>> refs = new HashMap<>(); for (T rc : reference) { Ref<T> ref = rc.tryRef(); if (ref == null) { release(refs.values()); return null; } refs.put(rc, ref); } return new Refs<T>(refs); }
[ "public", "static", "<", "T", "extends", "RefCounted", "<", "T", ">", ">", "Refs", "<", "T", ">", "tryRef", "(", "Iterable", "<", "T", ">", "reference", ")", "{", "HashMap", "<", "T", ",", "Ref", "<", "T", ">", ">", "refs", "=", "new", "HashMap",...
Acquire a reference to all of the provided objects, or none
[ "Acquire", "a", "reference", "to", "all", "of", "the", "provided", "objects", "or", "none" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/utils/concurrent/Refs.java#L181-L195
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/db/commitlog/CommitLogSegmentManager.java
CommitLogSegmentManager.allocate
public Allocation allocate(Mutation mutation, int size) { CommitLogSegment segment = allocatingFrom(); Allocation alloc; while ( null == (alloc = segment.allocate(mutation, size)) ) { // failed to allocate, so move to a new segment with enough room advanceAllocatingFrom(segment); segment = allocatingFrom; } return alloc; }
java
public Allocation allocate(Mutation mutation, int size) { CommitLogSegment segment = allocatingFrom(); Allocation alloc; while ( null == (alloc = segment.allocate(mutation, size)) ) { // failed to allocate, so move to a new segment with enough room advanceAllocatingFrom(segment); segment = allocatingFrom; } return alloc; }
[ "public", "Allocation", "allocate", "(", "Mutation", "mutation", ",", "int", "size", ")", "{", "CommitLogSegment", "segment", "=", "allocatingFrom", "(", ")", ";", "Allocation", "alloc", ";", "while", "(", "null", "==", "(", "alloc", "=", "segment", ".", "...
Reserve space in the current segment for the provided mutation or, if there isn't space available, create a new segment. @return the provided Allocation object
[ "Reserve", "space", "in", "the", "current", "segment", "for", "the", "provided", "mutation", "or", "if", "there", "isn", "t", "space", "available", "create", "a", "new", "segment", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/commitlog/CommitLogSegmentManager.java#L182-L195
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/db/commitlog/CommitLogSegmentManager.java
CommitLogSegmentManager.allocatingFrom
CommitLogSegment allocatingFrom() { CommitLogSegment r = allocatingFrom; if (r == null) { advanceAllocatingFrom(null); r = allocatingFrom; } return r; }
java
CommitLogSegment allocatingFrom() { CommitLogSegment r = allocatingFrom; if (r == null) { advanceAllocatingFrom(null); r = allocatingFrom; } return r; }
[ "CommitLogSegment", "allocatingFrom", "(", ")", "{", "CommitLogSegment", "r", "=", "allocatingFrom", ";", "if", "(", "r", "==", "null", ")", "{", "advanceAllocatingFrom", "(", "null", ")", ";", "r", "=", "allocatingFrom", ";", "}", "return", "r", ";", "}" ...
simple wrapper to ensure non-null value for allocatingFrom; only necessary on first call
[ "simple", "wrapper", "to", "ensure", "non", "-", "null", "value", "for", "allocatingFrom", ";", "only", "necessary", "on", "first", "call" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/commitlog/CommitLogSegmentManager.java#L198-L207
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/db/commitlog/CommitLogSegmentManager.java
CommitLogSegmentManager.advanceAllocatingFrom
private void advanceAllocatingFrom(CommitLogSegment old) { while (true) { CommitLogSegment next; synchronized (this) { // do this in a critical section so we can atomically remove from availableSegments and add to allocatingFrom/activeSegments // see https://issues.apache.org/jira/browse/CASSANDRA-6557?focusedCommentId=13874432&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-13874432 if (allocatingFrom != old) return; next = availableSegments.poll(); if (next != null) { allocatingFrom = next; activeSegments.add(next); } } if (next != null) { if (old != null) { // Now we can run the user defined command just after switching to the new commit log. // (Do this here instead of in the recycle call so we can get a head start on the archive.) CommitLog.instance.archiver.maybeArchive(old); // ensure we don't continue to use the old file; not strictly necessary, but cleaner to enforce it old.discardUnusedTail(); } // request that the CL be synced out-of-band, as we've finished a segment CommitLog.instance.requestExtraSync(); return; } // no more segments, so register to receive a signal when not empty WaitQueue.Signal signal = hasAvailableSegments.register(CommitLog.instance.metrics.waitingOnSegmentAllocation.time()); // trigger the management thread; this must occur after registering // the signal to ensure we are woken by any new segment creation wakeManager(); // check if the queue has already been added to before waiting on the signal, to catch modifications // that happened prior to registering the signal; *then* check to see if we've been beaten to making the change if (!availableSegments.isEmpty() || allocatingFrom != old) { signal.cancel(); // if we've been beaten, just stop immediately if (allocatingFrom != old) return; // otherwise try again, as there should be an available segment continue; } // can only reach here if the queue hasn't been inserted into // before we registered the signal, as we only remove items from the queue // after updating allocatingFrom. Can safely block until we are signalled // by the allocator that new segments have been published signal.awaitUninterruptibly(); } }
java
private void advanceAllocatingFrom(CommitLogSegment old) { while (true) { CommitLogSegment next; synchronized (this) { // do this in a critical section so we can atomically remove from availableSegments and add to allocatingFrom/activeSegments // see https://issues.apache.org/jira/browse/CASSANDRA-6557?focusedCommentId=13874432&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-13874432 if (allocatingFrom != old) return; next = availableSegments.poll(); if (next != null) { allocatingFrom = next; activeSegments.add(next); } } if (next != null) { if (old != null) { // Now we can run the user defined command just after switching to the new commit log. // (Do this here instead of in the recycle call so we can get a head start on the archive.) CommitLog.instance.archiver.maybeArchive(old); // ensure we don't continue to use the old file; not strictly necessary, but cleaner to enforce it old.discardUnusedTail(); } // request that the CL be synced out-of-band, as we've finished a segment CommitLog.instance.requestExtraSync(); return; } // no more segments, so register to receive a signal when not empty WaitQueue.Signal signal = hasAvailableSegments.register(CommitLog.instance.metrics.waitingOnSegmentAllocation.time()); // trigger the management thread; this must occur after registering // the signal to ensure we are woken by any new segment creation wakeManager(); // check if the queue has already been added to before waiting on the signal, to catch modifications // that happened prior to registering the signal; *then* check to see if we've been beaten to making the change if (!availableSegments.isEmpty() || allocatingFrom != old) { signal.cancel(); // if we've been beaten, just stop immediately if (allocatingFrom != old) return; // otherwise try again, as there should be an available segment continue; } // can only reach here if the queue hasn't been inserted into // before we registered the signal, as we only remove items from the queue // after updating allocatingFrom. Can safely block until we are signalled // by the allocator that new segments have been published signal.awaitUninterruptibly(); } }
[ "private", "void", "advanceAllocatingFrom", "(", "CommitLogSegment", "old", ")", "{", "while", "(", "true", ")", "{", "CommitLogSegment", "next", ";", "synchronized", "(", "this", ")", "{", "// do this in a critical section so we can atomically remove from availableSegments...
Fetches a new segment from the queue, creating a new one if necessary, and activates it
[ "Fetches", "a", "new", "segment", "from", "the", "queue", "creating", "a", "new", "one", "if", "necessary", "and", "activates", "it" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/commitlog/CommitLogSegmentManager.java#L212-L273
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/db/commitlog/CommitLogSegmentManager.java
CommitLogSegmentManager.forceRecycleAll
void forceRecycleAll(Iterable<UUID> droppedCfs) { List<CommitLogSegment> segmentsToRecycle = new ArrayList<>(activeSegments); CommitLogSegment last = segmentsToRecycle.get(segmentsToRecycle.size() - 1); advanceAllocatingFrom(last); // wait for the commit log modifications last.waitForModifications(); // make sure the writes have materialized inside of the memtables by waiting for all outstanding writes // on the relevant keyspaces to complete Set<Keyspace> keyspaces = new HashSet<>(); for (UUID cfId : last.getDirtyCFIDs()) { ColumnFamilyStore cfs = Schema.instance.getColumnFamilyStoreInstance(cfId); if (cfs != null) keyspaces.add(cfs.keyspace); } for (Keyspace keyspace : keyspaces) keyspace.writeOrder.awaitNewBarrier(); // flush and wait for all CFs that are dirty in segments up-to and including 'last' Future<?> future = flushDataFrom(segmentsToRecycle, true); try { future.get(); for (CommitLogSegment segment : activeSegments) for (UUID cfId : droppedCfs) segment.markClean(cfId, segment.getContext()); // now recycle segments that are unused, as we may not have triggered a discardCompletedSegments() // if the previous active segment was the only one to recycle (since an active segment isn't // necessarily dirty, and we only call dCS after a flush). for (CommitLogSegment segment : activeSegments) if (segment.isUnused()) recycleSegment(segment); CommitLogSegment first; if ((first = activeSegments.peek()) != null && first.id <= last.id) logger.error("Failed to force-recycle all segments; at least one segment is still in use with dirty CFs."); } catch (Throwable t) { // for now just log the error and return false, indicating that we failed logger.error("Failed waiting for a forced recycle of in-use commit log segments", t); } }
java
void forceRecycleAll(Iterable<UUID> droppedCfs) { List<CommitLogSegment> segmentsToRecycle = new ArrayList<>(activeSegments); CommitLogSegment last = segmentsToRecycle.get(segmentsToRecycle.size() - 1); advanceAllocatingFrom(last); // wait for the commit log modifications last.waitForModifications(); // make sure the writes have materialized inside of the memtables by waiting for all outstanding writes // on the relevant keyspaces to complete Set<Keyspace> keyspaces = new HashSet<>(); for (UUID cfId : last.getDirtyCFIDs()) { ColumnFamilyStore cfs = Schema.instance.getColumnFamilyStoreInstance(cfId); if (cfs != null) keyspaces.add(cfs.keyspace); } for (Keyspace keyspace : keyspaces) keyspace.writeOrder.awaitNewBarrier(); // flush and wait for all CFs that are dirty in segments up-to and including 'last' Future<?> future = flushDataFrom(segmentsToRecycle, true); try { future.get(); for (CommitLogSegment segment : activeSegments) for (UUID cfId : droppedCfs) segment.markClean(cfId, segment.getContext()); // now recycle segments that are unused, as we may not have triggered a discardCompletedSegments() // if the previous active segment was the only one to recycle (since an active segment isn't // necessarily dirty, and we only call dCS after a flush). for (CommitLogSegment segment : activeSegments) if (segment.isUnused()) recycleSegment(segment); CommitLogSegment first; if ((first = activeSegments.peek()) != null && first.id <= last.id) logger.error("Failed to force-recycle all segments; at least one segment is still in use with dirty CFs."); } catch (Throwable t) { // for now just log the error and return false, indicating that we failed logger.error("Failed waiting for a forced recycle of in-use commit log segments", t); } }
[ "void", "forceRecycleAll", "(", "Iterable", "<", "UUID", ">", "droppedCfs", ")", "{", "List", "<", "CommitLogSegment", ">", "segmentsToRecycle", "=", "new", "ArrayList", "<>", "(", "activeSegments", ")", ";", "CommitLogSegment", "last", "=", "segmentsToRecycle", ...
Switch to a new segment, regardless of how much is left in the current one. Flushes any dirty CFs for this segment and any older segments, and then recycles the segments
[ "Switch", "to", "a", "new", "segment", "regardless", "of", "how", "much", "is", "left", "in", "the", "current", "one", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/commitlog/CommitLogSegmentManager.java#L293-L340
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/db/commitlog/CommitLogSegmentManager.java
CommitLogSegmentManager.recycleSegment
void recycleSegment(final CommitLogSegment segment) { boolean archiveSuccess = CommitLog.instance.archiver.maybeWaitForArchiving(segment.getName()); activeSegments.remove(segment); if (!archiveSuccess) { // if archiving (command) was not successful then leave the file alone. don't delete or recycle. discardSegment(segment, false); return; } if (isCapExceeded()) { discardSegment(segment, true); return; } logger.debug("Recycling {}", segment); segmentManagementTasks.add(new Callable<CommitLogSegment>() { public CommitLogSegment call() { return segment.recycle(); } }); }
java
void recycleSegment(final CommitLogSegment segment) { boolean archiveSuccess = CommitLog.instance.archiver.maybeWaitForArchiving(segment.getName()); activeSegments.remove(segment); if (!archiveSuccess) { // if archiving (command) was not successful then leave the file alone. don't delete or recycle. discardSegment(segment, false); return; } if (isCapExceeded()) { discardSegment(segment, true); return; } logger.debug("Recycling {}", segment); segmentManagementTasks.add(new Callable<CommitLogSegment>() { public CommitLogSegment call() { return segment.recycle(); } }); }
[ "void", "recycleSegment", "(", "final", "CommitLogSegment", "segment", ")", "{", "boolean", "archiveSuccess", "=", "CommitLog", ".", "instance", ".", "archiver", ".", "maybeWaitForArchiving", "(", "segment", ".", "getName", "(", ")", ")", ";", "activeSegments", ...
Indicates that a segment is no longer in use and that it should be recycled. @param segment segment that is no longer in use
[ "Indicates", "that", "a", "segment", "is", "no", "longer", "in", "use", "and", "that", "it", "should", "be", "recycled", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/commitlog/CommitLogSegmentManager.java#L347-L371
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/db/commitlog/CommitLogSegmentManager.java
CommitLogSegmentManager.recycleSegment
void recycleSegment(final File file) { if (isCapExceeded() || CommitLogDescriptor.fromFileName(file.getName()).getMessagingVersion() != MessagingService.current_version) { // (don't decrease managed size, since this was never a "live" segment) logger.debug("(Unopened) segment {} is no longer needed and will be deleted now", file); FileUtils.deleteWithConfirm(file); return; } logger.debug("Recycling {}", file); // this wasn't previously a live segment, so add it to the managed size when we make it live size.addAndGet(DatabaseDescriptor.getCommitLogSegmentSize()); segmentManagementTasks.add(new Callable<CommitLogSegment>() { public CommitLogSegment call() { return new CommitLogSegment(file.getPath()); } }); }
java
void recycleSegment(final File file) { if (isCapExceeded() || CommitLogDescriptor.fromFileName(file.getName()).getMessagingVersion() != MessagingService.current_version) { // (don't decrease managed size, since this was never a "live" segment) logger.debug("(Unopened) segment {} is no longer needed and will be deleted now", file); FileUtils.deleteWithConfirm(file); return; } logger.debug("Recycling {}", file); // this wasn't previously a live segment, so add it to the managed size when we make it live size.addAndGet(DatabaseDescriptor.getCommitLogSegmentSize()); segmentManagementTasks.add(new Callable<CommitLogSegment>() { public CommitLogSegment call() { return new CommitLogSegment(file.getPath()); } }); }
[ "void", "recycleSegment", "(", "final", "File", "file", ")", "{", "if", "(", "isCapExceeded", "(", ")", "||", "CommitLogDescriptor", ".", "fromFileName", "(", "file", ".", "getName", "(", ")", ")", ".", "getMessagingVersion", "(", ")", "!=", "MessagingServic...
Differs from the above because it can work on any file instead of just existing commit log segments managed by this manager. @param file segment file that is no longer in use.
[ "Differs", "from", "the", "above", "because", "it", "can", "work", "on", "any", "file", "instead", "of", "just", "existing", "commit", "log", "segments", "managed", "by", "this", "manager", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/commitlog/CommitLogSegmentManager.java#L379-L400
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/db/commitlog/CommitLogSegmentManager.java
CommitLogSegmentManager.discardSegment
private void discardSegment(final CommitLogSegment segment, final boolean deleteFile) { logger.debug("Segment {} is no longer active and will be deleted {}", segment, deleteFile ? "now" : "by the archive script"); size.addAndGet(-DatabaseDescriptor.getCommitLogSegmentSize()); segmentManagementTasks.add(new Callable<CommitLogSegment>() { public CommitLogSegment call() { segment.close(); if (deleteFile) segment.delete(); return null; } }); }
java
private void discardSegment(final CommitLogSegment segment, final boolean deleteFile) { logger.debug("Segment {} is no longer active and will be deleted {}", segment, deleteFile ? "now" : "by the archive script"); size.addAndGet(-DatabaseDescriptor.getCommitLogSegmentSize()); segmentManagementTasks.add(new Callable<CommitLogSegment>() { public CommitLogSegment call() { segment.close(); if (deleteFile) segment.delete(); return null; } }); }
[ "private", "void", "discardSegment", "(", "final", "CommitLogSegment", "segment", ",", "final", "boolean", "deleteFile", ")", "{", "logger", ".", "debug", "(", "\"Segment {} is no longer active and will be deleted {}\"", ",", "segment", ",", "deleteFile", "?", "\"now\""...
Indicates that a segment file should be deleted. @param segment segment to be discarded
[ "Indicates", "that", "a", "segment", "file", "should", "be", "deleted", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/commitlog/CommitLogSegmentManager.java#L407-L422
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/db/commitlog/CommitLogSegmentManager.java
CommitLogSegmentManager.resetUnsafe
public void resetUnsafe() { logger.debug("Closing and clearing existing commit log segments..."); while (!segmentManagementTasks.isEmpty()) Thread.yield(); for (CommitLogSegment segment : activeSegments) segment.close(); activeSegments.clear(); for (CommitLogSegment segment : availableSegments) segment.close(); availableSegments.clear(); allocatingFrom = null; }
java
public void resetUnsafe() { logger.debug("Closing and clearing existing commit log segments..."); while (!segmentManagementTasks.isEmpty()) Thread.yield(); for (CommitLogSegment segment : activeSegments) segment.close(); activeSegments.clear(); for (CommitLogSegment segment : availableSegments) segment.close(); availableSegments.clear(); allocatingFrom = null; }
[ "public", "void", "resetUnsafe", "(", ")", "{", "logger", ".", "debug", "(", "\"Closing and clearing existing commit log segments...\"", ")", ";", "while", "(", "!", "segmentManagementTasks", ".", "isEmpty", "(", ")", ")", "Thread", ".", "yield", "(", ")", ";", ...
Resets all the segments, for testing purposes. DO NOT USE THIS OUTSIDE OF TESTS.
[ "Resets", "all", "the", "segments", "for", "testing", "purposes", ".", "DO", "NOT", "USE", "THIS", "OUTSIDE", "OF", "TESTS", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/commitlog/CommitLogSegmentManager.java#L514-L530
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/utils/BloomCalculations.java
BloomCalculations.computeBloomSpec
public static BloomSpecification computeBloomSpec(int bucketsPerElement) { assert bucketsPerElement >= 1; assert bucketsPerElement <= probs.length - 1; return new BloomSpecification(optKPerBuckets[bucketsPerElement], bucketsPerElement); }
java
public static BloomSpecification computeBloomSpec(int bucketsPerElement) { assert bucketsPerElement >= 1; assert bucketsPerElement <= probs.length - 1; return new BloomSpecification(optKPerBuckets[bucketsPerElement], bucketsPerElement); }
[ "public", "static", "BloomSpecification", "computeBloomSpec", "(", "int", "bucketsPerElement", ")", "{", "assert", "bucketsPerElement", ">=", "1", ";", "assert", "bucketsPerElement", "<=", "probs", ".", "length", "-", "1", ";", "return", "new", "BloomSpecification",...
Given the number of buckets that can be used per element, return a specification that minimizes the false positive rate. @param bucketsPerElement The number of buckets per element for the filter. @return A spec that minimizes the false positive rate.
[ "Given", "the", "number", "of", "buckets", "that", "can", "be", "used", "per", "element", "return", "a", "specification", "that", "minimizes", "the", "false", "positive", "rate", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/utils/BloomCalculations.java#L97-L102
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/utils/BloomCalculations.java
BloomCalculations.maxBucketsPerElement
public static int maxBucketsPerElement(long numElements) { numElements = Math.max(1, numElements); double v = (Long.MAX_VALUE - EXCESS) / (double)numElements; if (v < 1.0) { throw new UnsupportedOperationException("Cannot compute probabilities for " + numElements + " elements."); } return Math.min(BloomCalculations.probs.length - 1, (int)v); }
java
public static int maxBucketsPerElement(long numElements) { numElements = Math.max(1, numElements); double v = (Long.MAX_VALUE - EXCESS) / (double)numElements; if (v < 1.0) { throw new UnsupportedOperationException("Cannot compute probabilities for " + numElements + " elements."); } return Math.min(BloomCalculations.probs.length - 1, (int)v); }
[ "public", "static", "int", "maxBucketsPerElement", "(", "long", "numElements", ")", "{", "numElements", "=", "Math", ".", "max", "(", "1", ",", "numElements", ")", ";", "double", "v", "=", "(", "Long", ".", "MAX_VALUE", "-", "EXCESS", ")", "/", "(", "d...
Calculates the maximum number of buckets per element that this implementation can support. Crucially, it will lower the bucket count if necessary to meet BitSet's size restrictions.
[ "Calculates", "the", "maximum", "number", "of", "buckets", "per", "element", "that", "this", "implementation", "can", "support", ".", "Crucially", "it", "will", "lower", "the", "bucket", "count", "if", "necessary", "to", "meet", "BitSet", "s", "size", "restric...
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/utils/BloomCalculations.java#L175-L184
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/cql3/statements/PropertyDefinitions.java
PropertyDefinitions.getBoolean
public Boolean getBoolean(String key, Boolean defaultValue) throws SyntaxException { String value = getSimple(key); return (value == null) ? defaultValue : value.toLowerCase().matches("(1|true|yes)"); }
java
public Boolean getBoolean(String key, Boolean defaultValue) throws SyntaxException { String value = getSimple(key); return (value == null) ? defaultValue : value.toLowerCase().matches("(1|true|yes)"); }
[ "public", "Boolean", "getBoolean", "(", "String", "key", ",", "Boolean", "defaultValue", ")", "throws", "SyntaxException", "{", "String", "value", "=", "getSimple", "(", "key", ")", ";", "return", "(", "value", "==", "null", ")", "?", "defaultValue", ":", ...
Return a property value, typed as a Boolean
[ "Return", "a", "property", "value", "typed", "as", "a", "Boolean" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cql3/statements/PropertyDefinitions.java#L91-L95
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/cql3/statements/PropertyDefinitions.java
PropertyDefinitions.getDouble
public Double getDouble(String key, Double defaultValue) throws SyntaxException { String value = getSimple(key); if (value == null) { return defaultValue; } else { try { return Double.valueOf(value); } catch (NumberFormatException e) { throw new SyntaxException(String.format("Invalid double value %s for '%s'", value, key)); } } }
java
public Double getDouble(String key, Double defaultValue) throws SyntaxException { String value = getSimple(key); if (value == null) { return defaultValue; } else { try { return Double.valueOf(value); } catch (NumberFormatException e) { throw new SyntaxException(String.format("Invalid double value %s for '%s'", value, key)); } } }
[ "public", "Double", "getDouble", "(", "String", "key", ",", "Double", "defaultValue", ")", "throws", "SyntaxException", "{", "String", "value", "=", "getSimple", "(", "key", ")", ";", "if", "(", "value", "==", "null", ")", "{", "return", "defaultValue", ";...
Return a property value, typed as a Double
[ "Return", "a", "property", "value", "typed", "as", "a", "Double" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cql3/statements/PropertyDefinitions.java#L98-L116
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/cql3/statements/PropertyDefinitions.java
PropertyDefinitions.getInt
public Integer getInt(String key, Integer defaultValue) throws SyntaxException { String value = getSimple(key); return toInt(key, value, defaultValue); }
java
public Integer getInt(String key, Integer defaultValue) throws SyntaxException { String value = getSimple(key); return toInt(key, value, defaultValue); }
[ "public", "Integer", "getInt", "(", "String", "key", ",", "Integer", "defaultValue", ")", "throws", "SyntaxException", "{", "String", "value", "=", "getSimple", "(", "key", ")", ";", "return", "toInt", "(", "key", ",", "value", ",", "defaultValue", ")", ";...
Return a property value, typed as an Integer
[ "Return", "a", "property", "value", "typed", "as", "an", "Integer" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cql3/statements/PropertyDefinitions.java#L119-L123
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/db/commitlog/ReplayPosition.java
ReplayPosition.getReplayPosition
public static ReplayPosition getReplayPosition(Iterable<? extends SSTableReader> sstables) { if (Iterables.isEmpty(sstables)) return NONE; Function<SSTableReader, ReplayPosition> f = new Function<SSTableReader, ReplayPosition>() { public ReplayPosition apply(SSTableReader sstable) { return sstable.getReplayPosition(); } }; Ordering<ReplayPosition> ordering = Ordering.from(ReplayPosition.comparator); return ordering.max(Iterables.transform(sstables, f)); }
java
public static ReplayPosition getReplayPosition(Iterable<? extends SSTableReader> sstables) { if (Iterables.isEmpty(sstables)) return NONE; Function<SSTableReader, ReplayPosition> f = new Function<SSTableReader, ReplayPosition>() { public ReplayPosition apply(SSTableReader sstable) { return sstable.getReplayPosition(); } }; Ordering<ReplayPosition> ordering = Ordering.from(ReplayPosition.comparator); return ordering.max(Iterables.transform(sstables, f)); }
[ "public", "static", "ReplayPosition", "getReplayPosition", "(", "Iterable", "<", "?", "extends", "SSTableReader", ">", "sstables", ")", "{", "if", "(", "Iterables", ".", "isEmpty", "(", "sstables", ")", ")", "return", "NONE", ";", "Function", "<", "SSTableRead...
Convenience method to compute the replay position for a group of SSTables. @param sstables @return the most recent (highest) replay position
[ "Convenience", "method", "to", "compute", "the", "replay", "position", "for", "a", "group", "of", "SSTables", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/commitlog/ReplayPosition.java#L48-L62
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/utils/memory/MemtableAllocator.java
MemtableAllocator.setDiscarding
public void setDiscarding() { state = state.transition(LifeCycle.DISCARDING); // mark the memory owned by this allocator as reclaiming onHeap.markAllReclaiming(); offHeap.markAllReclaiming(); }
java
public void setDiscarding() { state = state.transition(LifeCycle.DISCARDING); // mark the memory owned by this allocator as reclaiming onHeap.markAllReclaiming(); offHeap.markAllReclaiming(); }
[ "public", "void", "setDiscarding", "(", ")", "{", "state", "=", "state", ".", "transition", "(", "LifeCycle", ".", "DISCARDING", ")", ";", "// mark the memory owned by this allocator as reclaiming", "onHeap", ".", "markAllReclaiming", "(", ")", ";", "offHeap", ".", ...
Mark this allocator reclaiming; this will permit any outstanding allocations to temporarily overshoot the maximum memory limit so that flushing can begin immediately
[ "Mark", "this", "allocator", "reclaiming", ";", "this", "will", "permit", "any", "outstanding", "allocations", "to", "temporarily", "overshoot", "the", "maximum", "memory", "limit", "so", "that", "flushing", "can", "begin", "immediately" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/utils/memory/MemtableAllocator.java#L82-L88
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/metrics/KeyspaceMetrics.java
KeyspaceMetrics.createKeyspaceGauge
private <T extends Number> Gauge<Long> createKeyspaceGauge(String name, final MetricValue extractor) { allMetrics.add(name); return Metrics.newGauge(factory.createMetricName(name), new Gauge<Long>() { public Long value() { long sum = 0; for (ColumnFamilyStore cf : keyspace.getColumnFamilyStores()) { sum += extractor.getValue(cf.metric); } return sum; } }); }
java
private <T extends Number> Gauge<Long> createKeyspaceGauge(String name, final MetricValue extractor) { allMetrics.add(name); return Metrics.newGauge(factory.createMetricName(name), new Gauge<Long>() { public Long value() { long sum = 0; for (ColumnFamilyStore cf : keyspace.getColumnFamilyStores()) { sum += extractor.getValue(cf.metric); } return sum; } }); }
[ "private", "<", "T", "extends", "Number", ">", "Gauge", "<", "Long", ">", "createKeyspaceGauge", "(", "String", "name", ",", "final", "MetricValue", "extractor", ")", "{", "allMetrics", ".", "add", "(", "name", ")", ";", "return", "Metrics", ".", "newGauge...
Creates a gauge that will sum the current value of a metric for all column families in this keyspace @param name @param MetricValue @return Gauge&gt;Long> that computes sum of MetricValue.getValue()
[ "Creates", "a", "gauge", "that", "will", "sum", "the", "current", "value", "of", "a", "metric", "for", "all", "column", "families", "in", "this", "keyspace" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/metrics/KeyspaceMetrics.java#L266-L281
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/dht/Murmur3Partitioner.java
Murmur3Partitioner.getToken
public LongToken getToken(ByteBuffer key) { if (key.remaining() == 0) return MINIMUM; long[] hash = new long[2]; MurmurHash.hash3_x64_128(key, key.position(), key.remaining(), 0, hash); return new LongToken(normalize(hash[0])); }
java
public LongToken getToken(ByteBuffer key) { if (key.remaining() == 0) return MINIMUM; long[] hash = new long[2]; MurmurHash.hash3_x64_128(key, key.position(), key.remaining(), 0, hash); return new LongToken(normalize(hash[0])); }
[ "public", "LongToken", "getToken", "(", "ByteBuffer", "key", ")", "{", "if", "(", "key", ".", "remaining", "(", ")", "==", "0", ")", "return", "MINIMUM", ";", "long", "[", "]", "hash", "=", "new", "long", "[", "2", "]", ";", "MurmurHash", ".", "has...
Generate the token of a key. Note that we need to ensure all generated token are strictly bigger than MINIMUM. In particular we don't want MINIMUM to correspond to any key because the range (MINIMUM, X] doesn't include MINIMUM but we use such range to select all data whose token is smaller than X.
[ "Generate", "the", "token", "of", "a", "key", ".", "Note", "that", "we", "need", "to", "ensure", "all", "generated", "token", "are", "strictly", "bigger", "than", "MINIMUM", ".", "In", "particular", "we", "don", "t", "want", "MINIMUM", "to", "correspond", ...
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/dht/Murmur3Partitioner.java#L91-L99
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/dht/OrderPreservingPartitioner.java
OrderPreservingPartitioner.bigForString
private static BigInteger bigForString(String str, int sigchars) { assert str.length() <= sigchars; BigInteger big = BigInteger.ZERO; for (int i = 0; i < str.length(); i++) { int charpos = 16 * (sigchars - (i + 1)); BigInteger charbig = BigInteger.valueOf(str.charAt(i) & 0xFFFF); big = big.or(charbig.shiftLeft(charpos)); } return big; }
java
private static BigInteger bigForString(String str, int sigchars) { assert str.length() <= sigchars; BigInteger big = BigInteger.ZERO; for (int i = 0; i < str.length(); i++) { int charpos = 16 * (sigchars - (i + 1)); BigInteger charbig = BigInteger.valueOf(str.charAt(i) & 0xFFFF); big = big.or(charbig.shiftLeft(charpos)); } return big; }
[ "private", "static", "BigInteger", "bigForString", "(", "String", "str", ",", "int", "sigchars", ")", "{", "assert", "str", ".", "length", "(", ")", "<=", "sigchars", ";", "BigInteger", "big", "=", "BigInteger", ".", "ZERO", ";", "for", "(", "int", "i", ...
Copies the characters of the given string into a BigInteger. TODO: Does not acknowledge any codepoints above 0xFFFF... problem?
[ "Copies", "the", "characters", "of", "the", "given", "string", "into", "a", "BigInteger", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/dht/OrderPreservingPartitioner.java#L66-L78
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/auth/PasswordAuthenticator.java
PasswordAuthenticator.setupDefaultUser
private void setupDefaultUser() { try { // insert the default superuser if AUTH_KS.CREDENTIALS_CF is empty. if (!hasExistingUsers()) { process(String.format("INSERT INTO %s.%s (username, salted_hash) VALUES ('%s', '%s') USING TIMESTAMP 0", Auth.AUTH_KS, CREDENTIALS_CF, DEFAULT_USER_NAME, escape(hashpw(DEFAULT_USER_PASSWORD))), ConsistencyLevel.ONE); logger.info("PasswordAuthenticator created default user '{}'", DEFAULT_USER_NAME); } } catch (RequestExecutionException e) { logger.warn("PasswordAuthenticator skipped default user setup: some nodes were not ready"); } }
java
private void setupDefaultUser() { try { // insert the default superuser if AUTH_KS.CREDENTIALS_CF is empty. if (!hasExistingUsers()) { process(String.format("INSERT INTO %s.%s (username, salted_hash) VALUES ('%s', '%s') USING TIMESTAMP 0", Auth.AUTH_KS, CREDENTIALS_CF, DEFAULT_USER_NAME, escape(hashpw(DEFAULT_USER_PASSWORD))), ConsistencyLevel.ONE); logger.info("PasswordAuthenticator created default user '{}'", DEFAULT_USER_NAME); } } catch (RequestExecutionException e) { logger.warn("PasswordAuthenticator skipped default user setup: some nodes were not ready"); } }
[ "private", "void", "setupDefaultUser", "(", ")", "{", "try", "{", "// insert the default superuser if AUTH_KS.CREDENTIALS_CF is empty.", "if", "(", "!", "hasExistingUsers", "(", ")", ")", "{", "process", "(", "String", ".", "format", "(", "\"INSERT INTO %s.%s (username,...
if there are no users yet - add default superuser.
[ "if", "there", "are", "no", "users", "yet", "-", "add", "default", "superuser", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/auth/PasswordAuthenticator.java#L212-L232
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/streaming/StreamReceiveTask.java
StreamReceiveTask.received
public synchronized void received(SSTableWriter sstable) { if (done) return; assert cfId.equals(sstable.metadata.cfId); sstables.add(sstable); if (sstables.size() == totalFiles) { done = true; executor.submit(new OnCompletionRunnable(this)); } }
java
public synchronized void received(SSTableWriter sstable) { if (done) return; assert cfId.equals(sstable.metadata.cfId); sstables.add(sstable); if (sstables.size() == totalFiles) { done = true; executor.submit(new OnCompletionRunnable(this)); } }
[ "public", "synchronized", "void", "received", "(", "SSTableWriter", "sstable", ")", "{", "if", "(", "done", ")", "return", ";", "assert", "cfId", ".", "equals", "(", "sstable", ".", "metadata", ".", "cfId", ")", ";", "sstables", ".", "add", "(", "sstable...
Process received file. @param sstable SSTable file received.
[ "Process", "received", "file", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/streaming/StreamReceiveTask.java#L74-L87
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/utils/btree/Path.java
Path.find
<V> void find(Object[] node, Comparator<V> comparator, Object target, Op mode, boolean forwards) { // TODO : should not require parameter 'forwards' - consider modifying index to represent both // child and key position, as opposed to just key position (which necessitates a different value depending // on which direction you're moving in. Prerequisite for making Path public and using to implement general // search depth = -1; if (target instanceof BTree.Special) { if (target == POSITIVE_INFINITY) moveEnd(node, forwards); else if (target == NEGATIVE_INFINITY) moveStart(node, forwards); else throw new AssertionError(); return; } while (true) { int keyEnd = getKeyEnd(node); // search for the target in the current node int i = BTree.find(comparator, target, node, 0, keyEnd); if (i >= 0) { // exact match. transform exclusive bounds into the correct index by moving back or forwards one push(node, i); switch (mode) { case HIGHER: successor(); break; case LOWER: predecessor(); } return; } i = -i - 1; // traverse into the appropriate child if (!isLeaf(node)) { push(node, forwards ? i - 1 : i); node = (Object[]) node[keyEnd + i]; continue; } // bottom of the tree and still not found. pick the right index to satisfy Op switch (mode) { case FLOOR: case LOWER: i--; } if (i < 0) { push(node, 0); predecessor(); } else if (i >= keyEnd) { push(node, keyEnd - 1); successor(); } else { push(node, i); } return; } }
java
<V> void find(Object[] node, Comparator<V> comparator, Object target, Op mode, boolean forwards) { // TODO : should not require parameter 'forwards' - consider modifying index to represent both // child and key position, as opposed to just key position (which necessitates a different value depending // on which direction you're moving in. Prerequisite for making Path public and using to implement general // search depth = -1; if (target instanceof BTree.Special) { if (target == POSITIVE_INFINITY) moveEnd(node, forwards); else if (target == NEGATIVE_INFINITY) moveStart(node, forwards); else throw new AssertionError(); return; } while (true) { int keyEnd = getKeyEnd(node); // search for the target in the current node int i = BTree.find(comparator, target, node, 0, keyEnd); if (i >= 0) { // exact match. transform exclusive bounds into the correct index by moving back or forwards one push(node, i); switch (mode) { case HIGHER: successor(); break; case LOWER: predecessor(); } return; } i = -i - 1; // traverse into the appropriate child if (!isLeaf(node)) { push(node, forwards ? i - 1 : i); node = (Object[]) node[keyEnd + i]; continue; } // bottom of the tree and still not found. pick the right index to satisfy Op switch (mode) { case FLOOR: case LOWER: i--; } if (i < 0) { push(node, 0); predecessor(); } else if (i >= keyEnd) { push(node, keyEnd - 1); successor(); } else { push(node, i); } return; } }
[ "<", "V", ">", "void", "find", "(", "Object", "[", "]", "node", ",", "Comparator", "<", "V", ">", "comparator", ",", "Object", "target", ",", "Op", "mode", ",", "boolean", "forwards", ")", "{", "// TODO : should not require parameter 'forwards' - consider modify...
Find the provided key in the tree rooted at node, and store the root to it in the path @param node the tree to search in @param comparator the comparator defining the order on the tree @param target the key to search for @param mode the type of search to perform @param forwards if the path should be setup for forward or backward iteration @param <V>
[ "Find", "the", "provided", "key", "in", "the", "tree", "rooted", "at", "node", "and", "store", "the", "root", "to", "it", "in", "the", "path" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/utils/btree/Path.java#L98-L172
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/utils/btree/Path.java
Path.successor
void successor() { Object[] node = currentNode(); int i = currentIndex(); if (!isLeaf(node)) { // if we're on a key in a branch, we MUST have a descendant either side of us, // so we always go down the left-most child until we hit a leaf node = (Object[]) node[getBranchKeyEnd(node) + i + 1]; while (!isLeaf(node)) { push(node, -1); node = (Object[]) node[getBranchKeyEnd(node)]; } push(node, 0); return; } // if we haven't reached the end of this leaf, just increment our index and return i += 1; if (i < getLeafKeyEnd(node)) { // moved to the next key in the same leaf setIndex(i); return; } // we've reached the end of this leaf, // so go up until we reach something we've not finished visiting while (!isRoot()) { pop(); i = currentIndex() + 1; node = currentNode(); if (i < getKeyEnd(node)) { setIndex(i); return; } } // we've visited the last key in the root node, so we're done setIndex(getKeyEnd(node)); }
java
void successor() { Object[] node = currentNode(); int i = currentIndex(); if (!isLeaf(node)) { // if we're on a key in a branch, we MUST have a descendant either side of us, // so we always go down the left-most child until we hit a leaf node = (Object[]) node[getBranchKeyEnd(node) + i + 1]; while (!isLeaf(node)) { push(node, -1); node = (Object[]) node[getBranchKeyEnd(node)]; } push(node, 0); return; } // if we haven't reached the end of this leaf, just increment our index and return i += 1; if (i < getLeafKeyEnd(node)) { // moved to the next key in the same leaf setIndex(i); return; } // we've reached the end of this leaf, // so go up until we reach something we've not finished visiting while (!isRoot()) { pop(); i = currentIndex() + 1; node = currentNode(); if (i < getKeyEnd(node)) { setIndex(i); return; } } // we've visited the last key in the root node, so we're done setIndex(getKeyEnd(node)); }
[ "void", "successor", "(", ")", "{", "Object", "[", "]", "node", "=", "currentNode", "(", ")", ";", "int", "i", "=", "currentIndex", "(", ")", ";", "if", "(", "!", "isLeaf", "(", "node", ")", ")", "{", "// if we're on a key in a branch, we MUST have a desce...
move to the next key in the tree
[ "move", "to", "the", "next", "key", "in", "the", "tree" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/utils/btree/Path.java#L206-L250
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/hadoop/pig/AbstractCassandraStorage.java
AbstractCassandraStorage.composeComposite
protected Tuple composeComposite(AbstractCompositeType comparator, ByteBuffer name) throws IOException { List<CompositeComponent> result = comparator.deconstruct(name); Tuple t = TupleFactory.getInstance().newTuple(result.size()); for (int i=0; i<result.size(); i++) setTupleValue(t, i, cassandraToObj(result.get(i).comparator, result.get(i).value)); return t; }
java
protected Tuple composeComposite(AbstractCompositeType comparator, ByteBuffer name) throws IOException { List<CompositeComponent> result = comparator.deconstruct(name); Tuple t = TupleFactory.getInstance().newTuple(result.size()); for (int i=0; i<result.size(); i++) setTupleValue(t, i, cassandraToObj(result.get(i).comparator, result.get(i).value)); return t; }
[ "protected", "Tuple", "composeComposite", "(", "AbstractCompositeType", "comparator", ",", "ByteBuffer", "name", ")", "throws", "IOException", "{", "List", "<", "CompositeComponent", ">", "result", "=", "comparator", ".", "deconstruct", "(", "name", ")", ";", "Tup...
Deconstructs a composite type to a Tuple.
[ "Deconstructs", "a", "composite", "type", "to", "a", "Tuple", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/hadoop/pig/AbstractCassandraStorage.java#L114-L122
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/hadoop/pig/AbstractCassandraStorage.java
AbstractCassandraStorage.columnToTuple
protected Tuple columnToTuple(Cell col, CfInfo cfInfo, AbstractType comparator) throws IOException { CfDef cfDef = cfInfo.cfDef; Tuple pair = TupleFactory.getInstance().newTuple(2); ByteBuffer colName = col.name().toByteBuffer(); // name if(comparator instanceof AbstractCompositeType) setTupleValue(pair, 0, composeComposite((AbstractCompositeType)comparator,colName)); else setTupleValue(pair, 0, cassandraToObj(comparator, colName)); // value Map<ByteBuffer,AbstractType> validators = getValidatorMap(cfDef); if (cfInfo.cql3Table && !cfInfo.compactCqlTable) { ByteBuffer[] names = ((AbstractCompositeType) parseType(cfDef.comparator_type)).split(colName); colName = names[names.length-1]; } if (validators.get(colName) == null) { Map<MarshallerType, AbstractType> marshallers = getDefaultMarshallers(cfDef); setTupleValue(pair, 1, cassandraToObj(marshallers.get(MarshallerType.DEFAULT_VALIDATOR), col.value())); } else setTupleValue(pair, 1, cassandraToObj(validators.get(colName), col.value())); return pair; }
java
protected Tuple columnToTuple(Cell col, CfInfo cfInfo, AbstractType comparator) throws IOException { CfDef cfDef = cfInfo.cfDef; Tuple pair = TupleFactory.getInstance().newTuple(2); ByteBuffer colName = col.name().toByteBuffer(); // name if(comparator instanceof AbstractCompositeType) setTupleValue(pair, 0, composeComposite((AbstractCompositeType)comparator,colName)); else setTupleValue(pair, 0, cassandraToObj(comparator, colName)); // value Map<ByteBuffer,AbstractType> validators = getValidatorMap(cfDef); if (cfInfo.cql3Table && !cfInfo.compactCqlTable) { ByteBuffer[] names = ((AbstractCompositeType) parseType(cfDef.comparator_type)).split(colName); colName = names[names.length-1]; } if (validators.get(colName) == null) { Map<MarshallerType, AbstractType> marshallers = getDefaultMarshallers(cfDef); setTupleValue(pair, 1, cassandraToObj(marshallers.get(MarshallerType.DEFAULT_VALIDATOR), col.value())); } else setTupleValue(pair, 1, cassandraToObj(validators.get(colName), col.value())); return pair; }
[ "protected", "Tuple", "columnToTuple", "(", "Cell", "col", ",", "CfInfo", "cfInfo", ",", "AbstractType", "comparator", ")", "throws", "IOException", "{", "CfDef", "cfDef", "=", "cfInfo", ".", "cfDef", ";", "Tuple", "pair", "=", "TupleFactory", ".", "getInstanc...
convert a column to a tuple
[ "convert", "a", "column", "to", "a", "tuple" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/hadoop/pig/AbstractCassandraStorage.java#L125-L153
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/hadoop/pig/AbstractCassandraStorage.java
AbstractCassandraStorage.getCfInfo
protected CfInfo getCfInfo(String signature) throws IOException { UDFContext context = UDFContext.getUDFContext(); Properties property = context.getUDFProperties(AbstractCassandraStorage.class); String prop = property.getProperty(signature); CfInfo cfInfo = new CfInfo(); cfInfo.cfDef = cfdefFromString(prop.substring(2)); cfInfo.compactCqlTable = prop.charAt(0) == '1' ? true : false; cfInfo.cql3Table = prop.charAt(1) == '1' ? true : false; return cfInfo; }
java
protected CfInfo getCfInfo(String signature) throws IOException { UDFContext context = UDFContext.getUDFContext(); Properties property = context.getUDFProperties(AbstractCassandraStorage.class); String prop = property.getProperty(signature); CfInfo cfInfo = new CfInfo(); cfInfo.cfDef = cfdefFromString(prop.substring(2)); cfInfo.compactCqlTable = prop.charAt(0) == '1' ? true : false; cfInfo.cql3Table = prop.charAt(1) == '1' ? true : false; return cfInfo; }
[ "protected", "CfInfo", "getCfInfo", "(", "String", "signature", ")", "throws", "IOException", "{", "UDFContext", "context", "=", "UDFContext", ".", "getUDFContext", "(", ")", ";", "Properties", "property", "=", "context", ".", "getUDFProperties", "(", "AbstractCas...
get the columnfamily definition for the signature
[ "get", "the", "columnfamily", "definition", "for", "the", "signature" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/hadoop/pig/AbstractCassandraStorage.java#L171-L181
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/hadoop/pig/AbstractCassandraStorage.java
AbstractCassandraStorage.getDefaultMarshallers
protected Map<MarshallerType, AbstractType> getDefaultMarshallers(CfDef cfDef) throws IOException { Map<MarshallerType, AbstractType> marshallers = new EnumMap<MarshallerType, AbstractType>(MarshallerType.class); AbstractType comparator; AbstractType subcomparator; AbstractType default_validator; AbstractType key_validator; comparator = parseType(cfDef.getComparator_type()); subcomparator = parseType(cfDef.getSubcomparator_type()); default_validator = parseType(cfDef.getDefault_validation_class()); key_validator = parseType(cfDef.getKey_validation_class()); marshallers.put(MarshallerType.COMPARATOR, comparator); marshallers.put(MarshallerType.DEFAULT_VALIDATOR, default_validator); marshallers.put(MarshallerType.KEY_VALIDATOR, key_validator); marshallers.put(MarshallerType.SUBCOMPARATOR, subcomparator); return marshallers; }
java
protected Map<MarshallerType, AbstractType> getDefaultMarshallers(CfDef cfDef) throws IOException { Map<MarshallerType, AbstractType> marshallers = new EnumMap<MarshallerType, AbstractType>(MarshallerType.class); AbstractType comparator; AbstractType subcomparator; AbstractType default_validator; AbstractType key_validator; comparator = parseType(cfDef.getComparator_type()); subcomparator = parseType(cfDef.getSubcomparator_type()); default_validator = parseType(cfDef.getDefault_validation_class()); key_validator = parseType(cfDef.getKey_validation_class()); marshallers.put(MarshallerType.COMPARATOR, comparator); marshallers.put(MarshallerType.DEFAULT_VALIDATOR, default_validator); marshallers.put(MarshallerType.KEY_VALIDATOR, key_validator); marshallers.put(MarshallerType.SUBCOMPARATOR, subcomparator); return marshallers; }
[ "protected", "Map", "<", "MarshallerType", ",", "AbstractType", ">", "getDefaultMarshallers", "(", "CfDef", "cfDef", ")", "throws", "IOException", "{", "Map", "<", "MarshallerType", ",", "AbstractType", ">", "marshallers", "=", "new", "EnumMap", "<", "MarshallerTy...
construct a map to store the mashaller type to cassandra data type mapping
[ "construct", "a", "map", "to", "store", "the", "mashaller", "type", "to", "cassandra", "data", "type", "mapping" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/hadoop/pig/AbstractCassandraStorage.java#L184-L202
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/hadoop/pig/AbstractCassandraStorage.java
AbstractCassandraStorage.getValidatorMap
protected Map<ByteBuffer, AbstractType> getValidatorMap(CfDef cfDef) throws IOException { Map<ByteBuffer, AbstractType> validators = new HashMap<ByteBuffer, AbstractType>(); for (ColumnDef cd : cfDef.getColumn_metadata()) { if (cd.getValidation_class() != null && !cd.getValidation_class().isEmpty()) { AbstractType validator = null; try { validator = TypeParser.parse(cd.getValidation_class()); if (validator instanceof CounterColumnType) validator = LongType.instance; validators.put(cd.name, validator); } catch (ConfigurationException e) { throw new IOException(e); } catch (SyntaxException e) { throw new IOException(e); } } } return validators; }
java
protected Map<ByteBuffer, AbstractType> getValidatorMap(CfDef cfDef) throws IOException { Map<ByteBuffer, AbstractType> validators = new HashMap<ByteBuffer, AbstractType>(); for (ColumnDef cd : cfDef.getColumn_metadata()) { if (cd.getValidation_class() != null && !cd.getValidation_class().isEmpty()) { AbstractType validator = null; try { validator = TypeParser.parse(cd.getValidation_class()); if (validator instanceof CounterColumnType) validator = LongType.instance; validators.put(cd.name, validator); } catch (ConfigurationException e) { throw new IOException(e); } catch (SyntaxException e) { throw new IOException(e); } } } return validators; }
[ "protected", "Map", "<", "ByteBuffer", ",", "AbstractType", ">", "getValidatorMap", "(", "CfDef", "cfDef", ")", "throws", "IOException", "{", "Map", "<", "ByteBuffer", ",", "AbstractType", ">", "validators", "=", "new", "HashMap", "<", "ByteBuffer", ",", "Abst...
get the validators
[ "get", "the", "validators" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/hadoop/pig/AbstractCassandraStorage.java#L205-L231
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/hadoop/pig/AbstractCassandraStorage.java
AbstractCassandraStorage.parseType
protected AbstractType parseType(String type) throws IOException { try { // always treat counters like longs, specifically CCT.compose is not what we need if (type != null && type.equals("org.apache.cassandra.db.marshal.CounterColumnType")) return LongType.instance; return TypeParser.parse(type); } catch (ConfigurationException e) { throw new IOException(e); } catch (SyntaxException e) { throw new IOException(e); } }
java
protected AbstractType parseType(String type) throws IOException { try { // always treat counters like longs, specifically CCT.compose is not what we need if (type != null && type.equals("org.apache.cassandra.db.marshal.CounterColumnType")) return LongType.instance; return TypeParser.parse(type); } catch (ConfigurationException e) { throw new IOException(e); } catch (SyntaxException e) { throw new IOException(e); } }
[ "protected", "AbstractType", "parseType", "(", "String", "type", ")", "throws", "IOException", "{", "try", "{", "// always treat counters like longs, specifically CCT.compose is not what we need", "if", "(", "type", "!=", "null", "&&", "type", ".", "equals", "(", "\"org...
parse the string to a cassandra data type
[ "parse", "the", "string", "to", "a", "cassandra", "data", "type" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/hadoop/pig/AbstractCassandraStorage.java#L234-L251
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/hadoop/pig/AbstractCassandraStorage.java
AbstractCassandraStorage.getQueryMap
public static Map<String, String> getQueryMap(String query) throws UnsupportedEncodingException { String[] params = query.split("&"); Map<String, String> map = new HashMap<String, String>(); for (String param : params) { String[] keyValue = param.split("="); map.put(keyValue[0], URLDecoder.decode(keyValue[1],"UTF-8")); } return map; }
java
public static Map<String, String> getQueryMap(String query) throws UnsupportedEncodingException { String[] params = query.split("&"); Map<String, String> map = new HashMap<String, String>(); for (String param : params) { String[] keyValue = param.split("="); map.put(keyValue[0], URLDecoder.decode(keyValue[1],"UTF-8")); } return map; }
[ "public", "static", "Map", "<", "String", ",", "String", ">", "getQueryMap", "(", "String", "query", ")", "throws", "UnsupportedEncodingException", "{", "String", "[", "]", "params", "=", "query", ".", "split", "(", "\"&\"", ")", ";", "Map", "<", "String",...
decompose the query to store the parameters in a map
[ "decompose", "the", "query", "to", "store", "the", "parameters", "in", "a", "map" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/hadoop/pig/AbstractCassandraStorage.java#L267-L277
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/hadoop/pig/AbstractCassandraStorage.java
AbstractCassandraStorage.getPigType
protected byte getPigType(AbstractType type) { if (type instanceof LongType || type instanceof DateType || type instanceof TimestampType) // DateType is bad and it should feel bad return DataType.LONG; else if (type instanceof IntegerType || type instanceof Int32Type) // IntegerType will overflow at 2**31, but is kept for compatibility until pig has a BigInteger return DataType.INTEGER; else if (type instanceof AsciiType || type instanceof UTF8Type || type instanceof DecimalType || type instanceof InetAddressType) return DataType.CHARARRAY; else if (type instanceof FloatType) return DataType.FLOAT; else if (type instanceof DoubleType) return DataType.DOUBLE; else if (type instanceof AbstractCompositeType || type instanceof CollectionType) return DataType.TUPLE; return DataType.BYTEARRAY; }
java
protected byte getPigType(AbstractType type) { if (type instanceof LongType || type instanceof DateType || type instanceof TimestampType) // DateType is bad and it should feel bad return DataType.LONG; else if (type instanceof IntegerType || type instanceof Int32Type) // IntegerType will overflow at 2**31, but is kept for compatibility until pig has a BigInteger return DataType.INTEGER; else if (type instanceof AsciiType || type instanceof UTF8Type || type instanceof DecimalType || type instanceof InetAddressType) return DataType.CHARARRAY; else if (type instanceof FloatType) return DataType.FLOAT; else if (type instanceof DoubleType) return DataType.DOUBLE; else if (type instanceof AbstractCompositeType || type instanceof CollectionType) return DataType.TUPLE; return DataType.BYTEARRAY; }
[ "protected", "byte", "getPigType", "(", "AbstractType", "type", ")", "{", "if", "(", "type", "instanceof", "LongType", "||", "type", "instanceof", "DateType", "||", "type", "instanceof", "TimestampType", ")", "// DateType is bad and it should feel bad", "return", "Dat...
get pig type for the cassandra data type
[ "get", "pig", "type", "for", "the", "cassandra", "data", "type" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/hadoop/pig/AbstractCassandraStorage.java#L329-L345
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/hadoop/pig/AbstractCassandraStorage.java
AbstractCassandraStorage.objToBB
protected ByteBuffer objToBB(Object o) { if (o == null) return nullToBB(); if (o instanceof java.lang.String) return ByteBuffer.wrap(new DataByteArray((String)o).get()); if (o instanceof Integer) return Int32Type.instance.decompose((Integer)o); if (o instanceof Long) return LongType.instance.decompose((Long)o); if (o instanceof Float) return FloatType.instance.decompose((Float)o); if (o instanceof Double) return DoubleType.instance.decompose((Double)o); if (o instanceof UUID) return ByteBuffer.wrap(UUIDGen.decompose((UUID) o)); if(o instanceof Tuple) { List<Object> objects = ((Tuple)o).getAll(); //collections if (objects.size() > 0 && objects.get(0) instanceof String) { String collectionType = (String) objects.get(0); if ("set".equalsIgnoreCase(collectionType) || "list".equalsIgnoreCase(collectionType)) return objToListOrSetBB(objects.subList(1, objects.size())); else if ("map".equalsIgnoreCase(collectionType)) return objToMapBB(objects.subList(1, objects.size())); } return objToCompositeBB(objects); } return ByteBuffer.wrap(((DataByteArray) o).get()); }
java
protected ByteBuffer objToBB(Object o) { if (o == null) return nullToBB(); if (o instanceof java.lang.String) return ByteBuffer.wrap(new DataByteArray((String)o).get()); if (o instanceof Integer) return Int32Type.instance.decompose((Integer)o); if (o instanceof Long) return LongType.instance.decompose((Long)o); if (o instanceof Float) return FloatType.instance.decompose((Float)o); if (o instanceof Double) return DoubleType.instance.decompose((Double)o); if (o instanceof UUID) return ByteBuffer.wrap(UUIDGen.decompose((UUID) o)); if(o instanceof Tuple) { List<Object> objects = ((Tuple)o).getAll(); //collections if (objects.size() > 0 && objects.get(0) instanceof String) { String collectionType = (String) objects.get(0); if ("set".equalsIgnoreCase(collectionType) || "list".equalsIgnoreCase(collectionType)) return objToListOrSetBB(objects.subList(1, objects.size())); else if ("map".equalsIgnoreCase(collectionType)) return objToMapBB(objects.subList(1, objects.size())); } return objToCompositeBB(objects); } return ByteBuffer.wrap(((DataByteArray) o).get()); }
[ "protected", "ByteBuffer", "objToBB", "(", "Object", "o", ")", "{", "if", "(", "o", "==", "null", ")", "return", "nullToBB", "(", ")", ";", "if", "(", "o", "instanceof", "java", ".", "lang", ".", "String", ")", "return", "ByteBuffer", ".", "wrap", "(...
convert object to ByteBuffer
[ "convert", "object", "to", "ByteBuffer" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/hadoop/pig/AbstractCassandraStorage.java#L396-L429
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/hadoop/pig/AbstractCassandraStorage.java
AbstractCassandraStorage.initSchema
protected void initSchema(String signature) throws IOException { Properties properties = UDFContext.getUDFContext().getUDFProperties(AbstractCassandraStorage.class); // Only get the schema if we haven't already gotten it if (!properties.containsKey(signature)) { try { Cassandra.Client client = ConfigHelper.getClientFromInputAddressList(conf); client.set_keyspace(keyspace); if (username != null && password != null) { Map<String, String> credentials = new HashMap<String, String>(2); credentials.put(IAuthenticator.USERNAME_KEY, username); credentials.put(IAuthenticator.PASSWORD_KEY, password); try { client.login(new AuthenticationRequest(credentials)); } catch (AuthenticationException e) { logger.error("Authentication exception: invalid username and/or password"); throw new IOException(e); } catch (AuthorizationException e) { throw new AssertionError(e); // never actually throws AuthorizationException. } } // compose the CfDef for the columfamily CfInfo cfInfo = getCfInfo(client); if (cfInfo.cfDef != null) { StringBuilder sb = new StringBuilder(); sb.append(cfInfo.compactCqlTable ? 1 : 0).append(cfInfo.cql3Table ? 1: 0).append(cfdefToString(cfInfo.cfDef)); properties.setProperty(signature, sb.toString()); } else throw new IOException(String.format("Column family '%s' not found in keyspace '%s'", column_family, keyspace)); } catch (Exception e) { throw new IOException(e); } } }
java
protected void initSchema(String signature) throws IOException { Properties properties = UDFContext.getUDFContext().getUDFProperties(AbstractCassandraStorage.class); // Only get the schema if we haven't already gotten it if (!properties.containsKey(signature)) { try { Cassandra.Client client = ConfigHelper.getClientFromInputAddressList(conf); client.set_keyspace(keyspace); if (username != null && password != null) { Map<String, String> credentials = new HashMap<String, String>(2); credentials.put(IAuthenticator.USERNAME_KEY, username); credentials.put(IAuthenticator.PASSWORD_KEY, password); try { client.login(new AuthenticationRequest(credentials)); } catch (AuthenticationException e) { logger.error("Authentication exception: invalid username and/or password"); throw new IOException(e); } catch (AuthorizationException e) { throw new AssertionError(e); // never actually throws AuthorizationException. } } // compose the CfDef for the columfamily CfInfo cfInfo = getCfInfo(client); if (cfInfo.cfDef != null) { StringBuilder sb = new StringBuilder(); sb.append(cfInfo.compactCqlTable ? 1 : 0).append(cfInfo.cql3Table ? 1: 0).append(cfdefToString(cfInfo.cfDef)); properties.setProperty(signature, sb.toString()); } else throw new IOException(String.format("Column family '%s' not found in keyspace '%s'", column_family, keyspace)); } catch (Exception e) { throw new IOException(e); } } }
[ "protected", "void", "initSchema", "(", "String", "signature", ")", "throws", "IOException", "{", "Properties", "properties", "=", "UDFContext", ".", "getUDFContext", "(", ")", ".", "getUDFProperties", "(", "AbstractCassandraStorage", ".", "class", ")", ";", "// O...
Methods to get the column family schema from Cassandra
[ "Methods", "to", "get", "the", "column", "family", "schema", "from", "Cassandra" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/hadoop/pig/AbstractCassandraStorage.java#L493-L545
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/hadoop/pig/AbstractCassandraStorage.java
AbstractCassandraStorage.cfdefToString
protected static String cfdefToString(CfDef cfDef) throws IOException { assert cfDef != null; // this is so awful it's kind of cool! TSerializer serializer = new TSerializer(new TBinaryProtocol.Factory()); try { return Hex.bytesToHex(serializer.serialize(cfDef)); } catch (TException e) { throw new IOException(e); } }
java
protected static String cfdefToString(CfDef cfDef) throws IOException { assert cfDef != null; // this is so awful it's kind of cool! TSerializer serializer = new TSerializer(new TBinaryProtocol.Factory()); try { return Hex.bytesToHex(serializer.serialize(cfDef)); } catch (TException e) { throw new IOException(e); } }
[ "protected", "static", "String", "cfdefToString", "(", "CfDef", "cfDef", ")", "throws", "IOException", "{", "assert", "cfDef", "!=", "null", ";", "// this is so awful it's kind of cool!", "TSerializer", "serializer", "=", "new", "TSerializer", "(", "new", "TBinaryProt...
convert CfDef to string
[ "convert", "CfDef", "to", "string" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/hadoop/pig/AbstractCassandraStorage.java#L548-L561
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/hadoop/pig/AbstractCassandraStorage.java
AbstractCassandraStorage.cfdefFromString
protected static CfDef cfdefFromString(String st) throws IOException { assert st != null; TDeserializer deserializer = new TDeserializer(new TBinaryProtocol.Factory()); CfDef cfDef = new CfDef(); try { deserializer.deserialize(cfDef, Hex.hexToBytes(st)); } catch (TException e) { throw new IOException(e); } return cfDef; }
java
protected static CfDef cfdefFromString(String st) throws IOException { assert st != null; TDeserializer deserializer = new TDeserializer(new TBinaryProtocol.Factory()); CfDef cfDef = new CfDef(); try { deserializer.deserialize(cfDef, Hex.hexToBytes(st)); } catch (TException e) { throw new IOException(e); } return cfDef; }
[ "protected", "static", "CfDef", "cfdefFromString", "(", "String", "st", ")", "throws", "IOException", "{", "assert", "st", "!=", "null", ";", "TDeserializer", "deserializer", "=", "new", "TDeserializer", "(", "new", "TBinaryProtocol", ".", "Factory", "(", ")", ...
convert string back to CfDef
[ "convert", "string", "back", "to", "CfDef" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/hadoop/pig/AbstractCassandraStorage.java#L564-L578
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/hadoop/pig/AbstractCassandraStorage.java
AbstractCassandraStorage.getCfInfo
protected CfInfo getCfInfo(Cassandra.Client client) throws InvalidRequestException, UnavailableException, TimedOutException, SchemaDisagreementException, TException, NotFoundException, org.apache.cassandra.exceptions.InvalidRequestException, ConfigurationException, IOException { // get CF meta data String query = "SELECT type," + " comparator," + " subcomparator," + " default_validator," + " key_validator," + " key_aliases " + "FROM system.schema_columnfamilies " + "WHERE keyspace_name = '%s' " + " AND columnfamily_name = '%s' "; CqlResult result = client.execute_cql3_query( ByteBufferUtil.bytes(String.format(query, keyspace, column_family)), Compression.NONE, ConsistencyLevel.ONE); if (result == null || result.rows == null || result.rows.isEmpty()) return null; Iterator<CqlRow> iteraRow = result.rows.iterator(); CfDef cfDef = new CfDef(); cfDef.keyspace = keyspace; cfDef.name = column_family; boolean cql3Table = false; if (iteraRow.hasNext()) { CqlRow cqlRow = iteraRow.next(); cfDef.column_type = ByteBufferUtil.string(cqlRow.columns.get(0).value); cfDef.comparator_type = ByteBufferUtil.string(cqlRow.columns.get(1).value); ByteBuffer subComparator = cqlRow.columns.get(2).value; if (subComparator != null) cfDef.subcomparator_type = ByteBufferUtil.string(subComparator); cfDef.default_validation_class = ByteBufferUtil.string(cqlRow.columns.get(3).value); cfDef.key_validation_class = ByteBufferUtil.string(cqlRow.columns.get(4).value); String keyAliases = ByteBufferUtil.string(cqlRow.columns.get(5).value); if (FBUtilities.fromJsonList(keyAliases).size() > 0) cql3Table = true; } cfDef.column_metadata = getColumnMetadata(client); CfInfo cfInfo = new CfInfo(); cfInfo.cfDef = cfDef; if (cql3Table && !(parseType(cfDef.comparator_type) instanceof AbstractCompositeType)) cfInfo.compactCqlTable = true; if (cql3Table) cfInfo.cql3Table = true;; return cfInfo; }
java
protected CfInfo getCfInfo(Cassandra.Client client) throws InvalidRequestException, UnavailableException, TimedOutException, SchemaDisagreementException, TException, NotFoundException, org.apache.cassandra.exceptions.InvalidRequestException, ConfigurationException, IOException { // get CF meta data String query = "SELECT type," + " comparator," + " subcomparator," + " default_validator," + " key_validator," + " key_aliases " + "FROM system.schema_columnfamilies " + "WHERE keyspace_name = '%s' " + " AND columnfamily_name = '%s' "; CqlResult result = client.execute_cql3_query( ByteBufferUtil.bytes(String.format(query, keyspace, column_family)), Compression.NONE, ConsistencyLevel.ONE); if (result == null || result.rows == null || result.rows.isEmpty()) return null; Iterator<CqlRow> iteraRow = result.rows.iterator(); CfDef cfDef = new CfDef(); cfDef.keyspace = keyspace; cfDef.name = column_family; boolean cql3Table = false; if (iteraRow.hasNext()) { CqlRow cqlRow = iteraRow.next(); cfDef.column_type = ByteBufferUtil.string(cqlRow.columns.get(0).value); cfDef.comparator_type = ByteBufferUtil.string(cqlRow.columns.get(1).value); ByteBuffer subComparator = cqlRow.columns.get(2).value; if (subComparator != null) cfDef.subcomparator_type = ByteBufferUtil.string(subComparator); cfDef.default_validation_class = ByteBufferUtil.string(cqlRow.columns.get(3).value); cfDef.key_validation_class = ByteBufferUtil.string(cqlRow.columns.get(4).value); String keyAliases = ByteBufferUtil.string(cqlRow.columns.get(5).value); if (FBUtilities.fromJsonList(keyAliases).size() > 0) cql3Table = true; } cfDef.column_metadata = getColumnMetadata(client); CfInfo cfInfo = new CfInfo(); cfInfo.cfDef = cfDef; if (cql3Table && !(parseType(cfDef.comparator_type) instanceof AbstractCompositeType)) cfInfo.compactCqlTable = true; if (cql3Table) cfInfo.cql3Table = true;; return cfInfo; }
[ "protected", "CfInfo", "getCfInfo", "(", "Cassandra", ".", "Client", "client", ")", "throws", "InvalidRequestException", ",", "UnavailableException", ",", "TimedOutException", ",", "SchemaDisagreementException", ",", "TException", ",", "NotFoundException", ",", "org", "...
return the CfInfo for the column family
[ "return", "the", "CfInfo", "for", "the", "column", "family" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/hadoop/pig/AbstractCassandraStorage.java#L581-L639
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/hadoop/pig/AbstractCassandraStorage.java
AbstractCassandraStorage.getColumnMeta
protected List<ColumnDef> getColumnMeta(Cassandra.Client client, boolean cassandraStorage, boolean includeCompactValueColumn) throws InvalidRequestException, UnavailableException, TimedOutException, SchemaDisagreementException, TException, CharacterCodingException, org.apache.cassandra.exceptions.InvalidRequestException, ConfigurationException, NotFoundException { String query = "SELECT column_name, " + " validator, " + " index_type, " + " type " + "FROM system.schema_columns " + "WHERE keyspace_name = '%s' " + " AND columnfamily_name = '%s'"; CqlResult result = client.execute_cql3_query( ByteBufferUtil.bytes(String.format(query, keyspace, column_family)), Compression.NONE, ConsistencyLevel.ONE); List<CqlRow> rows = result.rows; List<ColumnDef> columnDefs = new ArrayList<ColumnDef>(); if (rows == null || rows.isEmpty()) { // if CassandraStorage, just return the empty list if (cassandraStorage) return columnDefs; // otherwise for CqlNativeStorage, check metadata for classic thrift tables CFMetaData cfm = getCFMetaData(keyspace, column_family, client); for (ColumnDefinition def : cfm.regularAndStaticColumns()) { ColumnDef cDef = new ColumnDef(); String columnName = def.name.toString(); String type = def.type.toString(); logger.debug("name: {}, type: {} ", columnName, type); cDef.name = ByteBufferUtil.bytes(columnName); cDef.validation_class = type; columnDefs.add(cDef); } // we may not need to include the value column for compact tables as we // could have already processed it as schema_columnfamilies.value_alias if (columnDefs.size() == 0 && includeCompactValueColumn && cfm.compactValueColumn() != null) { ColumnDefinition def = cfm.compactValueColumn(); if ("value".equals(def.name.toString())) { ColumnDef cDef = new ColumnDef(); cDef.name = def.name.bytes; cDef.validation_class = def.type.toString(); columnDefs.add(cDef); } } return columnDefs; } Iterator<CqlRow> iterator = rows.iterator(); while (iterator.hasNext()) { CqlRow row = iterator.next(); ColumnDef cDef = new ColumnDef(); String type = ByteBufferUtil.string(row.getColumns().get(3).value); if (!type.equals("regular")) continue; cDef.setName(ByteBufferUtil.clone(row.getColumns().get(0).value)); cDef.validation_class = ByteBufferUtil.string(row.getColumns().get(1).value); ByteBuffer indexType = row.getColumns().get(2).value; if (indexType != null) cDef.index_type = getIndexType(ByteBufferUtil.string(indexType)); columnDefs.add(cDef); } return columnDefs; }
java
protected List<ColumnDef> getColumnMeta(Cassandra.Client client, boolean cassandraStorage, boolean includeCompactValueColumn) throws InvalidRequestException, UnavailableException, TimedOutException, SchemaDisagreementException, TException, CharacterCodingException, org.apache.cassandra.exceptions.InvalidRequestException, ConfigurationException, NotFoundException { String query = "SELECT column_name, " + " validator, " + " index_type, " + " type " + "FROM system.schema_columns " + "WHERE keyspace_name = '%s' " + " AND columnfamily_name = '%s'"; CqlResult result = client.execute_cql3_query( ByteBufferUtil.bytes(String.format(query, keyspace, column_family)), Compression.NONE, ConsistencyLevel.ONE); List<CqlRow> rows = result.rows; List<ColumnDef> columnDefs = new ArrayList<ColumnDef>(); if (rows == null || rows.isEmpty()) { // if CassandraStorage, just return the empty list if (cassandraStorage) return columnDefs; // otherwise for CqlNativeStorage, check metadata for classic thrift tables CFMetaData cfm = getCFMetaData(keyspace, column_family, client); for (ColumnDefinition def : cfm.regularAndStaticColumns()) { ColumnDef cDef = new ColumnDef(); String columnName = def.name.toString(); String type = def.type.toString(); logger.debug("name: {}, type: {} ", columnName, type); cDef.name = ByteBufferUtil.bytes(columnName); cDef.validation_class = type; columnDefs.add(cDef); } // we may not need to include the value column for compact tables as we // could have already processed it as schema_columnfamilies.value_alias if (columnDefs.size() == 0 && includeCompactValueColumn && cfm.compactValueColumn() != null) { ColumnDefinition def = cfm.compactValueColumn(); if ("value".equals(def.name.toString())) { ColumnDef cDef = new ColumnDef(); cDef.name = def.name.bytes; cDef.validation_class = def.type.toString(); columnDefs.add(cDef); } } return columnDefs; } Iterator<CqlRow> iterator = rows.iterator(); while (iterator.hasNext()) { CqlRow row = iterator.next(); ColumnDef cDef = new ColumnDef(); String type = ByteBufferUtil.string(row.getColumns().get(3).value); if (!type.equals("regular")) continue; cDef.setName(ByteBufferUtil.clone(row.getColumns().get(0).value)); cDef.validation_class = ByteBufferUtil.string(row.getColumns().get(1).value); ByteBuffer indexType = row.getColumns().get(2).value; if (indexType != null) cDef.index_type = getIndexType(ByteBufferUtil.string(indexType)); columnDefs.add(cDef); } return columnDefs; }
[ "protected", "List", "<", "ColumnDef", ">", "getColumnMeta", "(", "Cassandra", ".", "Client", "client", ",", "boolean", "cassandraStorage", ",", "boolean", "includeCompactValueColumn", ")", "throws", "InvalidRequestException", ",", "UnavailableException", ",", "TimedOut...
get column meta data
[ "get", "column", "meta", "data" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/hadoop/pig/AbstractCassandraStorage.java#L654-L730
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/hadoop/pig/AbstractCassandraStorage.java
AbstractCassandraStorage.getIndexType
protected IndexType getIndexType(String type) { type = type.toLowerCase(); if ("keys".equals(type)) return IndexType.KEYS; else if("custom".equals(type)) return IndexType.CUSTOM; else if("composites".equals(type)) return IndexType.COMPOSITES; else return null; }
java
protected IndexType getIndexType(String type) { type = type.toLowerCase(); if ("keys".equals(type)) return IndexType.KEYS; else if("custom".equals(type)) return IndexType.CUSTOM; else if("composites".equals(type)) return IndexType.COMPOSITES; else return null; }
[ "protected", "IndexType", "getIndexType", "(", "String", "type", ")", "{", "type", "=", "type", ".", "toLowerCase", "(", ")", ";", "if", "(", "\"keys\"", ".", "equals", "(", "type", ")", ")", "return", "IndexType", ".", "KEYS", ";", "else", "if", "(", ...
get index type from string
[ "get", "index", "type", "from", "string" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/hadoop/pig/AbstractCassandraStorage.java#L733-L744
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/hadoop/pig/AbstractCassandraStorage.java
AbstractCassandraStorage.getPartitionKeys
public String[] getPartitionKeys(String location, Job job) throws IOException { if (!usePartitionFilter) return null; List<ColumnDef> indexes = getIndexes(); String[] partitionKeys = new String[indexes.size()]; for (int i = 0; i < indexes.size(); i++) { partitionKeys[i] = new String(indexes.get(i).getName()); } return partitionKeys; }
java
public String[] getPartitionKeys(String location, Job job) throws IOException { if (!usePartitionFilter) return null; List<ColumnDef> indexes = getIndexes(); String[] partitionKeys = new String[indexes.size()]; for (int i = 0; i < indexes.size(); i++) { partitionKeys[i] = new String(indexes.get(i).getName()); } return partitionKeys; }
[ "public", "String", "[", "]", "getPartitionKeys", "(", "String", "location", ",", "Job", "job", ")", "throws", "IOException", "{", "if", "(", "!", "usePartitionFilter", ")", "return", "null", ";", "List", "<", "ColumnDef", ">", "indexes", "=", "getIndexes", ...
return partition keys
[ "return", "partition", "keys" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/hadoop/pig/AbstractCassandraStorage.java#L747-L758
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/hadoop/pig/AbstractCassandraStorage.java
AbstractCassandraStorage.getIndexes
protected List<ColumnDef> getIndexes() throws IOException { CfDef cfdef = getCfInfo(loadSignature).cfDef; List<ColumnDef> indexes = new ArrayList<ColumnDef>(); for (ColumnDef cdef : cfdef.column_metadata) { if (cdef.index_type != null) indexes.add(cdef); } return indexes; }
java
protected List<ColumnDef> getIndexes() throws IOException { CfDef cfdef = getCfInfo(loadSignature).cfDef; List<ColumnDef> indexes = new ArrayList<ColumnDef>(); for (ColumnDef cdef : cfdef.column_metadata) { if (cdef.index_type != null) indexes.add(cdef); } return indexes; }
[ "protected", "List", "<", "ColumnDef", ">", "getIndexes", "(", ")", "throws", "IOException", "{", "CfDef", "cfdef", "=", "getCfInfo", "(", "loadSignature", ")", ".", "cfDef", ";", "List", "<", "ColumnDef", ">", "indexes", "=", "new", "ArrayList", "<", "Col...
get a list of columns with defined index
[ "get", "a", "list", "of", "columns", "with", "defined", "index" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/hadoop/pig/AbstractCassandraStorage.java#L761-L771
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/hadoop/pig/AbstractCassandraStorage.java
AbstractCassandraStorage.getCFMetaData
protected CFMetaData getCFMetaData(String ks, String cf, Cassandra.Client client) throws NotFoundException, InvalidRequestException, TException, org.apache.cassandra.exceptions.InvalidRequestException, ConfigurationException { KsDef ksDef = client.describe_keyspace(ks); for (CfDef cfDef : ksDef.cf_defs) { if (cfDef.name.equalsIgnoreCase(cf)) return CFMetaData.fromThrift(cfDef); } return null; }
java
protected CFMetaData getCFMetaData(String ks, String cf, Cassandra.Client client) throws NotFoundException, InvalidRequestException, TException, org.apache.cassandra.exceptions.InvalidRequestException, ConfigurationException { KsDef ksDef = client.describe_keyspace(ks); for (CfDef cfDef : ksDef.cf_defs) { if (cfDef.name.equalsIgnoreCase(cf)) return CFMetaData.fromThrift(cfDef); } return null; }
[ "protected", "CFMetaData", "getCFMetaData", "(", "String", "ks", ",", "String", "cf", ",", "Cassandra", ".", "Client", "client", ")", "throws", "NotFoundException", ",", "InvalidRequestException", ",", "TException", ",", "org", ".", "apache", ".", "cassandra", "...
get CFMetaData of a column family
[ "get", "CFMetaData", "of", "a", "column", "family" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/hadoop/pig/AbstractCassandraStorage.java#L774-L788
train
Stratio/stratio-cassandra
src/java/com/stratio/cassandra/index/service/LuceneIndex.java
LuceneIndex.commit
public void commit() { Log.info("Committing"); try { indexWriter.commit(); } catch (IOException e) { Log.error(e, "Error while committing"); throw new RuntimeException(e); } }
java
public void commit() { Log.info("Committing"); try { indexWriter.commit(); } catch (IOException e) { Log.error(e, "Error while committing"); throw new RuntimeException(e); } }
[ "public", "void", "commit", "(", ")", "{", "Log", ".", "info", "(", "\"Committing\"", ")", ";", "try", "{", "indexWriter", ".", "commit", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "Log", ".", "error", "(", "e", ",", "\"Error w...
Commits the pending changes.
[ "Commits", "the", "pending", "changes", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/com/stratio/cassandra/index/service/LuceneIndex.java#L203-L211
train
Stratio/stratio-cassandra
src/java/com/stratio/cassandra/index/service/LuceneIndex.java
LuceneIndex.close
public void close() { Log.info("Closing index"); try { Log.info("Closing"); searcherReopener.interrupt(); searcherManager.close(); indexWriter.close(); directory.close(); } catch (IOException e) { Log.error(e, "Error while closing index"); throw new RuntimeException(e); } }
java
public void close() { Log.info("Closing index"); try { Log.info("Closing"); searcherReopener.interrupt(); searcherManager.close(); indexWriter.close(); directory.close(); } catch (IOException e) { Log.error(e, "Error while closing index"); throw new RuntimeException(e); } }
[ "public", "void", "close", "(", ")", "{", "Log", ".", "info", "(", "\"Closing index\"", ")", ";", "try", "{", "Log", ".", "info", "(", "\"Closing\"", ")", ";", "searcherReopener", ".", "interrupt", "(", ")", ";", "searcherManager", ".", "close", "(", "...
Commits all changes to the index, waits for pending merges to complete, and closes all associated resources.
[ "Commits", "all", "changes", "to", "the", "index", "waits", "for", "pending", "merges", "to", "complete", "and", "closes", "all", "associated", "resources", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/com/stratio/cassandra/index/service/LuceneIndex.java#L216-L228
train
Stratio/stratio-cassandra
src/java/com/stratio/cassandra/index/service/LuceneIndex.java
LuceneIndex.optimize
public void optimize() { Log.debug("Optimizing index"); try { indexWriter.forceMerge(1, true); indexWriter.commit(); } catch (IOException e) { Log.error(e, "Error while optimizing index"); throw new RuntimeException(e); } }
java
public void optimize() { Log.debug("Optimizing index"); try { indexWriter.forceMerge(1, true); indexWriter.commit(); } catch (IOException e) { Log.error(e, "Error while optimizing index"); throw new RuntimeException(e); } }
[ "public", "void", "optimize", "(", ")", "{", "Log", ".", "debug", "(", "\"Optimizing index\"", ")", ";", "try", "{", "indexWriter", ".", "forceMerge", "(", "1", ",", "true", ")", ";", "indexWriter", ".", "commit", "(", ")", ";", "}", "catch", "(", "I...
Optimizes the index forcing merge segments leaving one single segment. This operation blocks until all merging completes.
[ "Optimizes", "the", "index", "forcing", "merge", "segments", "leaving", "one", "single", "segment", ".", "This", "operation", "blocks", "until", "all", "merging", "completes", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/com/stratio/cassandra/index/service/LuceneIndex.java#L308-L317
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/io/sstable/SSTableWriter.java
SSTableWriter.beforeAppend
private long beforeAppend(DecoratedKey decoratedKey) { assert decoratedKey != null : "Keys must not be null"; // empty keys ARE allowed b/c of indexed column values if (lastWrittenKey != null && lastWrittenKey.compareTo(decoratedKey) >= 0) throw new RuntimeException("Last written key " + lastWrittenKey + " >= current key " + decoratedKey + " writing into " + getFilename()); return (lastWrittenKey == null) ? 0 : dataFile.getFilePointer(); }
java
private long beforeAppend(DecoratedKey decoratedKey) { assert decoratedKey != null : "Keys must not be null"; // empty keys ARE allowed b/c of indexed column values if (lastWrittenKey != null && lastWrittenKey.compareTo(decoratedKey) >= 0) throw new RuntimeException("Last written key " + lastWrittenKey + " >= current key " + decoratedKey + " writing into " + getFilename()); return (lastWrittenKey == null) ? 0 : dataFile.getFilePointer(); }
[ "private", "long", "beforeAppend", "(", "DecoratedKey", "decoratedKey", ")", "{", "assert", "decoratedKey", "!=", "null", ":", "\"Keys must not be null\"", ";", "// empty keys ARE allowed b/c of indexed column values", "if", "(", "lastWrittenKey", "!=", "null", "&&", "las...
Perform sanity checks on @param decoratedKey and @return the position in the data file before any data is written
[ "Perform", "sanity", "checks", "on" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/io/sstable/SSTableWriter.java#L160-L166
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/io/sstable/SSTableWriter.java
SSTableWriter.abort
public void abort() { assert descriptor.type.isTemporary; if (iwriter == null && dataFile == null) return; if (iwriter != null) iwriter.abort(); if (dataFile!= null) dataFile.abort(); Set<Component> components = SSTable.componentsFor(descriptor); try { if (!components.isEmpty()) SSTable.delete(descriptor, components); } catch (FSWriteError e) { logger.error(String.format("Failed deleting temp components for %s", descriptor), e); throw e; } }
java
public void abort() { assert descriptor.type.isTemporary; if (iwriter == null && dataFile == null) return; if (iwriter != null) iwriter.abort(); if (dataFile!= null) dataFile.abort(); Set<Component> components = SSTable.componentsFor(descriptor); try { if (!components.isEmpty()) SSTable.delete(descriptor, components); } catch (FSWriteError e) { logger.error(String.format("Failed deleting temp components for %s", descriptor), e); throw e; } }
[ "public", "void", "abort", "(", ")", "{", "assert", "descriptor", ".", "type", ".", "isTemporary", ";", "if", "(", "iwriter", "==", "null", "&&", "dataFile", "==", "null", ")", "return", ";", "if", "(", "iwriter", "!=", "null", ")", "iwriter", ".", "...
After failure, attempt to close the index writer and data file before deleting all temp components for the sstable
[ "After", "failure", "attempt", "to", "close", "the", "index", "writer", "and", "data", "file", "before", "deleting", "all", "temp", "components", "for", "the", "sstable" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/io/sstable/SSTableWriter.java#L334-L357
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/utils/btree/Cursor.java
Cursor.reset
public void reset(Object[] btree, boolean forwards) { _reset(btree, null, NEGATIVE_INFINITY, false, POSITIVE_INFINITY, false, forwards); }
java
public void reset(Object[] btree, boolean forwards) { _reset(btree, null, NEGATIVE_INFINITY, false, POSITIVE_INFINITY, false, forwards); }
[ "public", "void", "reset", "(", "Object", "[", "]", "btree", ",", "boolean", "forwards", ")", "{", "_reset", "(", "btree", ",", "null", ",", "NEGATIVE_INFINITY", ",", "false", ",", "POSITIVE_INFINITY", ",", "false", ",", "forwards", ")", ";", "}" ]
Reset this cursor for the provided tree, to iterate over its entire range @param btree the tree to iterate over @param forwards if false, the cursor will start at the end and move backwards
[ "Reset", "this", "cursor", "for", "the", "provided", "tree", "to", "iterate", "over", "its", "entire", "range" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/utils/btree/Cursor.java#L59-L62
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/db/AtomicBTreeColumns.java
AtomicBTreeColumns.addAllWithSizeDelta
public Pair<Long, Long> addAllWithSizeDelta(final ColumnFamily cm, MemtableAllocator allocator, OpOrder.Group writeOp, Updater indexer) { ColumnUpdater updater = new ColumnUpdater(this, cm.metadata, allocator, writeOp, indexer); DeletionInfo inputDeletionInfoCopy = null; boolean monitorOwned = false; try { if (usePessimisticLocking()) { Locks.monitorEnterUnsafe(this); monitorOwned = true; } while (true) { Holder current = ref; updater.ref = current; updater.reset(); DeletionInfo deletionInfo; if (cm.deletionInfo().mayModify(current.deletionInfo)) { if (inputDeletionInfoCopy == null) inputDeletionInfoCopy = cm.deletionInfo().copy(HeapAllocator.instance); deletionInfo = current.deletionInfo.copy().add(inputDeletionInfoCopy); updater.allocated(deletionInfo.unsharedHeapSize() - current.deletionInfo.unsharedHeapSize()); } else { deletionInfo = current.deletionInfo; } Object[] tree = BTree.update(current.tree, metadata.comparator.columnComparator(Memtable.MEMORY_POOL instanceof NativePool), cm, cm.getColumnCount(), true, updater); if (tree != null && refUpdater.compareAndSet(this, current, new Holder(tree, deletionInfo))) { indexer.updateRowLevelIndexes(); updater.finish(); return Pair.create(updater.dataSize, updater.colUpdateTimeDelta); } else if (!monitorOwned) { boolean shouldLock = usePessimisticLocking(); if (!shouldLock) { shouldLock = updateWastedAllocationTracker(updater.heapSize); } if (shouldLock) { Locks.monitorEnterUnsafe(this); monitorOwned = true; } } } } finally { if (monitorOwned) Locks.monitorExitUnsafe(this); } }
java
public Pair<Long, Long> addAllWithSizeDelta(final ColumnFamily cm, MemtableAllocator allocator, OpOrder.Group writeOp, Updater indexer) { ColumnUpdater updater = new ColumnUpdater(this, cm.metadata, allocator, writeOp, indexer); DeletionInfo inputDeletionInfoCopy = null; boolean monitorOwned = false; try { if (usePessimisticLocking()) { Locks.monitorEnterUnsafe(this); monitorOwned = true; } while (true) { Holder current = ref; updater.ref = current; updater.reset(); DeletionInfo deletionInfo; if (cm.deletionInfo().mayModify(current.deletionInfo)) { if (inputDeletionInfoCopy == null) inputDeletionInfoCopy = cm.deletionInfo().copy(HeapAllocator.instance); deletionInfo = current.deletionInfo.copy().add(inputDeletionInfoCopy); updater.allocated(deletionInfo.unsharedHeapSize() - current.deletionInfo.unsharedHeapSize()); } else { deletionInfo = current.deletionInfo; } Object[] tree = BTree.update(current.tree, metadata.comparator.columnComparator(Memtable.MEMORY_POOL instanceof NativePool), cm, cm.getColumnCount(), true, updater); if (tree != null && refUpdater.compareAndSet(this, current, new Holder(tree, deletionInfo))) { indexer.updateRowLevelIndexes(); updater.finish(); return Pair.create(updater.dataSize, updater.colUpdateTimeDelta); } else if (!monitorOwned) { boolean shouldLock = usePessimisticLocking(); if (!shouldLock) { shouldLock = updateWastedAllocationTracker(updater.heapSize); } if (shouldLock) { Locks.monitorEnterUnsafe(this); monitorOwned = true; } } } } finally { if (monitorOwned) Locks.monitorExitUnsafe(this); } }
[ "public", "Pair", "<", "Long", ",", "Long", ">", "addAllWithSizeDelta", "(", "final", "ColumnFamily", "cm", ",", "MemtableAllocator", "allocator", ",", "OpOrder", ".", "Group", "writeOp", ",", "Updater", "indexer", ")", "{", "ColumnUpdater", "updater", "=", "n...
This is only called by Memtable.resolve, so only AtomicBTreeColumns needs to implement it. @return the difference in size seen after merging the given columns
[ "This", "is", "only", "called", "by", "Memtable", ".", "resolve", "so", "only", "AtomicBTreeColumns", "needs", "to", "implement", "it", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/AtomicBTreeColumns.java#L192-L253
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/db/AtomicBTreeColumns.java
AtomicBTreeColumns.updateWastedAllocationTracker
private boolean updateWastedAllocationTracker(long wastedBytes) { // Early check for huge allocation that exceeds the limit if (wastedBytes < EXCESS_WASTE_BYTES) { // We round up to ensure work < granularity are still accounted for int wastedAllocation = ((int) (wastedBytes + ALLOCATION_GRANULARITY_BYTES - 1)) / ALLOCATION_GRANULARITY_BYTES; int oldTrackerValue; while (TRACKER_PESSIMISTIC_LOCKING != (oldTrackerValue = wasteTracker)) { // Note this time value has an arbitrary offset, but is a constant rate 32 bit counter (that may wrap) int time = (int) (System.nanoTime() >>> CLOCK_SHIFT); int delta = oldTrackerValue - time; if (oldTrackerValue == TRACKER_NEVER_WASTED || delta >= 0 || delta < -EXCESS_WASTE_OFFSET) delta = -EXCESS_WASTE_OFFSET; delta += wastedAllocation; if (delta >= 0) break; if (wasteTrackerUpdater.compareAndSet(this, oldTrackerValue, avoidReservedValues(time + delta))) return false; } } // We have definitely reached our waste limit so set the state if it isn't already wasteTrackerUpdater.set(this, TRACKER_PESSIMISTIC_LOCKING); // And tell the caller to proceed with pessimistic locking return true; }
java
private boolean updateWastedAllocationTracker(long wastedBytes) { // Early check for huge allocation that exceeds the limit if (wastedBytes < EXCESS_WASTE_BYTES) { // We round up to ensure work < granularity are still accounted for int wastedAllocation = ((int) (wastedBytes + ALLOCATION_GRANULARITY_BYTES - 1)) / ALLOCATION_GRANULARITY_BYTES; int oldTrackerValue; while (TRACKER_PESSIMISTIC_LOCKING != (oldTrackerValue = wasteTracker)) { // Note this time value has an arbitrary offset, but is a constant rate 32 bit counter (that may wrap) int time = (int) (System.nanoTime() >>> CLOCK_SHIFT); int delta = oldTrackerValue - time; if (oldTrackerValue == TRACKER_NEVER_WASTED || delta >= 0 || delta < -EXCESS_WASTE_OFFSET) delta = -EXCESS_WASTE_OFFSET; delta += wastedAllocation; if (delta >= 0) break; if (wasteTrackerUpdater.compareAndSet(this, oldTrackerValue, avoidReservedValues(time + delta))) return false; } } // We have definitely reached our waste limit so set the state if it isn't already wasteTrackerUpdater.set(this, TRACKER_PESSIMISTIC_LOCKING); // And tell the caller to proceed with pessimistic locking return true; }
[ "private", "boolean", "updateWastedAllocationTracker", "(", "long", "wastedBytes", ")", "{", "// Early check for huge allocation that exceeds the limit", "if", "(", "wastedBytes", "<", "EXCESS_WASTE_BYTES", ")", "{", "// We round up to ensure work < granularity are still accounted fo...
Update the wasted allocation tracker state based on newly wasted allocation information @param wastedBytes the number of bytes wasted by this thread @return true if the caller should now proceed with pessimistic locking because the waste limit has been reached
[ "Update", "the", "wasted", "allocation", "tracker", "state", "based", "on", "newly", "wasted", "allocation", "information" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/AtomicBTreeColumns.java#L266-L292
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/serializers/ListSerializer.java
ListSerializer.getElement
public ByteBuffer getElement(ByteBuffer serializedList, int index) { try { ByteBuffer input = serializedList.duplicate(); int n = readCollectionSize(input, Server.VERSION_3); if (n <= index) return null; for (int i = 0; i < index; i++) { int length = input.getInt(); input.position(input.position() + length); } return readValue(input, Server.VERSION_3); } catch (BufferUnderflowException e) { throw new MarshalException("Not enough bytes to read a list"); } }
java
public ByteBuffer getElement(ByteBuffer serializedList, int index) { try { ByteBuffer input = serializedList.duplicate(); int n = readCollectionSize(input, Server.VERSION_3); if (n <= index) return null; for (int i = 0; i < index; i++) { int length = input.getInt(); input.position(input.position() + length); } return readValue(input, Server.VERSION_3); } catch (BufferUnderflowException e) { throw new MarshalException("Not enough bytes to read a list"); } }
[ "public", "ByteBuffer", "getElement", "(", "ByteBuffer", "serializedList", ",", "int", "index", ")", "{", "try", "{", "ByteBuffer", "input", "=", "serializedList", ".", "duplicate", "(", ")", ";", "int", "n", "=", "readCollectionSize", "(", "input", ",", "Se...
Returns the element at the given index in a list. @param serializedList a serialized list @param index the index to get @return the serialized element at the given index, or null if the index exceeds the list size
[ "Returns", "the", "element", "at", "the", "given", "index", "in", "a", "list", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/serializers/ListSerializer.java#L120-L140
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/io/sstable/SSTableLoader.java
SSTableLoader.releaseReferences
private void releaseReferences() { for (SSTableReader sstable : sstables) { sstable.selfRef().release(); assert sstable.selfRef().globalCount() == 0; } }
java
private void releaseReferences() { for (SSTableReader sstable : sstables) { sstable.selfRef().release(); assert sstable.selfRef().globalCount() == 0; } }
[ "private", "void", "releaseReferences", "(", ")", "{", "for", "(", "SSTableReader", "sstable", ":", "sstables", ")", "{", "sstable", ".", "selfRef", "(", ")", ".", "release", "(", ")", ";", "assert", "sstable", ".", "selfRef", "(", ")", ".", "globalCount...
releases the shared reference for all sstables, we acquire this when opening the sstable
[ "releases", "the", "shared", "reference", "for", "all", "sstables", "we", "acquire", "this", "when", "opening", "the", "sstable" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/io/sstable/SSTableLoader.java#L203-L210
train
Stratio/stratio-cassandra
src/java/com/stratio/cassandra/util/TimeCounter.java
TimeCounter.start
public TimeCounter start() { switch (state) { case UNSTARTED: watch.start(); break; case RUNNING: throw new IllegalStateException("Already started. "); case STOPPED: watch.resume(); } state = State.RUNNING; return this; }
java
public TimeCounter start() { switch (state) { case UNSTARTED: watch.start(); break; case RUNNING: throw new IllegalStateException("Already started. "); case STOPPED: watch.resume(); } state = State.RUNNING; return this; }
[ "public", "TimeCounter", "start", "(", ")", "{", "switch", "(", "state", ")", "{", "case", "UNSTARTED", ":", "watch", ".", "start", "(", ")", ";", "break", ";", "case", "RUNNING", ":", "throw", "new", "IllegalStateException", "(", "\"Already started. \"", ...
Starts or resumes the time count. @return This {@link TimeCounter}.
[ "Starts", "or", "resumes", "the", "time", "count", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/com/stratio/cassandra/util/TimeCounter.java#L56-L68
train
Stratio/stratio-cassandra
src/java/com/stratio/cassandra/util/TimeCounter.java
TimeCounter.stop
public TimeCounter stop() { switch (state) { case UNSTARTED: throw new IllegalStateException("Not started. "); case STOPPED: throw new IllegalStateException("Already stopped. "); case RUNNING: watch.suspend(); } state = State.STOPPED; return this; }
java
public TimeCounter stop() { switch (state) { case UNSTARTED: throw new IllegalStateException("Not started. "); case STOPPED: throw new IllegalStateException("Already stopped. "); case RUNNING: watch.suspend(); } state = State.STOPPED; return this; }
[ "public", "TimeCounter", "stop", "(", ")", "{", "switch", "(", "state", ")", "{", "case", "UNSTARTED", ":", "throw", "new", "IllegalStateException", "(", "\"Not started. \"", ")", ";", "case", "STOPPED", ":", "throw", "new", "IllegalStateException", "(", "\"Al...
Stops or suspends the time count. @return This {@link TimeCounter}.
[ "Stops", "or", "suspends", "the", "time", "count", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/com/stratio/cassandra/util/TimeCounter.java#L75-L86
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/config/TriggerDefinition.java
TriggerDefinition.fromSchema
public static List<TriggerDefinition> fromSchema(Row serializedTriggers) { List<TriggerDefinition> triggers = new ArrayList<>(); String query = String.format("SELECT * FROM %s.%s", Keyspace.SYSTEM_KS, SystemKeyspace.SCHEMA_TRIGGERS_CF); for (UntypedResultSet.Row row : QueryProcessor.resultify(query, serializedTriggers)) { String name = row.getString(TRIGGER_NAME); String classOption = row.getMap(TRIGGER_OPTIONS, UTF8Type.instance, UTF8Type.instance).get(CLASS); triggers.add(new TriggerDefinition(name, classOption)); } return triggers; }
java
public static List<TriggerDefinition> fromSchema(Row serializedTriggers) { List<TriggerDefinition> triggers = new ArrayList<>(); String query = String.format("SELECT * FROM %s.%s", Keyspace.SYSTEM_KS, SystemKeyspace.SCHEMA_TRIGGERS_CF); for (UntypedResultSet.Row row : QueryProcessor.resultify(query, serializedTriggers)) { String name = row.getString(TRIGGER_NAME); String classOption = row.getMap(TRIGGER_OPTIONS, UTF8Type.instance, UTF8Type.instance).get(CLASS); triggers.add(new TriggerDefinition(name, classOption)); } return triggers; }
[ "public", "static", "List", "<", "TriggerDefinition", ">", "fromSchema", "(", "Row", "serializedTriggers", ")", "{", "List", "<", "TriggerDefinition", ">", "triggers", "=", "new", "ArrayList", "<>", "(", ")", ";", "String", "query", "=", "String", ".", "form...
Deserialize triggers from storage-level representation. @param serializedTriggers storage-level partition containing the trigger definitions @return the list of processed TriggerDefinitions
[ "Deserialize", "triggers", "from", "storage", "-", "level", "representation", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/config/TriggerDefinition.java#L61-L72
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/config/TriggerDefinition.java
TriggerDefinition.toSchema
public void toSchema(Mutation mutation, String cfName, long timestamp) { ColumnFamily cf = mutation.addOrGet(SystemKeyspace.SCHEMA_TRIGGERS_CF); CFMetaData cfm = CFMetaData.SchemaTriggersCf; Composite prefix = cfm.comparator.make(cfName, name); CFRowAdder adder = new CFRowAdder(cf, prefix, timestamp); adder.addMapEntry(TRIGGER_OPTIONS, CLASS, classOption); }
java
public void toSchema(Mutation mutation, String cfName, long timestamp) { ColumnFamily cf = mutation.addOrGet(SystemKeyspace.SCHEMA_TRIGGERS_CF); CFMetaData cfm = CFMetaData.SchemaTriggersCf; Composite prefix = cfm.comparator.make(cfName, name); CFRowAdder adder = new CFRowAdder(cf, prefix, timestamp); adder.addMapEntry(TRIGGER_OPTIONS, CLASS, classOption); }
[ "public", "void", "toSchema", "(", "Mutation", "mutation", ",", "String", "cfName", ",", "long", "timestamp", ")", "{", "ColumnFamily", "cf", "=", "mutation", ".", "addOrGet", "(", "SystemKeyspace", ".", "SCHEMA_TRIGGERS_CF", ")", ";", "CFMetaData", "cfm", "="...
Add specified trigger to the schema using given mutation. @param mutation The schema mutation @param cfName The name of the parent ColumnFamily @param timestamp The timestamp to use for the columns
[ "Add", "specified", "trigger", "to", "the", "schema", "using", "given", "mutation", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/config/TriggerDefinition.java#L81-L90
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/config/TriggerDefinition.java
TriggerDefinition.deleteFromSchema
public void deleteFromSchema(Mutation mutation, String cfName, long timestamp) { ColumnFamily cf = mutation.addOrGet(SystemKeyspace.SCHEMA_TRIGGERS_CF); int ldt = (int) (System.currentTimeMillis() / 1000); Composite prefix = CFMetaData.SchemaTriggersCf.comparator.make(cfName, name); cf.addAtom(new RangeTombstone(prefix, prefix.end(), timestamp, ldt)); }
java
public void deleteFromSchema(Mutation mutation, String cfName, long timestamp) { ColumnFamily cf = mutation.addOrGet(SystemKeyspace.SCHEMA_TRIGGERS_CF); int ldt = (int) (System.currentTimeMillis() / 1000); Composite prefix = CFMetaData.SchemaTriggersCf.comparator.make(cfName, name); cf.addAtom(new RangeTombstone(prefix, prefix.end(), timestamp, ldt)); }
[ "public", "void", "deleteFromSchema", "(", "Mutation", "mutation", ",", "String", "cfName", ",", "long", "timestamp", ")", "{", "ColumnFamily", "cf", "=", "mutation", ".", "addOrGet", "(", "SystemKeyspace", ".", "SCHEMA_TRIGGERS_CF", ")", ";", "int", "ldt", "=...
Drop specified trigger from the schema using given mutation. @param mutation The schema mutation @param cfName The name of the parent ColumnFamily @param timestamp The timestamp to use for the tombstone
[ "Drop", "specified", "trigger", "from", "the", "schema", "using", "given", "mutation", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/config/TriggerDefinition.java#L99-L106
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/utils/btree/NodeBuilder.java
NodeBuilder.clear
void clear() { NodeBuilder current = this; while (current != null && current.upperBound != null) { current.clearSelf(); current = current.child; } current = parent; while (current != null && current.upperBound != null) { current.clearSelf(); current = current.parent; } }
java
void clear() { NodeBuilder current = this; while (current != null && current.upperBound != null) { current.clearSelf(); current = current.child; } current = parent; while (current != null && current.upperBound != null) { current.clearSelf(); current = current.parent; } }
[ "void", "clear", "(", ")", "{", "NodeBuilder", "current", "=", "this", ";", "while", "(", "current", "!=", "null", "&&", "current", ".", "upperBound", "!=", "null", ")", "{", "current", ".", "clearSelf", "(", ")", ";", "current", "=", "current", ".", ...
ensure we aren't referencing any garbage
[ "ensure", "we", "aren", "t", "referencing", "any", "garbage" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/utils/btree/NodeBuilder.java#L68-L82
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/utils/btree/NodeBuilder.java
NodeBuilder.update
NodeBuilder update(Object key) { assert copyFrom != null; int copyFromKeyEnd = getKeyEnd(copyFrom); int i = copyFromKeyPosition; boolean found; // exact key match? boolean owns = true; // true iff this node (or a child) should contain the key if (i == copyFromKeyEnd) { found = false; } else { // this optimisation is for the common scenario of updating an existing row with the same columns/keys // and simply avoids performing a binary search until we've checked the proceeding key; // possibly we should disable this check if we determine that it fails more than a handful of times // during any given builder use to get the best of both worlds int c = -comparator.compare(key, copyFrom[i]); if (c >= 0) { found = c == 0; } else { i = find(comparator, key, copyFrom, i + 1, copyFromKeyEnd); found = i >= 0; if (!found) i = -i - 1; } } if (found) { Object prev = copyFrom[i]; Object next = updateFunction.apply(prev, key); // we aren't actually replacing anything, so leave our state intact and continue if (prev == next) return null; key = next; } else if (i == copyFromKeyEnd && compare(comparator, key, upperBound) >= 0) owns = false; if (isLeaf(copyFrom)) { if (owns) { // copy keys from the original node up to prior to the found index copyKeys(i); if (found) { // if found, we've applied updateFunction already replaceNextKey(key); } else { // if not found, we need to apply updateFunction still key = updateFunction.apply(key); addNewKey(key); // handles splitting parent if necessary via ensureRoom } // done, so return null return null; } else { // we don't want to copy anything if we're ascending and haven't copied anything previously, // as in this case we can return the original node. Leaving buildKeyPosition as 0 indicates // to buildFromRange that it should return the original instead of building a new node if (buildKeyPosition > 0) copyKeys(i); } // if we don't own it, all we need to do is ensure we've copied everything in this node // (which we have done, since not owning means pos >= keyEnd), ascend, and let Modifier.update // retry against the parent node. The if/ascend after the else branch takes care of that. } else { // branch if (found) { copyKeys(i); replaceNextKey(key); copyChildren(i + 1); return null; } else if (owns) { copyKeys(i); copyChildren(i); // belongs to the range owned by this node, but not equal to any key in the node // so descend into the owning child Object newUpperBound = i < copyFromKeyEnd ? copyFrom[i] : upperBound; Object[] descendInto = (Object[]) copyFrom[copyFromKeyEnd + i]; ensureChild().reset(descendInto, newUpperBound, updateFunction, comparator); return child; } else if (buildKeyPosition > 0 || buildChildPosition > 0) { // ensure we've copied all keys and children, but only if we've already copied something. // otherwise we want to return the original node copyKeys(copyFromKeyEnd); copyChildren(copyFromKeyEnd + 1); // since we know that there are exactly 1 more child nodes, than keys } } return ascend(); }
java
NodeBuilder update(Object key) { assert copyFrom != null; int copyFromKeyEnd = getKeyEnd(copyFrom); int i = copyFromKeyPosition; boolean found; // exact key match? boolean owns = true; // true iff this node (or a child) should contain the key if (i == copyFromKeyEnd) { found = false; } else { // this optimisation is for the common scenario of updating an existing row with the same columns/keys // and simply avoids performing a binary search until we've checked the proceeding key; // possibly we should disable this check if we determine that it fails more than a handful of times // during any given builder use to get the best of both worlds int c = -comparator.compare(key, copyFrom[i]); if (c >= 0) { found = c == 0; } else { i = find(comparator, key, copyFrom, i + 1, copyFromKeyEnd); found = i >= 0; if (!found) i = -i - 1; } } if (found) { Object prev = copyFrom[i]; Object next = updateFunction.apply(prev, key); // we aren't actually replacing anything, so leave our state intact and continue if (prev == next) return null; key = next; } else if (i == copyFromKeyEnd && compare(comparator, key, upperBound) >= 0) owns = false; if (isLeaf(copyFrom)) { if (owns) { // copy keys from the original node up to prior to the found index copyKeys(i); if (found) { // if found, we've applied updateFunction already replaceNextKey(key); } else { // if not found, we need to apply updateFunction still key = updateFunction.apply(key); addNewKey(key); // handles splitting parent if necessary via ensureRoom } // done, so return null return null; } else { // we don't want to copy anything if we're ascending and haven't copied anything previously, // as in this case we can return the original node. Leaving buildKeyPosition as 0 indicates // to buildFromRange that it should return the original instead of building a new node if (buildKeyPosition > 0) copyKeys(i); } // if we don't own it, all we need to do is ensure we've copied everything in this node // (which we have done, since not owning means pos >= keyEnd), ascend, and let Modifier.update // retry against the parent node. The if/ascend after the else branch takes care of that. } else { // branch if (found) { copyKeys(i); replaceNextKey(key); copyChildren(i + 1); return null; } else if (owns) { copyKeys(i); copyChildren(i); // belongs to the range owned by this node, but not equal to any key in the node // so descend into the owning child Object newUpperBound = i < copyFromKeyEnd ? copyFrom[i] : upperBound; Object[] descendInto = (Object[]) copyFrom[copyFromKeyEnd + i]; ensureChild().reset(descendInto, newUpperBound, updateFunction, comparator); return child; } else if (buildKeyPosition > 0 || buildChildPosition > 0) { // ensure we've copied all keys and children, but only if we've already copied something. // otherwise we want to return the original node copyKeys(copyFromKeyEnd); copyChildren(copyFromKeyEnd + 1); // since we know that there are exactly 1 more child nodes, than keys } } return ascend(); }
[ "NodeBuilder", "update", "(", "Object", "key", ")", "{", "assert", "copyFrom", "!=", "null", ";", "int", "copyFromKeyEnd", "=", "getKeyEnd", "(", "copyFrom", ")", ";", "int", "i", "=", "copyFromKeyPosition", ";", "boolean", "found", ";", "// exact key match?",...
Inserts or replaces the provided key, copying all not-yet-visited keys prior to it into our buffer. @param key key we are inserting/replacing @return the NodeBuilder to retry the update against (a child if we own the range being updated, a parent if we do not -- we got here from an earlier key -- and we need to ascend back up), or null if we finished the update in this node.
[ "Inserts", "or", "replaces", "the", "provided", "key", "copying", "all", "not", "-", "yet", "-", "visited", "keys", "prior", "to", "it", "into", "our", "buffer", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/utils/btree/NodeBuilder.java#L129-L241
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/utils/btree/NodeBuilder.java
NodeBuilder.ascendToRoot
NodeBuilder ascendToRoot() { NodeBuilder current = this; while (!current.isRoot()) current = current.ascend(); return current; }
java
NodeBuilder ascendToRoot() { NodeBuilder current = this; while (!current.isRoot()) current = current.ascend(); return current; }
[ "NodeBuilder", "ascendToRoot", "(", ")", "{", "NodeBuilder", "current", "=", "this", ";", "while", "(", "!", "current", ".", "isRoot", "(", ")", ")", "current", "=", "current", ".", "ascend", "(", ")", ";", "return", "current", ";", "}" ]
where we work only on the newest child node, which may construct many spill-over parents as it goes
[ "where", "we", "work", "only", "on", "the", "newest", "child", "node", "which", "may", "construct", "many", "spill", "-", "over", "parents", "as", "it", "goes" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/utils/btree/NodeBuilder.java#L256-L262
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/utils/btree/NodeBuilder.java
NodeBuilder.toNode
Object[] toNode() { assert buildKeyPosition <= FAN_FACTOR && (buildKeyPosition > 0 || copyFrom.length > 0) : buildKeyPosition; return buildFromRange(0, buildKeyPosition, isLeaf(copyFrom), false); }
java
Object[] toNode() { assert buildKeyPosition <= FAN_FACTOR && (buildKeyPosition > 0 || copyFrom.length > 0) : buildKeyPosition; return buildFromRange(0, buildKeyPosition, isLeaf(copyFrom), false); }
[ "Object", "[", "]", "toNode", "(", ")", "{", "assert", "buildKeyPosition", "<=", "FAN_FACTOR", "&&", "(", "buildKeyPosition", ">", "0", "||", "copyFrom", ".", "length", ">", "0", ")", ":", "buildKeyPosition", ";", "return", "buildFromRange", "(", "0", ",",...
builds a new root BTree node - must be called on root of operation
[ "builds", "a", "new", "root", "BTree", "node", "-", "must", "be", "called", "on", "root", "of", "operation" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/utils/btree/NodeBuilder.java#L265-L269
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/utils/btree/NodeBuilder.java
NodeBuilder.ascend
private NodeBuilder ascend() { ensureParent(); boolean isLeaf = isLeaf(copyFrom); if (buildKeyPosition > FAN_FACTOR) { // split current node and move the midpoint into parent, with the two halves as children int mid = buildKeyPosition / 2; parent.addExtraChild(buildFromRange(0, mid, isLeaf, true), buildKeys[mid]); parent.finishChild(buildFromRange(mid + 1, buildKeyPosition - (mid + 1), isLeaf, false)); } else { parent.finishChild(buildFromRange(0, buildKeyPosition, isLeaf, false)); } return parent; }
java
private NodeBuilder ascend() { ensureParent(); boolean isLeaf = isLeaf(copyFrom); if (buildKeyPosition > FAN_FACTOR) { // split current node and move the midpoint into parent, with the two halves as children int mid = buildKeyPosition / 2; parent.addExtraChild(buildFromRange(0, mid, isLeaf, true), buildKeys[mid]); parent.finishChild(buildFromRange(mid + 1, buildKeyPosition - (mid + 1), isLeaf, false)); } else { parent.finishChild(buildFromRange(0, buildKeyPosition, isLeaf, false)); } return parent; }
[ "private", "NodeBuilder", "ascend", "(", ")", "{", "ensureParent", "(", ")", ";", "boolean", "isLeaf", "=", "isLeaf", "(", "copyFrom", ")", ";", "if", "(", "buildKeyPosition", ">", "FAN_FACTOR", ")", "{", "// split current node and move the midpoint into parent, wit...
finish up this level and pass any constructed children up to our parent, ensuring a parent exists
[ "finish", "up", "this", "level", "and", "pass", "any", "constructed", "children", "up", "to", "our", "parent", "ensuring", "a", "parent", "exists" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/utils/btree/NodeBuilder.java#L272-L288
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/utils/btree/NodeBuilder.java
NodeBuilder.addNewKey
void addNewKey(Object key) { ensureRoom(buildKeyPosition + 1); buildKeys[buildKeyPosition++] = updateFunction.apply(key); }
java
void addNewKey(Object key) { ensureRoom(buildKeyPosition + 1); buildKeys[buildKeyPosition++] = updateFunction.apply(key); }
[ "void", "addNewKey", "(", "Object", "key", ")", "{", "ensureRoom", "(", "buildKeyPosition", "+", "1", ")", ";", "buildKeys", "[", "buildKeyPosition", "++", "]", "=", "updateFunction", ".", "apply", "(", "key", ")", ";", "}" ]
puts the provided key in the builder, with no impact on treatment of data from copyf
[ "puts", "the", "provided", "key", "in", "the", "builder", "with", "no", "impact", "on", "treatment", "of", "data", "from", "copyf" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/utils/btree/NodeBuilder.java#L319-L323
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/utils/btree/NodeBuilder.java
NodeBuilder.addExtraChild
private void addExtraChild(Object[] child, Object upperBound) { ensureRoom(buildKeyPosition + 1); buildKeys[buildKeyPosition++] = upperBound; buildChildren[buildChildPosition++] = child; }
java
private void addExtraChild(Object[] child, Object upperBound) { ensureRoom(buildKeyPosition + 1); buildKeys[buildKeyPosition++] = upperBound; buildChildren[buildChildPosition++] = child; }
[ "private", "void", "addExtraChild", "(", "Object", "[", "]", "child", ",", "Object", "upperBound", ")", "{", "ensureRoom", "(", "buildKeyPosition", "+", "1", ")", ";", "buildKeys", "[", "buildKeyPosition", "++", "]", "=", "upperBound", ";", "buildChildren", ...
adds a new and unexpected child to the builder - called by children that overflow
[ "adds", "a", "new", "and", "unexpected", "child", "to", "the", "builder", "-", "called", "by", "children", "that", "overflow" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/utils/btree/NodeBuilder.java#L341-L346
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/utils/btree/NodeBuilder.java
NodeBuilder.ensureRoom
private void ensureRoom(int nextBuildKeyPosition) { if (nextBuildKeyPosition < MAX_KEYS) return; // flush even number of items so we don't waste leaf space repeatedly Object[] flushUp = buildFromRange(0, FAN_FACTOR, isLeaf(copyFrom), true); ensureParent().addExtraChild(flushUp, buildKeys[FAN_FACTOR]); int size = FAN_FACTOR + 1; assert size <= buildKeyPosition : buildKeyPosition + "," + nextBuildKeyPosition; System.arraycopy(buildKeys, size, buildKeys, 0, buildKeyPosition - size); buildKeyPosition -= size; maxBuildKeyPosition = buildKeys.length; if (buildChildPosition > 0) { System.arraycopy(buildChildren, size, buildChildren, 0, buildChildPosition - size); buildChildPosition -= size; } }
java
private void ensureRoom(int nextBuildKeyPosition) { if (nextBuildKeyPosition < MAX_KEYS) return; // flush even number of items so we don't waste leaf space repeatedly Object[] flushUp = buildFromRange(0, FAN_FACTOR, isLeaf(copyFrom), true); ensureParent().addExtraChild(flushUp, buildKeys[FAN_FACTOR]); int size = FAN_FACTOR + 1; assert size <= buildKeyPosition : buildKeyPosition + "," + nextBuildKeyPosition; System.arraycopy(buildKeys, size, buildKeys, 0, buildKeyPosition - size); buildKeyPosition -= size; maxBuildKeyPosition = buildKeys.length; if (buildChildPosition > 0) { System.arraycopy(buildChildren, size, buildChildren, 0, buildChildPosition - size); buildChildPosition -= size; } }
[ "private", "void", "ensureRoom", "(", "int", "nextBuildKeyPosition", ")", "{", "if", "(", "nextBuildKeyPosition", "<", "MAX_KEYS", ")", "return", ";", "// flush even number of items so we don't waste leaf space repeatedly", "Object", "[", "]", "flushUp", "=", "buildFromRa...
checks if we can add the requested keys+children to the builder, and if not we spill-over into our parent
[ "checks", "if", "we", "can", "add", "the", "requested", "keys", "+", "children", "to", "the", "builder", "and", "if", "not", "we", "spill", "-", "over", "into", "our", "parent" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/utils/btree/NodeBuilder.java#L356-L374
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/utils/btree/NodeBuilder.java
NodeBuilder.buildFromRange
private Object[] buildFromRange(int offset, int keyLength, boolean isLeaf, boolean isExtra) { // if keyLength is 0, we didn't copy anything from the original, which means we didn't // modify any of the range owned by it, so can simply return it as is if (keyLength == 0) return copyFrom; Object[] a; if (isLeaf) { a = new Object[keyLength + (keyLength & 1)]; System.arraycopy(buildKeys, offset, a, 0, keyLength); } else { a = new Object[1 + (keyLength * 2)]; System.arraycopy(buildKeys, offset, a, 0, keyLength); System.arraycopy(buildChildren, offset, a, keyLength, keyLength + 1); } if (isExtra) updateFunction.allocated(ObjectSizes.sizeOfArray(a)); else if (a.length != copyFrom.length) updateFunction.allocated(ObjectSizes.sizeOfArray(a) - (copyFrom.length == 0 ? 0 : ObjectSizes.sizeOfArray(copyFrom))); return a; }
java
private Object[] buildFromRange(int offset, int keyLength, boolean isLeaf, boolean isExtra) { // if keyLength is 0, we didn't copy anything from the original, which means we didn't // modify any of the range owned by it, so can simply return it as is if (keyLength == 0) return copyFrom; Object[] a; if (isLeaf) { a = new Object[keyLength + (keyLength & 1)]; System.arraycopy(buildKeys, offset, a, 0, keyLength); } else { a = new Object[1 + (keyLength * 2)]; System.arraycopy(buildKeys, offset, a, 0, keyLength); System.arraycopy(buildChildren, offset, a, keyLength, keyLength + 1); } if (isExtra) updateFunction.allocated(ObjectSizes.sizeOfArray(a)); else if (a.length != copyFrom.length) updateFunction.allocated(ObjectSizes.sizeOfArray(a) - (copyFrom.length == 0 ? 0 : ObjectSizes.sizeOfArray(copyFrom))); return a; }
[ "private", "Object", "[", "]", "buildFromRange", "(", "int", "offset", ",", "int", "keyLength", ",", "boolean", "isLeaf", ",", "boolean", "isExtra", ")", "{", "// if keyLength is 0, we didn't copy anything from the original, which means we didn't", "// modify any of the range...
builds and returns a node from the buffered objects in the given range
[ "builds", "and", "returns", "a", "node", "from", "the", "buffered", "objects", "in", "the", "given", "range" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/utils/btree/NodeBuilder.java#L377-L402
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/utils/btree/NodeBuilder.java
NodeBuilder.ensureParent
private NodeBuilder ensureParent() { if (parent == null) { parent = new NodeBuilder(); parent.child = this; } if (parent.upperBound == null) parent.reset(EMPTY_BRANCH, upperBound, updateFunction, comparator); return parent; }
java
private NodeBuilder ensureParent() { if (parent == null) { parent = new NodeBuilder(); parent.child = this; } if (parent.upperBound == null) parent.reset(EMPTY_BRANCH, upperBound, updateFunction, comparator); return parent; }
[ "private", "NodeBuilder", "ensureParent", "(", ")", "{", "if", "(", "parent", "==", "null", ")", "{", "parent", "=", "new", "NodeBuilder", "(", ")", ";", "parent", ".", "child", "=", "this", ";", "}", "if", "(", "parent", ".", "upperBound", "==", "nu...
already be initialised, and only aren't in the case where we are overflowing the original root node
[ "already", "be", "initialised", "and", "only", "aren", "t", "in", "the", "case", "where", "we", "are", "overflowing", "the", "original", "root", "node" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/utils/btree/NodeBuilder.java#L407-L417
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/streaming/compress/CompressedStreamWriter.java
CompressedStreamWriter.getTransferSections
private List<Pair<Long, Long>> getTransferSections(CompressionMetadata.Chunk[] chunks) { List<Pair<Long, Long>> transferSections = new ArrayList<>(); Pair<Long, Long> lastSection = null; for (CompressionMetadata.Chunk chunk : chunks) { if (lastSection != null) { if (chunk.offset == lastSection.right) { // extend previous section to end of this chunk lastSection = Pair.create(lastSection.left, chunk.offset + chunk.length + 4); // 4 bytes for CRC } else { transferSections.add(lastSection); lastSection = Pair.create(chunk.offset, chunk.offset + chunk.length + 4); } } else { lastSection = Pair.create(chunk.offset, chunk.offset + chunk.length + 4); } } if (lastSection != null) transferSections.add(lastSection); return transferSections; }
java
private List<Pair<Long, Long>> getTransferSections(CompressionMetadata.Chunk[] chunks) { List<Pair<Long, Long>> transferSections = new ArrayList<>(); Pair<Long, Long> lastSection = null; for (CompressionMetadata.Chunk chunk : chunks) { if (lastSection != null) { if (chunk.offset == lastSection.right) { // extend previous section to end of this chunk lastSection = Pair.create(lastSection.left, chunk.offset + chunk.length + 4); // 4 bytes for CRC } else { transferSections.add(lastSection); lastSection = Pair.create(chunk.offset, chunk.offset + chunk.length + 4); } } else { lastSection = Pair.create(chunk.offset, chunk.offset + chunk.length + 4); } } if (lastSection != null) transferSections.add(lastSection); return transferSections; }
[ "private", "List", "<", "Pair", "<", "Long", ",", "Long", ">", ">", "getTransferSections", "(", "CompressionMetadata", ".", "Chunk", "[", "]", "chunks", ")", "{", "List", "<", "Pair", "<", "Long", ",", "Long", ">", ">", "transferSections", "=", "new", ...
chunks are assumed to be sorted by offset
[ "chunks", "are", "assumed", "to", "be", "sorted", "by", "offset" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/streaming/compress/CompressedStreamWriter.java#L99-L126
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/db/composites/SimpleDenseCellName.java
SimpleDenseCellName.copy
@Override public CellName copy(CFMetaData cfm, AbstractAllocator allocator) { return new SimpleDenseCellName(allocator.clone(element)); }
java
@Override public CellName copy(CFMetaData cfm, AbstractAllocator allocator) { return new SimpleDenseCellName(allocator.clone(element)); }
[ "@", "Override", "public", "CellName", "copy", "(", "CFMetaData", "cfm", ",", "AbstractAllocator", "allocator", ")", "{", "return", "new", "SimpleDenseCellName", "(", "allocator", ".", "clone", "(", "element", ")", ")", ";", "}" ]
we might want to try to do better.
[ "we", "might", "want", "to", "try", "to", "do", "better", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/composites/SimpleDenseCellName.java#L77-L81
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/db/compaction/DateTieredCompactionStrategy.java
DateTieredCompactionStrategy.getNow
private long getNow() { return Collections.max(cfs.getSSTables(), new Comparator<SSTableReader>() { public int compare(SSTableReader o1, SSTableReader o2) { return Long.compare(o1.getMaxTimestamp(), o2.getMaxTimestamp()); } }).getMaxTimestamp(); }
java
private long getNow() { return Collections.max(cfs.getSSTables(), new Comparator<SSTableReader>() { public int compare(SSTableReader o1, SSTableReader o2) { return Long.compare(o1.getMaxTimestamp(), o2.getMaxTimestamp()); } }).getMaxTimestamp(); }
[ "private", "long", "getNow", "(", ")", "{", "return", "Collections", ".", "max", "(", "cfs", ".", "getSSTables", "(", ")", ",", "new", "Comparator", "<", "SSTableReader", ">", "(", ")", "{", "public", "int", "compare", "(", "SSTableReader", "o1", ",", ...
Gets the timestamp that DateTieredCompactionStrategy considers to be the "current time". @return the maximum timestamp across all SSTables. @throws java.util.NoSuchElementException if there are no SSTables.
[ "Gets", "the", "timestamp", "that", "DateTieredCompactionStrategy", "considers", "to", "be", "the", "current", "time", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/compaction/DateTieredCompactionStrategy.java#L138-L147
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/db/compaction/DateTieredCompactionStrategy.java
DateTieredCompactionStrategy.filterOldSSTables
@VisibleForTesting static Iterable<SSTableReader> filterOldSSTables(List<SSTableReader> sstables, long maxSSTableAge, long now) { if (maxSSTableAge == 0) return sstables; final long cutoff = now - maxSSTableAge; return Iterables.filter(sstables, new Predicate<SSTableReader>() { @Override public boolean apply(SSTableReader sstable) { return sstable.getMaxTimestamp() >= cutoff; } }); }
java
@VisibleForTesting static Iterable<SSTableReader> filterOldSSTables(List<SSTableReader> sstables, long maxSSTableAge, long now) { if (maxSSTableAge == 0) return sstables; final long cutoff = now - maxSSTableAge; return Iterables.filter(sstables, new Predicate<SSTableReader>() { @Override public boolean apply(SSTableReader sstable) { return sstable.getMaxTimestamp() >= cutoff; } }); }
[ "@", "VisibleForTesting", "static", "Iterable", "<", "SSTableReader", ">", "filterOldSSTables", "(", "List", "<", "SSTableReader", ">", "sstables", ",", "long", "maxSSTableAge", ",", "long", "now", ")", "{", "if", "(", "maxSSTableAge", "==", "0", ")", "return"...
Removes all sstables with max timestamp older than maxSSTableAge. @param sstables all sstables to consider @param maxSSTableAge the age in milliseconds when an SSTable stops participating in compactions @param now current time. SSTables with max timestamp less than (now - maxSSTableAge) are filtered. @return a list of sstables with the oldest sstables excluded
[ "Removes", "all", "sstables", "with", "max", "timestamp", "older", "than", "maxSSTableAge", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/compaction/DateTieredCompactionStrategy.java#L156-L170
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/db/compaction/DateTieredCompactionStrategy.java
DateTieredCompactionStrategy.getBuckets
@VisibleForTesting static <T> List<List<T>> getBuckets(Collection<Pair<T, Long>> files, long timeUnit, int base, long now) { // Sort files by age. Newest first. final List<Pair<T, Long>> sortedFiles = Lists.newArrayList(files); Collections.sort(sortedFiles, Collections.reverseOrder(new Comparator<Pair<T, Long>>() { public int compare(Pair<T, Long> p1, Pair<T, Long> p2) { return p1.right.compareTo(p2.right); } })); List<List<T>> buckets = Lists.newArrayList(); Target target = getInitialTarget(now, timeUnit); PeekingIterator<Pair<T, Long>> it = Iterators.peekingIterator(sortedFiles.iterator()); outerLoop: while (it.hasNext()) { while (!target.onTarget(it.peek().right)) { // If the file is too new for the target, skip it. if (target.compareToTimestamp(it.peek().right) < 0) { it.next(); if (!it.hasNext()) break outerLoop; } else // If the file is too old for the target, switch targets. target = target.nextTarget(base); } List<T> bucket = Lists.newArrayList(); while (target.onTarget(it.peek().right)) { bucket.add(it.next().left); if (!it.hasNext()) break; } buckets.add(bucket); } return buckets; }
java
@VisibleForTesting static <T> List<List<T>> getBuckets(Collection<Pair<T, Long>> files, long timeUnit, int base, long now) { // Sort files by age. Newest first. final List<Pair<T, Long>> sortedFiles = Lists.newArrayList(files); Collections.sort(sortedFiles, Collections.reverseOrder(new Comparator<Pair<T, Long>>() { public int compare(Pair<T, Long> p1, Pair<T, Long> p2) { return p1.right.compareTo(p2.right); } })); List<List<T>> buckets = Lists.newArrayList(); Target target = getInitialTarget(now, timeUnit); PeekingIterator<Pair<T, Long>> it = Iterators.peekingIterator(sortedFiles.iterator()); outerLoop: while (it.hasNext()) { while (!target.onTarget(it.peek().right)) { // If the file is too new for the target, skip it. if (target.compareToTimestamp(it.peek().right) < 0) { it.next(); if (!it.hasNext()) break outerLoop; } else // If the file is too old for the target, switch targets. target = target.nextTarget(base); } List<T> bucket = Lists.newArrayList(); while (target.onTarget(it.peek().right)) { bucket.add(it.next().left); if (!it.hasNext()) break; } buckets.add(bucket); } return buckets; }
[ "@", "VisibleForTesting", "static", "<", "T", ">", "List", "<", "List", "<", "T", ">", ">", "getBuckets", "(", "Collection", "<", "Pair", "<", "T", ",", "Long", ">", ">", "files", ",", "long", "timeUnit", ",", "int", "base", ",", "long", "now", ")"...
Group files with similar min timestamp into buckets. Files with recent min timestamps are grouped together into buckets designated to short timespans while files with older timestamps are grouped into buckets representing longer timespans. @param files pairs consisting of a file and its min timestamp @param timeUnit @param base @param now @return a list of buckets of files. The list is ordered such that the files with newest timestamps come first. Each bucket is also a list of files ordered from newest to oldest.
[ "Group", "files", "with", "similar", "min", "timestamp", "into", "buckets", ".", "Files", "with", "recent", "min", "timestamps", "are", "grouped", "together", "into", "buckets", "designated", "to", "short", "timespans", "while", "files", "with", "older", "timest...
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/compaction/DateTieredCompactionStrategy.java#L257-L303
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/hadoop/cql3/CqlBulkRecordWriter.java
CqlBulkRecordWriter.write
@Override public void write(Object key, List<ByteBuffer> values) throws IOException { prepareWriter(); try { ((CQLSSTableWriter) writer).rawAddRow(values); if (null != progress) progress.progress(); if (null != context) HadoopCompat.progress(context); } catch (InvalidRequestException e) { throw new IOException("Error adding row with key: " + key, e); } }
java
@Override public void write(Object key, List<ByteBuffer> values) throws IOException { prepareWriter(); try { ((CQLSSTableWriter) writer).rawAddRow(values); if (null != progress) progress.progress(); if (null != context) HadoopCompat.progress(context); } catch (InvalidRequestException e) { throw new IOException("Error adding row with key: " + key, e); } }
[ "@", "Override", "public", "void", "write", "(", "Object", "key", ",", "List", "<", "ByteBuffer", ">", "values", ")", "throws", "IOException", "{", "prepareWriter", "(", ")", ";", "try", "{", "(", "(", "CQLSSTableWriter", ")", "writer", ")", ".", "rawAdd...
The column values must correspond to the order in which they appear in the insert stored procedure. Key is not used, so it can be null or any object. </p> @param key any object or null. @param values the values to write. @throws IOException
[ "The", "column", "values", "must", "correspond", "to", "the", "order", "in", "which", "they", "appear", "in", "the", "insert", "stored", "procedure", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/hadoop/cql3/CqlBulkRecordWriter.java#L144-L161
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/transport/Frame.java
Frame.discard
private static long discard(ByteBuf buffer, long remainingToDiscard) { int availableToDiscard = (int) Math.min(remainingToDiscard, buffer.readableBytes()); buffer.skipBytes(availableToDiscard); return remainingToDiscard - availableToDiscard; }
java
private static long discard(ByteBuf buffer, long remainingToDiscard) { int availableToDiscard = (int) Math.min(remainingToDiscard, buffer.readableBytes()); buffer.skipBytes(availableToDiscard); return remainingToDiscard - availableToDiscard; }
[ "private", "static", "long", "discard", "(", "ByteBuf", "buffer", ",", "long", "remainingToDiscard", ")", "{", "int", "availableToDiscard", "=", "(", "int", ")", "Math", ".", "min", "(", "remainingToDiscard", ",", "buffer", ".", "readableBytes", "(", ")", ")...
How much remains to be discarded
[ "How", "much", "remains", "to", "be", "discarded" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/transport/Frame.java#L280-L285
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/io/sstable/SSTable.java
SSTable.delete
public static boolean delete(Descriptor desc, Set<Component> components) { // remove the DATA component first if it exists if (components.contains(Component.DATA)) FileUtils.deleteWithConfirm(desc.filenameFor(Component.DATA)); for (Component component : components) { if (component.equals(Component.DATA) || component.equals(Component.SUMMARY)) continue; FileUtils.deleteWithConfirm(desc.filenameFor(component)); } FileUtils.delete(desc.filenameFor(Component.SUMMARY)); logger.debug("Deleted {}", desc); return true; }
java
public static boolean delete(Descriptor desc, Set<Component> components) { // remove the DATA component first if it exists if (components.contains(Component.DATA)) FileUtils.deleteWithConfirm(desc.filenameFor(Component.DATA)); for (Component component : components) { if (component.equals(Component.DATA) || component.equals(Component.SUMMARY)) continue; FileUtils.deleteWithConfirm(desc.filenameFor(component)); } FileUtils.delete(desc.filenameFor(Component.SUMMARY)); logger.debug("Deleted {}", desc); return true; }
[ "public", "static", "boolean", "delete", "(", "Descriptor", "desc", ",", "Set", "<", "Component", ">", "components", ")", "{", "// remove the DATA component first if it exists", "if", "(", "components", ".", "contains", "(", "Component", ".", "DATA", ")", ")", "...
We use a ReferenceQueue to manage deleting files that have been compacted and for which no more SSTable references exist. But this is not guaranteed to run for each such file because of the semantics of the JVM gc. So, we write a marker to `compactedFilename` when a file is compacted; if such a marker exists on startup, the file should be removed. This method will also remove SSTables that are marked as temporary. @return true if the file was deleted
[ "We", "use", "a", "ReferenceQueue", "to", "manage", "deleting", "files", "that", "have", "been", "compacted", "and", "for", "which", "no", "more", "SSTable", "references", "exist", ".", "But", "this", "is", "not", "guaranteed", "to", "run", "for", "each", ...
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/io/sstable/SSTable.java#L104-L120
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/io/sstable/SSTable.java
SSTable.getMinimalKey
public static DecoratedKey getMinimalKey(DecoratedKey key) { return key.getKey().position() > 0 || key.getKey().hasRemaining() || !key.getKey().hasArray() ? new BufferDecoratedKey(key.getToken(), HeapAllocator.instance.clone(key.getKey())) : key; }
java
public static DecoratedKey getMinimalKey(DecoratedKey key) { return key.getKey().position() > 0 || key.getKey().hasRemaining() || !key.getKey().hasArray() ? new BufferDecoratedKey(key.getToken(), HeapAllocator.instance.clone(key.getKey())) : key; }
[ "public", "static", "DecoratedKey", "getMinimalKey", "(", "DecoratedKey", "key", ")", "{", "return", "key", ".", "getKey", "(", ")", ".", "position", "(", ")", ">", "0", "||", "key", ".", "getKey", "(", ")", ".", "hasRemaining", "(", ")", "||", "!", ...
If the given @param key occupies only part of a larger buffer, allocate a new buffer that is only as large as necessary.
[ "If", "the", "given" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/io/sstable/SSTable.java#L126-L131
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/io/sstable/SSTable.java
SSTable.readTOC
protected static Set<Component> readTOC(Descriptor descriptor) throws IOException { File tocFile = new File(descriptor.filenameFor(Component.TOC)); List<String> componentNames = Files.readLines(tocFile, Charset.defaultCharset()); Set<Component> components = Sets.newHashSetWithExpectedSize(componentNames.size()); for (String componentName : componentNames) { Component component = new Component(Component.Type.fromRepresentation(componentName), componentName); if (!new File(descriptor.filenameFor(component)).exists()) logger.error("Missing component: {}", descriptor.filenameFor(component)); else components.add(component); } return components; }
java
protected static Set<Component> readTOC(Descriptor descriptor) throws IOException { File tocFile = new File(descriptor.filenameFor(Component.TOC)); List<String> componentNames = Files.readLines(tocFile, Charset.defaultCharset()); Set<Component> components = Sets.newHashSetWithExpectedSize(componentNames.size()); for (String componentName : componentNames) { Component component = new Component(Component.Type.fromRepresentation(componentName), componentName); if (!new File(descriptor.filenameFor(component)).exists()) logger.error("Missing component: {}", descriptor.filenameFor(component)); else components.add(component); } return components; }
[ "protected", "static", "Set", "<", "Component", ">", "readTOC", "(", "Descriptor", "descriptor", ")", "throws", "IOException", "{", "File", "tocFile", "=", "new", "File", "(", "descriptor", ".", "filenameFor", "(", "Component", ".", "TOC", ")", ")", ";", "...
Reads the list of components from the TOC component. @return set of components found in the TOC
[ "Reads", "the", "list", "of", "components", "from", "the", "TOC", "component", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/io/sstable/SSTable.java#L252-L266
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/io/sstable/SSTable.java
SSTable.appendTOC
protected static void appendTOC(Descriptor descriptor, Collection<Component> components) { File tocFile = new File(descriptor.filenameFor(Component.TOC)); PrintWriter w = null; try { w = new PrintWriter(new FileWriter(tocFile, true)); for (Component component : components) w.println(component.name); } catch (IOException e) { throw new FSWriteError(e, tocFile); } finally { FileUtils.closeQuietly(w); } }
java
protected static void appendTOC(Descriptor descriptor, Collection<Component> components) { File tocFile = new File(descriptor.filenameFor(Component.TOC)); PrintWriter w = null; try { w = new PrintWriter(new FileWriter(tocFile, true)); for (Component component : components) w.println(component.name); } catch (IOException e) { throw new FSWriteError(e, tocFile); } finally { FileUtils.closeQuietly(w); } }
[ "protected", "static", "void", "appendTOC", "(", "Descriptor", "descriptor", ",", "Collection", "<", "Component", ">", "components", ")", "{", "File", "tocFile", "=", "new", "File", "(", "descriptor", ".", "filenameFor", "(", "Component", ".", "TOC", ")", ")...
Appends new component names to the TOC component.
[ "Appends", "new", "component", "names", "to", "the", "TOC", "component", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/io/sstable/SSTable.java#L271-L289
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/io/sstable/SSTable.java
SSTable.addComponents
public synchronized void addComponents(Collection<Component> newComponents) { Collection<Component> componentsToAdd = Collections2.filter(newComponents, Predicates.not(Predicates.in(components))); appendTOC(descriptor, componentsToAdd); components.addAll(componentsToAdd); }
java
public synchronized void addComponents(Collection<Component> newComponents) { Collection<Component> componentsToAdd = Collections2.filter(newComponents, Predicates.not(Predicates.in(components))); appendTOC(descriptor, componentsToAdd); components.addAll(componentsToAdd); }
[ "public", "synchronized", "void", "addComponents", "(", "Collection", "<", "Component", ">", "newComponents", ")", "{", "Collection", "<", "Component", ">", "componentsToAdd", "=", "Collections2", ".", "filter", "(", "newComponents", ",", "Predicates", ".", "not",...
Registers new custom components. Used by custom compaction strategies. Adding a component for the second time is a no-op. Don't remove this - this method is a part of the public API, intended for use by custom compaction strategies. @param newComponents collection of components to be added
[ "Registers", "new", "custom", "components", ".", "Used", "by", "custom", "compaction", "strategies", ".", "Adding", "a", "component", "for", "the", "second", "time", "is", "a", "no", "-", "op", ".", "Don", "t", "remove", "this", "-", "this", "method", "i...
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/io/sstable/SSTable.java#L297-L302
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/io/sstable/metadata/LegacyMetadataSerializer.java
LegacyMetadataSerializer.serialize
@Override public void serialize(Map<MetadataType, MetadataComponent> components, DataOutputPlus out) throws IOException { ValidationMetadata validation = (ValidationMetadata) components.get(MetadataType.VALIDATION); StatsMetadata stats = (StatsMetadata) components.get(MetadataType.STATS); CompactionMetadata compaction = (CompactionMetadata) components.get(MetadataType.COMPACTION); assert validation != null && stats != null && compaction != null && validation.partitioner != null; EstimatedHistogram.serializer.serialize(stats.estimatedRowSize, out); EstimatedHistogram.serializer.serialize(stats.estimatedColumnCount, out); ReplayPosition.serializer.serialize(stats.replayPosition, out); out.writeLong(stats.minTimestamp); out.writeLong(stats.maxTimestamp); out.writeInt(stats.maxLocalDeletionTime); out.writeDouble(validation.bloomFilterFPChance); out.writeDouble(stats.compressionRatio); out.writeUTF(validation.partitioner); out.writeInt(compaction.ancestors.size()); for (Integer g : compaction.ancestors) out.writeInt(g); StreamingHistogram.serializer.serialize(stats.estimatedTombstoneDropTime, out); out.writeInt(stats.sstableLevel); out.writeInt(stats.minColumnNames.size()); for (ByteBuffer columnName : stats.minColumnNames) ByteBufferUtil.writeWithShortLength(columnName, out); out.writeInt(stats.maxColumnNames.size()); for (ByteBuffer columnName : stats.maxColumnNames) ByteBufferUtil.writeWithShortLength(columnName, out); }
java
@Override public void serialize(Map<MetadataType, MetadataComponent> components, DataOutputPlus out) throws IOException { ValidationMetadata validation = (ValidationMetadata) components.get(MetadataType.VALIDATION); StatsMetadata stats = (StatsMetadata) components.get(MetadataType.STATS); CompactionMetadata compaction = (CompactionMetadata) components.get(MetadataType.COMPACTION); assert validation != null && stats != null && compaction != null && validation.partitioner != null; EstimatedHistogram.serializer.serialize(stats.estimatedRowSize, out); EstimatedHistogram.serializer.serialize(stats.estimatedColumnCount, out); ReplayPosition.serializer.serialize(stats.replayPosition, out); out.writeLong(stats.minTimestamp); out.writeLong(stats.maxTimestamp); out.writeInt(stats.maxLocalDeletionTime); out.writeDouble(validation.bloomFilterFPChance); out.writeDouble(stats.compressionRatio); out.writeUTF(validation.partitioner); out.writeInt(compaction.ancestors.size()); for (Integer g : compaction.ancestors) out.writeInt(g); StreamingHistogram.serializer.serialize(stats.estimatedTombstoneDropTime, out); out.writeInt(stats.sstableLevel); out.writeInt(stats.minColumnNames.size()); for (ByteBuffer columnName : stats.minColumnNames) ByteBufferUtil.writeWithShortLength(columnName, out); out.writeInt(stats.maxColumnNames.size()); for (ByteBuffer columnName : stats.maxColumnNames) ByteBufferUtil.writeWithShortLength(columnName, out); }
[ "@", "Override", "public", "void", "serialize", "(", "Map", "<", "MetadataType", ",", "MetadataComponent", ">", "components", ",", "DataOutputPlus", "out", ")", "throws", "IOException", "{", "ValidationMetadata", "validation", "=", "(", "ValidationMetadata", ")", ...
Legacy serialization is only used for SSTable level reset.
[ "Legacy", "serialization", "is", "only", "used", "for", "SSTable", "level", "reset", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/io/sstable/metadata/LegacyMetadataSerializer.java#L44-L73
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/io/sstable/metadata/LegacyMetadataSerializer.java
LegacyMetadataSerializer.deserialize
@Override public Map<MetadataType, MetadataComponent> deserialize(Descriptor descriptor, EnumSet<MetadataType> types) throws IOException { Map<MetadataType, MetadataComponent> components = Maps.newHashMap(); File statsFile = new File(descriptor.filenameFor(Component.STATS)); if (!statsFile.exists() && types.contains(MetadataType.STATS)) { components.put(MetadataType.STATS, MetadataCollector.defaultStatsMetadata()); } else { try (DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(statsFile)))) { EstimatedHistogram rowSizes = EstimatedHistogram.serializer.deserialize(in); EstimatedHistogram columnCounts = EstimatedHistogram.serializer.deserialize(in); ReplayPosition replayPosition = ReplayPosition.serializer.deserialize(in); long minTimestamp = in.readLong(); long maxTimestamp = in.readLong(); int maxLocalDeletionTime = in.readInt(); double bloomFilterFPChance = in.readDouble(); double compressionRatio = in.readDouble(); String partitioner = in.readUTF(); int nbAncestors = in.readInt(); Set<Integer> ancestors = new HashSet<>(nbAncestors); for (int i = 0; i < nbAncestors; i++) ancestors.add(in.readInt()); StreamingHistogram tombstoneHistogram = StreamingHistogram.serializer.deserialize(in); int sstableLevel = 0; if (in.available() > 0) sstableLevel = in.readInt(); int colCount = in.readInt(); List<ByteBuffer> minColumnNames = new ArrayList<>(colCount); for (int i = 0; i < colCount; i++) minColumnNames.add(ByteBufferUtil.readWithShortLength(in)); colCount = in.readInt(); List<ByteBuffer> maxColumnNames = new ArrayList<>(colCount); for (int i = 0; i < colCount; i++) maxColumnNames.add(ByteBufferUtil.readWithShortLength(in)); if (types.contains(MetadataType.VALIDATION)) components.put(MetadataType.VALIDATION, new ValidationMetadata(partitioner, bloomFilterFPChance)); if (types.contains(MetadataType.STATS)) components.put(MetadataType.STATS, new StatsMetadata(rowSizes, columnCounts, replayPosition, minTimestamp, maxTimestamp, maxLocalDeletionTime, compressionRatio, tombstoneHistogram, sstableLevel, minColumnNames, maxColumnNames, true, ActiveRepairService.UNREPAIRED_SSTABLE)); if (types.contains(MetadataType.COMPACTION)) components.put(MetadataType.COMPACTION, new CompactionMetadata(ancestors, null)); } } return components; }
java
@Override public Map<MetadataType, MetadataComponent> deserialize(Descriptor descriptor, EnumSet<MetadataType> types) throws IOException { Map<MetadataType, MetadataComponent> components = Maps.newHashMap(); File statsFile = new File(descriptor.filenameFor(Component.STATS)); if (!statsFile.exists() && types.contains(MetadataType.STATS)) { components.put(MetadataType.STATS, MetadataCollector.defaultStatsMetadata()); } else { try (DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(statsFile)))) { EstimatedHistogram rowSizes = EstimatedHistogram.serializer.deserialize(in); EstimatedHistogram columnCounts = EstimatedHistogram.serializer.deserialize(in); ReplayPosition replayPosition = ReplayPosition.serializer.deserialize(in); long minTimestamp = in.readLong(); long maxTimestamp = in.readLong(); int maxLocalDeletionTime = in.readInt(); double bloomFilterFPChance = in.readDouble(); double compressionRatio = in.readDouble(); String partitioner = in.readUTF(); int nbAncestors = in.readInt(); Set<Integer> ancestors = new HashSet<>(nbAncestors); for (int i = 0; i < nbAncestors; i++) ancestors.add(in.readInt()); StreamingHistogram tombstoneHistogram = StreamingHistogram.serializer.deserialize(in); int sstableLevel = 0; if (in.available() > 0) sstableLevel = in.readInt(); int colCount = in.readInt(); List<ByteBuffer> minColumnNames = new ArrayList<>(colCount); for (int i = 0; i < colCount; i++) minColumnNames.add(ByteBufferUtil.readWithShortLength(in)); colCount = in.readInt(); List<ByteBuffer> maxColumnNames = new ArrayList<>(colCount); for (int i = 0; i < colCount; i++) maxColumnNames.add(ByteBufferUtil.readWithShortLength(in)); if (types.contains(MetadataType.VALIDATION)) components.put(MetadataType.VALIDATION, new ValidationMetadata(partitioner, bloomFilterFPChance)); if (types.contains(MetadataType.STATS)) components.put(MetadataType.STATS, new StatsMetadata(rowSizes, columnCounts, replayPosition, minTimestamp, maxTimestamp, maxLocalDeletionTime, compressionRatio, tombstoneHistogram, sstableLevel, minColumnNames, maxColumnNames, true, ActiveRepairService.UNREPAIRED_SSTABLE)); if (types.contains(MetadataType.COMPACTION)) components.put(MetadataType.COMPACTION, new CompactionMetadata(ancestors, null)); } } return components; }
[ "@", "Override", "public", "Map", "<", "MetadataType", ",", "MetadataComponent", ">", "deserialize", "(", "Descriptor", "descriptor", ",", "EnumSet", "<", "MetadataType", ">", "types", ")", "throws", "IOException", "{", "Map", "<", "MetadataType", ",", "Metadata...
Legacy serializer deserialize all components no matter what types are specified.
[ "Legacy", "serializer", "deserialize", "all", "components", "no", "matter", "what", "types", "are", "specified", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/io/sstable/metadata/LegacyMetadataSerializer.java#L78-L144
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/streaming/ConnectionHandler.java
ConnectionHandler.initiate
public void initiate() throws IOException { logger.debug("[Stream #{}] Sending stream init for incoming stream", session.planId()); Socket incomingSocket = session.createConnection(); incoming.start(incomingSocket, StreamMessage.CURRENT_VERSION); incoming.sendInitMessage(incomingSocket, true); logger.debug("[Stream #{}] Sending stream init for outgoing stream", session.planId()); Socket outgoingSocket = session.createConnection(); outgoing.start(outgoingSocket, StreamMessage.CURRENT_VERSION); outgoing.sendInitMessage(outgoingSocket, false); }
java
public void initiate() throws IOException { logger.debug("[Stream #{}] Sending stream init for incoming stream", session.planId()); Socket incomingSocket = session.createConnection(); incoming.start(incomingSocket, StreamMessage.CURRENT_VERSION); incoming.sendInitMessage(incomingSocket, true); logger.debug("[Stream #{}] Sending stream init for outgoing stream", session.planId()); Socket outgoingSocket = session.createConnection(); outgoing.start(outgoingSocket, StreamMessage.CURRENT_VERSION); outgoing.sendInitMessage(outgoingSocket, false); }
[ "public", "void", "initiate", "(", ")", "throws", "IOException", "{", "logger", ".", "debug", "(", "\"[Stream #{}] Sending stream init for incoming stream\"", ",", "session", ".", "planId", "(", ")", ")", ";", "Socket", "incomingSocket", "=", "session", ".", "crea...
Set up incoming message handler and initiate streaming. This method is called once on initiator. @throws IOException
[ "Set", "up", "incoming", "message", "handler", "and", "initiate", "streaming", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/streaming/ConnectionHandler.java#L76-L87
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/streaming/ConnectionHandler.java
ConnectionHandler.initiateOnReceivingSide
public void initiateOnReceivingSide(Socket socket, boolean isForOutgoing, int version) throws IOException { if (isForOutgoing) outgoing.start(socket, version); else incoming.start(socket, version); }
java
public void initiateOnReceivingSide(Socket socket, boolean isForOutgoing, int version) throws IOException { if (isForOutgoing) outgoing.start(socket, version); else incoming.start(socket, version); }
[ "public", "void", "initiateOnReceivingSide", "(", "Socket", "socket", ",", "boolean", "isForOutgoing", ",", "int", "version", ")", "throws", "IOException", "{", "if", "(", "isForOutgoing", ")", "outgoing", ".", "start", "(", "socket", ",", "version", ")", ";",...
Set up outgoing message handler on receiving side. @param socket socket to use for {@link org.apache.cassandra.streaming.ConnectionHandler.OutgoingMessageHandler}. @param version Streaming message version @throws IOException
[ "Set", "up", "outgoing", "message", "handler", "on", "receiving", "side", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/streaming/ConnectionHandler.java#L96-L102
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/io/sstable/IndexSummaryBuilder.java
IndexSummaryBuilder.setNextSamplePosition
private void setNextSamplePosition(long position) { tryAgain: while (true) { position += minIndexInterval; long test = indexIntervalMatches++; for (int start : startPoints) if ((test - start) % BASE_SAMPLING_LEVEL == 0) continue tryAgain; nextSamplePosition = position; return; } }
java
private void setNextSamplePosition(long position) { tryAgain: while (true) { position += minIndexInterval; long test = indexIntervalMatches++; for (int start : startPoints) if ((test - start) % BASE_SAMPLING_LEVEL == 0) continue tryAgain; nextSamplePosition = position; return; } }
[ "private", "void", "setNextSamplePosition", "(", "long", "position", ")", "{", "tryAgain", ":", "while", "(", "true", ")", "{", "position", "+=", "minIndexInterval", ";", "long", "test", "=", "indexIntervalMatches", "++", ";", "for", "(", "int", "start", ":"...
calculate the next key we will store to our summary
[ "calculate", "the", "next", "key", "we", "will", "store", "to", "our", "summary" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/io/sstable/IndexSummaryBuilder.java#L190-L203
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/io/sstable/IndexSummaryBuilder.java
IndexSummaryBuilder.build
public IndexSummary build(IPartitioner partitioner, ReadableBoundary boundary) { assert entries.length() > 0; int count = (int) (offsets.length() / 4); long entriesLength = entries.length(); if (boundary != null) { count = boundary.summaryCount; entriesLength = boundary.entriesLength; } int sizeAtFullSampling = (int) Math.ceil(keysWritten / (double) minIndexInterval); assert count > 0; return new IndexSummary(partitioner, offsets.currentBuffer().sharedCopy(), count, entries.currentBuffer().sharedCopy(), entriesLength, sizeAtFullSampling, minIndexInterval, samplingLevel); }
java
public IndexSummary build(IPartitioner partitioner, ReadableBoundary boundary) { assert entries.length() > 0; int count = (int) (offsets.length() / 4); long entriesLength = entries.length(); if (boundary != null) { count = boundary.summaryCount; entriesLength = boundary.entriesLength; } int sizeAtFullSampling = (int) Math.ceil(keysWritten / (double) minIndexInterval); assert count > 0; return new IndexSummary(partitioner, offsets.currentBuffer().sharedCopy(), count, entries.currentBuffer().sharedCopy(), entriesLength, sizeAtFullSampling, minIndexInterval, samplingLevel); }
[ "public", "IndexSummary", "build", "(", "IPartitioner", "partitioner", ",", "ReadableBoundary", "boundary", ")", "{", "assert", "entries", ".", "length", "(", ")", ">", "0", ";", "int", "count", "=", "(", "int", ")", "(", "offsets", ".", "length", "(", "...
multiple invocations of this build method
[ "multiple", "invocations", "of", "this", "build", "method" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/io/sstable/IndexSummaryBuilder.java#L216-L233
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/io/sstable/IndexSummaryBuilder.java
IndexSummaryBuilder.downsample
public static IndexSummary downsample(IndexSummary existing, int newSamplingLevel, int minIndexInterval, IPartitioner partitioner) { // To downsample the old index summary, we'll go through (potentially) several rounds of downsampling. // Conceptually, each round starts at position X and then removes every Nth item. The value of X follows // a particular pattern to evenly space out the items that we remove. The value of N decreases by one each // round. int currentSamplingLevel = existing.getSamplingLevel(); assert currentSamplingLevel > newSamplingLevel; assert minIndexInterval == existing.getMinIndexInterval(); // calculate starting indexes for downsampling rounds int[] startPoints = Downsampling.getStartPoints(currentSamplingLevel, newSamplingLevel); // calculate new off-heap size int newKeyCount = existing.size(); long newEntriesLength = existing.getEntriesLength(); for (int start : startPoints) { for (int j = start; j < existing.size(); j += currentSamplingLevel) { newKeyCount--; long length = existing.getEndInSummary(j) - existing.getPositionInSummary(j); newEntriesLength -= length; } } Memory oldEntries = existing.getEntries(); Memory newOffsets = Memory.allocate(newKeyCount * 4); Memory newEntries = Memory.allocate(newEntriesLength); // Copy old entries to our new Memory. int i = 0; int newEntriesOffset = 0; outer: for (int oldSummaryIndex = 0; oldSummaryIndex < existing.size(); oldSummaryIndex++) { // to determine if we can skip this entry, go through the starting points for our downsampling rounds // and see if the entry's index is covered by that round for (int start : startPoints) { if ((oldSummaryIndex - start) % currentSamplingLevel == 0) continue outer; } // write the position of the actual entry in the index summary (4 bytes) newOffsets.setInt(i * 4, newEntriesOffset); i++; long start = existing.getPositionInSummary(oldSummaryIndex); long length = existing.getEndInSummary(oldSummaryIndex) - start; newEntries.put(newEntriesOffset, oldEntries, start, length); newEntriesOffset += length; } assert newEntriesOffset == newEntriesLength; return new IndexSummary(partitioner, newOffsets, newKeyCount, newEntries, newEntriesLength, existing.getMaxNumberOfEntries(), minIndexInterval, newSamplingLevel); }
java
public static IndexSummary downsample(IndexSummary existing, int newSamplingLevel, int minIndexInterval, IPartitioner partitioner) { // To downsample the old index summary, we'll go through (potentially) several rounds of downsampling. // Conceptually, each round starts at position X and then removes every Nth item. The value of X follows // a particular pattern to evenly space out the items that we remove. The value of N decreases by one each // round. int currentSamplingLevel = existing.getSamplingLevel(); assert currentSamplingLevel > newSamplingLevel; assert minIndexInterval == existing.getMinIndexInterval(); // calculate starting indexes for downsampling rounds int[] startPoints = Downsampling.getStartPoints(currentSamplingLevel, newSamplingLevel); // calculate new off-heap size int newKeyCount = existing.size(); long newEntriesLength = existing.getEntriesLength(); for (int start : startPoints) { for (int j = start; j < existing.size(); j += currentSamplingLevel) { newKeyCount--; long length = existing.getEndInSummary(j) - existing.getPositionInSummary(j); newEntriesLength -= length; } } Memory oldEntries = existing.getEntries(); Memory newOffsets = Memory.allocate(newKeyCount * 4); Memory newEntries = Memory.allocate(newEntriesLength); // Copy old entries to our new Memory. int i = 0; int newEntriesOffset = 0; outer: for (int oldSummaryIndex = 0; oldSummaryIndex < existing.size(); oldSummaryIndex++) { // to determine if we can skip this entry, go through the starting points for our downsampling rounds // and see if the entry's index is covered by that round for (int start : startPoints) { if ((oldSummaryIndex - start) % currentSamplingLevel == 0) continue outer; } // write the position of the actual entry in the index summary (4 bytes) newOffsets.setInt(i * 4, newEntriesOffset); i++; long start = existing.getPositionInSummary(oldSummaryIndex); long length = existing.getEndInSummary(oldSummaryIndex) - start; newEntries.put(newEntriesOffset, oldEntries, start, length); newEntriesOffset += length; } assert newEntriesOffset == newEntriesLength; return new IndexSummary(partitioner, newOffsets, newKeyCount, newEntries, newEntriesLength, existing.getMaxNumberOfEntries(), minIndexInterval, newSamplingLevel); }
[ "public", "static", "IndexSummary", "downsample", "(", "IndexSummary", "existing", ",", "int", "newSamplingLevel", ",", "int", "minIndexInterval", ",", "IPartitioner", "partitioner", ")", "{", "// To downsample the old index summary, we'll go through (potentially) several rounds ...
Downsamples an existing index summary to a new sampling level. @param existing an existing IndexSummary @param newSamplingLevel the target level for the new IndexSummary. This must be less than the current sampling level for `existing`. @param partitioner the partitioner used for the index summary @return a new IndexSummary
[ "Downsamples", "an", "existing", "index", "summary", "to", "a", "new", "sampling", "level", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/io/sstable/IndexSummaryBuilder.java#L272-L328
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/utils/StreamingHistogram.java
StreamingHistogram.update
public void update(double p, long m) { Long mi = bin.get(p); if (mi != null) { // we found the same p so increment that counter bin.put(p, mi + m); } else { bin.put(p, m); // if bin size exceeds maximum bin size then trim down to max size while (bin.size() > maxBinSize) { // find points p1, p2 which have smallest difference Iterator<Double> keys = bin.keySet().iterator(); double p1 = keys.next(); double p2 = keys.next(); double smallestDiff = p2 - p1; double q1 = p1, q2 = p2; while (keys.hasNext()) { p1 = p2; p2 = keys.next(); double diff = p2 - p1; if (diff < smallestDiff) { smallestDiff = diff; q1 = p1; q2 = p2; } } // merge those two long k1 = bin.remove(q1); long k2 = bin.remove(q2); bin.put((q1 * k1 + q2 * k2) / (k1 + k2), k1 + k2); } } }
java
public void update(double p, long m) { Long mi = bin.get(p); if (mi != null) { // we found the same p so increment that counter bin.put(p, mi + m); } else { bin.put(p, m); // if bin size exceeds maximum bin size then trim down to max size while (bin.size() > maxBinSize) { // find points p1, p2 which have smallest difference Iterator<Double> keys = bin.keySet().iterator(); double p1 = keys.next(); double p2 = keys.next(); double smallestDiff = p2 - p1; double q1 = p1, q2 = p2; while (keys.hasNext()) { p1 = p2; p2 = keys.next(); double diff = p2 - p1; if (diff < smallestDiff) { smallestDiff = diff; q1 = p1; q2 = p2; } } // merge those two long k1 = bin.remove(q1); long k2 = bin.remove(q2); bin.put((q1 * k1 + q2 * k2) / (k1 + k2), k1 + k2); } } }
[ "public", "void", "update", "(", "double", "p", ",", "long", "m", ")", "{", "Long", "mi", "=", "bin", ".", "get", "(", "p", ")", ";", "if", "(", "mi", "!=", "null", ")", "{", "// we found the same p so increment that counter", "bin", ".", "put", "(", ...
Adds new point p with value m to this histogram. @param p @param m
[ "Adds", "new", "point", "p", "with", "value", "m", "to", "this", "histogram", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/utils/StreamingHistogram.java#L77-L115
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/db/compaction/CompactionManager.java
CompactionManager.getRateLimiter
public RateLimiter getRateLimiter() { double currentThroughput = DatabaseDescriptor.getCompactionThroughputMbPerSec() * 1024.0 * 1024.0; // if throughput is set to 0, throttling is disabled if (currentThroughput == 0 || StorageService.instance.isBootstrapMode()) currentThroughput = Double.MAX_VALUE; if (compactionRateLimiter.getRate() != currentThroughput) compactionRateLimiter.setRate(currentThroughput); return compactionRateLimiter; }
java
public RateLimiter getRateLimiter() { double currentThroughput = DatabaseDescriptor.getCompactionThroughputMbPerSec() * 1024.0 * 1024.0; // if throughput is set to 0, throttling is disabled if (currentThroughput == 0 || StorageService.instance.isBootstrapMode()) currentThroughput = Double.MAX_VALUE; if (compactionRateLimiter.getRate() != currentThroughput) compactionRateLimiter.setRate(currentThroughput); return compactionRateLimiter; }
[ "public", "RateLimiter", "getRateLimiter", "(", ")", "{", "double", "currentThroughput", "=", "DatabaseDescriptor", ".", "getCompactionThroughputMbPerSec", "(", ")", "*", "1024.0", "*", "1024.0", ";", "// if throughput is set to 0, throttling is disabled", "if", "(", "cur...
Gets compaction rate limiter. When compaction_throughput_mb_per_sec is 0 or node is bootstrapping, this returns rate limiter with the rate of Double.MAX_VALUE bytes per second. Rate unit is bytes per sec. @return RateLimiter with rate limit set
[ "Gets", "compaction", "rate", "limiter", ".", "When", "compaction_throughput_mb_per_sec", "is", "0", "or", "node", "is", "bootstrapping", "this", "returns", "rate", "limiter", "with", "the", "rate", "of", "Double", ".", "MAX_VALUE", "bytes", "per", "second", "."...
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/compaction/CompactionManager.java#L145-L154
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/db/compaction/CompactionManager.java
CompactionManager.lookupSSTable
private SSTableReader lookupSSTable(final ColumnFamilyStore cfs, Descriptor descriptor) { for (SSTableReader sstable : cfs.getSSTables()) { if (sstable.descriptor.equals(descriptor)) return sstable; } return null; }
java
private SSTableReader lookupSSTable(final ColumnFamilyStore cfs, Descriptor descriptor) { for (SSTableReader sstable : cfs.getSSTables()) { if (sstable.descriptor.equals(descriptor)) return sstable; } return null; }
[ "private", "SSTableReader", "lookupSSTable", "(", "final", "ColumnFamilyStore", "cfs", ",", "Descriptor", "descriptor", ")", "{", "for", "(", "SSTableReader", "sstable", ":", "cfs", ".", "getSSTables", "(", ")", ")", "{", "if", "(", "sstable", ".", "descriptor...
This is not efficient, do not use in any critical path
[ "This", "is", "not", "efficient", "do", "not", "use", "in", "any", "critical", "path" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/compaction/CompactionManager.java#L596-L604
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/db/compaction/CompactionManager.java
CompactionManager.submitValidation
public Future<Object> submitValidation(final ColumnFamilyStore cfStore, final Validator validator) { Callable<Object> callable = new Callable<Object>() { public Object call() throws IOException { try { doValidationCompaction(cfStore, validator); } catch (Throwable e) { // we need to inform the remote end of our failure, otherwise it will hang on repair forever validator.fail(); throw e; } return this; } }; return validationExecutor.submit(callable); }
java
public Future<Object> submitValidation(final ColumnFamilyStore cfStore, final Validator validator) { Callable<Object> callable = new Callable<Object>() { public Object call() throws IOException { try { doValidationCompaction(cfStore, validator); } catch (Throwable e) { // we need to inform the remote end of our failure, otherwise it will hang on repair forever validator.fail(); throw e; } return this; } }; return validationExecutor.submit(callable); }
[ "public", "Future", "<", "Object", ">", "submitValidation", "(", "final", "ColumnFamilyStore", "cfStore", ",", "final", "Validator", "validator", ")", "{", "Callable", "<", "Object", ">", "callable", "=", "new", "Callable", "<", "Object", ">", "(", ")", "{",...
Does not mutate data, so is not scheduled.
[ "Does", "not", "mutate", "data", "so", "is", "not", "scheduled", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/compaction/CompactionManager.java#L609-L629
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/db/compaction/CompactionManager.java
CompactionManager.needsCleanup
static boolean needsCleanup(SSTableReader sstable, Collection<Range<Token>> ownedRanges) { assert !ownedRanges.isEmpty(); // cleanup checks for this // unwrap and sort the ranges by LHS token List<Range<Token>> sortedRanges = Range.normalize(ownedRanges); // see if there are any keys LTE the token for the start of the first range // (token range ownership is exclusive on the LHS.) Range<Token> firstRange = sortedRanges.get(0); if (sstable.first.getToken().compareTo(firstRange.left) <= 0) return true; // then, iterate over all owned ranges and see if the next key beyond the end of the owned // range falls before the start of the next range for (int i = 0; i < sortedRanges.size(); i++) { Range<Token> range = sortedRanges.get(i); if (range.right.isMinimum()) { // we split a wrapping range and this is the second half. // there can't be any keys beyond this (and this is the last range) return false; } DecoratedKey firstBeyondRange = sstable.firstKeyBeyond(range.right.maxKeyBound()); if (firstBeyondRange == null) { // we ran off the end of the sstable looking for the next key; we don't need to check any more ranges return false; } if (i == (sortedRanges.size() - 1)) { // we're at the last range and we found a key beyond the end of the range return true; } Range<Token> nextRange = sortedRanges.get(i + 1); if (!nextRange.contains(firstBeyondRange.getToken())) { // we found a key in between the owned ranges return true; } } return false; }
java
static boolean needsCleanup(SSTableReader sstable, Collection<Range<Token>> ownedRanges) { assert !ownedRanges.isEmpty(); // cleanup checks for this // unwrap and sort the ranges by LHS token List<Range<Token>> sortedRanges = Range.normalize(ownedRanges); // see if there are any keys LTE the token for the start of the first range // (token range ownership is exclusive on the LHS.) Range<Token> firstRange = sortedRanges.get(0); if (sstable.first.getToken().compareTo(firstRange.left) <= 0) return true; // then, iterate over all owned ranges and see if the next key beyond the end of the owned // range falls before the start of the next range for (int i = 0; i < sortedRanges.size(); i++) { Range<Token> range = sortedRanges.get(i); if (range.right.isMinimum()) { // we split a wrapping range and this is the second half. // there can't be any keys beyond this (and this is the last range) return false; } DecoratedKey firstBeyondRange = sstable.firstKeyBeyond(range.right.maxKeyBound()); if (firstBeyondRange == null) { // we ran off the end of the sstable looking for the next key; we don't need to check any more ranges return false; } if (i == (sortedRanges.size() - 1)) { // we're at the last range and we found a key beyond the end of the range return true; } Range<Token> nextRange = sortedRanges.get(i + 1); if (!nextRange.contains(firstBeyondRange.getToken())) { // we found a key in between the owned ranges return true; } } return false; }
[ "static", "boolean", "needsCleanup", "(", "SSTableReader", "sstable", ",", "Collection", "<", "Range", "<", "Token", ">", ">", "ownedRanges", ")", "{", "assert", "!", "ownedRanges", ".", "isEmpty", "(", ")", ";", "// cleanup checks for this", "// unwrap and sort t...
Determines if a cleanup would actually remove any data in this SSTable based on a set of owned ranges.
[ "Determines", "if", "a", "cleanup", "would", "actually", "remove", "any", "data", "in", "this", "SSTable", "based", "on", "a", "set", "of", "owned", "ranges", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/compaction/CompactionManager.java#L662-L709
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/db/compaction/CompactionManager.java
CompactionManager.submitIndexBuild
public Future<?> submitIndexBuild(final SecondaryIndexBuilder builder) { Runnable runnable = new Runnable() { public void run() { metrics.beginCompaction(builder); try { builder.build(); } finally { metrics.finishCompaction(builder); } } }; if (executor.isShutdown()) { logger.info("Compaction executor has shut down, not submitting index build"); return null; } return executor.submit(runnable); }
java
public Future<?> submitIndexBuild(final SecondaryIndexBuilder builder) { Runnable runnable = new Runnable() { public void run() { metrics.beginCompaction(builder); try { builder.build(); } finally { metrics.finishCompaction(builder); } } }; if (executor.isShutdown()) { logger.info("Compaction executor has shut down, not submitting index build"); return null; } return executor.submit(runnable); }
[ "public", "Future", "<", "?", ">", "submitIndexBuild", "(", "final", "SecondaryIndexBuilder", "builder", ")", "{", "Runnable", "runnable", "=", "new", "Runnable", "(", ")", "{", "public", "void", "run", "(", ")", "{", "metrics", ".", "beginCompaction", "(", ...
Is not scheduled, because it is performing disjoint work from sstable compaction.
[ "Is", "not", "scheduled", "because", "it", "is", "performing", "disjoint", "work", "from", "sstable", "compaction", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/compaction/CompactionManager.java#L1129-L1153
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/db/compaction/CompactionManager.java
CompactionManager.interruptCompactionFor
public void interruptCompactionFor(Iterable<CFMetaData> columnFamilies, boolean interruptValidation) { assert columnFamilies != null; // interrupt in-progress compactions for (Holder compactionHolder : CompactionMetrics.getCompactions()) { CompactionInfo info = compactionHolder.getCompactionInfo(); if ((info.getTaskType() == OperationType.VALIDATION) && !interruptValidation) continue; if (Iterables.contains(columnFamilies, info.getCFMetaData())) compactionHolder.stop(); // signal compaction to stop } }
java
public void interruptCompactionFor(Iterable<CFMetaData> columnFamilies, boolean interruptValidation) { assert columnFamilies != null; // interrupt in-progress compactions for (Holder compactionHolder : CompactionMetrics.getCompactions()) { CompactionInfo info = compactionHolder.getCompactionInfo(); if ((info.getTaskType() == OperationType.VALIDATION) && !interruptValidation) continue; if (Iterables.contains(columnFamilies, info.getCFMetaData())) compactionHolder.stop(); // signal compaction to stop } }
[ "public", "void", "interruptCompactionFor", "(", "Iterable", "<", "CFMetaData", ">", "columnFamilies", ",", "boolean", "interruptValidation", ")", "{", "assert", "columnFamilies", "!=", "null", ";", "// interrupt in-progress compactions", "for", "(", "Holder", "compacti...
Try to stop all of the compactions for given ColumnFamilies. Note that this method does not wait for all compactions to finish; you'll need to loop against isCompacting if you want that behavior. @param columnFamilies The ColumnFamilies to try to stop compaction upon. @param interruptValidation true if validation operations for repair should also be interrupted
[ "Try", "to", "stop", "all", "of", "the", "compactions", "for", "given", "ColumnFamilies", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/compaction/CompactionManager.java#L1454-L1468
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/db/ArrayBackedSortedColumns.java
ArrayBackedSortedColumns.fastAddAll
private void fastAddAll(ArrayBackedSortedColumns other) { if (other.isInsertReversed() == isInsertReversed()) { cells = Arrays.copyOf(other.cells, other.cells.length); size = other.size; sortedSize = other.sortedSize; isSorted = other.isSorted; } else { if (cells.length < other.getColumnCount()) cells = new Cell[Math.max(MINIMAL_CAPACITY, other.getColumnCount())]; Iterator<Cell> iterator = reversed ? other.reverseIterator() : other.iterator(); while (iterator.hasNext()) cells[size++] = iterator.next(); sortedSize = size; isSorted = true; } }
java
private void fastAddAll(ArrayBackedSortedColumns other) { if (other.isInsertReversed() == isInsertReversed()) { cells = Arrays.copyOf(other.cells, other.cells.length); size = other.size; sortedSize = other.sortedSize; isSorted = other.isSorted; } else { if (cells.length < other.getColumnCount()) cells = new Cell[Math.max(MINIMAL_CAPACITY, other.getColumnCount())]; Iterator<Cell> iterator = reversed ? other.reverseIterator() : other.iterator(); while (iterator.hasNext()) cells[size++] = iterator.next(); sortedSize = size; isSorted = true; } }
[ "private", "void", "fastAddAll", "(", "ArrayBackedSortedColumns", "other", ")", "{", "if", "(", "other", ".", "isInsertReversed", "(", ")", "==", "isInsertReversed", "(", ")", ")", "{", "cells", "=", "Arrays", ".", "copyOf", "(", "other", ".", "cells", ","...
Fast path, when this ABSC is empty.
[ "Fast", "path", "when", "this", "ABSC", "is", "empty", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/ArrayBackedSortedColumns.java#L354-L373
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/db/ArrayBackedSortedColumns.java
ArrayBackedSortedColumns.internalRemove
private void internalRemove(int index) { int moving = size - index - 1; if (moving > 0) System.arraycopy(cells, index + 1, cells, index, moving); cells[--size] = null; }
java
private void internalRemove(int index) { int moving = size - index - 1; if (moving > 0) System.arraycopy(cells, index + 1, cells, index, moving); cells[--size] = null; }
[ "private", "void", "internalRemove", "(", "int", "index", ")", "{", "int", "moving", "=", "size", "-", "index", "-", "1", ";", "if", "(", "moving", ">", "0", ")", "System", ".", "arraycopy", "(", "cells", ",", "index", "+", "1", ",", "cells", ",", ...
Remove the cell at a given index, shifting the rest of the array to the left if needed. Please note that we mostly remove from the end, so the shifting should be rare.
[ "Remove", "the", "cell", "at", "a", "given", "index", "shifting", "the", "rest", "of", "the", "array", "to", "the", "left", "if", "needed", ".", "Please", "note", "that", "we", "mostly", "remove", "from", "the", "end", "so", "the", "shifting", "should", ...
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/ArrayBackedSortedColumns.java#L389-L395
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/db/ArrayBackedSortedColumns.java
ArrayBackedSortedColumns.reconcileWith
private void reconcileWith(int i, Cell cell) { cells[i] = cell.reconcile(cells[i]); }
java
private void reconcileWith(int i, Cell cell) { cells[i] = cell.reconcile(cells[i]); }
[ "private", "void", "reconcileWith", "(", "int", "i", ",", "Cell", "cell", ")", "{", "cells", "[", "i", "]", "=", "cell", ".", "reconcile", "(", "cells", "[", "i", "]", ")", ";", "}" ]
Reconcile with a cell at position i. Assume that i is a valid position.
[ "Reconcile", "with", "a", "cell", "at", "position", "i", ".", "Assume", "that", "i", "is", "a", "valid", "position", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/ArrayBackedSortedColumns.java#L401-L404
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/utils/memory/SlabAllocator.java
SlabAllocator.getRegion
private Region getRegion() { while (true) { // Try to get the region Region region = currentRegion.get(); if (region != null) return region; // No current region, so we want to allocate one. We race // against other allocators to CAS in a Region, and if we fail we stash the region for re-use region = RACE_ALLOCATED.poll(); if (region == null) region = new Region(allocateOnHeapOnly ? ByteBuffer.allocate(REGION_SIZE) : ByteBuffer.allocateDirect(REGION_SIZE)); if (currentRegion.compareAndSet(null, region)) { if (!allocateOnHeapOnly) offHeapRegions.add(region); regionCount.incrementAndGet(); logger.trace("{} regions now allocated in {}", regionCount, this); return region; } // someone else won race - that's fine, we'll try to grab theirs // in the next iteration of the loop. RACE_ALLOCATED.add(region); } }
java
private Region getRegion() { while (true) { // Try to get the region Region region = currentRegion.get(); if (region != null) return region; // No current region, so we want to allocate one. We race // against other allocators to CAS in a Region, and if we fail we stash the region for re-use region = RACE_ALLOCATED.poll(); if (region == null) region = new Region(allocateOnHeapOnly ? ByteBuffer.allocate(REGION_SIZE) : ByteBuffer.allocateDirect(REGION_SIZE)); if (currentRegion.compareAndSet(null, region)) { if (!allocateOnHeapOnly) offHeapRegions.add(region); regionCount.incrementAndGet(); logger.trace("{} regions now allocated in {}", regionCount, this); return region; } // someone else won race - that's fine, we'll try to grab theirs // in the next iteration of the loop. RACE_ALLOCATED.add(region); } }
[ "private", "Region", "getRegion", "(", ")", "{", "while", "(", "true", ")", "{", "// Try to get the region", "Region", "region", "=", "currentRegion", ".", "get", "(", ")", ";", "if", "(", "region", "!=", "null", ")", "return", "region", ";", "// No curren...
Get the current region, or, if there is no current region, allocate a new one
[ "Get", "the", "current", "region", "or", "if", "there", "is", "no", "current", "region", "allocate", "a", "new", "one" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/utils/memory/SlabAllocator.java#L124-L151
train