idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
37,400 | protected void configureList ( ) { list . setFont ( comboBox . getFont ( ) ) ; list . setBorder ( null ) ; list . setCellRenderer ( comboBox . getRenderer ( ) ) ; list . setFocusable ( false ) ; list . setSelectionMode ( ListSelectionModel . SINGLE_SELECTION ) ; int selectedIndex = comboBox . getSelectedIndex ( ) ; if ( selectedIndex == - 1 ) { list . clearSelection ( ) ; } else { list . setSelectedIndex ( selectedIndex ) ; list . ensureIndexIsVisible ( selectedIndex ) ; } installListListeners ( ) ; } | Configures the list which is used to hold the combo box items in the popup . This method is called when the UI class is created . |
37,401 | protected void configurePopup ( ) { setLayout ( new BoxLayout ( this , BoxLayout . Y_AXIS ) ) ; setBorderPainted ( true ) ; setBorder ( LIST_BORDER ) ; setOpaque ( false ) ; add ( scroller ) ; setDoubleBuffered ( true ) ; setFocusable ( false ) ; } | Configures the popup portion of the combo box . This method is called when the UI class is created . |
37,402 | protected Rectangle computePopupBounds ( int px , int py , int pw , int ph ) { Toolkit toolkit = Toolkit . getDefaultToolkit ( ) ; Rectangle screenBounds ; int listWidth = getList ( ) . getPreferredSize ( ) . width ; Insets margin = comboBox . getInsets ( ) ; if ( hasScrollBars ( ) ) { px += margin . left ; pw = Math . max ( pw - margin . left - margin . right , listWidth + 16 ) ; } else { px += margin . left ; pw = Math . max ( pw - LEFT_SHIFT - margin . left , listWidth ) ; } GraphicsConfiguration gc = comboBox . getGraphicsConfiguration ( ) ; Point p = new Point ( ) ; SwingUtilities . convertPointFromScreen ( p , comboBox ) ; if ( gc == null ) { screenBounds = new Rectangle ( p , toolkit . getScreenSize ( ) ) ; } else { Insets screenInsets = Toolkit . getDefaultToolkit ( ) . getScreenInsets ( gc ) ; screenBounds = new Rectangle ( gc . getBounds ( ) ) ; screenBounds . width -= ( screenInsets . left + screenInsets . right ) ; screenBounds . height -= ( screenInsets . top + screenInsets . bottom ) ; screenBounds . x += screenInsets . left ; screenBounds . y += screenInsets . top ; } if ( isDropDown ( ) ) { if ( isEditable ( ) ) { py -= margin . bottom + 2 ; } else { py -= margin . bottom ; } } else { int yOffset = - margin . top ; int selectedIndex = comboBox . getSelectedIndex ( ) ; if ( selectedIndex <= 0 ) { py = - yOffset ; } else { py = - yOffset - list . getCellBounds ( 0 , selectedIndex - 1 ) . height ; } } Rectangle rect = new Rectangle ( px , Math . max ( py , p . y + screenBounds . y ) , Math . min ( screenBounds . width , pw ) , Math . min ( screenBounds . height - 40 , ph ) ) ; if ( rect . height < ph ) { rect . width += 16 ; } return rect ; } | Calculate the placement and size of the popup portion of the combo box based on the combo box location and the enclosing screen bounds . If no transformations are required then the returned rectangle will have the same values as the parameters . |
37,403 | private void setListSelection ( int selectedIndex ) { if ( selectedIndex == - 1 ) { list . clearSelection ( ) ; } else { list . setSelectedIndex ( selectedIndex ) ; list . ensureIndexIsVisible ( selectedIndex ) ; } } | Sets the list selection index to the selectedIndex . This method is used to synchronize the list selection with the combo box selection . |
37,404 | private Point getPopupLocation ( ) { Dimension popupSize = comboBox . getSize ( ) ; Insets insets = getInsets ( ) ; popupSize . setSize ( popupSize . width - ( insets . right + insets . left ) , getPopupHeightForRowCount ( getMaximumRowCount ( ) ) ) ; Rectangle popupBounds = computePopupBounds ( 0 , comboBox . getBounds ( ) . height , popupSize . width , popupSize . height ) ; Dimension scrollSize = popupBounds . getSize ( ) ; Point popupLocation = popupBounds . getLocation ( ) ; scroller . setMaximumSize ( scrollSize ) ; scroller . setPreferredSize ( scrollSize ) ; scroller . setMinimumSize ( scrollSize ) ; list . revalidate ( ) ; return popupLocation ; } | Calculates the upper left location of the Popup . |
37,405 | private void updateStyle ( JPanel c ) { SeaGlassContext context = getContext ( c , ENABLED ) ; style = SeaGlassLookAndFeel . updateStyle ( context , this ) ; context . dispose ( ) ; LookAndFeel . installProperty ( c , "opaque" , ! ( c . getBackground ( ) instanceof UIResource ) ) ; } | Update the Synth style if a property changes . |
37,406 | private void drawBorder ( Graphics2D g , int width , int height , Color color , float size ) { int max = ( int ) ( Math . min ( ( height - 2 ) * size , height / 2.0f ) + 0.5 ) ; int alphaDelta = color . getAlpha ( ) / max ; for ( int i = 0 ; i < max ; i ++ ) { Shape s = shapeGenerator . createRoundRectangle ( i , i , width - 2 * i - 1 , height - 2 * i - 1 , CornerSize . CHECKBOX_INTERIOR ) ; Color newColor = new Color ( color . getRed ( ) , color . getGreen ( ) , color . getBlue ( ) , color . getAlpha ( ) - i * alphaDelta ) ; g . setPaint ( newColor ) ; g . draw ( s ) ; } } | Draw a border around the graphic . |
37,407 | private void drawEnabledGraphic ( Graphics2D g , int width , int height ) { Shape s = shapeGenerator . createTabCloseIcon ( 2 , 2 , width - 4 , height - 4 ) ; g . setPaint ( createGraphicInnerShadowGradient ( s ) ) ; g . fill ( s ) ; } | Draw the close graphic for the simple enabled state . |
37,408 | private void drawOverlayGraphic ( Graphics2D g , int width , int height ) { Shape s = shapeGenerator . createTabCloseIcon ( 2 , 2 , width - 4 , height - 4 ) ; g . setPaint ( graphicBase ) ; g . fill ( s ) ; s = shapeGenerator . createTabCloseIcon ( 2 , 3 , width - 4 , height - 4 ) ; g . setPaint ( createGraphicDropShadowGradient ( s ) ) ; Shape oldClip = g . getClip ( ) ; g . setClip ( 2 , 3 , width - 4 , height - 4 ) ; g . fill ( s ) ; g . setClip ( oldClip ) ; } | Draw the close graphic for a state where it overlays a border . |
37,409 | private Paint createGraphicInnerShadowGradient ( Shape s ) { Rectangle2D b = s . getBounds2D ( ) ; float midX = ( float ) b . getCenterX ( ) ; float y1 = ( float ) b . getMinY ( ) ; float y2 = ( float ) b . getMaxY ( ) ; return createGradient ( midX , y1 , midX , y2 , new float [ ] { 0f , 0.43f , 0.57f , 1f } , new Color [ ] { graphicInnerShadow1 , graphicInnerShadow2 , graphicInnerShadow3 , graphicInnerShadow4 } ) ; } | Create the gradient for the x inner shadow . |
37,410 | private Paint createGraphicDropShadowGradient ( Shape s ) { Rectangle2D b = s . getBounds2D ( ) ; float midX = ( float ) b . getCenterX ( ) ; float y1 = ( float ) b . getMinY ( ) ; float y2 = ( float ) b . getMaxY ( ) ; return createGradient ( midX , y1 , midX , y2 , new float [ ] { 0f , 0.43f , 0.57f , 1f } , new Color [ ] { graphicDropShadow1 , graphicDropShadow2 , graphicDropShadow3 , graphicDropShadow4 } ) ; } | Create the gradient for the x drop shadow . |
37,411 | public Insets getBorderInsets ( Component c , Insets insets ) { if ( this . insets != null ) { if ( insets == null ) { insets = new Insets ( this . insets . top , this . insets . left , this . insets . bottom , this . insets . right ) ; } else { insets . top = this . insets . top ; insets . bottom = this . insets . bottom ; insets . left = this . insets . left ; insets . right = this . insets . right ; } } else if ( insets == null ) { insets = new Insets ( 0 , 0 , 0 , 0 ) ; } else { insets . top = insets . bottom = insets . left = insets . right = 0 ; } if ( c instanceof JComponent ) { Insets margin = null ; Region region = SeaGlassLookAndFeel . getRegion ( ( JComponent ) c ) ; if ( ( region == Region . ARROW_BUTTON || region == Region . BUTTON || region == Region . CHECK_BOX || region == Region . CHECK_BOX_MENU_ITEM || region == Region . MENU || region == Region . MENU_ITEM || region == Region . RADIO_BUTTON || region == Region . RADIO_BUTTON_MENU_ITEM || region == Region . TOGGLE_BUTTON ) && ( c instanceof AbstractButton ) ) { margin = ( ( AbstractButton ) c ) . getMargin ( ) ; } else if ( ( region == Region . EDITOR_PANE || region == Region . FORMATTED_TEXT_FIELD || region == Region . PASSWORD_FIELD || region == Region . TEXT_AREA || region == Region . TEXT_FIELD || region == Region . TEXT_PANE ) && ( c instanceof JTextComponent ) ) { margin = ( ( JTextComponent ) c ) . getMargin ( ) ; } else if ( region == Region . TOOL_BAR && ( c instanceof JToolBar ) ) { margin = ( ( JToolBar ) c ) . getMargin ( ) ; } else if ( region == Region . MENU_BAR && ( c instanceof JMenuBar ) ) { margin = ( ( JMenuBar ) c ) . getMargin ( ) ; } if ( margin != null ) { insets . top += margin . top ; insets . bottom += margin . bottom ; insets . left += margin . left ; insets . right += margin . right ; } } return insets ; } | Reinitializes the insets parameter with this Border s current Insets . |
37,412 | private TableCellRenderer installRendererIfPossible ( Class objectClass , TableCellRenderer renderer ) { TableCellRenderer currentRenderer = table . getDefaultRenderer ( objectClass ) ; if ( currentRenderer instanceof UIResource ) { table . setDefaultRenderer ( objectClass , renderer ) ; } return currentRenderer ; } | Installs a renderer if the existing renderer is an instance of UIResource . |
37,413 | private void updateStyle ( JTable c ) { SeaGlassContext context = getContext ( c , ENABLED ) ; SynthStyle oldStyle = style ; SynthStyle s = SeaGlassLookAndFeel . updateStyle ( context , this ) ; if ( s instanceof SeaGlassStyle ) { style = ( SeaGlassStyle ) s ; selectionActiveBottomBorderColor = UIManager . getColor ( "seaGlassTableSelectionActiveBottom" ) ; selectionInactiveBottomBorderColor = UIManager . getColor ( "seaGlassTableSelectionInactiveBottom" ) ; transparentColor = UIManager . getColor ( "seaGlassTransparent" ) ; if ( style != oldStyle ) { table . remove ( rendererPane ) ; rendererPane = createCustomCellRendererPane ( ) ; table . add ( rendererPane ) ; context . setComponentState ( ENABLED | SELECTED ) ; Color sbg = table . getSelectionBackground ( ) ; if ( sbg == null || sbg instanceof UIResource ) { table . setSelectionBackground ( style . getColor ( context , ColorType . TEXT_BACKGROUND ) ) ; } Color sfg = table . getSelectionForeground ( ) ; if ( sfg == null || sfg instanceof UIResource ) { table . setSelectionForeground ( style . getColor ( context , ColorType . TEXT_FOREGROUND ) ) ; } context . setComponentState ( ENABLED ) ; Color gridColor = table . getGridColor ( ) ; if ( gridColor == null || gridColor instanceof UIResource ) { gridColor = ( Color ) style . get ( context , "Table.gridColor" ) ; if ( gridColor == null ) { gridColor = style . getColor ( context , ColorType . FOREGROUND ) ; } table . setGridColor ( gridColor ) ; } useTableColors = style . getBoolean ( context , "Table.rendererUseTableColors" , true ) ; useUIBorder = style . getBoolean ( context , "Table.rendererUseUIBorder" , true ) ; Object rowHeight = style . get ( context , "Table.rowHeight" ) ; if ( rowHeight != null ) { LookAndFeel . installProperty ( table , "rowHeight" , rowHeight ) ; } boolean showGrid = style . getBoolean ( context , "Table.showGrid" , true ) ; if ( ! showGrid ) { table . setShowGrid ( false ) ; } Dimension d = table . getIntercellSpacing ( ) ; if ( d != null ) { d = ( Dimension ) style . get ( context , "Table.intercellSpacing" ) ; } alternateColor = ( Color ) style . get ( context , "Table.alternateRowColor" ) ; if ( d != null ) { table . setIntercellSpacing ( d ) ; } table . setOpaque ( false ) ; if ( alternateColor != null ) { table . setShowHorizontalLines ( false ) ; } table . getTableHeader ( ) . setBorder ( createTableHeaderEmptyColumnPainter ( table ) ) ; setViewPortListeners ( table ) ; if ( oldStyle != null ) { uninstallKeyboardActions ( ) ; installKeyboardActions ( ) ; } } } context . dispose ( ) ; } | Update the style . |
37,414 | protected void paint ( SeaGlassContext context , Graphics g ) { Rectangle clip = g . getClipBounds ( ) ; Rectangle bounds = table . getBounds ( ) ; bounds . x = bounds . y = 0 ; if ( table . getRowCount ( ) <= 0 || table . getColumnCount ( ) <= 0 || ! bounds . intersects ( clip ) ) { paintDropLines ( context , g ) ; return ; } boolean ltr = table . getComponentOrientation ( ) . isLeftToRight ( ) ; Point upperLeft = clip . getLocation ( ) ; if ( ! ltr ) { upperLeft . x ++ ; } Point lowerRight = new Point ( clip . x + clip . width - ( ltr ? 1 : 0 ) , clip . y + clip . height ) ; int rMin = table . rowAtPoint ( upperLeft ) ; int rMax = table . rowAtPoint ( lowerRight ) ; if ( rMin == - 1 ) { rMin = 0 ; } if ( rMax == - 1 ) { rMax = table . getRowCount ( ) - 1 ; } int cMin = table . columnAtPoint ( ltr ? upperLeft : lowerRight ) ; int cMax = table . columnAtPoint ( ltr ? lowerRight : upperLeft ) ; if ( cMin == - 1 ) { cMin = 0 ; } if ( cMax == - 1 ) { cMax = table . getColumnCount ( ) - 1 ; } if ( ! ( table . getParent ( ) instanceof JViewport ) || ( table . getParent ( ) != null && ! ( table . getParent ( ) . getParent ( ) instanceof JScrollPane ) ) ) { paintStripesAndGrid ( context , g , table , table . getWidth ( ) , table . getHeight ( ) , 0 ) ; } paintCells ( context , g , rMin , rMax , cMin , cMax ) ; paintDropLines ( context , g ) ; } | Paint the component . |
37,415 | public void paintStripesAndGrid ( SeaGlassContext context , Graphics g , JComponent c , int width , int height , int top ) { int rh = table . getRowHeight ( ) ; int n = table . getRowCount ( ) ; int row = Math . abs ( top / rh ) ; if ( alternateColor != null ) { g . setColor ( alternateColor ) ; g . fillRect ( 0 , 0 , width , height ) ; g . setColor ( table . getBackground ( ) ) ; for ( int y = top + row * rh , ymax = height ; y < ymax ; y += rh ) { if ( row % 2 == 0 ) { g . fillRect ( 0 , y , width , rh ) ; } row ++ ; } } else { g . setColor ( table . getBackground ( ) ) ; g . fillRect ( 0 , 0 , c . getWidth ( ) , c . getHeight ( ) ) ; } SynthGraphicsUtils synthG = context . getStyle ( ) . getGraphicsUtils ( context ) ; if ( table . getShowHorizontalLines ( ) ) { g . setColor ( table . getGridColor ( ) ) ; row = Math . abs ( top / rh ) ; int y = top + row * rh + rh - 1 ; while ( y < height ) { synthG . drawLine ( context , "Table.grid" , g , 0 , y , width , y ) ; y += rh ; } } if ( table . getShowVerticalLines ( ) ) { g . setColor ( table . getGridColor ( ) ) ; TableColumnModel cm = table . getColumnModel ( ) ; n = cm . getColumnCount ( ) ; int y = top + row * rh ; ; int x = - 1 ; for ( int i = 0 ; i < n ; i ++ ) { TableColumn col = cm . getColumn ( i ) ; x += col . getWidth ( ) ; synthG . drawLine ( context , "Table.grid" , g , x , y , x , height ) ; } } } | Paint the stripes and grid . |
37,416 | private void paintDropLines ( SeaGlassContext context , Graphics g ) { JTable . DropLocation loc = table . getDropLocation ( ) ; if ( loc == null ) { return ; } Color color = ( Color ) style . get ( context , "Table.dropLineColor" ) ; Color shortColor = ( Color ) style . get ( context , "Table.dropLineShortColor" ) ; if ( color == null && shortColor == null ) { return ; } Rectangle rect ; rect = getHDropLineRect ( loc ) ; if ( rect != null ) { int x = rect . x ; int w = rect . width ; if ( color != null ) { extendRect ( rect , true ) ; g . setColor ( color ) ; g . fillRect ( rect . x , rect . y , rect . width , rect . height ) ; } if ( ! loc . isInsertColumn ( ) && shortColor != null ) { g . setColor ( shortColor ) ; g . fillRect ( x , rect . y , w , rect . height ) ; } } rect = getVDropLineRect ( loc ) ; if ( rect != null ) { int y = rect . y ; int h = rect . height ; if ( color != null ) { extendRect ( rect , false ) ; g . setColor ( color ) ; g . fillRect ( rect . x , rect . y , rect . width , rect . height ) ; } if ( ! loc . isInsertRow ( ) && shortColor != null ) { g . setColor ( shortColor ) ; g . fillRect ( rect . x , y , rect . width , h ) ; } } } | Paint the drop lines if any . |
37,417 | private Rectangle getHDropLineRect ( JTable . DropLocation loc ) { if ( ! loc . isInsertRow ( ) ) { return null ; } int row = loc . getRow ( ) ; int col = loc . getColumn ( ) ; if ( col >= table . getColumnCount ( ) ) { col -- ; } Rectangle rect = table . getCellRect ( row , col , true ) ; if ( row >= table . getRowCount ( ) ) { row -- ; Rectangle prevRect = table . getCellRect ( row , col , true ) ; rect . y = prevRect . y + prevRect . height ; } if ( rect . y == 0 ) { rect . y = - 1 ; } else { rect . y -= 2 ; } rect . height = 3 ; return rect ; } | Get the horizontal drop line rectangle . |
37,418 | private Rectangle getVDropLineRect ( JTable . DropLocation loc ) { if ( ! loc . isInsertColumn ( ) ) { return null ; } boolean ltr = table . getComponentOrientation ( ) . isLeftToRight ( ) ; int col = loc . getColumn ( ) ; Rectangle rect = table . getCellRect ( loc . getRow ( ) , col , true ) ; if ( col >= table . getColumnCount ( ) ) { col -- ; rect = table . getCellRect ( loc . getRow ( ) , col , true ) ; if ( ltr ) { rect . x = rect . x + rect . width ; } } else if ( ! ltr ) { rect . x = rect . x + rect . width ; } if ( rect . x == 0 ) { rect . x = - 1 ; } else { rect . x -= 2 ; } rect . width = 3 ; return rect ; } | Get the vertical drop line rectangle . |
37,419 | private void paintCells ( SeaGlassContext context , Graphics g , int rMin , int rMax , int cMin , int cMax ) { JTableHeader header = table . getTableHeader ( ) ; TableColumn draggedColumn = ( header == null ) ? null : header . getDraggedColumn ( ) ; TableColumnModel cm = table . getColumnModel ( ) ; int columnMargin = cm . getColumnMargin ( ) ; Rectangle cellRect ; TableColumn aColumn ; int columnWidth ; if ( table . getComponentOrientation ( ) . isLeftToRight ( ) ) { for ( int row = rMin ; row <= rMax ; row ++ ) { cellRect = table . getCellRect ( row , cMin , false ) ; for ( int column = cMin ; column <= cMax ; column ++ ) { aColumn = cm . getColumn ( column ) ; columnWidth = aColumn . getWidth ( ) ; cellRect . width = columnWidth - columnMargin ; if ( aColumn != draggedColumn ) { paintCell ( context , g , cellRect , row , column ) ; } cellRect . x += columnWidth ; } } } else { for ( int row = rMin ; row <= rMax ; row ++ ) { cellRect = table . getCellRect ( row , cMin , false ) ; aColumn = cm . getColumn ( cMin ) ; if ( aColumn != draggedColumn ) { columnWidth = aColumn . getWidth ( ) ; cellRect . width = columnWidth - columnMargin ; paintCell ( context , g , cellRect , row , cMin ) ; } for ( int column = cMin + 1 ; column <= cMax ; column ++ ) { aColumn = cm . getColumn ( column ) ; columnWidth = aColumn . getWidth ( ) ; cellRect . width = columnWidth - columnMargin ; cellRect . x -= columnWidth ; if ( aColumn != draggedColumn ) { paintCell ( context , g , cellRect , row , column ) ; } } } } if ( draggedColumn != null ) { paintDraggedArea ( context , g , rMin , rMax , draggedColumn , header . getDraggedDistance ( ) ) ; } rendererPane . removeAll ( ) ; } | Paint cells . |
37,420 | public static void setWindowShape ( Window window , Shape s ) { if ( PlatformUtils . isJava6 ( ) ) { setWindowShapeJava6 ( window , s ) ; } else { setWindowShapeJava7 ( window , s ) ; } } | Sets the shape of a window . This will be done via a com . sun API and may be not available on all platforms . |
37,421 | private static WindowListener createWeakWindowFocusListener ( WindowFocusListener windowFocusListener ) { final WeakReference < WindowFocusListener > weakReference = new WeakReference < WindowFocusListener > ( windowFocusListener ) ; return new WindowAdapter ( ) { public void windowActivated ( WindowEvent e ) { if ( weakReference . get ( ) != null ) { weakReference . get ( ) . windowGainedFocus ( e ) ; } } public void windowDeactivated ( WindowEvent e ) { if ( weakReference . get ( ) != null ) { weakReference . get ( ) . windowLostFocus ( e ) ; } } } ; } | Create the weak window focus listener . |
37,422 | private static AncestorListener createAncestorListener ( JComponent component , final WindowListener windowListener ) { final WeakReference < JComponent > weakReference = new WeakReference < JComponent > ( component ) ; return new AncestorListener ( ) { public void ancestorAdded ( AncestorEvent event ) { Window window = weakReference . get ( ) == null ? null : SwingUtilities . getWindowAncestor ( weakReference . get ( ) ) ; if ( window != null ) { window . removeWindowListener ( windowListener ) ; window . addWindowListener ( windowListener ) ; } } public void ancestorRemoved ( AncestorEvent event ) { Window window = weakReference . get ( ) == null ? null : SwingUtilities . getWindowAncestor ( weakReference . get ( ) ) ; if ( window != null ) { window . removeWindowListener ( windowListener ) ; } } public void ancestorMoved ( AncestorEvent event ) { } } ; } | Create the ancestor listener . |
37,423 | private static WindowFocusListener createRepaintWindowListener ( final JComponent component ) { return new WindowAdapter ( ) { public void windowActivated ( WindowEvent e ) { component . repaint ( ) ; } public void windowDeactivated ( WindowEvent e ) { component . repaint ( ) ; } } ; } | Create the repaint window listener . |
37,424 | private void updateTextured ( ) { paintTextured = ( root . getClientProperty ( UNIFIED_TOOLBAR_LOOK ) == Boolean . TRUE ) ; if ( paintTextured && PlatformUtils . isMac ( ) ) { if ( root . isValid ( ) ) { throw new IllegalArgumentException ( "This method only works if the given JRootPane has not yet been realized." ) ; } root . putClientProperty ( "apple.awt.brushMetalLook" , Boolean . TRUE ) ; LookAndFeel . installProperty ( ( JComponent ) root . getContentPane ( ) , "opaque" , Boolean . FALSE ) ; } else { root . putClientProperty ( "apple.awt.brushMetalLook" , null ) ; } } | Set the textured properties . |
37,425 | private WindowListener createFocusListener ( ) { return new WindowAdapter ( ) { public void windowActivated ( WindowEvent e ) { if ( root != null ) { root . repaint ( ) ; } } public void windowDeactivated ( WindowEvent e ) { if ( root != null ) { root . repaint ( ) ; } } } ; } | Creates the focus listener . |
37,426 | private MouseListener createMouseListener ( ) { return new MouseAdapter ( ) { public void mousePressed ( MouseEvent e ) { Point clickPoint = new Point ( e . getPoint ( ) ) ; SwingUtilities . convertPointToScreen ( clickPoint , fComponent ) ; dX = clickPoint . x - fWindow . getX ( ) ; dY = clickPoint . y - fWindow . getY ( ) ; } } ; } | Create the mouse listener . |
37,427 | private MouseMotionAdapter createMouseMotionListener ( ) { return new MouseMotionAdapter ( ) { public void mouseDragged ( MouseEvent e ) { Point dragPoint = new Point ( e . getPoint ( ) ) ; SwingUtilities . convertPointToScreen ( dragPoint , fComponent ) ; fWindow . setLocation ( dragPoint . x - dX , dragPoint . y - dY ) ; } } ; } | Create the mouse motion listener . |
37,428 | private void paintMenu ( Graphics2D g , JComponent c , int width , int height , ButtonColors colors ) { g . setRenderingHint ( RenderingHints . KEY_ANTIALIASING , RenderingHints . VALUE_ANTIALIAS_OFF ) ; g . setColor ( colors . top ) ; g . drawLine ( 0 , 0 , width - 2 , 0 ) ; g . setColor ( colors . leftOuter ) ; g . drawLine ( 0 , 0 , 0 , height - 4 ) ; g . setColor ( colors . leftInner ) ; g . drawLine ( 1 , 1 , 1 , height - 4 ) ; g . drawLine ( 2 , height - 3 , 2 , height - 3 ) ; Shape s = decodeInterior ( width , height ) ; g . setColor ( colors . interior ) ; g . fill ( s ) ; s = decodeEdge ( width , height ) ; g . setColor ( colors . edge ) ; g . draw ( s ) ; g . setColor ( colors . edgeShade ) ; g . drawLine ( 2 , height - 2 , 2 , height - 2 ) ; g . drawLine ( 1 , height - 3 , 1 , height - 3 ) ; g . drawLine ( 0 , height - 4 , 0 , height - 4 ) ; s = decodeShadow ( width , height ) ; g . setColor ( colors . shadow ) ; g . draw ( s ) ; g . setRenderingHint ( RenderingHints . KEY_ANTIALIASING , RenderingHints . VALUE_ANTIALIAS_ON ) ; s = decodeMarkInterior ( width , height ) ; g . setColor ( colors . markInterior ) ; g . fill ( s ) ; s = decodeMarkBorder ( width , height ) ; g . setColor ( colors . markBorder ) ; g . draw ( s ) ; } | Paint the button using the specified colors . |
37,429 | private Shape decodeInterior ( int width , int height ) { path . reset ( ) ; path . moveTo ( 1 , 1 ) ; path . lineTo ( width - 2 , 1 ) ; path . lineTo ( width - 2 , height - 3 ) ; path . lineTo ( width - 3 , height - 2 ) ; path . lineTo ( 3 , height - 2 ) ; path . lineTo ( 2 , height - 3 ) ; path . closePath ( ) ; return path ; } | Create the button interior shape |
37,430 | private Shape decodeMarkBorder ( int width , int height ) { double left = width / 2.0 - 4 ; double top = height / 2.0 - 4 ; path . reset ( ) ; path . moveTo ( left + 0 , top + 0 ) ; path . lineTo ( left + 8 , top ) ; path . lineTo ( left + 4 , top + 6 ) ; path . closePath ( ) ; return path ; } | Create the mark border shape . |
37,431 | public void paintText ( SynthContext ss , Graphics g , String text , int x , int y , int mnemonicIndex ) { if ( text != null ) { Graphics2D g2d = ( Graphics2D ) g . create ( ) ; g2d . setRenderingHint ( RenderingHints . KEY_TEXT_ANTIALIASING , RenderingHints . VALUE_TEXT_ANTIALIAS_ON ) ; JComponent c = ss . getComponent ( ) ; FontMetrics fm = SwingUtilities2 . getFontMetrics ( c , g2d ) ; y += fm . getAscent ( ) ; SwingUtilities2 . drawString ( c , g2d , text , x , y ) ; if ( mnemonicIndex >= 0 && mnemonicIndex < text . length ( ) ) { int underlineX = x + SwingUtilities2 . stringWidth ( c , fm , text . substring ( 0 , mnemonicIndex ) ) ; int underlineY = y ; int underlineWidth = fm . charWidth ( text . charAt ( mnemonicIndex ) ) ; int underlineHeight = 1 ; g2d . fillRect ( underlineX , underlineY + fm . getDescent ( ) - 1 , underlineWidth , underlineHeight ) ; } } } | Paints text at the specified location . This will not attempt to render the text as html nor will it offset by the insets of the component . |
37,432 | public void paintText ( SynthContext ss , Graphics g , String text , Icon icon , int hAlign , int vAlign , int hTextPosition , int vTextPosition , int iconTextGap , int mnemonicIndex , int textOffset ) { if ( ( icon == null ) && ( text == null ) ) { return ; } Graphics2D g2d = ( Graphics2D ) g . create ( ) ; g2d . setRenderingHint ( RenderingHints . KEY_TEXT_ANTIALIASING , RenderingHints . VALUE_TEXT_ANTIALIAS_ON ) ; JComponent c = ss . getComponent ( ) ; FontMetrics fm = SwingUtilities2 . getFontMetrics ( c , g2d ) ; Insets insets = SeaGlassLookAndFeel . getPaintingInsets ( ss , paintInsets ) ; paintViewR . x = insets . left ; paintViewR . y = insets . top ; paintViewR . width = c . getWidth ( ) - ( insets . left + insets . right ) ; paintViewR . height = c . getHeight ( ) - ( insets . top + insets . bottom ) ; paintIconR . x = paintIconR . y = paintIconR . width = paintIconR . height = 0 ; paintTextR . x = paintTextR . y = paintTextR . width = paintTextR . height = 0 ; String clippedText = layoutText ( ss , fm , text , icon , hAlign , vAlign , hTextPosition , vTextPosition , paintViewR , paintIconR , paintTextR , iconTextGap ) ; if ( icon != null ) { Color color = g2d . getColor ( ) ; paintIconR . x += textOffset ; paintIconR . y += textOffset ; SeaGlassIcon . paintIcon ( icon , ss , g2d , paintIconR . x , paintIconR . y , paintIconR . width , paintIconR . height ) ; g2d . setColor ( color ) ; } if ( text != null ) { View v = ( View ) c . getClientProperty ( BasicHTML . propertyKey ) ; if ( v != null ) { v . paint ( g2d , paintTextR ) ; } else { paintTextR . x += textOffset ; paintTextR . y += textOffset ; paintText ( ss , g2d , clippedText , paintTextR , mnemonicIndex ) ; } } } | Paints an icon and text . This will render the text as html if necessary and offset the location by the insets of the component . |
37,433 | private void paintMaximizeEnabled ( Graphics2D g , JComponent c , int width , int height ) { maximizePainter . paintEnabled ( g , c , width , height ) ; } | Paint the foreground maximized button enabled state . |
37,434 | private void paintMaximizeHover ( Graphics2D g , JComponent c , int width , int height ) { maximizePainter . paintHover ( g , c , width , height ) ; } | Paint the foreground maximized button mouse - over state . |
37,435 | private void paintMaximizePressed ( Graphics2D g , JComponent c , int width , int height ) { maximizePainter . paintPressed ( g , c , width , height ) ; } | Paint the foreground maximize button pressed state . |
37,436 | @ SuppressWarnings ( "unchecked" ) public void paintIcon ( Component c , Graphics g , int x , int y ) { SeaGlassPainter painter = ( SeaGlassPainter ) UIManager . get ( prefix + "[Enabled]." + key ) ; if ( painter != null ) { JComponent jc = ( c instanceof JComponent ) ? ( JComponent ) c : null ; Graphics2D gfx = ( Graphics2D ) g ; gfx . translate ( x , y ) ; painter . paint ( gfx , jc , width , height ) ; gfx . translate ( - x , - y ) ; } } | Implements the standard Icon interface s paintIcon method as the standard synth stub passes null for the context and this will cause us to not paint any thing so we override here so that we can paint the enabled state if no synth context is available |
37,437 | private int scale ( SynthContext context , int size ) { if ( context == null || context . getComponent ( ) == null ) { return size ; } String scaleKey = SeaGlassStyle . getSizeVariant ( context . getComponent ( ) ) ; if ( scaleKey != null ) { if ( SeaGlassStyle . LARGE_KEY . equals ( scaleKey ) ) { size *= SeaGlassStyle . LARGE_SCALE ; } else if ( SeaGlassStyle . SMALL_KEY . equals ( scaleKey ) ) { size *= SeaGlassStyle . SMALL_SCALE ; } else if ( SeaGlassStyle . MINI_KEY . equals ( scaleKey ) ) { size *= SeaGlassStyle . MINI_SCALE + 0.07 ; } } return size ; } | Scale a size based on the JComponent . sizeVariant client property of the component that is using this icon |
37,438 | public static boolean isConnectionClosure ( ShutdownSignalException e ) { return e instanceof AlreadyClosedException ? e . getReference ( ) instanceof Connection : e . isHardError ( ) ; } | Reliably returns whether the shutdown signal represents a connection closure . |
37,439 | @ SuppressWarnings ( "unchecked" ) public T withMaxDuration ( Duration maxDuration ) { Assert . notNull ( maxDuration , "maxDuration" ) ; this . maxDuration = maxDuration ; return ( T ) this ; } | Sets the max duration to perform attempts for . |
37,440 | boolean handleCommonMethods ( Object delegate , Method method , Object [ ] args ) throws Throwable { if ( "abort" . equals ( method . getName ( ) ) || "close" . equals ( method . getName ( ) ) ) { try { Reflection . invoke ( delegate , method , args ) ; return true ; } finally { closed = true ; afterClosure ( ) ; interruptWaiters ( ) ; } } else if ( "addShutdownListener" . equals ( method . getName ( ) ) && args [ 0 ] != null ) shutdownListeners . add ( ( ShutdownListener ) args [ 0 ] ) ; else if ( "removeShutdownListener" . equals ( method . getName ( ) ) && args [ 0 ] != null ) shutdownListeners . remove ( ( ShutdownListener ) args [ 0 ] ) ; return false ; } | Handles common method invocations . |
37,441 | public boolean isPolicyExceeded ( ) { boolean withinMaxRetries = maxAttempts == - 1 || attemptCount < maxAttempts ; boolean withinMaxDuration = maxDuration == - 1 || System . nanoTime ( ) - startTime < maxDuration ; return ! withinMaxRetries || ! withinMaxDuration ; } | Returns true if the max attempts or max duration for the recurring policy have been exceeded else false . |
37,442 | public Iterable < V > values ( ) { return new Iterable < V > ( ) { public Iterator < V > iterator ( ) { return new Iterator < V > ( ) { final Iterator < List < V > > valuesIterator = map . values ( ) . iterator ( ) ; Iterator < V > current ; { if ( valuesIterator . hasNext ( ) ) current = valuesIterator . next ( ) . iterator ( ) ; } public boolean hasNext ( ) { return current != null && current . hasNext ( ) ; } public V next ( ) { V value = current . next ( ) ; while ( ! current . hasNext ( ) && valuesIterator . hasNext ( ) ) current = valuesIterator . next ( ) . iterator ( ) ; return value ; } public void remove ( ) { throw new UnsupportedOperationException ( ) ; } } ; } } ; } | Returns an iterable over the multimap s values . Unsafe for concurrent modification . |
37,443 | synchronized void recoverChannel ( boolean viaConnectionRecovery ) throws Exception { recoveryPending . set ( false ) ; if ( circuit . isClosed ( ) ) return ; if ( recoveryStats == null ) { recoveryConsumers = consumerDeclarations . isEmpty ( ) ? null : new LinkedHashMap < String , ConsumerDeclaration > ( consumerDeclarations ) ; recoveryStats = new RecurringStats ( config . getChannelRecoveryPolicy ( ) ) ; recoveryStats . incrementTime ( ) ; } else if ( recoveryStats . isPolicyExceeded ( ) ) { recoveryFailed ( lastShutdownSignal ) ; if ( ! viaConnectionRecovery ) return ; } try { notifyRecoveryStarted ( ) ; delegate = callWithRetries ( new Callable < Channel > ( ) { public Channel call ( ) throws Exception { log . info ( "Recovering {}" , ChannelHandler . this ) ; previousMaxDeliveryTag = maxDeliveryTag ; Channel channel = connectionHandler . createChannel ( delegate . getChannelNumber ( ) ) ; migrateConfiguration ( channel ) ; log . info ( "Recovered {}" , ChannelHandler . this ) ; return channel ; } } , config . getChannelRecoveryPolicy ( ) , recoveryStats , config . getRecoverableExceptions ( ) , true , false ) ; notifyRecovery ( ) ; recoverConsumers ( ! viaConnectionRecovery ) ; recoverySucceeded ( ) ; } catch ( Exception e ) { ShutdownSignalException sse = Exceptions . extractCause ( e , ShutdownSignalException . class ) ; if ( sse != null ) { if ( Exceptions . isConnectionClosure ( sse ) ) throw e ; } else if ( recoveryStats . isPolicyExceeded ( ) ) recoveryFailed ( e ) ; } } | Atomically recovers the channel . |
37,444 | private void recoverConsumers ( boolean recoverReferences ) throws Exception { if ( config . isConsumerRecoveryEnabled ( ) && ! recoveryPending . get ( ) && recoveryConsumers != null ) { Set < QueueDeclaration > recoveredQueues = new HashSet < QueueDeclaration > ( ) ; Set < String > recoveredExchanges = new HashSet < String > ( ) ; for ( Iterator < Map . Entry < String , ConsumerDeclaration > > it = recoveryConsumers . entrySet ( ) . iterator ( ) ; it . hasNext ( ) ; ) { Map . Entry < String , ConsumerDeclaration > entry = it . next ( ) ; ConsumerDeclaration consumerDeclaration = entry . getValue ( ) ; Object [ ] args = consumerDeclaration . args ; ConsumerDelegate consumer = ( ConsumerDelegate ) args [ args . length - 1 ] ; String queueName = consumerDeclaration . queueDeclaration != null ? consumerDeclaration . queueDeclaration . name : ( String ) args [ 0 ] ; try { if ( recoverReferences ) { List < Binding > queueBindings = connectionHandler . queueBindings . get ( queueName ) ; recoverRelatedExchanges ( recoveredExchanges , queueBindings ) ; if ( consumerDeclaration . queueDeclaration != null && recoveredQueues . add ( consumerDeclaration . queueDeclaration ) ) queueName = recoverQueue ( queueName , consumerDeclaration . queueDeclaration , queueBindings ) ; } log . info ( "" . equals ( queueName ) ? "Recovering consumer-{}{} via {}" : "Recovering consumer-{} of {} via {}" , entry . getKey ( ) , queueName , this ) ; notifyConsumerRecoveryStarted ( consumer ) ; consumer . open ( ) ; consumerDeclaration . invoke ( delegate ) ; log . info ( "" . equals ( queueName ) ? "Recovered consumer-{}{} via {}" : "Recovered consumer-{} of {} via {}" , entry . getKey ( ) , queueName , this ) ; notifyConsumerRecoveryCompleted ( consumer ) ; } catch ( Exception e ) { log . error ( "Failed to recover consumer-{} via {}" , entry . getKey ( ) , this , e ) ; notifyConsumerRecoveryFailure ( consumer , e ) ; ShutdownSignalException sse = Exceptions . extractCause ( e , ShutdownSignalException . class ) ; if ( sse != null ) { if ( ! Exceptions . isConnectionClosure ( sse ) ) it . remove ( ) ; throw e ; } } } } } | Recovers the channel s consumers along with any exchanges exchange bindings queues and queue bindings that are referenced by the consumer . If a consumer recovery fails due to a channel closure then we will not attempt to recover that consumer or its references again . |
37,445 | public Address [ ] getAddresses ( ) { if ( addresses != null ) return addresses ; if ( hosts != null ) { addresses = new Address [ hosts . length ] ; for ( int i = 0 ; i < hosts . length ; i ++ ) addresses [ i ] = new Address ( hosts [ i ] , factory . getPort ( ) ) ; return addresses ; } Address address = factory == null ? new Address ( "localhost" , - 1 ) : new Address ( factory . getHost ( ) , factory . getPort ( ) ) ; return new Address [ ] { address } ; } | Returns the addresses to attempt connections to in round - robin order . |
37,446 | public ConnectionOptions withClientProperties ( Map < String , Object > clientProperties ) { factory . setClientProperties ( Assert . notNull ( clientProperties , "clientProperties" ) ) ; return this ; } | Sets the client properties . |
37,447 | public ConnectionOptions withNioParams ( NioParams nioParams ) { this . nioParams = nioParams ; factory . setNioParams ( Assert . notNull ( nioParams , "nioParams" ) ) ; factory . useNio ( ) ; return this ; } | Support for Java non - blocking IO |
37,448 | public Match include ( String ... fields ) { if ( fields != null ) { includes . addAll ( Arrays . asList ( fields ) ) ; } return this ; } | Mark fields for inclusion during serialization . |
37,449 | public Match exclude ( String ... fields ) { if ( fields != null ) { excludes . addAll ( Arrays . asList ( fields ) ) ; } return this ; } | Mark fields for exclusion during serialization . |
37,450 | @ SuppressWarnings ( "unchecked" ) public < X , Y , Z > Match transform ( String field , BiFunction < X , Y , Z > transformer ) { transforms . put ( field , ( BiFunction < Object , Object , Object > ) transformer ) ; return this ; } | Mark a field for transformation during serialization . |
37,451 | public boolean dispatchTouchEvent ( final MotionEvent event ) { checkNotNull ( event , "event == null" ) ; boolean isEventConsumed = false ; switch ( event . getAction ( ) ) { case MotionEvent . ACTION_DOWN : onActionDown ( event ) ; break ; case MotionEvent . ACTION_UP : isEventConsumed = onActionUp ( event ) ; break ; case MotionEvent . ACTION_MOVE : onActionMove ( event ) ; break ; default : break ; } return isEventConsumed ; } | Called to process touch screen events . |
37,452 | public boolean check ( ) throws IOException , TrustyUriException { TrustyUriModule module = ModuleDirectory . getModule ( r . getModuleId ( ) ) ; if ( module == null ) { throw new TrustyUriException ( "ERROR: Not a trusty URI or unknown module" ) ; } return module . hasCorrectHash ( r ) ; } | Checks whether the content matches the hash of the trusty URI . |
37,453 | private void init ( Context context , AttributeSet attrs , int defStyleAttr ) { TypedArray a = context . obtainStyledAttributes ( attrs , R . styleable . CircularSlider , defStyleAttr , 0 ) ; float startAngle = a . getFloat ( R . styleable . CircularSlider_start_angle , ( float ) Math . PI / 2 ) ; float angle = a . getFloat ( R . styleable . CircularSlider_angle , ( float ) Math . PI / 2 ) ; int thumbSize = a . getDimensionPixelSize ( R . styleable . CircularSlider_thumb_size , 50 ) ; int thumbColor = a . getColor ( R . styleable . CircularSlider_thumb_color , Color . GRAY ) ; int borderThickness = a . getDimensionPixelSize ( R . styleable . CircularSlider_border_thickness , 20 ) ; int borderColor = a . getColor ( R . styleable . CircularSlider_border_color , Color . RED ) ; String borderGradientColors = a . getString ( R . styleable . CircularSlider_border_gradient_colors ) ; Drawable thumbImage = a . getDrawable ( R . styleable . CircularSlider_thumb_image ) ; setStartAngle ( startAngle ) ; setAngle ( angle ) ; setBorderThickness ( borderThickness ) ; setBorderColor ( borderColor ) ; if ( borderGradientColors != null ) { setBorderGradientColors ( borderGradientColors . split ( ";" ) ) ; } setThumbSize ( thumbSize ) ; setThumbImage ( thumbImage ) ; setThumbColor ( thumbColor ) ; int padding ; if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . JELLY_BEAN_MR1 ) { int all = getPaddingLeft ( ) + getPaddingRight ( ) + getPaddingBottom ( ) + getPaddingTop ( ) + getPaddingEnd ( ) + getPaddingStart ( ) ; padding = all / 6 ; } else { padding = ( getPaddingLeft ( ) + getPaddingRight ( ) + getPaddingBottom ( ) + getPaddingTop ( ) ) / 4 ; } setPadding ( padding ) ; a . recycle ( ) ; } | common initializer method |
37,454 | private void updateSliderState ( int touchX , int touchY ) { int distanceX = touchX - mCircleCenterX ; int distanceY = mCircleCenterY - touchY ; double c = Math . sqrt ( Math . pow ( distanceX , 2 ) + Math . pow ( distanceY , 2 ) ) ; mAngle = Math . acos ( distanceX / c ) ; if ( distanceY < 0 ) { mAngle = - mAngle ; } if ( mListener != null ) { mListener . onSliderMoved ( ( mAngle - mStartAngle ) / ( 2 * Math . PI ) ) ; } } | Invoked when slider starts moving or is currently moving . This method calculates and sets position and angle of the thumb . |
37,455 | private MetaMethod specialCasedOverrideForCreate ( final Method m ) { return new MetaMethod ( ) { public int getModifiers ( ) { return m . getModifiers ( ) ; } public String getName ( ) { return m . getName ( ) ; } public Class < ? > getReturnType ( ) { return m . getReturnType ( ) ; } public CachedClass getDeclaringClass ( ) { return ReflectionCache . getCachedClass ( m . getDeclaringClass ( ) ) ; } @ SuppressWarnings ( "unchecked" ) public Object invoke ( Object object , final Object [ ] arguments ) { return Observable . create ( new GroovyCreateWrapper ( ( Closure ) arguments [ 0 ] ) ) ; } public CachedClass [ ] getParameterTypes ( ) { if ( parameterTypes == null ) { getParametersTypes0 ( ) ; } return parameterTypes ; } private synchronized void getParametersTypes0 ( ) { if ( parameterTypes != null ) return ; Class [ ] npt = nativeParamTypes == null ? getPT ( ) : nativeParamTypes ; CachedClass [ ] pt = new CachedClass [ npt . length ] ; for ( int i = 0 ; i != npt . length ; ++ i ) { if ( Function . class . isAssignableFrom ( npt [ i ] ) ) { pt [ i ] = ReflectionCache . getCachedClass ( Closure . class ) ; } else { pt [ i ] = ReflectionCache . getCachedClass ( npt [ i ] ) ; } } nativeParamTypes = npt ; setParametersTypes ( pt ) ; } protected Class [ ] getPT ( ) { return m . getParameterTypes ( ) ; } } ; } | Special case until we finish migrating off the deprecated create method signature |
37,456 | static String rewriteIPv4MappedNotation ( String string ) { if ( ! string . contains ( "." ) ) { return string ; } else { int lastColon = string . lastIndexOf ( ":" ) ; String firstPart = string . substring ( 0 , lastColon + 1 ) ; String mappedIPv4Part = string . substring ( lastColon + 1 ) ; if ( mappedIPv4Part . contains ( "." ) ) { String [ ] dotSplits = DOT_DELIM . split ( mappedIPv4Part ) ; if ( dotSplits . length != 4 ) throw new IllegalArgumentException ( String . format ( "can not parse [%s]" , string ) ) ; StringBuilder rewrittenString = new StringBuilder ( ) ; rewrittenString . append ( firstPart ) ; int byteZero = Integer . parseInt ( dotSplits [ 0 ] ) ; int byteOne = Integer . parseInt ( dotSplits [ 1 ] ) ; int byteTwo = Integer . parseInt ( dotSplits [ 2 ] ) ; int byteThree = Integer . parseInt ( dotSplits [ 3 ] ) ; rewrittenString . append ( String . format ( "%02x" , byteZero ) ) ; rewrittenString . append ( String . format ( "%02x" , byteOne ) ) ; rewrittenString . append ( ":" ) ; rewrittenString . append ( String . format ( "%02x" , byteTwo ) ) ; rewrittenString . append ( String . format ( "%02x" , byteThree ) ) ; return rewrittenString . toString ( ) ; } else { throw new IllegalArgumentException ( String . format ( "can not parse [%s]" , string ) ) ; } } } | Replaces a w . x . y . z substring at the end of the given string with corresponding hexadecimal notation . This is useful in case the string was using IPv4 - Mapped address notation . |
37,457 | public KeePassFileBuilder addTopGroups ( Group ... groups ) { for ( Group group : groups ) { rootBuilder . addGroup ( group ) ; } return this ; } | Adds the given groups right under the root node . |
37,458 | public KeePassFileBuilder addTopEntries ( Entry ... entries ) { for ( Entry entry : entries ) { topGroupBuilder . addEntry ( entry ) ; } return this ; } | Add the given entries right under the root node . |
37,459 | @ SuppressWarnings ( "resource" ) public void read ( byte [ ] keepassFile ) throws IOException { SafeInputStream inputStream = new SafeInputStream ( new BufferedInputStream ( new ByteArrayInputStream ( keepassFile ) ) ) ; inputStream . skipSafe ( VERSION_SIGNATURE_LENGTH ) ; if ( fileFormatVersion == 0 ) { throw new UnsupportedOperationException ( "File format version not set! Make sure to call checkVersionSupport before " ) ; } while ( true ) { try { int fieldId = inputStream . read ( ) ; byte [ ] fieldLength ; if ( fileFormatVersion < DATABASE_V4_FILE_VERSION_INT ) { fieldLength = new byte [ 2 ] ; } else { fieldLength = new byte [ 4 ] ; } inputStream . readSafe ( fieldLength ) ; ByteBuffer fieldLengthBuffer = ByteBuffer . wrap ( fieldLength ) ; fieldLengthBuffer . order ( ByteOrder . LITTLE_ENDIAN ) ; int fieldLengthInt = ByteUtils . toUnsignedInt ( fieldLengthBuffer . getShort ( ) ) ; if ( fieldLengthInt > 0 ) { byte [ ] data = new byte [ fieldLengthInt ] ; inputStream . readSafe ( data ) ; setValue ( fieldId , data ) ; } if ( fieldId == 0 ) { break ; } } catch ( IOException e ) { throw new KeePassHeaderUnreadableException ( "Could not read header input" , e ) ; } } } | Initializes the header values from a given byte array . |
37,460 | public byte [ ] getBytes ( ) { try { ByteArrayOutputStream stream = new ByteArrayOutputStream ( ) ; stream . write ( DATABASE_V2_FILE_SIGNATURE_1 ) ; stream . write ( DATABASE_V2_FILE_SIGNATURE_2 ) ; stream . write ( DATABASE_V2_FILE_VERSION ) ; for ( int i = 2 ; i < 11 ; i ++ ) { byte [ ] headerValue = getValue ( i ) ; stream . write ( i ) ; byte [ ] length = new byte [ ] { ( byte ) headerValue . length , 0 } ; stream . write ( length ) ; stream . write ( headerValue ) ; } stream . write ( getEndOfHeader ( ) ) ; return stream . toByteArray ( ) ; } catch ( IOException e ) { throw new KeePassHeaderUnreadableException ( "Could not write header value to stream" , e ) ; } } | Returns the whole header as byte array . |
37,461 | public Iterator < IPv6Network > split ( IPv6NetworkMask size ) { if ( size . asPrefixLength ( ) < this . getNetmask ( ) . asPrefixLength ( ) ) throw new IllegalArgumentException ( String . format ( "Can not split a network of size %s in subnets of larger size %s" , this . getNetmask ( ) . asPrefixLength ( ) , size . asPrefixLength ( ) ) ) ; return new IPv6NetworkSplitsIterator ( size ) ; } | Split a network in smaller subnets of a given size . |
37,462 | public static IPv6Address fromInetAddress ( final InetAddress inetAddress ) { if ( inetAddress == null ) throw new IllegalArgumentException ( "can not construct from [null]" ) ; return fromByteArray ( inetAddress . getAddress ( ) ) ; } | Create an IPv6 address from a java . net . Inet6Address . |
37,463 | public static IPv6Address fromByteArray ( final byte [ ] bytes ) { if ( bytes == null ) throw new IllegalArgumentException ( "can not construct from [null]" ) ; if ( bytes . length != N_BYTES ) throw new IllegalArgumentException ( "the byte array to construct from should be 16 bytes long" ) ; ByteBuffer buf = ByteBuffer . allocate ( N_BYTES ) ; for ( byte b : bytes ) { buf . put ( b ) ; } buf . rewind ( ) ; LongBuffer longBuffer = buf . asLongBuffer ( ) ; return new IPv6Address ( longBuffer . get ( ) , longBuffer . get ( ) ) ; } | Create an IPv6 address from a byte array . |
37,464 | public IPv6Address add ( int value ) { final long newLowBits = lowBits + value ; if ( value >= 0 ) { if ( IPv6AddressHelpers . isLessThanUnsigned ( newLowBits , lowBits ) ) { return new IPv6Address ( highBits + 1 , newLowBits ) ; } else { return new IPv6Address ( highBits , newLowBits ) ; } } else { if ( IPv6AddressHelpers . isLessThanUnsigned ( lowBits , newLowBits ) ) { return new IPv6Address ( highBits - 1 , newLowBits ) ; } else { return new IPv6Address ( highBits , newLowBits ) ; } } } | Addition . Will never overflow but wraps around when the highest ip address has been reached . |
37,465 | public IPv6Address subtract ( int value ) { final long newLowBits = lowBits - value ; if ( value >= 0 ) { if ( IPv6AddressHelpers . isLessThanUnsigned ( lowBits , newLowBits ) ) { return new IPv6Address ( highBits - 1 , newLowBits ) ; } else { return new IPv6Address ( highBits , newLowBits ) ; } } else { if ( IPv6AddressHelpers . isLessThanUnsigned ( newLowBits , lowBits ) ) { return new IPv6Address ( highBits + 1 , newLowBits ) ; } else { return new IPv6Address ( highBits , newLowBits ) ; } } } | Subtraction . Will never underflow but wraps around when the lowest ip address has been reached . |
37,466 | public IPv6Address maskWithNetworkMask ( final IPv6NetworkMask networkMask ) { if ( networkMask . asPrefixLength ( ) == 128 ) { return this ; } else if ( networkMask . asPrefixLength ( ) == 64 ) { return new IPv6Address ( this . highBits , 0 ) ; } else if ( networkMask . asPrefixLength ( ) == 0 ) { return new IPv6Address ( 0 , 0 ) ; } else if ( networkMask . asPrefixLength ( ) > 64 ) { final int remainingPrefixLength = networkMask . asPrefixLength ( ) - 64 ; return new IPv6Address ( this . highBits , this . lowBits & ( 0xFFFFFFFFFFFFFFFFL << ( 64 - remainingPrefixLength ) ) ) ; } else { return new IPv6Address ( this . highBits & ( 0xFFFFFFFFFFFFFFFFL << ( 64 - networkMask . asPrefixLength ( ) ) ) , 0 ) ; } } | Mask the address with the given network mask . |
37,467 | public IPv6Address setBit ( final int bit ) { if ( bit < 0 || bit > 127 ) throw new IllegalArgumentException ( "can only set bits in the interval [0, 127]" ) ; if ( bit < 64 ) { return new IPv6Address ( this . highBits , this . lowBits | ( 1L << bit ) ) ; } else { return new IPv6Address ( this . highBits | ( 1L << ( bit - 64 ) ) , this . lowBits ) ; } } | Set a bit in the address . |
37,468 | public void skipSafe ( long numBytes ) throws IOException { long skippedBytes = inputStream . skip ( numBytes ) ; if ( skippedBytes == - 1 ) { throw new IOException ( "Could not skip '" + numBytes + "' bytes in stream" ) ; } } | Skips over and discards numBytes bytes of data from the underlying input stream . Will throw an exception if the given number of bytes could not be skipped . |
37,469 | public List < Group > getTopGroups ( ) { if ( root != null && root . getGroups ( ) != null && root . getGroups ( ) . size ( ) == 1 ) { return root . getGroups ( ) . get ( 0 ) . getGroups ( ) ; } return new ArrayList < Group > ( ) ; } | Retrieves all groups at the root level of a KeePass database . |
37,470 | public List < Entry > getTopEntries ( ) { if ( root != null && root . getGroups ( ) != null && root . getGroups ( ) . size ( ) == 1 ) { return root . getGroups ( ) . get ( 0 ) . getEntries ( ) ; } return new ArrayList < Entry > ( ) ; } | Retrieves all entries at the root level of a KeePass database . |
37,471 | public List < Entry > getEntries ( ) { List < Entry > allEntries = new ArrayList < Entry > ( ) ; if ( root != null ) { getEntries ( root , allEntries ) ; } return allEntries ; } | Retrieves a list of all entries in the KeePass database . |
37,472 | public List < Group > getGroups ( ) { List < Group > allGroups = new ArrayList < Group > ( ) ; if ( root != null ) { getGroups ( root , allGroups ) ; } return allGroups ; } | Retrieves a list of all groups in the KeePass database . |
37,473 | public Entry getEntryByUUID ( final UUID UUID ) { List < Entry > allEntries = getEntries ( ) ; List < Entry > entries = ListFilter . filter ( allEntries , new Filter < Entry > ( ) { public boolean matches ( Entry item ) { if ( item . getUuid ( ) != null && item . getUuid ( ) . compareTo ( UUID ) == 0 ) { return true ; } else { return false ; } } } ) ; if ( entries . size ( ) == 1 ) { return entries . get ( 0 ) ; } else { return null ; } } | Retrieves an entry based on its UUID . |
37,474 | public Group getGroupByUUID ( final UUID UUID ) { List < Group > allGroups = getGroups ( ) ; List < Group > groups = ListFilter . filter ( allGroups , new Filter < Group > ( ) { public boolean matches ( Group item ) { if ( item . getUuid ( ) != null && item . getUuid ( ) . compareTo ( UUID ) == 0 ) { return true ; } else { return false ; } } } ) ; if ( groups . size ( ) == 1 ) { return groups . get ( 0 ) ; } else { return null ; } } | Retrieves a group based on its UUID . |
37,475 | public static KeePassDatabase getInstance ( File keePassDatabaseFile ) { if ( keePassDatabaseFile == null ) { throw new IllegalArgumentException ( "You must provide a valid KeePass database file." ) ; } InputStream keePassDatabaseStream = null ; try { keePassDatabaseStream = new FileInputStream ( keePassDatabaseFile ) ; return getInstance ( keePassDatabaseStream ) ; } catch ( FileNotFoundException e ) { throw new IllegalArgumentException ( "The KeePass database file could not be found. You must provide a valid KeePass database file." , e ) ; } finally { if ( keePassDatabaseStream != null ) { try { keePassDatabaseStream . close ( ) ; } catch ( IOException e ) { } } } } | Retrieves a KeePassDatabase instance . The instance returned is based on the given database file and tries to parse the database header of it . |
37,476 | public Entry getEntryByTitle ( String title ) { for ( Entry entry : entries ) { if ( entry . getTitle ( ) . equalsIgnoreCase ( title ) ) { return entry ; } } return null ; } | Retrieves the entry with the given title . |
37,477 | public KeePassFile enrichNodesWithIconData ( KeePassFile keePassFile ) { CustomIcons iconLibrary = keePassFile . getMeta ( ) . getCustomIcons ( ) ; GroupZipper zipper = new GroupZipper ( keePassFile ) ; Iterator < Group > iter = zipper . iterator ( ) ; while ( iter . hasNext ( ) ) { Group group = iter . next ( ) ; byte [ ] iconData = getIconData ( group . getCustomIconUuid ( ) , group . getIconId ( ) , iconLibrary ) ; Group groupWithIcon = new GroupBuilder ( group ) . iconData ( iconData ) . build ( ) ; zipper . replace ( groupWithIcon ) ; enrichEntriesWithIcons ( iconLibrary , group ) ; } return zipper . close ( ) ; } | Iterates through all nodes of the given KeePass file and replace the nodes with enriched icon data nodes . |
37,478 | public Binary getBinaryById ( int id ) { for ( Binary binary : binaryList ) { if ( binary . getId ( ) == id ) { return binary ; } } return null ; } | Retrieves a binary item based on its id . |
37,479 | public IPv6AddressRange extend ( IPv6Address address ) { if ( address . compareTo ( first ) < 0 ) return fromFirstAndLast ( address , last ) ; else if ( address . compareTo ( last ) > 0 ) return fromFirstAndLast ( first , address ) ; else return this ; } | Extend the range just enough at its head or tail such that the given address is included . |
37,480 | public Entry buildWithHistory ( ) { if ( originalEntry == null ) { throw new IllegalArgumentException ( "originalEntry is not set" ) ; } if ( history == null ) { history = new History ( ) ; } Entry entryWithoutHistory = new EntryBuilder ( originalEntry ) . history ( new History ( ) ) . build ( ) ; history . getHistoricEntries ( ) . add ( entryWithoutHistory ) ; return build ( ) ; } | Builds a new entry and place the original one in the history list . |
37,481 | public CustomIcon getIconByUuid ( UUID uuid ) { for ( CustomIcon customIcon : customIconList ) { if ( customIcon . getUuid ( ) != null && customIcon . getUuid ( ) . compareTo ( uuid ) == 0 ) { return customIcon ; } } return null ; } | Retrieves a custom icon based on its uuid . |
37,482 | public IPv6AddressPool allocate ( ) { if ( ! isExhausted ( ) ) { final IPv6AddressRange firstFreeRange = freeRanges . first ( ) ; final IPv6Network allocated = IPv6Network . fromAddressAndMask ( firstFreeRange . getFirst ( ) , allocationSubnetSize ) ; return doAllocate ( allocated , firstFreeRange ) ; } else { return null ; } } | Allocate the first available subnet from the pool . |
37,483 | public IPv6AddressPool allocate ( IPv6Network toAllocate ) { if ( ! contains ( toAllocate ) ) throw new IllegalArgumentException ( "can not allocate network which is not contained in the pool to allocate from [" + toAllocate + "]" ) ; if ( ! this . allocationSubnetSize . equals ( toAllocate . getNetmask ( ) ) ) throw new IllegalArgumentException ( "can not allocate network with prefix length /" + toAllocate . getNetmask ( ) . asPrefixLength ( ) + " from a pool configured to hand out subnets with prefix length /" + allocationSubnetSize ) ; final IPv6AddressRange rangeToAllocateFrom = findFreeRangeContaining ( toAllocate ) ; if ( rangeToAllocateFrom != null ) { return doAllocate ( toAllocate , rangeToAllocateFrom ) ; } else { return null ; } } | Allocate the given subnet from the pool . |
37,484 | private IPv6AddressPool doAllocate ( final IPv6Network toAllocate , final IPv6AddressRange rangeToAllocateFrom ) { assert freeRanges . contains ( rangeToAllocateFrom ) ; assert rangeToAllocateFrom . contains ( toAllocate ) ; final TreeSet < IPv6AddressRange > newFreeRanges = new TreeSet < IPv6AddressRange > ( this . freeRanges ) ; newFreeRanges . remove ( rangeToAllocateFrom ) ; final List < IPv6AddressRange > newRanges = rangeToAllocateFrom . remove ( toAllocate ) ; newFreeRanges . addAll ( newRanges ) ; return new IPv6AddressPool ( underlyingRange , allocationSubnetSize , newFreeRanges , toAllocate ) ; } | Private helper method to perform the allocation of a subnet within one of the free ranges . |
37,485 | private IPv6AddressRange findFreeRangeBefore ( IPv6Network network ) { for ( IPv6AddressRange freeRange : freeRanges ) { if ( freeRange . getLast ( ) . add ( 1 ) . equals ( network . getFirst ( ) ) ) { return freeRange ; } } return null ; } | Private helper method to find the free range just before the given network . |
37,486 | private IPv6AddressRange findFreeRangeAfter ( IPv6Network network ) { for ( IPv6AddressRange freeRange : freeRanges ) { if ( freeRange . getFirst ( ) . subtract ( 1 ) . equals ( network . getLast ( ) ) ) { return freeRange ; } } return null ; } | Private helper method to find the free range just after the given address . |
37,487 | public boolean canRight ( ) { if ( parent == null ) { return false ; } if ( index + 1 >= parent . getNode ( ) . getGroups ( ) . size ( ) ) { return false ; } return true ; } | Returns true if it is possible to navigate right . |
37,488 | public GroupZipper right ( ) { if ( ! canRight ( ) ) { throw new NoSuchElementException ( "Could not move right because the last node at this level has already been reached" ) ; } index ++ ; node = parent . getNode ( ) . getGroups ( ) . get ( index ) ; return this ; } | Navigates right the tree to the next node at the same level . |
37,489 | public GroupZipper left ( ) { if ( ! canLeft ( ) ) { throw new NoSuchElementException ( "Could not move left because the first node at this level has already been reached" ) ; } index -- ; node = parent . getNode ( ) . getGroups ( ) . get ( index ) ; return this ; } | Navigates left the tree to the previous node at the same level . |
37,490 | public T [ ] simplify ( T [ ] points , double tolerance , boolean highestQuality ) { if ( points == null || points . length <= 2 ) { return points ; } double sqTolerance = tolerance * tolerance ; if ( ! highestQuality ) { points = simplifyRadialDistance ( points , sqTolerance ) ; } points = simplifyDouglasPeucker ( points , sqTolerance ) ; return points ; } | Simplifies a list of points to a shorter list of points . |
37,491 | public static boolean migrate ( final Session session , final MigrationResources resources ) { return MigrationEngine . withSession ( session ) . migrate ( resources ) ; } | Execute all migrations in migration resource collection . |
37,492 | public int getCurrentVersion ( final MigrationType type ) { final Statement select = QueryBuilder . select ( ) . all ( ) . from ( SCHEMA_VERSION_CF ) . where ( QueryBuilder . eq ( TYPE , type . name ( ) ) ) . limit ( 1 ) . setConsistencyLevel ( ConsistencyLevel . ALL ) ; final ResultSet result = session . execute ( select ) ; final Row row = result . one ( ) ; return row == null ? 0 : row . getInt ( VERSION ) ; } | Get current database version for given migration type with ALL consistency . Select one row since migration history is saved ordered descending by timestamp . If there are no rows in the schema_version table return 0 as default database version . Data version is changed by executing migrations . |
37,493 | public boolean updateVersion ( final Migration migration ) { final Statement insert = QueryBuilder . insertInto ( SCHEMA_VERSION_CF ) . value ( TYPE , migration . getType ( ) . name ( ) ) . value ( VERSION , migration . getVersion ( ) ) . value ( TIMESTAMP , System . currentTimeMillis ( ) ) . value ( DESCRIPTION , migration . getDescription ( ) ) . setConsistencyLevel ( ConsistencyLevel . ALL ) ; try { session . execute ( insert ) ; return true ; } catch ( final Exception e ) { LOGGER . error ( "Failed to execute update version statement" , e ) ; return false ; } } | Update current database version to the migration version . This is executed after migration success . |
37,494 | protected void executeWithSchemaAgreement ( Statement statement ) throws SchemaAgreementException { ResultSet result = this . session . execute ( statement ) ; if ( checkSchemaAgreement ( result ) ) { return ; } if ( checkClusterSchemaAgreement ( ) ) { return ; } throw new SchemaAgreementException ( "Failed to propagate schema update to all nodes (schema agreement error)" ) ; } | Execute provided statement and checks if the schema migration has been propagated to all nodes in the cluster . Use this method when executing schema migrations . |
37,495 | @ ConditionalOnMissingBean ( AuthenticationInformationRetriever . class ) public AuthenticationInformationRetriever < HodAuthentication < EntityType . Combined > , HodAuthenticationPrincipal > authenticationInformationRetriever ( ) { @ SuppressWarnings ( "unchecked" ) final AuthenticationInformationRetriever < HodAuthentication < EntityType . Combined > , HodAuthenticationPrincipal > retriever = new SpringSecurityAuthenticationInformationRetriever < > ( ( Class < HodAuthentication < EntityType . Combined > > ) ( Class < ? > ) HodAuthentication . class , HodAuthenticationPrincipal . class ) ; return retriever ; } | Note that this bean cannot go in HavenSearchHodApplication because it would then cause a circular dependency in upstream applications |
37,496 | public static final < T > JPAExecutionResult < T > doSelectStatic ( final Callable < T > aCallable ) { ValueEnforcer . notNull ( aCallable , "Callable" ) ; final StopWatch aSW = StopWatch . createdStarted ( ) ; try { final T ret = aCallable . call ( ) ; s_aStatsCounterSuccess . increment ( ) ; s_aStatsTimerExecutionSuccess . addTime ( aSW . stopAndGetMillis ( ) ) ; return JPAExecutionResult . createSuccess ( ret ) ; } catch ( final Exception ex ) { s_aStatsCounterError . increment ( ) ; s_aStatsTimerExecutionError . addTime ( aSW . stopAndGetMillis ( ) ) ; _invokeCustomExceptionCallback ( ex ) ; return JPAExecutionResult . < T > createFailure ( ex ) ; } finally { if ( isDefaultExecutionWarnTimeEnabled ( ) ) if ( aSW . getMillis ( ) > getDefaultExecutionWarnTime ( ) ) onExecutionTimeExceeded ( "Execution of select took too long: " + aCallable . toString ( ) , aSW . getMillis ( ) ) ; } } | Perform a select without a transaction |
37,497 | public final < T > JPAExecutionResult < T > doSelect ( final Callable < T > aCallable ) { if ( isUseTransactionsForSelect ( ) ) { return doInTransaction ( aCallable ) ; } final EntityManager aEntityMgr = getEntityManager ( ) ; if ( ! isSyncEntityMgr ( ) ) { return doSelectStatic ( aCallable ) ; } synchronized ( aEntityMgr ) { return doSelectStatic ( aCallable ) ; } } | Run a read - only query . By default no transaction is used and the entity manager is synchronized . |
37,498 | public String getPropertyValue ( String key ) { checkArgument ( ! Strings . isNullOrEmpty ( key ) , "key" ) ; String errorMessage = String . format ( "Failed to retrieve %s property from Conqueso server: %s" , key , conquesoUrl . toExternalForm ( ) ) ; return readStringFromUrl ( "properties/" + key , errorMessage ) ; } | Retrieve the latest value for the given property key from the Conqueso Server returned as a String . |
37,499 | public ImmutableList < RoleInfo > getRoles ( ) { TypeReference < List < RoleInfo > > typeReference = new TypeReference < List < RoleInfo > > ( ) { } ; String errorMessage = String . format ( "Failed to retrieve roles from Conqueso server: %s" , conquesoUrl . toExternalForm ( ) ) ; return ImmutableList . copyOf ( readObjectFromJson ( typeReference , "/api/roles" , errorMessage ) ) ; } | Retrieve information about the roles from the Conqueso Server . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.