idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
8,100
public Range convertToSeq2Range ( Range rangeInSeq1 ) { int from = aabs ( convertToSeq2Position ( rangeInSeq1 . getFrom ( ) ) ) ; int to = aabs ( convertToSeq2Position ( rangeInSeq1 . getTo ( ) ) ) ; if ( from == - 1 || to == - 1 ) return null ; return new Range ( from , to ) ; }
Converts range in sequence1 to range in sequence2 or returns null if input range is not fully covered by alignment
8,101
public Alignment < S > invert ( S sequence2 ) { return new Alignment < > ( sequence2 , getRelativeMutations ( ) . invert ( ) . move ( sequence2Range . getFrom ( ) ) , sequence2Range , sequence1Range , score ) ; }
Having sequence2 creates alignment from sequence2 to sequence1
8,102
public float similarity ( ) { int match = 0 , mismatch = 0 ; AlignmentIteratorForward < S > iterator = forwardIterator ( ) ; while ( iterator . advance ( ) ) { final int mut = iterator . getCurrentMutation ( ) ; if ( mut == NON_MUTATION ) ++ match ; else ++ mismatch ; } return 1.0f * match / ( match + mismatch ) ; }
Returns number of matches divided by sum of number of matches and mismatches .
8,103
public Long peekDelta ( String name , long count ) { Long previous = lookup . get ( name ) ; return calculateDelta ( name , previous , count ) ; }
Gets the delta without updating the internal data store
8,104
public Long getDelta ( String name , long count ) { Long previous = lookup . put ( name , count ) ; return calculateDelta ( name , previous , count ) ; }
Calculates the delta . If this is a new value that has not been seen before zero will be assumed to be the initial value . Updates the internal map with the supplied count .
8,105
public static Range extendRange ( SequenceQuality quality , QualityTrimmerParameters parameters , Range initialRange ) { int lower = pabs ( trim ( quality , 0 , initialRange . getLower ( ) , - 1 , false , parameters ) ) ; int upper = pabs ( trim ( quality , initialRange . getUpper ( ) , quality . size ( ) , + 1 , false , parameters ) ) + 1 ; return new Range ( lower , upper , initialRange . isReverse ( ) ) ; }
Extend initialRange to the biggest possible range that fulfils the criteria of QualityTrimmer along the whole extended region .
8,106
public static Range trim ( SequenceQuality quality , QualityTrimmerParameters parameters ) { return trim ( quality , parameters , new Range ( 0 , quality . size ( ) ) ) ; }
Trims the quality string by cutting off low quality nucleotides on both edges .
8,107
public static Range trim ( SequenceQuality quality , QualityTrimmerParameters parameters , Range initialRange ) { int lower = pabs ( trim ( quality , initialRange . getLower ( ) , initialRange . getUpper ( ) , + 1 , true , parameters ) ) + 1 ; assert lower >= initialRange . getLower ( ) ; if ( lower == initialRange . getUpper ( ) ) return null ; int upper = pabs ( trim ( quality , lower , initialRange . getUpper ( ) , - 1 , true , parameters ) ) ; if ( upper == lower ) return null ; return new Range ( lower , upper , initialRange . isReverse ( ) ) ; }
Trims the initialRange by cutting off low quality nucleotides on both edges .
8,108
public static AminoAcidSequence translate ( NucleotideSequence sequence ) { if ( sequence . size ( ) % 3 != 0 ) throw new IllegalArgumentException ( "Only nucleotide sequences with size multiple " + "of three are supported (in-frame)." ) ; byte [ ] aaData = new byte [ sequence . size ( ) / 3 ] ; GeneticCode . translate ( aaData , 0 , sequence , 0 , sequence . size ( ) ) ; return new AminoAcidSequence ( aaData , true ) ; }
Translates sequence having length divisible by 3 starting from first nucleotide .
8,109
public void validate ( ) { for ( String in : getInputFiles ( ) ) { if ( ! new File ( in ) . exists ( ) ) throwValidationException ( "ERROR: input file \"" + in + "\" does not exist." , false ) ; validateInfo ( in ) ; } }
Validate injected parameters and options
8,110
public static < T > Serializer < T > dummySerializer ( ) { return new Serializer < T > ( ) { public void write ( PrimitivO output , T object ) { throw new RuntimeException ( "Dummy serializer." ) ; } public T read ( PrimitivI input ) { throw new RuntimeException ( "Dummy serializer." ) ; } public boolean isReference ( ) { return true ; } public boolean handlesReference ( ) { return false ; } } ; }
Serializer that throws exception for any serialization . Use for known objects .
8,111
public static AffineGapAlignmentScoring < NucleotideSequence > getNucleotideBLASTScoring ( int gapOpenPenalty , int gapExtensionPenalty ) { return new AffineGapAlignmentScoring < > ( NucleotideSequence . ALPHABET , 5 , - 4 , gapOpenPenalty , gapExtensionPenalty ) ; }
Returns Nucleotide BLAST scoring
8,112
public static AffineGapAlignmentScoring < AminoAcidSequence > getAminoAcidBLASTScoring ( BLASTMatrix matrix , int gapOpenPenalty , int gapExtensionPenalty ) { return new AffineGapAlignmentScoring < > ( AminoAcidSequence . ALPHABET , matrix . getMatrix ( ) , gapOpenPenalty , gapExtensionPenalty ) ; }
Returns AminoAcid BLAST scoring
8,113
public static boolean belongsToAlphabet ( Alphabet < ? > alphabet , String string ) { for ( int i = 0 ; i < string . length ( ) ; ++ i ) if ( alphabet . symbolToCode ( string . charAt ( i ) ) == - 1 ) return false ; return true ; }
Check if a sequence contains letters only from specified alphabet . So in can be converted to corresponding type of sequence .
8,114
public static Set < Alphabet < ? > > possibleAlphabets ( String string ) { HashSet < Alphabet < ? > > alphabets = new HashSet < > ( ) ; for ( Alphabet alphabet : Alphabets . getAll ( ) ) { if ( belongsToAlphabet ( alphabet , string ) ) alphabets . add ( alphabet ) ; } return alphabets ; }
Returns a set of possible alphabets for a given string .
8,115
public static < S extends Seq < S > > S concatenate ( S ... sequences ) { if ( sequences . length == 0 ) throw new IllegalArgumentException ( "Zero arguments" ) ; if ( sequences . length == 1 ) return sequences [ 0 ] ; int size = 0 ; for ( S s : sequences ) size += s . size ( ) ; SeqBuilder < S > builder = sequences [ 0 ] . getBuilder ( ) . ensureCapacity ( size ) ; for ( S s : sequences ) builder . append ( s ) ; return builder . createAndDestroy ( ) ; }
Returns a concatenation of several sequences .
8,116
public static Bit2Array convertNSequenceToBit2Array ( NucleotideSequence seq ) { if ( seq . containWildcards ( ) ) throw new IllegalArgumentException ( "Sequences with wildcards are not supported." ) ; Bit2Array bar = new Bit2Array ( seq . size ( ) ) ; for ( int i = 0 ; i < seq . size ( ) ; i ++ ) bar . set ( i , seq . codeAt ( i ) ) ; return bar ; }
Used to write legacy file formats .
8,117
public static NucleotideSequence convertBit2ArrayToNSequence ( Bit2Array bar ) { SequenceBuilder < NucleotideSequence > seq = NucleotideSequence . ALPHABET . createBuilder ( ) . ensureCapacity ( bar . size ( ) ) ; for ( int i = 0 ; i < bar . size ( ) ; i ++ ) seq . append ( ( byte ) bar . get ( i ) ) ; return seq . createAndDestroy ( ) ; }
Used to read legacy file formats .
8,118
public FileIndexBuilder setStartingRecordNumber ( long recordNumber ) { checkIfDestroyed ( ) ; if ( index . size ( ) != 1 ) throw new IllegalStateException ( "Initial record is already initialised to " + index . get ( 0 ) ) ; startingRecordNumber = recordNumber ; return this ; }
Sets the starting record number to a specified one .
8,119
public FileIndexBuilder putMetadata ( String key , String value ) { checkIfDestroyed ( ) ; metadata . put ( key , value ) ; return this ; }
Puts metadata .
8,120
public FileIndexBuilder appendNextRecord ( long recordSize ) { checkIfDestroyed ( ) ; if ( recordSize < 0 ) throw new IllegalArgumentException ( "Size cannot be negative." ) ; if ( currentRecord == step ) { index . add ( startingByte + currentByte ) ; currentRecord = 0 ; } currentByte += recordSize ; ++ currentRecord ; return this ; }
Appends next record to this index builder and returns this .
8,121
public static int computeRawVarint64Size ( final long value ) { if ( ( value & ( 0xffffffffffffffffL << 7 ) ) == 0 ) return 1 ; if ( ( value & ( 0xffffffffffffffffL << 14 ) ) == 0 ) return 2 ; if ( ( value & ( 0xffffffffffffffffL << 21 ) ) == 0 ) return 3 ; if ( ( value & ( 0xffffffffffffffffL << 28 ) ) == 0 ) return 4 ; if ( ( value & ( 0xffffffffffffffffL << 35 ) ) == 0 ) return 5 ; if ( ( value & ( 0xffffffffffffffffL << 42 ) ) == 0 ) return 6 ; if ( ( value & ( 0xffffffffffffffffL << 49 ) ) == 0 ) return 7 ; if ( ( value & ( 0xffffffffffffffffL << 56 ) ) == 0 ) return 8 ; if ( ( value & ( 0xffffffffffffffffL << 63 ) ) == 0 ) return 9 ; return 10 ; }
Compute the number of bytes that would be needed to encode a varint .
8,122
public boolean checkModified ( LightFileDescriptor other ) { if ( isAlwaysModified ( ) || other . isAlwaysModified ( ) ) return true ; if ( ! name . equals ( other . name ) ) return true ; if ( ! ( hasChecksum ( ) && other . hasChecksum ( ) ) && ! ( hasModificationDate ( ) && other . hasModificationDate ( ) ) ) return true ; if ( hasChecksum ( ) && other . hasChecksum ( ) && ! Arrays . equals ( checksum , other . checksum ) ) return true ; if ( hasModificationDate ( ) && other . hasModificationDate ( ) && ! lastModified . equals ( other . lastModified ) ) return true ; return false ; }
Returns true if file modified
8,123
public String toBase64 ( ) { return name + ( checksum == null ? "null" : Base64 . getDecoder ( ) . decode ( checksum ) ) + ( lastModified == null ? "null" : lastModified ) ; }
A string representation of this .
8,124
public byte minValue ( ) { if ( data . length == 0 ) return 0 ; byte min = Byte . MAX_VALUE ; for ( byte b : data ) if ( b < min ) min = b ; return min ; }
Returns the worst sequence quality value
8,125
public byte meanValue ( ) { if ( data . length == 0 ) return 0 ; int sum = 0 ; for ( byte b : data ) sum += b ; return ( byte ) ( sum / data . length ) ; }
Returns average sequence quality value
8,126
public SequenceQuality getRange ( Range range ) { byte [ ] rdata = Arrays . copyOfRange ( data , range . getLower ( ) , range . getUpper ( ) ) ; if ( range . isReverse ( ) ) ArraysUtils . reverse ( rdata ) ; return new SequenceQuality ( rdata , true ) ; }
Returns substring of current quality scores line .
8,127
public void encodeTo ( QualityFormat format , byte [ ] buffer , int offset ) { byte vo = format . getOffset ( ) ; for ( int i = 0 ; i < data . length ; ++ i ) buffer [ offset ++ ] = ( byte ) ( data [ i ] + vo ) ; }
Encodes current quality line with given offset . Common values for offset are 33 and 64 .
8,128
public static SequenceQuality getUniformQuality ( byte qualityValue , int length ) { byte [ ] data = new byte [ length ] ; Arrays . fill ( data , qualityValue ) ; return new SequenceQuality ( data , true ) ; }
Creates a phred sequence quality containing only given values of quality .
8,129
public static Alignment < NucleotideSequence > alignLeftAdded ( LinearGapAlignmentScoring scoring , NucleotideSequence seq1 , NucleotideSequence seq2 , int offset1 , int length1 , int addedNucleotides1 , int offset2 , int length2 , int addedNucleotides2 , int width ) { try { MutationsBuilder < NucleotideSequence > mutations = new MutationsBuilder < > ( NucleotideSequence . ALPHABET ) ; BandedSemiLocalResult result = alignLeftAdded0 ( scoring , seq1 , seq2 , offset1 , length1 , addedNucleotides1 , offset2 , length2 , addedNucleotides2 , width , mutations , AlignmentCache . get ( ) ) ; return new Alignment < > ( seq1 , mutations . createAndDestroy ( ) , new Range ( result . sequence1Stop , offset1 + length1 ) , new Range ( result . sequence2Stop , offset2 + length2 ) , result . score ) ; } finally { AlignmentCache . release ( ) ; } }
Semi - semi - global alignment with artificially added letters .
8,130
public int addReference ( NucleotideSequence sequence ) { if ( sequence . containWildcards ( ) ) throw new IllegalArgumentException ( "Reference sequences with wildcards not supported." ) ; int id = mapper . addReference ( sequence ) ; assert sequences . size ( ) == id ; sequences . add ( sequence ) ; return id ; }
Adds new reference sequence to the base of this mapper and returns index assigned to it .
8,131
public Motif < S > or ( Motif < S > other ) { if ( other . size != size ) throw new IllegalArgumentException ( "Supports only motifs with the same size as this." ) ; BitArray result = data . clone ( ) ; result . or ( other . data ) ; return new Motif < > ( alphabet , size , result ) ; }
Returns per - position or of two motifs .
8,132
public static Alignment < NucleotideSequence > alignGlobal ( final AlignmentScoring < NucleotideSequence > scoring , final NucleotideSequence seq1 , final NucleotideSequence seq2 , final int offset1 , final int length1 , final int offset2 , final int length2 , final int width ) { if ( scoring instanceof AffineGapAlignmentScoring ) return BandedAffineAligner . align ( ( AffineGapAlignmentScoring < NucleotideSequence > ) scoring , seq1 , seq2 , offset1 , length1 , offset2 , length2 , width ) ; else return BandedLinearAligner . align ( ( LinearGapAlignmentScoring < NucleotideSequence > ) scoring , seq1 , seq2 , offset1 , length1 , offset2 , length2 , width ) ; }
Classical Banded Alignment .
8,133
public static < S extends Sequence < S > > Alignment < S > alignGlobal ( AlignmentScoring < S > alignmentScoring , S seq1 , S seq2 ) { if ( alignmentScoring instanceof AffineGapAlignmentScoring ) return alignGlobalAffine ( ( AffineGapAlignmentScoring < S > ) alignmentScoring , seq1 , seq2 ) ; if ( alignmentScoring instanceof LinearGapAlignmentScoring ) return alignGlobalLinear ( ( LinearGapAlignmentScoring < S > ) alignmentScoring , seq1 , seq2 ) ; throw new RuntimeException ( "Unknown scoring type." ) ; }
Performs global alignment
8,134
public static < S extends Sequence < S > > Alignment < S > alignLocal ( AlignmentScoring < S > alignmentScoring , S seq1 , S seq2 ) { if ( alignmentScoring instanceof AffineGapAlignmentScoring ) return alignLocalAffine ( ( AffineGapAlignmentScoring < S > ) alignmentScoring , seq1 , seq2 ) ; if ( alignmentScoring instanceof LinearGapAlignmentScoring ) return alignLocalLinear ( ( LinearGapAlignmentScoring < S > ) alignmentScoring , seq1 , seq2 ) ; throw new RuntimeException ( "Unknown scoring type." ) ; }
Performs local alignment
8,135
public void processAllChildren ( TObjectProcedure < Cluster < T > > procedure ) { if ( children == null ) return ; for ( Cluster < T > child : children ) { procedure . execute ( child ) ; child . processAllChildren ( procedure ) ; } }
do not process this cluster
8,136
public S getEmptySequence ( ) { if ( empty == null ) synchronized ( this ) { if ( empty == null ) empty = createBuilder ( ) . createAndDestroy ( ) ; } return empty ; }
Returns empty sequence singleton
8,137
public final S parse ( String string ) { SequenceBuilder < S > builder = createBuilder ( ) . ensureCapacity ( string . length ( ) ) ; for ( int i = 0 ; i < string . length ( ) ; ++ i ) { byte code = symbolToCode ( string . charAt ( i ) ) ; if ( code == - 1 ) throw new IllegalArgumentException ( "Letter \'" + string . charAt ( i ) + "\' is not defined in \'" + toString ( ) + "\'." ) ; builder . append ( code ) ; } return builder . createAndDestroy ( ) ; }
Parses string representation of sequence .
8,138
public boolean compatibleWith ( PipelineConfiguration oth ) { if ( oth == null ) return false ; if ( pipelineSteps . length != oth . pipelineSteps . length ) return false ; for ( int i = 0 ; i < pipelineSteps . length ; ++ i ) if ( ! pipelineSteps [ i ] . compatibleWith ( oth . pipelineSteps [ i ] ) ) return false ; return true ; }
Whether configurations are fully compatible
8,139
public static PipelineConfiguration appendStep ( PipelineConfiguration history , List < String > inputFiles , ActionConfiguration configuration , AppVersionInfo versionInfo ) { LightFileDescriptor [ ] inputDescriptors = inputFiles . stream ( ) . map ( f -> LightFileDescriptor . calculate ( Paths . get ( f ) ) ) . toArray ( LightFileDescriptor [ ] :: new ) ; return new PipelineConfiguration ( Stream . concat ( Stream . of ( history . pipelineSteps ) , Stream . of ( new PipelineStep ( versionInfo , inputDescriptors , configuration ) ) ) . toArray ( PipelineStep [ ] :: new ) ) ; }
Appends a new pipeline step
8,140
public static PipelineConfiguration mkInitial ( List < String > inputFiles , ActionConfiguration configuration , AppVersionInfo versionInfo ) { LightFileDescriptor [ ] inputDescriptors = inputFiles . stream ( ) . map ( f -> LightFileDescriptor . calculate ( Paths . get ( f ) ) ) . toArray ( LightFileDescriptor [ ] :: new ) ; return new PipelineConfiguration ( new PipelineStep [ ] { new PipelineStep ( versionInfo , inputDescriptors , configuration ) } ) ; }
Creates initial history
8,141
public static < S extends Sequence < S > > Alignment < S > shiftIndelsAtHomopolymers ( Alignment < S > alignment ) { return new Alignment < > ( alignment . sequence1 , MutationsUtil . shiftIndelsAtHomopolymers ( alignment . sequence1 , alignment . sequence1Range . getFrom ( ) , alignment . mutations ) , alignment . sequence1Range , alignment . sequence2Range , alignment . score ) ; }
Shifts indels to the left at homopolymer regions
8,142
public static int [ ] btopDecode ( String alignment , Alphabet alphabet ) { Matcher matcher = btopPattern . matcher ( alignment ) ; IntArrayList mutations = new IntArrayList ( ) ; int sPosition = 0 ; while ( matcher . find ( ) ) { String g = matcher . group ( ) ; if ( isPositiveInteger ( g ) ) sPosition += Integer . parseInt ( g ) ; else if ( g . charAt ( 0 ) == '-' ) { mutations . add ( createDeletion ( sPosition , alphabet . symbolToCodeWithException ( g . charAt ( 1 ) ) ) ) ; ++ sPosition ; } else if ( g . charAt ( 1 ) == '-' ) mutations . add ( createInsertion ( sPosition , alphabet . symbolToCodeWithException ( g . charAt ( 0 ) ) ) ) ; else { mutations . add ( createSubstitution ( sPosition , alphabet . symbolToCodeWithException ( g . charAt ( 1 ) ) , alphabet . symbolToCodeWithException ( g . charAt ( 0 ) ) ) ) ; ++ sPosition ; } } return mutations . toArray ( ) ; }
Decodes btop - encoded mutations .
8,143
public static MutationNt2AADescriptor [ ] nt2aaDetailed ( NucleotideSequence seq1 , Mutations < NucleotideSequence > mutations , TranslationParameters translationParameters , int maxShiftedTriplets ) { MutationsWitMapping mutationsWitMapping = nt2aaWithMapping ( seq1 , mutations , translationParameters , maxShiftedTriplets ) ; int [ ] individualMutations = nt2IndividualAA ( seq1 , mutations , translationParameters ) ; MutationNt2AADescriptor [ ] result = new MutationNt2AADescriptor [ mutations . size ( ) ] ; for ( int i = 0 ; i < mutations . size ( ) ; i ++ ) { result [ i ] = new MutationNt2AADescriptor ( mutations . getMutation ( i ) , individualMutations [ i ] , mutationsWitMapping . mapping [ i ] == - 1 ? NON_MUTATION : mutationsWitMapping . mutations . getMutation ( mutationsWitMapping . mapping [ i ] ) ) ; } return result ; }
Performs a comprehensive translation of mutations present in a nucleotide sequence to effective mutations in corresponding amino acid sequence .
8,144
public int convertPointToRelativePosition ( int absolutePosition ) { if ( absolutePosition < lower || absolutePosition >= upper ) throw new IllegalArgumentException ( "Position outside this range (" + absolutePosition + ")." ) ; if ( reversed ) return upper - 1 - absolutePosition ; else return absolutePosition - lower ; }
Returns relative point position inside this range .
8,145
public int convertBoundaryToRelativePosition ( int absolutePosition ) { if ( absolutePosition < lower || absolutePosition > upper ) throw new IllegalArgumentException ( "Position outside this range (" + absolutePosition + ") this=" + this + "." ) ; if ( reversed ) return upper - absolutePosition ; else return absolutePosition - lower ; }
Returns relative boundary position inside this range .
8,146
@ SuppressWarnings ( "unchecked" ) public List < Range > without ( Range range ) { if ( ! intersectsWith ( range ) ) return Collections . singletonList ( this ) ; if ( upper <= range . upper ) return range . lower <= lower ? Collections . EMPTY_LIST : Collections . singletonList ( new Range ( lower , range . lower , reversed ) ) ; if ( range . lower <= lower ) return Collections . singletonList ( new Range ( range . upper , upper , reversed ) ) ; return Arrays . asList ( new Range ( lower , range . lower , reversed ) , new Range ( range . upper , upper , reversed ) ) ; }
Subtract provided range and return list of ranges contained in current range and not intersecting with other range .
8,147
public int convertPointToAbsolutePosition ( int relativePosition ) { if ( relativePosition < 0 || relativePosition >= length ( ) ) throw new IllegalArgumentException ( "Relative position outside this range (" + relativePosition + ")." ) ; if ( reversed ) return upper - 1 - relativePosition ; else return relativePosition + lower ; }
Converts relative point position to absolute position
8,148
public int convertBoundaryToAbsolutePosition ( int relativePosition ) { if ( relativePosition < 0 || relativePosition > length ( ) ) throw new IllegalArgumentException ( "Relative position outside this range (" + relativePosition + ")." ) ; if ( reversed ) return upper - relativePosition ; else return relativePosition + lower ; }
Converts relative boundary position to absolute position
8,149
public final void write ( byte [ ] data ) { if ( sendBinary ) { int prev = 0 ; for ( int i = 0 ; i < data . length ; i ++ ) { if ( data [ i ] == - 1 ) { rawWrite ( data , prev , i - prev ) ; send ( new byte [ ] { - 1 , - 1 } ) ; prev = i + 1 ; } } rawWrite ( data , prev , data . length - prev ) ; } else { for ( int i = 0 ; i < data . length ; i ++ ) { data [ i ] = ( byte ) ( data [ i ] & 0x7F ) ; } send ( data ) ; } }
Write data to the client escaping data if necessary or truncating it . The original buffer can be mutated if incorrect data is provided .
8,150
private void readFile ( ) { if ( historyFile . exists ( ) ) { try ( BufferedReader reader = new BufferedReader ( new FileReader ( historyFile ) ) ) { String line ; while ( ( line = reader . readLine ( ) ) != null ) push ( Parser . toCodePoints ( line ) ) ; } catch ( FileNotFoundException ignored ) { } catch ( IOException e ) { if ( logging ) LOGGER . log ( Level . WARNING , "Failed to read from history file, " , e ) ; } } }
Read specified history file to history buffer
8,151
private void writeFile ( ) throws IOException { historyFile . delete ( ) ; try ( FileWriter fw = new FileWriter ( historyFile ) ) { for ( int i = 0 ; i < size ( ) ; i ++ ) fw . write ( Parser . fromCodePoints ( get ( i ) ) + ( Config . getLineSeparator ( ) ) ) ; } if ( historyFilePermission != null ) { historyFile . setReadable ( false , false ) ; historyFile . setReadable ( historyFilePermission . isReadable ( ) , historyFilePermission . isReadableOwnerOnly ( ) ) ; historyFile . setWritable ( false , false ) ; historyFile . setWritable ( historyFilePermission . isWritable ( ) , historyFilePermission . isWritableOwnerOnly ( ) ) ; historyFile . setExecutable ( false , false ) ; historyFile . setExecutable ( historyFilePermission . isExecutable ( ) , historyFilePermission . isExecutableOwnerOnly ( ) ) ; } }
Write the content of the history buffer to file
8,152
private static boolean setVTMode ( ) { long console = GetStdHandle ( STD_OUTPUT_HANDLE ) ; int [ ] mode = new int [ 1 ] ; if ( Kernel32 . GetConsoleMode ( console , mode ) == 0 ) { return false ; } if ( Kernel32 . SetConsoleMode ( console , mode [ 0 ] | VIRTUAL_TERMINAL_PROCESSING ) == 0 ) { return false ; } return true ; }
This allows to take benefit from Windows 10 + new features .
8,153
public static String formatDisplayCompactListTerminalString ( List < TerminalString > displayList , int termWidth ) { if ( displayList == null || displayList . size ( ) < 1 ) return "" ; if ( termWidth < 1 ) termWidth = 80 ; int numRows = 1 ; while ( ! canDisplayColumns ( displayList , numRows , termWidth ) && numRows < displayList . size ( ) ) { numRows ++ ; } int numColumns = displayList . size ( ) / numRows ; if ( displayList . size ( ) % numRows > 0 ) { numColumns ++ ; } int [ ] columnsSizes = calculateColumnSizes ( displayList , numColumns , numRows , termWidth ) ; StringBuilder stringOutput = new StringBuilder ( ) ; for ( int i = 0 ; i < numRows ; i ++ ) { for ( int c = 0 ; c < numColumns ; c ++ ) { int fetch = i + ( c * numRows ) ; int nextFetch = i + ( ( c + 1 ) * numRows ) ; if ( fetch < displayList . size ( ) ) { if ( nextFetch < displayList . size ( ) ) { stringOutput . append ( padRight ( columnsSizes [ c ] + displayList . get ( i + ( c * numRows ) ) . getANSILength ( ) , displayList . get ( i + ( c * numRows ) ) . toString ( ) ) ) ; } else { stringOutput . append ( displayList . get ( i + ( c * numRows ) ) . toString ( ) ) ; } } else { break ; } } stringOutput . append ( Config . getLineSeparator ( ) ) ; } return stringOutput . toString ( ) ; }
Format output to columns with flexible sizes and no redundant space between them
8,154
private static boolean canDisplayColumns ( List < TerminalString > displayList , int numRows , int terminalWidth ) { int numColumns = displayList . size ( ) / numRows ; if ( displayList . size ( ) % numRows > 0 ) { numColumns ++ ; } int [ ] columnSizes = calculateColumnSizes ( displayList , numColumns , numRows , terminalWidth ) ; int totalSize = 0 ; for ( int columnSize : columnSizes ) { totalSize += columnSize ; } return totalSize <= terminalWidth ; }
Decides if it s possible to format provided Strings into calculated number of columns while the output will not exceed terminal width
8,155
public static String trimOptionName ( String word ) { if ( word . startsWith ( "--" ) ) return word . substring ( 2 ) ; else if ( word . startsWith ( "-" ) ) return word . substring ( 1 ) ; else return word ; }
remove leading dashes from word
8,156
public static String findStartsWithOperation ( List < ? extends CompleteOperation > coList ) { List < String > tmpList = new ArrayList < > ( ) ; for ( CompleteOperation co : coList ) { String s = findStartsWith ( co . getFormattedCompletionCandidates ( ) ) ; if ( s . length ( ) > 0 ) tmpList . add ( s ) ; else return "" ; } return findStartsWith ( tmpList ) ; }
If there is any common start string in the completion list return it
8,157
public static String findCurrentWordFromCursor ( String text , int cursor ) { if ( text . length ( ) <= cursor + 1 ) { if ( text . contains ( SPACE ) ) { if ( doWordContainEscapedSpace ( text ) ) { if ( doWordContainOnlyEscapedSpace ( text ) ) return switchEscapedSpacesToSpacesInWord ( text ) ; else { return switchEscapedSpacesToSpacesInWord ( findEscapedSpaceWordCloseToEnd ( text ) ) ; } } else { if ( text . lastIndexOf ( SPACE ) >= cursor ) return text . substring ( text . substring ( 0 , cursor ) . lastIndexOf ( SPACE ) ) . trim ( ) ; else return text . substring ( text . lastIndexOf ( SPACE ) ) . trim ( ) ; } } else return text . trim ( ) ; } else { String rest ; if ( text . length ( ) > cursor + 1 ) rest = text . substring ( 0 , cursor + 1 ) ; else rest = text ; if ( doWordContainOnlyEscapedSpace ( rest ) ) { if ( cursor > 1 && text . charAt ( cursor ) == SPACE_CHAR && text . charAt ( cursor - 1 ) == SPACE_CHAR ) return "" ; else return switchEscapedSpacesToSpacesInWord ( rest ) ; } else { if ( cursor > 1 && text . charAt ( cursor ) == SPACE_CHAR && text . charAt ( cursor - 1 ) == SPACE_CHAR ) return "" ; if ( rest . trim ( ) . contains ( SPACE ) ) return rest . substring ( rest . trim ( ) . lastIndexOf ( " " ) ) . trim ( ) ; else return rest . trim ( ) ; } } }
Return the word connected to cursor the word ends at cursor position . Note that cursor position starts at 0
8,158
public static String findEscapedSpaceWordCloseToEnd ( String text ) { int index ; String originalText = text ; while ( ( index = text . lastIndexOf ( SPACE ) ) > - 1 ) { if ( index > 0 && text . charAt ( index - 1 ) == BACK_SLASH ) { text = text . substring ( 0 , index - 1 ) ; } else return originalText . substring ( index + 1 ) ; } return originalText ; }
Search backwards for a non - escaped space and only return work containing non - escaped space
8,159
public static boolean doesStringContainOpenQuote ( String text ) { boolean doubleQuote = false ; boolean singleQuote = false ; boolean escapedByBackSlash = false ; if ( commentPattern . matcher ( text ) . find ( ) ) return false ; for ( int i = 0 ; i < text . length ( ) ; i ++ ) { if ( text . charAt ( i ) == BACK_SLASH || escapedByBackSlash ) { escapedByBackSlash = ! escapedByBackSlash ; continue ; } if ( text . charAt ( i ) == SINGLE_QUOTE ) { if ( ! doubleQuote ) singleQuote = ! singleQuote ; } else if ( text . charAt ( i ) == DOUBLE_QUOTE ) { if ( ! singleQuote ) doubleQuote = ! doubleQuote ; } } return doubleQuote || singleQuote ; }
Check if a string contain openBlocking quotes . Escaped quotes does not count .
8,160
public static int findNumberOfSpacesInWord ( String word ) { int count = 0 ; for ( int i = 0 ; i < word . length ( ) ; i ++ ) if ( word . charAt ( i ) == SPACE_CHAR && ( i == 0 || word . charAt ( i - 1 ) != BACK_SLASH ) ) count ++ ; return count ; }
find number of spaces in the given word . escaped spaces are not counted
8,161
public static String trimInFront ( String buffer ) { int count = 0 ; for ( int i = 0 ; i < buffer . length ( ) ; i ++ ) { if ( buffer . charAt ( i ) == SPACE_CHAR ) count ++ ; else break ; } if ( count > 0 ) return buffer . substring ( count ) ; else return buffer ; }
Only trim space in front of the word
8,162
public static int [ ] mapQuoteKeys ( String keys ) { if ( keys != null && keys . length ( ) > 1 ) return mapKeys ( keys . substring ( 1 ) ) ; else return null ; }
Parse key mapping lines that start with
8,163
public static int [ ] printAnsi ( char ... out ) { int [ ] ansi = new int [ out . length + 2 ] ; ansi [ 0 ] = 27 ; ansi [ 1 ] = '[' ; int counter = 0 ; for ( char anOut : out ) { if ( anOut == '\t' ) { Arrays . fill ( ansi , counter + 2 , counter + 2 + TAB , ' ' ) ; counter += TAB - 1 ; } else ansi [ counter + 2 ] = anOut ; counter ++ ; } return ansi ; }
Return a ansified string based on param
8,164
@ SuppressWarnings ( "unchecked" ) public static < T extends Annotation > T createAnnotation ( final Class < T > clazz ) { return ( T ) Proxy . newProxyInstance ( clazz . getClassLoader ( ) , new Class [ ] { clazz , Annotation . class } , new SimpleAnnoInvocationHandler ( clazz ) ) ; }
Create an annotation instance from annotation class .
8,165
static int hashMember ( String name , Object value ) { int part1 = name . hashCode ( ) * 127 ; if ( value . getClass ( ) . isArray ( ) ) { return part1 ^ arrayMemberHash ( value . getClass ( ) . getComponentType ( ) , value ) ; } if ( value instanceof Annotation ) { return part1 ^ hashCode ( ( Annotation ) value ) ; } return part1 ^ value . hashCode ( ) ; }
Helper method for generating a hash code for a member of an annotation .
8,166
private BeanSpec beanSpecOf ( Field field , Type genericType ) { return of ( field , genericType , injector ) ; }
find the beanspec of a field with generic type
8,167
private void storeTagAnnotation ( Annotation anno ) { Class < ? extends Annotation > annoType = anno . annotationType ( ) ; Annotation [ ] tags = annoType . getAnnotations ( ) ; for ( Annotation tag : tags ) { Class < ? extends Annotation > tagType = tag . annotationType ( ) ; if ( WAIVE_TAG_TYPES . contains ( tagType ) ) { continue ; } Set < Annotation > tagged = tagAnnotations . get ( tagType ) ; if ( null == tagged ) { tagged = new HashSet < > ( ) ; tagAnnotations . put ( tagType , tagged ) ; } tagged . add ( anno ) ; } }
Walk through anno s tag annotations
8,168
public OpenStackRequest < R > queryString ( String queryString ) { if ( queryString != null ) { String [ ] params = queryString . split ( "&" ) ; for ( String param : params ) { String [ ] s = param . split ( "=" ) ; if ( s [ 0 ] != null && s [ 1 ] != null ) { queryParam ( s [ 0 ] , s [ 1 ] ) ; } } } return this ; }
This method will parse the query string which is a collection of name value pairs and put then in queryParam hash map
8,169
public EvacuateAction evacuate ( String serverId , String host ) { return evacuate ( serverId , host , null , null ) ; }
Evacuates the server to a new host . The caller can supply the host name or id .
8,170
private SSLContext getSSLContext ( ) throws NoSuchAlgorithmException , KeyManagementException { SSLContext sslContext = SSLContext . getInstance ( "SSL" ) ; sslContext . init ( null , new TrustManager [ ] { new X509TrustManager ( ) { public void checkClientTrusted ( X509Certificate [ ] certs , String authType ) { } public void checkServerTrusted ( X509Certificate [ ] certs , String authType ) { } public java . security . cert . X509Certificate [ ] getAcceptedIssuers ( ) { return null ; } } } , new java . security . SecureRandom ( ) ) ; return sslContext ; }
This SSLContext is used only when the protocol is HTTPS AND a trusted hosts list has been provided . In that case this SSLContext accepts all certificates whether they are expired or not and regardless of the CA that issued them .
8,171
public RetentionStrategy getRetentionStrategyCopy ( ) { if ( retentionStrategy instanceof DockerOnceRetentionStrategy ) { DockerOnceRetentionStrategy onceRetention = ( DockerOnceRetentionStrategy ) retentionStrategy ; return new DockerOnceRetentionStrategy ( onceRetention . getIdleMinutes ( ) ) ; } return retentionStrategy ; }
tmp fix for terminating boolean caching
8,172
@ SuppressWarnings ( "unused" ) public Object readResolve ( ) { if ( configVersion < 1 ) { if ( isNull ( nodeProperties ) ) nodeProperties = new ArrayList < > ( ) ; nodeProperties . add ( new DockerNodeProperty ( "DOCKER_CONTAINER_ID" , "JENKINS_CLOUD_ID" , "DOCKER_HOST" ) ) ; configVersion = 1 ; } if ( mode == null ) { mode = Node . Mode . NORMAL ; } if ( retentionStrategy == null ) { retentionStrategy = new DockerOnceRetentionStrategy ( 10 ) ; } try { labelSet = Label . parse ( getLabelString ( ) ) ; } catch ( Throwable t ) { LOG . error ( "Can't parse labels: {}" , t ) ; } return this ; }
Initializes data structure that we don t persist .
8,173
public DockerComputerLauncher getPreparedLauncher ( String cloudId , DockerSlaveTemplate template , InspectContainerResponse containerInspectResponse ) { final DockerComputerJNLPLauncher cloneJNLPlauncher = new DockerComputerJNLPLauncher ( ) ; cloneJNLPlauncher . setLaunchTimeout ( getLaunchTimeout ( ) ) ; cloneJNLPlauncher . setUser ( getUser ( ) ) ; cloneJNLPlauncher . setJvmOpts ( getJvmOpts ( ) ) ; cloneJNLPlauncher . setSlaveOpts ( getSlaveOpts ( ) ) ; cloneJNLPlauncher . setJenkinsUrl ( getJenkinsUrl ( ) ) ; cloneJNLPlauncher . setNoCertificateCheck ( isNoCertificateCheck ( ) ) ; cloneJNLPlauncher . setNoReconnect ( isNoReconnect ( ) ) ; return cloneJNLPlauncher ; }
Clone object .
8,174
public String runContainer ( DockerSlaveTemplate slaveTemplate ) throws DockerException , IOException { final DockerCreateContainer dockerCreateContainer = slaveTemplate . getDockerContainerLifecycle ( ) . getCreateContainer ( ) ; final String image = slaveTemplate . getDockerContainerLifecycle ( ) . getImage ( ) ; CreateContainerCmd containerConfig = getClient ( ) . createContainerCmd ( image ) ; dockerCreateContainer . fillContainerConfig ( containerConfig , null ) ; slaveTemplate . getLauncher ( ) . appendContainerConfig ( slaveTemplate , containerConfig ) ; appendContainerConfig ( slaveTemplate , containerConfig ) ; CreateContainerResponse response = containerConfig . exec ( ) ; String containerId = response . getId ( ) ; LOG . debug ( "Created container {}, for {}" , containerId , getDisplayName ( ) ) ; slaveTemplate . getLauncher ( ) . afterContainerCreate ( getClient ( ) , containerId ) ; StartContainerCmd startCommand = getClient ( ) . startContainerCmd ( containerId ) ; try { startCommand . exec ( ) ; LOG . debug ( "Running container {}, for {}" , containerId , getDisplayName ( ) ) ; } catch ( Exception ex ) { try { getClient ( ) . logContainerCmd ( containerId ) . withStdErr ( true ) . withStdOut ( true ) . exec ( new MyLogContainerResultCallback ( ) ) . awaitCompletion ( ) ; } catch ( Throwable t ) { LOG . warn ( "Can't get logs for container start" , t ) ; } throw ex ; } return containerId ; }
Run docker container for given template
8,175
private void appendContainerConfig ( DockerSlaveTemplate slaveTemplate , CreateContainerCmd containerConfig ) { Map < String , String > labels = containerConfig . getLabels ( ) ; if ( labels == null ) labels = new HashMap < > ( ) ; labels . put ( DOCKER_CLOUD_LABEL , getDisplayName ( ) ) ; labels . put ( DOCKER_TEMPLATE_LABEL , slaveTemplate . getId ( ) ) ; containerConfig . withLabels ( labels ) ; }
Cloud specific container config options
8,176
private OsType determineOsType ( String imageId ) { InspectImageResponse ir = getClient ( ) . inspectImageCmd ( imageId ) . exec ( ) ; if ( "linux" . equalsIgnoreCase ( ir . getOs ( ) ) ) { LOG . trace ( "Detected LINUX operating system for image: {}" , imageId ) ; return OsType . LINUX ; } else if ( "windows" . equalsIgnoreCase ( ir . getOs ( ) ) ) { LOG . trace ( "Detected WINDOWS operating system for image: {}" , imageId ) ; return OsType . WINDOWS ; } else { LOG . trace ( "Detected OTHER operating system ({}) for image: {}" , ir . getOs ( ) , imageId ) ; return OsType . OTHER ; } }
Determine the operating system associated with an image .
8,177
public int countCurrentDockerSlaves ( final DockerSlaveTemplate template ) throws Exception { int count = 0 ; List < Container > containers = getClient ( ) . listContainersCmd ( ) . exec ( ) ; for ( Container container : containers ) { final Map < String , String > labels = container . getLabels ( ) ; if ( labels . containsKey ( DOCKER_CLOUD_LABEL ) && labels . get ( DOCKER_CLOUD_LABEL ) . equals ( getDisplayName ( ) ) ) { if ( template == null ) { count ++ ; } else if ( labels . containsKey ( DOCKER_TEMPLATE_LABEL ) && labels . get ( DOCKER_TEMPLATE_LABEL ) . equals ( template . getId ( ) ) ) { count ++ ; } } } return count ; }
Counts the number of instances in Docker currently running that are using the specified template .
8,178
private synchronized boolean addProvisionedSlave ( DockerSlaveTemplate template ) throws Exception { final DockerContainerLifecycle dockerCreateContainer = template . getDockerContainerLifecycle ( ) ; String dockerImageName = dockerCreateContainer . getImage ( ) ; int templateCapacity = template . getMaxCapacity ( ) ; int estimatedTotalSlaves = countCurrentDockerSlaves ( null ) ; int estimatedAmiSlaves = countCurrentDockerSlaves ( template ) ; synchronized ( provisionedImages ) { int currentProvisioning = 0 ; if ( provisionedImages . containsKey ( template ) ) { currentProvisioning = provisionedImages . get ( template ) ; } for ( int amiCount : provisionedImages . values ( ) ) { estimatedTotalSlaves += amiCount ; } estimatedAmiSlaves += currentProvisioning ; if ( estimatedTotalSlaves >= getContainerCap ( ) ) { LOG . info ( "Not Provisioning '{}'; Server '{}' full with '{}' container(s)" , dockerImageName , name , getContainerCap ( ) ) ; return false ; } if ( templateCapacity != 0 && estimatedAmiSlaves >= templateCapacity ) { LOG . info ( "Not Provisioning '{}'. Instance limit of '{}' reached on server '{}'" , dockerImageName , templateCapacity , name ) ; return false ; } LOG . info ( "Provisioning '{}' number '{}' on '{}'; Total containers: '{}'" , dockerImageName , estimatedAmiSlaves , name , estimatedTotalSlaves ) ; provisionedImages . put ( template , currentProvisioning + 1 ) ; return true ; } }
Check not too many already running .
8,179
public static List < Descriptor < ComputerLauncher > > getDockerComputerLauncherDescriptors ( ) { List < Descriptor < ComputerLauncher > > launchers = new ArrayList < > ( ) ; launchers . add ( getInstance ( ) . getDescriptor ( DockerComputerSSHLauncher . class ) ) ; launchers . add ( getInstance ( ) . getDescriptor ( DockerComputerJNLPLauncher . class ) ) ; launchers . add ( getInstance ( ) . getDescriptor ( DockerComputerIOLauncher . class ) ) ; return launchers ; }
Only this plugin specific launchers .
8,180
public static List < Descriptor < RetentionStrategy < ? > > > getDockerRetentionStrategyDescriptors ( ) { List < Descriptor < RetentionStrategy < ? > > > strategies = new ArrayList < > ( ) ; strategies . add ( getInstance ( ) . getDescriptor ( DockerOnceRetentionStrategy . class ) ) ; strategies . add ( getInstance ( ) . getDescriptor ( DockerCloudRetentionStrategy . class ) ) ; strategies . add ( getInstance ( ) . getDescriptor ( DockerComputerIOLauncher . class ) ) ; return strategies ; }
Only this plugin specific strategies .
8,181
public static List < DockerCloud > getAllDockerClouds ( ) { return getInstance ( ) . clouds . stream ( ) . filter ( Objects :: nonNull ) . filter ( DockerCloud . class :: isInstance ) . map ( cloud -> ( DockerCloud ) cloud ) . collect ( Collectors . toList ( ) ) ; }
Get the list of Docker servers .
8,182
public RestartPolicy getRestartPolicy ( ) { if ( isNull ( policyName ) ) return null ; return RestartPolicy . parse ( String . format ( "%s:%d" , policyName . toString ( ) . toLowerCase ( Locale . ENGLISH ) . replace ( "_" , "-" ) , getMaximumRetryCount ( ) ) ) ; }
runtime ABI dependency on docker - java
8,183
public static String resolveVar ( String var , Run run , TaskListener taskListener ) { String resolvedVar = var ; try { final EnvVars envVars = run . getEnvironment ( taskListener ) ; resolvedVar = envVars . expand ( var ) ; } catch ( IOException | InterruptedException e ) { LOG . warn ( "Can't resolve variable " + var + " for {}" , run , e ) ; } return resolvedVar ; }
Resolve on remoting side during execution . Because node may have some specific node vars .
8,184
protected CliPort getCliTcpPort ( String jenkinsAddr ) throws IOException { URL jenkinsUrl = new URL ( jenkinsAddr ) ; if ( jenkinsUrl . getHost ( ) == null || jenkinsUrl . getHost ( ) . length ( ) == 0 ) { throw new IOException ( "Invalid URL: " + jenkinsAddr ) ; } URLConnection head = jenkinsUrl . openConnection ( ) ; try { head . connect ( ) ; } catch ( IOException e ) { throw ( IOException ) new IOException ( "Failed to connect to " + jenkinsAddr ) . initCause ( e ) ; } String h = head . getHeaderField ( "X-Jenkins-CLI-Host" ) ; if ( h == null ) h = head . getURL ( ) . getHost ( ) ; String identity = head . getHeaderField ( "X-Instance-Identity" ) ; flushURLConnection ( head ) ; return new CliPort ( new InetSocketAddress ( h , exposedPort ) , identity , 2 ) ; }
If the server advertises CLI endpoint returns its location .
8,185
public void close ( ) throws IOException , InterruptedException { channel . close ( ) ; channel . join ( ) ; if ( ownsPool ) pool . shutdown ( ) ; for ( Closeable c : closables ) c . close ( ) ; }
Shuts down the channel and closes the underlying connection .
8,186
public void upgrade ( ) { ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; if ( execute ( Arrays . asList ( "groovy" , "=" ) , new ByteArrayInputStream ( "hudson.remoting.Channel.current().setRestricted(false)" . getBytes ( defaultCharset ( ) ) ) , out , out ) != 0 ) { throw new SecurityException ( out . toString ( ) ) ; } }
Attempts to lift the security restriction on the underlying channel . This requires the administer privilege on the server .
8,187
protected static EnvVars getEnvVars ( Run run , TaskListener listener ) throws IOException , InterruptedException { final EnvVars envVars = run . getCharacteristicEnvVars ( ) ; for ( EnvironmentContributor ec : EnvironmentContributor . all ( ) . reverseView ( ) ) { ec . buildEnvironmentFor ( run . getParent ( ) , envVars , listener ) ; if ( ec instanceof CoreEnvironmentContributor ) { envVars . put ( "BUILD_DISPLAY_NAME" , run . getDisplayName ( ) ) ; String rootUrl = Jenkins . getInstance ( ) . getRootUrl ( ) ; if ( rootUrl != null ) { envVars . put ( "BUILD_URL" , rootUrl + run . getUrl ( ) ) ; } envVars . remove ( "JENKINS_HOME" ) ; envVars . remove ( "HUDSON_HOME" ) ; } else { ec . buildEnvironmentFor ( run , envVars , listener ) ; } } return envVars ; }
Return all job related vars without executor vars . I . e . slave is running in osx but docker image for shell is linux .
8,188
protected static void insertLabels ( CreateContainerCmd containerConfig , Run run ) { Map < String , String > labels = containerConfig . getLabels ( ) ; if ( labels == null ) labels = new HashMap < > ( ) ; labels . put ( "YAD_PLUGIN" , DockerShellStep . class . getName ( ) ) ; labels . put ( "JENKINS_JOB_BASE_NAME" , run . getParent ( ) . getName ( ) ) ; labels . put ( "JENKINS_INSTANCE_IDENTITY" , new String ( encodeBase64 ( InstanceIdentity . get ( ) . getPublic ( ) . getEncoded ( ) ) , UTF_8 ) ) ; containerConfig . withLabels ( labels ) ; }
Append some tags to identify who created this container .
8,189
public void setEnabled ( boolean enabled ) { final ExtensionList < NodeProvisioner . Strategy > strategies = lookup ( NodeProvisioner . Strategy . class ) ; DockerProvisioningStrategy strategy = strategies . get ( DockerProvisioningStrategy . class ) ; if ( isNull ( strategy ) ) { LOG . debug ( "YAD strategy was null, creating new." ) ; strategy = new DockerProvisioningStrategy ( ) ; } else { LOG . debug ( "Removing YAD strategy." ) ; strategies . remove ( strategy ) ; } LOG . debug ( "Inserting YAD strategy at position 0" ) ; strategies . add ( 0 , strategy ) ; }
For groovy .
8,190
public static < T extends RingPosition < T > > boolean isWrapAround ( T left , T right ) { return left . compareTo ( right ) >= 0 ; }
Tells if the given range is a wrap around .
8,191
private ArrayList < Range < T > > subtractContained ( Range < T > contained ) { ArrayList < Range < T > > difference = new ArrayList < Range < T > > ( 2 ) ; if ( ! left . equals ( contained . left ) ) difference . add ( new Range < T > ( left , contained . left , partitioner ) ) ; if ( ! right . equals ( contained . right ) ) difference . add ( new Range < T > ( contained . right , right , partitioner ) ) ; return difference ; }
Subtracts a portion of this range .
8,192
private static < T extends RingPosition < T > > List < Range < T > > deoverlap ( List < Range < T > > ranges ) { if ( ranges . isEmpty ( ) ) return ranges ; List < Range < T > > output = new ArrayList < Range < T > > ( ) ; Iterator < Range < T > > iter = ranges . iterator ( ) ; Range < T > current = iter . next ( ) ; @ SuppressWarnings ( "unchecked" ) T min = ( T ) current . partitioner . minValue ( current . left . getClass ( ) ) ; while ( iter . hasNext ( ) ) { if ( current . right . equals ( min ) ) { if ( current . left . equals ( min ) ) return Collections . < Range < T > > singletonList ( current ) ; output . add ( new Range < T > ( current . left , min ) ) ; return output ; } Range < T > next = iter . next ( ) ; if ( next . left . compareTo ( current . right ) <= 0 ) { if ( next . right . equals ( min ) || current . right . compareTo ( next . right ) < 0 ) current = new Range < T > ( current . left , next . right ) ; } else { output . add ( current ) ; current = next ; } } output . add ( current ) ; return output ; }
Given a list of unwrapped ranges sorted by left position return an equivalent list of ranges but with no overlapping ranges .
8,193
public static Range < RowPosition > makeRowRange ( Token left , Token right , IPartitioner partitioner ) { return new Range < RowPosition > ( left . maxKeyBound ( partitioner ) , right . maxKeyBound ( partitioner ) , partitioner ) ; }
Compute a range of keys corresponding to a given range of token .
8,194
public final int compareTo ( final Composite that ) { if ( isStatic ( ) != that . isStatic ( ) ) { if ( isEmpty ( ) ) return that . isEmpty ( ) ? 0 : - 1 ; if ( that . isEmpty ( ) ) return 1 ; return isStatic ( ) ? - 1 : 1 ; } int size = size ( ) ; int size2 = that . size ( ) ; int minSize = Math . min ( size , size2 ) ; int startDelta = 0 ; int cellNamesOffset = nameDeltaOffset ( size ) ; for ( int i = 0 ; i < minSize ; i ++ ) { int endDelta = i < size - 1 ? getShort ( nameDeltaOffset ( i + 1 ) ) : valueStartOffset ( ) - cellNamesOffset ; long offset = peer + cellNamesOffset + startDelta ; int length = endDelta - startDelta ; int cmp = FastByteOperations . UnsafeOperations . compareTo ( null , offset , length , that . get ( i ) ) ; if ( cmp != 0 ) return cmp ; startDelta = endDelta ; } EOC eoc = that . eoc ( ) ; if ( size == size2 ) return this . eoc ( ) . compareTo ( eoc ) ; return size < size2 ? this . eoc ( ) . prefixComparisonResult : - eoc . prefixComparisonResult ; }
requires isByteOrderComparable to be true . Compares the name components only ; ; may need to compare EOC etc still
8,195
private ColumnFamily processModifications ( ColumnFamily changesCF ) { ColumnFamilyStore cfs = Keyspace . open ( getKeyspaceName ( ) ) . getColumnFamilyStore ( changesCF . id ( ) ) ; ColumnFamily resultCF = changesCF . cloneMeShallow ( ) ; List < CounterUpdateCell > counterUpdateCells = new ArrayList < > ( changesCF . getColumnCount ( ) ) ; for ( Cell cell : changesCF ) { if ( cell instanceof CounterUpdateCell ) counterUpdateCells . add ( ( CounterUpdateCell ) cell ) ; else resultCF . addColumn ( cell ) ; } if ( counterUpdateCells . isEmpty ( ) ) return resultCF ; ClockAndCount [ ] currentValues = getCurrentValues ( counterUpdateCells , cfs ) ; for ( int i = 0 ; i < counterUpdateCells . size ( ) ; i ++ ) { ClockAndCount currentValue = currentValues [ i ] ; CounterUpdateCell update = counterUpdateCells . get ( i ) ; long clock = currentValue . clock + 1L ; long count = currentValue . count + update . delta ( ) ; resultCF . addColumn ( new BufferCounterCell ( update . name ( ) , CounterContext . instance ( ) . createGlobal ( CounterId . getLocalId ( ) , clock , count ) , update . timestamp ( ) ) ) ; } return resultCF ; }
Replaces all the CounterUpdateCell - s with updated regular CounterCell - s
8,196
private int getCurrentValuesFromCache ( List < CounterUpdateCell > counterUpdateCells , ColumnFamilyStore cfs , ClockAndCount [ ] currentValues ) { int cacheMisses = 0 ; for ( int i = 0 ; i < counterUpdateCells . size ( ) ; i ++ ) { ClockAndCount cached = cfs . getCachedCounter ( key ( ) , counterUpdateCells . get ( i ) . name ( ) ) ; if ( cached != null ) currentValues [ i ] = cached ; else cacheMisses ++ ; } return cacheMisses ; }
Returns the count of cache misses .
8,197
private void getCurrentValuesFromCFS ( List < CounterUpdateCell > counterUpdateCells , ColumnFamilyStore cfs , ClockAndCount [ ] currentValues ) { SortedSet < CellName > names = new TreeSet < > ( cfs . metadata . comparator ) ; for ( int i = 0 ; i < currentValues . length ; i ++ ) if ( currentValues [ i ] == null ) names . add ( counterUpdateCells . get ( i ) . name ( ) ) ; ReadCommand cmd = new SliceByNamesReadCommand ( getKeyspaceName ( ) , key ( ) , cfs . metadata . cfName , Long . MIN_VALUE , new NamesQueryFilter ( names ) ) ; Row row = cmd . getRow ( cfs . keyspace ) ; ColumnFamily cf = row == null ? null : row . cf ; for ( int i = 0 ; i < currentValues . length ; i ++ ) { if ( currentValues [ i ] != null ) continue ; Cell cell = cf == null ? null : cf . getColumn ( counterUpdateCells . get ( i ) . name ( ) ) ; if ( cell == null || ! cell . isLive ( ) ) currentValues [ i ] = ClockAndCount . BLANK ; else currentValues [ i ] = CounterContext . instance ( ) . getLocalClockAndCount ( cell . value ( ) ) ; } }
Reads the missing current values from the CFS .
8,198
public static Function makeToBlobFunction ( AbstractType < ? > fromType ) { String name = fromType . asCQL3Type ( ) + "asblob" ; return new AbstractFunction ( name , BytesType . instance , fromType ) { public ByteBuffer execute ( List < ByteBuffer > parameters ) { return parameters . get ( 0 ) ; } } ; }
bytes internally . They only trick the type system .
8,199
public void run ( ) { outer : while ( run || ! queue . isEmpty ( ) ) { List < ByteBuffer > bindVariables ; try { bindVariables = queue . take ( ) ; } catch ( InterruptedException e ) { continue ; } Iterator < InetAddress > iter = endpoints . iterator ( ) ; while ( true ) { try { int i = 0 ; int itemId = preparedStatement ( client ) ; while ( bindVariables != null ) { client . execute_prepared_cql3_query ( itemId , bindVariables , ConsistencyLevel . ONE ) ; i ++ ; if ( i >= batchThreshold ) break ; bindVariables = queue . poll ( ) ; } break ; } catch ( Exception e ) { closeInternal ( ) ; if ( ! iter . hasNext ( ) ) { lastException = new IOException ( e ) ; break outer ; } } try { InetAddress address = iter . next ( ) ; String host = address . getHostName ( ) ; int port = ConfigHelper . getOutputRpcPort ( conf ) ; client = CqlOutputFormat . createAuthenticatedClient ( host , port , conf ) ; } catch ( Exception e ) { closeInternal ( ) ; if ( ( ! ( e instanceof TException ) ) || ! iter . hasNext ( ) ) { lastException = new IOException ( e ) ; break outer ; } } } } closeInternal ( ) ; }
Loops collecting cql binded variable values from the queue and sending to Cassandra