code
stringlengths
73
34.1k
label
stringclasses
1 value
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); } ...
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...
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; }
java
@Deprecated public void close(org.apache.hadoop.mapred.Reporter reporter) throws IOException { close(); }
java
static SelectStatement forSelection(CFMetaData cfm, Selection selection) { return new SelectStatement(cfm, 0, defaultParameters, selection, null); }
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; }
java
private static Composite addEOC(Composite composite, Bound eocBound) { return eocBound == Bound.END ? composite.end() : composite.start(); }
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); }
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) { ...
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...
java
synchronized void requestReport(CountDownLatch signal) { if (finalReport != null) { report = finalReport; finalReport = new TimingInterval(0); signal.countDown(); } else reportRequest = signal; }
java
public synchronized void close() { if (reportRequest == null) finalReport = buildReport(); else { finalReport = new TimingInterval(0); report = buildReport(); reportRequest.countDown(); reportRequest = null; } }
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() ? DataInteg...
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() ...
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); }
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...
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)); }
java
@Override public void execute(Runnable command) { super.execute(isTracing() && !(command instanceof TraceSessionWrapper) ? new TraceSessionWrapper<Object>(Executors.callable(command, null)) : command); }
java
public void executeCLIStatement(String statement) throws CharacterCodingException, TException, TimedOutException, NotFoundException, NoSuchFieldException, InvalidRequestException, UnavailableException, InstantiationException, IllegalAccessException { Tree tree = CliCompiler.compileQuery(statement); ...
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>) Tr...
java
private void executeIncr(Tree statement, long multiplier) throws TException, NotFoundException, InvalidRequestException, UnavailableException, TimedOutException { if (!CliMain.isConnected() || !hasKeySpace()) return; Tree columnFamilySpec = statement.getChild(0); St...
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(keyspaceN...
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())); ...
java
private void executeUpdateKeySpace(Tree statement) { if (!CliMain.isConnected()) return; try { String keyspaceName = CliCompiler.getKeySpace(statement, thriftClient.describe_keyspaces()); KsDef currentKsDef = getKSMetaData(keyspaceName); KsDe...
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 C...
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.getChil...
java
private void executeDelKeySpace(Tree statement) throws TException, InvalidRequestException, NotFoundException, SchemaDisagreementException { if (!CliMain.isConnected()) return; String keyspaceName = CliCompiler.getKeySpace(statement, thriftClient.describe_keyspaces()); ...
java
private void executeDelColumnFamily(Tree statement) throws TException, InvalidRequestException, NotFoundException, SchemaDisagreementException { if (!CliMain.isConnected() || !hasKeySpace()) return; String cfName = CliCompiler.getColumnFamily(statement, currentCfDefs()); ...
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 != nul...
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 ...
java
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 IndexType getIndexTypeFromString(String indexTypeAsString) { IndexType indexType; try { indexType = IndexType.findByValue(new Integer(indexTypeAsString)); } catch (NumberFormatException e) { try { // if this...
java
private ByteBuffer subColumnNameAsBytes(String superColumn, String columnFamily) { CfDef columnFamilyDef = getCfDef(columnFamily); return subColumnNameAsBytes(superColumn, columnFamilyDef); }
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'", colum...
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 (Array...
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 f...
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.getValid...
java
private ColumnDef getColumnDefByName(CfDef columnFamily, ByteBuffer columnName) { for (ColumnDef columnDef : columnFamily.getColumn_metadata()) { byte[] currName = columnDef.getName(); if (ByteBufferUtil.compare(currName, columnName) == 0) { retur...
java
private String formatSubcolumnName(String keyspace, String columnFamily, ByteBuffer name) { return getFormatType(getCfDef(keyspace, columnFamily).subcomparator_type).getString(name); }
java
private String formatColumnName(String keyspace, String columnFamily, ByteBuffer name) { return getFormatType(getCfDef(keyspace, columnFamily).comparator_type).getString(name); }
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 ...
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.capa...
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(...
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, ...
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 repair...
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 waiti...
java
public String getString(ByteBuffer bytes) { TypeSerializer<T> serializer = getSerializer(); serializer.validate(bytes); return serializer.toString(serializer.deserialize(bytes)); }
java
public boolean isValueCompatibleWith(AbstractType<?> otherType) { return isValueCompatibleWithInternal((otherType instanceof ReversedType) ? ((ReversedType) otherType).baseType : otherType); }
java
public int compareCollectionMembers(ByteBuffer v1, ByteBuffer v2, ByteBuffer collectionName) { return compare(v1, v2); }
java
private static void writeKey(PrintStream out, String value) { writeJSON(out, value); out.print(": "); }
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) ...
java
private static void serializeRow(SSTableIdentityIterator row, DecoratedKey key, PrintStream out) { serializeRow(row.getColumnFamily().deletionInfo(), row, row.getColumnFamily().metadata(), key, out); }
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....
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...
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; ...
java
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, String[] excludes, CFMetaData metadata) throws IOException { export(desc, System.out, excludes, metadata); }
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.par...
java
public SemanticVersion findSupportingVersion(SemanticVersion... versions) { for (SemanticVersion version : versions) { if (isSupportedBy(version)) return version; } return null; }
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()) {...
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 += ...
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...
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); ...
java
private void startSpinning() { assert get() == Work.WORKING; pool.spinningCount.incrementAndGet(); set(Work.SPINNING); }
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); sle...
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 (po...
java
public List<Row> postReconciliationProcessing(List<IndexExpression> clause, List<Row> rows) { return rows; }
java
public boolean isIndexBuilt(ByteBuffer columnName) { return SystemKeyspace.isIndexBuilt(baseCfs.keyspace.getName(), getNameForSystemKeyspace(columnName)); }
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) ...
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...
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); }
java
public static SecondaryIndex createInstance(ColumnFamilyStore baseCfs, ColumnDefinition cdef) throws ConfigurationException { SecondaryIndex index; switch (cdef.getIndexType()) { case KEYS: index = new KeysIndex(); break; case COMPOSITES: ...
java
public static CellNameType getIndexComparator(CFMetaData baseMetadata, ColumnDefinition cdef) { switch (cdef.getIndexType()) { case KEYS: return new SimpleDenseCellNameType(keyComparator); case COMPOSITES: return CompositesIndex.getIndexCompara...
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...
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<Tok...
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( ...
java
public void activate() { String pidFile = System.getProperty("cassandra-pidfile"); try { try { MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); mbs.registerMBean(new StandardMBean(new NativeAccess(), NativeAccessMBean.clas...
java
protected static String toInternalName(String name, boolean keepCase) { return keepCase ? name : name.toLowerCase(Locale.US); }
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...
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 eac...
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 + ...
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; ...
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) ...
java
public void reloadClasses() { File triggerDirectory = FBUtilities.cassandraTriggerDir(); if (triggerDirectory == null) return; customClassLoader = new CustomClassLoader(parent, triggerDirectory); cachedTriggers.clear(); }
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.currentThrea...
java
private static CharArraySet getDefaultStopwords(String language) { switch (language) { case "English": return EnglishAnalyzer.getDefaultStopSet(); case "French": return FrenchAnalyzer.getDefaultStopSet(); case "Spanish": return ...
java
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 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 setInputWhereClauses(Configuration conf, String clauses) { if (clauses == null || clauses.isEmpty()) return; conf.set(INPUT_CQL_WHERE_CLAUSE_CONFIG, clauses); }
java
public static void setOutputCql(Configuration conf, String cql) { if (cql == null || cql.isEmpty()) return; conf.set(OUTPUT_CQL, cql); }
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)) ...
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", ...
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.getR...
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...
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().getAbsolute...
java
public String runFreshJenkinsContainer(DockerImagePullStrategy pullStrategy, boolean forceRefresh) throws IOException, SettingsBuildingException, InterruptedException { LOG.debug("Entering run fresh jenkins container."); pullImage(pullStrategy, JENKINS_DEFAULT.getDockerImageName()); ...
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 ./ /"...
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 CL...
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(); ...
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; }
java