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/io/sstable/IndexHelper.java | IndexHelper.skipIndex | public static void skipIndex(DataInput in) throws IOException
{
/* read only the column index list */
int columnIndexSize = in.readInt();
/* skip the column index data */
if (in instanceof FileDataInput)
{
FileUtils.skipBytesFully(in, columnIndexSize);
}
else
{
// skip bytes
byte[] skip = new byte[columnIndexSize];
in.readFully(skip);
}
} | java | public static void skipIndex(DataInput in) throws IOException
{
/* read only the column index list */
int columnIndexSize = in.readInt();
/* skip the column index data */
if (in instanceof FileDataInput)
{
FileUtils.skipBytesFully(in, columnIndexSize);
}
else
{
// skip bytes
byte[] skip = new byte[columnIndexSize];
in.readFully(skip);
}
} | [
"public",
"static",
"void",
"skipIndex",
"(",
"DataInput",
"in",
")",
"throws",
"IOException",
"{",
"/* read only the column index list */",
"int",
"columnIndexSize",
"=",
"in",
".",
"readInt",
"(",
")",
";",
"/* skip the column index data */",
"if",
"(",
"in",
"ins... | Skip the index
@param in the data input from which the index should be skipped
@throws IOException if an I/O error occurs. | [
"Skip",
"the",
"index"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/io/sstable/IndexHelper.java#L52-L67 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/io/sstable/IndexHelper.java | IndexHelper.deserializeIndex | public static List<IndexInfo> deserializeIndex(FileDataInput in, CType type) throws IOException
{
int columnIndexSize = in.readInt();
if (columnIndexSize == 0)
return Collections.<IndexInfo>emptyList();
ArrayList<IndexInfo> indexList = new ArrayList<IndexInfo>();
FileMark mark = in.mark();
ISerializer<IndexInfo> serializer = type.indexSerializer();
while (in.bytesPastMark(mark) < columnIndexSize)
{
indexList.add(serializer.deserialize(in));
}
assert in.bytesPastMark(mark) == columnIndexSize;
return indexList;
} | java | public static List<IndexInfo> deserializeIndex(FileDataInput in, CType type) throws IOException
{
int columnIndexSize = in.readInt();
if (columnIndexSize == 0)
return Collections.<IndexInfo>emptyList();
ArrayList<IndexInfo> indexList = new ArrayList<IndexInfo>();
FileMark mark = in.mark();
ISerializer<IndexInfo> serializer = type.indexSerializer();
while (in.bytesPastMark(mark) < columnIndexSize)
{
indexList.add(serializer.deserialize(in));
}
assert in.bytesPastMark(mark) == columnIndexSize;
return indexList;
} | [
"public",
"static",
"List",
"<",
"IndexInfo",
">",
"deserializeIndex",
"(",
"FileDataInput",
"in",
",",
"CType",
"type",
")",
"throws",
"IOException",
"{",
"int",
"columnIndexSize",
"=",
"in",
".",
"readInt",
"(",
")",
";",
"if",
"(",
"columnIndexSize",
"=="... | Deserialize the index into a structure and return it
@param in input source
@param type the comparator type for the column family
@return ArrayList<IndexInfo> - list of de-serialized indexes
@throws IOException if an I/O error occurs. | [
"Deserialize",
"the",
"index",
"into",
"a",
"structure",
"and",
"return",
"it"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/io/sstable/IndexHelper.java#L78-L93 | train |
Stratio/stratio-cassandra | tools/stress/src/org/apache/cassandra/stress/util/Timing.java | Timing.newTimer | public Timer newTimer(String opType, int sampleCount)
{
final Timer timer = new Timer(sampleCount);
if (!timers.containsKey(opType))
timers.put(opType, new ArrayList<Timer>());
timers.get(opType).add(timer);
return timer;
} | java | public Timer newTimer(String opType, int sampleCount)
{
final Timer timer = new Timer(sampleCount);
if (!timers.containsKey(opType))
timers.put(opType, new ArrayList<Timer>());
timers.get(opType).add(timer);
return timer;
} | [
"public",
"Timer",
"newTimer",
"(",
"String",
"opType",
",",
"int",
"sampleCount",
")",
"{",
"final",
"Timer",
"timer",
"=",
"new",
"Timer",
"(",
"sampleCount",
")",
";",
"if",
"(",
"!",
"timers",
".",
"containsKey",
"(",
"opType",
")",
")",
"timers",
... | build a new timer and add it to the set of running timers. | [
"build",
"a",
"new",
"timer",
"and",
"add",
"it",
"to",
"the",
"set",
"of",
"running",
"timers",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/tools/stress/src/org/apache/cassandra/stress/util/Timing.java#L125-L134 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/hadoop/AbstractBulkRecordWriter.java | AbstractBulkRecordWriter.close | @Deprecated
public void close(org.apache.hadoop.mapred.Reporter reporter) throws IOException
{
close();
} | java | @Deprecated
public void close(org.apache.hadoop.mapred.Reporter reporter) throws IOException
{
close();
} | [
"@",
"Deprecated",
"public",
"void",
"close",
"(",
"org",
".",
"apache",
".",
"hadoop",
".",
"mapred",
".",
"Reporter",
"reporter",
")",
"throws",
"IOException",
"{",
"close",
"(",
")",
";",
"}"
] | Fills the deprecated RecordWriter interface for streaming. | [
"Fills",
"the",
"deprecated",
"RecordWriter",
"interface",
"for",
"streaming",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/hadoop/AbstractBulkRecordWriter.java#L111-L115 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/cql3/statements/SelectStatement.java | SelectStatement.forSelection | static SelectStatement forSelection(CFMetaData cfm, Selection selection)
{
return new SelectStatement(cfm, 0, defaultParameters, selection, null);
} | java | static SelectStatement forSelection(CFMetaData cfm, Selection selection)
{
return new SelectStatement(cfm, 0, defaultParameters, selection, null);
} | [
"static",
"SelectStatement",
"forSelection",
"(",
"CFMetaData",
"cfm",
",",
"Selection",
"selection",
")",
"{",
"return",
"new",
"SelectStatement",
"(",
"cfm",
",",
"0",
",",
"defaultParameters",
",",
"selection",
",",
"null",
")",
";",
"}"
] | queried data through processColumnFamily. | [
"queried",
"data",
"through",
"processColumnFamily",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cql3/statements/SelectStatement.java#L161-L164 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/cql3/statements/SelectStatement.java | SelectStatement.selectACollection | private boolean selectACollection()
{
if (!cfm.comparator.hasCollections())
return false;
for (ColumnDefinition def : selection.getColumns())
{
if (def.type.isCollection() && def.type.isMultiCell())
return true;
}
return false;
} | java | private boolean selectACollection()
{
if (!cfm.comparator.hasCollections())
return false;
for (ColumnDefinition def : selection.getColumns())
{
if (def.type.isCollection() && def.type.isMultiCell())
return true;
}
return false;
} | [
"private",
"boolean",
"selectACollection",
"(",
")",
"{",
"if",
"(",
"!",
"cfm",
".",
"comparator",
".",
"hasCollections",
"(",
")",
")",
"return",
"false",
";",
"for",
"(",
"ColumnDefinition",
"def",
":",
"selection",
".",
"getColumns",
"(",
")",
")",
"... | Returns true if a non-frozen collection is selected, false otherwise. | [
"Returns",
"true",
"if",
"a",
"non",
"-",
"frozen",
"collection",
"is",
"selected",
"false",
"otherwise",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cql3/statements/SelectStatement.java#L836-L848 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/cql3/statements/SelectStatement.java | SelectStatement.addEOC | private static Composite addEOC(Composite composite, Bound eocBound)
{
return eocBound == Bound.END ? composite.end() : composite.start();
} | java | private static Composite addEOC(Composite composite, Bound eocBound)
{
return eocBound == Bound.END ? composite.end() : composite.start();
} | [
"private",
"static",
"Composite",
"addEOC",
"(",
"Composite",
"composite",
",",
"Bound",
"eocBound",
")",
"{",
"return",
"eocBound",
"==",
"Bound",
".",
"END",
"?",
"composite",
".",
"end",
"(",
")",
":",
"composite",
".",
"start",
"(",
")",
";",
"}"
] | Adds an EOC to the specified Composite.
@param composite the composite
@param eocBound the EOC bound
@return a new <code>Composite</code> with the EOC corresponding to the eocBound | [
"Adds",
"an",
"EOC",
"to",
"the",
"specified",
"Composite",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cql3/statements/SelectStatement.java#L979-L982 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/cql3/statements/SelectStatement.java | SelectStatement.addValue | private static void addValue(CBuilder builder, ColumnDefinition def, ByteBuffer value) throws InvalidRequestException
{
if (value == null)
throw new InvalidRequestException(String.format("Invalid null value in condition for column %s", def.name));
builder.add(value);
} | java | private static void addValue(CBuilder builder, ColumnDefinition def, ByteBuffer value) throws InvalidRequestException
{
if (value == null)
throw new InvalidRequestException(String.format("Invalid null value in condition for column %s", def.name));
builder.add(value);
} | [
"private",
"static",
"void",
"addValue",
"(",
"CBuilder",
"builder",
",",
"ColumnDefinition",
"def",
",",
"ByteBuffer",
"value",
")",
"throws",
"InvalidRequestException",
"{",
"if",
"(",
"value",
"==",
"null",
")",
"throw",
"new",
"InvalidRequestException",
"(",
... | Adds the specified value to the specified builder
@param builder the CBuilder to which the value must be added
@param def the column associated to the value
@param value the value to add
@throws InvalidRequestException if the value is null | [
"Adds",
"the",
"specified",
"value",
"to",
"the",
"specified",
"builder"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cql3/statements/SelectStatement.java#L992-L997 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/cql3/statements/SelectStatement.java | SelectStatement.processColumnFamily | void processColumnFamily(ByteBuffer key, ColumnFamily cf, QueryOptions options, long now, Selection.ResultSetBuilder result)
throws InvalidRequestException
{
CFMetaData cfm = cf.metadata();
ByteBuffer[] keyComponents = null;
if (cfm.getKeyValidator() instanceof CompositeType)
{
keyComponents = ((CompositeType)cfm.getKeyValidator()).split(key);
}
else
{
keyComponents = new ByteBuffer[]{ key };
}
Iterator<Cell> cells = cf.getSortedColumns().iterator();
if (sliceRestriction != null)
cells = applySliceRestriction(cells, options);
CQL3Row.RowIterator iter = cfm.comparator.CQL3RowBuilder(cfm, now).group(cells);
// If there is static columns but there is no non-static row, then provided the select was a full
// partition selection (i.e. not a 2ndary index search and there was no condition on clustering columns)
// then we want to include the static columns in the result set (and we're done).
CQL3Row staticRow = iter.getStaticRow();
if (staticRow != null && !iter.hasNext() && !usesSecondaryIndexing && hasNoClusteringColumnsRestriction())
{
result.newRow();
for (ColumnDefinition def : selection.getColumns())
{
switch (def.kind)
{
case PARTITION_KEY:
result.add(keyComponents[def.position()]);
break;
case STATIC:
addValue(result, def, staticRow, options);
break;
default:
result.add((ByteBuffer)null);
}
}
return;
}
while (iter.hasNext())
{
CQL3Row cql3Row = iter.next();
// Respect requested order
result.newRow();
// Respect selection order
for (ColumnDefinition def : selection.getColumns())
{
switch (def.kind)
{
case PARTITION_KEY:
result.add(keyComponents[def.position()]);
break;
case CLUSTERING_COLUMN:
result.add(cql3Row.getClusteringColumn(def.position()));
break;
case COMPACT_VALUE:
result.add(cql3Row.getColumn(null));
break;
case REGULAR:
addValue(result, def, cql3Row, options);
break;
case STATIC:
addValue(result, def, staticRow, options);
break;
}
}
}
} | java | void processColumnFamily(ByteBuffer key, ColumnFamily cf, QueryOptions options, long now, Selection.ResultSetBuilder result)
throws InvalidRequestException
{
CFMetaData cfm = cf.metadata();
ByteBuffer[] keyComponents = null;
if (cfm.getKeyValidator() instanceof CompositeType)
{
keyComponents = ((CompositeType)cfm.getKeyValidator()).split(key);
}
else
{
keyComponents = new ByteBuffer[]{ key };
}
Iterator<Cell> cells = cf.getSortedColumns().iterator();
if (sliceRestriction != null)
cells = applySliceRestriction(cells, options);
CQL3Row.RowIterator iter = cfm.comparator.CQL3RowBuilder(cfm, now).group(cells);
// If there is static columns but there is no non-static row, then provided the select was a full
// partition selection (i.e. not a 2ndary index search and there was no condition on clustering columns)
// then we want to include the static columns in the result set (and we're done).
CQL3Row staticRow = iter.getStaticRow();
if (staticRow != null && !iter.hasNext() && !usesSecondaryIndexing && hasNoClusteringColumnsRestriction())
{
result.newRow();
for (ColumnDefinition def : selection.getColumns())
{
switch (def.kind)
{
case PARTITION_KEY:
result.add(keyComponents[def.position()]);
break;
case STATIC:
addValue(result, def, staticRow, options);
break;
default:
result.add((ByteBuffer)null);
}
}
return;
}
while (iter.hasNext())
{
CQL3Row cql3Row = iter.next();
// Respect requested order
result.newRow();
// Respect selection order
for (ColumnDefinition def : selection.getColumns())
{
switch (def.kind)
{
case PARTITION_KEY:
result.add(keyComponents[def.position()]);
break;
case CLUSTERING_COLUMN:
result.add(cql3Row.getClusteringColumn(def.position()));
break;
case COMPACT_VALUE:
result.add(cql3Row.getColumn(null));
break;
case REGULAR:
addValue(result, def, cql3Row, options);
break;
case STATIC:
addValue(result, def, staticRow, options);
break;
}
}
}
} | [
"void",
"processColumnFamily",
"(",
"ByteBuffer",
"key",
",",
"ColumnFamily",
"cf",
",",
"QueryOptions",
"options",
",",
"long",
"now",
",",
"Selection",
".",
"ResultSetBuilder",
"result",
")",
"throws",
"InvalidRequestException",
"{",
"CFMetaData",
"cfm",
"=",
"c... | Used by ModificationStatement for CAS operations | [
"Used",
"by",
"ModificationStatement",
"for",
"CAS",
"operations"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cql3/statements/SelectStatement.java#L1216-L1289 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/cql3/statements/SelectStatement.java | SelectStatement.isRestrictedByMultipleContains | private boolean isRestrictedByMultipleContains(ColumnDefinition columnDef)
{
if (!columnDef.type.isCollection())
return false;
Restriction restriction = metadataRestrictions.get(columnDef.name);
if (!(restriction instanceof Contains))
return false;
Contains contains = (Contains) restriction;
return (contains.numberOfValues() + contains.numberOfKeys()) > 1;
} | java | private boolean isRestrictedByMultipleContains(ColumnDefinition columnDef)
{
if (!columnDef.type.isCollection())
return false;
Restriction restriction = metadataRestrictions.get(columnDef.name);
if (!(restriction instanceof Contains))
return false;
Contains contains = (Contains) restriction;
return (contains.numberOfValues() + contains.numberOfKeys()) > 1;
} | [
"private",
"boolean",
"isRestrictedByMultipleContains",
"(",
"ColumnDefinition",
"columnDef",
")",
"{",
"if",
"(",
"!",
"columnDef",
".",
"type",
".",
"isCollection",
"(",
")",
")",
"return",
"false",
";",
"Restriction",
"restriction",
"=",
"metadataRestrictions",
... | Checks if the specified column is restricted by multiple contains or contains key.
@param columnDef the definition of the column to check
@return <code>true</code> the specified column is restricted by multiple contains or contains key,
<code>false</code> otherwise | [
"Checks",
"if",
"the",
"specified",
"column",
"is",
"restricted",
"by",
"multiple",
"contains",
"or",
"contains",
"key",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cql3/statements/SelectStatement.java#L1399-L1411 | train |
Stratio/stratio-cassandra | tools/stress/src/org/apache/cassandra/stress/util/Timer.java | Timer.requestReport | synchronized void requestReport(CountDownLatch signal)
{
if (finalReport != null)
{
report = finalReport;
finalReport = new TimingInterval(0);
signal.countDown();
}
else
reportRequest = signal;
} | java | synchronized void requestReport(CountDownLatch signal)
{
if (finalReport != null)
{
report = finalReport;
finalReport = new TimingInterval(0);
signal.countDown();
}
else
reportRequest = signal;
} | [
"synchronized",
"void",
"requestReport",
"(",
"CountDownLatch",
"signal",
")",
"{",
"if",
"(",
"finalReport",
"!=",
"null",
")",
"{",
"report",
"=",
"finalReport",
";",
"finalReport",
"=",
"new",
"TimingInterval",
"(",
"0",
")",
";",
"signal",
".",
"countDow... | checks to see if the timer is dead; if not requests a report, and otherwise fulfills the request itself | [
"checks",
"to",
"see",
"if",
"the",
"timer",
"is",
"dead",
";",
"if",
"not",
"requests",
"a",
"report",
"and",
"otherwise",
"fulfills",
"the",
"request",
"itself"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/tools/stress/src/org/apache/cassandra/stress/util/Timer.java#L142-L152 | train |
Stratio/stratio-cassandra | tools/stress/src/org/apache/cassandra/stress/util/Timer.java | Timer.close | public synchronized void close()
{
if (reportRequest == null)
finalReport = buildReport();
else
{
finalReport = new TimingInterval(0);
report = buildReport();
reportRequest.countDown();
reportRequest = null;
}
} | java | public synchronized void close()
{
if (reportRequest == null)
finalReport = buildReport();
else
{
finalReport = new TimingInterval(0);
report = buildReport();
reportRequest.countDown();
reportRequest = null;
}
} | [
"public",
"synchronized",
"void",
"close",
"(",
")",
"{",
"if",
"(",
"reportRequest",
"==",
"null",
")",
"finalReport",
"=",
"buildReport",
"(",
")",
";",
"else",
"{",
"finalReport",
"=",
"new",
"TimingInterval",
"(",
"0",
")",
";",
"report",
"=",
"build... | closes the timer; if a request is outstanding, it furnishes the request, otherwise it populates finalReport | [
"closes",
"the",
"timer",
";",
"if",
"a",
"request",
"is",
"outstanding",
"it",
"furnishes",
"the",
"request",
"otherwise",
"it",
"populates",
"finalReport"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/tools/stress/src/org/apache/cassandra/stress/util/Timer.java#L155-L166 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/streaming/StreamWriter.java | StreamWriter.write | public void write(WritableByteChannel channel) throws IOException
{
long totalSize = totalSize();
RandomAccessReader file = sstable.openDataReader();
ChecksumValidator validator = new File(sstable.descriptor.filenameFor(Component.CRC)).exists()
? DataIntegrityMetadata.checksumValidator(sstable.descriptor)
: null;
transferBuffer = validator == null ? new byte[DEFAULT_CHUNK_SIZE] : new byte[validator.chunkSize];
// setting up data compression stream
compressedOutput = new LZFOutputStream(Channels.newOutputStream(channel));
long progress = 0L;
try
{
// stream each of the required sections of the file
for (Pair<Long, Long> section : sections)
{
long start = validator == null ? section.left : validator.chunkStart(section.left);
int readOffset = (int) (section.left - start);
// seek to the beginning of the section
file.seek(start);
if (validator != null)
validator.seek(start);
// length of the section to read
long length = section.right - start;
// tracks write progress
long bytesRead = 0;
while (bytesRead < length)
{
long lastBytesRead = write(file, validator, readOffset, length, bytesRead);
bytesRead += lastBytesRead;
progress += (lastBytesRead - readOffset);
session.progress(sstable.descriptor, ProgressInfo.Direction.OUT, progress, totalSize);
readOffset = 0;
}
// make sure that current section is send
compressedOutput.flush();
}
}
finally
{
// no matter what happens close file
FileUtils.closeQuietly(file);
FileUtils.closeQuietly(validator);
}
} | java | public void write(WritableByteChannel channel) throws IOException
{
long totalSize = totalSize();
RandomAccessReader file = sstable.openDataReader();
ChecksumValidator validator = new File(sstable.descriptor.filenameFor(Component.CRC)).exists()
? DataIntegrityMetadata.checksumValidator(sstable.descriptor)
: null;
transferBuffer = validator == null ? new byte[DEFAULT_CHUNK_SIZE] : new byte[validator.chunkSize];
// setting up data compression stream
compressedOutput = new LZFOutputStream(Channels.newOutputStream(channel));
long progress = 0L;
try
{
// stream each of the required sections of the file
for (Pair<Long, Long> section : sections)
{
long start = validator == null ? section.left : validator.chunkStart(section.left);
int readOffset = (int) (section.left - start);
// seek to the beginning of the section
file.seek(start);
if (validator != null)
validator.seek(start);
// length of the section to read
long length = section.right - start;
// tracks write progress
long bytesRead = 0;
while (bytesRead < length)
{
long lastBytesRead = write(file, validator, readOffset, length, bytesRead);
bytesRead += lastBytesRead;
progress += (lastBytesRead - readOffset);
session.progress(sstable.descriptor, ProgressInfo.Direction.OUT, progress, totalSize);
readOffset = 0;
}
// make sure that current section is send
compressedOutput.flush();
}
}
finally
{
// no matter what happens close file
FileUtils.closeQuietly(file);
FileUtils.closeQuietly(validator);
}
} | [
"public",
"void",
"write",
"(",
"WritableByteChannel",
"channel",
")",
"throws",
"IOException",
"{",
"long",
"totalSize",
"=",
"totalSize",
"(",
")",
";",
"RandomAccessReader",
"file",
"=",
"sstable",
".",
"openDataReader",
"(",
")",
";",
"ChecksumValidator",
"v... | Stream file of specified sections to given channel.
StreamWriter uses LZF compression on wire to decrease size to transfer.
@param channel where this writes data to
@throws IOException on any I/O error | [
"Stream",
"file",
"of",
"specified",
"sections",
"to",
"given",
"channel",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/streaming/StreamWriter.java#L71-L119 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/streaming/StreamWriter.java | StreamWriter.write | protected long write(RandomAccessReader reader, ChecksumValidator validator, int start, long length, long bytesTransferred) throws IOException
{
int toTransfer = (int) Math.min(transferBuffer.length, length - bytesTransferred);
int minReadable = (int) Math.min(transferBuffer.length, reader.length() - reader.getFilePointer());
reader.readFully(transferBuffer, 0, minReadable);
if (validator != null)
validator.validate(transferBuffer, 0, minReadable);
limiter.acquire(toTransfer - start);
compressedOutput.write(transferBuffer, start, (toTransfer - start));
return toTransfer;
} | java | protected long write(RandomAccessReader reader, ChecksumValidator validator, int start, long length, long bytesTransferred) throws IOException
{
int toTransfer = (int) Math.min(transferBuffer.length, length - bytesTransferred);
int minReadable = (int) Math.min(transferBuffer.length, reader.length() - reader.getFilePointer());
reader.readFully(transferBuffer, 0, minReadable);
if (validator != null)
validator.validate(transferBuffer, 0, minReadable);
limiter.acquire(toTransfer - start);
compressedOutput.write(transferBuffer, start, (toTransfer - start));
return toTransfer;
} | [
"protected",
"long",
"write",
"(",
"RandomAccessReader",
"reader",
",",
"ChecksumValidator",
"validator",
",",
"int",
"start",
",",
"long",
"length",
",",
"long",
"bytesTransferred",
")",
"throws",
"IOException",
"{",
"int",
"toTransfer",
"=",
"(",
"int",
")",
... | Sequentially read bytes from the file and write them to the output stream
@param reader The file reader to read from
@param validator validator to verify data integrity
@param start number of bytes to skip transfer, but include for validation.
@param length The full length that should be read from {@code reader}
@param bytesTransferred Number of bytes already read out of {@code length}
@return Number of bytes read
@throws java.io.IOException on any I/O error | [
"Sequentially",
"read",
"bytes",
"from",
"the",
"file",
"and",
"write",
"them",
"to",
"the",
"output",
"stream"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/streaming/StreamWriter.java#L142-L155 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/utils/ObjectSizes.java | ObjectSizes.sizeOnHeapOf | public static long sizeOnHeapOf(ByteBuffer[] array)
{
long allElementsSize = 0;
for (int i = 0; i < array.length; i++)
if (array[i] != null)
allElementsSize += sizeOnHeapOf(array[i]);
return allElementsSize + sizeOfArray(array);
} | java | public static long sizeOnHeapOf(ByteBuffer[] array)
{
long allElementsSize = 0;
for (int i = 0; i < array.length; i++)
if (array[i] != null)
allElementsSize += sizeOnHeapOf(array[i]);
return allElementsSize + sizeOfArray(array);
} | [
"public",
"static",
"long",
"sizeOnHeapOf",
"(",
"ByteBuffer",
"[",
"]",
"array",
")",
"{",
"long",
"allElementsSize",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"array",
".",
"length",
";",
"i",
"++",
")",
"if",
"(",
"array",
... | Memory a ByteBuffer array consumes. | [
"Memory",
"a",
"ByteBuffer",
"array",
"consumes",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/utils/ObjectSizes.java#L100-L108 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/utils/ObjectSizes.java | ObjectSizes.sizeOnHeapOf | public static long sizeOnHeapOf(ByteBuffer buffer)
{
if (buffer.isDirect())
return BUFFER_EMPTY_SIZE;
// if we're only referencing a sub-portion of the ByteBuffer, don't count the array overhead (assume it's slab
// allocated, so amortized over all the allocations the overhead is negligible and better to undercount than over)
if (buffer.capacity() > buffer.remaining())
return buffer.remaining();
return BUFFER_EMPTY_SIZE + sizeOfArray(buffer.capacity(), 1);
} | java | public static long sizeOnHeapOf(ByteBuffer buffer)
{
if (buffer.isDirect())
return BUFFER_EMPTY_SIZE;
// if we're only referencing a sub-portion of the ByteBuffer, don't count the array overhead (assume it's slab
// allocated, so amortized over all the allocations the overhead is negligible and better to undercount than over)
if (buffer.capacity() > buffer.remaining())
return buffer.remaining();
return BUFFER_EMPTY_SIZE + sizeOfArray(buffer.capacity(), 1);
} | [
"public",
"static",
"long",
"sizeOnHeapOf",
"(",
"ByteBuffer",
"buffer",
")",
"{",
"if",
"(",
"buffer",
".",
"isDirect",
"(",
")",
")",
"return",
"BUFFER_EMPTY_SIZE",
";",
"// if we're only referencing a sub-portion of the ByteBuffer, don't count the array overhead (assume it... | Memory a byte buffer consumes
@param buffer ByteBuffer to calculate in memory size
@return Total in-memory size of the byte buffer | [
"Memory",
"a",
"byte",
"buffer",
"consumes"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/utils/ObjectSizes.java#L119-L128 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/concurrent/DebuggableThreadPoolExecutor.java | DebuggableThreadPoolExecutor.createWithMaximumPoolSize | public static DebuggableThreadPoolExecutor createWithMaximumPoolSize(String threadPoolName, int size, int keepAliveTime, TimeUnit unit)
{
return new DebuggableThreadPoolExecutor(size, Integer.MAX_VALUE, keepAliveTime, unit, new LinkedBlockingQueue<Runnable>(), new NamedThreadFactory(threadPoolName));
} | java | public static DebuggableThreadPoolExecutor createWithMaximumPoolSize(String threadPoolName, int size, int keepAliveTime, TimeUnit unit)
{
return new DebuggableThreadPoolExecutor(size, Integer.MAX_VALUE, keepAliveTime, unit, new LinkedBlockingQueue<Runnable>(), new NamedThreadFactory(threadPoolName));
} | [
"public",
"static",
"DebuggableThreadPoolExecutor",
"createWithMaximumPoolSize",
"(",
"String",
"threadPoolName",
",",
"int",
"size",
",",
"int",
"keepAliveTime",
",",
"TimeUnit",
"unit",
")",
"{",
"return",
"new",
"DebuggableThreadPoolExecutor",
"(",
"size",
",",
"In... | Returns a ThreadPoolExecutor with a fixed maximum number of threads, but whose
threads are terminated when idle for too long.
When all threads are actively executing tasks, new tasks are queued.
@param threadPoolName the name of the threads created by this executor
@param size the maximum number of threads for this executor
@param keepAliveTime the time an idle thread is kept alive before being terminated
@param unit tht time unit for {@code keepAliveTime}
@return the new DebuggableThreadPoolExecutor | [
"Returns",
"a",
"ThreadPoolExecutor",
"with",
"a",
"fixed",
"maximum",
"number",
"of",
"threads",
"but",
"whose",
"threads",
"are",
"terminated",
"when",
"idle",
"for",
"too",
"long",
".",
"When",
"all",
"threads",
"are",
"actively",
"executing",
"tasks",
"new... | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/concurrent/DebuggableThreadPoolExecutor.java#L125-L128 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/concurrent/DebuggableThreadPoolExecutor.java | DebuggableThreadPoolExecutor.execute | @Override
public void execute(Runnable command)
{
super.execute(isTracing() && !(command instanceof TraceSessionWrapper)
? new TraceSessionWrapper<Object>(Executors.callable(command, null))
: command);
} | java | @Override
public void execute(Runnable command)
{
super.execute(isTracing() && !(command instanceof TraceSessionWrapper)
? new TraceSessionWrapper<Object>(Executors.callable(command, null))
: command);
} | [
"@",
"Override",
"public",
"void",
"execute",
"(",
"Runnable",
"command",
")",
"{",
"super",
".",
"execute",
"(",
"isTracing",
"(",
")",
"&&",
"!",
"(",
"command",
"instanceof",
"TraceSessionWrapper",
")",
"?",
"new",
"TraceSessionWrapper",
"<",
"Object",
">... | execute does not call newTaskFor | [
"execute",
"does",
"not",
"call",
"newTaskFor"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/concurrent/DebuggableThreadPoolExecutor.java#L147-L153 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/cli/CliClient.java | CliClient.executeCLIStatement | public void executeCLIStatement(String statement) throws CharacterCodingException, TException, TimedOutException, NotFoundException, NoSuchFieldException, InvalidRequestException, UnavailableException, InstantiationException, IllegalAccessException
{
Tree tree = CliCompiler.compileQuery(statement);
try
{
switch (tree.getType())
{
case CliParser.NODE_EXIT:
cleanupAndExit();
break;
case CliParser.NODE_THRIFT_GET:
executeGet(tree);
break;
case CliParser.NODE_THRIFT_GET_WITH_CONDITIONS:
executeGetWithConditions(tree);
break;
case CliParser.NODE_HELP:
executeHelp(tree);
break;
case CliParser.NODE_THRIFT_SET:
executeSet(tree);
break;
case CliParser.NODE_THRIFT_DEL:
executeDelete(tree);
break;
case CliParser.NODE_THRIFT_COUNT:
executeCount(tree);
break;
case CliParser.NODE_ADD_KEYSPACE:
executeAddKeySpace(tree.getChild(0));
break;
case CliParser.NODE_ADD_COLUMN_FAMILY:
executeAddColumnFamily(tree.getChild(0));
break;
case CliParser.NODE_UPDATE_KEYSPACE:
executeUpdateKeySpace(tree.getChild(0));
break;
case CliParser.NODE_UPDATE_COLUMN_FAMILY:
executeUpdateColumnFamily(tree.getChild(0));
break;
case CliParser.NODE_DEL_COLUMN_FAMILY:
executeDelColumnFamily(tree);
break;
case CliParser.NODE_DEL_KEYSPACE:
executeDelKeySpace(tree);
break;
case CliParser.NODE_SHOW_CLUSTER_NAME:
executeShowClusterName();
break;
case CliParser.NODE_SHOW_VERSION:
executeShowVersion();
break;
case CliParser.NODE_SHOW_KEYSPACES:
executeShowKeySpaces();
break;
case CliParser.NODE_SHOW_SCHEMA:
executeShowSchema(tree);
break;
case CliParser.NODE_DESCRIBE:
executeDescribe(tree);
break;
case CliParser.NODE_DESCRIBE_CLUSTER:
executeDescribeCluster();
break;
case CliParser.NODE_USE_TABLE:
executeUseKeySpace(tree);
break;
case CliParser.NODE_TRACE_NEXT_QUERY:
executeTraceNextQuery();
break;
case CliParser.NODE_CONNECT:
executeConnect(tree);
break;
case CliParser.NODE_LIST:
executeList(tree);
break;
case CliParser.NODE_TRUNCATE:
executeTruncate(tree.getChild(0).getText());
break;
case CliParser.NODE_ASSUME:
executeAssumeStatement(tree);
break;
case CliParser.NODE_CONSISTENCY_LEVEL:
executeConsistencyLevelStatement(tree);
break;
case CliParser.NODE_THRIFT_INCR:
executeIncr(tree, 1L);
break;
case CliParser.NODE_THRIFT_DECR:
executeIncr(tree, -1L);
break;
case CliParser.NODE_DROP_INDEX:
executeDropIndex(tree);
break;
case CliParser.NODE_NO_OP:
// comment lines come here; they are treated as no ops.
break;
default:
sessionState.err.println("Invalid Statement (Type: " + tree.getType() + ")");
if (sessionState.batch)
System.exit(2);
break;
}
}
catch (SchemaDisagreementException e)
{
throw new RuntimeException("schema does not match across nodes, (try again later).", e);
}
} | java | public void executeCLIStatement(String statement) throws CharacterCodingException, TException, TimedOutException, NotFoundException, NoSuchFieldException, InvalidRequestException, UnavailableException, InstantiationException, IllegalAccessException
{
Tree tree = CliCompiler.compileQuery(statement);
try
{
switch (tree.getType())
{
case CliParser.NODE_EXIT:
cleanupAndExit();
break;
case CliParser.NODE_THRIFT_GET:
executeGet(tree);
break;
case CliParser.NODE_THRIFT_GET_WITH_CONDITIONS:
executeGetWithConditions(tree);
break;
case CliParser.NODE_HELP:
executeHelp(tree);
break;
case CliParser.NODE_THRIFT_SET:
executeSet(tree);
break;
case CliParser.NODE_THRIFT_DEL:
executeDelete(tree);
break;
case CliParser.NODE_THRIFT_COUNT:
executeCount(tree);
break;
case CliParser.NODE_ADD_KEYSPACE:
executeAddKeySpace(tree.getChild(0));
break;
case CliParser.NODE_ADD_COLUMN_FAMILY:
executeAddColumnFamily(tree.getChild(0));
break;
case CliParser.NODE_UPDATE_KEYSPACE:
executeUpdateKeySpace(tree.getChild(0));
break;
case CliParser.NODE_UPDATE_COLUMN_FAMILY:
executeUpdateColumnFamily(tree.getChild(0));
break;
case CliParser.NODE_DEL_COLUMN_FAMILY:
executeDelColumnFamily(tree);
break;
case CliParser.NODE_DEL_KEYSPACE:
executeDelKeySpace(tree);
break;
case CliParser.NODE_SHOW_CLUSTER_NAME:
executeShowClusterName();
break;
case CliParser.NODE_SHOW_VERSION:
executeShowVersion();
break;
case CliParser.NODE_SHOW_KEYSPACES:
executeShowKeySpaces();
break;
case CliParser.NODE_SHOW_SCHEMA:
executeShowSchema(tree);
break;
case CliParser.NODE_DESCRIBE:
executeDescribe(tree);
break;
case CliParser.NODE_DESCRIBE_CLUSTER:
executeDescribeCluster();
break;
case CliParser.NODE_USE_TABLE:
executeUseKeySpace(tree);
break;
case CliParser.NODE_TRACE_NEXT_QUERY:
executeTraceNextQuery();
break;
case CliParser.NODE_CONNECT:
executeConnect(tree);
break;
case CliParser.NODE_LIST:
executeList(tree);
break;
case CliParser.NODE_TRUNCATE:
executeTruncate(tree.getChild(0).getText());
break;
case CliParser.NODE_ASSUME:
executeAssumeStatement(tree);
break;
case CliParser.NODE_CONSISTENCY_LEVEL:
executeConsistencyLevelStatement(tree);
break;
case CliParser.NODE_THRIFT_INCR:
executeIncr(tree, 1L);
break;
case CliParser.NODE_THRIFT_DECR:
executeIncr(tree, -1L);
break;
case CliParser.NODE_DROP_INDEX:
executeDropIndex(tree);
break;
case CliParser.NODE_NO_OP:
// comment lines come here; they are treated as no ops.
break;
default:
sessionState.err.println("Invalid Statement (Type: " + tree.getType() + ")");
if (sessionState.batch)
System.exit(2);
break;
}
}
catch (SchemaDisagreementException e)
{
throw new RuntimeException("schema does not match across nodes, (try again later).", e);
}
} | [
"public",
"void",
"executeCLIStatement",
"(",
"String",
"statement",
")",
"throws",
"CharacterCodingException",
",",
"TException",
",",
"TimedOutException",
",",
"NotFoundException",
",",
"NoSuchFieldException",
",",
"InvalidRequestException",
",",
"UnavailableException",
"... | Execute a CLI Statement | [
"Execute",
"a",
"CLI",
"Statement"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cli/CliClient.java#L214-L323 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/cli/CliClient.java | CliClient.executeSet | private void executeSet(Tree statement)
throws TException, InvalidRequestException, UnavailableException, TimedOutException
{
if (!CliMain.isConnected() || !hasKeySpace())
return;
long startTime = System.nanoTime();
// ^(NODE_COLUMN_ACCESS <cf> <key> <column>)
Tree columnFamilySpec = statement.getChild(0);
Tree keyTree = columnFamilySpec.getChild(1); // could be a function or regular text
String columnFamily = CliCompiler.getColumnFamily(columnFamilySpec, currentCfDefs());
CfDef cfDef = getCfDef(columnFamily);
int columnSpecCnt = CliCompiler.numColumnSpecifiers(columnFamilySpec);
String value = CliUtils.unescapeSQLString(statement.getChild(1).getText());
Tree valueTree = statement.getChild(1);
byte[] superColumnName = null;
ByteBuffer columnName;
// keyspace.cf['key']
if (columnSpecCnt == 0)
{
sessionState.err.println("No cell name specified, (type 'help;' or '?' for help on syntax).");
return;
}
// keyspace.cf['key']['column'] = 'value'
else if (columnSpecCnt == 1)
{
// get the column name
if (cfDef.column_type.equals("Super"))
{
sessionState.out.println("Column family " + columnFamily + " may only contain SuperColumns");
return;
}
columnName = getColumnName(columnFamily, columnFamilySpec.getChild(2));
}
// keyspace.cf['key']['super_column']['column'] = 'value'
else
{
assert (columnSpecCnt == 2) : "serious parsing error (this is a bug).";
superColumnName = getColumnName(columnFamily, columnFamilySpec.getChild(2)).array();
columnName = getSubColumnName(columnFamily, columnFamilySpec.getChild(3));
}
ByteBuffer columnValueInBytes;
switch (valueTree.getType())
{
case CliParser.FUNCTION_CALL:
columnValueInBytes = convertValueByFunction(valueTree, cfDef, columnName, true);
break;
default:
columnValueInBytes = columnValueAsBytes(columnName, columnFamily, value);
}
ColumnParent parent = new ColumnParent(columnFamily);
if(superColumnName != null)
parent.setSuper_column(superColumnName);
Column columnToInsert = new Column(columnName).setValue(columnValueInBytes).setTimestamp(FBUtilities.timestampMicros());
// children count = 3 mean that we have ttl in arguments
if (statement.getChildCount() == 3)
{
String ttl = statement.getChild(2).getText();
try
{
columnToInsert.setTtl(Integer.parseInt(ttl));
}
catch (NumberFormatException e)
{
sessionState.err.println(String.format("TTL '%s' is invalid, should be a positive integer.", ttl));
return;
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
// do the insert
thriftClient.insert(getKeyAsBytes(columnFamily, keyTree), parent, columnToInsert, consistencyLevel);
sessionState.out.println("Value inserted.");
elapsedTime(startTime);
} | java | private void executeSet(Tree statement)
throws TException, InvalidRequestException, UnavailableException, TimedOutException
{
if (!CliMain.isConnected() || !hasKeySpace())
return;
long startTime = System.nanoTime();
// ^(NODE_COLUMN_ACCESS <cf> <key> <column>)
Tree columnFamilySpec = statement.getChild(0);
Tree keyTree = columnFamilySpec.getChild(1); // could be a function or regular text
String columnFamily = CliCompiler.getColumnFamily(columnFamilySpec, currentCfDefs());
CfDef cfDef = getCfDef(columnFamily);
int columnSpecCnt = CliCompiler.numColumnSpecifiers(columnFamilySpec);
String value = CliUtils.unescapeSQLString(statement.getChild(1).getText());
Tree valueTree = statement.getChild(1);
byte[] superColumnName = null;
ByteBuffer columnName;
// keyspace.cf['key']
if (columnSpecCnt == 0)
{
sessionState.err.println("No cell name specified, (type 'help;' or '?' for help on syntax).");
return;
}
// keyspace.cf['key']['column'] = 'value'
else if (columnSpecCnt == 1)
{
// get the column name
if (cfDef.column_type.equals("Super"))
{
sessionState.out.println("Column family " + columnFamily + " may only contain SuperColumns");
return;
}
columnName = getColumnName(columnFamily, columnFamilySpec.getChild(2));
}
// keyspace.cf['key']['super_column']['column'] = 'value'
else
{
assert (columnSpecCnt == 2) : "serious parsing error (this is a bug).";
superColumnName = getColumnName(columnFamily, columnFamilySpec.getChild(2)).array();
columnName = getSubColumnName(columnFamily, columnFamilySpec.getChild(3));
}
ByteBuffer columnValueInBytes;
switch (valueTree.getType())
{
case CliParser.FUNCTION_CALL:
columnValueInBytes = convertValueByFunction(valueTree, cfDef, columnName, true);
break;
default:
columnValueInBytes = columnValueAsBytes(columnName, columnFamily, value);
}
ColumnParent parent = new ColumnParent(columnFamily);
if(superColumnName != null)
parent.setSuper_column(superColumnName);
Column columnToInsert = new Column(columnName).setValue(columnValueInBytes).setTimestamp(FBUtilities.timestampMicros());
// children count = 3 mean that we have ttl in arguments
if (statement.getChildCount() == 3)
{
String ttl = statement.getChild(2).getText();
try
{
columnToInsert.setTtl(Integer.parseInt(ttl));
}
catch (NumberFormatException e)
{
sessionState.err.println(String.format("TTL '%s' is invalid, should be a positive integer.", ttl));
return;
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
// do the insert
thriftClient.insert(getKeyAsBytes(columnFamily, keyTree), parent, columnToInsert, consistencyLevel);
sessionState.out.println("Value inserted.");
elapsedTime(startTime);
} | [
"private",
"void",
"executeSet",
"(",
"Tree",
"statement",
")",
"throws",
"TException",
",",
"InvalidRequestException",
",",
"UnavailableException",
",",
"TimedOutException",
"{",
"if",
"(",
"!",
"CliMain",
".",
"isConnected",
"(",
")",
"||",
"!",
"hasKeySpace",
... | Execute SET statement | [
"Execute",
"SET",
"statement"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cli/CliClient.java#L905-L992 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/cli/CliClient.java | CliClient.executeIncr | private void executeIncr(Tree statement, long multiplier)
throws TException, NotFoundException, InvalidRequestException, UnavailableException, TimedOutException
{
if (!CliMain.isConnected() || !hasKeySpace())
return;
Tree columnFamilySpec = statement.getChild(0);
String columnFamily = CliCompiler.getColumnFamily(columnFamilySpec, currentCfDefs());
ByteBuffer key = getKeyAsBytes(columnFamily, columnFamilySpec.getChild(1));
int columnSpecCnt = CliCompiler.numColumnSpecifiers(columnFamilySpec);
byte[] superColumnName = null;
ByteBuffer columnName;
// keyspace.cf['key']['column'] -- incr standard
if (columnSpecCnt == 1)
{
columnName = getColumnName(columnFamily, columnFamilySpec.getChild(2));
}
// keyspace.cf['key']['column']['column'] -- incr super
else if (columnSpecCnt == 2)
{
superColumnName = getColumnName(columnFamily, columnFamilySpec.getChild(2)).array();
columnName = getSubColumnName(columnFamily, columnFamilySpec.getChild(3));
}
// The parser groks an arbitrary number of these so it is possible to get here.
else
{
sessionState.out.println("Invalid row, super column, or column specification.");
return;
}
ColumnParent parent = new ColumnParent(columnFamily);
if(superColumnName != null)
parent.setSuper_column(superColumnName);
long value = 1L;
// children count = 3 mean that we have by in arguments
if (statement.getChildCount() == 2)
{
String byValue = statement.getChild(1).getText();
try
{
value = Long.parseLong(byValue);
}
catch (NumberFormatException e)
{
sessionState.err.println(String.format("'%s' is an invalid value, should be an integer.", byValue));
return;
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
CounterColumn columnToInsert = new CounterColumn(columnName, multiplier * value);
// do the insert
thriftClient.add(key, parent, columnToInsert, consistencyLevel);
sessionState.out.printf("Value %s%n", multiplier < 0 ? "decremented." : "incremented.");
} | java | private void executeIncr(Tree statement, long multiplier)
throws TException, NotFoundException, InvalidRequestException, UnavailableException, TimedOutException
{
if (!CliMain.isConnected() || !hasKeySpace())
return;
Tree columnFamilySpec = statement.getChild(0);
String columnFamily = CliCompiler.getColumnFamily(columnFamilySpec, currentCfDefs());
ByteBuffer key = getKeyAsBytes(columnFamily, columnFamilySpec.getChild(1));
int columnSpecCnt = CliCompiler.numColumnSpecifiers(columnFamilySpec);
byte[] superColumnName = null;
ByteBuffer columnName;
// keyspace.cf['key']['column'] -- incr standard
if (columnSpecCnt == 1)
{
columnName = getColumnName(columnFamily, columnFamilySpec.getChild(2));
}
// keyspace.cf['key']['column']['column'] -- incr super
else if (columnSpecCnt == 2)
{
superColumnName = getColumnName(columnFamily, columnFamilySpec.getChild(2)).array();
columnName = getSubColumnName(columnFamily, columnFamilySpec.getChild(3));
}
// The parser groks an arbitrary number of these so it is possible to get here.
else
{
sessionState.out.println("Invalid row, super column, or column specification.");
return;
}
ColumnParent parent = new ColumnParent(columnFamily);
if(superColumnName != null)
parent.setSuper_column(superColumnName);
long value = 1L;
// children count = 3 mean that we have by in arguments
if (statement.getChildCount() == 2)
{
String byValue = statement.getChild(1).getText();
try
{
value = Long.parseLong(byValue);
}
catch (NumberFormatException e)
{
sessionState.err.println(String.format("'%s' is an invalid value, should be an integer.", byValue));
return;
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
CounterColumn columnToInsert = new CounterColumn(columnName, multiplier * value);
// do the insert
thriftClient.add(key, parent, columnToInsert, consistencyLevel);
sessionState.out.printf("Value %s%n", multiplier < 0 ? "decremented." : "incremented.");
} | [
"private",
"void",
"executeIncr",
"(",
"Tree",
"statement",
",",
"long",
"multiplier",
")",
"throws",
"TException",
",",
"NotFoundException",
",",
"InvalidRequestException",
",",
"UnavailableException",
",",
"TimedOutException",
"{",
"if",
"(",
"!",
"CliMain",
".",
... | Execute INCR statement | [
"Execute",
"INCR",
"statement"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cli/CliClient.java#L995-L1059 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/cli/CliClient.java | CliClient.executeAddKeySpace | private void executeAddKeySpace(Tree statement)
{
if (!CliMain.isConnected())
return;
// first value is the keyspace name, after that it is all key=value
String keyspaceName = CliUtils.unescapeSQLString(statement.getChild(0).getText());
KsDef ksDef = new KsDef(keyspaceName, DEFAULT_PLACEMENT_STRATEGY, new LinkedList<CfDef>());
try
{
String mySchemaVersion = thriftClient.system_add_keyspace(updateKsDefAttributes(statement, ksDef));
sessionState.out.println(mySchemaVersion);
keyspacesMap.put(keyspaceName, thriftClient.describe_keyspace(keyspaceName));
}
catch (InvalidRequestException e)
{
throw new RuntimeException(e);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
} | java | private void executeAddKeySpace(Tree statement)
{
if (!CliMain.isConnected())
return;
// first value is the keyspace name, after that it is all key=value
String keyspaceName = CliUtils.unescapeSQLString(statement.getChild(0).getText());
KsDef ksDef = new KsDef(keyspaceName, DEFAULT_PLACEMENT_STRATEGY, new LinkedList<CfDef>());
try
{
String mySchemaVersion = thriftClient.system_add_keyspace(updateKsDefAttributes(statement, ksDef));
sessionState.out.println(mySchemaVersion);
keyspacesMap.put(keyspaceName, thriftClient.describe_keyspace(keyspaceName));
}
catch (InvalidRequestException e)
{
throw new RuntimeException(e);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
} | [
"private",
"void",
"executeAddKeySpace",
"(",
"Tree",
"statement",
")",
"{",
"if",
"(",
"!",
"CliMain",
".",
"isConnected",
"(",
")",
")",
"return",
";",
"// first value is the keyspace name, after that it is all key=value",
"String",
"keyspaceName",
"=",
"CliUtils",
... | Add a keyspace
@param statement - a token tree representing current statement | [
"Add",
"a",
"keyspace"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cli/CliClient.java#L1073-L1098 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/cli/CliClient.java | CliClient.executeAddColumnFamily | private void executeAddColumnFamily(Tree statement)
{
if (!CliMain.isConnected() || !hasKeySpace())
return;
// first value is the column family name, after that it is all key=value
CfDef cfDef = new CfDef(keySpace, CliUtils.unescapeSQLString(statement.getChild(0).getText()));
try
{
String mySchemaVersion = thriftClient.system_add_column_family(updateCfDefAttributes(statement, cfDef));
sessionState.out.println(mySchemaVersion);
keyspacesMap.put(keySpace, thriftClient.describe_keyspace(keySpace));
}
catch (InvalidRequestException e)
{
throw new RuntimeException(e);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
} | java | private void executeAddColumnFamily(Tree statement)
{
if (!CliMain.isConnected() || !hasKeySpace())
return;
// first value is the column family name, after that it is all key=value
CfDef cfDef = new CfDef(keySpace, CliUtils.unescapeSQLString(statement.getChild(0).getText()));
try
{
String mySchemaVersion = thriftClient.system_add_column_family(updateCfDefAttributes(statement, cfDef));
sessionState.out.println(mySchemaVersion);
keyspacesMap.put(keySpace, thriftClient.describe_keyspace(keySpace));
}
catch (InvalidRequestException e)
{
throw new RuntimeException(e);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
} | [
"private",
"void",
"executeAddColumnFamily",
"(",
"Tree",
"statement",
")",
"{",
"if",
"(",
"!",
"CliMain",
".",
"isConnected",
"(",
")",
"||",
"!",
"hasKeySpace",
"(",
")",
")",
"return",
";",
"// first value is the column family name, after that it is all key=value"... | Add a column family
@param statement - a token tree representing current statement | [
"Add",
"a",
"column",
"family"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cli/CliClient.java#L1105-L1127 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/cli/CliClient.java | CliClient.executeUpdateKeySpace | private void executeUpdateKeySpace(Tree statement)
{
if (!CliMain.isConnected())
return;
try
{
String keyspaceName = CliCompiler.getKeySpace(statement, thriftClient.describe_keyspaces());
KsDef currentKsDef = getKSMetaData(keyspaceName);
KsDef updatedKsDef = updateKsDefAttributes(statement, currentKsDef);
String mySchemaVersion = thriftClient.system_update_keyspace(updatedKsDef);
sessionState.out.println(mySchemaVersion);
keyspacesMap.remove(keyspaceName);
getKSMetaData(keyspaceName);
}
catch (InvalidRequestException e)
{
throw new RuntimeException(e);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
} | java | private void executeUpdateKeySpace(Tree statement)
{
if (!CliMain.isConnected())
return;
try
{
String keyspaceName = CliCompiler.getKeySpace(statement, thriftClient.describe_keyspaces());
KsDef currentKsDef = getKSMetaData(keyspaceName);
KsDef updatedKsDef = updateKsDefAttributes(statement, currentKsDef);
String mySchemaVersion = thriftClient.system_update_keyspace(updatedKsDef);
sessionState.out.println(mySchemaVersion);
keyspacesMap.remove(keyspaceName);
getKSMetaData(keyspaceName);
}
catch (InvalidRequestException e)
{
throw new RuntimeException(e);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
} | [
"private",
"void",
"executeUpdateKeySpace",
"(",
"Tree",
"statement",
")",
"{",
"if",
"(",
"!",
"CliMain",
".",
"isConnected",
"(",
")",
")",
"return",
";",
"try",
"{",
"String",
"keyspaceName",
"=",
"CliCompiler",
".",
"getKeySpace",
"(",
"statement",
",",
... | Update existing keyspace identified by name
@param statement - tree represeting statement | [
"Update",
"existing",
"keyspace",
"identified",
"by",
"name"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cli/CliClient.java#L1133-L1158 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/cli/CliClient.java | CliClient.executeUpdateColumnFamily | private void executeUpdateColumnFamily(Tree statement)
{
if (!CliMain.isConnected() || !hasKeySpace())
return;
String cfName = CliCompiler.getColumnFamily(statement, currentCfDefs());
try
{
// request correct cfDef from the server (we let that call include CQL3 cf even though
// they can't be modified by thrift because the error message that will be thrown by
// system_update_column_family will be more useful)
CfDef cfDef = getCfDef(thriftClient.describe_keyspace(this.keySpace), cfName, true);
if (cfDef == null)
throw new RuntimeException("Column Family " + cfName + " was not found in the current keyspace.");
String mySchemaVersion = thriftClient.system_update_column_family(updateCfDefAttributes(statement, cfDef));
sessionState.out.println(mySchemaVersion);
keyspacesMap.put(keySpace, thriftClient.describe_keyspace(keySpace));
}
catch (InvalidRequestException e)
{
throw new RuntimeException(e);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
} | java | private void executeUpdateColumnFamily(Tree statement)
{
if (!CliMain.isConnected() || !hasKeySpace())
return;
String cfName = CliCompiler.getColumnFamily(statement, currentCfDefs());
try
{
// request correct cfDef from the server (we let that call include CQL3 cf even though
// they can't be modified by thrift because the error message that will be thrown by
// system_update_column_family will be more useful)
CfDef cfDef = getCfDef(thriftClient.describe_keyspace(this.keySpace), cfName, true);
if (cfDef == null)
throw new RuntimeException("Column Family " + cfName + " was not found in the current keyspace.");
String mySchemaVersion = thriftClient.system_update_column_family(updateCfDefAttributes(statement, cfDef));
sessionState.out.println(mySchemaVersion);
keyspacesMap.put(keySpace, thriftClient.describe_keyspace(keySpace));
}
catch (InvalidRequestException e)
{
throw new RuntimeException(e);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
} | [
"private",
"void",
"executeUpdateColumnFamily",
"(",
"Tree",
"statement",
")",
"{",
"if",
"(",
"!",
"CliMain",
".",
"isConnected",
"(",
")",
"||",
"!",
"hasKeySpace",
"(",
")",
")",
"return",
";",
"String",
"cfName",
"=",
"CliCompiler",
".",
"getColumnFamily... | Update existing column family identified by name
@param statement - tree represeting statement | [
"Update",
"existing",
"column",
"family",
"identified",
"by",
"name"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cli/CliClient.java#L1164-L1193 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/cli/CliClient.java | CliClient.updateKsDefAttributes | private KsDef updateKsDefAttributes(Tree statement, KsDef ksDefToUpdate)
{
KsDef ksDef = new KsDef(ksDefToUpdate);
// removing all column definitions - thrift system_update_keyspace method requires that
ksDef.setCf_defs(new LinkedList<CfDef>());
for(int i = 1; i < statement.getChildCount(); i += 2)
{
String currentStatement = statement.getChild(i).getText().toUpperCase();
AddKeyspaceArgument mArgument = AddKeyspaceArgument.valueOf(currentStatement);
String mValue = statement.getChild(i + 1).getText();
switch(mArgument)
{
case PLACEMENT_STRATEGY:
ksDef.setStrategy_class(CliUtils.unescapeSQLString(mValue));
break;
case STRATEGY_OPTIONS:
ksDef.setStrategy_options(getStrategyOptionsFromTree(statement.getChild(i + 1)));
break;
case DURABLE_WRITES:
ksDef.setDurable_writes(Boolean.parseBoolean(mValue));
break;
default:
//must match one of the above or we'd throw an exception at the valueOf statement above.
assert(false);
}
}
// using default snitch options if strategy is NetworkTopologyStrategy and no options were set.
if (ksDef.getStrategy_class().contains(".NetworkTopologyStrategy"))
{
Map<String, String> currentStrategyOptions = ksDef.getStrategy_options();
// adding default data center from SimpleSnitch
if (currentStrategyOptions == null || currentStrategyOptions.isEmpty())
{
SimpleSnitch snitch = new SimpleSnitch();
Map<String, String> options = new HashMap<String, String>();
try
{
options.put(snitch.getDatacenter(InetAddress.getLocalHost()), "1");
}
catch (UnknownHostException e)
{
throw new RuntimeException(e);
}
ksDef.setStrategy_options(options);
}
}
return ksDef;
} | java | private KsDef updateKsDefAttributes(Tree statement, KsDef ksDefToUpdate)
{
KsDef ksDef = new KsDef(ksDefToUpdate);
// removing all column definitions - thrift system_update_keyspace method requires that
ksDef.setCf_defs(new LinkedList<CfDef>());
for(int i = 1; i < statement.getChildCount(); i += 2)
{
String currentStatement = statement.getChild(i).getText().toUpperCase();
AddKeyspaceArgument mArgument = AddKeyspaceArgument.valueOf(currentStatement);
String mValue = statement.getChild(i + 1).getText();
switch(mArgument)
{
case PLACEMENT_STRATEGY:
ksDef.setStrategy_class(CliUtils.unescapeSQLString(mValue));
break;
case STRATEGY_OPTIONS:
ksDef.setStrategy_options(getStrategyOptionsFromTree(statement.getChild(i + 1)));
break;
case DURABLE_WRITES:
ksDef.setDurable_writes(Boolean.parseBoolean(mValue));
break;
default:
//must match one of the above or we'd throw an exception at the valueOf statement above.
assert(false);
}
}
// using default snitch options if strategy is NetworkTopologyStrategy and no options were set.
if (ksDef.getStrategy_class().contains(".NetworkTopologyStrategy"))
{
Map<String, String> currentStrategyOptions = ksDef.getStrategy_options();
// adding default data center from SimpleSnitch
if (currentStrategyOptions == null || currentStrategyOptions.isEmpty())
{
SimpleSnitch snitch = new SimpleSnitch();
Map<String, String> options = new HashMap<String, String>();
try
{
options.put(snitch.getDatacenter(InetAddress.getLocalHost()), "1");
}
catch (UnknownHostException e)
{
throw new RuntimeException(e);
}
ksDef.setStrategy_options(options);
}
}
return ksDef;
} | [
"private",
"KsDef",
"updateKsDefAttributes",
"(",
"Tree",
"statement",
",",
"KsDef",
"ksDefToUpdate",
")",
"{",
"KsDef",
"ksDef",
"=",
"new",
"KsDef",
"(",
"ksDefToUpdate",
")",
";",
"// removing all column definitions - thrift system_update_keyspace method requires that",
... | Used to update keyspace definition attributes
@param statement - ANTRL tree representing current statement
@param ksDefToUpdate - keyspace definition to update
@return ksDef - updated keyspace definition | [
"Used",
"to",
"update",
"keyspace",
"definition",
"attributes"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cli/CliClient.java#L1201-L1254 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/cli/CliClient.java | CliClient.executeDelKeySpace | private void executeDelKeySpace(Tree statement)
throws TException, InvalidRequestException, NotFoundException, SchemaDisagreementException
{
if (!CliMain.isConnected())
return;
String keyspaceName = CliCompiler.getKeySpace(statement, thriftClient.describe_keyspaces());
String version = thriftClient.system_drop_keyspace(keyspaceName);
sessionState.out.println(version);
if (keyspaceName.equals(keySpace)) //we just deleted the keyspace we were authenticated too
keySpace = null;
} | java | private void executeDelKeySpace(Tree statement)
throws TException, InvalidRequestException, NotFoundException, SchemaDisagreementException
{
if (!CliMain.isConnected())
return;
String keyspaceName = CliCompiler.getKeySpace(statement, thriftClient.describe_keyspaces());
String version = thriftClient.system_drop_keyspace(keyspaceName);
sessionState.out.println(version);
if (keyspaceName.equals(keySpace)) //we just deleted the keyspace we were authenticated too
keySpace = null;
} | [
"private",
"void",
"executeDelKeySpace",
"(",
"Tree",
"statement",
")",
"throws",
"TException",
",",
"InvalidRequestException",
",",
"NotFoundException",
",",
"SchemaDisagreementException",
"{",
"if",
"(",
"!",
"CliMain",
".",
"isConnected",
"(",
")",
")",
"return",... | Delete a keyspace
@param statement - a token tree representing current statement
@throws TException - exception
@throws InvalidRequestException - exception
@throws NotFoundException - exception
@throws SchemaDisagreementException | [
"Delete",
"a",
"keyspace"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cli/CliClient.java#L1389-L1401 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/cli/CliClient.java | CliClient.executeDelColumnFamily | private void executeDelColumnFamily(Tree statement)
throws TException, InvalidRequestException, NotFoundException, SchemaDisagreementException
{
if (!CliMain.isConnected() || !hasKeySpace())
return;
String cfName = CliCompiler.getColumnFamily(statement, currentCfDefs());
String mySchemaVersion = thriftClient.system_drop_column_family(cfName);
sessionState.out.println(mySchemaVersion);
} | java | private void executeDelColumnFamily(Tree statement)
throws TException, InvalidRequestException, NotFoundException, SchemaDisagreementException
{
if (!CliMain.isConnected() || !hasKeySpace())
return;
String cfName = CliCompiler.getColumnFamily(statement, currentCfDefs());
String mySchemaVersion = thriftClient.system_drop_column_family(cfName);
sessionState.out.println(mySchemaVersion);
} | [
"private",
"void",
"executeDelColumnFamily",
"(",
"Tree",
"statement",
")",
"throws",
"TException",
",",
"InvalidRequestException",
",",
"NotFoundException",
",",
"SchemaDisagreementException",
"{",
"if",
"(",
"!",
"CliMain",
".",
"isConnected",
"(",
")",
"||",
"!",... | Delete a column family
@param statement - a token tree representing current statement
@throws TException - exception
@throws InvalidRequestException - exception
@throws NotFoundException - exception
@throws SchemaDisagreementException | [
"Delete",
"a",
"column",
"family"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cli/CliClient.java#L1411-L1420 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/cli/CliClient.java | CliClient.showKeyspace | private void showKeyspace(PrintStream output, KsDef ksDef)
{
output.append("create keyspace ").append(CliUtils.maybeEscapeName(ksDef.name));
writeAttr(output, true, "placement_strategy", normaliseType(ksDef.strategy_class, "org.apache.cassandra.locator"));
if (ksDef.strategy_options != null && !ksDef.strategy_options.isEmpty())
{
final StringBuilder opts = new StringBuilder();
opts.append("{");
String prefix = "";
for (Map.Entry<String, String> opt : ksDef.strategy_options.entrySet())
{
opts.append(prefix).append(CliUtils.escapeSQLString(opt.getKey())).append(" : ").append(CliUtils.escapeSQLString(opt.getValue()));
prefix = ", ";
}
opts.append("}");
writeAttrRaw(output, false, "strategy_options", opts.toString());
}
writeAttr(output, false, "durable_writes", ksDef.durable_writes);
output.append(";").append(NEWLINE);
output.append(NEWLINE);
output.append("use ").append(CliUtils.maybeEscapeName(ksDef.name)).append(";");
output.append(NEWLINE);
output.append(NEWLINE);
Collections.sort(ksDef.cf_defs, new CfDefNamesComparator());
for (CfDef cfDef : ksDef.cf_defs)
showColumnFamily(output, cfDef);
output.append(NEWLINE);
output.append(NEWLINE);
}
/**
* Creates a CLI script for the CfDef including meta data to the supplied StringBuilder.
*
* @param output File to write to.
* @param cfDef CfDef to export attributes from.
*/
private void showColumnFamily(PrintStream output, CfDef cfDef)
{
output.append("create column family ").append(CliUtils.maybeEscapeName(cfDef.name));
writeAttr(output, true, "column_type", cfDef.column_type);
writeAttr(output, false, "comparator", normaliseType(cfDef.comparator_type, "org.apache.cassandra.db.marshal"));
if (cfDef.column_type.equals("Super"))
writeAttr(output, false, "subcomparator", normaliseType(cfDef.subcomparator_type, "org.apache.cassandra.db.marshal"));
if (!StringUtils.isEmpty(cfDef.default_validation_class))
writeAttr(output, false, "default_validation_class",
normaliseType(cfDef.default_validation_class, "org.apache.cassandra.db.marshal"));
writeAttr(output, false, "key_validation_class",
normaliseType(cfDef.key_validation_class, "org.apache.cassandra.db.marshal"));
writeAttr(output, false, "read_repair_chance", cfDef.read_repair_chance);
writeAttr(output, false, "dclocal_read_repair_chance", cfDef.dclocal_read_repair_chance);
writeAttr(output, false, "gc_grace", cfDef.gc_grace_seconds);
writeAttr(output, false, "min_compaction_threshold", cfDef.min_compaction_threshold);
writeAttr(output, false, "max_compaction_threshold", cfDef.max_compaction_threshold);
writeAttr(output, false, "compaction_strategy", cfDef.compaction_strategy);
writeAttr(output, false, "caching", cfDef.caching);
writeAttr(output, false, "cells_per_row_to_cache", cfDef.cells_per_row_to_cache);
writeAttr(output, false, "default_time_to_live", cfDef.default_time_to_live);
writeAttr(output, false, "speculative_retry", cfDef.speculative_retry);
if (cfDef.isSetBloom_filter_fp_chance())
writeAttr(output, false, "bloom_filter_fp_chance", cfDef.bloom_filter_fp_chance);
if (!cfDef.compaction_strategy_options.isEmpty())
{
StringBuilder cOptions = new StringBuilder();
cOptions.append("{");
Map<String, String> options = cfDef.compaction_strategy_options;
int i = 0, size = options.size();
for (Map.Entry<String, String> entry : options.entrySet())
{
cOptions.append(CliUtils.quote(entry.getKey())).append(" : ").append(CliUtils.quote(entry.getValue()));
if (i != size - 1)
cOptions.append(", ");
i++;
}
cOptions.append("}");
writeAttrRaw(output, false, "compaction_strategy_options", cOptions.toString());
}
if (!StringUtils.isEmpty(cfDef.comment))
writeAttr(output, false, "comment", cfDef.comment);
if (!cfDef.column_metadata.isEmpty())
{
output.append(NEWLINE)
.append(TAB)
.append("and column_metadata = [");
boolean first = true;
for (ColumnDef colDef : cfDef.column_metadata)
{
if (!first)
output.append(",");
first = false;
showColumnMeta(output, cfDef, colDef);
}
output.append("]");
}
if (cfDef.compression_options != null && !cfDef.compression_options.isEmpty())
{
StringBuilder compOptions = new StringBuilder();
compOptions.append("{");
int i = 0, size = cfDef.compression_options.size();
for (Map.Entry<String, String> entry : cfDef.compression_options.entrySet())
{
compOptions.append(CliUtils.quote(entry.getKey())).append(" : ").append(CliUtils.quote(entry.getValue()));
if (i != size - 1)
compOptions.append(", ");
i++;
}
compOptions.append("}");
writeAttrRaw(output, false, "compression_options", compOptions.toString());
}
if (cfDef.isSetIndex_interval())
writeAttr(output, false, "index_interval", cfDef.index_interval);
output.append(";");
output.append(NEWLINE);
output.append(NEWLINE);
} | java | private void showKeyspace(PrintStream output, KsDef ksDef)
{
output.append("create keyspace ").append(CliUtils.maybeEscapeName(ksDef.name));
writeAttr(output, true, "placement_strategy", normaliseType(ksDef.strategy_class, "org.apache.cassandra.locator"));
if (ksDef.strategy_options != null && !ksDef.strategy_options.isEmpty())
{
final StringBuilder opts = new StringBuilder();
opts.append("{");
String prefix = "";
for (Map.Entry<String, String> opt : ksDef.strategy_options.entrySet())
{
opts.append(prefix).append(CliUtils.escapeSQLString(opt.getKey())).append(" : ").append(CliUtils.escapeSQLString(opt.getValue()));
prefix = ", ";
}
opts.append("}");
writeAttrRaw(output, false, "strategy_options", opts.toString());
}
writeAttr(output, false, "durable_writes", ksDef.durable_writes);
output.append(";").append(NEWLINE);
output.append(NEWLINE);
output.append("use ").append(CliUtils.maybeEscapeName(ksDef.name)).append(";");
output.append(NEWLINE);
output.append(NEWLINE);
Collections.sort(ksDef.cf_defs, new CfDefNamesComparator());
for (CfDef cfDef : ksDef.cf_defs)
showColumnFamily(output, cfDef);
output.append(NEWLINE);
output.append(NEWLINE);
}
/**
* Creates a CLI script for the CfDef including meta data to the supplied StringBuilder.
*
* @param output File to write to.
* @param cfDef CfDef to export attributes from.
*/
private void showColumnFamily(PrintStream output, CfDef cfDef)
{
output.append("create column family ").append(CliUtils.maybeEscapeName(cfDef.name));
writeAttr(output, true, "column_type", cfDef.column_type);
writeAttr(output, false, "comparator", normaliseType(cfDef.comparator_type, "org.apache.cassandra.db.marshal"));
if (cfDef.column_type.equals("Super"))
writeAttr(output, false, "subcomparator", normaliseType(cfDef.subcomparator_type, "org.apache.cassandra.db.marshal"));
if (!StringUtils.isEmpty(cfDef.default_validation_class))
writeAttr(output, false, "default_validation_class",
normaliseType(cfDef.default_validation_class, "org.apache.cassandra.db.marshal"));
writeAttr(output, false, "key_validation_class",
normaliseType(cfDef.key_validation_class, "org.apache.cassandra.db.marshal"));
writeAttr(output, false, "read_repair_chance", cfDef.read_repair_chance);
writeAttr(output, false, "dclocal_read_repair_chance", cfDef.dclocal_read_repair_chance);
writeAttr(output, false, "gc_grace", cfDef.gc_grace_seconds);
writeAttr(output, false, "min_compaction_threshold", cfDef.min_compaction_threshold);
writeAttr(output, false, "max_compaction_threshold", cfDef.max_compaction_threshold);
writeAttr(output, false, "compaction_strategy", cfDef.compaction_strategy);
writeAttr(output, false, "caching", cfDef.caching);
writeAttr(output, false, "cells_per_row_to_cache", cfDef.cells_per_row_to_cache);
writeAttr(output, false, "default_time_to_live", cfDef.default_time_to_live);
writeAttr(output, false, "speculative_retry", cfDef.speculative_retry);
if (cfDef.isSetBloom_filter_fp_chance())
writeAttr(output, false, "bloom_filter_fp_chance", cfDef.bloom_filter_fp_chance);
if (!cfDef.compaction_strategy_options.isEmpty())
{
StringBuilder cOptions = new StringBuilder();
cOptions.append("{");
Map<String, String> options = cfDef.compaction_strategy_options;
int i = 0, size = options.size();
for (Map.Entry<String, String> entry : options.entrySet())
{
cOptions.append(CliUtils.quote(entry.getKey())).append(" : ").append(CliUtils.quote(entry.getValue()));
if (i != size - 1)
cOptions.append(", ");
i++;
}
cOptions.append("}");
writeAttrRaw(output, false, "compaction_strategy_options", cOptions.toString());
}
if (!StringUtils.isEmpty(cfDef.comment))
writeAttr(output, false, "comment", cfDef.comment);
if (!cfDef.column_metadata.isEmpty())
{
output.append(NEWLINE)
.append(TAB)
.append("and column_metadata = [");
boolean first = true;
for (ColumnDef colDef : cfDef.column_metadata)
{
if (!first)
output.append(",");
first = false;
showColumnMeta(output, cfDef, colDef);
}
output.append("]");
}
if (cfDef.compression_options != null && !cfDef.compression_options.isEmpty())
{
StringBuilder compOptions = new StringBuilder();
compOptions.append("{");
int i = 0, size = cfDef.compression_options.size();
for (Map.Entry<String, String> entry : cfDef.compression_options.entrySet())
{
compOptions.append(CliUtils.quote(entry.getKey())).append(" : ").append(CliUtils.quote(entry.getValue()));
if (i != size - 1)
compOptions.append(", ");
i++;
}
compOptions.append("}");
writeAttrRaw(output, false, "compression_options", compOptions.toString());
}
if (cfDef.isSetIndex_interval())
writeAttr(output, false, "index_interval", cfDef.index_interval);
output.append(";");
output.append(NEWLINE);
output.append(NEWLINE);
} | [
"private",
"void",
"showKeyspace",
"(",
"PrintStream",
"output",
",",
"KsDef",
"ksDef",
")",
"{",
"output",
".",
"append",
"(",
"\"create keyspace \"",
")",
".",
"append",
"(",
"CliUtils",
".",
"maybeEscapeName",
"(",
"ksDef",
".",
"name",
")",
")",
";",
"... | Creates a CLI script to create the Keyspace it's Column Families
@param output StringBuilder to write to.
@param ksDef KsDef to create the cli script for. | [
"Creates",
"a",
"CLI",
"script",
"to",
"create",
"the",
"Keyspace",
"it",
"s",
"Column",
"Families"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cli/CliClient.java#L1766-L1908 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/cli/CliClient.java | CliClient.showColumnMeta | private void showColumnMeta(PrintStream output, CfDef cfDef, ColumnDef colDef)
{
output.append(NEWLINE + TAB + TAB + "{");
final AbstractType<?> comparator = getFormatType(cfDef.column_type.equals("Super")
? cfDef.subcomparator_type
: cfDef.comparator_type);
output.append("column_name : '" + CliUtils.escapeSQLString(comparator.getString(colDef.name)) + "'," + NEWLINE);
String validationClass = normaliseType(colDef.validation_class, "org.apache.cassandra.db.marshal");
output.append(TAB + TAB + "validation_class : " + CliUtils.escapeSQLString(validationClass));
if (colDef.isSetIndex_name())
{
output.append(",").append(NEWLINE)
.append(TAB + TAB + "index_name : '" + CliUtils.escapeSQLString(colDef.index_name) + "'," + NEWLINE)
.append(TAB + TAB + "index_type : " + CliUtils.escapeSQLString(Integer.toString(colDef.index_type.getValue())));
if (colDef.index_options != null && !colDef.index_options.isEmpty())
{
output.append(",").append(NEWLINE);
output.append(TAB + TAB + "index_options : {" + NEWLINE);
int numOpts = colDef.index_options.size();
for (Map.Entry<String, String> entry : colDef.index_options.entrySet())
{
String option = CliUtils.escapeSQLString(entry.getKey());
String optionValue = CliUtils.escapeSQLString(entry.getValue());
output.append(TAB + TAB + TAB)
.append("'" + option + "' : '")
.append(optionValue)
.append("'");
if (--numOpts > 0)
output.append(",").append(NEWLINE);
}
output.append("}");
}
}
output.append("}");
} | java | private void showColumnMeta(PrintStream output, CfDef cfDef, ColumnDef colDef)
{
output.append(NEWLINE + TAB + TAB + "{");
final AbstractType<?> comparator = getFormatType(cfDef.column_type.equals("Super")
? cfDef.subcomparator_type
: cfDef.comparator_type);
output.append("column_name : '" + CliUtils.escapeSQLString(comparator.getString(colDef.name)) + "'," + NEWLINE);
String validationClass = normaliseType(colDef.validation_class, "org.apache.cassandra.db.marshal");
output.append(TAB + TAB + "validation_class : " + CliUtils.escapeSQLString(validationClass));
if (colDef.isSetIndex_name())
{
output.append(",").append(NEWLINE)
.append(TAB + TAB + "index_name : '" + CliUtils.escapeSQLString(colDef.index_name) + "'," + NEWLINE)
.append(TAB + TAB + "index_type : " + CliUtils.escapeSQLString(Integer.toString(colDef.index_type.getValue())));
if (colDef.index_options != null && !colDef.index_options.isEmpty())
{
output.append(",").append(NEWLINE);
output.append(TAB + TAB + "index_options : {" + NEWLINE);
int numOpts = colDef.index_options.size();
for (Map.Entry<String, String> entry : colDef.index_options.entrySet())
{
String option = CliUtils.escapeSQLString(entry.getKey());
String optionValue = CliUtils.escapeSQLString(entry.getValue());
output.append(TAB + TAB + TAB)
.append("'" + option + "' : '")
.append(optionValue)
.append("'");
if (--numOpts > 0)
output.append(",").append(NEWLINE);
}
output.append("}");
}
}
output.append("}");
} | [
"private",
"void",
"showColumnMeta",
"(",
"PrintStream",
"output",
",",
"CfDef",
"cfDef",
",",
"ColumnDef",
"colDef",
")",
"{",
"output",
".",
"append",
"(",
"NEWLINE",
"+",
"TAB",
"+",
"TAB",
"+",
"\"{\"",
")",
";",
"final",
"AbstractType",
"<",
"?",
">... | Writes the supplied ColumnDef to the StringBuilder as a cli script.
@param output The File to write to.
@param cfDef The CfDef as a source for comparator/validator
@param colDef The Column Definition to export | [
"Writes",
"the",
"supplied",
"ColumnDef",
"to",
"the",
"StringBuilder",
"as",
"a",
"cli",
"script",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cli/CliClient.java#L1917-L1955 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/cli/CliClient.java | CliClient.hasKeySpace | private boolean hasKeySpace(boolean printError)
{
boolean hasKeyspace = keySpace != null;
if (!hasKeyspace && printError)
sessionState.err.println("Not authorized to a working keyspace.");
return hasKeyspace;
} | java | private boolean hasKeySpace(boolean printError)
{
boolean hasKeyspace = keySpace != null;
if (!hasKeyspace && printError)
sessionState.err.println("Not authorized to a working keyspace.");
return hasKeyspace;
} | [
"private",
"boolean",
"hasKeySpace",
"(",
"boolean",
"printError",
")",
"{",
"boolean",
"hasKeyspace",
"=",
"keySpace",
"!=",
"null",
";",
"if",
"(",
"!",
"hasKeyspace",
"&&",
"printError",
")",
"sessionState",
".",
"err",
".",
"println",
"(",
"\"Not authorize... | Returns true if this.keySpace is set, false otherwise
@return boolean | [
"Returns",
"true",
"if",
"this",
".",
"keySpace",
"is",
"set",
"false",
"otherwise"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cli/CliClient.java#L1990-L1998 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/cli/CliClient.java | CliClient.getIndexTypeFromString | private IndexType getIndexTypeFromString(String indexTypeAsString)
{
IndexType indexType;
try
{
indexType = IndexType.findByValue(new Integer(indexTypeAsString));
}
catch (NumberFormatException e)
{
try
{
// if this is not an integer lets try to get IndexType by name
indexType = IndexType.valueOf(indexTypeAsString);
}
catch (IllegalArgumentException ie)
{
throw new RuntimeException("IndexType '" + indexTypeAsString + "' is unsupported.", ie);
}
}
if (indexType == null)
{
throw new RuntimeException("IndexType '" + indexTypeAsString + "' is unsupported.");
}
return indexType;
} | java | private IndexType getIndexTypeFromString(String indexTypeAsString)
{
IndexType indexType;
try
{
indexType = IndexType.findByValue(new Integer(indexTypeAsString));
}
catch (NumberFormatException e)
{
try
{
// if this is not an integer lets try to get IndexType by name
indexType = IndexType.valueOf(indexTypeAsString);
}
catch (IllegalArgumentException ie)
{
throw new RuntimeException("IndexType '" + indexTypeAsString + "' is unsupported.", ie);
}
}
if (indexType == null)
{
throw new RuntimeException("IndexType '" + indexTypeAsString + "' is unsupported.");
}
return indexType;
} | [
"private",
"IndexType",
"getIndexTypeFromString",
"(",
"String",
"indexTypeAsString",
")",
"{",
"IndexType",
"indexType",
";",
"try",
"{",
"indexType",
"=",
"IndexType",
".",
"findByValue",
"(",
"new",
"Integer",
"(",
"indexTypeAsString",
")",
")",
";",
"}",
"ca... | Getting IndexType object from indexType string
@param indexTypeAsString - string return by parser corresponding to IndexType
@return IndexType - an IndexType object | [
"Getting",
"IndexType",
"object",
"from",
"indexType",
"string"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cli/CliClient.java#L2516-L2543 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/cli/CliClient.java | CliClient.subColumnNameAsBytes | private ByteBuffer subColumnNameAsBytes(String superColumn, String columnFamily)
{
CfDef columnFamilyDef = getCfDef(columnFamily);
return subColumnNameAsBytes(superColumn, columnFamilyDef);
} | java | private ByteBuffer subColumnNameAsBytes(String superColumn, String columnFamily)
{
CfDef columnFamilyDef = getCfDef(columnFamily);
return subColumnNameAsBytes(superColumn, columnFamilyDef);
} | [
"private",
"ByteBuffer",
"subColumnNameAsBytes",
"(",
"String",
"superColumn",
",",
"String",
"columnFamily",
")",
"{",
"CfDef",
"columnFamilyDef",
"=",
"getCfDef",
"(",
"columnFamily",
")",
";",
"return",
"subColumnNameAsBytes",
"(",
"superColumn",
",",
"columnFamily... | Converts sub-column name into ByteBuffer according to comparator type
@param superColumn - sub-column name from parser
@param columnFamily - column family name from parser
@return ByteBuffer bytes - into which column name was converted according to comparator type | [
"Converts",
"sub",
"-",
"column",
"name",
"into",
"ByteBuffer",
"according",
"to",
"comparator",
"type"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cli/CliClient.java#L2617-L2621 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/cli/CliClient.java | CliClient.subColumnNameAsBytes | private ByteBuffer subColumnNameAsBytes(String superColumn, CfDef columnFamilyDef)
{
String comparatorClass = columnFamilyDef.subcomparator_type;
if (comparatorClass == null)
{
sessionState.out.println(String.format("Notice: defaulting to BytesType subcomparator for '%s'", columnFamilyDef.getName()));
comparatorClass = "BytesType";
}
return getBytesAccordingToType(superColumn, getFormatType(comparatorClass));
} | java | private ByteBuffer subColumnNameAsBytes(String superColumn, CfDef columnFamilyDef)
{
String comparatorClass = columnFamilyDef.subcomparator_type;
if (comparatorClass == null)
{
sessionState.out.println(String.format("Notice: defaulting to BytesType subcomparator for '%s'", columnFamilyDef.getName()));
comparatorClass = "BytesType";
}
return getBytesAccordingToType(superColumn, getFormatType(comparatorClass));
} | [
"private",
"ByteBuffer",
"subColumnNameAsBytes",
"(",
"String",
"superColumn",
",",
"CfDef",
"columnFamilyDef",
")",
"{",
"String",
"comparatorClass",
"=",
"columnFamilyDef",
".",
"subcomparator_type",
";",
"if",
"(",
"comparatorClass",
"==",
"null",
")",
"{",
"sess... | Converts column name into ByteBuffer according to comparator type
@param superColumn - sub-column name from parser
@param columnFamilyDef - column family from parser
@return ByteBuffer bytes - into which column name was converted according to comparator type | [
"Converts",
"column",
"name",
"into",
"ByteBuffer",
"according",
"to",
"comparator",
"type"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cli/CliClient.java#L2629-L2640 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/cli/CliClient.java | CliClient.getValidatorForValue | private AbstractType<?> getValidatorForValue(CfDef cfDef, byte[] columnNameInBytes)
{
String defaultValidator = cfDef.default_validation_class;
for (ColumnDef columnDefinition : cfDef.getColumn_metadata())
{
byte[] nameInBytes = columnDefinition.getName();
if (Arrays.equals(nameInBytes, columnNameInBytes))
{
return getFormatType(columnDefinition.getValidation_class());
}
}
if (defaultValidator != null && !defaultValidator.isEmpty())
{
return getFormatType(defaultValidator);
}
return null;
} | java | private AbstractType<?> getValidatorForValue(CfDef cfDef, byte[] columnNameInBytes)
{
String defaultValidator = cfDef.default_validation_class;
for (ColumnDef columnDefinition : cfDef.getColumn_metadata())
{
byte[] nameInBytes = columnDefinition.getName();
if (Arrays.equals(nameInBytes, columnNameInBytes))
{
return getFormatType(columnDefinition.getValidation_class());
}
}
if (defaultValidator != null && !defaultValidator.isEmpty())
{
return getFormatType(defaultValidator);
}
return null;
} | [
"private",
"AbstractType",
"<",
"?",
">",
"getValidatorForValue",
"(",
"CfDef",
"cfDef",
",",
"byte",
"[",
"]",
"columnNameInBytes",
")",
"{",
"String",
"defaultValidator",
"=",
"cfDef",
".",
"default_validation_class",
";",
"for",
"(",
"ColumnDef",
"columnDefinit... | Get validator for specific column value
@param cfDef - CfDef object representing column family with metadata
@param columnNameInBytes - column name as byte array
@return AbstractType - validator for column value | [
"Get",
"validator",
"for",
"specific",
"column",
"value"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cli/CliClient.java#L2692-L2712 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/cli/CliClient.java | CliClient.getTypeByFunction | public static AbstractType<?> getTypeByFunction(String functionName)
{
Function function;
try
{
function = Function.valueOf(functionName.toUpperCase());
}
catch (IllegalArgumentException e)
{
String message = String.format("Function '%s' not found. Available functions: %s", functionName, Function.getFunctionNames());
throw new RuntimeException(message, e);
}
return function.getValidator();
} | java | public static AbstractType<?> getTypeByFunction(String functionName)
{
Function function;
try
{
function = Function.valueOf(functionName.toUpperCase());
}
catch (IllegalArgumentException e)
{
String message = String.format("Function '%s' not found. Available functions: %s", functionName, Function.getFunctionNames());
throw new RuntimeException(message, e);
}
return function.getValidator();
} | [
"public",
"static",
"AbstractType",
"<",
"?",
">",
"getTypeByFunction",
"(",
"String",
"functionName",
")",
"{",
"Function",
"function",
";",
"try",
"{",
"function",
"=",
"Function",
".",
"valueOf",
"(",
"functionName",
".",
"toUpperCase",
"(",
")",
")",
";"... | Get AbstractType by function name
@param functionName - name of the function e.g. utf8, integer, long etc.
@return AbstractType type corresponding to the function name | [
"Get",
"AbstractType",
"by",
"function",
"name"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cli/CliClient.java#L2827-L2842 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/cli/CliClient.java | CliClient.updateColumnMetaData | private void updateColumnMetaData(CfDef columnFamily, ByteBuffer columnName, String validationClass)
{
ColumnDef column = getColumnDefByName(columnFamily, columnName);
if (column != null)
{
// if validation class is the same - no need to modify it
if (column.getValidation_class().equals(validationClass))
return;
// updating column definition with new validation_class
column.setValidation_class(validationClass);
}
else
{
List<ColumnDef> columnMetaData = new ArrayList<ColumnDef>(columnFamily.getColumn_metadata());
columnMetaData.add(new ColumnDef(columnName, validationClass));
columnFamily.setColumn_metadata(columnMetaData);
}
} | java | private void updateColumnMetaData(CfDef columnFamily, ByteBuffer columnName, String validationClass)
{
ColumnDef column = getColumnDefByName(columnFamily, columnName);
if (column != null)
{
// if validation class is the same - no need to modify it
if (column.getValidation_class().equals(validationClass))
return;
// updating column definition with new validation_class
column.setValidation_class(validationClass);
}
else
{
List<ColumnDef> columnMetaData = new ArrayList<ColumnDef>(columnFamily.getColumn_metadata());
columnMetaData.add(new ColumnDef(columnName, validationClass));
columnFamily.setColumn_metadata(columnMetaData);
}
} | [
"private",
"void",
"updateColumnMetaData",
"(",
"CfDef",
"columnFamily",
",",
"ByteBuffer",
"columnName",
",",
"String",
"validationClass",
")",
"{",
"ColumnDef",
"column",
"=",
"getColumnDefByName",
"(",
"columnFamily",
",",
"columnName",
")",
";",
"if",
"(",
"co... | Used to locally update column family definition with new column metadata
@param columnFamily - CfDef record
@param columnName - column name represented as byte[]
@param validationClass - value validation class | [
"Used",
"to",
"locally",
"update",
"column",
"family",
"definition",
"with",
"new",
"column",
"metadata"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cli/CliClient.java#L2850-L2869 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/cli/CliClient.java | CliClient.getColumnDefByName | private ColumnDef getColumnDefByName(CfDef columnFamily, ByteBuffer columnName)
{
for (ColumnDef columnDef : columnFamily.getColumn_metadata())
{
byte[] currName = columnDef.getName();
if (ByteBufferUtil.compare(currName, columnName) == 0)
{
return columnDef;
}
}
return null;
} | java | private ColumnDef getColumnDefByName(CfDef columnFamily, ByteBuffer columnName)
{
for (ColumnDef columnDef : columnFamily.getColumn_metadata())
{
byte[] currName = columnDef.getName();
if (ByteBufferUtil.compare(currName, columnName) == 0)
{
return columnDef;
}
}
return null;
} | [
"private",
"ColumnDef",
"getColumnDefByName",
"(",
"CfDef",
"columnFamily",
",",
"ByteBuffer",
"columnName",
")",
"{",
"for",
"(",
"ColumnDef",
"columnDef",
":",
"columnFamily",
".",
"getColumn_metadata",
"(",
")",
")",
"{",
"byte",
"[",
"]",
"currName",
"=",
... | Get specific ColumnDef in column family meta data by column name
@param columnFamily - CfDef record
@param columnName - column name represented as byte[]
@return ColumnDef - found column definition | [
"Get",
"specific",
"ColumnDef",
"in",
"column",
"family",
"meta",
"data",
"by",
"column",
"name"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cli/CliClient.java#L2877-L2890 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/cli/CliClient.java | CliClient.formatSubcolumnName | private String formatSubcolumnName(String keyspace, String columnFamily, ByteBuffer name)
{
return getFormatType(getCfDef(keyspace, columnFamily).subcomparator_type).getString(name);
} | java | private String formatSubcolumnName(String keyspace, String columnFamily, ByteBuffer name)
{
return getFormatType(getCfDef(keyspace, columnFamily).subcomparator_type).getString(name);
} | [
"private",
"String",
"formatSubcolumnName",
"(",
"String",
"keyspace",
",",
"String",
"columnFamily",
",",
"ByteBuffer",
"name",
")",
"{",
"return",
"getFormatType",
"(",
"getCfDef",
"(",
"keyspace",
",",
"columnFamily",
")",
".",
"subcomparator_type",
")",
".",
... | returns sub-column name in human-readable format | [
"returns",
"sub",
"-",
"column",
"name",
"in",
"human",
"-",
"readable",
"format"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cli/CliClient.java#L2971-L2974 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/cli/CliClient.java | CliClient.formatColumnName | private String formatColumnName(String keyspace, String columnFamily, ByteBuffer name)
{
return getFormatType(getCfDef(keyspace, columnFamily).comparator_type).getString(name);
} | java | private String formatColumnName(String keyspace, String columnFamily, ByteBuffer name)
{
return getFormatType(getCfDef(keyspace, columnFamily).comparator_type).getString(name);
} | [
"private",
"String",
"formatColumnName",
"(",
"String",
"keyspace",
",",
"String",
"columnFamily",
",",
"ByteBuffer",
"name",
")",
"{",
"return",
"getFormatType",
"(",
"getCfDef",
"(",
"keyspace",
",",
"columnFamily",
")",
".",
"comparator_type",
")",
".",
"getS... | retuns column name in human-readable format | [
"retuns",
"column",
"name",
"in",
"human",
"-",
"readable",
"format"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cli/CliClient.java#L2977-L2980 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/cli/CliClient.java | CliClient.elapsedTime | private void elapsedTime(long startTime)
{
/** time elapsed in nanoseconds */
long eta = System.nanoTime() - startTime;
sessionState.out.print("Elapsed time: ");
if (eta < 10000000)
{
sessionState.out.print(Math.round(eta/10000.0)/100.0);
}
else
{
sessionState.out.print(Math.round(eta/1000000.0));
}
sessionState.out.println(" msec(s).");
} | java | private void elapsedTime(long startTime)
{
/** time elapsed in nanoseconds */
long eta = System.nanoTime() - startTime;
sessionState.out.print("Elapsed time: ");
if (eta < 10000000)
{
sessionState.out.print(Math.round(eta/10000.0)/100.0);
}
else
{
sessionState.out.print(Math.round(eta/1000000.0));
}
sessionState.out.println(" msec(s).");
} | [
"private",
"void",
"elapsedTime",
"(",
"long",
"startTime",
")",
"{",
"/** time elapsed in nanoseconds */",
"long",
"eta",
"=",
"System",
".",
"nanoTime",
"(",
")",
"-",
"startTime",
";",
"sessionState",
".",
"out",
".",
"print",
"(",
"\"Elapsed time: \"",
")",
... | Print elapsed time. Print 2 fraction digits if eta is under 10 ms.
@param startTime starting time in nanoseconds | [
"Print",
"elapsed",
"time",
".",
"Print",
"2",
"fraction",
"digits",
"if",
"eta",
"is",
"under",
"10",
"ms",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cli/CliClient.java#L3048-L3063 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/io/util/MappedFileDataInput.java | MappedFileDataInput.seek | public void seek(long pos) throws IOException
{
long inSegmentPos = pos - segmentOffset;
if (inSegmentPos < 0 || inSegmentPos > buffer.capacity())
throw new IOException(String.format("Seek position %d is not within mmap segment (seg offs: %d, length: %d)", pos, segmentOffset, buffer.capacity()));
seekInternal((int) inSegmentPos);
} | java | public void seek(long pos) throws IOException
{
long inSegmentPos = pos - segmentOffset;
if (inSegmentPos < 0 || inSegmentPos > buffer.capacity())
throw new IOException(String.format("Seek position %d is not within mmap segment (seg offs: %d, length: %d)", pos, segmentOffset, buffer.capacity()));
seekInternal((int) inSegmentPos);
} | [
"public",
"void",
"seek",
"(",
"long",
"pos",
")",
"throws",
"IOException",
"{",
"long",
"inSegmentPos",
"=",
"pos",
"-",
"segmentOffset",
";",
"if",
"(",
"inSegmentPos",
"<",
"0",
"||",
"inSegmentPos",
">",
"buffer",
".",
"capacity",
"(",
")",
")",
"thr... | IOException otherwise. | [
"IOException",
"otherwise",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/io/util/MappedFileDataInput.java#L51-L58 | train |
Stratio/stratio-cassandra | src/java/com/stratio/cassandra/index/RowIndex.java | RowIndex.index | @Override
public void index(ByteBuffer key, ColumnFamily columnFamily) {
Log.debug("Indexing row %s in index %s ", key, logName);
lock.readLock().lock();
try {
if (rowService != null) {
long timestamp = System.currentTimeMillis();
rowService.index(key, columnFamily, timestamp);
}
} catch (RuntimeException e) {
Log.error("Error while indexing row %s", key);
throw e;
} finally {
lock.readLock().unlock();
}
} | java | @Override
public void index(ByteBuffer key, ColumnFamily columnFamily) {
Log.debug("Indexing row %s in index %s ", key, logName);
lock.readLock().lock();
try {
if (rowService != null) {
long timestamp = System.currentTimeMillis();
rowService.index(key, columnFamily, timestamp);
}
} catch (RuntimeException e) {
Log.error("Error while indexing row %s", key);
throw e;
} finally {
lock.readLock().unlock();
}
} | [
"@",
"Override",
"public",
"void",
"index",
"(",
"ByteBuffer",
"key",
",",
"ColumnFamily",
"columnFamily",
")",
"{",
"Log",
".",
"debug",
"(",
"\"Indexing row %s in index %s \"",
",",
"key",
",",
"logName",
")",
";",
"lock",
".",
"readLock",
"(",
")",
".",
... | Index the given row.
@param key The partition key.
@param columnFamily The column family data to be indexed | [
"Index",
"the",
"given",
"row",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/com/stratio/cassandra/index/RowIndex.java#L148-L163 | train |
Stratio/stratio-cassandra | src/java/com/stratio/cassandra/index/RowIndex.java | RowIndex.delete | @Override
public void delete(DecoratedKey key, OpOrder.Group opGroup) {
Log.debug("Removing row %s from index %s", key, logName);
lock.writeLock().lock();
try {
rowService.delete(key);
rowService = null;
} catch (RuntimeException e) {
Log.error(e, "Error deleting row %s", key);
throw e;
} finally {
lock.writeLock().unlock();
}
} | java | @Override
public void delete(DecoratedKey key, OpOrder.Group opGroup) {
Log.debug("Removing row %s from index %s", key, logName);
lock.writeLock().lock();
try {
rowService.delete(key);
rowService = null;
} catch (RuntimeException e) {
Log.error(e, "Error deleting row %s", key);
throw e;
} finally {
lock.writeLock().unlock();
}
} | [
"@",
"Override",
"public",
"void",
"delete",
"(",
"DecoratedKey",
"key",
",",
"OpOrder",
".",
"Group",
"opGroup",
")",
"{",
"Log",
".",
"debug",
"(",
"\"Removing row %s from index %s\"",
",",
"key",
",",
"logName",
")",
";",
"lock",
".",
"writeLock",
"(",
... | cleans up deleted columns from cassandra cleanup compaction
@param key The partition key of the physical row to be deleted. | [
"cleans",
"up",
"deleted",
"columns",
"from",
"cassandra",
"cleanup",
"compaction"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/com/stratio/cassandra/index/RowIndex.java#L170-L183 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/repair/RepairJob.java | RepairJob.sendTreeRequests | public void sendTreeRequests(Collection<InetAddress> endpoints)
{
// send requests to all nodes
List<InetAddress> allEndpoints = new ArrayList<>(endpoints);
allEndpoints.add(FBUtilities.getBroadcastAddress());
// Create a snapshot at all nodes unless we're using pure parallel repairs
if (parallelismDegree != RepairParallelism.PARALLEL)
{
List<ListenableFuture<InetAddress>> snapshotTasks = new ArrayList<>(allEndpoints.size());
for (InetAddress endpoint : allEndpoints)
{
SnapshotTask snapshotTask = new SnapshotTask(desc, endpoint);
snapshotTasks.add(snapshotTask);
taskExecutor.execute(snapshotTask);
}
ListenableFuture<List<InetAddress>> allSnapshotTasks = Futures.allAsList(snapshotTasks);
// Execute send tree request after all snapshot complete
Futures.addCallback(allSnapshotTasks, new FutureCallback<List<InetAddress>>()
{
public void onSuccess(List<InetAddress> endpoints)
{
sendTreeRequestsInternal(endpoints);
}
public void onFailure(Throwable throwable)
{
// TODO need to propagate error to RepairSession
logger.error("Error occurred during snapshot phase", throwable);
listener.failedSnapshot();
failed = true;
}
}, taskExecutor);
}
else
{
sendTreeRequestsInternal(allEndpoints);
}
} | java | public void sendTreeRequests(Collection<InetAddress> endpoints)
{
// send requests to all nodes
List<InetAddress> allEndpoints = new ArrayList<>(endpoints);
allEndpoints.add(FBUtilities.getBroadcastAddress());
// Create a snapshot at all nodes unless we're using pure parallel repairs
if (parallelismDegree != RepairParallelism.PARALLEL)
{
List<ListenableFuture<InetAddress>> snapshotTasks = new ArrayList<>(allEndpoints.size());
for (InetAddress endpoint : allEndpoints)
{
SnapshotTask snapshotTask = new SnapshotTask(desc, endpoint);
snapshotTasks.add(snapshotTask);
taskExecutor.execute(snapshotTask);
}
ListenableFuture<List<InetAddress>> allSnapshotTasks = Futures.allAsList(snapshotTasks);
// Execute send tree request after all snapshot complete
Futures.addCallback(allSnapshotTasks, new FutureCallback<List<InetAddress>>()
{
public void onSuccess(List<InetAddress> endpoints)
{
sendTreeRequestsInternal(endpoints);
}
public void onFailure(Throwable throwable)
{
// TODO need to propagate error to RepairSession
logger.error("Error occurred during snapshot phase", throwable);
listener.failedSnapshot();
failed = true;
}
}, taskExecutor);
}
else
{
sendTreeRequestsInternal(allEndpoints);
}
} | [
"public",
"void",
"sendTreeRequests",
"(",
"Collection",
"<",
"InetAddress",
">",
"endpoints",
")",
"{",
"// send requests to all nodes",
"List",
"<",
"InetAddress",
">",
"allEndpoints",
"=",
"new",
"ArrayList",
"<>",
"(",
"endpoints",
")",
";",
"allEndpoints",
".... | Send merkle tree request to every involved neighbor. | [
"Send",
"merkle",
"tree",
"request",
"to",
"every",
"involved",
"neighbor",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/repair/RepairJob.java#L117-L155 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/repair/RepairJob.java | RepairJob.addTree | public synchronized int addTree(InetAddress endpoint, MerkleTree tree)
{
// Wait for all request to have been performed (see #3400)
try
{
requestsSent.await();
}
catch (InterruptedException e)
{
throw new AssertionError("Interrupted while waiting for requests to be sent");
}
if (tree == null)
failed = true;
else
trees.add(new TreeResponse(endpoint, tree));
return treeRequests.completed(endpoint);
} | java | public synchronized int addTree(InetAddress endpoint, MerkleTree tree)
{
// Wait for all request to have been performed (see #3400)
try
{
requestsSent.await();
}
catch (InterruptedException e)
{
throw new AssertionError("Interrupted while waiting for requests to be sent");
}
if (tree == null)
failed = true;
else
trees.add(new TreeResponse(endpoint, tree));
return treeRequests.completed(endpoint);
} | [
"public",
"synchronized",
"int",
"addTree",
"(",
"InetAddress",
"endpoint",
",",
"MerkleTree",
"tree",
")",
"{",
"// Wait for all request to have been performed (see #3400)",
"try",
"{",
"requestsSent",
".",
"await",
"(",
")",
";",
"}",
"catch",
"(",
"InterruptedExcep... | Add a new received tree and return the number of remaining tree to
be received for the job to be complete.
Callers may assume exactly one addTree call will result in zero remaining endpoints.
@param endpoint address of the endpoint that sent response
@param tree sent Merkle tree or null if validation failed on endpoint
@return the number of responses waiting to receive | [
"Add",
"a",
"new",
"received",
"tree",
"and",
"return",
"the",
"number",
"of",
"remaining",
"tree",
"to",
"be",
"received",
"for",
"the",
"job",
"to",
"be",
"complete",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/repair/RepairJob.java#L178-L195 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/db/marshal/AbstractType.java | AbstractType.getString | public String getString(ByteBuffer bytes)
{
TypeSerializer<T> serializer = getSerializer();
serializer.validate(bytes);
return serializer.toString(serializer.deserialize(bytes));
} | java | public String getString(ByteBuffer bytes)
{
TypeSerializer<T> serializer = getSerializer();
serializer.validate(bytes);
return serializer.toString(serializer.deserialize(bytes));
} | [
"public",
"String",
"getString",
"(",
"ByteBuffer",
"bytes",
")",
"{",
"TypeSerializer",
"<",
"T",
">",
"serializer",
"=",
"getSerializer",
"(",
")",
";",
"serializer",
".",
"validate",
"(",
"bytes",
")",
";",
"return",
"serializer",
".",
"toString",
"(",
... | get a string representation of the bytes suitable for log messages | [
"get",
"a",
"string",
"representation",
"of",
"the",
"bytes",
"suitable",
"for",
"log",
"messages"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/marshal/AbstractType.java#L77-L83 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/db/marshal/AbstractType.java | AbstractType.isValueCompatibleWith | public boolean isValueCompatibleWith(AbstractType<?> otherType)
{
return isValueCompatibleWithInternal((otherType instanceof ReversedType) ? ((ReversedType) otherType).baseType : otherType);
} | java | public boolean isValueCompatibleWith(AbstractType<?> otherType)
{
return isValueCompatibleWithInternal((otherType instanceof ReversedType) ? ((ReversedType) otherType).baseType : otherType);
} | [
"public",
"boolean",
"isValueCompatibleWith",
"(",
"AbstractType",
"<",
"?",
">",
"otherType",
")",
"{",
"return",
"isValueCompatibleWithInternal",
"(",
"(",
"otherType",
"instanceof",
"ReversedType",
")",
"?",
"(",
"(",
"ReversedType",
")",
"otherType",
")",
".",... | Returns true if values of the other AbstractType can be read and "reasonably" interpreted by the this
AbstractType. Note that this is a weaker version of isCompatibleWith, as it does not require that both type
compare values the same way.
The restriction on the other type being "reasonably" interpreted is to prevent, for example, IntegerType from
being compatible with all other types. Even though any byte string is a valid IntegerType value, it doesn't
necessarily make sense to interpret a UUID or a UTF8 string as an integer.
Note that a type should be compatible with at least itself. | [
"Returns",
"true",
"if",
"values",
"of",
"the",
"other",
"AbstractType",
"can",
"be",
"read",
"and",
"reasonably",
"interpreted",
"by",
"the",
"this",
"AbstractType",
".",
"Note",
"that",
"this",
"is",
"a",
"weaker",
"version",
"of",
"isCompatibleWith",
"as",
... | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/marshal/AbstractType.java#L177-L180 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/db/marshal/AbstractType.java | AbstractType.compareCollectionMembers | public int compareCollectionMembers(ByteBuffer v1, ByteBuffer v2, ByteBuffer collectionName)
{
return compare(v1, v2);
} | java | public int compareCollectionMembers(ByteBuffer v1, ByteBuffer v2, ByteBuffer collectionName)
{
return compare(v1, v2);
} | [
"public",
"int",
"compareCollectionMembers",
"(",
"ByteBuffer",
"v1",
",",
"ByteBuffer",
"v2",
",",
"ByteBuffer",
"collectionName",
")",
"{",
"return",
"compare",
"(",
"v1",
",",
"v2",
")",
";",
"}"
] | An alternative comparison function used by CollectionsType in conjunction with CompositeType.
This comparator is only called to compare components of a CompositeType. It gets the value of the
previous component as argument (or null if it's the first component of the composite).
Unless you're doing something very similar to CollectionsType, you shouldn't override this. | [
"An",
"alternative",
"comparison",
"function",
"used",
"by",
"CollectionsType",
"in",
"conjunction",
"with",
"CompositeType",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/marshal/AbstractType.java#L208-L211 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/tools/SSTableExport.java | SSTableExport.writeKey | private static void writeKey(PrintStream out, String value)
{
writeJSON(out, value);
out.print(": ");
} | java | private static void writeKey(PrintStream out, String value)
{
writeJSON(out, value);
out.print(": ");
} | [
"private",
"static",
"void",
"writeKey",
"(",
"PrintStream",
"out",
",",
"String",
"value",
")",
"{",
"writeJSON",
"(",
"out",
",",
"value",
")",
";",
"out",
".",
"print",
"(",
"\": \"",
")",
";",
"}"
] | JSON Hash Key serializer
@param out The output steam to write data
@param value value to set as a key | [
"JSON",
"Hash",
"Key",
"serializer"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/tools/SSTableExport.java#L91-L95 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/tools/SSTableExport.java | SSTableExport.serializeColumn | private static List<Object> serializeColumn(Cell cell, CFMetaData cfMetaData)
{
CellNameType comparator = cfMetaData.comparator;
ArrayList<Object> serializedColumn = new ArrayList<Object>();
serializedColumn.add(comparator.getString(cell.name()));
if (cell instanceof DeletedCell)
{
serializedColumn.add(cell.getLocalDeletionTime());
}
else
{
AbstractType<?> validator = cfMetaData.getValueValidator(cell.name());
serializedColumn.add(validator.getString(cell.value()));
}
serializedColumn.add(cell.timestamp());
if (cell instanceof DeletedCell)
{
serializedColumn.add("d");
}
else if (cell instanceof ExpiringCell)
{
serializedColumn.add("e");
serializedColumn.add(((ExpiringCell) cell).getTimeToLive());
serializedColumn.add(cell.getLocalDeletionTime());
}
else if (cell instanceof CounterCell)
{
serializedColumn.add("c");
serializedColumn.add(((CounterCell) cell).timestampOfLastDelete());
}
return serializedColumn;
} | java | private static List<Object> serializeColumn(Cell cell, CFMetaData cfMetaData)
{
CellNameType comparator = cfMetaData.comparator;
ArrayList<Object> serializedColumn = new ArrayList<Object>();
serializedColumn.add(comparator.getString(cell.name()));
if (cell instanceof DeletedCell)
{
serializedColumn.add(cell.getLocalDeletionTime());
}
else
{
AbstractType<?> validator = cfMetaData.getValueValidator(cell.name());
serializedColumn.add(validator.getString(cell.value()));
}
serializedColumn.add(cell.timestamp());
if (cell instanceof DeletedCell)
{
serializedColumn.add("d");
}
else if (cell instanceof ExpiringCell)
{
serializedColumn.add("e");
serializedColumn.add(((ExpiringCell) cell).getTimeToLive());
serializedColumn.add(cell.getLocalDeletionTime());
}
else if (cell instanceof CounterCell)
{
serializedColumn.add("c");
serializedColumn.add(((CounterCell) cell).timestampOfLastDelete());
}
return serializedColumn;
} | [
"private",
"static",
"List",
"<",
"Object",
">",
"serializeColumn",
"(",
"Cell",
"cell",
",",
"CFMetaData",
"cfMetaData",
")",
"{",
"CellNameType",
"comparator",
"=",
"cfMetaData",
".",
"comparator",
";",
"ArrayList",
"<",
"Object",
">",
"serializedColumn",
"=",... | Serialize a given cell to a List of Objects that jsonMapper knows how to turn into strings. Format is
human_readable_name, value, timestamp, [flag, [options]]
Value is normally the human readable value as rendered by the validator, but for deleted cells we
give the local deletion time instead.
Flag may be exactly one of {d,e,c} for deleted, expiring, or counter:
- No options for deleted cells
- If expiring, options will include the TTL and local deletion time.
- If counter, options will include timestamp of last delete
@param cell cell presentation
@param cfMetaData Column Family metadata (to get validator)
@return cell as serialized list | [
"Serialize",
"a",
"given",
"cell",
"to",
"a",
"List",
"of",
"Objects",
"that",
"jsonMapper",
"knows",
"how",
"to",
"turn",
"into",
"strings",
".",
"Format",
"is"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/tools/SSTableExport.java#L134-L170 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/tools/SSTableExport.java | SSTableExport.serializeRow | private static void serializeRow(SSTableIdentityIterator row, DecoratedKey key, PrintStream out)
{
serializeRow(row.getColumnFamily().deletionInfo(), row, row.getColumnFamily().metadata(), key, out);
} | java | private static void serializeRow(SSTableIdentityIterator row, DecoratedKey key, PrintStream out)
{
serializeRow(row.getColumnFamily().deletionInfo(), row, row.getColumnFamily().metadata(), key, out);
} | [
"private",
"static",
"void",
"serializeRow",
"(",
"SSTableIdentityIterator",
"row",
",",
"DecoratedKey",
"key",
",",
"PrintStream",
"out",
")",
"{",
"serializeRow",
"(",
"row",
".",
"getColumnFamily",
"(",
")",
".",
"deletionInfo",
"(",
")",
",",
"row",
",",
... | Get portion of the columns and serialize in loop while not more columns left in the row
@param row SSTableIdentityIterator row representation with Column Family
@param key Decorated Key for the required row
@param out output stream | [
"Get",
"portion",
"of",
"the",
"columns",
"and",
"serialize",
"in",
"loop",
"while",
"not",
"more",
"columns",
"left",
"in",
"the",
"row"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/tools/SSTableExport.java#L179-L182 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/tools/SSTableExport.java | SSTableExport.enumeratekeys | public static void enumeratekeys(Descriptor desc, PrintStream outs, CFMetaData metadata)
throws IOException
{
KeyIterator iter = new KeyIterator(desc);
try
{
DecoratedKey lastKey = null;
while (iter.hasNext())
{
DecoratedKey key = iter.next();
// validate order of the keys in the sstable
if (lastKey != null && lastKey.compareTo(key) > 0)
throw new IOException("Key out of order! " + lastKey + " > " + key);
lastKey = key;
outs.println(metadata.getKeyValidator().getString(key.getKey()));
checkStream(outs); // flushes
}
}
finally
{
iter.close();
}
} | java | public static void enumeratekeys(Descriptor desc, PrintStream outs, CFMetaData metadata)
throws IOException
{
KeyIterator iter = new KeyIterator(desc);
try
{
DecoratedKey lastKey = null;
while (iter.hasNext())
{
DecoratedKey key = iter.next();
// validate order of the keys in the sstable
if (lastKey != null && lastKey.compareTo(key) > 0)
throw new IOException("Key out of order! " + lastKey + " > " + key);
lastKey = key;
outs.println(metadata.getKeyValidator().getString(key.getKey()));
checkStream(outs); // flushes
}
}
finally
{
iter.close();
}
} | [
"public",
"static",
"void",
"enumeratekeys",
"(",
"Descriptor",
"desc",
",",
"PrintStream",
"outs",
",",
"CFMetaData",
"metadata",
")",
"throws",
"IOException",
"{",
"KeyIterator",
"iter",
"=",
"new",
"KeyIterator",
"(",
"desc",
")",
";",
"try",
"{",
"Decorate... | Enumerate row keys from an SSTableReader and write the result to a PrintStream.
@param desc the descriptor of the file to export the rows from
@param outs PrintStream to write the output to
@param metadata Metadata to print keys in a proper format
@throws IOException on failure to read/write input/output | [
"Enumerate",
"row",
"keys",
"from",
"an",
"SSTableReader",
"and",
"write",
"the",
"result",
"to",
"a",
"PrintStream",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/tools/SSTableExport.java#L225-L249 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/tools/SSTableExport.java | SSTableExport.export | public static void export(Descriptor desc, PrintStream outs, Collection<String> toExport, String[] excludes, CFMetaData metadata) throws IOException
{
SSTableReader sstable = SSTableReader.open(desc);
RandomAccessReader dfile = sstable.openDataReader();
try
{
IPartitioner partitioner = sstable.partitioner;
if (excludes != null)
toExport.removeAll(Arrays.asList(excludes));
outs.println("[");
int i = 0;
// last key to compare order
DecoratedKey lastKey = null;
for (String key : toExport)
{
DecoratedKey decoratedKey = partitioner.decorateKey(metadata.getKeyValidator().fromString(key));
if (lastKey != null && lastKey.compareTo(decoratedKey) > 0)
throw new IOException("Key out of order! " + lastKey + " > " + decoratedKey);
lastKey = decoratedKey;
RowIndexEntry entry = sstable.getPosition(decoratedKey, SSTableReader.Operator.EQ);
if (entry == null)
continue;
dfile.seek(entry.position);
ByteBufferUtil.readWithShortLength(dfile); // row key
DeletionInfo deletionInfo = new DeletionInfo(DeletionTime.serializer.deserialize(dfile));
Iterator<OnDiskAtom> atomIterator = sstable.metadata.getOnDiskIterator(dfile, sstable.descriptor.version);
checkStream(outs);
if (i != 0)
outs.println(",");
i++;
serializeRow(deletionInfo, atomIterator, sstable.metadata, decoratedKey, outs);
}
outs.println("\n]");
outs.flush();
}
finally
{
dfile.close();
}
} | java | public static void export(Descriptor desc, PrintStream outs, Collection<String> toExport, String[] excludes, CFMetaData metadata) throws IOException
{
SSTableReader sstable = SSTableReader.open(desc);
RandomAccessReader dfile = sstable.openDataReader();
try
{
IPartitioner partitioner = sstable.partitioner;
if (excludes != null)
toExport.removeAll(Arrays.asList(excludes));
outs.println("[");
int i = 0;
// last key to compare order
DecoratedKey lastKey = null;
for (String key : toExport)
{
DecoratedKey decoratedKey = partitioner.decorateKey(metadata.getKeyValidator().fromString(key));
if (lastKey != null && lastKey.compareTo(decoratedKey) > 0)
throw new IOException("Key out of order! " + lastKey + " > " + decoratedKey);
lastKey = decoratedKey;
RowIndexEntry entry = sstable.getPosition(decoratedKey, SSTableReader.Operator.EQ);
if (entry == null)
continue;
dfile.seek(entry.position);
ByteBufferUtil.readWithShortLength(dfile); // row key
DeletionInfo deletionInfo = new DeletionInfo(DeletionTime.serializer.deserialize(dfile));
Iterator<OnDiskAtom> atomIterator = sstable.metadata.getOnDiskIterator(dfile, sstable.descriptor.version);
checkStream(outs);
if (i != 0)
outs.println(",");
i++;
serializeRow(deletionInfo, atomIterator, sstable.metadata, decoratedKey, outs);
}
outs.println("\n]");
outs.flush();
}
finally
{
dfile.close();
}
} | [
"public",
"static",
"void",
"export",
"(",
"Descriptor",
"desc",
",",
"PrintStream",
"outs",
",",
"Collection",
"<",
"String",
">",
"toExport",
",",
"String",
"[",
"]",
"excludes",
",",
"CFMetaData",
"metadata",
")",
"throws",
"IOException",
"{",
"SSTableReade... | Export specific rows from an SSTable and write the resulting JSON to a PrintStream.
@param desc the descriptor of the sstable to read from
@param outs PrintStream to write the output to
@param toExport the keys corresponding to the rows to export
@param excludes keys to exclude from export
@param metadata Metadata to print keys in a proper format
@throws IOException on failure to read/write input/output | [
"Export",
"specific",
"rows",
"from",
"an",
"SSTable",
"and",
"write",
"the",
"resulting",
"JSON",
"to",
"a",
"PrintStream",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/tools/SSTableExport.java#L261-L312 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/tools/SSTableExport.java | SSTableExport.export | static void export(SSTableReader reader, PrintStream outs, String[] excludes, CFMetaData metadata) throws IOException
{
Set<String> excludeSet = new HashSet<String>();
if (excludes != null)
excludeSet = new HashSet<String>(Arrays.asList(excludes));
SSTableIdentityIterator row;
ISSTableScanner scanner = reader.getScanner();
try
{
outs.println("[");
int i = 0;
// collecting keys to export
while (scanner.hasNext())
{
row = (SSTableIdentityIterator) scanner.next();
String currentKey = row.getColumnFamily().metadata().getKeyValidator().getString(row.getKey().getKey());
if (excludeSet.contains(currentKey))
continue;
else if (i != 0)
outs.println(",");
serializeRow(row, row.getKey(), outs);
checkStream(outs);
i++;
}
outs.println("\n]");
outs.flush();
}
finally
{
scanner.close();
}
} | java | static void export(SSTableReader reader, PrintStream outs, String[] excludes, CFMetaData metadata) throws IOException
{
Set<String> excludeSet = new HashSet<String>();
if (excludes != null)
excludeSet = new HashSet<String>(Arrays.asList(excludes));
SSTableIdentityIterator row;
ISSTableScanner scanner = reader.getScanner();
try
{
outs.println("[");
int i = 0;
// collecting keys to export
while (scanner.hasNext())
{
row = (SSTableIdentityIterator) scanner.next();
String currentKey = row.getColumnFamily().metadata().getKeyValidator().getString(row.getKey().getKey());
if (excludeSet.contains(currentKey))
continue;
else if (i != 0)
outs.println(",");
serializeRow(row, row.getKey(), outs);
checkStream(outs);
i++;
}
outs.println("\n]");
outs.flush();
}
finally
{
scanner.close();
}
} | [
"static",
"void",
"export",
"(",
"SSTableReader",
"reader",
",",
"PrintStream",
"outs",
",",
"String",
"[",
"]",
"excludes",
",",
"CFMetaData",
"metadata",
")",
"throws",
"IOException",
"{",
"Set",
"<",
"String",
">",
"excludeSet",
"=",
"new",
"HashSet",
"<"... | than once from within the same process. | [
"than",
"once",
"from",
"within",
"the",
"same",
"process",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/tools/SSTableExport.java#L316-L356 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/tools/SSTableExport.java | SSTableExport.export | public static void export(Descriptor desc, PrintStream outs, String[] excludes, CFMetaData metadata) throws IOException
{
export(SSTableReader.open(desc), outs, excludes, metadata);
} | java | public static void export(Descriptor desc, PrintStream outs, String[] excludes, CFMetaData metadata) throws IOException
{
export(SSTableReader.open(desc), outs, excludes, metadata);
} | [
"public",
"static",
"void",
"export",
"(",
"Descriptor",
"desc",
",",
"PrintStream",
"outs",
",",
"String",
"[",
"]",
"excludes",
",",
"CFMetaData",
"metadata",
")",
"throws",
"IOException",
"{",
"export",
"(",
"SSTableReader",
".",
"open",
"(",
"desc",
")",... | Export an SSTable and write the resulting JSON to a PrintStream.
@param desc the descriptor of the sstable to read from
@param outs PrintStream to write the output to
@param excludes keys to exclude from export
@param metadata Metadata to print keys in a proper format
@throws IOException on failure to read/write input/output | [
"Export",
"an",
"SSTable",
"and",
"write",
"the",
"resulting",
"JSON",
"to",
"a",
"PrintStream",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/tools/SSTableExport.java#L367-L370 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/tools/SSTableExport.java | SSTableExport.export | public static void export(Descriptor desc, String[] excludes, CFMetaData metadata) throws IOException
{
export(desc, System.out, excludes, metadata);
} | java | public static void export(Descriptor desc, String[] excludes, CFMetaData metadata) throws IOException
{
export(desc, System.out, excludes, metadata);
} | [
"public",
"static",
"void",
"export",
"(",
"Descriptor",
"desc",
",",
"String",
"[",
"]",
"excludes",
",",
"CFMetaData",
"metadata",
")",
"throws",
"IOException",
"{",
"export",
"(",
"desc",
",",
"System",
".",
"out",
",",
"excludes",
",",
"metadata",
")",... | Export an SSTable and write the resulting JSON to standard out.
@param desc the descriptor of the sstable to read from
@param excludes keys to exclude from export
@param metadata Metadata to print keys in a proper format
@throws IOException on failure to read/write SSTable/standard out | [
"Export",
"an",
"SSTable",
"and",
"write",
"the",
"resulting",
"JSON",
"to",
"standard",
"out",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/tools/SSTableExport.java#L380-L383 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/tools/SSTableExport.java | SSTableExport.main | public static void main(String[] args) throws ConfigurationException
{
String usage = String.format("Usage: %s <sstable> [-k key [-k key [...]] -x key [-x key [...]]]%n", SSTableExport.class.getName());
CommandLineParser parser = new PosixParser();
try
{
cmd = parser.parse(options, args);
}
catch (ParseException e1)
{
System.err.println(e1.getMessage());
System.err.println(usage);
System.exit(1);
}
if (cmd.getArgs().length != 1)
{
System.err.println("You must supply exactly one sstable");
System.err.println(usage);
System.exit(1);
}
String[] keys = cmd.getOptionValues(KEY_OPTION);
String[] excludes = cmd.getOptionValues(EXCLUDEKEY_OPTION);
String ssTableFileName = new File(cmd.getArgs()[0]).getAbsolutePath();
DatabaseDescriptor.loadSchemas(false);
Descriptor descriptor = Descriptor.fromFilename(ssTableFileName);
// Start by validating keyspace name
if (Schema.instance.getKSMetaData(descriptor.ksname) == null)
{
System.err.println(String.format("Filename %s references to nonexistent keyspace: %s!",
ssTableFileName, descriptor.ksname));
System.exit(1);
}
Keyspace keyspace = Keyspace.open(descriptor.ksname);
// Make it works for indexes too - find parent cf if necessary
String baseName = descriptor.cfname;
if (descriptor.cfname.contains("."))
{
String[] parts = descriptor.cfname.split("\\.", 2);
baseName = parts[0];
}
// IllegalArgumentException will be thrown here if ks/cf pair does not exist
ColumnFamilyStore cfStore = null;
try
{
cfStore = keyspace.getColumnFamilyStore(baseName);
}
catch (IllegalArgumentException e)
{
System.err.println(String.format("The provided column family is not part of this cassandra keyspace: keyspace = %s, column family = %s",
descriptor.ksname, descriptor.cfname));
System.exit(1);
}
try
{
if (cmd.hasOption(ENUMERATEKEYS_OPTION))
{
enumeratekeys(descriptor, System.out, cfStore.metadata);
}
else
{
if ((keys != null) && (keys.length > 0))
export(descriptor, System.out, Arrays.asList(keys), excludes, cfStore.metadata);
else
export(descriptor, excludes, cfStore.metadata);
}
}
catch (IOException e)
{
// throwing exception outside main with broken pipe causes windows cmd to hang
e.printStackTrace(System.err);
}
System.exit(0);
} | java | public static void main(String[] args) throws ConfigurationException
{
String usage = String.format("Usage: %s <sstable> [-k key [-k key [...]] -x key [-x key [...]]]%n", SSTableExport.class.getName());
CommandLineParser parser = new PosixParser();
try
{
cmd = parser.parse(options, args);
}
catch (ParseException e1)
{
System.err.println(e1.getMessage());
System.err.println(usage);
System.exit(1);
}
if (cmd.getArgs().length != 1)
{
System.err.println("You must supply exactly one sstable");
System.err.println(usage);
System.exit(1);
}
String[] keys = cmd.getOptionValues(KEY_OPTION);
String[] excludes = cmd.getOptionValues(EXCLUDEKEY_OPTION);
String ssTableFileName = new File(cmd.getArgs()[0]).getAbsolutePath();
DatabaseDescriptor.loadSchemas(false);
Descriptor descriptor = Descriptor.fromFilename(ssTableFileName);
// Start by validating keyspace name
if (Schema.instance.getKSMetaData(descriptor.ksname) == null)
{
System.err.println(String.format("Filename %s references to nonexistent keyspace: %s!",
ssTableFileName, descriptor.ksname));
System.exit(1);
}
Keyspace keyspace = Keyspace.open(descriptor.ksname);
// Make it works for indexes too - find parent cf if necessary
String baseName = descriptor.cfname;
if (descriptor.cfname.contains("."))
{
String[] parts = descriptor.cfname.split("\\.", 2);
baseName = parts[0];
}
// IllegalArgumentException will be thrown here if ks/cf pair does not exist
ColumnFamilyStore cfStore = null;
try
{
cfStore = keyspace.getColumnFamilyStore(baseName);
}
catch (IllegalArgumentException e)
{
System.err.println(String.format("The provided column family is not part of this cassandra keyspace: keyspace = %s, column family = %s",
descriptor.ksname, descriptor.cfname));
System.exit(1);
}
try
{
if (cmd.hasOption(ENUMERATEKEYS_OPTION))
{
enumeratekeys(descriptor, System.out, cfStore.metadata);
}
else
{
if ((keys != null) && (keys.length > 0))
export(descriptor, System.out, Arrays.asList(keys), excludes, cfStore.metadata);
else
export(descriptor, excludes, cfStore.metadata);
}
}
catch (IOException e)
{
// throwing exception outside main with broken pipe causes windows cmd to hang
e.printStackTrace(System.err);
}
System.exit(0);
} | [
"public",
"static",
"void",
"main",
"(",
"String",
"[",
"]",
"args",
")",
"throws",
"ConfigurationException",
"{",
"String",
"usage",
"=",
"String",
".",
"format",
"(",
"\"Usage: %s <sstable> [-k key [-k key [...]] -x key [-x key [...]]]%n\"",
",",
"SSTableExport",
".",... | Given arguments specifying an SSTable, and optionally an output file,
export the contents of the SSTable to JSON.
@param args command lines arguments
@throws IOException on failure to open/read/write files or output streams
@throws ConfigurationException on configuration failure (wrong params given) | [
"Given",
"arguments",
"specifying",
"an",
"SSTable",
"and",
"optionally",
"an",
"output",
"file",
"export",
"the",
"contents",
"of",
"the",
"SSTable",
"to",
"JSON",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/tools/SSTableExport.java#L393-L476 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/utils/SemanticVersion.java | SemanticVersion.findSupportingVersion | public SemanticVersion findSupportingVersion(SemanticVersion... versions)
{
for (SemanticVersion version : versions)
{
if (isSupportedBy(version))
return version;
}
return null;
} | java | public SemanticVersion findSupportingVersion(SemanticVersion... versions)
{
for (SemanticVersion version : versions)
{
if (isSupportedBy(version))
return version;
}
return null;
} | [
"public",
"SemanticVersion",
"findSupportingVersion",
"(",
"SemanticVersion",
"...",
"versions",
")",
"{",
"for",
"(",
"SemanticVersion",
"version",
":",
"versions",
")",
"{",
"if",
"(",
"isSupportedBy",
"(",
"version",
")",
")",
"return",
"version",
";",
"}",
... | Returns a version that is backward compatible with this version amongst a list
of provided version, or null if none can be found.
For instance:
"2.0.0".findSupportingVersion("2.0.0", "3.0.0") == "2.0.0"
"2.0.0".findSupportingVersion("2.1.3", "3.0.0") == "2.1.3"
"2.0.0".findSupportingVersion("3.0.0") == null
"2.0.3".findSupportingVersion("2.0.0") == "2.0.0"
"2.1.0".findSupportingVersion("2.0.0") == null | [
"Returns",
"a",
"version",
"that",
"is",
"backward",
"compatible",
"with",
"this",
"version",
"amongst",
"a",
"list",
"of",
"provided",
"version",
"or",
"null",
"if",
"none",
"can",
"be",
"found",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/utils/SemanticVersion.java#L134-L142 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/io/sstable/IndexSummaryManager.java | IndexSummaryManager.getCompactingAndNonCompactingSSTables | private Pair<List<SSTableReader>, Multimap<DataTracker, SSTableReader>> getCompactingAndNonCompactingSSTables()
{
List<SSTableReader> allCompacting = new ArrayList<>();
Multimap<DataTracker, SSTableReader> allNonCompacting = HashMultimap.create();
for (Keyspace ks : Keyspace.all())
{
for (ColumnFamilyStore cfStore: ks.getColumnFamilyStores())
{
Set<SSTableReader> nonCompacting, allSSTables;
do
{
allSSTables = cfStore.getDataTracker().getSSTables();
nonCompacting = Sets.newHashSet(cfStore.getDataTracker().getUncompactingSSTables(allSSTables));
}
while (!(nonCompacting.isEmpty() || cfStore.getDataTracker().markCompacting(nonCompacting)));
allNonCompacting.putAll(cfStore.getDataTracker(), nonCompacting);
allCompacting.addAll(Sets.difference(allSSTables, nonCompacting));
}
}
return Pair.create(allCompacting, allNonCompacting);
} | java | private Pair<List<SSTableReader>, Multimap<DataTracker, SSTableReader>> getCompactingAndNonCompactingSSTables()
{
List<SSTableReader> allCompacting = new ArrayList<>();
Multimap<DataTracker, SSTableReader> allNonCompacting = HashMultimap.create();
for (Keyspace ks : Keyspace.all())
{
for (ColumnFamilyStore cfStore: ks.getColumnFamilyStores())
{
Set<SSTableReader> nonCompacting, allSSTables;
do
{
allSSTables = cfStore.getDataTracker().getSSTables();
nonCompacting = Sets.newHashSet(cfStore.getDataTracker().getUncompactingSSTables(allSSTables));
}
while (!(nonCompacting.isEmpty() || cfStore.getDataTracker().markCompacting(nonCompacting)));
allNonCompacting.putAll(cfStore.getDataTracker(), nonCompacting);
allCompacting.addAll(Sets.difference(allSSTables, nonCompacting));
}
}
return Pair.create(allCompacting, allNonCompacting);
} | [
"private",
"Pair",
"<",
"List",
"<",
"SSTableReader",
">",
",",
"Multimap",
"<",
"DataTracker",
",",
"SSTableReader",
">",
">",
"getCompactingAndNonCompactingSSTables",
"(",
")",
"{",
"List",
"<",
"SSTableReader",
">",
"allCompacting",
"=",
"new",
"ArrayList",
"... | Returns a Pair of all compacting and non-compacting sstables. Non-compacting sstables will be marked as
compacting. | [
"Returns",
"a",
"Pair",
"of",
"all",
"compacting",
"and",
"non",
"-",
"compacting",
"sstables",
".",
"Non",
"-",
"compacting",
"sstables",
"will",
"be",
"marked",
"as",
"compacting",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/io/sstable/IndexSummaryManager.java#L211-L231 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/io/sstable/IndexSummaryManager.java | IndexSummaryManager.redistributeSummaries | @VisibleForTesting
public static List<SSTableReader> redistributeSummaries(List<SSTableReader> compacting, List<SSTableReader> nonCompacting, long memoryPoolBytes) throws IOException
{
long total = 0;
for (SSTableReader sstable : Iterables.concat(compacting, nonCompacting))
total += sstable.getIndexSummaryOffHeapSize();
List<SSTableReader> oldFormatSSTables = new ArrayList<>();
for (SSTableReader sstable : nonCompacting)
{
// We can't change the sampling level of sstables with the old format, because the serialization format
// doesn't include the sampling level. Leave this one as it is. (See CASSANDRA-8993 for details.)
logger.trace("SSTable {} cannot be re-sampled due to old sstable format", sstable);
if (!sstable.descriptor.version.hasSamplingLevel)
oldFormatSSTables.add(sstable);
}
nonCompacting.removeAll(oldFormatSSTables);
logger.debug("Beginning redistribution of index summaries for {} sstables with memory pool size {} MB; current spaced used is {} MB",
nonCompacting.size(), memoryPoolBytes / 1024L / 1024L, total / 1024.0 / 1024.0);
final Map<SSTableReader, Double> readRates = new HashMap<>(nonCompacting.size());
double totalReadsPerSec = 0.0;
for (SSTableReader sstable : nonCompacting)
{
if (sstable.getReadMeter() != null)
{
Double readRate = sstable.getReadMeter().fifteenMinuteRate();
totalReadsPerSec += readRate;
readRates.put(sstable, readRate);
}
}
logger.trace("Total reads/sec across all sstables in index summary resize process: {}", totalReadsPerSec);
// copy and sort by read rates (ascending)
List<SSTableReader> sstablesByHotness = new ArrayList<>(nonCompacting);
Collections.sort(sstablesByHotness, new ReadRateComparator(readRates));
long remainingBytes = memoryPoolBytes;
for (SSTableReader sstable : Iterables.concat(compacting, oldFormatSSTables))
remainingBytes -= sstable.getIndexSummaryOffHeapSize();
logger.trace("Index summaries for compacting SSTables are using {} MB of space",
(memoryPoolBytes - remainingBytes) / 1024.0 / 1024.0);
List<SSTableReader> newSSTables = adjustSamplingLevels(sstablesByHotness, totalReadsPerSec, remainingBytes);
total = 0;
for (SSTableReader sstable : Iterables.concat(compacting, oldFormatSSTables, newSSTables))
total += sstable.getIndexSummaryOffHeapSize();
logger.debug("Completed resizing of index summaries; current approximate memory used: {} MB",
total / 1024.0 / 1024.0);
return newSSTables;
} | java | @VisibleForTesting
public static List<SSTableReader> redistributeSummaries(List<SSTableReader> compacting, List<SSTableReader> nonCompacting, long memoryPoolBytes) throws IOException
{
long total = 0;
for (SSTableReader sstable : Iterables.concat(compacting, nonCompacting))
total += sstable.getIndexSummaryOffHeapSize();
List<SSTableReader> oldFormatSSTables = new ArrayList<>();
for (SSTableReader sstable : nonCompacting)
{
// We can't change the sampling level of sstables with the old format, because the serialization format
// doesn't include the sampling level. Leave this one as it is. (See CASSANDRA-8993 for details.)
logger.trace("SSTable {} cannot be re-sampled due to old sstable format", sstable);
if (!sstable.descriptor.version.hasSamplingLevel)
oldFormatSSTables.add(sstable);
}
nonCompacting.removeAll(oldFormatSSTables);
logger.debug("Beginning redistribution of index summaries for {} sstables with memory pool size {} MB; current spaced used is {} MB",
nonCompacting.size(), memoryPoolBytes / 1024L / 1024L, total / 1024.0 / 1024.0);
final Map<SSTableReader, Double> readRates = new HashMap<>(nonCompacting.size());
double totalReadsPerSec = 0.0;
for (SSTableReader sstable : nonCompacting)
{
if (sstable.getReadMeter() != null)
{
Double readRate = sstable.getReadMeter().fifteenMinuteRate();
totalReadsPerSec += readRate;
readRates.put(sstable, readRate);
}
}
logger.trace("Total reads/sec across all sstables in index summary resize process: {}", totalReadsPerSec);
// copy and sort by read rates (ascending)
List<SSTableReader> sstablesByHotness = new ArrayList<>(nonCompacting);
Collections.sort(sstablesByHotness, new ReadRateComparator(readRates));
long remainingBytes = memoryPoolBytes;
for (SSTableReader sstable : Iterables.concat(compacting, oldFormatSSTables))
remainingBytes -= sstable.getIndexSummaryOffHeapSize();
logger.trace("Index summaries for compacting SSTables are using {} MB of space",
(memoryPoolBytes - remainingBytes) / 1024.0 / 1024.0);
List<SSTableReader> newSSTables = adjustSamplingLevels(sstablesByHotness, totalReadsPerSec, remainingBytes);
total = 0;
for (SSTableReader sstable : Iterables.concat(compacting, oldFormatSSTables, newSSTables))
total += sstable.getIndexSummaryOffHeapSize();
logger.debug("Completed resizing of index summaries; current approximate memory used: {} MB",
total / 1024.0 / 1024.0);
return newSSTables;
} | [
"@",
"VisibleForTesting",
"public",
"static",
"List",
"<",
"SSTableReader",
">",
"redistributeSummaries",
"(",
"List",
"<",
"SSTableReader",
">",
"compacting",
",",
"List",
"<",
"SSTableReader",
">",
"nonCompacting",
",",
"long",
"memoryPoolBytes",
")",
"throws",
... | Attempts to fairly distribute a fixed pool of memory for index summaries across a set of SSTables based on
their recent read rates.
@param nonCompacting a list of sstables to share the memory pool across
@param memoryPoolBytes a size (in bytes) that the total index summary space usage should stay close to or
under, if possible
@return a list of new SSTableReader instances | [
"Attempts",
"to",
"fairly",
"distribute",
"a",
"fixed",
"pool",
"of",
"memory",
"for",
"index",
"summaries",
"across",
"a",
"set",
"of",
"SSTables",
"based",
"on",
"their",
"recent",
"read",
"rates",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/io/sstable/IndexSummaryManager.java#L255-L308 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/cql/Term.java | Term.getByteBuffer | public ByteBuffer getByteBuffer() throws InvalidRequestException
{
switch (type)
{
case STRING:
return AsciiType.instance.fromString(text);
case INTEGER:
return IntegerType.instance.fromString(text);
case UUID:
// we specifically want the Lexical class here, not "UUIDType," because we're supposed to have
// a uuid-shaped string here, and UUIDType also accepts integer or date strings (and turns them into version 1 uuids).
return LexicalUUIDType.instance.fromString(text);
case FLOAT:
return FloatType.instance.fromString(text);
}
// FIXME: handle scenario that should never happen
return null;
} | java | public ByteBuffer getByteBuffer() throws InvalidRequestException
{
switch (type)
{
case STRING:
return AsciiType.instance.fromString(text);
case INTEGER:
return IntegerType.instance.fromString(text);
case UUID:
// we specifically want the Lexical class here, not "UUIDType," because we're supposed to have
// a uuid-shaped string here, and UUIDType also accepts integer or date strings (and turns them into version 1 uuids).
return LexicalUUIDType.instance.fromString(text);
case FLOAT:
return FloatType.instance.fromString(text);
}
// FIXME: handle scenario that should never happen
return null;
} | [
"public",
"ByteBuffer",
"getByteBuffer",
"(",
")",
"throws",
"InvalidRequestException",
"{",
"switch",
"(",
"type",
")",
"{",
"case",
"STRING",
":",
"return",
"AsciiType",
".",
"instance",
".",
"fromString",
"(",
"text",
")",
";",
"case",
"INTEGER",
":",
"re... | Returns the typed value, serialized to a ByteBuffer.
@return a ByteBuffer of the value.
@throws InvalidRequestException if unable to coerce the string to its type. | [
"Returns",
"the",
"typed",
"value",
"serialized",
"to",
"a",
"ByteBuffer",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cql/Term.java#L113-L131 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/concurrent/SEPWorker.java | SEPWorker.selfAssign | private boolean selfAssign()
{
// if we aren't permitted to assign in this state, fail
if (!get().canAssign(true))
return false;
for (SEPExecutor exec : pool.executors)
{
if (exec.takeWorkPermit(true))
{
Work work = new Work(exec);
// we successfully started work on this executor, so we must either assign it to ourselves or ...
if (assign(work, true))
return true;
// ... if we fail, schedule it to another worker
pool.schedule(work);
// and return success as we must have already been assigned a task
assert get().assigned != null;
return true;
}
}
return false;
} | java | private boolean selfAssign()
{
// if we aren't permitted to assign in this state, fail
if (!get().canAssign(true))
return false;
for (SEPExecutor exec : pool.executors)
{
if (exec.takeWorkPermit(true))
{
Work work = new Work(exec);
// we successfully started work on this executor, so we must either assign it to ourselves or ...
if (assign(work, true))
return true;
// ... if we fail, schedule it to another worker
pool.schedule(work);
// and return success as we must have already been assigned a task
assert get().assigned != null;
return true;
}
}
return false;
} | [
"private",
"boolean",
"selfAssign",
"(",
")",
"{",
"// if we aren't permitted to assign in this state, fail",
"if",
"(",
"!",
"get",
"(",
")",
".",
"canAssign",
"(",
"true",
")",
")",
"return",
"false",
";",
"for",
"(",
"SEPExecutor",
"exec",
":",
"pool",
".",... | try to assign ourselves an executor with work available | [
"try",
"to",
"assign",
"ourselves",
"an",
"executor",
"with",
"work",
"available"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/concurrent/SEPWorker.java#L179-L200 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/concurrent/SEPWorker.java | SEPWorker.startSpinning | private void startSpinning()
{
assert get() == Work.WORKING;
pool.spinningCount.incrementAndGet();
set(Work.SPINNING);
} | java | private void startSpinning()
{
assert get() == Work.WORKING;
pool.spinningCount.incrementAndGet();
set(Work.SPINNING);
} | [
"private",
"void",
"startSpinning",
"(",
")",
"{",
"assert",
"get",
"(",
")",
"==",
"Work",
".",
"WORKING",
";",
"pool",
".",
"spinningCount",
".",
"incrementAndGet",
"(",
")",
";",
"set",
"(",
"Work",
".",
"SPINNING",
")",
";",
"}"
] | collection at the same time | [
"collection",
"at",
"the",
"same",
"time"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/concurrent/SEPWorker.java#L205-L210 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/concurrent/SEPWorker.java | SEPWorker.doWaitSpin | private void doWaitSpin()
{
// pick a random sleep interval based on the number of threads spinning, so that
// we should always have a thread about to wake up, but most threads are sleeping
long sleep = 10000L * pool.spinningCount.get();
sleep = Math.min(1000000, sleep);
sleep *= Math.random();
sleep = Math.max(10000, sleep);
long start = System.nanoTime();
// place ourselves in the spinning collection; if we clash with another thread just exit
Long target = start + sleep;
if (pool.spinning.putIfAbsent(target, this) != null)
return;
LockSupport.parkNanos(sleep);
// remove ourselves (if haven't been already) - we should be at or near the front, so should be cheap-ish
pool.spinning.remove(target, this);
// finish timing and grab spinningTime (before we finish timing so it is under rather than overestimated)
long end = System.nanoTime();
long spin = end - start;
long stopCheck = pool.stopCheck.addAndGet(spin);
maybeStop(stopCheck, end);
if (prevStopCheck + spin == stopCheck)
soleSpinnerSpinTime += spin;
else
soleSpinnerSpinTime = 0;
prevStopCheck = stopCheck;
} | java | private void doWaitSpin()
{
// pick a random sleep interval based on the number of threads spinning, so that
// we should always have a thread about to wake up, but most threads are sleeping
long sleep = 10000L * pool.spinningCount.get();
sleep = Math.min(1000000, sleep);
sleep *= Math.random();
sleep = Math.max(10000, sleep);
long start = System.nanoTime();
// place ourselves in the spinning collection; if we clash with another thread just exit
Long target = start + sleep;
if (pool.spinning.putIfAbsent(target, this) != null)
return;
LockSupport.parkNanos(sleep);
// remove ourselves (if haven't been already) - we should be at or near the front, so should be cheap-ish
pool.spinning.remove(target, this);
// finish timing and grab spinningTime (before we finish timing so it is under rather than overestimated)
long end = System.nanoTime();
long spin = end - start;
long stopCheck = pool.stopCheck.addAndGet(spin);
maybeStop(stopCheck, end);
if (prevStopCheck + spin == stopCheck)
soleSpinnerSpinTime += spin;
else
soleSpinnerSpinTime = 0;
prevStopCheck = stopCheck;
} | [
"private",
"void",
"doWaitSpin",
"(",
")",
"{",
"// pick a random sleep interval based on the number of threads spinning, so that",
"// we should always have a thread about to wake up, but most threads are sleeping",
"long",
"sleep",
"=",
"10000L",
"*",
"pool",
".",
"spinningCount",
... | perform a sleep-spin, incrementing pool.stopCheck accordingly | [
"perform",
"a",
"sleep",
"-",
"spin",
"incrementing",
"pool",
".",
"stopCheck",
"accordingly"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/concurrent/SEPWorker.java#L223-L253 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/concurrent/SEPWorker.java | SEPWorker.maybeStop | private void maybeStop(long stopCheck, long now)
{
long delta = now - stopCheck;
if (delta <= 0)
{
// if stopCheck has caught up with present, we've been spinning too much, so if we can atomically
// set it to the past again, we should stop a worker
if (pool.stopCheck.compareAndSet(stopCheck, now - stopCheckInterval))
{
// try and stop ourselves;
// if we've already been assigned work stop another worker
if (!assign(Work.STOP_SIGNALLED, true))
pool.schedule(Work.STOP_SIGNALLED);
}
}
else if (soleSpinnerSpinTime > stopCheckInterval && pool.spinningCount.get() == 1)
{
// permit self-stopping
assign(Work.STOP_SIGNALLED, true);
}
else
{
// if stop check has gotten too far behind present, update it so new spins can affect it
while (delta > stopCheckInterval * 2 && !pool.stopCheck.compareAndSet(stopCheck, now - stopCheckInterval))
{
stopCheck = pool.stopCheck.get();
delta = now - stopCheck;
}
}
} | java | private void maybeStop(long stopCheck, long now)
{
long delta = now - stopCheck;
if (delta <= 0)
{
// if stopCheck has caught up with present, we've been spinning too much, so if we can atomically
// set it to the past again, we should stop a worker
if (pool.stopCheck.compareAndSet(stopCheck, now - stopCheckInterval))
{
// try and stop ourselves;
// if we've already been assigned work stop another worker
if (!assign(Work.STOP_SIGNALLED, true))
pool.schedule(Work.STOP_SIGNALLED);
}
}
else if (soleSpinnerSpinTime > stopCheckInterval && pool.spinningCount.get() == 1)
{
// permit self-stopping
assign(Work.STOP_SIGNALLED, true);
}
else
{
// if stop check has gotten too far behind present, update it so new spins can affect it
while (delta > stopCheckInterval * 2 && !pool.stopCheck.compareAndSet(stopCheck, now - stopCheckInterval))
{
stopCheck = pool.stopCheck.get();
delta = now - stopCheck;
}
}
} | [
"private",
"void",
"maybeStop",
"(",
"long",
"stopCheck",
",",
"long",
"now",
")",
"{",
"long",
"delta",
"=",
"now",
"-",
"stopCheck",
";",
"if",
"(",
"delta",
"<=",
"0",
")",
"{",
"// if stopCheck has caught up with present, we've been spinning too much, so if we c... | realtime we have spun too much and deschedule; if we get too far behind realtime, we reset to our initial offset | [
"realtime",
"we",
"have",
"spun",
"too",
"much",
"and",
"deschedule",
";",
"if",
"we",
"get",
"too",
"far",
"behind",
"realtime",
"we",
"reset",
"to",
"our",
"initial",
"offset"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/concurrent/SEPWorker.java#L261-L290 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/db/index/SecondaryIndexSearcher.java | SecondaryIndexSearcher.postReconciliationProcessing | public List<Row> postReconciliationProcessing(List<IndexExpression> clause, List<Row> rows)
{
return rows;
} | java | public List<Row> postReconciliationProcessing(List<IndexExpression> clause, List<Row> rows)
{
return rows;
} | [
"public",
"List",
"<",
"Row",
">",
"postReconciliationProcessing",
"(",
"List",
"<",
"IndexExpression",
">",
"clause",
",",
"List",
"<",
"Row",
">",
"rows",
")",
"{",
"return",
"rows",
";",
"}"
] | Combines index query results from multiple nodes. This is done by the coordinator node after it has reconciled
the replica responses.
@param clause A list of {@link IndexExpression}s
@param rows The index query results to be combined
@return The combination of the index query results | [
"Combines",
"index",
"query",
"results",
"from",
"multiple",
"nodes",
".",
"This",
"is",
"done",
"by",
"the",
"coordinator",
"node",
"after",
"it",
"has",
"reconciled",
"the",
"replica",
"responses",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/index/SecondaryIndexSearcher.java#L136-L139 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/db/index/SecondaryIndex.java | SecondaryIndex.isIndexBuilt | public boolean isIndexBuilt(ByteBuffer columnName)
{
return SystemKeyspace.isIndexBuilt(baseCfs.keyspace.getName(), getNameForSystemKeyspace(columnName));
} | java | public boolean isIndexBuilt(ByteBuffer columnName)
{
return SystemKeyspace.isIndexBuilt(baseCfs.keyspace.getName(), getNameForSystemKeyspace(columnName));
} | [
"public",
"boolean",
"isIndexBuilt",
"(",
"ByteBuffer",
"columnName",
")",
"{",
"return",
"SystemKeyspace",
".",
"isIndexBuilt",
"(",
"baseCfs",
".",
"keyspace",
".",
"getName",
"(",
")",
",",
"getNameForSystemKeyspace",
"(",
"columnName",
")",
")",
";",
"}"
] | Checks if the index for specified column is fully built
@param columnName the column
@return true if the index is fully built | [
"Checks",
"if",
"the",
"index",
"for",
"specified",
"column",
"is",
"fully",
"built"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/index/SecondaryIndex.java#L143-L146 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/db/index/SecondaryIndex.java | SecondaryIndex.buildIndexBlocking | protected void buildIndexBlocking()
{
logger.info(String.format("Submitting index build of %s for data in %s",
getIndexName(), StringUtils.join(baseCfs.getSSTables(), ", ")));
try (Refs<SSTableReader> sstables = baseCfs.selectAndReference(ColumnFamilyStore.CANONICAL_SSTABLES).refs)
{
SecondaryIndexBuilder builder = new SecondaryIndexBuilder(baseCfs,
Collections.singleton(getIndexName()),
new ReducingKeyIterator(sstables));
Future<?> future = CompactionManager.instance.submitIndexBuild(builder);
FBUtilities.waitOnFuture(future);
forceBlockingFlush();
setIndexBuilt();
}
logger.info("Index build of {} complete", getIndexName());
} | java | protected void buildIndexBlocking()
{
logger.info(String.format("Submitting index build of %s for data in %s",
getIndexName(), StringUtils.join(baseCfs.getSSTables(), ", ")));
try (Refs<SSTableReader> sstables = baseCfs.selectAndReference(ColumnFamilyStore.CANONICAL_SSTABLES).refs)
{
SecondaryIndexBuilder builder = new SecondaryIndexBuilder(baseCfs,
Collections.singleton(getIndexName()),
new ReducingKeyIterator(sstables));
Future<?> future = CompactionManager.instance.submitIndexBuild(builder);
FBUtilities.waitOnFuture(future);
forceBlockingFlush();
setIndexBuilt();
}
logger.info("Index build of {} complete", getIndexName());
} | [
"protected",
"void",
"buildIndexBlocking",
"(",
")",
"{",
"logger",
".",
"info",
"(",
"String",
".",
"format",
"(",
"\"Submitting index build of %s for data in %s\"",
",",
"getIndexName",
"(",
")",
",",
"StringUtils",
".",
"join",
"(",
"baseCfs",
".",
"getSSTables... | Builds the index using the data in the underlying CFS
Blocks till it's complete | [
"Builds",
"the",
"index",
"using",
"the",
"data",
"in",
"the",
"underlying",
"CFS",
"Blocks",
"till",
"it",
"s",
"complete"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/index/SecondaryIndex.java#L202-L218 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/db/index/SecondaryIndex.java | SecondaryIndex.buildIndexAsync | public Future<?> buildIndexAsync()
{
// if we're just linking in the index to indexedColumns on an already-built index post-restart, we're done
boolean allAreBuilt = true;
for (ColumnDefinition cdef : columnDefs)
{
if (!SystemKeyspace.isIndexBuilt(baseCfs.keyspace.getName(), getNameForSystemKeyspace(cdef.name.bytes)))
{
allAreBuilt = false;
break;
}
}
if (allAreBuilt)
return null;
// build it asynchronously; addIndex gets called by CFS open and schema update, neither of which
// we want to block for a long period. (actual build is serialized on CompactionManager.)
Runnable runnable = new Runnable()
{
public void run()
{
baseCfs.forceBlockingFlush();
buildIndexBlocking();
}
};
FutureTask<?> f = new FutureTask<Object>(runnable, null);
new Thread(f, "Creating index: " + getIndexName()).start();
return f;
} | java | public Future<?> buildIndexAsync()
{
// if we're just linking in the index to indexedColumns on an already-built index post-restart, we're done
boolean allAreBuilt = true;
for (ColumnDefinition cdef : columnDefs)
{
if (!SystemKeyspace.isIndexBuilt(baseCfs.keyspace.getName(), getNameForSystemKeyspace(cdef.name.bytes)))
{
allAreBuilt = false;
break;
}
}
if (allAreBuilt)
return null;
// build it asynchronously; addIndex gets called by CFS open and schema update, neither of which
// we want to block for a long period. (actual build is serialized on CompactionManager.)
Runnable runnable = new Runnable()
{
public void run()
{
baseCfs.forceBlockingFlush();
buildIndexBlocking();
}
};
FutureTask<?> f = new FutureTask<Object>(runnable, null);
new Thread(f, "Creating index: " + getIndexName()).start();
return f;
} | [
"public",
"Future",
"<",
"?",
">",
"buildIndexAsync",
"(",
")",
"{",
"// if we're just linking in the index to indexedColumns on an already-built index post-restart, we're done",
"boolean",
"allAreBuilt",
"=",
"true",
";",
"for",
"(",
"ColumnDefinition",
"cdef",
":",
"columnD... | Builds the index using the data in the underlying CF, non blocking
@return A future object which the caller can block on (optional) | [
"Builds",
"the",
"index",
"using",
"the",
"data",
"in",
"the",
"underlying",
"CF",
"non",
"blocking"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/index/SecondaryIndex.java#L227-L257 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/db/index/SecondaryIndex.java | SecondaryIndex.getIndexKeyFor | public DecoratedKey getIndexKeyFor(ByteBuffer value)
{
// FIXME: this imply one column definition per index
ByteBuffer name = columnDefs.iterator().next().name.bytes;
return new BufferDecoratedKey(new LocalToken(baseCfs.metadata.getColumnDefinition(name).type, value), value);
} | java | public DecoratedKey getIndexKeyFor(ByteBuffer value)
{
// FIXME: this imply one column definition per index
ByteBuffer name = columnDefs.iterator().next().name.bytes;
return new BufferDecoratedKey(new LocalToken(baseCfs.metadata.getColumnDefinition(name).type, value), value);
} | [
"public",
"DecoratedKey",
"getIndexKeyFor",
"(",
"ByteBuffer",
"value",
")",
"{",
"// FIXME: this imply one column definition per index",
"ByteBuffer",
"name",
"=",
"columnDefs",
".",
"iterator",
"(",
")",
".",
"next",
"(",
")",
".",
"name",
".",
"bytes",
";",
"re... | Returns the decoratedKey for a column value
@param value column value
@return decorated key | [
"Returns",
"the",
"decoratedKey",
"for",
"a",
"column",
"value"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/index/SecondaryIndex.java#L300-L305 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/db/index/SecondaryIndex.java | SecondaryIndex.createInstance | public static SecondaryIndex createInstance(ColumnFamilyStore baseCfs, ColumnDefinition cdef) throws ConfigurationException
{
SecondaryIndex index;
switch (cdef.getIndexType())
{
case KEYS:
index = new KeysIndex();
break;
case COMPOSITES:
index = CompositesIndex.create(cdef);
break;
case CUSTOM:
assert cdef.getIndexOptions() != null;
String class_name = cdef.getIndexOptions().get(CUSTOM_INDEX_OPTION_NAME);
assert class_name != null;
try
{
index = (SecondaryIndex) Class.forName(class_name).newInstance();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
break;
default:
throw new RuntimeException("Unknown index type: " + cdef.getIndexName());
}
index.addColumnDef(cdef);
index.validateOptions();
index.setBaseCfs(baseCfs);
return index;
} | java | public static SecondaryIndex createInstance(ColumnFamilyStore baseCfs, ColumnDefinition cdef) throws ConfigurationException
{
SecondaryIndex index;
switch (cdef.getIndexType())
{
case KEYS:
index = new KeysIndex();
break;
case COMPOSITES:
index = CompositesIndex.create(cdef);
break;
case CUSTOM:
assert cdef.getIndexOptions() != null;
String class_name = cdef.getIndexOptions().get(CUSTOM_INDEX_OPTION_NAME);
assert class_name != null;
try
{
index = (SecondaryIndex) Class.forName(class_name).newInstance();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
break;
default:
throw new RuntimeException("Unknown index type: " + cdef.getIndexName());
}
index.addColumnDef(cdef);
index.validateOptions();
index.setBaseCfs(baseCfs);
return index;
} | [
"public",
"static",
"SecondaryIndex",
"createInstance",
"(",
"ColumnFamilyStore",
"baseCfs",
",",
"ColumnDefinition",
"cdef",
")",
"throws",
"ConfigurationException",
"{",
"SecondaryIndex",
"index",
";",
"switch",
"(",
"cdef",
".",
"getIndexType",
"(",
")",
")",
"{"... | This is the primary way to create a secondary index instance for a CF column.
It will validate the index_options before initializing.
@param baseCfs the source of data for the Index
@param cdef the meta information about this column (index_type, index_options, name, etc...)
@return The secondary index instance for this column
@throws ConfigurationException | [
"This",
"is",
"the",
"primary",
"way",
"to",
"create",
"a",
"secondary",
"index",
"instance",
"for",
"a",
"CF",
"column",
".",
"It",
"will",
"validate",
"the",
"index_options",
"before",
"initializing",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/index/SecondaryIndex.java#L322-L356 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/db/index/SecondaryIndex.java | SecondaryIndex.getIndexComparator | public static CellNameType getIndexComparator(CFMetaData baseMetadata, ColumnDefinition cdef)
{
switch (cdef.getIndexType())
{
case KEYS:
return new SimpleDenseCellNameType(keyComparator);
case COMPOSITES:
return CompositesIndex.getIndexComparator(baseMetadata, cdef);
case CUSTOM:
return null;
}
throw new AssertionError();
} | java | public static CellNameType getIndexComparator(CFMetaData baseMetadata, ColumnDefinition cdef)
{
switch (cdef.getIndexType())
{
case KEYS:
return new SimpleDenseCellNameType(keyComparator);
case COMPOSITES:
return CompositesIndex.getIndexComparator(baseMetadata, cdef);
case CUSTOM:
return null;
}
throw new AssertionError();
} | [
"public",
"static",
"CellNameType",
"getIndexComparator",
"(",
"CFMetaData",
"baseMetadata",
",",
"ColumnDefinition",
"cdef",
")",
"{",
"switch",
"(",
"cdef",
".",
"getIndexType",
"(",
")",
")",
"{",
"case",
"KEYS",
":",
"return",
"new",
"SimpleDenseCellNameType",... | Returns the index comparator for index backed by CFS, or null.
Note: it would be cleaner to have this be a member method. However we need this when opening indexes
sstables, but by then the CFS won't be fully initiated, so the SecondaryIndex object won't be accessible. | [
"Returns",
"the",
"index",
"comparator",
"for",
"index",
"backed",
"by",
"CFS",
"or",
"null",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/index/SecondaryIndex.java#L368-L380 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/service/ActiveRepairService.java | ActiveRepairService.submitRepairSession | public RepairFuture submitRepairSession(UUID parentRepairSession, Range<Token> range, String keyspace, RepairParallelism parallelismDegree, Set<InetAddress> endpoints, String... cfnames)
{
if (cfnames.length == 0)
return null;
RepairSession session = new RepairSession(parentRepairSession, range, keyspace, parallelismDegree, endpoints, cfnames);
if (session.endpoints.isEmpty())
return null;
RepairFuture futureTask = new RepairFuture(session);
executor.execute(futureTask);
return futureTask;
} | java | public RepairFuture submitRepairSession(UUID parentRepairSession, Range<Token> range, String keyspace, RepairParallelism parallelismDegree, Set<InetAddress> endpoints, String... cfnames)
{
if (cfnames.length == 0)
return null;
RepairSession session = new RepairSession(parentRepairSession, range, keyspace, parallelismDegree, endpoints, cfnames);
if (session.endpoints.isEmpty())
return null;
RepairFuture futureTask = new RepairFuture(session);
executor.execute(futureTask);
return futureTask;
} | [
"public",
"RepairFuture",
"submitRepairSession",
"(",
"UUID",
"parentRepairSession",
",",
"Range",
"<",
"Token",
">",
"range",
",",
"String",
"keyspace",
",",
"RepairParallelism",
"parallelismDegree",
",",
"Set",
"<",
"InetAddress",
">",
"endpoints",
",",
"String",
... | Requests repairs for the given keyspace and column families.
@return Future for asynchronous call or null if there is no need to repair | [
"Requests",
"repairs",
"for",
"the",
"given",
"keyspace",
"and",
"column",
"families",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/service/ActiveRepairService.java#L123-L133 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/service/ActiveRepairService.java | ActiveRepairService.getNeighbors | public static Set<InetAddress> getNeighbors(String keyspaceName, Range<Token> toRepair, Collection<String> dataCenters, Collection<String> hosts)
{
StorageService ss = StorageService.instance;
Map<Range<Token>, List<InetAddress>> replicaSets = ss.getRangeToAddressMap(keyspaceName);
Range<Token> rangeSuperSet = null;
for (Range<Token> range : ss.getLocalRanges(keyspaceName))
{
if (range.contains(toRepair))
{
rangeSuperSet = range;
break;
}
else if (range.intersects(toRepair))
{
throw new IllegalArgumentException("Requested range intersects a local range but is not fully contained in one; this would lead to imprecise repair");
}
}
if (rangeSuperSet == null || !replicaSets.containsKey(rangeSuperSet))
return Collections.emptySet();
Set<InetAddress> neighbors = new HashSet<>(replicaSets.get(rangeSuperSet));
neighbors.remove(FBUtilities.getBroadcastAddress());
if (dataCenters != null)
{
TokenMetadata.Topology topology = ss.getTokenMetadata().cloneOnlyTokenMap().getTopology();
Set<InetAddress> dcEndpoints = Sets.newHashSet();
Multimap<String,InetAddress> dcEndpointsMap = topology.getDatacenterEndpoints();
for (String dc : dataCenters)
{
Collection<InetAddress> c = dcEndpointsMap.get(dc);
if (c != null)
dcEndpoints.addAll(c);
}
return Sets.intersection(neighbors, dcEndpoints);
}
else if (hosts != null)
{
Set<InetAddress> specifiedHost = new HashSet<>();
for (final String host : hosts)
{
try
{
final InetAddress endpoint = InetAddress.getByName(host.trim());
if (endpoint.equals(FBUtilities.getBroadcastAddress()) || neighbors.contains(endpoint))
specifiedHost.add(endpoint);
}
catch (UnknownHostException e)
{
throw new IllegalArgumentException("Unknown host specified " + host, e);
}
}
if (!specifiedHost.contains(FBUtilities.getBroadcastAddress()))
throw new IllegalArgumentException("The current host must be part of the repair");
if (specifiedHost.size() <= 1)
{
String msg = "Repair requires at least two endpoints that are neighbours before it can continue, the endpoint used for this repair is %s, " +
"other available neighbours are %s but these neighbours were not part of the supplied list of hosts to use during the repair (%s).";
throw new IllegalArgumentException(String.format(msg, specifiedHost, neighbors, hosts));
}
specifiedHost.remove(FBUtilities.getBroadcastAddress());
return specifiedHost;
}
return neighbors;
} | java | public static Set<InetAddress> getNeighbors(String keyspaceName, Range<Token> toRepair, Collection<String> dataCenters, Collection<String> hosts)
{
StorageService ss = StorageService.instance;
Map<Range<Token>, List<InetAddress>> replicaSets = ss.getRangeToAddressMap(keyspaceName);
Range<Token> rangeSuperSet = null;
for (Range<Token> range : ss.getLocalRanges(keyspaceName))
{
if (range.contains(toRepair))
{
rangeSuperSet = range;
break;
}
else if (range.intersects(toRepair))
{
throw new IllegalArgumentException("Requested range intersects a local range but is not fully contained in one; this would lead to imprecise repair");
}
}
if (rangeSuperSet == null || !replicaSets.containsKey(rangeSuperSet))
return Collections.emptySet();
Set<InetAddress> neighbors = new HashSet<>(replicaSets.get(rangeSuperSet));
neighbors.remove(FBUtilities.getBroadcastAddress());
if (dataCenters != null)
{
TokenMetadata.Topology topology = ss.getTokenMetadata().cloneOnlyTokenMap().getTopology();
Set<InetAddress> dcEndpoints = Sets.newHashSet();
Multimap<String,InetAddress> dcEndpointsMap = topology.getDatacenterEndpoints();
for (String dc : dataCenters)
{
Collection<InetAddress> c = dcEndpointsMap.get(dc);
if (c != null)
dcEndpoints.addAll(c);
}
return Sets.intersection(neighbors, dcEndpoints);
}
else if (hosts != null)
{
Set<InetAddress> specifiedHost = new HashSet<>();
for (final String host : hosts)
{
try
{
final InetAddress endpoint = InetAddress.getByName(host.trim());
if (endpoint.equals(FBUtilities.getBroadcastAddress()) || neighbors.contains(endpoint))
specifiedHost.add(endpoint);
}
catch (UnknownHostException e)
{
throw new IllegalArgumentException("Unknown host specified " + host, e);
}
}
if (!specifiedHost.contains(FBUtilities.getBroadcastAddress()))
throw new IllegalArgumentException("The current host must be part of the repair");
if (specifiedHost.size() <= 1)
{
String msg = "Repair requires at least two endpoints that are neighbours before it can continue, the endpoint used for this repair is %s, " +
"other available neighbours are %s but these neighbours were not part of the supplied list of hosts to use during the repair (%s).";
throw new IllegalArgumentException(String.format(msg, specifiedHost, neighbors, hosts));
}
specifiedHost.remove(FBUtilities.getBroadcastAddress());
return specifiedHost;
}
return neighbors;
} | [
"public",
"static",
"Set",
"<",
"InetAddress",
">",
"getNeighbors",
"(",
"String",
"keyspaceName",
",",
"Range",
"<",
"Token",
">",
"toRepair",
",",
"Collection",
"<",
"String",
">",
"dataCenters",
",",
"Collection",
"<",
"String",
">",
"hosts",
")",
"{",
... | Return all of the neighbors with whom we share the provided range.
@param keyspaceName keyspace to repair
@param toRepair token to repair
@param dataCenters the data centers to involve in the repair
@return neighbors with whom we share the provided range | [
"Return",
"all",
"of",
"the",
"neighbors",
"with",
"whom",
"we",
"share",
"the",
"provided",
"range",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/service/ActiveRepairService.java#L179-L248 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/transport/CBUtil.java | CBUtil.decodeString | private static String decodeString(ByteBuffer src) throws CharacterCodingException
{
// the decoder needs to be reset every time we use it, hence the copy per thread
CharsetDecoder theDecoder = decoder.get();
theDecoder.reset();
final CharBuffer dst = CharBuffer.allocate(
(int) ((double) src.remaining() * theDecoder.maxCharsPerByte()));
CoderResult cr = theDecoder.decode(src, dst, true);
if (!cr.isUnderflow())
cr.throwException();
cr = theDecoder.flush(dst);
if (!cr.isUnderflow())
cr.throwException();
return dst.flip().toString();
} | java | private static String decodeString(ByteBuffer src) throws CharacterCodingException
{
// the decoder needs to be reset every time we use it, hence the copy per thread
CharsetDecoder theDecoder = decoder.get();
theDecoder.reset();
final CharBuffer dst = CharBuffer.allocate(
(int) ((double) src.remaining() * theDecoder.maxCharsPerByte()));
CoderResult cr = theDecoder.decode(src, dst, true);
if (!cr.isUnderflow())
cr.throwException();
cr = theDecoder.flush(dst);
if (!cr.isUnderflow())
cr.throwException();
return dst.flip().toString();
} | [
"private",
"static",
"String",
"decodeString",
"(",
"ByteBuffer",
"src",
")",
"throws",
"CharacterCodingException",
"{",
"// the decoder needs to be reset every time we use it, hence the copy per thread",
"CharsetDecoder",
"theDecoder",
"=",
"decoder",
".",
"get",
"(",
")",
"... | is resolved in a release used by Cassandra. | [
"is",
"resolved",
"in",
"a",
"release",
"used",
"by",
"Cassandra",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/transport/CBUtil.java#L101-L119 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/service/CassandraDaemon.java | CassandraDaemon.activate | public void activate()
{
String pidFile = System.getProperty("cassandra-pidfile");
try
{
try
{
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
mbs.registerMBean(new StandardMBean(new NativeAccess(), NativeAccessMBean.class), new ObjectName(MBEAN_NAME));
}
catch (Exception e)
{
logger.error("error registering MBean {}", MBEAN_NAME, e);
//Allow the server to start even if the bean can't be registered
}
setup();
if (pidFile != null)
{
new File(pidFile).deleteOnExit();
}
if (System.getProperty("cassandra-foreground") == null)
{
System.out.close();
System.err.close();
}
start();
}
catch (Throwable e)
{
logger.error("Exception encountered during startup", e);
// try to warn user on stdout too, if we haven't already detached
e.printStackTrace();
System.out.println("Exception encountered during startup: " + e.getMessage());
System.exit(3);
}
} | java | public void activate()
{
String pidFile = System.getProperty("cassandra-pidfile");
try
{
try
{
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
mbs.registerMBean(new StandardMBean(new NativeAccess(), NativeAccessMBean.class), new ObjectName(MBEAN_NAME));
}
catch (Exception e)
{
logger.error("error registering MBean {}", MBEAN_NAME, e);
//Allow the server to start even if the bean can't be registered
}
setup();
if (pidFile != null)
{
new File(pidFile).deleteOnExit();
}
if (System.getProperty("cassandra-foreground") == null)
{
System.out.close();
System.err.close();
}
start();
}
catch (Throwable e)
{
logger.error("Exception encountered during startup", e);
// try to warn user on stdout too, if we haven't already detached
e.printStackTrace();
System.out.println("Exception encountered during startup: " + e.getMessage());
System.exit(3);
}
} | [
"public",
"void",
"activate",
"(",
")",
"{",
"String",
"pidFile",
"=",
"System",
".",
"getProperty",
"(",
"\"cassandra-pidfile\"",
")",
";",
"try",
"{",
"try",
"{",
"MBeanServer",
"mbs",
"=",
"ManagementFactory",
".",
"getPlatformMBeanServer",
"(",
")",
";",
... | A convenience method to initialize and start the daemon in one shot. | [
"A",
"convenience",
"method",
"to",
"initialize",
"and",
"start",
"the",
"daemon",
"in",
"one",
"shot",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/service/CassandraDaemon.java#L519-L561 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/cql3/KeyspaceElementName.java | KeyspaceElementName.toInternalName | protected static String toInternalName(String name, boolean keepCase)
{
return keepCase ? name : name.toLowerCase(Locale.US);
} | java | protected static String toInternalName(String name, boolean keepCase)
{
return keepCase ? name : name.toLowerCase(Locale.US);
} | [
"protected",
"static",
"String",
"toInternalName",
"(",
"String",
"name",
",",
"boolean",
"keepCase",
")",
"{",
"return",
"keepCase",
"?",
"name",
":",
"name",
".",
"toLowerCase",
"(",
"Locale",
".",
"US",
")",
";",
"}"
] | Converts the specified name into the name used internally.
@param name the name
@param keepCase <code>true</code> if the case must be kept, <code>false</code> otherwise.
@return the name used internally. | [
"Converts",
"the",
"specified",
"name",
"into",
"the",
"name",
"used",
"internally",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cql3/KeyspaceElementName.java#L64-L67 | train |
Stratio/stratio-cassandra | tools/stress/src/org/apache/cassandra/stress/util/DynamicList.java | DynamicList.append | public Node<E> append(E value, int maxSize)
{
Node<E> newTail = new Node<>(randomLevel(), value);
lock.writeLock().lock();
try
{
if (size >= maxSize)
return null;
size++;
Node<E> tail = head;
for (int i = maxHeight - 1 ; i >= newTail.height() ; i--)
{
Node<E> next;
while ((next = tail.next(i)) != null)
tail = next;
tail.size[i]++;
}
for (int i = newTail.height() - 1 ; i >= 0 ; i--)
{
Node<E> next;
while ((next = tail.next(i)) != null)
tail = next;
tail.setNext(i, newTail);
newTail.setPrev(i, tail);
}
return newTail;
}
finally
{
lock.writeLock().unlock();
}
} | java | public Node<E> append(E value, int maxSize)
{
Node<E> newTail = new Node<>(randomLevel(), value);
lock.writeLock().lock();
try
{
if (size >= maxSize)
return null;
size++;
Node<E> tail = head;
for (int i = maxHeight - 1 ; i >= newTail.height() ; i--)
{
Node<E> next;
while ((next = tail.next(i)) != null)
tail = next;
tail.size[i]++;
}
for (int i = newTail.height() - 1 ; i >= 0 ; i--)
{
Node<E> next;
while ((next = tail.next(i)) != null)
tail = next;
tail.setNext(i, newTail);
newTail.setPrev(i, tail);
}
return newTail;
}
finally
{
lock.writeLock().unlock();
}
} | [
"public",
"Node",
"<",
"E",
">",
"append",
"(",
"E",
"value",
",",
"int",
"maxSize",
")",
"{",
"Node",
"<",
"E",
">",
"newTail",
"=",
"new",
"Node",
"<>",
"(",
"randomLevel",
"(",
")",
",",
"value",
")",
";",
"lock",
".",
"writeLock",
"(",
")",
... | regardless of its future position in the list from other modifications | [
"regardless",
"of",
"its",
"future",
"position",
"in",
"the",
"list",
"from",
"other",
"modifications"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/tools/stress/src/org/apache/cassandra/stress/util/DynamicList.java#L115-L150 | train |
Stratio/stratio-cassandra | tools/stress/src/org/apache/cassandra/stress/util/DynamicList.java | DynamicList.remove | public void remove(Node<E> node)
{
lock.writeLock().lock();
assert node.value != null;
node.value = null;
try
{
size--;
// go up through each level in the skip list, unlinking this node; this entails
// simply linking each neighbour to each other, and appending the size of the
// current level owned by this node's index to the preceding neighbour (since
// ownership is defined as any node that you must visit through the index,
// removal of ourselves from a level means the preceding index entry is the
// entry point to all of the removed node's descendants)
for (int i = 0 ; i < node.height() ; i++)
{
Node<E> prev = node.prev(i);
Node<E> next = node.next(i);
assert prev != null;
prev.setNext(i, next);
if (next != null)
next.setPrev(i, prev);
prev.size[i] += node.size[i] - 1;
}
// then go up the levels, removing 1 from the size at each height above ours
for (int i = node.height() ; i < maxHeight ; i++)
{
// if we're at our height limit, we backtrack at our top level until we
// hit a neighbour with a greater height
while (i == node.height())
node = node.prev(i - 1);
node.size[i]--;
}
}
finally
{
lock.writeLock().unlock();
}
} | java | public void remove(Node<E> node)
{
lock.writeLock().lock();
assert node.value != null;
node.value = null;
try
{
size--;
// go up through each level in the skip list, unlinking this node; this entails
// simply linking each neighbour to each other, and appending the size of the
// current level owned by this node's index to the preceding neighbour (since
// ownership is defined as any node that you must visit through the index,
// removal of ourselves from a level means the preceding index entry is the
// entry point to all of the removed node's descendants)
for (int i = 0 ; i < node.height() ; i++)
{
Node<E> prev = node.prev(i);
Node<E> next = node.next(i);
assert prev != null;
prev.setNext(i, next);
if (next != null)
next.setPrev(i, prev);
prev.size[i] += node.size[i] - 1;
}
// then go up the levels, removing 1 from the size at each height above ours
for (int i = node.height() ; i < maxHeight ; i++)
{
// if we're at our height limit, we backtrack at our top level until we
// hit a neighbour with a greater height
while (i == node.height())
node = node.prev(i - 1);
node.size[i]--;
}
}
finally
{
lock.writeLock().unlock();
}
} | [
"public",
"void",
"remove",
"(",
"Node",
"<",
"E",
">",
"node",
")",
"{",
"lock",
".",
"writeLock",
"(",
")",
".",
"lock",
"(",
")",
";",
"assert",
"node",
".",
"value",
"!=",
"null",
";",
"node",
".",
"value",
"=",
"null",
";",
"try",
"{",
"si... | remove the provided node and its associated value from the list | [
"remove",
"the",
"provided",
"node",
"and",
"its",
"associated",
"value",
"from",
"the",
"list"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/tools/stress/src/org/apache/cassandra/stress/util/DynamicList.java#L153-L193 | train |
Stratio/stratio-cassandra | tools/stress/src/org/apache/cassandra/stress/util/DynamicList.java | DynamicList.get | public E get(int index)
{
lock.readLock().lock();
try
{
if (index >= size)
return null;
index++;
int c = 0;
Node<E> finger = head;
for (int i = maxHeight - 1 ; i >= 0 ; i--)
{
while (c + finger.size[i] <= index)
{
c += finger.size[i];
finger = finger.next(i);
}
}
assert c == index;
return finger.value;
}
finally
{
lock.readLock().unlock();
}
} | java | public E get(int index)
{
lock.readLock().lock();
try
{
if (index >= size)
return null;
index++;
int c = 0;
Node<E> finger = head;
for (int i = maxHeight - 1 ; i >= 0 ; i--)
{
while (c + finger.size[i] <= index)
{
c += finger.size[i];
finger = finger.next(i);
}
}
assert c == index;
return finger.value;
}
finally
{
lock.readLock().unlock();
}
} | [
"public",
"E",
"get",
"(",
"int",
"index",
")",
"{",
"lock",
".",
"readLock",
"(",
")",
".",
"lock",
"(",
")",
";",
"try",
"{",
"if",
"(",
"index",
">=",
"size",
")",
"return",
"null",
";",
"index",
"++",
";",
"int",
"c",
"=",
"0",
";",
"Node... | retrieve the item at the provided index, or return null if the index is past the end of the list | [
"retrieve",
"the",
"item",
"at",
"the",
"provided",
"index",
"or",
"return",
"null",
"if",
"the",
"index",
"is",
"past",
"the",
"end",
"of",
"the",
"list"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/tools/stress/src/org/apache/cassandra/stress/util/DynamicList.java#L196-L223 | train |
Stratio/stratio-cassandra | tools/stress/src/org/apache/cassandra/stress/util/DynamicList.java | DynamicList.isWellFormed | private boolean isWellFormed()
{
for (int i = 0 ; i < maxHeight ; i++)
{
int c = 0;
for (Node node = head ; node != null ; node = node.next(i))
{
if (node.prev(i) != null && node.prev(i).next(i) != node)
return false;
if (node.next(i) != null && node.next(i).prev(i) != node)
return false;
c += node.size[i];
if (i + 1 < maxHeight && node.parent(i + 1).next(i + 1) == node.next(i))
{
if (node.parent(i + 1).size[i + 1] != c)
return false;
c = 0;
}
}
if (i == maxHeight - 1 && c != size + 1)
return false;
}
return true;
} | java | private boolean isWellFormed()
{
for (int i = 0 ; i < maxHeight ; i++)
{
int c = 0;
for (Node node = head ; node != null ; node = node.next(i))
{
if (node.prev(i) != null && node.prev(i).next(i) != node)
return false;
if (node.next(i) != null && node.next(i).prev(i) != node)
return false;
c += node.size[i];
if (i + 1 < maxHeight && node.parent(i + 1).next(i + 1) == node.next(i))
{
if (node.parent(i + 1).size[i + 1] != c)
return false;
c = 0;
}
}
if (i == maxHeight - 1 && c != size + 1)
return false;
}
return true;
} | [
"private",
"boolean",
"isWellFormed",
"(",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"maxHeight",
";",
"i",
"++",
")",
"{",
"int",
"c",
"=",
"0",
";",
"for",
"(",
"Node",
"node",
"=",
"head",
";",
"node",
"!=",
"null",
";",
"... | don't create a separate unit test - tools tree doesn't currently warrant them | [
"don",
"t",
"create",
"a",
"separate",
"unit",
"test",
"-",
"tools",
"tree",
"doesn",
"t",
"currently",
"warrant",
"them"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/tools/stress/src/org/apache/cassandra/stress/util/DynamicList.java#L228-L251 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/io/sstable/IndexSummary.java | IndexSummary.binarySearch | public int binarySearch(RowPosition key)
{
int low = 0, mid = offsetCount, high = mid - 1, result = -1;
while (low <= high)
{
mid = (low + high) >> 1;
result = -DecoratedKey.compareTo(partitioner, ByteBuffer.wrap(getKey(mid)), key);
if (result > 0)
{
low = mid + 1;
}
else if (result == 0)
{
return mid;
}
else
{
high = mid - 1;
}
}
return -mid - (result < 0 ? 1 : 2);
} | java | public int binarySearch(RowPosition key)
{
int low = 0, mid = offsetCount, high = mid - 1, result = -1;
while (low <= high)
{
mid = (low + high) >> 1;
result = -DecoratedKey.compareTo(partitioner, ByteBuffer.wrap(getKey(mid)), key);
if (result > 0)
{
low = mid + 1;
}
else if (result == 0)
{
return mid;
}
else
{
high = mid - 1;
}
}
return -mid - (result < 0 ? 1 : 2);
} | [
"public",
"int",
"binarySearch",
"(",
"RowPosition",
"key",
")",
"{",
"int",
"low",
"=",
"0",
",",
"mid",
"=",
"offsetCount",
",",
"high",
"=",
"mid",
"-",
"1",
",",
"result",
"=",
"-",
"1",
";",
"while",
"(",
"low",
"<=",
"high",
")",
"{",
"mid"... | Harmony's Collections implementation | [
"Harmony",
"s",
"Collections",
"implementation"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/io/sstable/IndexSummary.java#L107-L129 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/triggers/TriggerExecutor.java | TriggerExecutor.reloadClasses | public void reloadClasses()
{
File triggerDirectory = FBUtilities.cassandraTriggerDir();
if (triggerDirectory == null)
return;
customClassLoader = new CustomClassLoader(parent, triggerDirectory);
cachedTriggers.clear();
} | java | public void reloadClasses()
{
File triggerDirectory = FBUtilities.cassandraTriggerDir();
if (triggerDirectory == null)
return;
customClassLoader = new CustomClassLoader(parent, triggerDirectory);
cachedTriggers.clear();
} | [
"public",
"void",
"reloadClasses",
"(",
")",
"{",
"File",
"triggerDirectory",
"=",
"FBUtilities",
".",
"cassandraTriggerDir",
"(",
")",
";",
"if",
"(",
"triggerDirectory",
"==",
"null",
")",
"return",
";",
"customClassLoader",
"=",
"new",
"CustomClassLoader",
"(... | Reload the triggers which is already loaded, Invoking this will update
the class loader so new jars can be loaded. | [
"Reload",
"the",
"triggers",
"which",
"is",
"already",
"loaded",
"Invoking",
"this",
"will",
"update",
"the",
"class",
"loader",
"so",
"new",
"jars",
"can",
"be",
"loaded",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/triggers/TriggerExecutor.java#L54-L61 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/triggers/TriggerExecutor.java | TriggerExecutor.executeInternal | private List<Mutation> executeInternal(ByteBuffer key, ColumnFamily columnFamily)
{
Map<String, TriggerDefinition> triggers = columnFamily.metadata().getTriggers();
if (triggers.isEmpty())
return null;
List<Mutation> tmutations = Lists.newLinkedList();
Thread.currentThread().setContextClassLoader(customClassLoader);
try
{
for (TriggerDefinition td : triggers.values())
{
ITrigger trigger = cachedTriggers.get(td.classOption);
if (trigger == null)
{
trigger = loadTriggerInstance(td.classOption);
cachedTriggers.put(td.classOption, trigger);
}
Collection<Mutation> temp = trigger.augment(key, columnFamily);
if (temp != null)
tmutations.addAll(temp);
}
return tmutations;
}
catch (Exception ex)
{
throw new RuntimeException(String.format("Exception while creating trigger on CF with ID: %s", columnFamily.id()), ex);
}
finally
{
Thread.currentThread().setContextClassLoader(parent);
}
} | java | private List<Mutation> executeInternal(ByteBuffer key, ColumnFamily columnFamily)
{
Map<String, TriggerDefinition> triggers = columnFamily.metadata().getTriggers();
if (triggers.isEmpty())
return null;
List<Mutation> tmutations = Lists.newLinkedList();
Thread.currentThread().setContextClassLoader(customClassLoader);
try
{
for (TriggerDefinition td : triggers.values())
{
ITrigger trigger = cachedTriggers.get(td.classOption);
if (trigger == null)
{
trigger = loadTriggerInstance(td.classOption);
cachedTriggers.put(td.classOption, trigger);
}
Collection<Mutation> temp = trigger.augment(key, columnFamily);
if (temp != null)
tmutations.addAll(temp);
}
return tmutations;
}
catch (Exception ex)
{
throw new RuntimeException(String.format("Exception while creating trigger on CF with ID: %s", columnFamily.id()), ex);
}
finally
{
Thread.currentThread().setContextClassLoader(parent);
}
} | [
"private",
"List",
"<",
"Mutation",
">",
"executeInternal",
"(",
"ByteBuffer",
"key",
",",
"ColumnFamily",
"columnFamily",
")",
"{",
"Map",
"<",
"String",
",",
"TriggerDefinition",
">",
"triggers",
"=",
"columnFamily",
".",
"metadata",
"(",
")",
".",
"getTrigg... | Switch class loader before using the triggers for the column family, if
not loaded them with the custom class loader. | [
"Switch",
"class",
"loader",
"before",
"using",
"the",
"triggers",
"for",
"the",
"column",
"family",
"if",
"not",
"loaded",
"them",
"with",
"the",
"custom",
"class",
"loader",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/triggers/TriggerExecutor.java#L174-L205 | train |
Stratio/stratio-cassandra | src/java/com/stratio/cassandra/index/schema/analysis/SnowballAnalyzerBuilder.java | SnowballAnalyzerBuilder.getDefaultStopwords | private static CharArraySet getDefaultStopwords(String language) {
switch (language) {
case "English":
return EnglishAnalyzer.getDefaultStopSet();
case "French":
return FrenchAnalyzer.getDefaultStopSet();
case "Spanish":
return SpanishAnalyzer.getDefaultStopSet();
case "Portuguese":
return PortugueseAnalyzer.getDefaultStopSet();
case "Italian":
return ItalianAnalyzer.getDefaultStopSet();
case "Romanian":
return RomanianAnalyzer.getDefaultStopSet();
case "German":
return GermanAnalyzer.getDefaultStopSet();
case "Dutch":
return DutchAnalyzer.getDefaultStopSet();
case "Swedish":
return SwedishAnalyzer.getDefaultStopSet();
case "Norwegian":
return NorwegianAnalyzer.getDefaultStopSet();
case "Danish":
return DanishAnalyzer.getDefaultStopSet();
case "Russian":
return RussianAnalyzer.getDefaultStopSet();
case "Finnish":
return FinnishAnalyzer.getDefaultStopSet();
case "Irish":
return IrishAnalyzer.getDefaultStopSet();
case "Hungarian":
return HungarianAnalyzer.getDefaultStopSet();
case "Turkish":
return SpanishAnalyzer.getDefaultStopSet();
case "Armenian":
return SpanishAnalyzer.getDefaultStopSet();
case "Basque":
return BasqueAnalyzer.getDefaultStopSet();
case "Catalan":
return CatalanAnalyzer.getDefaultStopSet();
default:
return CharArraySet.EMPTY_SET;
}
} | java | private static CharArraySet getDefaultStopwords(String language) {
switch (language) {
case "English":
return EnglishAnalyzer.getDefaultStopSet();
case "French":
return FrenchAnalyzer.getDefaultStopSet();
case "Spanish":
return SpanishAnalyzer.getDefaultStopSet();
case "Portuguese":
return PortugueseAnalyzer.getDefaultStopSet();
case "Italian":
return ItalianAnalyzer.getDefaultStopSet();
case "Romanian":
return RomanianAnalyzer.getDefaultStopSet();
case "German":
return GermanAnalyzer.getDefaultStopSet();
case "Dutch":
return DutchAnalyzer.getDefaultStopSet();
case "Swedish":
return SwedishAnalyzer.getDefaultStopSet();
case "Norwegian":
return NorwegianAnalyzer.getDefaultStopSet();
case "Danish":
return DanishAnalyzer.getDefaultStopSet();
case "Russian":
return RussianAnalyzer.getDefaultStopSet();
case "Finnish":
return FinnishAnalyzer.getDefaultStopSet();
case "Irish":
return IrishAnalyzer.getDefaultStopSet();
case "Hungarian":
return HungarianAnalyzer.getDefaultStopSet();
case "Turkish":
return SpanishAnalyzer.getDefaultStopSet();
case "Armenian":
return SpanishAnalyzer.getDefaultStopSet();
case "Basque":
return BasqueAnalyzer.getDefaultStopSet();
case "Catalan":
return CatalanAnalyzer.getDefaultStopSet();
default:
return CharArraySet.EMPTY_SET;
}
} | [
"private",
"static",
"CharArraySet",
"getDefaultStopwords",
"(",
"String",
"language",
")",
"{",
"switch",
"(",
"language",
")",
"{",
"case",
"\"English\"",
":",
"return",
"EnglishAnalyzer",
".",
"getDefaultStopSet",
"(",
")",
";",
"case",
"\"French\"",
":",
"re... | Returns the default stopwords set used by Lucene language analyzer for the specified language.
@param language The language for which the stopwords are. The supported languages are English, French, Spanish,
Portuguese, Italian, Romanian, German, Dutch, Swedish, Norwegian, Danish, Russian, Finnish,
Irish, Hungarian, Turkish, Armenian, Basque and Catalan.
@return The default stopwords set used by Lucene language analyzers. | [
"Returns",
"the",
"default",
"stopwords",
"set",
"used",
"by",
"Lucene",
"language",
"analyzer",
"for",
"the",
"specified",
"language",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/com/stratio/cassandra/index/schema/analysis/SnowballAnalyzerBuilder.java#L140-L183 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/hadoop/cql3/CqlConfigHelper.java | CqlConfigHelper.setInputColumns | public static void setInputColumns(Configuration conf, String columns)
{
if (columns == null || columns.isEmpty())
return;
conf.set(INPUT_CQL_COLUMNS_CONFIG, columns);
} | java | public static void setInputColumns(Configuration conf, String columns)
{
if (columns == null || columns.isEmpty())
return;
conf.set(INPUT_CQL_COLUMNS_CONFIG, columns);
} | [
"public",
"static",
"void",
"setInputColumns",
"(",
"Configuration",
"conf",
",",
"String",
"columns",
")",
"{",
"if",
"(",
"columns",
"==",
"null",
"||",
"columns",
".",
"isEmpty",
"(",
")",
")",
"return",
";",
"conf",
".",
"set",
"(",
"INPUT_CQL_COLUMNS_... | Set the CQL columns for the input of this job.
@param conf Job configuration you are about to run
@param columns | [
"Set",
"the",
"CQL",
"columns",
"for",
"the",
"input",
"of",
"this",
"job",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/hadoop/cql3/CqlConfigHelper.java#L94-L100 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/hadoop/cql3/CqlConfigHelper.java | CqlConfigHelper.setInputCQLPageRowSize | public static void setInputCQLPageRowSize(Configuration conf, String cqlPageRowSize)
{
if (cqlPageRowSize == null)
{
throw new UnsupportedOperationException("cql page row size may not be null");
}
conf.set(INPUT_CQL_PAGE_ROW_SIZE_CONFIG, cqlPageRowSize);
} | java | public static void setInputCQLPageRowSize(Configuration conf, String cqlPageRowSize)
{
if (cqlPageRowSize == null)
{
throw new UnsupportedOperationException("cql page row size may not be null");
}
conf.set(INPUT_CQL_PAGE_ROW_SIZE_CONFIG, cqlPageRowSize);
} | [
"public",
"static",
"void",
"setInputCQLPageRowSize",
"(",
"Configuration",
"conf",
",",
"String",
"cqlPageRowSize",
")",
"{",
"if",
"(",
"cqlPageRowSize",
"==",
"null",
")",
"{",
"throw",
"new",
"UnsupportedOperationException",
"(",
"\"cql page row size may not be null... | Set the CQL query Limit for the input of this job.
@param conf Job configuration you are about to run
@param cqlPageRowSize | [
"Set",
"the",
"CQL",
"query",
"Limit",
"for",
"the",
"input",
"of",
"this",
"job",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/hadoop/cql3/CqlConfigHelper.java#L108-L116 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/hadoop/cql3/CqlConfigHelper.java | CqlConfigHelper.setInputWhereClauses | public static void setInputWhereClauses(Configuration conf, String clauses)
{
if (clauses == null || clauses.isEmpty())
return;
conf.set(INPUT_CQL_WHERE_CLAUSE_CONFIG, clauses);
} | java | public static void setInputWhereClauses(Configuration conf, String clauses)
{
if (clauses == null || clauses.isEmpty())
return;
conf.set(INPUT_CQL_WHERE_CLAUSE_CONFIG, clauses);
} | [
"public",
"static",
"void",
"setInputWhereClauses",
"(",
"Configuration",
"conf",
",",
"String",
"clauses",
")",
"{",
"if",
"(",
"clauses",
"==",
"null",
"||",
"clauses",
".",
"isEmpty",
"(",
")",
")",
"return",
";",
"conf",
".",
"set",
"(",
"INPUT_CQL_WHE... | Set the CQL user defined where clauses for the input of this job.
@param conf Job configuration you are about to run
@param clauses | [
"Set",
"the",
"CQL",
"user",
"defined",
"where",
"clauses",
"for",
"the",
"input",
"of",
"this",
"job",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/hadoop/cql3/CqlConfigHelper.java#L124-L130 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/hadoop/cql3/CqlConfigHelper.java | CqlConfigHelper.setOutputCql | public static void setOutputCql(Configuration conf, String cql)
{
if (cql == null || cql.isEmpty())
return;
conf.set(OUTPUT_CQL, cql);
} | java | public static void setOutputCql(Configuration conf, String cql)
{
if (cql == null || cql.isEmpty())
return;
conf.set(OUTPUT_CQL, cql);
} | [
"public",
"static",
"void",
"setOutputCql",
"(",
"Configuration",
"conf",
",",
"String",
"cql",
")",
"{",
"if",
"(",
"cql",
"==",
"null",
"||",
"cql",
".",
"isEmpty",
"(",
")",
")",
"return",
";",
"conf",
".",
"set",
"(",
"OUTPUT_CQL",
",",
"cql",
")... | Set the CQL prepared statement for the output of this job.
@param conf Job configuration you are about to run
@param cql | [
"Set",
"the",
"CQL",
"prepared",
"statement",
"for",
"the",
"output",
"of",
"this",
"job",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/hadoop/cql3/CqlConfigHelper.java#L138-L144 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/service/ClientState.java | ClientState.getTimestamp | public long getTimestamp()
{
while (true)
{
long current = System.currentTimeMillis() * 1000;
long last = lastTimestampMicros.get();
long tstamp = last >= current ? last + 1 : current;
if (lastTimestampMicros.compareAndSet(last, tstamp))
return tstamp;
}
} | java | public long getTimestamp()
{
while (true)
{
long current = System.currentTimeMillis() * 1000;
long last = lastTimestampMicros.get();
long tstamp = last >= current ? last + 1 : current;
if (lastTimestampMicros.compareAndSet(last, tstamp))
return tstamp;
}
} | [
"public",
"long",
"getTimestamp",
"(",
")",
"{",
"while",
"(",
"true",
")",
"{",
"long",
"current",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
"*",
"1000",
";",
"long",
"last",
"=",
"lastTimestampMicros",
".",
"get",
"(",
")",
";",
"long",
"tst... | This clock guarantees that updates for the same ClientState will be ordered
in the sequence seen, even if multiple updates happen in the same millisecond. | [
"This",
"clock",
"guarantees",
"that",
"updates",
"for",
"the",
"same",
"ClientState",
"will",
"be",
"ordered",
"in",
"the",
"sequence",
"seen",
"even",
"if",
"multiple",
"updates",
"happen",
"in",
"the",
"same",
"millisecond",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/service/ClientState.java#L141-L151 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/service/ClientState.java | ClientState.login | public void login(AuthenticatedUser user) throws AuthenticationException
{
if (!user.isAnonymous() && !Auth.isExistingUser(user.getName()))
throw new AuthenticationException(String.format("User %s doesn't exist - create it with CREATE USER query first",
user.getName()));
this.user = user;
} | java | public void login(AuthenticatedUser user) throws AuthenticationException
{
if (!user.isAnonymous() && !Auth.isExistingUser(user.getName()))
throw new AuthenticationException(String.format("User %s doesn't exist - create it with CREATE USER query first",
user.getName()));
this.user = user;
} | [
"public",
"void",
"login",
"(",
"AuthenticatedUser",
"user",
")",
"throws",
"AuthenticationException",
"{",
"if",
"(",
"!",
"user",
".",
"isAnonymous",
"(",
")",
"&&",
"!",
"Auth",
".",
"isExistingUser",
"(",
"user",
".",
"getName",
"(",
")",
")",
")",
"... | Attempts to login the given user. | [
"Attempts",
"to",
"login",
"the",
"given",
"user",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/service/ClientState.java#L203-L209 | train |
KostyaSha/yet-another-docker-plugin | yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/DockerProvisioningStrategy.java | DockerProvisioningStrategy.notAllowedStrategy | @VisibleForTesting
protected static boolean notAllowedStrategy(DockerSlaveTemplate template) {
if (isNull(template)) {
LOG.debug("Skipping DockerProvisioningStrategy because: template is null");
return true;
}
final RetentionStrategy retentionStrategy = template.getRetentionStrategy();
if (isNull(retentionStrategy)) {
LOG.debug("Skipping DockerProvisioningStrategy because: strategy is null for {}", template);
}
if (retentionStrategy instanceof DockerOnceRetentionStrategy) {
if (template.getNumExecutors() == 1) {
LOG.debug("Applying faster provisioning for single executor template {}", template);
return false;
} else {
LOG.debug("Skipping DockerProvisioningStrategy because: numExecutors is {} for {}",
template.getNumExecutors(), template);
return true;
}
}
if (retentionStrategy instanceof RetentionStrategy.Demand) {
LOG.debug("Applying faster provisioning for Demand strategy for template {}", template);
return false;
}
// forbid by default
LOG.trace("Skipping YAD provisioning for unknown mix of configuration for {}", template);
return true;
} | java | @VisibleForTesting
protected static boolean notAllowedStrategy(DockerSlaveTemplate template) {
if (isNull(template)) {
LOG.debug("Skipping DockerProvisioningStrategy because: template is null");
return true;
}
final RetentionStrategy retentionStrategy = template.getRetentionStrategy();
if (isNull(retentionStrategy)) {
LOG.debug("Skipping DockerProvisioningStrategy because: strategy is null for {}", template);
}
if (retentionStrategy instanceof DockerOnceRetentionStrategy) {
if (template.getNumExecutors() == 1) {
LOG.debug("Applying faster provisioning for single executor template {}", template);
return false;
} else {
LOG.debug("Skipping DockerProvisioningStrategy because: numExecutors is {} for {}",
template.getNumExecutors(), template);
return true;
}
}
if (retentionStrategy instanceof RetentionStrategy.Demand) {
LOG.debug("Applying faster provisioning for Demand strategy for template {}", template);
return false;
}
// forbid by default
LOG.trace("Skipping YAD provisioning for unknown mix of configuration for {}", template);
return true;
} | [
"@",
"VisibleForTesting",
"protected",
"static",
"boolean",
"notAllowedStrategy",
"(",
"DockerSlaveTemplate",
"template",
")",
"{",
"if",
"(",
"isNull",
"(",
"template",
")",
")",
"{",
"LOG",
".",
"debug",
"(",
"\"Skipping DockerProvisioningStrategy because: template is... | Exclude unknown mix of configuration. | [
"Exclude",
"unknown",
"mix",
"of",
"configuration",
"."
] | 40b12e39ff94c3834cff7e028c3dd01c88e87d77 | https://github.com/KostyaSha/yet-another-docker-plugin/blob/40b12e39ff94c3834cff7e028c3dd01c88e87d77/yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/DockerProvisioningStrategy.java#L119-L150 | train |
KostyaSha/yet-another-docker-plugin | yet-another-docker-its/src/main/java/com/github/kostyasha/it/rule/DockerRule.java | DockerRule.pullImage | public void pullImage(DockerImagePullStrategy pullStrategy, String imageName) throws InterruptedException {
LOG.info("Pulling image {} with {} strategy...", imageName, pullStrategy);
final List<Image> images = getDockerCli().listImagesCmd().withShowAll(true).exec();
NameParser.ReposTag repostag = NameParser.parseRepositoryTag(imageName);
// if image was specified without tag, then treat as latest
final String fullImageName = repostag.repos + ":" + (repostag.tag.isEmpty() ? "latest" : repostag.tag);
boolean hasImage = Iterables.any(
images, image ->
nonNull(image.getRepoTags()) &&
Arrays.asList(image.getRepoTags()).contains(fullImageName)
);
boolean pull = hasImage ?
pullStrategy.pullIfExists(imageName) :
pullStrategy.pullIfNotExists(imageName);
if (pull) {
LOG.info("Pulling image '{}' {}. This may take awhile...", imageName,
hasImage ? "again" : "since one was not found");
long startTime = System.currentTimeMillis();
//Identifier amiId = Identifier.fromCompoundString(ami);
getDockerCli().pullImageCmd(imageName).exec(new PullImageResultCallback()).awaitSuccess();
long pullTime = System.currentTimeMillis() - startTime;
LOG.info("Finished pulling image '{}', took {} ms", imageName, pullTime);
}
} | java | public void pullImage(DockerImagePullStrategy pullStrategy, String imageName) throws InterruptedException {
LOG.info("Pulling image {} with {} strategy...", imageName, pullStrategy);
final List<Image> images = getDockerCli().listImagesCmd().withShowAll(true).exec();
NameParser.ReposTag repostag = NameParser.parseRepositoryTag(imageName);
// if image was specified without tag, then treat as latest
final String fullImageName = repostag.repos + ":" + (repostag.tag.isEmpty() ? "latest" : repostag.tag);
boolean hasImage = Iterables.any(
images, image ->
nonNull(image.getRepoTags()) &&
Arrays.asList(image.getRepoTags()).contains(fullImageName)
);
boolean pull = hasImage ?
pullStrategy.pullIfExists(imageName) :
pullStrategy.pullIfNotExists(imageName);
if (pull) {
LOG.info("Pulling image '{}' {}. This may take awhile...", imageName,
hasImage ? "again" : "since one was not found");
long startTime = System.currentTimeMillis();
//Identifier amiId = Identifier.fromCompoundString(ami);
getDockerCli().pullImageCmd(imageName).exec(new PullImageResultCallback()).awaitSuccess();
long pullTime = System.currentTimeMillis() - startTime;
LOG.info("Finished pulling image '{}', took {} ms", imageName, pullTime);
}
} | [
"public",
"void",
"pullImage",
"(",
"DockerImagePullStrategy",
"pullStrategy",
",",
"String",
"imageName",
")",
"throws",
"InterruptedException",
"{",
"LOG",
".",
"info",
"(",
"\"Pulling image {} with {} strategy...\"",
",",
"imageName",
",",
"pullStrategy",
")",
";",
... | Pull docker image on this docker host. | [
"Pull",
"docker",
"image",
"on",
"this",
"docker",
"host",
"."
] | 40b12e39ff94c3834cff7e028c3dd01c88e87d77 | https://github.com/KostyaSha/yet-another-docker-plugin/blob/40b12e39ff94c3834cff7e028c3dd01c88e87d77/yet-another-docker-its/src/main/java/com/github/kostyasha/it/rule/DockerRule.java#L144-L173 | train |
KostyaSha/yet-another-docker-plugin | yet-another-docker-its/src/main/java/com/github/kostyasha/it/rule/DockerRule.java | DockerRule.buildImage | public String buildImage(Map<String, File> plugins) throws IOException, InterruptedException {
LOG.debug("Building image for {}", plugins);
// final File tempDirectory = TempFileHelper.createTempDirectory("build-image", targetDir().toPath());
final File buildDir = new File(targetDir().getAbsolutePath() + "/docker-it/build-image");
if (buildDir.exists()) {
deleteDirectory(buildDir);
}
if (!buildDir.mkdirs()) {
throw new IllegalStateException("Can't create temp directory " + buildDir.getAbsolutePath());
}
final String dockerfile = generateDockerfileFor(plugins);
final File dockerfileFile = new File(buildDir, "Dockerfile");
writeStringToFile(dockerfileFile, dockerfile);
final File buildHomePath = new File(buildDir, JenkinsDockerImage.JENKINS_DEFAULT.homePath);
final File jenkinsConfig = new File(buildHomePath, "config.xml");
DockerHPIContainerUtil.copyResourceFromClass(DockerHPIContainerUtil.class, "config.xml", jenkinsConfig);
writeStringToFile(new File(buildHomePath, "jenkins.install.UpgradeWizard.state"), "2.19.4");
writeStringToFile(new File(buildHomePath, "jenkins.install.InstallUtil.lastExecVersion"), "2.19.4");
final File pluginDir = new File(buildHomePath, "/plugins/");
if (!pluginDir.mkdirs()) {
throw new IllegalStateException("Can't create dirs " + pluginDir.getAbsolutePath());
}
for (Map.Entry<String, File> entry : plugins.entrySet()) {
final File dst = new File(pluginDir + "/" + entry.getKey());
copyFile(entry.getValue(), dst);
}
try {
LOG.info("Building data-image...");
return getDockerCli().buildImageCmd(buildDir)
.withTag(DATA_IMAGE)
.withForcerm(true)
.exec(new BuildImageResultCallback() {
public void onNext(BuildResponseItem item) {
String text = item.getStream();
if (nonNull(text)) {
LOG.debug(StringUtils.removeEnd(text, NL));
}
super.onNext(item);
}
})
.awaitImageId();
} finally {
buildDir.delete();
}
} | java | public String buildImage(Map<String, File> plugins) throws IOException, InterruptedException {
LOG.debug("Building image for {}", plugins);
// final File tempDirectory = TempFileHelper.createTempDirectory("build-image", targetDir().toPath());
final File buildDir = new File(targetDir().getAbsolutePath() + "/docker-it/build-image");
if (buildDir.exists()) {
deleteDirectory(buildDir);
}
if (!buildDir.mkdirs()) {
throw new IllegalStateException("Can't create temp directory " + buildDir.getAbsolutePath());
}
final String dockerfile = generateDockerfileFor(plugins);
final File dockerfileFile = new File(buildDir, "Dockerfile");
writeStringToFile(dockerfileFile, dockerfile);
final File buildHomePath = new File(buildDir, JenkinsDockerImage.JENKINS_DEFAULT.homePath);
final File jenkinsConfig = new File(buildHomePath, "config.xml");
DockerHPIContainerUtil.copyResourceFromClass(DockerHPIContainerUtil.class, "config.xml", jenkinsConfig);
writeStringToFile(new File(buildHomePath, "jenkins.install.UpgradeWizard.state"), "2.19.4");
writeStringToFile(new File(buildHomePath, "jenkins.install.InstallUtil.lastExecVersion"), "2.19.4");
final File pluginDir = new File(buildHomePath, "/plugins/");
if (!pluginDir.mkdirs()) {
throw new IllegalStateException("Can't create dirs " + pluginDir.getAbsolutePath());
}
for (Map.Entry<String, File> entry : plugins.entrySet()) {
final File dst = new File(pluginDir + "/" + entry.getKey());
copyFile(entry.getValue(), dst);
}
try {
LOG.info("Building data-image...");
return getDockerCli().buildImageCmd(buildDir)
.withTag(DATA_IMAGE)
.withForcerm(true)
.exec(new BuildImageResultCallback() {
public void onNext(BuildResponseItem item) {
String text = item.getStream();
if (nonNull(text)) {
LOG.debug(StringUtils.removeEnd(text, NL));
}
super.onNext(item);
}
})
.awaitImageId();
} finally {
buildDir.delete();
}
} | [
"public",
"String",
"buildImage",
"(",
"Map",
"<",
"String",
",",
"File",
">",
"plugins",
")",
"throws",
"IOException",
",",
"InterruptedException",
"{",
"LOG",
".",
"debug",
"(",
"\"Building image for {}\"",
",",
"plugins",
")",
";",
"// final File tempDir... | Build docker image containing specified plugins. | [
"Build",
"docker",
"image",
"containing",
"specified",
"plugins",
"."
] | 40b12e39ff94c3834cff7e028c3dd01c88e87d77 | https://github.com/KostyaSha/yet-another-docker-plugin/blob/40b12e39ff94c3834cff7e028c3dd01c88e87d77/yet-another-docker-its/src/main/java/com/github/kostyasha/it/rule/DockerRule.java#L377-L427 | train |
KostyaSha/yet-another-docker-plugin | yet-another-docker-its/src/main/java/com/github/kostyasha/it/rule/DockerRule.java | DockerRule.runFreshJenkinsContainer | public String runFreshJenkinsContainer(DockerImagePullStrategy pullStrategy, boolean forceRefresh)
throws IOException, SettingsBuildingException, InterruptedException {
LOG.debug("Entering run fresh jenkins container.");
pullImage(pullStrategy, JENKINS_DEFAULT.getDockerImageName());
// labels attached to container allows cleanup container if it wasn't removed
final Map<String, String> labels = new HashMap<>();
labels.put("test.displayName", description.getDisplayName());
LOG.debug("Removing existed container before");
try {
final List<Container> containers = getDockerCli().listContainersCmd().withShowAll(true).exec();
for (Container c : containers) {
if (c.getLabels().equals(labels)) { // equals? container labels vs image labels?
LOG.debug("Removing {}, for labels: '{}'", c, labels);
getDockerCli().removeContainerCmd(c.getId())
.withForce(true)
.exec();
break;
}
}
} catch (NotFoundException ex) {
LOG.debug("Container wasn't found, that's ok");
}
LOG.debug("Recreating data container without data-image doesn't make sense, so reuse boolean.");
String dataContainerId = getDataContainerId(forceRefresh);
final String id = getDockerCli().createContainerCmd(JENKINS_DEFAULT.getDockerImageName())
.withEnv(CONTAINER_JAVA_OPTS)
.withExposedPorts(new ExposedPort(JENKINS_DEFAULT.tcpPort))
.withPortSpecs(String.format("%d/tcp", JENKINS_DEFAULT.tcpPort))
.withHostConfig(HostConfig.newHostConfig()
.withPortBindings(PortBinding.parse("0.0.0.0:48000:48000"))
.withVolumesFrom(new VolumesFrom(dataContainerId))
.withPublishAllPorts(true))
.withLabels(labels)
// .withPortBindings(PortBinding.parse("0.0.0.0:48000:48000"), PortBinding.parse("0.0.0.0:50000:50000"))
.exec()
.getId();
provisioned.add(id);
LOG.debug("Starting container");
getDockerCli().startContainerCmd(id).exec();
return id;
} | java | public String runFreshJenkinsContainer(DockerImagePullStrategy pullStrategy, boolean forceRefresh)
throws IOException, SettingsBuildingException, InterruptedException {
LOG.debug("Entering run fresh jenkins container.");
pullImage(pullStrategy, JENKINS_DEFAULT.getDockerImageName());
// labels attached to container allows cleanup container if it wasn't removed
final Map<String, String> labels = new HashMap<>();
labels.put("test.displayName", description.getDisplayName());
LOG.debug("Removing existed container before");
try {
final List<Container> containers = getDockerCli().listContainersCmd().withShowAll(true).exec();
for (Container c : containers) {
if (c.getLabels().equals(labels)) { // equals? container labels vs image labels?
LOG.debug("Removing {}, for labels: '{}'", c, labels);
getDockerCli().removeContainerCmd(c.getId())
.withForce(true)
.exec();
break;
}
}
} catch (NotFoundException ex) {
LOG.debug("Container wasn't found, that's ok");
}
LOG.debug("Recreating data container without data-image doesn't make sense, so reuse boolean.");
String dataContainerId = getDataContainerId(forceRefresh);
final String id = getDockerCli().createContainerCmd(JENKINS_DEFAULT.getDockerImageName())
.withEnv(CONTAINER_JAVA_OPTS)
.withExposedPorts(new ExposedPort(JENKINS_DEFAULT.tcpPort))
.withPortSpecs(String.format("%d/tcp", JENKINS_DEFAULT.tcpPort))
.withHostConfig(HostConfig.newHostConfig()
.withPortBindings(PortBinding.parse("0.0.0.0:48000:48000"))
.withVolumesFrom(new VolumesFrom(dataContainerId))
.withPublishAllPorts(true))
.withLabels(labels)
// .withPortBindings(PortBinding.parse("0.0.0.0:48000:48000"), PortBinding.parse("0.0.0.0:50000:50000"))
.exec()
.getId();
provisioned.add(id);
LOG.debug("Starting container");
getDockerCli().startContainerCmd(id).exec();
return id;
} | [
"public",
"String",
"runFreshJenkinsContainer",
"(",
"DockerImagePullStrategy",
"pullStrategy",
",",
"boolean",
"forceRefresh",
")",
"throws",
"IOException",
",",
"SettingsBuildingException",
",",
"InterruptedException",
"{",
"LOG",
".",
"debug",
"(",
"\"Entering run fresh ... | Run, record and remove after test container with jenkins.
@param forceRefresh enforce data container and data image refresh | [
"Run",
"record",
"and",
"remove",
"after",
"test",
"container",
"with",
"jenkins",
"."
] | 40b12e39ff94c3834cff7e028c3dd01c88e87d77 | https://github.com/KostyaSha/yet-another-docker-plugin/blob/40b12e39ff94c3834cff7e028c3dd01c88e87d77/yet-another-docker-its/src/main/java/com/github/kostyasha/it/rule/DockerRule.java#L444-L488 | train |
KostyaSha/yet-another-docker-plugin | yet-another-docker-its/src/main/java/com/github/kostyasha/it/rule/DockerRule.java | DockerRule.generateDockerfileFor | public String generateDockerfileFor(Map<String, File> plugins) throws IOException {
StringBuilder builder = new StringBuilder();
builder.append("FROM scratch").append(NL)
.append("MAINTAINER Kanstantsin Shautsou <kanstantsin.sha@gmail.com>").append(NL)
.append("COPY ./ /").append(NL)
.append("VOLUME /usr/share/jenkins/ref").append(NL);
for (Map.Entry<String, String> entry : generateLabels(plugins).entrySet()) {
builder.append("LABEL ").append(entry.getKey()).append("=").append(entry.getValue()).append(NL);
}
// newClientBuilderForConnector.append("LABEL GENERATION_UUID=").append(UUID.randomUUID()).append(NL);
return builder.toString();
} | java | public String generateDockerfileFor(Map<String, File> plugins) throws IOException {
StringBuilder builder = new StringBuilder();
builder.append("FROM scratch").append(NL)
.append("MAINTAINER Kanstantsin Shautsou <kanstantsin.sha@gmail.com>").append(NL)
.append("COPY ./ /").append(NL)
.append("VOLUME /usr/share/jenkins/ref").append(NL);
for (Map.Entry<String, String> entry : generateLabels(plugins).entrySet()) {
builder.append("LABEL ").append(entry.getKey()).append("=").append(entry.getValue()).append(NL);
}
// newClientBuilderForConnector.append("LABEL GENERATION_UUID=").append(UUID.randomUUID()).append(NL);
return builder.toString();
} | [
"public",
"String",
"generateDockerfileFor",
"(",
"Map",
"<",
"String",
",",
"File",
">",
"plugins",
")",
"throws",
"IOException",
"{",
"StringBuilder",
"builder",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"builder",
".",
"append",
"(",
"\"FROM scratch\"",
"... | 'Dockerfile' as String based on sratch for placing plugins. | [
"Dockerfile",
"as",
"String",
"based",
"on",
"sratch",
"for",
"placing",
"plugins",
"."
] | 40b12e39ff94c3834cff7e028c3dd01c88e87d77 | https://github.com/KostyaSha/yet-another-docker-plugin/blob/40b12e39ff94c3834cff7e028c3dd01c88e87d77/yet-another-docker-its/src/main/java/com/github/kostyasha/it/rule/DockerRule.java#L502-L516 | train |
KostyaSha/yet-another-docker-plugin | yet-another-docker-its/src/main/java/com/github/kostyasha/it/rule/DockerRule.java | DockerRule.createCliWithWait | private DockerCLI createCliWithWait(URL url, int port) throws InterruptedException, IOException {
DockerCLI tempCli = null;
boolean connected = false;
int i = 0;
while (i <= 10 && !connected) {
i++;
try {
final CLIConnectionFactory factory = new CLIConnectionFactory().url(url);
tempCli = new DockerCLI(factory, port);
final String channelName = tempCli.getChannel().getName();
if (channelName.contains("CLI connection to")) {
tempCli.upgrade();
connected = true;
LOG.debug(channelName);
} else {
LOG.debug("Cli connection is not via CliPort '{}'. Sleeping for 5s...", channelName);
tempCli.close();
Thread.sleep(5 * 1000);
}
} catch (IOException e) {
LOG.debug("Jenkins is not available. Sleeping for 5s...", e.getMessage());
Thread.sleep(5 * 1000);
}
}
if (!connected) {
throw new IOException("Can't connect to {}" + url.toString());
}
LOG.info("Jenkins future {}", url);
LOG.info("Jenkins future {}/configure", url);
LOG.info("Jenkins future {}/log/all", url);
return tempCli;
} | java | private DockerCLI createCliWithWait(URL url, int port) throws InterruptedException, IOException {
DockerCLI tempCli = null;
boolean connected = false;
int i = 0;
while (i <= 10 && !connected) {
i++;
try {
final CLIConnectionFactory factory = new CLIConnectionFactory().url(url);
tempCli = new DockerCLI(factory, port);
final String channelName = tempCli.getChannel().getName();
if (channelName.contains("CLI connection to")) {
tempCli.upgrade();
connected = true;
LOG.debug(channelName);
} else {
LOG.debug("Cli connection is not via CliPort '{}'. Sleeping for 5s...", channelName);
tempCli.close();
Thread.sleep(5 * 1000);
}
} catch (IOException e) {
LOG.debug("Jenkins is not available. Sleeping for 5s...", e.getMessage());
Thread.sleep(5 * 1000);
}
}
if (!connected) {
throw new IOException("Can't connect to {}" + url.toString());
}
LOG.info("Jenkins future {}", url);
LOG.info("Jenkins future {}/configure", url);
LOG.info("Jenkins future {}/log/all", url);
return tempCli;
} | [
"private",
"DockerCLI",
"createCliWithWait",
"(",
"URL",
"url",
",",
"int",
"port",
")",
"throws",
"InterruptedException",
",",
"IOException",
"{",
"DockerCLI",
"tempCli",
"=",
"null",
";",
"boolean",
"connected",
"=",
"false",
";",
"int",
"i",
"=",
"0",
";"... | Create DockerCLI connection against specified jnlpSlaveAgent port | [
"Create",
"DockerCLI",
"connection",
"against",
"specified",
"jnlpSlaveAgent",
"port"
] | 40b12e39ff94c3834cff7e028c3dd01c88e87d77 | https://github.com/KostyaSha/yet-another-docker-plugin/blob/40b12e39ff94c3834cff7e028c3dd01c88e87d77/yet-another-docker-its/src/main/java/com/github/kostyasha/it/rule/DockerRule.java#L568-L601 | train |
KostyaSha/yet-another-docker-plugin | yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/strategy/DockerCloudRetentionStrategy.java | DockerCloudRetentionStrategy.check | @Override
@GuardedBy("hudson.model.Queue.lock")
public long check(final AbstractCloudComputer c) {
final AbstractCloudSlave computerNode = c.getNode();
if (c.isIdle() && computerNode != null) {
final long idleMilliseconds = System.currentTimeMillis() - c.getIdleStartMilliseconds();
if (idleMilliseconds > MINUTES.toMillis(idleMinutes)) {
LOG.info("Disconnecting {}, after {} min timeout.", c.getName(), idleMinutes);
try {
computerNode.terminate();
} catch (InterruptedException | IOException e) {
LOG.warn("Failed to terminate {}", c.getName(), e);
}
}
}
return 1;
} | java | @Override
@GuardedBy("hudson.model.Queue.lock")
public long check(final AbstractCloudComputer c) {
final AbstractCloudSlave computerNode = c.getNode();
if (c.isIdle() && computerNode != null) {
final long idleMilliseconds = System.currentTimeMillis() - c.getIdleStartMilliseconds();
if (idleMilliseconds > MINUTES.toMillis(idleMinutes)) {
LOG.info("Disconnecting {}, after {} min timeout.", c.getName(), idleMinutes);
try {
computerNode.terminate();
} catch (InterruptedException | IOException e) {
LOG.warn("Failed to terminate {}", c.getName(), e);
}
}
}
return 1;
} | [
"@",
"Override",
"@",
"GuardedBy",
"(",
"\"hudson.model.Queue.lock\"",
")",
"public",
"long",
"check",
"(",
"final",
"AbstractCloudComputer",
"c",
")",
"{",
"final",
"AbstractCloudSlave",
"computerNode",
"=",
"c",
".",
"getNode",
"(",
")",
";",
"if",
"(",
"c",... | While x-stream serialisation buggy, copy implementation. | [
"While",
"x",
"-",
"stream",
"serialisation",
"buggy",
"copy",
"implementation",
"."
] | 40b12e39ff94c3834cff7e028c3dd01c88e87d77 | https://github.com/KostyaSha/yet-another-docker-plugin/blob/40b12e39ff94c3834cff7e028c3dd01c88e87d77/yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/strategy/DockerCloudRetentionStrategy.java#L38-L54 | train |
KostyaSha/yet-another-docker-plugin | yet-another-docker-its/src/main/java/com/github/kostyasha/it/utils/JenkinsRuleHelpers.java | JenkinsRuleHelpers.isSomethingHappening | public static boolean isSomethingHappening(Jenkins jenkins) {
if (!jenkins.getQueue().isEmpty())
return true;
for (Computer n : jenkins.getComputers())
if (!n.isIdle())
return true;
return false;
} | java | public static boolean isSomethingHappening(Jenkins jenkins) {
if (!jenkins.getQueue().isEmpty())
return true;
for (Computer n : jenkins.getComputers())
if (!n.isIdle())
return true;
return false;
} | [
"public",
"static",
"boolean",
"isSomethingHappening",
"(",
"Jenkins",
"jenkins",
")",
"{",
"if",
"(",
"!",
"jenkins",
".",
"getQueue",
"(",
")",
".",
"isEmpty",
"(",
")",
")",
"return",
"true",
";",
"for",
"(",
"Computer",
"n",
":",
"jenkins",
".",
"g... | Returns true if Hudson is building something or going to build something. | [
"Returns",
"true",
"if",
"Hudson",
"is",
"building",
"something",
"or",
"going",
"to",
"build",
"something",
"."
] | 40b12e39ff94c3834cff7e028c3dd01c88e87d77 | https://github.com/KostyaSha/yet-another-docker-plugin/blob/40b12e39ff94c3834cff7e028c3dd01c88e87d77/yet-another-docker-its/src/main/java/com/github/kostyasha/it/utils/JenkinsRuleHelpers.java#L38-L45 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.