idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
21,500 | private void growSize ( ) { size ++ ; if ( size > maxSize ) { if ( keys . length == Integer . MAX_VALUE ) { throw new IllegalStateException ( "Max capacity reached at size=" + size ) ; } rehash ( keys . length << 1 ) ; } } | Grows the map size after an insertion . If necessary performs a rehash of the map . |
21,501 | private boolean removeAt ( final int index ) { -- size ; keys [ index ] = 0 ; values [ index ] = null ; int nextFree = index ; int i = probeNext ( index ) ; for ( V value = values [ i ] ; value != null ; value = values [ i = probeNext ( i ) ] ) { long key = keys [ i ] ; int bucket = hashIndex ( key ) ; if ( i < bucket && ( bucket <= nextFree || nextFree <= i ) || bucket <= nextFree && nextFree <= i ) { keys [ nextFree ] = key ; values [ nextFree ] = value ; keys [ i ] = 0 ; values [ i ] = null ; nextFree = i ; } } return nextFree != index ; } | Removes entry at the given index position . Also performs opportunistic incremental rehashing if necessary to not break conflict chains . |
21,502 | private void rehash ( int newCapacity ) { long [ ] oldKeys = keys ; V [ ] oldVals = values ; keys = new long [ newCapacity ] ; @ SuppressWarnings ( { "unchecked" , "SuspiciousArrayCast" } ) V [ ] temp = ( V [ ] ) new Object [ newCapacity ] ; values = temp ; maxSize = calcMaxSize ( newCapacity ) ; mask = newCapacity - 1 ; for ( int i = 0 ; i < oldVals . length ; ++ i ) { V oldVal = oldVals [ i ] ; if ( oldVal != null ) { long oldKey = oldKeys [ i ] ; int index = hashIndex ( oldKey ) ; for ( ; ; ) { if ( values [ index ] == null ) { keys [ index ] = oldKey ; values [ index ] = oldVal ; break ; } index = probeNext ( index ) ; } } } } | Rehashes the map for the given capacity . |
21,503 | public static long [ ] sortAndFilterThreadIdsByValue ( LongObjectMap map , int threadLimit ) { int max = Math . min ( threadLimit , map . size ( ) ) ; List < Map . Entry > list = new LinkedList ( map . entrySet ( ) ) ; Collections . sort ( list , new Comparator ( ) { public int compare ( Object o1 , Object o2 ) { return ( ( Comparable ) ( ( Map . Entry ) ( o2 ) ) . getValue ( ) ) . compareTo ( ( ( Map . Entry ) ( o1 ) ) . getValue ( ) ) ; } } ) ; long [ ] topTidArray = new long [ max ] ; int i = 0 ; for ( Map . Entry entry : list ) { topTidArray [ i ] = ( Long ) entry . getKey ( ) ; if ( ++ i >= max ) { break ; } } return topTidArray ; } | Sorts a Map by its values using natural ordering . |
21,504 | public static double calcLoad ( Long deltaCpuTime , long deltaUptime , long factor ) { if ( deltaCpuTime == null || deltaCpuTime <= 0 || deltaUptime == 0 ) { return 0.0 ; } return deltaCpuTime * 100d / factor / deltaUptime ; } | calculates a load given on two deltas |
21,505 | final void internalReset ( long initialValue ) { Cell [ ] as = cells ; base = initialValue ; if ( as != null ) { int n = as . length ; for ( int i = 0 ; i < n ; ++ i ) { Cell a = as [ i ] ; if ( a != null ) a . value = initialValue ; } } } | Sets base and all cells to the given value . |
21,506 | public static String toXml ( Object root ) { Class clazz = ClassUtil . unwrapCglib ( root ) ; return toXml ( root , clazz , null ) ; } | Java Object - > Xml without encoding . |
21,507 | public static String toXml ( Object root , Class clazz , String encoding ) { try { StringWriter writer = new StringWriter ( ) ; createMarshaller ( clazz , encoding ) . marshal ( root , writer ) ; return writer . toString ( ) ; } catch ( JAXBException e ) { throw ExceptionUtil . unchecked ( e ) ; } } | Java Object - > Xml with encoding . |
21,508 | protected Object [ ] execute ( final String hostportOrPid , final String login , final String password , final String beanname , String [ ] command , final boolean oneBeanOnly ) throws Exception { JMXConnector jmxc = connect ( hostportOrPid , login , password ) ; Object [ ] result = null ; try { MBeanServerConnection mbsc = jmxc . getMBeanServerConnection ( ) ; result = doBeans ( mbsc , getObjectName ( beanname ) , command , oneBeanOnly ) ; } finally { jmxc . close ( ) ; } return result ; } | Execute command against remote JMX agent . |
21,509 | private void clear ( long time ) { if ( time < lastTime . get ( ) + size ) { return ; } int index = ( int ) ( time % size ) ; for ( int i = 0 ; i < size ; i ++ ) { if ( i != index ) { counts . set ( i , 0 ) ; } } } | clear prev data |
21,510 | public static String rightStr ( String str , int length ) { return str . substring ( Math . max ( 0 , str . length ( ) - length ) ) ; } | Returns a substring of the given string representing the length most - right characters |
21,511 | public static String leftStr ( String str , int length ) { return str . substring ( 0 , Math . min ( str . length ( ) , length ) ) ; } | Returns a substring of the given string representing the length most - left characters |
21,512 | public static String join ( List < String > list , String delim ) { StringBuilder sb = new StringBuilder ( ) ; String loopDelim = "" ; for ( String s : list ) { sb . append ( loopDelim ) ; sb . append ( s ) ; loopDelim = delim ; } return sb . toString ( ) ; } | Joins the given list of strings using the given delimiter delim |
21,513 | public static VMInfo createDeadVM ( String pid , VMInfoState state ) { VMInfo vmInfo = new VMInfo ( ) ; vmInfo . state = state ; vmInfo . pid = pid ; return vmInfo ; } | Creates a dead VMInfo representing a jvm in a given state which cannot be attached or other monitoring issues occurred . |
21,514 | public void update ( boolean needJvmInfo ) { if ( state == VMInfoState . ERROR_DURING_ATTACH || state == VMInfoState . DETACHED ) { return ; } try { int lastJmxErrorCount = jmxUpdateErrorCount ; state = VMInfoState . ATTACHED ; jmxClient . flush ( ) ; updateUpTime ( ) ; if ( needJvmInfo ) { if ( isLinux ) { updateProcessStatus ( ) ; updateIO ( ) ; } updateCpu ( ) ; updateThreads ( ) ; updateClassLoader ( ) ; updateMemoryPool ( ) ; updateGC ( ) ; updateSafepoint ( ) ; } if ( jmxUpdateErrorCount == lastJmxErrorCount ) { jmxUpdateErrorCount = 0 ; } } catch ( Throwable e ) { e . printStackTrace ( ) ; System . out . flush ( ) ; state = VMInfoState . DETACHED ; } } | Updates all jvm metrics to the most recent remote values |
21,515 | private static void swap ( Object [ ] arr , int i , int j ) { Object tmp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = tmp ; } | Swaps the two specified elements in the specified array . |
21,516 | @ SuppressWarnings ( { "unchecked" } ) protected int compare ( E k1 , E k2 ) { if ( comparator == null ) { return ( ( Comparable ) k1 ) . compareTo ( k2 ) ; } return comparator . compare ( k1 , k2 ) ; } | Compares two keys using the correct comparison method for this collection . |
21,517 | private static void triggerGc ( Integer pid ) { VirtualMachine vm = null ; try { vm = VirtualMachine . attach ( String . valueOf ( pid ) ) ; HotSpotVirtualMachine hvm = ( HotSpotVirtualMachine ) vm ; try ( InputStream in = hvm . executeJCmd ( "GC.run" ) ; ) { byte b [ ] = new byte [ 256 ] ; int n ; do { n = in . read ( b ) ; if ( n > 0 ) { String s = new String ( b , 0 , n , "UTF-8" ) ; tty . print ( s ) ; } } while ( n > 0 ) ; tty . println ( ) ; } } catch ( Exception e ) { tty . println ( e . getMessage ( ) ) ; } finally { if ( vm != null ) { try { vm . detach ( ) ; } catch ( IOException e ) { tty . println ( e . getMessage ( ) ) ; } } } } | Trigger a remote gc using HotSpotVirtualMachine inspired by jcmd s source code . |
21,518 | private int indexOf ( int key ) { int startIndex = hashIndex ( key ) ; int index = startIndex ; for ( ; ; ) { if ( values [ index ] == null ) { return - 1 ; } if ( key == keys [ index ] ) { return index ; } if ( ( index = probeNext ( index ) ) == startIndex ) { return - 1 ; } } } | Locates the index for the given key . This method probes using double hashing . |
21,519 | private void updateErrorContainerSize ( double w , double errorContainerHeight ) { errorContainerClip . setWidth ( w ) ; errorContainerClip . setHeight ( errorContainerHeight ) ; resize ( w , errorContainerHeight ) ; } | update the size of error container and its clip |
21,520 | private KeyFrame createSmallerScaleFrame ( double errorContainerHeight ) { return new KeyFrame ( Duration . millis ( 100 ) , new KeyValue ( errorClipScale . yProperty ( ) , errorContainerHeight / getHeight ( ) , Interpolator . EASE_BOTH ) ) ; } | creates error animation frames when moving from large - > small error container |
21,521 | private KeyFrame createScaleToOneFrames ( ) { return new KeyFrame ( Duration . millis ( 100 ) , new KeyValue ( errorClipScale . yProperty ( ) , 1 , Interpolator . EASE_BOTH ) ) ; } | creates error animation frames when moving from small - > large error container |
21,522 | public void setContent ( Region content ) { if ( content != null ) { this . content = content ; this . content . setPickOnBounds ( false ) ; contentHolder . getChildren ( ) . setAll ( content ) ; } } | set the content of the dialog |
21,523 | public void close ( ) { if ( animation != null ) { animation . setRate ( - 1 ) ; animation . play ( ) ; animation . setOnFinished ( e -> { closeDialog ( ) ; } ) ; } else { setOpacity ( 0 ) ; setVisible ( false ) ; closeDialog ( ) ; } } | close the dialog |
21,524 | private void createChip ( T item ) { JFXChip < T > chip = null ; try { if ( getSkinnable ( ) . getChipFactory ( ) != null ) { chip = getSkinnable ( ) . getChipFactory ( ) . apply ( getSkinnable ( ) , item ) ; } else { chip = new JFXDefaultChip < T > ( getSkinnable ( ) , item ) ; } } catch ( Exception e ) { throw new RuntimeException ( "can't create chip for item '" + item + "' make sure to override the string converter and return null if text input is not valid." , e ) ; } int size = root . getChildren ( ) . size ( ) ; root . getChildren ( ) . add ( size - 1 , chip ) ; } | these methods are called inside the chips items change listener |
21,525 | public void cache ( ) { if ( ! isCached . getAndSet ( true ) ) { this . cache = node . isCache ( ) ; this . cacheHint = node . getCacheHint ( ) ; node . setCache ( true ) ; node . setCacheHint ( CacheHint . SPEED ) ; if ( node instanceof Region ) { this . cacheShape = ( ( Region ) node ) . isCacheShape ( ) ; this . snapToPixel = ( ( Region ) node ) . isSnapToPixel ( ) ; ( ( Region ) node ) . setCacheShape ( true ) ; ( ( Region ) node ) . setSnapToPixel ( true ) ; } } } | this method will cache the node only if it wasn t cached before |
21,526 | protected void starting ( ) { if ( mementos != null ) { for ( int i = 0 ; i < mementos . length ; i ++ ) { mementos [ i ] . cache ( ) ; } } } | Called when the animation is starting |
21,527 | protected void stopping ( ) { if ( mementos != null ) { for ( int i = 0 ; i < mementos . length ; i ++ ) { mementos [ i ] . restore ( ) ; } } } | Called when the animation is stopping |
21,528 | protected void onEval ( ) { Node control = getSrcControl ( ) ; if ( hasErrors . get ( ) ) { control . pseudoClassStateChanged ( PSEUDO_CLASS_ERROR , true ) ; if ( control instanceof Control ) { Tooltip controlTooltip = ( ( Control ) control ) . getTooltip ( ) ; if ( controlTooltip != null && ! controlTooltip . getStyleClass ( ) . contains ( "error-tooltip" ) ) { tooltip = ( ( Control ) control ) . getTooltip ( ) ; } errorTooltip . setText ( getMessage ( ) ) ; ( ( Control ) control ) . setTooltip ( errorTooltip ) ; } } else { if ( control instanceof Control ) { Tooltip controlTooltip = ( ( Control ) control ) . getTooltip ( ) ; if ( ( controlTooltip != null && controlTooltip . getStyleClass ( ) . contains ( "error-tooltip" ) ) || ( controlTooltip == null && tooltip != null ) ) { ( ( Control ) control ) . setTooltip ( tooltip ) ; } tooltip = null ; } control . pseudoClassStateChanged ( PSEUDO_CLASS_ERROR , false ) ; } } | this method will update the source control after evaluating the validation condition |
21,529 | private void scanAllNodes ( Parent parent , PseudoClass pseudoClass ) { parent . getChildrenUnmodifiable ( ) . addListener ( new ListChangeListener < Node > ( ) { public void onChanged ( javafx . collections . ListChangeListener . Change < ? extends Node > c ) { while ( c . next ( ) ) { if ( ! c . wasPermutated ( ) && ! c . wasUpdated ( ) ) { for ( Node addedNode : c . getAddedSubList ( ) ) { if ( addedNode instanceof Parent ) { scanAllNodes ( ( Parent ) addedNode , pseudoClass ) ; } } } } } } ) ; for ( Node component : parent . getChildrenUnmodifiable ( ) ) { if ( component instanceof Pane ) { ( ( Pane ) component ) . getChildren ( ) . addListener ( new ListChangeListener < Node > ( ) { public void onChanged ( javafx . collections . ListChangeListener . Change < ? extends Node > c ) { while ( c . next ( ) ) { if ( ! c . wasPermutated ( ) && ! c . wasUpdated ( ) ) { for ( Node addedNode : c . getAddedSubList ( ) ) { if ( addedNode instanceof Parent ) { scanAllNodes ( ( Parent ) addedNode , pseudoClass ) ; } } } } } } ) ; scanAllNodes ( ( Pane ) component , pseudoClass ) ; } else if ( component instanceof ScrollPane ) { ( ( ScrollPane ) component ) . contentProperty ( ) . addListener ( ( o , oldVal , newVal ) -> { scanAllNodes ( ( Parent ) newVal , pseudoClass ) ; } ) ; if ( ( ( ScrollPane ) component ) . getContent ( ) instanceof Parent ) { scanAllNodes ( ( Parent ) ( ( ScrollPane ) component ) . getContent ( ) , pseudoClass ) ; } } else if ( component instanceof Control ) { component . pseudoClassStateChanged ( PSEUDO_CLASS_EX_SMALL , pseudoClass == PSEUDO_CLASS_EX_SMALL ) ; component . pseudoClassStateChanged ( PSEUDO_CLASS_SMALL , pseudoClass == PSEUDO_CLASS_SMALL ) ; component . pseudoClassStateChanged ( PSEUDO_CLASS_MEDIUM , pseudoClass == PSEUDO_CLASS_MEDIUM ) ; component . pseudoClassStateChanged ( PSEUDO_CLASS_LARGE , pseudoClass == PSEUDO_CLASS_LARGE ) ; } } } | scans all nodes in the scene and apply the css pseduoClass to them . |
21,530 | public void updateSelection ( Color color ) { setFocusedSquare ( null ) ; for ( ColorSquare c : colorPickerGrid . getSquares ( ) ) { if ( c . rectangle . getFill ( ) . equals ( color ) ) { setFocusedSquare ( c ) ; return ; } } for ( Node n : customColorGrid . getChildren ( ) ) { ColorSquare c = ( ColorSquare ) n ; if ( c . rectangle . getFill ( ) . equals ( color ) ) { setFocusedSquare ( c ) ; return ; } } } | The skin can update selection if colorpicker value changes .. |
21,531 | private JFXAlertAnimation getCurrentAnimation ( ) { JFXAlertAnimation usedAnimation = getAnimation ( ) ; usedAnimation = usedAnimation == null ? JFXAlertAnimation . NO_ANIMATION : usedAnimation ; return usedAnimation ; } | this method ensure not null value for current animation |
21,532 | public void hideWithAnimation ( ) { if ( transition == null || transition . getStatus ( ) . equals ( Animation . Status . STOPPED ) ) { JFXAlertAnimation currentAnimation = getCurrentAnimation ( ) ; Animation animation = currentAnimation . createHidingAnimation ( getDialogPane ( ) . getContent ( ) , getDialogPane ( ) ) ; if ( animation != null ) { transition = animation ; animation . setOnFinished ( finish -> { animateClosing = false ; hide ( ) ; transition = null ; } ) ; animation . play ( ) ; } else { animateClosing = false ; transition = null ; Platform . runLater ( this :: hide ) ; } } } | play the hide animation for the dialog as the java hide method is set to final so it can not be overridden |
21,533 | public final Node getDisclosureNode ( ) { if ( disclosureNode . get ( ) == null ) { final StackPane disclosureNode = new StackPane ( ) ; disclosureNode . getStyleClass ( ) . setAll ( "tree-disclosure-node" ) ; disclosureNode . setMouseTransparent ( true ) ; final StackPane disclosureNodeArrow = new StackPane ( ) ; disclosureNodeArrow . getStyleClass ( ) . setAll ( "arrow" ) ; disclosureNode . getChildren ( ) . add ( disclosureNodeArrow ) ; setDisclosureNode ( disclosureNode ) ; } return disclosureNode . get ( ) ; } | Returns the current disclosure node set in this cell . |
21,534 | protected void positionControl ( Node control ) { if ( this . position . get ( ) == RipplerPos . BACK ) { getChildren ( ) . add ( control ) ; } else { getChildren ( ) . add ( 0 , control ) ; } } | Override this method to create JFXRippler for a control outside the ripple |
21,535 | protected Node getMask ( ) { double borderWidth = ripplerPane . getBorder ( ) != null ? ripplerPane . getBorder ( ) . getInsets ( ) . getTop ( ) : 0 ; Bounds bounds = control . getBoundsInParent ( ) ; double width = control . getLayoutBounds ( ) . getWidth ( ) ; double height = control . getLayoutBounds ( ) . getHeight ( ) ; double diffMinX = Math . abs ( control . getBoundsInLocal ( ) . getMinX ( ) - control . getLayoutBounds ( ) . getMinX ( ) ) ; double diffMinY = Math . abs ( control . getBoundsInLocal ( ) . getMinY ( ) - control . getLayoutBounds ( ) . getMinY ( ) ) ; double diffMaxX = Math . abs ( control . getBoundsInLocal ( ) . getMaxX ( ) - control . getLayoutBounds ( ) . getMaxX ( ) ) ; double diffMaxY = Math . abs ( control . getBoundsInLocal ( ) . getMaxY ( ) - control . getLayoutBounds ( ) . getMaxY ( ) ) ; Node mask ; switch ( getMaskType ( ) ) { case RECT : mask = new Rectangle ( bounds . getMinX ( ) + diffMinX - snappedLeftInset ( ) , bounds . getMinY ( ) + diffMinY - snappedTopInset ( ) , width - 2 * borderWidth , height - 2 * borderWidth ) ; break ; case CIRCLE : double radius = Math . min ( ( width / 2 ) - 2 * borderWidth , ( height / 2 ) - 2 * borderWidth ) ; mask = new Circle ( ( bounds . getMinX ( ) + diffMinX + bounds . getMaxX ( ) - diffMaxX ) / 2 - snappedLeftInset ( ) , ( bounds . getMinY ( ) + diffMinY + bounds . getMaxY ( ) - diffMaxY ) / 2 - snappedTopInset ( ) , radius , Color . BLUE ) ; break ; case FIT : mask = new Region ( ) ; if ( control instanceof Shape ) { ( ( Region ) mask ) . setShape ( ( Shape ) control ) ; } else if ( control instanceof Region ) { ( ( Region ) mask ) . setShape ( ( ( Region ) control ) . getShape ( ) ) ; JFXNodeUtils . updateBackground ( ( ( Region ) control ) . getBackground ( ) , ( Region ) mask ) ; } mask . resize ( width , height ) ; mask . relocate ( bounds . getMinX ( ) + diffMinX , bounds . getMinY ( ) + diffMinY ) ; break ; default : mask = new Rectangle ( bounds . getMinX ( ) + diffMinX - snappedLeftInset ( ) , bounds . getMinY ( ) + diffMinY - snappedTopInset ( ) , width - 2 * borderWidth , height - 2 * borderWidth ) ; break ; } return mask ; } | generate the clipping mask |
21,536 | protected double computeRippleRadius ( ) { double width2 = control . getLayoutBounds ( ) . getWidth ( ) * control . getLayoutBounds ( ) . getWidth ( ) ; double height2 = control . getLayoutBounds ( ) . getHeight ( ) * control . getLayoutBounds ( ) . getHeight ( ) ; return Math . min ( Math . sqrt ( width2 + height2 ) , RIPPLE_MAX_RADIUS ) * 1.1 + 5 ; } | compute the ripple radius |
21,537 | protected void initControlListeners ( ) { control . layoutBoundsProperty ( ) . addListener ( observable -> resetRippler ( ) ) ; if ( getChildren ( ) . contains ( control ) ) control . boundsInParentProperty ( ) . addListener ( observable -> resetRippler ( ) ) ; control . addEventHandler ( MouseEvent . MOUSE_PRESSED , ( event ) -> createRipple ( event . getX ( ) , event . getY ( ) ) ) ; control . addEventHandler ( MouseEvent . MOUSE_RELEASED , e -> releaseRipple ( ) ) ; } | init mouse listeners on the control |
21,538 | protected void createRipple ( double x , double y ) { if ( ! isRipplerDisabled ( ) ) { rippler . setGeneratorCenterX ( x ) ; rippler . setGeneratorCenterY ( y ) ; rippler . createRipple ( ) ; } } | creates Ripple effect |
21,539 | public Runnable createManualRipple ( ) { if ( ! isRipplerDisabled ( ) ) { rippler . setGeneratorCenterX ( control . getLayoutBounds ( ) . getWidth ( ) / 2 ) ; rippler . setGeneratorCenterY ( control . getLayoutBounds ( ) . getHeight ( ) / 2 ) ; rippler . createRipple ( ) ; return ( ) -> { releaseRipple ( ) ; } ; } return ( ) -> { } ; } | creates Ripple effect in the center of the control |
21,540 | public void reverseAndContinue ( ) { if ( isRunning ( ) ) { super . stop ( ) ; for ( AnimationHandler handler : animationHandlers ) { handler . reverse ( totalElapsedMilliseconds ) ; } startTime = - 1 ; super . start ( ) ; } else { start ( ) ; } } | this method will pause the timer and reverse the animation if the timer already started otherwise it will start the animation . |
21,541 | protected TableColumnHeader createTableColumnHeader ( TableColumnBase col ) { return col . getColumns ( ) . isEmpty ( ) ? new JFXTableColumnHeader ( getTableViewSkin ( ) , col ) : new NestedTableColumnHeader ( getTableViewSkin ( ) , col ) ; } | protected to allow subclasses to customise the column header types |
21,542 | public void show ( Node node , PopupVPosition vAlign , PopupHPosition hAlign ) { this . show ( node , vAlign , hAlign , 0 , 0 ) ; } | show the popup according to the specified position |
21,543 | public void show ( Node node , PopupVPosition vAlign , PopupHPosition hAlign , double initOffsetX , double initOffsetY ) { if ( ! isShowing ( ) ) { if ( node . getScene ( ) == null || node . getScene ( ) . getWindow ( ) == null ) { throw new IllegalStateException ( "Can not show popup. The node must be attached to a scene/window." ) ; } Window parent = node . getScene ( ) . getWindow ( ) ; final Point2D origin = node . localToScene ( 0 , 0 ) ; final double anchorX = parent . getX ( ) + origin . getX ( ) + node . getScene ( ) . getX ( ) + ( hAlign == PopupHPosition . RIGHT ? ( ( Region ) node ) . getWidth ( ) : 0 ) ; final double anchorY = parent . getY ( ) + origin . getY ( ) + node . getScene ( ) . getY ( ) + ( vAlign == PopupVPosition . BOTTOM ? ( ( Region ) node ) . getHeight ( ) : 0 ) ; this . show ( parent , anchorX , anchorY ) ; ( ( JFXPopupSkin ) getSkin ( ) ) . reset ( vAlign , hAlign , initOffsetX , initOffsetY ) ; Platform . runLater ( ( ) -> ( ( JFXPopupSkin ) getSkin ( ) ) . animate ( ) ) ; } } | show the popup according to the specified position with a certain offset |
21,544 | public void group ( TreeTableColumn < S , ? > ... treeTableColumns ) { try { lock . lock ( ) ; if ( groupOrder . size ( ) == 0 ) { groups = new HashMap < > ( ) ; } try { if ( originalRoot == null ) { originalRoot = getRoot ( ) ; } for ( TreeTableColumn < S , ? > treeTableColumn : treeTableColumns ) { if ( groupOrder . contains ( treeTableColumn ) ) { continue ; } groups = group ( treeTableColumn , groups , null , ( RecursiveTreeItem < S > ) originalRoot ) ; } groupOrder . addAll ( treeTableColumns ) ; buildGroupedRoot ( groups , null , 0 ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } finally { lock . unlock ( ) ; } } | this is a blocking method so it should not be called from the ui thread it will regroup the tree table view |
21,545 | public void unGroup ( TreeTableColumn < S , ? > ... treeTableColumns ) { try { lock . lock ( ) ; if ( groupOrder . size ( ) > 0 ) { groupOrder . removeAll ( treeTableColumns ) ; List < TreeTableColumn < S , ? > > grouped = new ArrayList < > ( ) ; grouped . addAll ( groupOrder ) ; groupOrder . clear ( ) ; JFXUtilities . runInFXAndWait ( ( ) -> { ArrayList < TreeTableColumn < S , ? > > sortOrder = new ArrayList < > ( ) ; sortOrder . addAll ( getSortOrder ( ) ) ; List children = Arrays . asList ( originalRoot . getChildren ( ) . toArray ( ) ) ; originalRoot . getChildren ( ) . clear ( ) ; originalRoot . getChildren ( ) . setAll ( children ) ; internalSetRoot = true ; setRoot ( originalRoot ) ; internalSetRoot = false ; getSelectionModel ( ) . select ( 0 ) ; getSortOrder ( ) . addAll ( sortOrder ) ; if ( grouped . size ( ) != 0 ) { refreshGroups ( grouped ) ; } } ) ; } } finally { lock . unlock ( ) ; } } | this is a blocking method so it should not be called from the ui thread it will ungroup the tree table view |
21,546 | private void filter ( Predicate < TreeItem < S > > predicate ) { if ( task != null ) { task . cancel ( false ) ; } task = threadPool . schedule ( filterRunnable , 200 , TimeUnit . MILLISECONDS ) ; } | this method will filter the tree table |
21,547 | public static void runInFX ( Runnable doRun ) { if ( Platform . isFxApplicationThread ( ) ) { doRun . run ( ) ; return ; } Platform . runLater ( doRun ) ; } | This method is used to run a specified Runnable in the FX Application thread it returns before the task finished execution |
21,548 | public static void runInFXAndWait ( Runnable doRun ) { if ( Platform . isFxApplicationThread ( ) ) { doRun . run ( ) ; return ; } final CountDownLatch doneLatch = new CountDownLatch ( 1 ) ; Platform . runLater ( ( ) -> { try { doRun . run ( ) ; } finally { doneLatch . countDown ( ) ; } } ) ; try { doneLatch . await ( ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; } } | This method is used to run a specified Runnable in the FX Application thread it waits for the task to finish before returning to the main thread . |
21,549 | public void setSize ( double width , double height ) { this . setMinSize ( StackPane . USE_PREF_SIZE , StackPane . USE_PREF_SIZE ) ; this . setPrefSize ( width , height ) ; this . setMaxSize ( StackPane . USE_PREF_SIZE , StackPane . USE_PREF_SIZE ) ; } | resize the svg to a certain width and height |
21,550 | public synchronized void highlight ( Parent pane , String query ) { if ( this . parent != null && ! boxes . isEmpty ( ) ) { clear ( ) ; } if ( query == null || query . isEmpty ( ) ) return ; this . parent = pane ; Set < Node > nodes = getTextNodes ( pane ) ; ArrayList < Rectangle > allRectangles = new ArrayList < > ( ) ; for ( Node node : nodes ) { Text text = ( ( Text ) node ) ; final int beginIndex = text . getText ( ) . toLowerCase ( ) . indexOf ( query . toLowerCase ( ) ) ; if ( beginIndex > - 1 && node . impl_isTreeVisible ( ) ) { ArrayList < Bounds > boundingBoxes = getMatchingBounds ( query , text ) ; ArrayList < Rectangle > rectangles = new ArrayList < > ( ) ; for ( Bounds boundingBox : boundingBoxes ) { HighLightRectangle rect = new HighLightRectangle ( text ) ; rect . setCacheHint ( CacheHint . SPEED ) ; rect . setCache ( true ) ; rect . setMouseTransparent ( true ) ; rect . setBlendMode ( BlendMode . MULTIPLY ) ; rect . fillProperty ( ) . bind ( paintProperty ( ) ) ; rect . setManaged ( false ) ; rect . setX ( boundingBox . getMinX ( ) ) ; rect . setY ( boundingBox . getMinY ( ) ) ; rect . setWidth ( boundingBox . getWidth ( ) ) ; rect . setHeight ( boundingBox . getHeight ( ) ) ; rectangles . add ( rect ) ; allRectangles . add ( rect ) ; } boxes . put ( node , rectangles ) ; } } Platform . runLater ( ( ) -> getParentChildren ( pane ) . addAll ( allRectangles ) ) ; } | highlights the matching text in the specified pane |
21,551 | public static SVGGlyph getIcoMoonGlyph ( String glyphName ) throws Exception { SVGGlyphBuilder builder = glyphsMap . get ( glyphName ) ; if ( builder == null ) throw new Exception ( "Glyph '" + glyphName + "' not found!" ) ; SVGGlyph glyph = builder . build ( ) ; glyph . getTransforms ( ) . add ( new Scale ( 1 , - 1 ) ) ; Translate height = new Translate ( ) ; height . yProperty ( ) . bind ( Bindings . createDoubleBinding ( ( ) -> - glyph . getHeight ( ) , glyph . heightProperty ( ) ) ) ; glyph . getTransforms ( ) . add ( height ) ; return glyph ; } | will retrieve icons from the glyphs map for a certain glyphName |
21,552 | public static void loadGlyphsFont ( InputStream stream , String keyPrefix ) throws IOException { try { DocumentBuilderFactory docFactory = DocumentBuilderFactory . newInstance ( ) ; DocumentBuilder docBuilder = docFactory . newDocumentBuilder ( ) ; docBuilder . setEntityResolver ( ( publicId , systemId ) -> { return new InputSource ( new StringReader ( "" ) ) ; } ) ; Document doc = docBuilder . parse ( stream ) ; doc . getDocumentElement ( ) . normalize ( ) ; NodeList glyphsList = doc . getElementsByTagName ( "glyph" ) ; for ( int i = 0 ; i < glyphsList . getLength ( ) ; i ++ ) { Node glyph = glyphsList . item ( i ) ; Node glyphName = glyph . getAttributes ( ) . getNamedItem ( "glyph-name" ) ; if ( glyphName == null ) { continue ; } String glyphId = glyphName . getNodeValue ( ) ; SVGGlyphBuilder glyphPane = new SVGGlyphBuilder ( i , glyphId , glyph . getAttributes ( ) . getNamedItem ( "d" ) . getNodeValue ( ) ) ; glyphsMap . put ( keyPrefix + "." + glyphId , glyphPane ) ; } stream . close ( ) ; } catch ( ParserConfigurationException | SAXException e ) { e . printStackTrace ( ) ; } } | will load SVG icons from input stream |
21,553 | public static SVGGlyph loadGlyph ( URL url ) throws IOException { String urlString = url . toString ( ) ; String filename = urlString . substring ( urlString . lastIndexOf ( '/' ) + 1 ) ; int startPos = 0 ; int endPos = 0 ; while ( endPos < filename . length ( ) && filename . charAt ( endPos ) != '-' ) { endPos ++ ; } int id = Integer . parseInt ( filename . substring ( startPos , endPos ) ) ; startPos = endPos + 1 ; while ( endPos < filename . length ( ) && filename . charAt ( endPos ) != '.' ) { endPos ++ ; } String name = filename . substring ( startPos , endPos ) ; return new SVGGlyph ( id , name , extractSvgPath ( getStringFromInputStream ( url . openStream ( ) ) ) , Color . BLACK ) ; } | load a single svg icon from a file |
21,554 | private boolean checkGroupedColumn ( ) { boolean allowEdit = true ; if ( getTreeTableRow ( ) . getTreeItem ( ) != null ) { Object rowObject = getTreeTableRow ( ) . getTreeItem ( ) . getValue ( ) ; if ( rowObject instanceof RecursiveTreeObject && rowObject . getClass ( ) == RecursiveTreeObject . class ) { allowEdit = false ; } else { if ( getTableColumn ( ) instanceof JFXTreeTableColumn && ( ( JFXTreeTableColumn ) getTableColumn ( ) ) . isGrouped ( ) ) { if ( getTreeTableRow ( ) . getTreeItem ( ) . getParent ( ) != null && getTreeTableRow ( ) . getTreeItem ( ) . getParent ( ) . getValue ( ) . getClass ( ) == RecursiveTreeObject . class ) { allowEdit = false ; } } } } return allowEdit ; } | only allows editing for items that are not grouped |
21,555 | public static void registerMXBean ( Cache < ? , ? > cache , Object mxbean , MBeanType type ) { ObjectName objectName = getObjectName ( cache , type ) ; register ( objectName , mxbean ) ; } | Registers the JMX management bean for the cache . |
21,556 | public static void unregisterMXBean ( CacheProxy < ? , ? > cache , MBeanType type ) { ObjectName objectName = getObjectName ( cache , type ) ; unregister ( objectName ) ; } | Unregisters the JMX management bean for the cache . |
21,557 | private static void register ( ObjectName objectName , Object mbean ) { MBeanServer server = ManagementFactory . getPlatformMBeanServer ( ) ; try { if ( ! server . isRegistered ( objectName ) ) { server . registerMBean ( mbean , objectName ) ; } } catch ( InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e ) { throw new CacheException ( "Error registering " + objectName , e ) ; } } | Registers the management bean with the given object name . |
21,558 | private static ObjectName getObjectName ( Cache < ? , ? > cache , MBeanType type ) { String cacheManagerName = sanitize ( cache . getCacheManager ( ) . getURI ( ) . toString ( ) ) ; String cacheName = sanitize ( cache . getName ( ) ) ; try { String name = String . format ( "javax.cache:type=Cache%s,CacheManager=%s,Cache=%s" , type , cacheManagerName , cacheName ) ; return new ObjectName ( name ) ; } catch ( MalformedObjectNameException e ) { String msg = String . format ( "Illegal ObjectName for cacheManager=[%s], cache=[%s]" , cacheManagerName , cacheName ) ; throw new CacheException ( msg , e ) ; } } | Returns the object name of the management bean . |
21,559 | private static boolean canBulkLoad ( AsyncCacheLoader < ? , ? > loader ) { try { Class < ? > defaultLoaderClass = AsyncCacheLoader . class ; if ( loader instanceof CacheLoader < ? , ? > ) { defaultLoaderClass = CacheLoader . class ; Method classLoadAll = loader . getClass ( ) . getMethod ( "loadAll" , Iterable . class ) ; Method defaultLoadAll = CacheLoader . class . getMethod ( "loadAll" , Iterable . class ) ; if ( ! classLoadAll . equals ( defaultLoadAll ) ) { return true ; } } Method classAsyncLoadAll = loader . getClass ( ) . getMethod ( "asyncLoadAll" , Iterable . class , Executor . class ) ; Method defaultAsyncLoadAll = defaultLoaderClass . getMethod ( "asyncLoadAll" , Iterable . class , Executor . class ) ; return ! classAsyncLoadAll . equals ( defaultAsyncLoadAll ) ; } catch ( NoSuchMethodException | SecurityException e ) { logger . log ( Level . WARNING , "Cannot determine if CacheLoader can bulk load" , e ) ; return false ; } } | Returns whether the supplied cache loader has bulk load functionality . |
21,560 | static int index ( ) { int probe = UnsafeAccess . UNSAFE . getInt ( Thread . currentThread ( ) , PROBE ) ; if ( probe == 0 ) { ThreadLocalRandom . current ( ) ; probe = UnsafeAccess . UNSAFE . getInt ( Thread . currentThread ( ) , PROBE ) ; } return ( probe & ARENA_MASK ) ; } | Returns the arena index for the current thread . |
21,561 | private void onWindowHit ( Node node ) { admittor . record ( node . key ) ; node . moveToTail ( headWindow ) ; } | Moves the entry to the MRU position in the admission window . |
21,562 | private void onProtectedHit ( Node node ) { admittor . record ( node . key ) ; node . moveToTail ( headProtected ) ; } | Moves the entry to the MRU position if it falls outside of the fast - path threshold . |
21,563 | protected final MethodSpec newGetRef ( String varName ) { MethodSpec . Builder getter = MethodSpec . methodBuilder ( "get" + capitalize ( varName ) + "Reference" ) . addModifiers ( context . publicFinalModifiers ( ) ) . returns ( Object . class ) ; getter . addStatement ( "return $T.UNSAFE.getObject(this, $N)" , UNSAFE_ACCESS , offsetName ( varName ) ) ; return getter . build ( ) ; } | Creates an accessor that returns the reference . |
21,564 | protected final MethodSpec newGetter ( Strength strength , TypeName varType , String varName , Visibility visibility ) { MethodSpec . Builder getter = MethodSpec . methodBuilder ( "get" + capitalize ( varName ) ) . addModifiers ( context . publicFinalModifiers ( ) ) . returns ( varType ) ; String type ; if ( varType . isPrimitive ( ) ) { type = varType . equals ( TypeName . INT ) ? "Int" : "Long" ; } else { type = "Object" ; } if ( strength == Strength . STRONG ) { if ( visibility . isRelaxed ) { if ( varType . isPrimitive ( ) ) { getter . addStatement ( "return $T.UNSAFE.get$N(this, $N)" , UNSAFE_ACCESS , type , offsetName ( varName ) ) ; } else { getter . addStatement ( "return ($T) $T.UNSAFE.get$N(this, $N)" , varType , UNSAFE_ACCESS , type , offsetName ( varName ) ) ; } } else { getter . addStatement ( "return $N" , varName ) ; } } else { if ( visibility . isRelaxed ) { getter . addStatement ( "return (($T<$T>) $T.UNSAFE.get$N(this, $N)).get()" , Reference . class , varType , UNSAFE_ACCESS , type , offsetName ( varName ) ) ; } else { getter . addStatement ( "return $N.get()" , varName ) ; } } return getter . build ( ) ; } | Creates an accessor that returns the unwrapped variable . |
21,565 | protected final MethodSpec newSetter ( TypeName varType , String varName , Visibility visibility ) { String methodName = "set" + Character . toUpperCase ( varName . charAt ( 0 ) ) + varName . substring ( 1 ) ; String type ; if ( varType . isPrimitive ( ) ) { type = varType . equals ( TypeName . INT ) ? "Int" : "Long" ; } else { type = "Object" ; } MethodSpec . Builder setter = MethodSpec . methodBuilder ( methodName ) . addModifiers ( context . publicFinalModifiers ( ) ) . addParameter ( varType , varName ) ; if ( visibility . isRelaxed ) { setter . addStatement ( "$T.UNSAFE.put$L(this, $N, $N)" , UNSAFE_ACCESS , type , offsetName ( varName ) , varName ) ; } else { setter . addStatement ( "this.$N = $N" , varName , varName ) ; } return setter . build ( ) ; } | Creates a mutator to the variable . |
21,566 | private void add ( Node node ) { evict ( ) ; if ( handHot == null ) { handHot = handCold = handTest = node ; node . next = node . prev = node ; } else { node . prev = handHot ; node . next = handHot . next ; handHot . next . prev = node ; handHot . next = node ; } if ( handCold == handHot ) { handCold = node . next ; } if ( handTest == handHot ) { handTest = node . next ; } handHot = node . next ; } | Add meta data after hand hot evict data if required and update hands accordingly . |
21,567 | private void delete ( Node node ) { if ( handHot == node ) { handHot = node . next ; } if ( handCold == node ) { handCold = node . next ; } if ( handTest == node ) { handTest = node . next ; } node . remove ( ) ; } | Delete meta data data update hands accordingly . |
21,568 | private void scanHot ( ) { if ( handHot == handTest ) { scanTest ( ) ; } if ( handHot . status == Status . HOT ) { if ( handHot . marked ) { handHot . marked = false ; } else { handHot . status = Status . COLD ; sizeCold ++ ; sizeHot -- ; } } handHot = handHot . next ; } | Moves the hot hand forward . |
21,569 | public static long objectFieldOffset ( Class < ? > clazz , String fieldName ) { try { return UNSAFE . objectFieldOffset ( clazz . getDeclaredField ( fieldName ) ) ; } catch ( NoSuchFieldException | SecurityException e ) { throw new Error ( e ) ; } } | Returns the location of a given static field . |
21,570 | void regularIncrement ( long e ) { int hash = spread ( Long . hashCode ( e ) ) ; int start = ( hash & 3 ) << 2 ; int index0 = indexOf ( hash , 0 ) ; int index1 = indexOf ( hash , 1 ) ; int index2 = indexOf ( hash , 2 ) ; int index3 = indexOf ( hash , 3 ) ; boolean added = incrementAt ( index0 , start , step ) ; added |= incrementAt ( index1 , start + 1 , step ) ; added |= incrementAt ( index2 , start + 2 , step ) ; added |= incrementAt ( index3 , start + 3 , step ) ; tryReset ( added ) ; } | Increments all of the associated counters . |
21,571 | void conservativeIncrement ( long e ) { int hash = spread ( Long . hashCode ( e ) ) ; int start = ( hash & 3 ) << 2 ; int [ ] index = new int [ 4 ] ; int [ ] count = new int [ 4 ] ; int min = Integer . MAX_VALUE ; for ( int i = 0 ; i < 4 ; i ++ ) { index [ i ] = indexOf ( hash , i ) ; count [ i ] = ( int ) ( ( table [ index [ i ] ] >>> ( ( start + i ) << 2 ) ) & 0xfL ) ; min = Math . min ( min , count [ i ] ) ; } if ( min == 15 ) { tryReset ( false ) ; return ; } for ( int i = 0 ; i < 4 ; i ++ ) { if ( count [ i ] == min ) { incrementAt ( index [ i ] , start + i , step ) ; } } tryReset ( true ) ; } | Increments the associated counters that are at the observed minimum . |
21,572 | int spread ( int x ) { x = ( ( x >>> 16 ) ^ x ) * 0x45d9f3b ; x = ( ( x >>> 16 ) ^ x ) * 0x45d9f3b ; return ( x >>> 16 ) ^ x ; } | Applies a supplemental hash function to a given hashCode which defends against poor quality hash functions . |
21,573 | protected Map < K , Expirable < V > > getAndFilterExpiredEntries ( Set < ? extends K > keys , boolean updateAccessTime ) { Map < K , Expirable < V > > result = new HashMap < > ( cache . getAllPresent ( keys ) ) ; int [ ] expired = { 0 } ; long [ ] millis = { 0L } ; result . entrySet ( ) . removeIf ( entry -> { if ( ! entry . getValue ( ) . isEternal ( ) && ( millis [ 0 ] == 0L ) ) { millis [ 0 ] = currentTimeMillis ( ) ; } if ( entry . getValue ( ) . hasExpired ( millis [ 0 ] ) ) { cache . asMap ( ) . computeIfPresent ( entry . getKey ( ) , ( k , expirable ) -> { if ( expirable == entry . getValue ( ) ) { dispatcher . publishExpired ( this , entry . getKey ( ) , entry . getValue ( ) . get ( ) ) ; expired [ 0 ] ++ ; return null ; } return expirable ; } ) ; return true ; } if ( updateAccessTime ) { setAccessExpirationTime ( entry . getValue ( ) , millis [ 0 ] ) ; } return false ; } ) ; statistics . recordHits ( result . size ( ) ) ; statistics . recordMisses ( keys . size ( ) - result . size ( ) ) ; statistics . recordEvictions ( expired [ 0 ] ) ; return result ; } | Returns all of the mappings present expiring as required and optionally updates their access expiry time . |
21,574 | private void loadAllAndReplaceExisting ( Set < ? extends K > keys ) { int [ ] ignored = { 0 } ; Map < K , V > loaded = cacheLoader . get ( ) . loadAll ( keys ) ; for ( Map . Entry < ? extends K , ? extends V > entry : loaded . entrySet ( ) ) { putNoCopyOrAwait ( entry . getKey ( ) , entry . getValue ( ) , false , ignored ) ; } } | Performs the bulk load where the existing entries are replace . |
21,575 | private void loadAllAndKeepExisting ( Set < ? extends K > keys ) { List < K > keysToLoad = keys . stream ( ) . filter ( key -> ! cache . asMap ( ) . containsKey ( key ) ) . collect ( toList ( ) ) ; Map < K , V > result = cacheLoader . get ( ) . loadAll ( keysToLoad ) ; for ( Map . Entry < K , V > entry : result . entrySet ( ) ) { if ( ( entry . getKey ( ) != null ) && ( entry . getValue ( ) != null ) ) { putIfAbsentNoAwait ( entry . getKey ( ) , entry . getValue ( ) , false ) ; } } } | Performs the bulk load where the existing entries are retained . |
21,576 | protected V putNoCopyOrAwait ( K key , V value , boolean publishToWriter , int [ ] puts ) { requireNonNull ( key ) ; requireNonNull ( value ) ; @ SuppressWarnings ( "unchecked" ) V [ ] replaced = ( V [ ] ) new Object [ 1 ] ; cache . asMap ( ) . compute ( copyOf ( key ) , ( k , expirable ) -> { V newValue = copyOf ( value ) ; if ( publishToWriter && configuration . isWriteThrough ( ) ) { publishToCacheWriter ( writer :: write , ( ) -> new EntryProxy < > ( key , value ) ) ; } if ( ( expirable != null ) && ! expirable . isEternal ( ) && expirable . hasExpired ( currentTimeMillis ( ) ) ) { dispatcher . publishExpired ( this , key , expirable . get ( ) ) ; statistics . recordEvictions ( 1L ) ; expirable = null ; } long expireTimeMS = getWriteExpireTimeMS ( ( expirable == null ) ) ; if ( ( expirable != null ) && ( expireTimeMS == Long . MIN_VALUE ) ) { expireTimeMS = expirable . getExpireTimeMS ( ) ; } if ( expireTimeMS == 0 ) { replaced [ 0 ] = ( expirable == null ) ? null : expirable . get ( ) ; return null ; } else if ( expirable == null ) { dispatcher . publishCreated ( this , key , newValue ) ; } else { replaced [ 0 ] = expirable . get ( ) ; dispatcher . publishUpdated ( this , key , expirable . get ( ) , newValue ) ; } puts [ 0 ] ++ ; return new Expirable < > ( newValue , expireTimeMS ) ; } ) ; return replaced [ 0 ] ; } | Associates the specified value with the specified key in the cache . |
21,577 | private boolean putIfAbsentNoAwait ( K key , V value , boolean publishToWriter ) { boolean [ ] absent = { false } ; cache . asMap ( ) . compute ( copyOf ( key ) , ( k , expirable ) -> { if ( ( expirable != null ) && ! expirable . isEternal ( ) && expirable . hasExpired ( currentTimeMillis ( ) ) ) { dispatcher . publishExpired ( this , key , expirable . get ( ) ) ; statistics . recordEvictions ( 1L ) ; expirable = null ; } if ( expirable != null ) { return expirable ; } absent [ 0 ] = true ; long expireTimeMS = getWriteExpireTimeMS ( true ) ; if ( expireTimeMS == 0 ) { return null ; } if ( publishToWriter ) { publishToCacheWriter ( writer :: write , ( ) -> new EntryProxy < > ( key , value ) ) ; } V copy = copyOf ( value ) ; dispatcher . publishCreated ( this , key , copy ) ; return new Expirable < > ( copy , expireTimeMS ) ; } ) ; return absent [ 0 ] ; } | Associates the specified value with the specified key in the cache if there is no existing mapping . |
21,578 | private V removeNoCopyOrAwait ( K key ) { @ SuppressWarnings ( "unchecked" ) V [ ] removed = ( V [ ] ) new Object [ 1 ] ; cache . asMap ( ) . computeIfPresent ( key , ( k , expirable ) -> { if ( ! expirable . isEternal ( ) && expirable . hasExpired ( currentTimeMillis ( ) ) ) { dispatcher . publishExpired ( this , key , expirable . get ( ) ) ; statistics . recordEvictions ( 1L ) ; return null ; } dispatcher . publishRemoved ( this , key , expirable . get ( ) ) ; removed [ 0 ] = expirable . get ( ) ; return null ; } ) ; return removed [ 0 ] ; } | Removes the mapping from the cache without store - by - value copying nor waiting for synchronous listeners to complete . |
21,579 | private V replaceNoCopyOrAwait ( K key , V value ) { requireNonNull ( value ) ; V copy = copyOf ( value ) ; @ SuppressWarnings ( "unchecked" ) V [ ] replaced = ( V [ ] ) new Object [ 1 ] ; cache . asMap ( ) . computeIfPresent ( key , ( k , expirable ) -> { if ( ! expirable . isEternal ( ) && expirable . hasExpired ( currentTimeMillis ( ) ) ) { dispatcher . publishExpired ( this , key , expirable . get ( ) ) ; statistics . recordEvictions ( 1L ) ; return null ; } publishToCacheWriter ( writer :: write , ( ) -> new EntryProxy < > ( key , value ) ) ; long expireTimeMS = getWriteExpireTimeMS ( false ) ; if ( expireTimeMS == Long . MIN_VALUE ) { expireTimeMS = expirable . getExpireTimeMS ( ) ; } dispatcher . publishUpdated ( this , key , expirable . get ( ) , copy ) ; replaced [ 0 ] = expirable . get ( ) ; return new Expirable < > ( copy , expireTimeMS ) ; } ) ; return replaced [ 0 ] ; } | Replaces the entry for the specified key only if it is currently mapped to some value . The entry is not store - by - value copied nor does the method wait for synchronous listeners to complete . |
21,580 | @ SuppressWarnings ( { "fallthrough" , "PMD.MissingBreakInSwitch" , "PMD.SwitchStmtsShouldHaveDefault" , "NullAway" } ) private Expirable < V > postProcess ( Expirable < V > expirable , EntryProcessorEntry < K , V > entry , long currentTimeMS ) { switch ( entry . getAction ( ) ) { case NONE : if ( expirable == null ) { return null ; } else if ( expirable . isEternal ( ) ) { return expirable ; } if ( currentTimeMS == 0 ) { currentTimeMS = currentTimeMillis ( ) ; } if ( expirable . hasExpired ( currentTimeMS ) ) { dispatcher . publishExpired ( this , entry . getKey ( ) , expirable . get ( ) ) ; statistics . recordEvictions ( 1 ) ; return null ; } return expirable ; case READ : { setAccessExpirationTime ( expirable , 0L ) ; return expirable ; } case CREATED : this . publishToCacheWriter ( writer :: write , ( ) -> entry ) ; case LOADED : statistics . recordPuts ( 1L ) ; dispatcher . publishCreated ( this , entry . getKey ( ) , entry . getValue ( ) ) ; return new Expirable < > ( entry . getValue ( ) , getWriteExpireTimeMS ( true ) ) ; case UPDATED : { statistics . recordPuts ( 1L ) ; publishToCacheWriter ( writer :: write , ( ) -> entry ) ; dispatcher . publishUpdated ( this , entry . getKey ( ) , expirable . get ( ) , entry . getValue ( ) ) ; long expireTimeMS = getWriteExpireTimeMS ( false ) ; if ( expireTimeMS == Long . MIN_VALUE ) { expireTimeMS = expirable . getExpireTimeMS ( ) ; } return new Expirable < > ( entry . getValue ( ) , expireTimeMS ) ; } case DELETED : statistics . recordRemovals ( 1L ) ; publishToCacheWriter ( writer :: delete , entry :: getKey ) ; dispatcher . publishRemoved ( this , entry . getKey ( ) , entry . getValue ( ) ) ; return null ; } throw new IllegalStateException ( "Unknown state: " + entry . getAction ( ) ) ; } | Returns the updated expirable value after performing the post processing actions . |
21,581 | void enableManagement ( boolean enabled ) { requireNotClosed ( ) ; synchronized ( configuration ) { if ( enabled ) { JmxRegistration . registerMXBean ( this , cacheMXBean , MBeanType . Configuration ) ; } else { JmxRegistration . unregisterMXBean ( this , MBeanType . Configuration ) ; } configuration . setManagementEnabled ( enabled ) ; } } | Enables or disables the configuration management JMX bean . |
21,582 | void enableStatistics ( boolean enabled ) { requireNotClosed ( ) ; synchronized ( configuration ) { if ( enabled ) { JmxRegistration . registerMXBean ( this , statistics , MBeanType . Statistics ) ; } else { JmxRegistration . unregisterMXBean ( this , MBeanType . Statistics ) ; } statistics . enable ( enabled ) ; configuration . setStatisticsEnabled ( enabled ) ; } } | Enables or disables the statistics JMX bean . |
21,583 | private < T > void publishToCacheWriter ( Consumer < T > action , Supplier < T > data ) { if ( ! configuration . isWriteThrough ( ) ) { return ; } try { action . accept ( data . get ( ) ) ; } catch ( CacheWriterException e ) { throw e ; } catch ( RuntimeException e ) { throw new CacheWriterException ( "Exception in CacheWriter" , e ) ; } } | Performs the action with the cache writer if write - through is enabled . |
21,584 | private CacheWriterException writeAllToCacheWriter ( Map < ? extends K , ? extends V > map ) { if ( ! configuration . isWriteThrough ( ) || map . isEmpty ( ) ) { return null ; } List < Cache . Entry < ? extends K , ? extends V > > entries = map . entrySet ( ) . stream ( ) . map ( entry -> new EntryProxy < > ( entry . getKey ( ) , entry . getValue ( ) ) ) . collect ( toList ( ) ) ; try { writer . writeAll ( entries ) ; return null ; } catch ( CacheWriterException e ) { entries . forEach ( entry -> { map . remove ( entry . getKey ( ) ) ; } ) ; throw e ; } catch ( RuntimeException e ) { entries . forEach ( entry -> { map . remove ( entry . getKey ( ) ) ; } ) ; return new CacheWriterException ( "Exception in CacheWriter" , e ) ; } } | Writes all of the entries to the cache writer if write - through is enabled . |
21,585 | private CacheWriterException deleteAllToCacheWriter ( Set < ? extends K > keys ) { if ( ! configuration . isWriteThrough ( ) || keys . isEmpty ( ) ) { return null ; } List < K > keysToDelete = new ArrayList < > ( keys ) ; try { writer . deleteAll ( keysToDelete ) ; return null ; } catch ( CacheWriterException e ) { keys . removeAll ( keysToDelete ) ; throw e ; } catch ( RuntimeException e ) { keys . removeAll ( keysToDelete ) ; return new CacheWriterException ( "Exception in CacheWriter" , e ) ; } } | Deletes all of the entries using the cache writer retaining only the keys that succeeded . |
21,586 | protected final Map < K , V > copyMap ( Map < K , Expirable < V > > map ) { ClassLoader classLoader = cacheManager . getClassLoader ( ) ; return map . entrySet ( ) . stream ( ) . collect ( toMap ( entry -> copier . copy ( entry . getKey ( ) , classLoader ) , entry -> copier . copy ( entry . getValue ( ) . get ( ) , classLoader ) ) ) ; } | Returns a deep copy of the map if value - based caching is enabled . |
21,587 | protected final void setAccessExpirationTime ( Expirable < ? > expirable , long currentTimeMS ) { try { Duration duration = expiry . getExpiryForAccess ( ) ; if ( duration == null ) { return ; } else if ( duration . isZero ( ) ) { expirable . setExpireTimeMS ( 0L ) ; } else if ( duration . isEternal ( ) ) { expirable . setExpireTimeMS ( Long . MAX_VALUE ) ; } else { if ( currentTimeMS == 0L ) { currentTimeMS = currentTimeMillis ( ) ; } long expireTimeMS = duration . getAdjustedTime ( currentTimeMS ) ; expirable . setExpireTimeMS ( expireTimeMS ) ; } } catch ( Exception e ) { logger . log ( Level . WARNING , "Failed to set the entry's expiration time" , e ) ; } } | Sets the access expiration time . |
21,588 | protected final long getWriteExpireTimeMS ( boolean created ) { try { Duration duration = created ? expiry . getExpiryForCreation ( ) : expiry . getExpiryForUpdate ( ) ; if ( duration == null ) { return Long . MIN_VALUE ; } else if ( duration . isZero ( ) ) { return 0L ; } else if ( duration . isEternal ( ) ) { return Long . MAX_VALUE ; } return duration . getAdjustedTime ( currentTimeMillis ( ) ) ; } catch ( Exception e ) { logger . log ( Level . WARNING , "Failed to get the policy's expiration time" , e ) ; return Long . MIN_VALUE ; } } | Returns the time when the entry will expire . |
21,589 | private MethodSpec makeSetValue ( ) { MethodSpec . Builder setter = MethodSpec . methodBuilder ( "setValue" ) . addModifiers ( context . publicFinalModifiers ( ) ) . addParameter ( vTypeVar , "value" ) . addParameter ( vRefQueueType , "referenceQueue" ) ; if ( isStrongValues ( ) ) { setter . addStatement ( "$T.UNSAFE.putObject(this, $N, $N)" , UNSAFE_ACCESS , offsetName ( "value" ) , "value" ) ; } else { setter . addStatement ( "(($T<V>) getValueReference()).clear()" , Reference . class ) ; setter . addStatement ( "$T.UNSAFE.putObject(this, $N, new $T($L, $N, referenceQueue))" , UNSAFE_ACCESS , offsetName ( "value" ) , valueReferenceType ( ) , "getKeyReference()" , "value" ) ; } return setter . build ( ) ; } | Creates the setValue method . |
21,590 | protected < T > T roundtrip ( T object , ClassLoader classLoader ) { A data = serialize ( object ) ; @ SuppressWarnings ( "unchecked" ) T copy = ( T ) deserialize ( data , classLoader ) ; return copy ; } | Performs the serialization and deserialization returning the copied object . |
21,591 | @ SuppressWarnings ( "PMD.AvoidDuplicateLiterals" ) protected String assemble ( List < PolicyStats > results ) { String [ ] [ ] data = new String [ results . size ( ) ] [ headers ( ) . length ] ; for ( int i = 0 ; i < results . size ( ) ; i ++ ) { PolicyStats policyStats = results . get ( i ) ; data [ i ] = new String [ ] { policyStats . name ( ) , String . format ( "%.2f %%" , 100 * policyStats . hitRate ( ) ) , String . format ( "%,d" , policyStats . hitCount ( ) ) , String . format ( "%,d" , policyStats . missCount ( ) ) , String . format ( "%,d" , policyStats . requestCount ( ) ) , String . format ( "%,d" , policyStats . evictionCount ( ) ) , String . format ( "%.2f %%" , 100 * policyStats . admissionRate ( ) ) , steps ( policyStats ) , policyStats . stopwatch ( ) . toString ( ) } ; } return FlipTable . of ( headers ( ) , data ) ; } | Assembles an aggregated report . |
21,592 | private void addStrength ( String collectName , String queueName , TypeName type ) { context . cache . addMethod ( MethodSpec . methodBuilder ( queueName ) . addModifiers ( context . protectedFinalModifiers ( ) ) . returns ( type ) . addStatement ( "return $N" , queueName ) . build ( ) ) ; context . cache . addField ( FieldSpec . builder ( type , queueName , Modifier . FINAL ) . initializer ( "new $T()" , type ) . build ( ) ) ; context . cache . addMethod ( MethodSpec . methodBuilder ( collectName ) . addModifiers ( context . protectedFinalModifiers ( ) ) . addStatement ( "return true" ) . returns ( boolean . class ) . build ( ) ) ; } | Adds the reference strength methods for the key or value . |
21,593 | protected InputStream readFiles ( ) throws IOException { BufferedInputStream input = new BufferedInputStream ( openFile ( ) , BUFFER_SIZE ) ; input . mark ( 100 ) ; try { return new XZInputStream ( input ) ; } catch ( IOException e ) { input . reset ( ) ; } try { return new CompressorStreamFactory ( ) . createCompressorInputStream ( input ) ; } catch ( CompressorException e ) { input . reset ( ) ; } try { return new ArchiveStreamFactory ( ) . createArchiveInputStream ( input ) ; } catch ( ArchiveException e ) { input . reset ( ) ; } return input ; } | Returns the input stream of the trace data . |
21,594 | private InputStream openFile ( ) throws IOException { Path file = Paths . get ( filePath ) ; if ( Files . exists ( file ) ) { return Files . newInputStream ( file ) ; } InputStream input = getClass ( ) . getResourceAsStream ( filePath ) ; checkArgument ( input != null , "Could not find file: " + filePath ) ; return input ; } | Returns the input stream for the raw file . |
21,595 | public void register ( CacheEntryListenerConfiguration < K , V > configuration ) { if ( configuration . getCacheEntryListenerFactory ( ) == null ) { return ; } EventTypeAwareListener < K , V > listener = new EventTypeAwareListener < > ( configuration . getCacheEntryListenerFactory ( ) . create ( ) ) ; CacheEntryEventFilter < K , V > filter = event -> true ; if ( configuration . getCacheEntryEventFilterFactory ( ) != null ) { filter = new EventTypeFilter < > ( listener , configuration . getCacheEntryEventFilterFactory ( ) . create ( ) ) ; } Registration < K , V > registration = new Registration < > ( configuration , filter , listener ) ; dispatchQueues . putIfAbsent ( registration , CompletableFuture . completedFuture ( null ) ) ; } | Registers a cache entry listener based on the supplied configuration . |
21,596 | public void deregister ( CacheEntryListenerConfiguration < K , V > configuration ) { requireNonNull ( configuration ) ; dispatchQueues . keySet ( ) . removeIf ( registration -> configuration . equals ( registration . getConfiguration ( ) ) ) ; } | Deregisters a cache entry listener based on the supplied configuration . |
21,597 | public void publishCreated ( Cache < K , V > cache , K key , V value ) { publish ( cache , EventType . CREATED , key , null , value , false ) ; } | Publishes a creation event for the entry to all of the interested listeners . |
21,598 | public void publishUpdated ( Cache < K , V > cache , K key , V oldValue , V newValue ) { publish ( cache , EventType . UPDATED , key , oldValue , newValue , false ) ; } | Publishes a update event for the entry to all of the interested listeners . |
21,599 | public void publishRemoved ( Cache < K , V > cache , K key , V value ) { publish ( cache , EventType . REMOVED , key , null , value , false ) ; } | Publishes a remove event for the entry to all of the interested listeners . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.