idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
21,900
public synchronized void setSelectedIndex ( final int selectedIndex ) { if ( items . size ( ) <= selectedIndex || selectedIndex < - 1 ) { throw new IndexOutOfBoundsException ( "Illegal argument to ComboBox.setSelectedIndex: " + selectedIndex ) ; } final int oldSelection = this . selectedIndex ; this . selectedIndex = selectedIndex ; if ( selectedIndex == - 1 ) { updateText ( "" ) ; } else { updateText ( items . get ( selectedIndex ) . toString ( ) ) ; } runOnGUIThreadIfExistsOtherwiseRunDirect ( new Runnable ( ) { public void run ( ) { for ( Listener listener : listeners ) { listener . onSelectionChanged ( selectedIndex , oldSelection ) ; } } } ) ; invalidate ( ) ; }
Programmatically selects one item in the combo box which causes the displayed text to change to match the label of the selected index .
21,901
public static String getANSIControlSequenceAt ( String string , int index ) { int len = getANSIControlSequenceLength ( string , index ) ; return len == 0 ? null : string . substring ( index , index + len ) ; }
Given a string and an index in that string returns the ANSI control sequence beginning on this index . If there is no control sequence starting there the method will return null . The returned value is the complete escape sequence including the ESC prefix .
21,902
public static int getANSIControlSequenceLength ( String string , int index ) { int len = 0 , restlen = string . length ( ) - index ; if ( restlen >= 3 ) { char esc = string . charAt ( index ) , bracket = string . charAt ( index + 1 ) ; if ( esc == 0x1B && bracket == '[' ) { len = 3 ; for ( int i = 2 ; i < restlen ; i ++ ) { char ch = string . charAt ( i + index ) ; if ( ( ch >= '0' && ch <= '9' ) || ch == ';' ) { len ++ ; } else { break ; } } if ( len > restlen ) { len = 0 ; } } } return len ; }
Given a string and an index in that string returns the number of characters starting at index that make up a complete ANSI control sequence . If there is no control sequence starting there the method will return 0 .
21,903
public static List < String > getWordWrappedText ( int maxWidth , String ... lines ) { if ( maxWidth <= 0 ) { return Arrays . asList ( lines ) ; } List < String > result = new ArrayList < String > ( ) ; LinkedList < String > linesToBeWrapped = new LinkedList < String > ( Arrays . asList ( lines ) ) ; while ( ! linesToBeWrapped . isEmpty ( ) ) { String row = linesToBeWrapped . removeFirst ( ) ; int rowWidth = getColumnWidth ( row ) ; if ( rowWidth <= maxWidth ) { result . add ( row ) ; } else { final int characterIndexMax = getStringCharacterIndex ( row , maxWidth ) ; int characterIndex = characterIndexMax ; while ( characterIndex >= 0 && ! Character . isSpaceChar ( row . charAt ( characterIndex ) ) && ! isCharCJK ( row . charAt ( characterIndex ) ) ) { characterIndex -- ; } if ( characterIndex >= 0 && characterIndex < characterIndexMax && isCharCJK ( row . charAt ( characterIndex ) ) ) { characterIndex ++ ; } if ( characterIndex < 0 ) { characterIndex = Math . max ( characterIndexMax , 1 ) ; result . add ( row . substring ( 0 , characterIndex ) ) ; linesToBeWrapped . addFirst ( row . substring ( characterIndex ) ) ; } else { characterIndex = Math . max ( characterIndex , 1 ) ; result . add ( row . substring ( 0 , characterIndex ) ) ; while ( characterIndex < row . length ( ) && Character . isSpaceChar ( row . charAt ( characterIndex ) ) ) { characterIndex ++ ; } if ( characterIndex < row . length ( ) ) { linesToBeWrapped . addFirst ( row . substring ( characterIndex ) ) ; } } } } return result ; }
This method will calculate word wrappings given a number of lines of text and how wide the text can be printed . The result is a list of new rows where word - wrapping was applied .
21,904
protected synchronized void onResized ( TerminalSize newSize ) { if ( lastKnownSize == null || ! lastKnownSize . equals ( newSize ) ) { lastKnownSize = newSize ; for ( TerminalResizeListener resizeListener : resizeListeners ) { resizeListener . onResized ( this , lastKnownSize ) ; } } }
Call this method when the terminal has been resized or the initial size of the terminal has been discovered . It will trigger all resize listeners but only if the size has changed from before .
21,905
public Color toAWTColor ( TextColor color , boolean isForeground , boolean inBoldContext ) { if ( color instanceof TextColor . ANSI ) { return colorPalette . get ( ( TextColor . ANSI ) color , isForeground , inBoldContext && useBrightColorsOnBold ) ; } return color . toColor ( ) ; }
Given a TextColor and a hint as to if the color is to be used as foreground or not and if we currently have bold text enabled or not it returns the closest AWT color that matches this .
21,906
private static int getFontSize ( ) { if ( Toolkit . getDefaultToolkit ( ) . getScreenResolution ( ) >= 110 ) { return Toolkit . getDefaultToolkit ( ) . getScreenResolution ( ) / 7 + 1 ; } else { GraphicsEnvironment ge = GraphicsEnvironment . getLocalGraphicsEnvironment ( ) ; if ( ge . getMaximumWindowBounds ( ) . getWidth ( ) > 4096 ) { return 56 ; } else if ( ge . getMaximumWindowBounds ( ) . getWidth ( ) > 2048 ) { return 28 ; } else { return 14 ; } } }
Here we check the screen resolution on the primary monitor and make a guess at if it s high - DPI or not
21,907
protected static Font [ ] selectDefaultFont ( ) { String osName = System . getProperty ( "os.name" , "" ) . toLowerCase ( ) ; if ( osName . contains ( "win" ) ) { List < Font > windowsFonts = getDefaultWindowsFonts ( ) ; return windowsFonts . toArray ( new Font [ windowsFonts . size ( ) ] ) ; } else if ( osName . contains ( "linux" ) ) { List < Font > linuxFonts = getDefaultLinuxFonts ( ) ; return linuxFonts . toArray ( new Font [ linuxFonts . size ( ) ] ) ; } else { List < Font > defaultFonts = getDefaultFonts ( ) ; return defaultFonts . toArray ( new Font [ defaultFonts . size ( ) ] ) ; } }
Returns the default font to use depending on the platform
21,908
public static Font [ ] filterMonospaced ( Font ... fonts ) { List < Font > result = new ArrayList < Font > ( fonts . length ) ; for ( Font font : fonts ) { if ( isFontMonospaced ( font ) ) { result . add ( font ) ; } } return result . toArray ( new Font [ result . size ( ) ] ) ; }
Given an array of fonts returns another array with only the ones that are monospaced . The fonts in the result will have the same order as in which they came in . A font is considered monospaced if the width of i and W is the same .
21,909
public TextInputDialogBuilder setValidationPattern ( final Pattern pattern , final String errorMessage ) { return setValidator ( new TextInputDialogResultValidator ( ) { public String validate ( String content ) { Matcher matcher = pattern . matcher ( content ) ; if ( ! matcher . matches ( ) ) { if ( errorMessage == null ) { return "Invalid input" ; } return errorMessage ; } return null ; } } ) ; }
Helper method that assigned a validator to the text box the dialog will have which matches the pattern supplied
21,910
protected String getBundleKeyValue ( Locale locale , String key , Object ... parameters ) { String value = null ; try { value = getBundle ( locale ) . getString ( key ) ; } catch ( Exception ignore ) { } return value != null ? MessageFormat . format ( value , parameters ) : null ; }
Method that centralizes the way to get the value associated to a bundle key .
21,911
public static AnimatedLabel createClassicSpinningLine ( int speed ) { AnimatedLabel animatedLabel = new AnimatedLabel ( "-" ) ; animatedLabel . addFrame ( "\\" ) ; animatedLabel . addFrame ( "|" ) ; animatedLabel . addFrame ( "/" ) ; animatedLabel . startAnimation ( speed ) ; return animatedLabel ; }
Creates a classic spinning bar which can be used to signal to the user that an operation in is process .
21,912
public synchronized AnimatedLabel addFrame ( String text ) { String [ ] lines = splitIntoMultipleLines ( text ) ; frames . add ( lines ) ; ensurePreferredSize ( lines ) ; return this ; }
Adds one more frame at the end of the list of frames
21,913
public synchronized void nextFrame ( ) { currentFrame ++ ; if ( currentFrame >= frames . size ( ) ) { currentFrame = 0 ; } super . setLines ( frames . get ( currentFrame ) ) ; invalidate ( ) ; }
Advances the animated label to the next frame . You normally don t need to call this manually as it will be done by the animation thread .
21,914
public void setMinimumSize ( TerminalSize minimumSize ) { this . minimumSize = minimumSize ; TerminalSize virtualSize = minimumSize . max ( realScreen . getTerminalSize ( ) ) ; if ( ! minimumSize . equals ( virtualSize ) ) { addResizeRequest ( virtualSize ) ; super . doResizeIfNecessary ( ) ; } calculateViewport ( realScreen . getTerminalSize ( ) ) ; }
Sets the minimum size we want the virtual screen to have . If the user resizes the real terminal to something smaller than this the virtual screen will refuse to make it smaller and add scrollbars to the view .
21,915
public TerminalSize withColumns ( int columns ) { if ( this . columns == columns ) { return this ; } if ( columns == 0 && this . rows == 0 ) { return ZERO ; } return new TerminalSize ( columns , this . rows ) ; }
Creates a new size based on this size but with a different width
21,916
public TerminalSize withRows ( int rows ) { if ( this . rows == rows ) { return this ; } if ( rows == 0 && this . columns == 0 ) { return ZERO ; } return new TerminalSize ( this . columns , rows ) ; }
Creates a new size based on this size but with a different height
21,917
public TerminalSize max ( TerminalSize other ) { return withColumns ( Math . max ( columns , other . columns ) ) . withRows ( Math . max ( rows , other . rows ) ) ; }
Takes a different TerminalSize and returns a new TerminalSize that has the largest dimensions of the two measured separately . So calling 3x5 on a 5x3 will return 5x5 .
21,918
public TerminalSize min ( TerminalSize other ) { return withColumns ( Math . min ( columns , other . columns ) ) . withRows ( Math . min ( rows , other . rows ) ) ; }
Takes a different TerminalSize and returns a new TerminalSize that has the smallest dimensions of the two measured separately . So calling 3x5 on a 5x3 will return 3x3 .
21,919
public synchronized Boolean isChecked ( V object ) { if ( object == null ) return null ; if ( indexOf ( object ) == - 1 ) return null ; return checkedIndex == indexOf ( object ) ; }
This method will see if an object is the currently selected item in this RadioCheckBoxList
21,920
private void moveCursorToNextLine ( ) { cursorPosition = cursorPosition . withColumn ( 0 ) . withRelativeRow ( 1 ) ; if ( cursorPosition . getRow ( ) >= currentTextBuffer . getLineCount ( ) ) { currentTextBuffer . newLine ( ) ; } trimBufferBacklog ( ) ; correctCursor ( ) ; }
Moves the text cursor to the first column of the next line and trims the backlog of necessary
21,921
public void scrollLines ( int firstLine , int lastLine , int distance ) { if ( distance == 0 || firstLine > lastLine ) { return ; } super . scrollLines ( firstLine , lastLine , distance ) ; ScrollHint newHint = new ScrollHint ( firstLine , lastLine , distance ) ; if ( scrollHint == null ) { scrollHint = newHint ; } else if ( scrollHint == ScrollHint . INVALID ) { } else if ( scrollHint . matches ( newHint ) ) { scrollHint . distance += newHint . distance ; } else { this . scrollHint = ScrollHint . INVALID ; } }
Perform the scrolling and save scroll - range and distance in order to be able to optimize Terminal - update later .
21,922
public B setTitle ( String title ) { if ( title == null ) { title = "" ; } this . title = title ; return self ( ) ; }
Changes the title of the dialog
21,923
public final T build ( ) { T dialog = buildDialog ( ) ; if ( ! extraWindowHints . isEmpty ( ) ) { Set < Window . Hint > combinedHints = new HashSet < Window . Hint > ( dialog . getHints ( ) ) ; combinedHints . addAll ( extraWindowHints ) ; dialog . setHints ( combinedHints ) ; } return dialog ; }
Builds a new dialog following the specifications of this builder
21,924
public synchronized T addItem ( V item ) { if ( item == null ) { return self ( ) ; } items . add ( item ) ; if ( selectedIndex == - 1 ) { selectedIndex = 0 ; } invalidate ( ) ; return self ( ) ; }
Adds one more item to the list box at the end .
21,925
public synchronized V removeItem ( int index ) { V existing = items . remove ( index ) ; if ( index < selectedIndex ) { selectedIndex -- ; } while ( selectedIndex >= items . size ( ) ) { selectedIndex -- ; } invalidate ( ) ; return existing ; }
Removes an item from the list box by its index . The current selection in the list box will be adjusted accordingly .
21,926
public static IOSafeTerminal createRuntimeExceptionConvertingAdapter ( Terminal terminal ) { if ( terminal instanceof ExtendedTerminal ) { return createRuntimeExceptionConvertingAdapter ( ( ExtendedTerminal ) terminal ) ; } else { return new IOSafeTerminalAdapter ( terminal , new ConvertToRuntimeException ( ) ) ; } }
Creates a wrapper around a Terminal that exposes it as a IOSafeTerminal . If any IOExceptions occur they will be wrapped by a RuntimeException and re - thrown .
21,927
public static IOSafeTerminal createDoNothingOnExceptionAdapter ( Terminal terminal ) { if ( terminal instanceof ExtendedTerminal ) { return createDoNothingOnExceptionAdapter ( ( ExtendedTerminal ) terminal ) ; } else { return new IOSafeTerminalAdapter ( terminal , new DoNothingAndOrReturnNull ( ) ) ; } }
Creates a wrapper around a Terminal that exposes it as a IOSafeTerminal . If any IOExceptions occur they will be silently ignored and for those method with a non - void return type null will be returned .
21,928
public final synchronized void setLabel ( String label ) { if ( label == null ) { throw new IllegalArgumentException ( "null label to a button is not allowed" ) ; } if ( label . isEmpty ( ) ) { label = " " ; } this . label = label ; invalidate ( ) ; }
Updates the label on the button to the specified string
21,929
public List < String > findRedundantDeclarations ( ) { List < String > result = new ArrayList < String > ( ) ; for ( ThemeTreeNode node : rootNode . childMap . values ( ) ) { findRedundantDeclarations ( result , node ) ; } Collections . sort ( result ) ; return result ; }
Returns a list of redundant theme entries in this theme . A redundant entry means that it doesn t need to be specified because there is a parent node in the hierarchy which has the same property so if the redundant entry wasn t there the parent node would be picked up and the end result would be the same .
21,930
public void copyFrom ( TextImage source , int startRowIndex , int rows , int startColumnIndex , int columns , int destinationRowOffset , int destinationColumnOffset ) { source . copyTo ( backend , startRowIndex , rows , startColumnIndex , columns , destinationRowOffset , destinationColumnOffset ) ; }
Copies the content from a TextImage into this buffer .
21,931
@ SuppressWarnings ( "SameParameterValue" ) public TextCharacter withCharacter ( char character ) { if ( this . character == character ) { return this ; } return new TextCharacter ( character , foregroundColor , backgroundColor , modifiers ) ; }
Returns a new TextCharacter with the same colors and modifiers but a different underlying character
21,932
public TextCharacter withForegroundColor ( TextColor foregroundColor ) { if ( this . foregroundColor == foregroundColor || this . foregroundColor . equals ( foregroundColor ) ) { return this ; } return new TextCharacter ( character , foregroundColor , backgroundColor , modifiers ) ; }
Returns a copy of this TextCharacter with a specified foreground color
21,933
public TextCharacter withBackgroundColor ( TextColor backgroundColor ) { if ( this . backgroundColor == backgroundColor || this . backgroundColor . equals ( backgroundColor ) ) { return this ; } return new TextCharacter ( character , foregroundColor , backgroundColor , modifiers ) ; }
Returns a copy of this TextCharacter with a specified background color
21,934
public TextCharacter withModifiers ( Collection < SGR > modifiers ) { EnumSet < SGR > newSet = EnumSet . copyOf ( modifiers ) ; if ( modifiers . equals ( newSet ) ) { return this ; } return new TextCharacter ( character , foregroundColor , backgroundColor , newSet ) ; }
Returns a copy of this TextCharacter with specified list of SGR modifiers . None of the currently active SGR codes will be carried over to the copy only those in the passed in value .
21,935
public TextCharacter withModifier ( SGR modifier ) { if ( modifiers . contains ( modifier ) ) { return this ; } EnumSet < SGR > newSet = EnumSet . copyOf ( this . modifiers ) ; newSet . add ( modifier ) ; return new TextCharacter ( character , foregroundColor , backgroundColor , newSet ) ; }
Returns a copy of this TextCharacter with an additional SGR modifier . All of the currently active SGR codes will be carried over to the copy in addition to the one specified .
21,936
public TextCharacter withoutModifier ( SGR modifier ) { if ( ! modifiers . contains ( modifier ) ) { return this ; } EnumSet < SGR > newSet = EnumSet . copyOf ( this . modifiers ) ; newSet . remove ( modifier ) ; return new TextCharacter ( character , foregroundColor , backgroundColor , newSet ) ; }
Returns a copy of this TextCharacter with an SGR modifier removed . All of the currently active SGR codes will be carried over to the copy except for the one specified . If the current TextCharacter doesn t have the SGR specified it will return itself .
21,937
public Terminal createTerminalEmulator ( ) { Window window ; if ( ! forceAWTOverSwing && hasSwing ( ) ) { window = createSwingTerminal ( ) ; } else { window = createAWTTerminal ( ) ; } if ( autoOpenTerminalFrame ) { window . setVisible ( true ) ; } return ( Terminal ) window ; }
Creates a new terminal emulator window which will be either Swing - based or AWT - based depending on what is available on the system
21,938
public TelnetTerminal createTelnetTerminal ( ) { try { System . err . print ( "Waiting for incoming telnet connection on port " + telnetPort + " ... " ) ; System . err . flush ( ) ; TelnetTerminalServer tts = new TelnetTerminalServer ( telnetPort ) ; TelnetTerminal rawTerminal = tts . acceptConnection ( ) ; tts . close ( ) ; System . err . println ( "Ok, got it!" ) ; if ( mouseCaptureMode != null ) { rawTerminal . setMouseCaptureMode ( mouseCaptureMode ) ; } if ( inputTimeout >= 0 ) { rawTerminal . getInputDecoder ( ) . setTimeoutUnits ( inputTimeout ) ; } return rawTerminal ; } catch ( IOException ioe ) { throw new RuntimeException ( ioe ) ; } }
Creates a new TelnetTerminal
21,939
public synchronized Table < V > setTableModel ( TableModel < V > tableModel ) { if ( tableModel == null ) { throw new IllegalArgumentException ( "Cannot assign a null TableModel" ) ; } this . tableModel . removeListener ( tableModelListener ) ; this . tableModel = tableModel ; this . tableModel . addListener ( tableModelListener ) ; invalidate ( ) ; return this ; }
Updates the table with a new table model effectively replacing the content of the table completely
21,940
public TelnetTerminal acceptConnection ( ) throws IOException { Socket clientSocket = serverSocket . accept ( ) ; clientSocket . setTcpNoDelay ( true ) ; return new TelnetTerminal ( clientSocket , charset ) ; }
Waits for the next client to connect in to our server and returns a Terminal implementation TelnetTerminal that represents the remote terminal this client is running . The terminal can be used just like any other Terminal but keep in mind that all operations are sent over the network .
21,941
public int getViewSize ( ) { if ( viewSize > 0 ) { return viewSize ; } if ( direction == Direction . HORIZONTAL ) { return getSize ( ) . getColumns ( ) ; } else { return getSize ( ) . getRows ( ) ; } }
Returns the view size of the scrollbar
21,942
public synchronized void setText ( String text ) { setLines ( splitIntoMultipleLines ( text ) ) ; this . labelSize = getBounds ( lines , labelSize ) ; invalidate ( ) ; }
Updates the text this label is displaying
21,943
public synchronized String getText ( ) { if ( lines . length == 0 ) { return "" ; } StringBuilder bob = new StringBuilder ( lines [ 0 ] ) ; for ( int i = 1 ; i < lines . length ; i ++ ) { bob . append ( "\n" ) . append ( lines [ i ] ) ; } return bob . toString ( ) ; }
Returns the text this label is displaying . Multi - line labels will have their text concatenated with \ n even if they were originally set using multi - line text having \ r \ n as line terminators .
21,944
protected TerminalSize getBounds ( String [ ] lines , TerminalSize currentBounds ) { if ( currentBounds == null ) { currentBounds = TerminalSize . ZERO ; } currentBounds = currentBounds . withRows ( lines . length ) ; if ( labelWidth == null || labelWidth == 0 ) { int preferredWidth = 0 ; for ( String line : lines ) { int lineWidth = TerminalTextUtils . getColumnWidth ( line ) ; if ( preferredWidth < lineWidth ) { preferredWidth = lineWidth ; } } currentBounds = currentBounds . withColumns ( preferredWidth ) ; } else { List < String > wordWrapped = TerminalTextUtils . getWordWrappedText ( labelWidth , lines ) ; currentBounds = currentBounds . withColumns ( labelWidth ) . withRows ( wordWrapped . size ( ) ) ; } return currentBounds ; }
Returns the area in terminal columns and rows required to fully draw the lines passed in .
21,945
protected KeyStroke getKeyStroke ( KeyType key , int mods ) { boolean bShift = false , bCtrl = false , bAlt = false ; if ( key == null ) { return null ; } if ( mods >= 0 ) { bShift = ( mods & SHIFT ) != 0 ; bAlt = ( mods & ALT ) != 0 ; bCtrl = ( mods & CTRL ) != 0 ; } return new KeyStroke ( key , bCtrl , bAlt , bShift ) ; }
combines a KeyType and modifiers into a KeyStroke . Subclasses can override this for customization purposes .
21,946
protected KeyStroke getKeyStrokeRaw ( char first , int num1 , int num2 , char last , boolean bEsc ) { KeyType kt ; boolean bPuttyCtrl = false ; if ( last == '~' && stdMap . containsKey ( num1 ) ) { kt = stdMap . get ( num1 ) ; } else if ( finMap . containsKey ( last ) ) { kt = finMap . get ( last ) ; if ( first == 'O' && last >= 'A' && last <= 'D' ) { bPuttyCtrl = true ; } } else { kt = null ; } int mods = num2 - 1 ; if ( bEsc ) { if ( mods >= 0 ) { mods |= ALT ; } else { mods = ALT ; } } if ( bPuttyCtrl ) { if ( mods >= 0 ) { mods |= CTRL ; } else { mods = CTRL ; } } return getKeyStroke ( kt , mods ) ; }
combines the raw parts of the sequence into a KeyStroke . This method does not check the first char but overrides may do so .
21,947
public ActionListBox addItem ( final String label , final Runnable action ) { return addItem ( new Runnable ( ) { public void run ( ) { action . run ( ) ; } public String toString ( ) { return label ; } } ) ; }
Adds a new item to the list which is displayed in the list using a supplied label .
21,948
private void initDelegate ( ) { boolean powerSaveMode = Utils . isPowerSaveModeEnabled ( mPowerManager ) ; if ( powerSaveMode ) { if ( mPBDelegate == null || ! ( mPBDelegate instanceof PowerSaveModeDelegate ) ) { if ( mPBDelegate != null ) mPBDelegate . stop ( ) ; mPBDelegate = new PowerSaveModeDelegate ( this ) ; } } else { if ( mPBDelegate == null || ( mPBDelegate instanceof PowerSaveModeDelegate ) ) { if ( mPBDelegate != null ) mPBDelegate . stop ( ) ; mPBDelegate = new DefaultDelegate ( this , mOptions ) ; } } }
Inits the delegate . Create one if the delegate is null or not the right mode
21,949
public void hide ( ) { mDismissed = true ; removeCallbacks ( mDelayedShow ) ; long diff = System . currentTimeMillis ( ) - mStartTime ; if ( diff >= MIN_SHOW_TIME || mStartTime == - 1 ) { setVisibility ( View . GONE ) ; } else { if ( ! mPostedHide ) { postDelayed ( mDelayedHide , MIN_SHOW_TIME - diff ) ; mPostedHide = true ; } } }
Hide the progress view if it is visible . The progress view will not be hidden until it has been shown for at least a minimum show time . If the progress view was not yet visible cancels showing the progress view .
21,950
Class loadAccessClass ( String name ) { if ( localClassNames . contains ( name ) ) { try { return loadClass ( name , false ) ; } catch ( ClassNotFoundException ex ) { throw new RuntimeException ( ex ) ; } } return null ; }
Returns null if the access class has not yet been defined .
21,951
public Object invoke ( Object object , String methodName , Class [ ] paramTypes , Object ... args ) { return invoke ( object , getIndex ( methodName , paramTypes ) , args ) ; }
Invokes the method with the specified name and the specified param types .
21,952
public Object invoke ( Object object , String methodName , Object ... args ) { return invoke ( object , getIndex ( methodName , args == null ? 0 : args . length ) , args ) ; }
Invokes the first method with the specified name and the specified number of arguments .
21,953
public int getIndex ( String methodName ) { for ( int i = 0 , n = methodNames . length ; i < n ; i ++ ) if ( methodNames [ i ] . equals ( methodName ) ) return i ; throw new IllegalArgumentException ( "Unable to find non-private method: " + methodName ) ; }
Returns the index of the first method with the specified name .
21,954
public int getIndex ( String methodName , Class ... paramTypes ) { for ( int i = 0 , n = methodNames . length ; i < n ; i ++ ) if ( methodNames [ i ] . equals ( methodName ) && Arrays . equals ( paramTypes , parameterTypes [ i ] ) ) return i ; throw new IllegalArgumentException ( "Unable to find non-private method: " + methodName + " " + Arrays . toString ( paramTypes ) ) ; }
Returns the index of the first method with the specified name and param types .
21,955
public static long [ ] MurmurHash3_x64_128 ( final long [ ] key , final int seed ) { State state = new State ( ) ; state . h1 = 0x9368e53c2f6af274L ^ seed ; state . h2 = 0x586dcd208f7cd3fdL ^ seed ; state . c1 = 0x87c37b91114253d5L ; state . c2 = 0x4cf5ad432745937fL ; for ( int i = 0 ; i < key . length / 2 ; i ++ ) { state . k1 = key [ i * 2 ] ; state . k2 = key [ i * 2 + 1 ] ; bmix ( state ) ; } long tail = key [ key . length - 1 ] ; if ( ( key . length & 1 ) == 1 ) { state . k1 ^= tail ; bmix ( state ) ; } state . h2 ^= key . length * 8 ; state . h1 += state . h2 ; state . h2 += state . h1 ; state . h1 = fmix ( state . h1 ) ; state . h2 = fmix ( state . h2 ) ; state . h1 += state . h2 ; state . h2 += state . h1 ; return new long [ ] { state . h1 , state . h2 } ; }
Hash a value using the x64 128 bit variant of MurmurHash3
21,956
protected void pushState ( final Cache < ? , ? > cache ) throws Exception { DataContainer < ? , ? > dc = cache . getAdvancedCache ( ) . getDataContainer ( ) ; dc . forEach ( entry -> { MarshallableEntry me = ctx . getMarshallableEntryFactory ( ) . create ( entry . getKey ( ) , entry . getValue ( ) , entry . getMetadata ( ) , entry . getExpiryTime ( ) , entry . getLastUsed ( ) ) ; write ( me ) ; } ) ; }
Pushes the state of a specific cache by reading the cache s data and putting in the cache store .
21,957
protected void awaitForPushToFinish ( Future < ? > future , long timeout , TimeUnit unit ) { final boolean debugEnabled = log . isDebugEnabled ( ) ; try { if ( debugEnabled ) log . debug ( "wait for state push to cache loader to finish" ) ; future . get ( timeout , unit ) ; } catch ( TimeoutException e ) { if ( debugEnabled ) log . debug ( "timed out waiting for state push to cache loader to finish" ) ; } catch ( ExecutionException e ) { if ( debugEnabled ) log . debug ( "exception reported waiting for state push to cache loader to finish" ) ; } catch ( InterruptedException ie ) { Thread . currentThread ( ) . interrupt ( ) ; if ( trace ) log . trace ( "wait for state push to cache loader to finish was interrupted" ) ; } }
Method that waits for the in - memory to cache loader state to finish . This method s called in case a push state is already in progress and we need to wait for it to finish .
21,958
private void doPushState ( ) throws PushStateException { if ( pushStateFuture == null || pushStateFuture . isDone ( ) ) { Callable < ? > task = createPushStateTask ( ) ; pushStateFuture = executor . submit ( task ) ; try { waitForTaskToFinish ( pushStateFuture , singletonConfiguration . pushStateTimeout ( ) , TimeUnit . MILLISECONDS ) ; } catch ( Exception e ) { throw new PushStateException ( "unable to complete in memory state push to cache loader" , e ) ; } } else { awaitForPushToFinish ( pushStateFuture , singletonConfiguration . pushStateTimeout ( ) , TimeUnit . MILLISECONDS ) ; } }
Called when the SingletonStore discovers that the cache has become the coordinator and push in memory state has been enabled . It might not actually push the state if there s an ongoing push task running in which case will wait for the push task to finish .
21,959
private void waitForTaskToFinish ( Future < ? > future , long timeout , TimeUnit unit ) throws Exception { try { future . get ( timeout , unit ) ; } catch ( TimeoutException e ) { throw new Exception ( "task timed out" , e ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; if ( trace ) log . trace ( "task was interrupted" ) ; } finally { future . cancel ( true ) ; } }
Waits within a time constraint for a task to finish .
21,960
private ValueRef < K , V > create ( K key , V value , ReferenceQueue < V > q ) { return WeakValueRef . create ( key , value , q ) ; }
Create new value ref instance .
21,961
@ SuppressWarnings ( "unchecked" ) private void processQueue ( ) { ValueRef < K , V > ref = ( ValueRef < K , V > ) queue . poll ( ) ; while ( ref != null ) { if ( ref == map . get ( ref . getKey ( ) ) ) map . remove ( ref . getKey ( ) ) ; ref = ( ValueRef < K , V > ) queue . poll ( ) ; } }
Remove all entries whose values have been discarded .
21,962
public ClusteringConfigurationBuilder biasLifespan ( long l , TimeUnit unit ) { attributes . attribute ( BIAS_LIFESPAN ) . set ( unit . toMillis ( l ) ) ; return this ; }
Used in scattered cache . Specifies how long can be the acquired bias held ; while the reads will never be stale tracking that information consumes memory on primary owner .
21,963
private void rebuildIndex ( ) throws Exception { ByteBuffer buf = ByteBuffer . allocate ( KEY_POS ) ; for ( ; ; ) { buf . clear ( ) . limit ( KEY_POS ) ; channel . read ( buf , filePos ) ; if ( buf . remaining ( ) > 0 ) return ; buf . flip ( ) ; int entrySize = buf . getInt ( ) ; int keyLen = buf . getInt ( ) ; int dataLen = buf . getInt ( ) ; int metadataLen = buf . getInt ( ) ; long expiryTime = buf . getLong ( ) ; FileEntry fe = new FileEntry ( filePos , entrySize , keyLen , dataLen , metadataLen , expiryTime ) ; if ( fe . size < KEY_POS + fe . keyLen + fe . dataLen + fe . metadataLen ) { throw log . errorReadingFileStore ( file . getPath ( ) , filePos ) ; } filePos += fe . size ; if ( fe . keyLen > 0 ) { if ( buf . capacity ( ) < fe . keyLen ) buf = ByteBuffer . allocate ( fe . keyLen ) ; buf . clear ( ) . limit ( fe . keyLen ) ; channel . read ( buf , fe . offset + KEY_POS ) ; K key = ( K ) ctx . getMarshaller ( ) . objectFromByteBuffer ( buf . array ( ) , 0 , fe . keyLen ) ; entries . put ( key , fe ) ; } else { freeList . add ( fe ) ; } } }
Rebuilds the in - memory index from file .
21,964
private FileEntry allocate ( int len ) { synchronized ( freeList ) { SortedSet < FileEntry > candidates = freeList . tailSet ( new FileEntry ( 0 , len ) ) ; for ( Iterator < FileEntry > it = candidates . iterator ( ) ; it . hasNext ( ) ; ) { FileEntry free = it . next ( ) ; if ( free . isLocked ( ) ) continue ; it . remove ( ) ; return allocateExistingEntry ( free , len ) ; } FileEntry fe = new FileEntry ( filePos , len ) ; filePos += len ; if ( trace ) log . tracef ( "New entry allocated at %d:%d, %d free entries, file size is %d" , fe . offset , fe . size , freeList . size ( ) , filePos ) ; return fe ; } }
Allocates the requested space in the file .
21,965
private void addNewFreeEntry ( FileEntry fe ) throws IOException { ByteBuffer buf = ByteBuffer . allocate ( KEY_POS ) ; buf . putInt ( fe . size ) ; buf . putInt ( 0 ) ; buf . putInt ( 0 ) ; buf . putInt ( 0 ) ; buf . putLong ( - 1 ) ; buf . flip ( ) ; channel . write ( buf , fe . offset ) ; freeList . add ( fe ) ; }
Writes a new free entry to the file and also adds it to the free list
21,966
private FileEntry evict ( ) { if ( configuration . maxEntries ( ) > 0 ) { synchronized ( entries ) { if ( entries . size ( ) > configuration . maxEntries ( ) ) { Iterator < FileEntry > it = entries . values ( ) . iterator ( ) ; FileEntry fe = it . next ( ) ; it . remove ( ) ; return fe ; } } } return null ; }
Try to evict an entry if the capacity of the cache store is reached .
21,967
private void processFreeEntries ( ) { List < FileEntry > l = new ArrayList < > ( freeList ) ; l . sort ( ( o1 , o2 ) -> { long diff = o1 . offset - o2 . offset ; return ( diff == 0 ) ? 0 : ( ( diff > 0 ) ? - 1 : 1 ) ; } ) ; truncateFile ( l ) ; mergeFreeEntries ( l ) ; }
Manipulates the free entries for optimizing disk space .
21,968
private void truncateFile ( List < FileEntry > entries ) { long startTime = 0 ; if ( trace ) startTime = timeService . wallClockTime ( ) ; int reclaimedSpace = 0 ; int removedEntries = 0 ; long truncateOffset = - 1 ; for ( Iterator < FileEntry > it = entries . iterator ( ) ; it . hasNext ( ) ; ) { FileEntry fe = it . next ( ) ; if ( ! fe . isLocked ( ) && ( ( fe . offset + fe . size ) == filePos ) ) { truncateOffset = fe . offset ; filePos = fe . offset ; freeList . remove ( fe ) ; it . remove ( ) ; reclaimedSpace += fe . size ; removedEntries ++ ; } else { break ; } } if ( truncateOffset > 0 ) { try { channel . truncate ( truncateOffset ) ; } catch ( IOException e ) { throw new PersistenceException ( "Error while truncating file" , e ) ; } } if ( trace ) { log . tracef ( "Removed entries: %d, Reclaimed Space: %d, Free Entries %d" , removedEntries , reclaimedSpace , freeList . size ( ) ) ; log . tracef ( "Time taken for truncateFile: %d (ms)" , timeService . wallClockTime ( ) - startTime ) ; } }
Removes free entries towards the end of the file and truncates the file .
21,969
public static < T > Set < T > immutableSetConvert ( Collection < ? extends T > collection ) { return immutableSetWrap ( new HashSet < T > ( collection ) ) ; }
Converts a Collections into an immutable Set by copying it .
21,970
public static < T > Set < T > immutableSetCopy ( Set < T > set ) { if ( set == null ) return null ; if ( set . isEmpty ( ) ) return Collections . emptySet ( ) ; if ( set . size ( ) == 1 ) return Collections . singleton ( set . iterator ( ) . next ( ) ) ; Set < ? extends T > copy = ObjectDuplicator . duplicateSet ( set ) ; if ( copy == null ) copy = attemptCopyConstructor ( set , Collection . class ) ; if ( copy == null ) copy = new HashSet < > ( set ) ; return new ImmutableSetWrapper < > ( copy ) ; }
Creates an immutable copy of the specified set .
21,971
public static < K , V > Map < K , V > immutableMapWrap ( Map < ? extends K , ? extends V > map ) { return new ImmutableMapWrapper < > ( map ) ; }
Wraps a map with an immutable map . There is no copying involved .
21,972
public static < K , V > Map < K , V > immutableMapCopy ( Map < K , V > map ) { if ( map == null ) return null ; if ( map . isEmpty ( ) ) return Collections . emptyMap ( ) ; if ( map . size ( ) == 1 ) { Map . Entry < K , V > me = map . entrySet ( ) . iterator ( ) . next ( ) ; return Collections . singletonMap ( me . getKey ( ) , me . getValue ( ) ) ; } Map < ? extends K , ? extends V > copy = ObjectDuplicator . duplicateMap ( map ) ; if ( copy == null ) copy = attemptCopyConstructor ( map , Map . class ) ; if ( copy == null ) copy = new HashMap < > ( map ) ; return new ImmutableMapWrapper < > ( copy ) ; }
Creates an immutable copy of the specified map .
21,973
public static < T > Collection < T > immutableCollectionCopy ( Collection < T > collection ) { if ( collection == null ) return null ; if ( collection . isEmpty ( ) ) return Collections . emptySet ( ) ; if ( collection . size ( ) == 1 ) return Collections . singleton ( collection . iterator ( ) . next ( ) ) ; Collection < ? extends T > copy = ObjectDuplicator . duplicateCollection ( collection ) ; if ( copy == null ) copy = attemptCopyConstructor ( collection , Collection . class ) ; if ( copy == null ) copy = new ArrayList < > ( collection ) ; return new ImmutableCollectionWrapper < > ( copy ) ; }
Creates a new immutable copy of the specified Collection .
21,974
public < T > Collector < T > create ( long id , Collection < Address > backupOwners , int topologyId ) { if ( backupOwners . isEmpty ( ) ) { return new PrimaryOwnerOnlyCollector < > ( ) ; } SingleKeyCollector < T > collector = new SingleKeyCollector < > ( id , backupOwners , topologyId ) ; BaseAckTarget prev = collectorMap . put ( id , collector ) ; assert prev == null || prev . topologyId < topologyId : format ( "replaced old collector '%s' by '%s'" , prev , collector ) ; if ( trace ) { log . tracef ( "Created new collector for %s. BackupOwners=%s" , id , backupOwners ) ; } return collector ; }
Creates a collector for a single key write operation .
21,975
public void backupAck ( long id , Address from , int topologyId ) { BaseAckTarget ackTarget = collectorMap . get ( id ) ; if ( ackTarget instanceof SingleKeyCollector ) { ( ( SingleKeyCollector ) ackTarget ) . backupAck ( topologyId , from ) ; } else if ( ackTarget instanceof MultiTargetCollectorImpl ) { ( ( MultiTargetCollectorImpl ) ackTarget ) . backupAck ( topologyId , from ) ; } }
Acknowledges a write operation completion in the backup owner .
21,976
public void onMembersChange ( Collection < Address > members ) { Set < Address > currentMembers = new HashSet < > ( members ) ; this . currentMembers = currentMembers ; for ( BaseAckTarget < ? > ackTarget : collectorMap . values ( ) ) { ackTarget . onMembersChange ( currentMembers ) ; } }
Notifies a change in member list .
21,977
static < K , V , T , R > void writeTo ( ObjectOutput output , Mutation < K , V , R > mutation ) throws IOException { BaseMutation bm = ( BaseMutation ) mutation ; DataConversion . writeTo ( output , bm . keyDataConversion ) ; DataConversion . writeTo ( output , bm . valueDataConversion ) ; byte type = mutation . type ( ) ; output . writeByte ( type ) ; switch ( type ) { case ReadWrite . TYPE : output . writeObject ( ( ( ReadWrite < K , V , ? > ) mutation ) . f ) ; break ; case ReadWriteWithValue . TYPE : ReadWriteWithValue < K , V , T , R > rwwv = ( ReadWriteWithValue < K , V , T , R > ) mutation ; output . writeObject ( rwwv . argument ) ; output . writeObject ( rwwv . f ) ; break ; case Write . TYPE : output . writeObject ( ( ( Write < K , V > ) mutation ) . f ) ; break ; case WriteWithValue . TYPE : WriteWithValue < K , V , T > wwv = ( WriteWithValue < K , V , T > ) mutation ; output . writeObject ( wwv . argument ) ; output . writeObject ( wwv . f ) ; break ; } }
No need to occupy externalizer ids when we have a limited set of options
21,978
public void preStart ( ) { defaultMetadata = new EmbeddedMetadata . Builder ( ) . lifespan ( config . expiration ( ) . lifespan ( ) ) . maxIdle ( config . expiration ( ) . maxIdle ( ) ) . build ( ) ; transactional = config . transaction ( ) . transactionMode ( ) . isTransactional ( ) ; batchingEnabled = config . invocationBatching ( ) . enabled ( ) ; }
of EncoderCache . ATM there s not method to invoke
21,979
@ ManagedAttribute ( description = "Returns the cache name" , displayName = "Cache name" , dataType = DataType . TRAIT , displayType = DisplayType . SUMMARY ) public String getCacheName ( ) { String name = getName ( ) . equals ( BasicCacheContainer . DEFAULT_CACHE_NAME ) ? "Default Cache" : getName ( ) ; return name + "(" + getCacheConfiguration ( ) . clustering ( ) . cacheMode ( ) . toString ( ) . toLowerCase ( ) + ")" ; }
Returns the cache name . If this is the default cache it returns a more friendly name .
21,980
static ModelNode createOperation ( ModelNode address , ModelNode model ) throws OperationFailedException { ModelNode operation = Util . getEmptyOperation ( ADD , address ) ; INSTANCE . populate ( model , operation ) ; return operation ; }
used to create subsystem description
21,981
public final void registerComponent ( Object component , Class < ? > type ) { registerComponent ( component , type . getName ( ) , type . equals ( component . getClass ( ) ) ) ; }
Registers a component in the registry under the given type and injects any dependencies needed .
21,982
protected AbstractComponentFactory getFactory ( Class < ? > componentClass ) { String cfClass = getComponentMetadataRepo ( ) . findFactoryForComponent ( componentClass ) ; if ( cfClass == null ) { throw new CacheConfigurationException ( "No registered default factory for component '" + componentClass + "' found!" ) ; } return basicComponentRegistry . getComponent ( cfClass , AbstractComponentFactory . class ) . wired ( ) ; }
Retrieves a component factory instance capable of constructing components of a specified type . If the factory doesn t exist in the registry one is created .
21,983
@ SuppressWarnings ( "unchecked" ) public < T > T getComponent ( Class < T > type ) { String className = type . getName ( ) ; return ( T ) getComponent ( type , className ) ; }
Retrieves a component of a specified type from the registry or null if it cannot be found .
21,984
private void handleLifecycleTransitionFailure ( Throwable t ) { if ( t . getCause ( ) != null && t . getCause ( ) instanceof CacheConfigurationException ) throw ( CacheConfigurationException ) t . getCause ( ) ; else if ( t . getCause ( ) != null && t . getCause ( ) instanceof InvocationTargetException && t . getCause ( ) . getCause ( ) != null && t . getCause ( ) . getCause ( ) instanceof CacheConfigurationException ) throw ( CacheConfigurationException ) t . getCause ( ) . getCause ( ) ; else if ( t instanceof CacheException ) throw ( CacheException ) t ; else if ( t instanceof RuntimeException ) throw ( RuntimeException ) t ; else if ( t instanceof Error ) throw ( Error ) t ; else throw new CacheException ( t ) ; }
Sets the cacheStatus to FAILED and re - throws the problem as one of the declared types . Converts any non - RuntimeException Exception to CacheException .
21,985
public Set < Component > getRegisteredComponents ( ) { Set < Component > set = new HashSet < > ( ) ; for ( ComponentRef < ? > c : basicComponentRegistry . getRegisteredComponents ( ) ) { ComponentMetadata metadata = c . wired ( ) != null ? componentMetadataRepo . getComponentMetadata ( c . wired ( ) . getClass ( ) ) : null ; Component component = new Component ( c , metadata ) ; set . add ( component ) ; } return set ; }
Returns an immutable set containing all the components that exists in the repository at this moment .
21,986
private boolean isMultiChunked ( final String filename ) { final FileCacheKey fileCacheKey = new FileCacheKey ( indexName , filename , affinitySegmentId ) ; final FileMetadata fileMetadata = metadataCache . get ( fileCacheKey ) ; if ( fileMetadata == null ) { return true ; } else { return fileMetadata . isMultiChunked ( ) ; } }
Evaluates if the file is potentially being stored as fragmented into multiple chunks ; when it s a single chunk we don t need to apply readlocks .
21,987
public boolean acquireReadLock ( String filename ) { FileReadLockKey readLockKey = new FileReadLockKey ( indexName , filename , affinitySegmentId ) ; Integer lockValue = locksCache . get ( readLockKey ) ; boolean done = false ; while ( done == false ) { if ( lockValue != null ) { int refCount = lockValue . intValue ( ) ; if ( refCount == 0 ) { return false ; } Integer newValue = Integer . valueOf ( refCount + 1 ) ; done = locksCache . replace ( readLockKey , lockValue , newValue ) ; if ( ! done ) { lockValue = locksCache . get ( readLockKey ) ; } } else { lockValue = locksCache . putIfAbsent ( readLockKey , 2 ) ; done = ( null == lockValue ) ; if ( done ) { final FileCacheKey fileKey = new FileCacheKey ( indexName , filename , affinitySegmentId ) ; if ( metadataCache . get ( fileKey ) == null ) { locksCache . withFlags ( Flag . IGNORE_RETURN_VALUES ) . removeAsync ( readLockKey ) ; return false ; } } } } return true ; }
Acquires a readlock on all chunks for this file to make sure chunks are not deleted while iterating on the group . This is needed to avoid an eager lock on all elements .
21,988
void forgetTransaction ( Xid xid ) { try { TransactionOperationFactory factory = assertStartedAndReturnFactory ( ) ; ForgetTransactionOperation operation = factory . newForgetTransactionOperation ( xid ) ; operation . execute ( ) ; } catch ( Exception e ) { if ( isTraceLogEnabled ( ) ) { getLog ( ) . tracef ( e , "Exception in forget transaction xid=%s" , xid ) ; } } }
Tells the server to forget this transaction .
21,989
CompletableFuture < Collection < Xid > > fetchPreparedTransactions ( ) { try { TransactionOperationFactory factory = assertStartedAndReturnFactory ( ) ; return factory . newRecoveryOperation ( ) . execute ( ) ; } catch ( Exception e ) { if ( isTraceLogEnabled ( ) ) { getLog ( ) . trace ( "Exception while fetching prepared transactions" , e ) ; } return CompletableFuture . completedFuture ( Collections . emptyList ( ) ) ; } }
It requests the server for all in - doubt prepared transactions to be handled by the recovery process .
21,990
public static CompletionStage < Void > allOf ( CompletionStage < Void > first , CompletionStage < Void > second ) { if ( ! isCompletedSuccessfully ( first ) ) { if ( isCompletedSuccessfully ( second ) ) { return first ; } else { return CompletionStages . aggregateCompletionStage ( ) . dependsOn ( first ) . dependsOn ( second ) . freeze ( ) ; } } return second ; }
Returns a CompletableStage that completes when both of the provides CompletionStages complete . This method may choose to return either of the argument if the other is complete or a new instance completely .
21,991
public static CompletionStage < Void > allOf ( CompletionStage < ? > ... stages ) { AggregateCompletionStage < Void > aggregateCompletionStage = null ; for ( CompletionStage < ? > stage : stages ) { if ( ! isCompletedSuccessfully ( stage ) ) { if ( aggregateCompletionStage == null ) { aggregateCompletionStage = CompletionStages . aggregateCompletionStage ( ) ; } aggregateCompletionStage . dependsOn ( stage ) ; } } return aggregateCompletionStage != null ? aggregateCompletionStage . freeze ( ) : CompletableFutures . completedNull ( ) ; }
Returns a CompletionStage that completes when all of the provided stages complete either normally or via exception . If one or more states complete exceptionally the returned CompletionStage will complete with the exception of one of these . If no CompletionStages are provided returns a CompletionStage completed with the value null .
21,992
Object extractKey ( DocumentExtractor extractor , int docIndex ) { String strKey ; try { strKey = ( String ) extractor . extract ( docIndex ) . getId ( ) ; } catch ( IOException e ) { throw new SearchException ( "Error while extracting key" , e ) ; } return keyTransformationHandler . stringToKey ( strKey ) ; }
Utility to extract the cache key of a DocumentExtractor and use the KeyTransformationHandler to turn the string into the actual key object .
21,993
public CompletableFuture < Void > requestSegments ( ) { return startTransfer ( applyState ? StateRequestCommand . Type . START_STATE_TRANSFER : StateRequestCommand . Type . START_CONSISTENCY_CHECK ) ; }
Send START_STATE_TRANSFER request to source node .
21,994
public void cancelSegments ( IntSet cancelledSegments ) { if ( isCancelled ) { throw new IllegalArgumentException ( "The task is already cancelled." ) ; } if ( trace ) { log . tracef ( "Partially cancelling inbound state transfer from node %s, segments %s" , source , cancelledSegments ) ; } synchronized ( segments ) { if ( ! segments . containsAll ( cancelledSegments ) ) { throw new IllegalArgumentException ( "Some of the specified segments cannot be cancelled because they were not previously requested" ) ; } unfinishedSegments . removeAll ( cancelledSegments ) ; if ( unfinishedSegments . isEmpty ( ) ) { isCancelled = true ; } } sendCancelCommand ( cancelledSegments ) ; if ( isCancelled ) { notifyCompletion ( false ) ; } }
Cancels a set of segments and marks them as finished .
21,995
public void cancel ( ) { if ( ! isCancelled ) { isCancelled = true ; IntSet segmentsCopy = getUnfinishedSegments ( ) ; synchronized ( segments ) { unfinishedSegments . clear ( ) ; } if ( trace ) { log . tracef ( "Cancelling inbound state transfer from %s with unfinished segments %s" , source , segmentsCopy ) ; } sendCancelCommand ( segmentsCopy ) ; notifyCompletion ( false ) ; } }
Cancels all the segments and marks them as finished sends a cancel command then completes the task .
21,996
public BufferSizePredictor getBufferSizePredictor ( Class < ? > type ) { MarshallingType marshallingType = typeHints . get ( type ) ; if ( marshallingType == null ) { marshallingType = new MarshallingType ( null , new AdaptiveBufferSizePredictor ( ) ) ; MarshallingType prev = typeHints . putIfAbsent ( type , marshallingType ) ; if ( prev != null ) { marshallingType = prev ; } else { if ( trace ) { log . tracef ( "Cache a buffer size predictor for '%s' assuming " + "its serializability is unknown" , type . getName ( ) ) ; } } } return marshallingType . sizePredictor ; }
Get the serialized form size predictor for a particular type .
21,997
public boolean isKnownMarshallable ( Class < ? > type ) { MarshallingType marshallingType = typeHints . get ( type ) ; return marshallingType != null && marshallingType . isMarshallable != null ; }
Returns whether the hint on whether a particular type is marshallable or not is available . This method can be used to avoid attempting to marshall a type if the hints for the type have already been calculated .
21,998
public void markMarshallable ( Class < ? > type , boolean isMarshallable ) { MarshallingType marshallType = typeHints . get ( type ) ; if ( marshallableUpdateRequired ( isMarshallable , marshallType ) ) { boolean replaced = typeHints . replace ( type , marshallType , new MarshallingType ( Boolean . valueOf ( isMarshallable ) , marshallType . sizePredictor ) ) ; if ( replaced && trace ) { log . tracef ( "Replacing '%s' type to be marshallable=%b" , type . getName ( ) , isMarshallable ) ; } } else if ( marshallType == null ) { if ( trace ) { log . tracef ( "Cache '%s' type to be marshallable=%b" , type . getName ( ) , isMarshallable ) ; } typeHints . put ( type , new MarshallingType ( Boolean . valueOf ( isMarshallable ) , new AdaptiveBufferSizePredictor ( ) ) ) ; } }
Marks a particular type as being marshallable or not being not marshallable .
21,999
public GroupsConfigurationBuilder withGroupers ( List < Grouper < ? > > groupers ) { attributes . attribute ( GROUPERS ) . set ( groupers ) ; return this ; }
Set the groupers to use