idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
12,200
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 { Stri...
Add a column family
190
4
12,201
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 ,...
Update existing keyspace identified by name
187
7
12,202
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 mod...
Update existing column family identified by name
274
7
12,203
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...
Used to update keyspace definition attributes
513
7
12,204
private void executeDelKeySpace ( Tree statement ) throws TException , InvalidRequestException , NotFoundException , SchemaDisagreementException { if ( ! CliMain . isConnected ( ) ) return ; String keyspaceName = CliCompiler . getKeySpace ( statement , thriftClient . describe_keyspaces ( ) ) ; String version = thriftCl...
Delete a keyspace
130
4
12,205
private void executeDelColumnFamily ( Tree statement ) throws TException , InvalidRequestException , NotFoundException , SchemaDisagreementException { if ( ! CliMain . isConnected ( ) || ! hasKeySpace ( ) ) return ; String cfName = CliCompiler . getColumnFamily ( statement , currentCfDefs ( ) ) ; String mySchemaVersion...
Delete a column family
111
4
12,206
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 :...
Writes the supplied ColumnDef to the StringBuilder as a cli script .
525
16
12,207
private boolean hasKeySpace ( boolean printError ) { boolean hasKeyspace = keySpace != null ; if ( ! hasKeyspace && printError ) sessionState . err . println ( "Not authorized to a working keyspace." ) ; return hasKeyspace ; }
Returns true if this . keySpace is set false otherwise
55
11
12,208
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 ( ind...
Getting IndexType object from indexType string
156
8
12,209
private ByteBuffer subColumnNameAsBytes ( String superColumn , String columnFamily ) { CfDef columnFamilyDef = getCfDef ( columnFamily ) ; return subColumnNameAsBytes ( superColumn , columnFamilyDef ) ; }
Converts sub - column name into ByteBuffer according to comparator type
49
14
12,210
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 ...
Converts column name into ByteBuffer according to comparator type
117
12
12,211
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 , c...
Get validator for specific column value
145
7
12,212
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 , Functi...
Get AbstractType by function name
106
6
12,213
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 ( validationC...
Used to locally update column family definition with new column metadata
164
11
12,214
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 ; }
Get specific ColumnDef in column family meta data by column name
83
12
12,215
private String formatSubcolumnName ( String keyspace , String columnFamily , ByteBuffer name ) { return getFormatType ( getCfDef ( keyspace , columnFamily ) . subcomparator_type ) . getString ( name ) ; }
returns sub - column name in human - readable format
52
11
12,216
private String formatColumnName ( String keyspace , String columnFamily , ByteBuffer name ) { return getFormatType ( getCfDef ( keyspace , columnFamily ) . comparator_type ) . getString ( name ) ; }
retuns column name in human - readable format
49
9
12,217
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 . r...
Print elapsed time . Print 2 fraction digits if eta is under 10 ms .
121
16
12,218
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 ( ) ) ...
IOException otherwise .
104
4
12,219
@ 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 ) ; } } ...
Index the given row .
130
5
12,220
@ 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 ) ; ...
cleans up deleted columns from cassandra cleanup compaction
113
11
12,221
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 ( parall...
Send merkle tree request to every involved neighbor .
336
11
12,222
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 = ...
Add a new received tree and return the number of remaining tree to be received for the job to be complete .
108
22
12,223
public String getString ( ByteBuffer bytes ) { TypeSerializer < T > serializer = getSerializer ( ) ; serializer . validate ( bytes ) ; return serializer . toString ( serializer . deserialize ( bytes ) ) ; }
get a string representation of the bytes suitable for log messages
52
11
12,224
public boolean isValueCompatibleWith ( AbstractType < ? > otherType ) { return isValueCompatibleWithInternal ( ( otherType instanceof ReversedType ) ? ( ( ReversedType ) otherType ) . baseType : 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 .
55
47
12,225
public int compareCollectionMembers ( ByteBuffer v1 , ByteBuffer v2 , ByteBuffer collectionName ) { return compare ( v1 , v2 ) ; }
An alternative comparison function used by CollectionsType in conjunction with CompositeType .
33
14
12,226
private static void writeKey ( PrintStream out , String value ) { writeJSON ( out , value ) ; out . print ( ": " ) ; }
JSON Hash Key serializer
32
5
12,227
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 ) { s...
Serialize a given cell to a List of Objects that jsonMapper knows how to turn into strings . Format is
297
23
12,228
private static void serializeRow ( SSTableIdentityIterator row , DecoratedKey key , PrintStream out ) { serializeRow ( row . getColumnFamily ( ) . deletionInfo ( ) , row , row . getColumnFamily ( ) . metadata ( ) , key , out ) ; }
Get portion of the columns and serialize in loop while not more columns left in the row
63
18
12,229
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 ( lastK...
Enumerate row keys from an SSTableReader and write the result to a PrintStream .
171
20
12,230
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 . ...
Export specific rows from an SSTable and write the resulting JSON to a PrintStream .
413
18
12,231
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 ; ISSTableSc...
than once from within the same process .
258
8
12,232
public static void export ( Descriptor desc , PrintStream outs , String [ ] excludes , CFMetaData metadata ) throws IOException { export ( SSTableReader . open ( desc ) , outs , excludes , metadata ) ; }
Export an SSTable and write the resulting JSON to a PrintStream .
48
15
12,233
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 .
38
14
12,234
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 ) ; } ...
Given arguments specifying an SSTable and optionally an output file export the contents of the SSTable to JSON .
681
23
12,235
public SemanticVersion findSupportingVersion ( SemanticVersion ... versions ) { for ( SemanticVersion version : versions ) { if ( isSupportedBy ( version ) ) return version ; } return null ; }
Returns a version that is backward compatible with this version amongst a list of provided version or null if none can be found .
43
24
12,236
private Pair < List < SSTableReader > , Multimap < DataTracker , SSTableReader > > getCompactingAndNonCompactingSSTables ( ) { List < SSTableReader > allCompacting = new ArrayList <> ( ) ; Multimap < DataTracker , SSTableReader > allNonCompacting = HashMultimap . create ( ) ; for ( Keyspace ks : Keyspace . all ( ) ) { ...
Returns a Pair of all compacting and non - compacting sstables . Non - compacting sstables will be marked as compacting .
286
30
12,237
@ 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 . ge...
Attempts to fairly distribute a fixed pool of memory for index summaries across a set of SSTables based on their recent read rates .
722
27
12,238
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...
Returns the typed value serialized to a ByteBuffer .
156
11
12,239
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...
try to assign ourselves an executor with work available
155
10
12,240
private void startSpinning ( ) { assert get ( ) == Work . WORKING ; pool . spinningCount . incrementAndGet ( ) ; set ( Work . SPINNING ) ; }
collection at the same time
39
5
12,241
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 ( ) ; sl...
perform a sleep - spin incrementing pool . stopCheck accordingly
290
13
12,242
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 - stopC...
realtime we have spun too much and deschedule ; if we get too far behind realtime we reset to our initial offset
258
26
12,243
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 .
32
25
12,244
public boolean isIndexBuilt ( ByteBuffer columnName ) { return SystemKeyspace . isIndexBuilt ( baseCfs . keyspace . getName ( ) , getNameForSystemKeyspace ( columnName ) ) ; }
Checks if the index for specified column is fully built
46
11
12,245
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 ) . ref...
Builds the index using the data in the underlying CFS Blocks till it s complete
204
17
12,246
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 ( ) , getNameForSystemKeyspac...
Builds the index using the data in the underlying CF non blocking
248
13
12,247
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 ) ; }
Returns the decoratedKey for a column value
80
8
12,248
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 ...
This is the primary way to create a secondary index instance for a CF column . It will validate the index_options before initializing .
225
27
12,249
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 ; ...
Returns the index comparator for index backed by CFS or null .
96
14
12,250
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 ,...
Requests repairs for the given keyspace and column families .
134
12
12,251
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 ) ; ...
Return all of the neighbors with whom we share the provided range .
677
13
12,252
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 . rema...
is resolved in a release used by Cassandra .
174
9
12,253
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...
A convenience method to initialize and start the daemon in one shot .
278
13
12,254
protected static String toInternalName ( String name , boolean keepCase ) { return keepCase ? name : name . toLowerCase ( Locale . US ) ; }
Converts the specified name into the name used internally .
34
11
12,255
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 (...
regardless of its future position in the list from other modifications
222
12
12,256
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 ow...
remove the provided node and its associated value from the list
332
11
12,257
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 == ...
retrieve the item at the provided index or return null if the index is past the end of the list
124
21
12,258
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 ) != nod...
don t create a separate unit test - tools tree doesn t currently warrant them
201
15
12,259
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 ==...
Harmony s Collections implementation
128
6
12,260
public void reloadClasses ( ) { File triggerDirectory = FBUtilities . cassandraTriggerDir ( ) ; if ( triggerDirectory == null ) return ; customClassLoader = new CustomClassLoader ( parent , triggerDirectory ) ; cachedTriggers . clear ( ) ; }
Reload the triggers which is already loaded Invoking this will update the class loader so new jars can be loaded .
57
23
12,261
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 ( ) . set...
Switch class loader before using the triggers for the column family if not loaded them with the custom class loader .
256
21
12,262
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 Portu...
Returns the default stopwords set used by Lucene language analyzer for the specified language .
371
18
12,263
public static void setInputColumns ( Configuration conf , String columns ) { if ( columns == null || columns . isEmpty ( ) ) return ; conf . set ( INPUT_CQL_COLUMNS_CONFIG , columns ) ; }
Set the CQL columns for the input of this job .
51
12
12,264
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 ) ; }
Set the CQL query Limit for the input of this job .
83
13
12,265
public static void setInputWhereClauses ( Configuration conf , String clauses ) { if ( clauses == null || clauses . isEmpty ( ) ) return ; conf . set ( INPUT_CQL_WHERE_CLAUSE_CONFIG , clauses ) ; }
Set the CQL user defined where clauses for the input of this job .
53
15
12,266
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 .
48
13
12,267
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 ; } }
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 .
81
28
12,268
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 = ...
Attempts to login the given user .
83
7
12,269
@ 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 ...
Exclude unknown mix of configuration .
286
7
12,270
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 ...
Pull docker image on this docker host .
382
8
12,271
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 ( ) . getAbsolutePa...
Build docker image containing specified plugins .
597
7
12,272
public String runFreshJenkinsContainer ( DockerImagePullStrategy pullStrategy , boolean forceRefresh ) throws IOException , SettingsBuildingException , InterruptedException { LOG . debug ( "Entering run fresh jenkins container." ) ; pullImage ( pullStrategy , JENKINS_DEFAULT . getDockerImageName ( ) ) ; // labels attac...
Run record and remove after test container with jenkins .
601
12
12,273
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...
Dockerfile as String based on sratch for placing plugins .
226
13
12,274
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 Docker...
Create DockerCLI connection against specified jnlpSlaveAgent port
327
14
12,275
@ 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 ( idle...
While x - stream serialisation buggy copy implementation .
189
10
12,276
public static boolean isSomethingHappening ( Jenkins jenkins ) { if ( ! jenkins . getQueue ( ) . isEmpty ( ) ) return true ; for ( Computer n : jenkins . getComputers ( ) ) if ( ! n . isIdle ( ) ) return true ; return false ; }
Returns true if Hudson is building something or going to build something .
68
13
12,277
public static void waitUntilNoActivityUpTo ( Jenkins jenkins , int timeout ) throws Exception { long startTime = System . currentTimeMillis ( ) ; int streak = 0 ; while ( true ) { Thread . sleep ( 10 ) ; if ( isSomethingHappening ( jenkins ) ) { streak = 0 ; } else { streak ++ ; } if ( streak > 5 ) { // the system is q...
Waits until Hudson finishes building everything including those in the queue or fail the test if the specified timeout milliseconds is
304
22
12,278
public boolean waitUp ( String cloudId , DockerSlaveTemplate dockerSlaveTemplate , InspectContainerResponse containerInspect ) { if ( isFalse ( containerInspect . getState ( ) . getRunning ( ) ) ) { throw new IllegalStateException ( "Container '" + containerInspect . getId ( ) + "' is not running!" ) ; } return true ; ...
Wait until slave is up and ready for connection .
79
10
12,279
public ClientBuilderForConnector forConnector ( DockerConnector connector ) throws UnrecoverableKeyException , NoSuchAlgorithmException , KeyStoreException , KeyManagementException { LOG . debug ( "Building connection to docker host '{}'" , connector . getServerUrl ( ) ) ; withCredentialsId ( connector . getCredentials...
Provides ready to use docker client with information from docker connector
137
12
12,280
public ClientBuilderForConnector withCredentialsId ( String credentialsId ) throws UnrecoverableKeyException , NoSuchAlgorithmException , KeyStoreException , KeyManagementException { if ( isNotBlank ( credentialsId ) ) { withCredentials ( lookupSystemCredentials ( credentialsId ) ) ; } else { withSslConfig ( null ) ; }...
Sets SSLConfig from defined credentials id .
81
9
12,281
public static Credentials lookupSystemCredentials ( String credentialsId ) { return firstOrNull ( lookupCredentials ( Credentials . class , Jenkins . getInstance ( ) , ACL . SYSTEM , emptyList ( ) ) , withId ( credentialsId ) ) ; }
Util method to find credential by id in jenkins
58
12
12,282
@ Nonnull public List < DockerSlaveTemplate > getTemplates ( Label label ) { List < DockerSlaveTemplate > dockerSlaveTemplates = new ArrayList <> ( ) ; for ( DockerSlaveTemplate t : templates ) { if ( isNull ( label ) && t . getMode ( ) == Node . Mode . NORMAL ) { dockerSlaveTemplates . add ( t ) ; } if ( nonNull ( lab...
Multiple templates may have the same label .
129
8
12,283
public void setTemplates ( List < DockerSlaveTemplate > replaceTemplates ) { if ( replaceTemplates != null ) { templates = new ArrayList <> ( replaceTemplates ) ; } else { templates = Collections . emptyList ( ) ; } }
Set list of available templates
54
5
12,284
protected void decrementAmiSlaveProvision ( DockerSlaveTemplate container ) { synchronized ( provisionedImages ) { int currentProvisioning = 0 ; if ( provisionedImages . containsKey ( container ) ) { currentProvisioning = provisionedImages . get ( container ) ; } provisionedImages . put ( container , Math . max ( curre...
Decrease the count of slaves being provisioned .
86
10
12,285
public void execInternal ( @ Nonnull final DockerClient client , @ Nonnull final String imageName , TaskListener listener ) throws IOException { PrintStream llog = listener . getLogger ( ) ; if ( shouldPullImage ( client , imageName ) ) { LOG . info ( "Pulling image '{}'. This may take awhile..." , imageName ) ; llog ....
Action around image with defined configuration
570
6
12,286
public void resolveCreds ( ) { final AuthConfigurations authConfigs = new AuthConfigurations ( ) ; for ( Map . Entry < String , String > entry : creds . entrySet ( ) ) { final String registry = entry . getKey ( ) ; final String credId = entry . getValue ( ) ; final Credentials credentials = ClientBuilderForConnector . ...
Fill additional object with resolved creds . For example before transfering object to remote .
262
17
12,287
protected List < DockerCloud > getAvailableDockerClouds ( Label label ) { return getAllDockerClouds ( ) . stream ( ) . filter ( cloud -> cloud . canProvision ( label ) && ( countCurrentDockerSlaves ( cloud ) >= 0 ) && ( countCurrentDockerSlaves ( cloud ) < cloud . getContainerCap ( ) ) ) . collect ( Collectors . toList...
Get a list of available DockerCloud clouds which are not at max capacity .
91
15
12,288
public static AppEngineDescriptor parse ( InputStream in ) throws IOException , SAXException { Preconditions . checkNotNull ( in , "Null input" ) ; try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory . newInstance ( ) ; documentBuilderFactory . setNamespaceAware ( true ) ; return new AppEngineD...
Parses an appengine - web . xml file .
125
12
12,289
public String getRuntime ( ) throws AppEngineException { String runtime = getText ( getNode ( document , "appengine-web-app" , "runtime" ) ) ; if ( runtime == null ) { runtime = "java7" ; // the default runtime when not specified. } return runtime ; }
Returns runtime from the &lt ; runtime&gt ; element of the appengine - web . xml or the default one when it is missing .
64
29
12,290
@ Nullable public String getServiceId ( ) throws AppEngineException { String serviceId = getText ( getNode ( document , "appengine-web-app" , "service" ) ) ; if ( serviceId != null ) { return serviceId ; } return getText ( getNode ( document , "appengine-web-app" , "module" ) ) ; }
Returns service ID from the &lt ; service&gt ; element of the appengine - web . xml or null if it is missing . Will also look at module ID .
80
35
12,291
private static Map < String , String > getAttributeMap ( Node parent , String nodeName , String keyAttributeName , String valueAttributeName ) throws AppEngineException { Map < String , String > nameValueAttributeMap = new HashMap <> ( ) ; if ( parent . hasChildNodes ( ) ) { for ( int i = 0 ; i < parent . getChildNodes...
Returns a map formed from the attributes of the nodes contained within the parent node .
263
16
12,292
@ Nullable private static Node getNode ( Document doc , String parentNodeName , String targetNodeName ) { NodeList parentElements = doc . getElementsByTagNameNS ( APP_ENGINE_NAMESPACE , parentNodeName ) ; if ( parentElements . getLength ( ) > 0 ) { Node parent = parentElements . item ( 0 ) ; if ( parent . hasChildNodes...
Returns the first node found matching the given name contained within the parent node .
165
15
12,293
public void login ( ) throws AppEngineException { try { runner . run ( ImmutableList . of ( "auth" , "login" ) , null ) ; } catch ( ProcessHandlerException | IOException ex ) { throw new AppEngineException ( ex ) ; } }
Launches the gcloud auth login flow .
57
9
12,294
public void activateServiceAccount ( Path jsonFile ) throws AppEngineException { Preconditions . checkArgument ( Files . exists ( jsonFile ) , "File does not exist: " + jsonFile ) ; try { List < String > args = new ArrayList <> ( 3 ) ; args . add ( "auth" ) ; args . add ( "activate-service-account" ) ; args . addAll ( ...
Activates a service account based on a configured json key file .
136
13
12,295
@ Override public int compareTo ( CloudSdkVersion other ) { Preconditions . checkNotNull ( other ) ; if ( "HEAD" . equals ( version ) && ! "HEAD" . equals ( other . version ) ) { return 1 ; } else if ( ! "HEAD" . equals ( version ) && "HEAD" . equals ( other . version ) ) { return - 1 ; } // First, compare required fie...
Compares this to another CloudSdkVersion per the Semantic Versioning 2 . 0 . 0 specification .
299
22
12,296
public void deploy ( DeployConfiguration config ) throws AppEngineException { Preconditions . checkNotNull ( config ) ; Preconditions . checkNotNull ( config . getDeployables ( ) ) ; Preconditions . checkArgument ( config . getDeployables ( ) . size ( ) > 0 ) ; Path workingDirectory = null ; List < String > arguments =...
Deploys a project to App Engine .
521
8
12,297
@ Override public int compareTo ( CloudSdkVersionPreRelease other ) { Preconditions . checkNotNull ( other ) ; // Compare segments from left to right. A smaller number of pre-release segments comes before a // higher number, if all preceding segments are equal. int index = 0 ; while ( index < this . segments . size ( )...
Compares this to another CloudSdkVersionPreRelease .
192
12
12,298
public static boolean contains ( String className ) { if ( className . startsWith ( "javax." ) ) { return ! isBundledInJre ( className ) || WHITELIST . contains ( className ) ; } else if ( className . startsWith ( "java." ) || className . startsWith ( "sun.util." ) || className . startsWith ( "org.xml.sax." ) || classN...
Determine whether class is allowed in App Engine Standard .
446
12
12,299
private static boolean isBundledInJre ( String className ) { if ( className . startsWith ( "javax.accessibility." ) || className . startsWith ( "javax.activation." ) || className . startsWith ( "javax.activity." ) || className . startsWith ( "javax.annotation." ) || className . startsWith ( "javax.crypto." ) || classNa...
javax packages are tricky . Some are in the JRE . Some aren t .
352
18