code
stringlengths
73
34.1k
label
stringclasses
1 value
public static CompressionMetadata create(String dataFilePath) { Descriptor desc = Descriptor.fromFilename(dataFilePath); return new CompressionMetadata(desc.filenameFor(Component.COMPRESSION_INFO), new File(dataFilePath).length(), desc.version.hasPostCompressionAdlerChecksums); }
java
boolean reset(double useChance, int targetCount, boolean isWrite) { this.isWrite = isWrite; if (this.useChance < 1d) { // we clear our prior roll-modifiers if the use chance was previously less-than zero Arrays.fill(rollmodifier, 1d); ...
java
private int setNoLastRow(int firstComponentCount) { Arrays.fill(lastRow, Integer.MAX_VALUE); return firstComponentCount * generator.clusteringDescendantAverages[0]; }
java
private int setLastRow(int position) { if (position < 0) throw new IllegalStateException(); decompose(position, lastRow); int expectedRowCount = 0; for (int i = 0 ; i < lastRow.length ; i++) { int l = lastRow[i]; ...
java
private int compareToLastRow(int depth) { for (int i = 0 ; i <= depth ; i++) { int p = currentRow[i], l = lastRow[i], r = clusteringComponents[i].size(); if ((p == l) | (r == 1)) continue; return p - l; } ...
java
private void decompose(int scalar, int[] decomposed) { for (int i = 0 ; i < decomposed.length ; i++) { int avg = generator.clusteringDescendantAverages[i]; decomposed[i] = scalar / avg; scalar %= avg; } for (int i = ...
java
private State seek(int scalar) { if (scalar == 0) { this.currentRow[0] = -1; clusteringComponents[0].addFirst(this); return setHasNext(advance(0, true)); } int[] position = this.currentRow; decompose(sca...
java
void advance() { // we are always at the leaf level when this method is invoked // so we calculate the seed for generating the row by combining the seed that generated the clustering components int depth = clusteringComponents.length - 1; long parentSeed = cluster...
java
void fill(int depth) { long seed = clusteringSeeds[depth - 1]; Generator gen = generator.clusteringComponents.get(depth); gen.setSeed(seed); clusteringSeeds[depth] = seed(clusteringComponents[depth - 1].peek(), generator.clusteringComponents.get(depth - 1).type, s...
java
void fill(Queue<Object> queue, int count, Generator generator) { if (count == 1) { queue.add(generator.generate()); return; } switch (this.generator.order) { case SORTED: if (Comparab...
java
public WaitQueue.Signal requestExtraSync() { WaitQueue.Signal signal = syncComplete.register(); haveWork.release(1); return signal; }
java
static URL getStorageConfigURL() throws ConfigurationException { String configUrl = System.getProperty("cassandra.config"); if (configUrl == null) configUrl = DEFAULT_CONFIGURATION; URL url; try { url = new URL(configUrl); url.openStream()...
java
public void deleteFromSchema(Mutation mutation, long timestamp) { ColumnFamily cf = mutation.addOrGet(CFMetaData.SchemaColumnsCf); int ldt = (int) (System.currentTimeMillis() / 1000); // Note: we do want to use name.toString(), not name.bytes directly for backward compatibility (For CQL3, t...
java
public static List<ColumnDefinition> fromSchema(UntypedResultSet serializedColumns, String ksName, String cfName, AbstractType<?> rawComparator, boolean isSuper) { List<ColumnDefinition> cds = new ArrayList<>(); for (UntypedResultSet.Row row : serializedColumns) { Kind kind = row...
java
public ByteBuffer getSerializedValue(ByteBuffer serializedMap, ByteBuffer serializedKey, AbstractType keyType) { try { ByteBuffer input = serializedMap.duplicate(); int n = readCollectionSize(input, Server.VERSION_3); for (int i = 0; i < n; i++) { ...
java
public static <V> Object[] build(Iterable<V> source, int size, Comparator<V> comparator, boolean sorted, UpdateFunction<V> updateF) { if (size < FAN_FACTOR) { // pad to even length to match contract that all leaf nodes are even V[] values = (V[]) new Object[size + (size & 1)]...
java
public static <V> Cursor<V, V> slice(Object[] btree, boolean forwards) { Cursor<V, V> r = new Cursor<>(); r.reset(btree, forwards); return r; }
java
public static <K, V extends K> Cursor<K, V> slice(Object[] btree, Comparator<K> comparator, K start, boolean startInclusive, K end, boolean endInclusive, boolean forwards) { Cursor<K, V> r = new Cursor<>(); r.reset(btree, comparator, start, startInclusive, end, endInclusive, forwards); retur...
java
static int getLeafKeyEnd(Object[] node) { int len = node.length; if (len == 0) return 0; else if (node[len - 1] == null) return len - 1; else return len; }
java
private static <V> Collection<V> sorted(Iterable<V> source, Comparator<V> comparator, int size) { V[] vs = (V[]) new Object[size]; int i = 0; for (V v : source) vs[i++] = v; Arrays.sort(vs, comparator); return Arrays.asList(vs); }
java
public int completed(InetAddress request) { String dc = DatabaseDescriptor.getEndpointSnitch().getDatacenter(request); Queue<InetAddress> requests = requestsByDatacenter.get(dc); assert requests != null; assert request.equals(requests.peek()); requests.poll(); if (!re...
java
public static DataResource fromName(String name) { String[] parts = StringUtils.split(name, '/'); if (!parts[0].equals(ROOT_NAME) || parts.length > 3) throw new IllegalArgumentException(String.format("%s is not a valid data resource name", name)); if (parts.length == 1) ...
java
protected <T extends Number> Gauge<T> createColumnFamilyGauge(final String name, Gauge<T> gauge) { return createColumnFamilyGauge(name, gauge, new Gauge<Long>() { public Long value() { long total = 0; for (Metric cfGauge : allColumnFamilyMetric...
java
protected <G,T> Gauge<T> createColumnFamilyGauge(String name, Gauge<T> gauge, Gauge<G> globalGauge) { Gauge<T> cfGauge = Metrics.newGauge(factory.createMetricName(name), gauge); if (register(name, cfGauge)) { Metrics.newGauge(globalNameFactory.createMetricName(name), globalGauge)...
java
protected Counter createColumnFamilyCounter(final String name) { Counter cfCounter = Metrics.newCounter(factory.createMetricName(name)); if (register(name, cfCounter)) { Metrics.newGauge(globalNameFactory.createMetricName(name), new Gauge<Long>() { pub...
java
protected ColumnFamilyHistogram createColumnFamilyHistogram(String name, Histogram keyspaceHistogram) { Histogram cfHistogram = Metrics.newHistogram(factory.createMetricName(name), true); register(name, cfHistogram); return new ColumnFamilyHistogram(cfHistogram, keyspaceHistogram, Metrics...
java
private boolean register(String name, Metric metric) { boolean ret = allColumnFamilyMetrics.putIfAbsent(name, new HashSet<Metric>()) == null; allColumnFamilyMetrics.get(name).add(metric); all.add(name); return ret; }
java
public static void setOutputKeyspace(Configuration conf, String keyspace) { if (keyspace == null) throw new UnsupportedOperationException("keyspace may not be null"); conf.set(OUTPUT_KEYSPACE_CONFIG, keyspace); }
java
public static void setOutputColumnFamily(Configuration conf, String keyspace, String columnFamily) { setOutputKeyspace(conf, keyspace); setOutputColumnFamily(conf, columnFamily); }
java
public static void setInputSlicePredicate(Configuration conf, SlicePredicate predicate) { conf.set(INPUT_PREDICATE_CONFIG, thriftToString(predicate)); }
java
public static KeyRange getInputKeyRange(Configuration conf) { String str = conf.get(INPUT_KEYRANGE_CONFIG); return str == null ? null : keyRangeFromString(str); }
java
public OnDiskAtom readNext() throws IOException { Composite name = nameDeserializer.readNext(); assert !name.isEmpty(); // This would imply hasNext() hasn't been called nextFlags = nextFlags == Integer.MIN_VALUE ? in.readUnsignedByte() : nextFlags; OnDiskAtom atom = (nextFlags & Col...
java
public void skipNext() throws IOException { nameDeserializer.skipNext(); nextFlags = nextFlags == Integer.MIN_VALUE ? in.readUnsignedByte() : nextFlags; if ((nextFlags & ColumnSerializer.RANGE_TOMBSTONE_MASK) != 0) type.rangeTombstoneSerializer().skipBody(in, version); el...
java
public void connectionComplete(SocketAddress socket) { assert socket != null; activeSocketSessions.remove(socket); if (logger.isTraceEnabled()) logger.trace("ClientState removed for socket addr {}", socket); }
java
public void delete(final DecoratedKey partitionKey) { if (indexQueue == null) { deleteInner(partitionKey); } else { indexQueue.submitAsynchronous(partitionKey, new Runnable() { @Override public void run() { deleteInner(partition...
java
public final void commit() { if (indexQueue == null) { luceneIndex.commit(); } else { indexQueue.submitSynchronous(new Runnable() { @Override public void run() { luceneIndex.commit(); } }); } ...
java
public static void printOptions(PrintStream out, String command, GroupedOptions... groupings) { out.println(); boolean firstRow = true; for (GroupedOptions grouping : groupings) { if (!firstRow) { out.println(" OR "); } ...
java
public ByteBuffer createMessage(boolean compress, int version) { int header = 0; // set compression bit. if (compress) header |= 4; // set streaming bit header |= 8; // Setting up the version bit header |= (version << 8); byte[] bytes; ...
java
public RowIndexEntry tryAppend(AbstractCompactedRow row) { writer.mark(); try { return append(row); } catch (Throwable t) { writer.resetAndTruncate(); throw t; } }
java
private void moveStarts(SSTableReader newReader, DecoratedKey lowerbound, boolean reset) { if (isOffline) return; List<SSTableReader> toReplace = new ArrayList<>(); List<SSTableReader> replaceWith = new ArrayList<>(); final List<DecoratedKey> invalidateKeys = new ArrayLis...
java
private void replaceWithFinishedReaders(List<SSTableReader> finished) { if (isOffline) { for (SSTableReader reader : discard) { if (reader.getCurrentReplacement() == reader) reader.markObsolete(); reader.selfRef().release();...
java
public CQLSSTableWriter rawAddRow(ByteBuffer... values) throws InvalidRequestException, IOException { return rawAddRow(Arrays.asList(values)); }
java
public static void calculatePendingRanges(AbstractReplicationStrategy strategy, String keyspaceName) { TokenMetadata tm = StorageService.instance.getTokenMetadata(); Multimap<Range<Token>, InetAddress> pendingRanges = HashMultimap.create(); BiMultiValMap<Token, InetAddress> bootstrapTokens =...
java
@Override public synchronized void gossiperStarting() { gossiperInitialized = true; StorageService.instance.gossipSnitchInfo(); Gossiper.instance.register(new ReconnectableSnitchHelper(this, localNodeData.datacenter, true)); }
java
public synchronized ScheduledFuture scheduleTimeout(final int sequenceNumber, long time, TimeUnit unit) { if (!files.containsKey(sequenceNumber)) return null; ScheduledFuture future = timeoutExecutor.schedule(new Runnable() { public void run() { ...
java
public void add(Composite start, Composite end, long markedAt, int delTime) { if (isEmpty()) { addInternal(0, start, end, markedAt, delTime); return; } int c = comparator.compare(ends[size-1], start); // Fast path if we add in sorted order if...
java
public void purge(int gcBefore) { int j = 0; for (int i = 0; i < size; i++) { if (delTimes[i] >= gcBefore) setInternal(j++, starts[i], ends[i], markedAts[i], delTimes[i]); } size = j; }
java
public void updateDigest(MessageDigest digest) { ByteBuffer longBuffer = ByteBuffer.allocate(8); for (int i = 0; i < size; i++) { for (int j = 0; j < starts[i].size(); j++) digest.update(starts[i].get(j).duplicate()); for (int j = 0; j < ends[i].size()...
java
@VisibleForTesting public long[] getHashBuckets(ByteBuffer key, int hashCount, long max) { long[] hash = new long[2]; hash(key, key.position(), key.remaining(), 0L, hash); long[] indexes = new long[hashCount]; setIndexes(hash[0], hash[1], hashCount, max, indexes); return ...
java
private long[] indexes(ByteBuffer key) { // we use the same array both for storing the hash result, and for storing the indexes we return, // so that we do not need to allocate two arrays. long[] indexes = reusableIndexes.get(); hash(key, key.position(), key.remaining(), 0L, indexes)...
java
public final void addFields(Document document, CellName cellName) { String serializedKey = ByteBufferUtils.toString(cellName.toByteBuffer()); Field field = new StringField(FIELD_NAME, serializedKey, Field.Store.YES); document.add(field); }
java
public final List<CellName> clusteringKeys(ColumnFamily columnFamily) { List<CellName> clusteringKeys = new ArrayList<>(); CellName lastClusteringKey = null; for (Cell cell : columnFamily) { CellName cellName = cell.name(); if (!isStatic(cellName)) { CellN...
java
public final CellName makeCellName(CellName cellName, ColumnDefinition columnDefinition) { return cellNameType.create(start(cellName), columnDefinition); }
java
public final CellName clusteringKey(BytesRef bytesRef) { String string = bytesRef.utf8ToString(); ByteBuffer bb = ByteBufferUtils.fromString(string); return cellNameType.cellFromByteBuffer(bb); }
java
public final Composite start(CellName cellName) { CBuilder builder = cellNameType.builder(); for (int i = 0; i < cellName.clusteringSize(); i++) { ByteBuffer component = cellName.get(i); builder.add(component); } return builder.build(); }
java
public final Composite end(CellName cellName) { return start(cellName).withEOC(Composite.EOC.END); }
java
public final List<CellName> sort(List<CellName> clusteringKeys) { List<CellName> result = new ArrayList<>(clusteringKeys); Collections.sort(result, new Comparator<CellName>() { @Override public int compare(CellName o1, CellName o2) { return cellNameType.compare(o1...
java
public String get(String propertyName, String defaultValue) { return properties.getProperty(propertyName, defaultValue); }
java
public static AbstractType<?> parse(String str) throws SyntaxException, ConfigurationException { if (str == null) return BytesType.instance; AbstractType<?> type = cache.get(str); if (type != null) return type; // This could be simplier (i.e. new TypeParser...
java
public AbstractType<?> parse() throws SyntaxException, ConfigurationException { skipBlank(); String name = readNextIdentifier(); skipBlank(); if (!isEOS() && str.charAt(idx) == '(') return getAbstractType(name, this); else return getAbstractType(name)...
java
private boolean skipBlankAndComma() { boolean commaFound = false; while (!isEOS()) { int c = str.charAt(idx); if (c == ',') { if (commaFound) return true; else commaFound = true; ...
java
public String readNextIdentifier() { int i = idx; while (!isEOS() && isIdentifierChar(str.charAt(idx))) ++idx; return str.substring(i, idx); }
java
private void seekToChunkStart() { if (getOnDiskFilePointer() != chunkOffset) { try { out.seek(chunkOffset); } catch (IOException e) { throw new FSReadError(e, getPath()); } } }
java
public void validate(CFMetaData metadata) { for (Map.Entry<String, ColumnMapper> entry : columnMappers.entrySet()) { String name = entry.getKey(); ColumnMapper columnMapper = entry.getValue(); ByteBuffer columnName = UTF8Type.instance.decompose(name); ColumnDefi...
java
public void reload() { // figure out what needs to be added and dropped. // future: if/when we have modifiable settings for secondary indexes, // they'll need to be handled here. Collection<ByteBuffer> indexedColumnNames = indexesByColumn.keySet(); for (ByteBuffer indexedColu...
java
public void maybeBuildSecondaryIndexes(Collection<SSTableReader> sstables, Set<String> idxNames) { if (idxNames.isEmpty()) return; logger.info(String.format("Submitting index build of %s for data in %s", idxNames, StringUtils.join(sstables, ", "))); ...
java
public void removeIndexedColumn(ByteBuffer column) { SecondaryIndex index = indexesByColumn.remove(column); if (index == null) return; // Remove this column from from row level index map as well as all indexes set if (index instanceof PerRowSecondaryIndex) { ...
java
public synchronized Future<?> addIndexedColumn(ColumnDefinition cdef) { if (indexesByColumn.containsKey(cdef.name.bytes)) return null; assert cdef.getIndexType() != null; SecondaryIndex index; try { index = SecondaryIndex.createInstance(baseCfs, cdef...
java
public void flushIndexesBlocking() { // despatch flushes for all CFS backed indexes List<Future<?>> wait = new ArrayList<>(); synchronized (baseCfs.getDataTracker()) { for (SecondaryIndex index : allIndexes) if (index.getIndexCfs() != null) ...
java
public void indexRow(ByteBuffer key, ColumnFamily cf, OpOrder.Group opGroup) { // Update entire row only once per row level index Set<Class<? extends SecondaryIndex>> appliedRowLevelIndexes = null; for (SecondaryIndex index : allIndexes) { if (index instanceof PerRowSeco...
java
public void deleteFromIndexes(DecoratedKey key, List<Cell> indexedColumnsInRow, OpOrder.Group opGroup) { // Update entire row only once per row level index Set<Class<? extends SecondaryIndex>> cleanedRowLevelIndexes = null; for (Cell cell : indexedColumnsInRow) { for (Se...
java
public List<SecondaryIndexSearcher> getIndexSearchersForQuery(List<IndexExpression> clause) { Map<String, Set<ByteBuffer>> groupByIndexType = new HashMap<>(); //Group columns by type for (IndexExpression ix : clause) { SecondaryIndex index = getIndexForColumn(ix.column);...
java
public List<Row> search(ExtendedFilter filter) { SecondaryIndexSearcher mostSelective = getHighestSelectivityIndexSearcher(filter.getClause()); if (mostSelective == null) return Collections.emptyList(); else return mostSelective.search(filter); }
java
public void write(DataOutput out) throws IOException { out.writeUTF(startToken); out.writeUTF(endToken); out.writeInt(dataNodes.length); for (String endpoint : dataNodes) { out.writeUTF(endpoint); } }
java
@Override public void afterExecute(Runnable r, Throwable t) { super.afterExecute(r,t); DebuggableThreadPoolExecutor.logExceptionsAfterExecute(r, t); }
java
public long snapshotCreationTime(String snapshotName) { for (File dir : dataPaths) { File snapshotDir = new File(dir, join(SNAPSHOT_SUBDIR, snapshotName)); if (snapshotDir.exists()) return snapshotDir.lastModified(); } throw new RuntimeExceptio...
java
public static List<File> getKSChildDirectories(String ksName) { List<File> result = new ArrayList<>(); for (DataDirectory dataDirectory : dataDirectories) { File ksDir = new File(dataDirectory.location, ksName); File[] cfDirs = ksDir.listFiles(); if (cfDir...
java
protected static String makeFilename(File directory, final String keyspace, final String columnFamily) { final Set<Descriptor> existing = new HashSet<Descriptor>(); directory.list(new FilenameFilter() { public boolean accept(File dir, String name) { Pa...
java
private void setToRowStart(RowIndexEntry rowEntry, FileDataInput in) throws IOException { if (in == null) { this.file = sstable.getFileDataInput(rowEntry.position); } else { this.file = in; in.seek(rowEntry.position); } ssta...
java
public void collectMarkerSpecification(VariableSpecifications boundNames) { if (collectionElement != null) collectionElement.collectMarkerSpecification(boundNames); if (operator.equals(Operator.IN) && inValues != null) { for (Term value : inValues) va...
java
public Socket createConnection(InetAddress peer) throws IOException { int attempts = 0; while (true) { try { Socket socket = OutboundTcpConnectionPool.newSocket(peer); socket.setSoTimeout(DatabaseDescriptor.getStreamingSocketTimeout());...
java
public void init() { // determine the depth to which we can safely split the tree byte sizedepth = (byte)(Math.log10(maxsize) / Math.log10(2)); byte depth = (byte)Math.min(sizedepth, hashdepth); root = initHelper(fullRange.left, fullRange.right, (byte)0, depth); size = (long...
java
public TreeRange get(Token t) { return getHelper(root, fullRange.left, fullRange.right, (byte)0, t); }
java
public boolean split(Token t) { if (!(size < maxsize)) return false; try { root = splitHelper(root, fullRange.left, fullRange.right, (byte)0, t); } catch (StopRecursion.TooDeep e) { return false; } return true; ...
java
public static void inspectThrowable(Throwable t) { boolean isUnstable = false; if (t instanceof OutOfMemoryError) isUnstable = true; if (DatabaseDescriptor.getDiskFailurePolicy() == Config.DiskFailurePolicy.die) if (t instanceof FSError || t instanceof CorruptSSTable...
java
private void reduceNameFilter(QueryFilter filter, ColumnFamily container, long sstableTimestamp) { if (container == null) return; for (Iterator<CellName> iterator = ((NamesQueryFilter) filter.filter).columns.iterator(); iterator.hasNext(); ) { CellName filterColumn =...
java
public static CellNameType getIndexComparator(CFMetaData baseMetadata, ColumnDefinition cfDef) { if (cfDef.type.isCollection() && cfDef.type.isMultiCell()) { switch (((CollectionType)cfDef.type).kind) { case LIST: return CompositesIndexOnCo...
java
private String getLocation() { Collection<InetAddress> localAddresses = FBUtilities.getAllLocalAddresses(); for (InetAddress address : localAddresses) { for (String location : split.getLocations()) { InetAddress locationAddress = null; ...
java
public static RuntimeException rethrow(RequestExecutionException e) throws UnavailableException, TimedOutException { if (e instanceof RequestTimeoutException) throw toThrift((RequestTimeoutException)e); else throw new UnavailableException(); }
java
OutboundTcpConnection getConnection(MessageOut msg) { Stage stage = msg.getStage(); return stage == Stage.REQUEST_RESPONSE || stage == Stage.INTERNAL_RESPONSE || stage == Stage.GOSSIP ? ackCon : cmdCon; }
java
@Override public void execute(Runnable task) { // count a new task in process tasksInProcess.incrementAndGet(); try { super.execute(task); } catch (RuntimeException e) { // specifically handle RejectedExecutionException tasksInProcess.decrementAndGet(); ...
java
public static int getEffectiveIndexIntervalAfterIndex(int index, int samplingLevel, int minIndexInterval) { assert index >= 0; index %= samplingLevel; List<Integer> originalIndexes = getOriginalIndexes(samplingLevel); int nextEntryOriginalIndex = (index == originalIndexes.size() - 1)...
java
Allocation allocate(Mutation mutation, int size) { final OpOrder.Group opGroup = appendOrder.start(); try { int position = allocate(size); if (position < 0) { opGroup.close(); return null; } markDirty...
java
private int allocate(int size) { while (true) { int prev = allocatePosition.get(); int next = prev + size; if (next >= buffer.capacity()) return -1; if (allocatePosition.compareAndSet(prev, next)) return prev; } ...
java
void discardUnusedTail() { // we guard this with the OpOrdering instead of synchronised due to potential dead-lock with CLSM.advanceAllocatingFrom() // this actually isn't strictly necessary, as currently all calls to discardUnusedTail occur within a block // already protected by this OpOrde...
java
synchronized void sync() { try { // check we have more work to do if (allocatePosition.get() <= lastSyncedOffset + SYNC_MARKER_SIZE) return; // allocate a new sync marker; this is both necessary in itself, but also serves to demarcate ...
java
CommitLogSegment recycle() { try { sync(); } catch (FSWriteError e) { logger.error("I/O error flushing {} {}", this, e.getMessage()); throw e; } close(); return new CommitLogSegment(getPath()); }
java
public synchronized void markClean(UUID cfId, ReplayPosition context) { if (!cfDirty.containsKey(cfId)) return; if (context.segment == id) markClean(cfId, context.position); else if (context.segment > id) markClean(cfId, Integer.MAX_VALUE); }
java
public String dirtyString() { StringBuilder sb = new StringBuilder(); for (UUID cfId : getDirtyCFIDs()) { CFMetaData m = Schema.instance.getCFMetaData(cfId); sb.append(m == null ? "<deleted>" : m.cfName).append(" (").append(cfId).append("), "); } retur...
java
public StreamPlan transferFiles(InetAddress to, Collection<StreamSession.SSTableStreamingSections> sstableDetails) { coordinator.transferFiles(to, sstableDetails); return this; }
java