idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
3,800
public static < T > T getMostCommonElementInList ( List < T > sourceList ) { if ( sourceList == null || sourceList . isEmpty ( ) ) { return null ; } Map < T , Integer > hashMap = new HashMap < T , Integer > ( ) ; for ( T element : sourceList ) { Integer countOrNull = hashMap . get ( element ) ; int newCount = ( countOrNull == null ) ? 1 : ( countOrNull + 1 ) ; hashMap . put ( element , newCount ) ; } Entry < T , Integer > largestEntry = null ; for ( Entry < T , Integer > currentEntry : hashMap . entrySet ( ) ) { if ( largestEntry == null || currentEntry . getValue ( ) > largestEntry . getValue ( ) ) { largestEntry = currentEntry ; } } T result = ( largestEntry == null ) ? null : largestEntry . getKey ( ) ; return result ; }
getMostCommonElementInList This returns the most common element in the supplied list . In the event of a tie any element that is tied as the largest element may be returned . If the list has no elements or if the list is null then this will return null . This can also return null if null happens to be the most common element in the source list .
3,801
static public Insets getScreenInsets ( Window windowOrNull ) { Insets insets ; if ( windowOrNull == null ) { insets = Toolkit . getDefaultToolkit ( ) . getScreenInsets ( GraphicsEnvironment . getLocalGraphicsEnvironment ( ) . getDefaultScreenDevice ( ) . getDefaultConfiguration ( ) ) ; } else { insets = windowOrNull . getToolkit ( ) . getScreenInsets ( windowOrNull . getGraphicsConfiguration ( ) ) ; } return insets ; }
getScreenInsets This returns the insets of the screen which are defined by any task bars that have been set up by the user . This function accounts for multi - monitor setups . If a window is supplied then the the monitor that contains the window will be used . If a window is not supplied then the primary monitor will be used .
3,802
public static DateTimeFormatter generateDefaultFormatterCE ( Locale pickerLocale ) { DateTimeFormatter formatCE = new DateTimeFormatterBuilder ( ) . parseLenient ( ) . parseCaseInsensitive ( ) . appendLocalized ( FormatStyle . LONG , null ) . toFormatter ( pickerLocale ) ; String language = pickerLocale . getLanguage ( ) ; if ( "tr" . equals ( language ) ) { formatCE = PickerUtilities . createFormatterFromPatternString ( "dd MMMM yyyy" , pickerLocale ) ; } return formatCE ; }
generateDefaultFormatterCE This returns a default formatter for the specified locale that can be used for displaying or parsing AD dates . The formatter is generated from the default FormatStyle . LONG formatter in the specified locale .
3,803
public static DateTimeFormatter generateDefaultFormatterBCE ( Locale pickerLocale ) { String displayFormatterBCPattern = DateTimeFormatterBuilder . getLocalizedDateTimePattern ( FormatStyle . LONG , null , IsoChronology . INSTANCE , pickerLocale ) ; displayFormatterBCPattern = displayFormatterBCPattern . replace ( "y" , "u" ) ; DateTimeFormatter displayFormatterBC = new DateTimeFormatterBuilder ( ) . parseLenient ( ) . parseCaseInsensitive ( ) . appendPattern ( displayFormatterBCPattern ) . toFormatter ( pickerLocale ) ; String language = pickerLocale . getLanguage ( ) ; if ( "tr" . equals ( language ) ) { displayFormatterBC = PickerUtilities . createFormatterFromPatternString ( "dd MMMM uuuu" , pickerLocale ) ; } return displayFormatterBC ; }
generateDefaultFormatterBCE This returns a default formatter for the specified locale that can be used for displaying or parsing BC dates . The formatter is generated from the default FormatStyle . LONG formatter in the specified locale . The resulting format is intended to be nearly identical to the default formatter used for AD dates .
3,804
static public LocalDate getParsedDateOrNull ( String text , DateTimeFormatter displayFormatterADStrict , DateTimeFormatter displayFormatterBCStrict , ArrayList < DateTimeFormatter > parsingFormattersStrict , Locale formatLocale ) { if ( text == null || text . trim ( ) . isEmpty ( ) ) { return null ; } text = text . trim ( ) . toLowerCase ( ) ; LocalDate parsedDate = null ; if ( parsedDate == null ) { try { parsedDate = LocalDate . parse ( text , displayFormatterADStrict ) ; } catch ( Exception ex ) { } } if ( parsedDate == null ) { try { parsedDate = LocalDate . parse ( text , displayFormatterBCStrict ) ; } catch ( Exception ex ) { } } for ( int i = 0 ; ( ( parsedDate == null ) && ( i < parsingFormattersStrict . size ( ) ) ) ; ++ i ) { try { parsedDate = LocalDate . parse ( text , parsingFormattersStrict . get ( i ) ) ; } catch ( Exception ex ) { } } return parsedDate ; }
getParsedDateOrNull This takes text from the date picker text field and tries to parse it into a java . time . LocalDate instance . If the text cannot be parsed this will return null .
3,805
static String capitalizeFirstLetterOfString ( String text , Locale locale ) { if ( text == null || text . length ( ) < 1 ) { return text ; } String textCapitalized = text . substring ( 0 , 1 ) . toUpperCase ( locale ) + text . substring ( 1 ) ; return textCapitalized ; }
capitalizeFirstLetterOfString This capitalizes the first letter of the supplied string in a way that is sensitive to the specified locale .
3,806
static public boolean isDateVetoed ( DateVetoPolicy policy , LocalDate date ) { if ( policy == null || date == null ) { return false ; } return ( ! policy . isDateAllowed ( date ) ) ; }
isDateVetoed This is a convenience function for checking whether or not a particular date is vetoed . Note that veto policies do not have any say about null dates so this function always returns false for null dates .
3,807
static public boolean isMouseWithinComponent ( Component component ) { Point mousePos = MouseInfo . getPointerInfo ( ) . getLocation ( ) ; Rectangle bounds = component . getBounds ( ) ; bounds . setLocation ( component . getLocationOnScreen ( ) ) ; return bounds . contains ( mousePos ) ; }
isMouseWithinComponent This returns true if the mouse is inside of the specified component otherwise returns false .
3,808
static public String safeSubstring ( String text , int beginIndex , int endIndexExclusive ) { if ( text == null ) { return null ; } int textLength = text . length ( ) ; if ( beginIndex < 0 ) { beginIndex = 0 ; } if ( endIndexExclusive < 0 ) { endIndexExclusive = 0 ; } if ( endIndexExclusive > textLength ) { endIndexExclusive = textLength ; } if ( beginIndex > endIndexExclusive ) { beginIndex = endIndexExclusive ; } if ( beginIndex == endIndexExclusive ) { return "" ; } return text . substring ( beginIndex , endIndexExclusive ) ; }
safeSubstring This is a version of the substring function which is guaranteed to never throw an exception . If the supplied string is null then this will return null . If the beginIndex or endIndexExclusive are out of range for the string then the indexes will be compressed to fit within the bounds of the supplied string . If the beginIndex is greater than or equal to endIndexExclusive then this will return an empty string .
3,809
public static int getCompiledJavaVersionFromJavaClassFile ( InputStream classByteStream , boolean majorVersionRequested ) throws Exception { DataInputStream dataInputStream = new DataInputStream ( classByteStream ) ; dataInputStream . readInt ( ) ; int minorVersion = dataInputStream . readUnsignedShort ( ) ; int majorVersion = dataInputStream . readUnsignedShort ( ) ; return ( majorVersionRequested ) ? majorVersion : minorVersion ; }
getCompiledJavaVersionFromJavaClassFile Given an input stream to a Java class file this will return the major or minor version of Java that was used to compile the file . In a Maven POM file this is known as the target version of Java that was used to compile the file .
3,810
public static void setDefaultTableEditorsClicks ( JTable table , int clickCountToStart ) { TableCellEditor editor ; editor = table . getDefaultEditor ( Object . class ) ; if ( editor instanceof DefaultCellEditor ) { ( ( DefaultCellEditor ) editor ) . setClickCountToStart ( clickCountToStart ) ; } editor = table . getDefaultEditor ( Number . class ) ; if ( editor instanceof DefaultCellEditor ) { ( ( DefaultCellEditor ) editor ) . setClickCountToStart ( clickCountToStart ) ; } editor = table . getDefaultEditor ( Boolean . class ) ; if ( editor instanceof DefaultCellEditor ) { ( ( DefaultCellEditor ) editor ) . setClickCountToStart ( clickCountToStart ) ; } }
setDefaultTableEditorsClicks This sets the number of clicks required to start the default table editors in the supplied table . Typically you would set the table editors to start after 1 click or 2 clicks as desired .
3,811
public void generatePotentialMenuTimes ( ArrayList < LocalTime > desiredTimes ) { potentialMenuTimes = new ArrayList < LocalTime > ( ) ; if ( desiredTimes == null || desiredTimes . isEmpty ( ) ) { return ; } TreeSet < LocalTime > timeSet = new TreeSet < LocalTime > ( ) ; for ( LocalTime desiredTime : desiredTimes ) { if ( desiredTime != null ) { timeSet . add ( desiredTime ) ; } } for ( LocalTime timeSetEntry : timeSet ) { potentialMenuTimes . add ( timeSetEntry ) ; } }
generatePotentialMenuTimes This will generate the menu times for populating the combo box menu using the items from a list of LocalTime instances . The list will be sorted and cleaned of duplicates before use . Null values and duplicate values will not be added . When this function is complete the menu will contain one instance of each unique LocalTime that was supplied to this function in ascending order going from Midnight to 11 . 59pm . The drop down menu will not contain any time values except those supplied in the desiredTimes list .
3,812
public boolean isTimeAllowed ( LocalTime time ) { if ( time == null ) { return allowEmptyTimes ; } return ( ! ( InternalUtilities . isTimeVetoed ( vetoPolicy , time ) ) ) ; }
isTimeAllowed This checks to see if the specified time is allowed by any currently set veto policy and allowed by the current setting of allowEmptyTimes .
3,813
public void setFormatForDisplayTime ( String patternString ) { DateTimeFormatter formatter = PickerUtilities . createFormatterFromPatternString ( patternString , locale ) ; setFormatForDisplayTime ( formatter ) ; }
setFormatForDisplayTime This sets the format that is used to display or parse the text field time times in the time picker using a pattern string . The default format is generated using the locale of the settings instance .
3,814
public void setFormatForMenuTimes ( String patternString ) { DateTimeFormatter formatter = PickerUtilities . createFormatterFromPatternString ( patternString , locale ) ; setFormatForMenuTimes ( formatter ) ; }
setFormatForMenuTimes This sets the format that is used to display or parse menu times in the time picker using a pattern string . The default format is generated using the locale of the settings instance .
3,815
private void zApplyAllowEmptyTimes ( ) { if ( ( ! allowEmptyTimes ) && ( parent . getTime ( ) == null ) ) { LocalTime defaultTime = LocalTime . of ( 7 , 0 ) ; if ( InternalUtilities . isTimeVetoed ( vetoPolicy , defaultTime ) ) { throw new RuntimeException ( "Exception in TimePickerSettings.zApplyAllowEmptyTimes(), " + "Could not initialize a null time to 7am, because 7am is vetoed by " + "the veto policy. To prevent this exception, always call " + "setAllowEmptyTimes() -before- setting a veto policy." ) ; } parent . setTime ( defaultTime ) ; } }
zApplyAllowEmptyTimes This applies the named setting to the parent component .
3,816
void zApplyDisplaySpinnerButtons ( ) { if ( parent == null ) { return ; } parent . getComponentDecreaseSpinnerButton ( ) . setEnabled ( displaySpinnerButtons ) ; parent . getComponentDecreaseSpinnerButton ( ) . setVisible ( displaySpinnerButtons ) ; parent . getComponentIncreaseSpinnerButton ( ) . setEnabled ( displaySpinnerButtons ) ; parent . getComponentIncreaseSpinnerButton ( ) . setVisible ( displaySpinnerButtons ) ; }
zApplyDisplaySpinnerButtons This applies the specified setting to the time picker .
3,817
void zApplyDisplayToggleTimeMenuButton ( ) { if ( parent == null ) { return ; } parent . getComponentToggleTimeMenuButton ( ) . setEnabled ( displayToggleTimeMenuButton ) ; parent . getComponentToggleTimeMenuButton ( ) . setVisible ( displayToggleTimeMenuButton ) ; }
zApplyDisplayToggleTimeMenuButton This applies the specified setting to the time picker .
3,818
private void zApplyInitialTime ( ) { if ( allowEmptyTimes == true && initialTime == null ) { parent . setTime ( null ) ; } if ( initialTime != null ) { parent . setTime ( initialTime ) ; } }
zApplyInitialTime This applies the named setting to the parent component .
3,819
void zApplyMinimumSpinnerButtonWidthInPixels ( ) { if ( parent == null ) { return ; } Dimension decreaseButtonPreferredSize = parent . getComponentDecreaseSpinnerButton ( ) . getPreferredSize ( ) ; Dimension increaseButtonPreferredSize = parent . getComponentIncreaseSpinnerButton ( ) . getPreferredSize ( ) ; int width = Math . max ( decreaseButtonPreferredSize . width , increaseButtonPreferredSize . width ) ; int height = Math . max ( decreaseButtonPreferredSize . height , increaseButtonPreferredSize . height ) ; int minimumWidth = minimumSpinnerButtonWidthInPixels ; width = ( width < minimumWidth ) ? minimumWidth : width ; Dimension newSize = new Dimension ( width , height ) ; parent . getComponentDecreaseSpinnerButton ( ) . setPreferredSize ( newSize ) ; parent . getComponentIncreaseSpinnerButton ( ) . setPreferredSize ( newSize ) ; }
zApplyMinimumSpinnerButtonWidthInPixels The applies the specified setting to the time picker .
3,820
void zApplyMinimumToggleTimeMenuButtonWidthInPixels ( ) { if ( parent == null ) { return ; } Dimension menuButtonPreferredSize = parent . getComponentToggleTimeMenuButton ( ) . getPreferredSize ( ) ; int width = menuButtonPreferredSize . width ; int height = menuButtonPreferredSize . height ; int minimumWidth = minimumToggleTimeMenuButtonWidthInPixels ; width = ( width < minimumWidth ) ? minimumWidth : width ; Dimension newSize = new Dimension ( width , height ) ; parent . getComponentToggleTimeMenuButton ( ) . setPreferredSize ( newSize ) ; }
zApplyMinimumToggleTimeMenuButtonWidthInPixels This applies the specified setting to the time picker .
3,821
static ConstantSize valueOf ( String encodedValueAndUnit , boolean horizontal ) { String [ ] split = ConstantSize . splitValueAndUnit ( encodedValueAndUnit ) ; String encodedValue = split [ 0 ] ; String encodedUnit = split [ 1 ] ; Unit unit = Unit . valueOf ( encodedUnit , horizontal ) ; double value = Double . parseDouble ( encodedValue ) ; if ( unit . requiresIntegers ) { checkArgument ( value == ( int ) value , "%s value %s must be an integer." , unit , encodedValue ) ; } return new ConstantSize ( value , unit ) ; }
Creates and returns a ConstantSize from the given encoded size and unit description .
3,822
public int getPixelSize ( Component component ) { if ( unit == PIXEL ) { return intValue ( ) ; } else if ( unit == POINT ) { return Sizes . pointAsPixel ( intValue ( ) , component ) ; } else if ( unit == INCH ) { return Sizes . inchAsPixel ( value , component ) ; } else if ( unit == MILLIMETER ) { return Sizes . millimeterAsPixel ( value , component ) ; } else if ( unit == CENTIMETER ) { return Sizes . centimeterAsPixel ( value , component ) ; } else if ( unit == DIALOG_UNITS_X ) { return Sizes . dialogUnitXAsPixel ( intValue ( ) , component ) ; } else if ( unit == DIALOG_UNITS_Y ) { return Sizes . dialogUnitYAsPixel ( intValue ( ) , component ) ; } else { throw new IllegalStateException ( "Invalid unit " + unit ) ; } }
Converts the size if necessary and returns the value in pixels .
3,823
public String encode ( ) { return value == intValue ( ) ? Integer . toString ( intValue ( ) ) + unit . encode ( ) : Double . toString ( value ) + unit . encode ( ) ; }
Returns a parseable string representation of this constant size .
3,824
private static String [ ] splitValueAndUnit ( String encodedValueAndUnit ) { String [ ] result = new String [ 2 ] ; int len = encodedValueAndUnit . length ( ) ; int firstLetterIndex = len ; while ( firstLetterIndex > 0 && Character . isLetter ( encodedValueAndUnit . charAt ( firstLetterIndex - 1 ) ) ) { firstLetterIndex -- ; } result [ 0 ] = encodedValueAndUnit . substring ( 0 , firstLetterIndex ) ; result [ 1 ] = encodedValueAndUnit . substring ( firstLetterIndex ) ; return result ; }
Splits a string that encodes size with unit into the size and unit substrings . Returns an array of two strings .
3,825
public static ColumnSpec decode ( String encodedColumnSpec , LayoutMap layoutMap ) { checkNotBlank ( encodedColumnSpec , "The encoded column specification must not be null, empty or whitespace." ) ; checkNotNull ( layoutMap , "The LayoutMap must not be null." ) ; String trimmed = encodedColumnSpec . trim ( ) ; String lower = trimmed . toLowerCase ( Locale . ENGLISH ) ; return decodeExpanded ( layoutMap . expand ( lower , true ) ) ; }
Parses the encoded column specifications and returns a ColumnSpec object that represents the string . Variables are expanded using the given LayoutMap .
3,826
static ColumnSpec decodeExpanded ( String expandedTrimmedLowerCaseSpec ) { ColumnSpec spec = CACHE . get ( expandedTrimmedLowerCaseSpec ) ; if ( spec == null ) { spec = new ColumnSpec ( expandedTrimmedLowerCaseSpec ) ; CACHE . put ( expandedTrimmedLowerCaseSpec , spec ) ; } return spec ; }
Decodes an expanded trimmed lower case column spec . Called by the public ColumnSpec factory methods . Looks up and returns the ColumnSpec object from the cache - if any or constructs and returns a new ColumnSpec instance .
3,827
public Component getTableCellEditorComponent ( JTable table , Object value , boolean isSelected , int row , int column ) { setCellEditorValue ( value ) ; zAdjustTableRowHeightIfNeeded ( table ) ; timePicker . getComponentTimeTextField ( ) . setScrollOffset ( 0 ) ; return timePicker ; }
getTableCellEditorComponent this returns the editor that is used for editing the cell . This is required by the TableCellEditor interface .
3,828
public Image getIcon ( int iconType ) { Pair < String , Image > pair = iconInformation . get ( iconType ) ; String imagePath = pair . first ; Image imageOrNull = pair . second ; if ( ( imageOrNull == null ) && ( imagePath != null ) ) { imageOrNull = loadImage ( imagePath ) ; } return imageOrNull ; }
getIcon Returns the requested BeanInfo icon type or null if an icon does not exist or cannot be retrieved .
3,829
protected double computeAverageCharWidth ( FontMetrics metrics , String testString ) { int width = metrics . stringWidth ( testString ) ; double average = ( double ) width / testString . length ( ) ; return average ; }
Computes and returns the average character width of the specified test string using the given FontMetrics . The test string shall represent an average text .
3,830
protected int getScreenResolution ( Component c ) { if ( c == null ) { return getDefaultScreenResolution ( ) ; } Toolkit toolkit = c . getToolkit ( ) ; return toolkit != null ? toolkit . getScreenResolution ( ) : getDefaultScreenResolution ( ) ; }
Returns the components screen resolution or the default screen resolution if the component is null or has no toolkit assigned yet .
3,831
public String encode ( ) { StringBuffer buffer = new StringBuffer ( "[" ) ; if ( lowerBound != null ) { buffer . append ( lowerBound . encode ( ) ) ; buffer . append ( ',' ) ; } buffer . append ( basis . encode ( ) ) ; if ( upperBound != null ) { buffer . append ( ',' ) ; buffer . append ( upperBound . encode ( ) ) ; } buffer . append ( ']' ) ; return buffer . toString ( ) ; }
Returns a parseable string representation of this bounded size .
3,832
public static boolean isLocalTimeInRange ( LocalTime value , LocalTime optionalMinimum , LocalTime optionalMaximum , boolean inclusiveOfEndpoints ) { LocalTime minimum = ( optionalMinimum == null ) ? LocalTime . MIN : optionalMinimum ; LocalTime maximum = ( optionalMaximum == null ) ? LocalTime . MAX : optionalMaximum ; if ( value == null ) { return false ; } if ( maximum . isBefore ( minimum ) || maximum . equals ( minimum ) ) { return false ; } if ( inclusiveOfEndpoints ) { return ( ( value . isAfter ( minimum ) || value . equals ( minimum ) ) && ( value . isBefore ( maximum ) || value . equals ( maximum ) ) ) ; } else { return ( value . isAfter ( minimum ) && value . isBefore ( maximum ) ) ; } }
isLocalTimeInRange This returns true if the specified value is inside of the specified range . This returns false if the specified value is outside of the specified range . If the specified value is null then this will return false .
3,833
static public boolean isSameLocalDate ( LocalDate first , LocalDate second ) { if ( first == null && second == null ) { return true ; } if ( first == null || second == null ) { return false ; } return first . isEqual ( second ) ; }
isSameLocalDate This compares two date variables to see if their values are equal . Returns true if the values are equal otherwise returns false .
3,834
public static boolean isSameYearMonth ( YearMonth first , YearMonth second ) { if ( first == null && second == null ) { return true ; } if ( first == null || second == null ) { return false ; } return first . equals ( second ) ; }
isSameYearMonth This compares two YearMonth variables to see if their values are equal . Returns true if the values are equal otherwise returns false .
3,835
public static String localTimeToString ( LocalTime time , String emptyTimeString ) { return ( time == null ) ? emptyTimeString : time . toString ( ) ; }
localTimeToString This will return the supplied time as a string . If the time is null this will return the value of emptyTimeString .
3,836
private static Integer decodeInt ( String token ) { try { return Integer . decode ( token ) ; } catch ( NumberFormatException e ) { return null ; } }
Decodes an integer string representation and returns the associated Integer or null in case of an invalid number format .
3,837
void ensureValidGridBounds ( int colCount , int rowCount ) { if ( gridX <= 0 ) { throw new IndexOutOfBoundsException ( "The column index " + gridX + " must be positive." ) ; } if ( gridX > colCount ) { throw new IndexOutOfBoundsException ( "The column index " + gridX + " must be less than or equal to " + colCount + "." ) ; } if ( gridX + gridWidth - 1 > colCount ) { throw new IndexOutOfBoundsException ( "The grid width " + gridWidth + " must be less than or equal to " + ( colCount - gridX + 1 ) + "." ) ; } if ( gridY <= 0 ) { throw new IndexOutOfBoundsException ( "The row index " + gridY + " must be positive." ) ; } if ( gridY > rowCount ) { throw new IndexOutOfBoundsException ( "The row index " + gridY + " must be less than or equal to " + rowCount + "." ) ; } if ( gridY + gridHeight - 1 > rowCount ) { throw new IndexOutOfBoundsException ( "The grid height " + gridHeight + " must be less than or equal to " + ( rowCount - gridY + 1 ) + "." ) ; } }
Checks and verifies that this constraints object has valid grid index values i . e . the display area cells are inside the form s grid .
3,838
private static void ensureValidOrientations ( Alignment horizontalAlignment , Alignment verticalAlignment ) { if ( ! horizontalAlignment . isHorizontal ( ) ) { throw new IllegalArgumentException ( "The horizontal alignment must be one of: left, center, right, fill, default." ) ; } if ( ! verticalAlignment . isVertical ( ) ) { throw new IllegalArgumentException ( "The vertical alignment must be one of: top, center, bottom, fill, default." ) ; } }
Checks and verifies that the horizontal alignment is a horizontal and the vertical alignment is vertical .
3,839
void setBounds ( Component c , FormLayout layout , Rectangle cellBounds , FormLayout . Measure minWidthMeasure , FormLayout . Measure minHeightMeasure , FormLayout . Measure prefWidthMeasure , FormLayout . Measure prefHeightMeasure ) { ColumnSpec colSpec = gridWidth == 1 ? layout . getColumnSpec ( gridX ) : null ; RowSpec rowSpec = gridHeight == 1 ? layout . getRowSpec ( gridY ) : null ; Alignment concreteHAlign = concreteAlignment ( this . hAlign , colSpec ) ; Alignment concreteVAlign = concreteAlignment ( this . vAlign , rowSpec ) ; Insets concreteInsets = this . insets != null ? this . insets : EMPTY_INSETS ; int cellX = cellBounds . x + concreteInsets . left ; int cellY = cellBounds . y + concreteInsets . top ; int cellW = cellBounds . width - concreteInsets . left - concreteInsets . right ; int cellH = cellBounds . height - concreteInsets . top - concreteInsets . bottom ; int compW = componentSize ( c , colSpec , cellW , minWidthMeasure , prefWidthMeasure ) ; int compH = componentSize ( c , rowSpec , cellH , minHeightMeasure , prefHeightMeasure ) ; int x = origin ( concreteHAlign , cellX , cellW , compW ) ; int y = origin ( concreteVAlign , cellY , cellH , compH ) ; int w = extent ( concreteHAlign , cellW , compW ) ; int h = extent ( concreteVAlign , cellH , compH ) ; c . setBounds ( x , y , w , h ) ; }
Sets the component s bounds using the given component and cell bounds .
3,840
private static int componentSize ( Component component , FormSpec formSpec , int cellSize , FormLayout . Measure minMeasure , FormLayout . Measure prefMeasure ) { if ( formSpec == null ) { return prefMeasure . sizeOf ( component ) ; } else if ( formSpec . getSize ( ) == Sizes . MINIMUM ) { return minMeasure . sizeOf ( component ) ; } else if ( formSpec . getSize ( ) == Sizes . PREFERRED ) { return prefMeasure . sizeOf ( component ) ; } else { return Math . min ( cellSize , prefMeasure . sizeOf ( component ) ) ; } }
Computes and returns the pixel size of the given component using the given form specification measures and cell size .
3,841
private static int origin ( Alignment alignment , int cellOrigin , int cellSize , int componentSize ) { if ( alignment == RIGHT || alignment == BOTTOM ) { return cellOrigin + cellSize - componentSize ; } else if ( alignment == CENTER ) { return cellOrigin + ( cellSize - componentSize ) / 2 ; } else { return cellOrigin ; } }
Computes and returns the component s pixel origin .
3,842
private static String formatInt ( int number ) { String str = Integer . toString ( number ) ; return number < 10 ? " " + str : str ; }
Returns an integer that has a minimum of two characters .
3,843
protected final void firePropertyChange ( String propertyName , Object oldValue , Object newValue ) { PropertyChangeSupport aChangeSupport = this . changeSupport ; if ( aChangeSupport == null ) { return ; } aChangeSupport . firePropertyChange ( propertyName , oldValue , newValue ) ; }
Support for reporting bound property changes for Object properties . This method can be called when a bound property has changed and it will send the appropriate PropertyChangeEvent to any registered PropertyChangeListeners .
3,844
protected final void firePropertyChange ( String propertyName , double oldValue , double newValue ) { firePropertyChange ( propertyName , Double . valueOf ( oldValue ) , Double . valueOf ( newValue ) ) ; }
Support for reporting bound property changes for integer properties . This method can be called when a bound property has changed and it will send the appropriate PropertyChangeEvent to any registered PropertyChangeListeners .
3,845
protected final void fireVetoableChange ( String propertyName , Object oldValue , Object newValue ) throws PropertyVetoException { VetoableChangeSupport aVetoSupport = this . vetoSupport ; if ( aVetoSupport == null ) { return ; } aVetoSupport . fireVetoableChange ( propertyName , oldValue , newValue ) ; }
Support for reporting changes for constrained Object properties . This method can be called before a constrained property will be changed and it will send the appropriate PropertyChangeEvent to any registered VetoableChangeListeners .
3,846
protected final void fireVetoableChange ( String propertyName , long oldValue , long newValue ) throws PropertyVetoException { fireVetoableChange ( propertyName , Long . valueOf ( oldValue ) , Long . valueOf ( newValue ) ) ; }
Support for reporting changes for constrained integer properties . This method can be called before a constrained property will be changed and it will send the appropriate PropertyChangeEvent to any registered VetoableChangeListeners .
3,847
public static void main ( String [ ] args ) { SwingUtilities . invokeLater ( new Runnable ( ) { public void run ( ) { BasicDemo basicDemo = new BasicDemo ( ) ; basicDemo . setVisible ( true ) ; } } ) ; }
main This is the entry point for the basic demo .
3,848
private void parseAndInitValues ( String encodedDescription ) { checkNotBlank ( encodedDescription , "The encoded form specification must not be null, empty or whitespace." ) ; String [ ] token = TOKEN_SEPARATOR_PATTERN . split ( encodedDescription ) ; checkArgument ( token . length > 0 , "The form spec must not be empty." ) ; int nextIndex = 0 ; String next = token [ nextIndex ++ ] ; DefaultAlignment alignment = DefaultAlignment . valueOf ( next , isHorizontal ( ) ) ; if ( alignment != null ) { setDefaultAlignment ( alignment ) ; checkArgument ( token . length > 1 , "The form spec must provide a size." ) ; next = token [ nextIndex ++ ] ; } setSize ( parseSize ( next ) ) ; if ( nextIndex < token . length ) { setResizeWeight ( parseResizeWeight ( token [ nextIndex ] ) ) ; } }
Parses an encoded form specification and initializes all required fields . The encoded description must be in lower case .
3,849
private Size parseSize ( String token ) { if ( token . startsWith ( "[" ) && token . endsWith ( "]" ) ) { return parseBoundedSize ( token ) ; } if ( token . startsWith ( "max(" ) && token . endsWith ( ")" ) ) { return parseOldBoundedSize ( token , false ) ; } if ( token . startsWith ( "min(" ) && token . endsWith ( ")" ) ) { return parseOldBoundedSize ( token , true ) ; } return parseAtomicSize ( token ) ; }
Parses an encoded size spec and returns the size .
3,850
private Size parseAtomicSize ( String token ) { String trimmedToken = token . trim ( ) ; if ( trimmedToken . startsWith ( "'" ) && trimmedToken . endsWith ( "'" ) ) { int length = trimmedToken . length ( ) ; if ( length < 2 ) { throw new IllegalArgumentException ( "Missing closing \"'\" for prototype." ) ; } return new PrototypeSize ( trimmedToken . substring ( 1 , length - 1 ) ) ; } Sizes . ComponentSize componentSize = Sizes . ComponentSize . valueOf ( trimmedToken ) ; if ( componentSize != null ) { return componentSize ; } return ConstantSize . valueOf ( trimmedToken , isHorizontal ( ) ) ; }
Decodes and returns an atomic size that is either a constant size or a component size .
3,851
private static double parseResizeWeight ( String token ) { if ( token . equals ( "g" ) || token . equals ( "grow" ) ) { return DEFAULT_GROW ; } if ( token . equals ( "n" ) || token . equals ( "nogrow" ) || token . equals ( "none" ) ) { return NO_GROW ; } if ( ( token . startsWith ( "grow(" ) || token . startsWith ( "g(" ) ) && token . endsWith ( ")" ) ) { int leftParen = token . indexOf ( '(' ) ; int rightParen = token . indexOf ( ')' ) ; String substring = token . substring ( leftParen + 1 , rightParen ) ; return Double . parseDouble ( substring ) ; } throw new IllegalArgumentException ( "The resize argument '" + token + "' is invalid. " + " Must be one of: grow, g, none, n, grow(<double>), g(<double>)" ) ; }
Decodes an encoded resize mode and resize weight and answers the resize weight .
3,852
public void hide ( ) { if ( displayWindow != null ) { displayWindow . setVisible ( false ) ; displayWindow . removeWindowFocusListener ( this ) ; displayWindow = null ; } if ( topWindow != null ) { topWindow . removeComponentListener ( this ) ; topWindow = null ; } if ( optionalCustomPopupCloseListener != null ) { optionalCustomPopupCloseListener . zEventCustomPopupWasClosed ( this ) ; optionalCustomPopupCloseListener = null ; } }
hide This hides the popup window . This removes this class from the list of window focus listeners for the popup window and removes this class from the list of window movement listeners for the top window . This can be called internally or externally . If this is called multiple times then only the first call will have an effect .
3,853
public void windowLostFocus ( WindowEvent e ) { if ( ! enableHideWhenFocusIsLost ) { e . getWindow ( ) . requestFocus ( ) ; return ; } if ( InternalUtilities . isMouseWithinComponent ( displayWindow ) ) { return ; } hide ( ) ; }
windowLostFocus Part of WindowFocusListener . Whenever the popup window loses focus it will be hidden .
3,854
public java . util . Date getDateWithDefaultZone ( ) { LocalDate pickerDate = parentDatePicker . getDate ( ) ; if ( pickerDate == null ) { return null ; } Instant instant = pickerDate . atStartOfDay ( ZoneId . systemDefault ( ) ) . toInstant ( ) ; java . util . Date javaUtilDate = getJavaUtilDateFromInstant ( instant ) ; return javaUtilDate ; }
getDateWithDefaultZone Returns the date picker value as a java . util . Date that was created using the system default time zone or returns null . This will return null when the date picker has no value .
3,855
public java . util . Date getDateWithZone ( ZoneId timezone ) { LocalDate pickerDate = parentDatePicker . getDate ( ) ; if ( pickerDate == null || timezone == null ) { return null ; } Instant instant = pickerDate . atStartOfDay ( timezone ) . toInstant ( ) ; java . util . Date javaUtilDate = getJavaUtilDateFromInstant ( instant ) ; return javaUtilDate ; }
getDateWithZone Returns the date picker value as a java . util . Date that was created using the specified time zone or returns null . This will return null if either the date picker has no value or if the supplied time zone was null .
3,856
public void setDateWithDefaultZone ( java . util . Date javaUtilDate ) { if ( javaUtilDate == null ) { parentDatePicker . setDate ( null ) ; return ; } Instant instant = Instant . ofEpochMilli ( javaUtilDate . getTime ( ) ) ; ZonedDateTime zonedDateTime = instant . atZone ( ZoneId . systemDefault ( ) ) ; LocalDate localDate = zonedDateTime . toLocalDate ( ) ; parentDatePicker . setDate ( localDate ) ; }
setDateWithDefaultZone Sets the date picker value from a java . util . Date using the system default time zone . If either the date or the time zone are null the date picker will be cleared .
3,857
private java . util . Date getJavaUtilDateFromInstant ( Instant instant ) { java . util . Date javaUtilDate ; try { javaUtilDate = new java . util . Date ( instant . toEpochMilli ( ) ) ; } catch ( ArithmeticException ex ) { throw new IllegalArgumentException ( ex ) ; } return javaUtilDate ; }
getJavaUtilDateFromInstant Converts a Java . time or backport310 instant to a java . util . Date . This code was copied from backport310 and should work in both java . time and backport310 .
3,858
public boolean isDateAllowed ( LocalDate date ) { if ( ( firstAllowedDate != null ) && ( date . isBefore ( firstAllowedDate ) ) ) { return false ; } if ( ( lastAllowedDate != null ) && ( date . isAfter ( lastAllowedDate ) ) ) { return false ; } return true ; }
isDateAllowed This implements the DateVetoPolicy interface . This returns true if the date is allowed otherwise this returns false . The value of null will never be passed to this function under any case .
3,859
public void setDateRangeLimits ( LocalDate firstAllowedDate , LocalDate lastAllowedDate ) { if ( firstAllowedDate == null && lastAllowedDate == null ) { throw new RuntimeException ( "DateVetoPolicyMinimumMaximumDate.setDateRangeLimits()," + "The variable firstAllowedDate can be null, or lastAllowedDate can be null, " + "but both values cannot be null at the same time. " + "If you wish to clear the veto policy, then call the function: " + "'DatePickerSettings.setVetoPolicy(null)'." ) ; } if ( firstAllowedDate != null && lastAllowedDate != null && lastAllowedDate . isBefore ( firstAllowedDate ) ) { throw new RuntimeException ( "\"DateVetoPolicyMinimumMaximumDate.setDateRangeLimits()," + "The lastAllowedDate must be greater than or equal to the firstAllowedDate." ) ; } this . firstAllowedDate = firstAllowedDate ; this . lastAllowedDate = lastAllowedDate ; }
setDateRangeLimits This sets the currently used date limits .
3,860
public static void createAndShowTableDemoFrame ( ) { JFrame frame = new JFrame ( "LGoodDatePicker Table Editors Demo " + InternalUtilities . getProjectVersionString ( ) ) ; frame . setDefaultCloseOperation ( JFrame . DISPOSE_ON_CLOSE ) ; TableEditorsDemo tableDemoPanel = new TableEditorsDemo ( ) ; frame . setContentPane ( tableDemoPanel ) ; tableDemoPanel . setOpaque ( true ) ; frame . pack ( ) ; frame . setSize ( new Dimension ( 1000 , 700 ) ) ; frame . setLocationRelativeTo ( null ) ; frame . setVisible ( true ) ; }
createAndShowTableDemoFrame This creates and displays a frame with the table demo .
3,861
public void setDefaultDialogFont ( Font newFont ) { Font oldFont = defaultDialogFont ; defaultDialogFont = newFont ; clearCache ( ) ; firePropertyChange ( PROPERTY_DEFAULT_DIALOG_FONT , oldFont , newFont ) ; }
Sets a dialog font that will be used to compute the dialog base units .
3,862
private static Font lookupDefaultDialogFont ( ) { Font buttonFont = UIManager . getFont ( "Button.font" ) ; return buttonFont != null ? buttonFont : new JButton ( ) . getFont ( ) ; }
Looks up and returns the font used by buttons . First tries to request the button font from the UIManager ; if this fails a JButton is created and asked for its font .
3,863
IntTree < V > changeKeysAbove ( final long key , final int delta ) { if ( size == 0 || delta == 0 ) return this ; if ( this . key >= key ) return new IntTree < V > ( this . key + delta , value , left . changeKeysBelow ( key - this . key , - delta ) , right ) ; IntTree < V > newRight = right . changeKeysAbove ( key - this . key , delta ) ; if ( newRight == right ) return this ; return new IntTree < V > ( this . key , value , left , newRight ) ; }
Changes every key k > = key to k + delta .
3,864
public static void copyRecursively ( Path source , Path destination ) throws IOException { if ( Files . isDirectory ( source ) ) { Files . createDirectories ( destination ) ; final Set < Path > sources = listFiles ( source ) ; for ( Path srcFile : sources ) { Path destFile = destination . resolve ( srcFile . getFileName ( ) ) ; copyRecursively ( srcFile , destFile ) ; } } else { Files . copy ( source , destination , StandardCopyOption . COPY_ATTRIBUTES , StandardCopyOption . REPLACE_EXISTING ) ; } }
Copy a directory recursively preserving attributes in particular permissions .
3,865
public static void setScriptPermission ( InstanceConfiguration config , String scriptName ) { if ( SystemUtils . IS_OS_WINDOWS ) { return ; } if ( VersionUtil . isEqualOrGreater_7_0_0 ( config . getClusterConfiguration ( ) . getVersion ( ) ) ) { return ; } CommandLine command = new CommandLine ( "chmod" ) . addArgument ( "755" ) . addArgument ( String . format ( "bin/%s" , scriptName ) ) ; ProcessUtil . executeScript ( config , command ) ; command = new CommandLine ( "sed" ) . addArguments ( "-i''" ) . addArgument ( "-e" ) . addArgument ( "1s:.*:#!/usr/bin/env bash:" , false ) . addArgument ( String . format ( "bin/%s" , scriptName ) ) ; ProcessUtil . executeScript ( config , command ) ; }
Set the 755 permissions on the given script .
3,866
public void lock ( ) { log . info ( "Elasticsearch has started and the maven process has been blocked. Press CTRL+C to stop the process." ) ; synchronized ( lock ) { try { lock . wait ( ) ; } catch ( InterruptedException exception ) { log . warn ( "RunElasticsearchNodeMojo interrupted" ) ; } } }
Causes the current thread to wait indefinitely . This method does not return .
3,867
private File resolveArtifact ( ClusterConfiguration config ) throws ArtifactException , IOException { String flavour = config . getFlavour ( ) ; String version = config . getVersion ( ) ; String artifactId = getArtifactId ( flavour , version ) ; String classifier = getArtifactClassifier ( version ) ; String type = getArtifactType ( version ) ; ElasticsearchArtifact artifactReference = new ElasticsearchArtifact ( artifactId , version , classifier , type ) ; config . getLog ( ) . debug ( "Artifact ref: " + artifactReference ) ; PluginArtifactResolver artifactResolver = config . getArtifactResolver ( ) ; try { config . getLog ( ) . debug ( "Resolving artifact against the local maven repo (stage 1)" ) ; return artifactResolver . resolveArtifact ( artifactReference . getArtifactCoordinates ( ) ) ; } catch ( ArtifactException e ) { config . getLog ( ) . debug ( "Artifact not found; downloading and installing it" ) ; File tempFile = downloadArtifact ( artifactReference , config ) ; config . getLog ( ) . debug ( "Installing " + tempFile + " in the local maven repo" ) ; config . getArtifactInstaller ( ) . installArtifact ( artifactReference . getGroupId ( ) , artifactReference . getArtifactId ( ) , artifactReference . getVersion ( ) , artifactReference . getClassifier ( ) , artifactReference . getType ( ) , tempFile ) ; config . getLog ( ) . debug ( "Resolving artifact against the local maven repo (stage 2)" ) ; return artifactResolver . resolveArtifact ( artifactReference . getArtifactCoordinates ( ) ) ; } }
Resolve the artifact and return a file reference to the local file .
3,868
private File downloadArtifact ( ElasticsearchArtifact artifactReference , ClusterConfiguration config ) throws IOException { String filename = Joiner . on ( "-" ) . skipNulls ( ) . join ( artifactReference . getArtifactId ( ) , artifactReference . getVersion ( ) , artifactReference . getClassifier ( ) ) + "." + artifactReference . getType ( ) ; File tempFile = new File ( FilesystemUtil . getTempDirectory ( ) , filename ) ; tempFile . deleteOnExit ( ) ; FileUtils . deleteQuietly ( tempFile ) ; URL downloadUrl = new URL ( StringUtils . isBlank ( config . getDownloadUrl ( ) ) ? String . format ( ELASTICSEARCH_DOWNLOAD_URL , filename ) : config . getDownloadUrl ( ) ) ; config . getLog ( ) . debug ( "Downloading " + downloadUrl + " to " + tempFile ) ; FileUtils . copyURLToFile ( downloadUrl , tempFile ) ; return tempFile ; }
Download the artifact from the download repository .
3,869
public static boolean isProcessRunning ( String baseDir ) { File pidFile = new File ( baseDir , "pid" ) ; boolean exists = pidFile . isFile ( ) ; return exists ; }
Check whether the PID file created by the ES process exists or not .
3,870
public boolean isInstanceRunning ( String clusterName ) { boolean result ; try { @ SuppressWarnings ( "unchecked" ) Map < String , Object > response = client . get ( "/" , Map . class ) ; result = clusterName . equals ( response . get ( "cluster_name" ) ) ; } catch ( ElasticsearchClientException e ) { result = false ; } return result ; }
Check whether the cluster with the given name exists in the current ES instance .
3,871
public static CommandLine buildKillCommandLine ( String pid ) { CommandLine command ; if ( SystemUtils . IS_OS_WINDOWS ) { command = new CommandLine ( "taskkill" ) . addArgument ( "/F" ) . addArgument ( "/pid" ) . addArgument ( pid ) ; } else { command = new CommandLine ( "kill" ) . addArgument ( pid ) ; } return command ; }
Build an OS dependent command line to kill the process with the given PID .
3,872
public static String getElasticsearchPid ( String baseDir ) { try { String pid = new String ( Files . readAllBytes ( Paths . get ( baseDir , "pid" ) ) ) ; return pid ; } catch ( IOException e ) { throw new IllegalStateException ( String . format ( "Cannot read the PID of the Elasticsearch process from the pid file in directory '%s'" , baseDir ) , e ) ; } }
Read the ES PID from the pid file and return it .
3,873
public static boolean isWindowsProcessAlive ( InstanceConfiguration config , String pid ) { CommandLine command = new CommandLine ( "tasklist" ) . addArgument ( "/FI" ) . addArgument ( "PID eq " + pid , true ) ; List < String > output = executeScript ( config , command , true ) ; String keyword = String . format ( " %s " , pid ) ; boolean isRunning = output . stream ( ) . anyMatch ( s -> s . contains ( keyword ) ) ; return isRunning ; }
Check if the process with the given PID is running or not . This method only handles processes running on Windows .
3,874
public static Map < String , String > createEnvironment ( Map < String , String > environment ) { Map < String , String > result = null ; try { result = EnvironmentUtils . getProcEnvironment ( ) ; } catch ( IOException ex ) { throw new ElasticsearchSetupException ( "Cannot get the current process environment" , ex ) ; } result . remove ( "JAVA_TOOL_OPTIONS" ) ; result . remove ( "JAVA_OPTS" ) ; result . remove ( "ES_HOME" ) ; result . remove ( "ES_JAVA_OPTS" ) ; result . remove ( "ES_PATH_CONF" ) ; result . remove ( "ES_TMPDIR" ) ; if ( environment != null ) { result . putAll ( environment ) ; } return result ; }
Create an environment by merging the current environment and the supplied one . If the supplied environment is null null is returned .
3,875
public File resolveArtifact ( String coordinates ) throws ArtifactException { ArtifactRequest request = new ArtifactRequest ( ) ; Artifact artifact = new DefaultArtifact ( coordinates ) ; request . setArtifact ( artifact ) ; request . setRepositories ( remoteRepositories ) ; log . debug ( String . format ( "Resolving artifact %s from %s" , artifact , remoteRepositories ) ) ; ArtifactResult result ; try { result = repositorySystem . resolveArtifact ( repositorySession , request ) ; } catch ( ArtifactResolutionException e ) { throw new ArtifactException ( e . getMessage ( ) , e ) ; } log . debug ( String . format ( "Resolved artifact %s to %s from %s" , artifact , result . getArtifact ( ) . getFile ( ) , result . getRepository ( ) ) ) ; return result . getArtifact ( ) . getFile ( ) ; }
Resolves an Artifact from the repositories .
3,876
public Future < AsperaTransaction > upload ( String bucket , File localFileName , String remoteFileName ) { return upload ( bucket , localFileName , remoteFileName , asperaConfig , null ) ; }
Uploads a file via Aspera FASP
3,877
public AsperaTransaction processTransfer ( String transferSpecStr , String bucketName , String key , String fileName , ProgressListener progressListener ) { String xferId = UUID . randomUUID ( ) . toString ( ) ; AsperaTransactionImpl asperaTransaction = null ; try { TransferProgress transferProgress = new TransferProgress ( ) ; S3ProgressListenerChain listenerChain = new S3ProgressListenerChain ( new TransferProgressUpdatingListener ( transferProgress ) , progressListener ) ; log . trace ( "AsperaTransferManager.processTransfer >> creating AsperaTransactionImpl " + System . nanoTime ( ) ) ; asperaTransaction = new AsperaTransactionImpl ( xferId , bucketName , key , fileName , transferProgress , listenerChain ) ; log . trace ( "AsperaTransferManager.processTransfer << creating AsperaTransactionImpl " + System . nanoTime ( ) ) ; asperaFaspManagerWrapper . setAsperaTransaction ( asperaTransaction ) ; log . trace ( "AsperaTransferManager.processTransfer >> start transfer " + System . nanoTime ( ) ) ; asperaFaspManagerWrapper . startTransfer ( xferId , transferSpecStr ) ; log . trace ( "AsperaTransferManager.processTransfer >> end transfer " + System . nanoTime ( ) ) ; } catch ( IllegalArgumentException e ) { e . printStackTrace ( ) ; } catch ( SecurityException e1 ) { e1 . printStackTrace ( ) ; } return asperaTransaction ; }
Process the transfer spec to call the underlying Aspera libraries to begin the transfer
3,878
public FASPConnectionInfo getFaspConnectionInfo ( String bucketName ) { log . trace ( "AsperaTransferManager.getFaspConnectionInfo >> start " + System . nanoTime ( ) ) ; FASPConnectionInfo faspConnectionInfo = akCache . get ( bucketName ) ; if ( null == faspConnectionInfo ) { log . trace ( "AsperaTransferManager.getFaspConnectionInfo >> retrieve from COS " + System . nanoTime ( ) ) ; faspConnectionInfo = s3Client . getBucketFaspConnectionInfo ( bucketName ) ; log . trace ( "AsperaTransferManager.getFaspConnectionInfo << retrieve from COS " + System . nanoTime ( ) ) ; if ( null == faspConnectionInfo ) { throw new SdkClientException ( "Failed to retrieve faspConnectionInfo for bucket: " + bucketName ) ; } akCache . put ( bucketName , faspConnectionInfo ) ; } log . trace ( "AsperaTransferManager.getFaspConnectionInfo << end " + System . nanoTime ( ) ) ; return faspConnectionInfo ; }
Check the LRU cache to see if the Aspera Key has already been retrieved for this bucket . If it has return it else call onto the s3Client to get the FASPConnectionInfo for the bucket name
3,879
public void checkMultiSessionAllGlobalConfig ( TransferSpecs transferSpecs ) { if ( asperaTransferManagerConfig . isMultiSession ( ) ) { for ( TransferSpec transferSpec : transferSpecs . transfer_specs ) { transferSpec . setRemote_host ( updateRemoteHost ( transferSpec . getRemote_host ( ) ) ) ; } } }
Modify the retrieved TransferSpec and apply an - all suffix to the subdomain on the remote ) host field
3,880
public void modifyTransferSpec ( AsperaConfig sessionDetails , TransferSpecs transferSpecs ) { for ( TransferSpec transferSpec : transferSpecs . transfer_specs ) { if ( ! StringUtils . isNullOrEmpty ( String . valueOf ( sessionDetails . getTargetRateKbps ( ) ) ) ) transferSpec . setTarget_rate_kbps ( sessionDetails . getTargetRateKbps ( ) ) ; if ( ! StringUtils . isNullOrEmpty ( String . valueOf ( sessionDetails . getTargetRateCapKbps ( ) ) ) ) transferSpec . setTarget_rate_cap_kbps ( sessionDetails . getTargetRateCapKbps ( ) ) ; if ( ! StringUtils . isNullOrEmpty ( String . valueOf ( sessionDetails . getMinRateCapKbps ( ) ) ) ) transferSpec . setMin_rate_cap_kbps ( sessionDetails . getMinRateCapKbps ( ) ) ; if ( ! StringUtils . isNullOrEmpty ( String . valueOf ( sessionDetails . getMinRateKbps ( ) ) ) ) transferSpec . setMin_rate_kbps ( sessionDetails . getMinRateKbps ( ) ) ; if ( ! StringUtils . isNullOrEmpty ( sessionDetails . getRatePolicy ( ) ) ) transferSpec . setRate_policy ( sessionDetails . getRatePolicy ( ) ) ; if ( ! StringUtils . isNullOrEmpty ( String . valueOf ( sessionDetails . isLockMinRate ( ) ) ) ) transferSpec . setLock_min_rate ( sessionDetails . isLockMinRate ( ) ) ; if ( ! StringUtils . isNullOrEmpty ( String . valueOf ( sessionDetails . isLockTargetRate ( ) ) ) ) transferSpec . setLock_target_rate ( sessionDetails . isLockTargetRate ( ) ) ; if ( ! StringUtils . isNullOrEmpty ( String . valueOf ( sessionDetails . isLockRatePolicy ( ) ) ) ) transferSpec . setLock_rate_policy ( sessionDetails . isLockRatePolicy ( ) ) ; if ( ! StringUtils . isNullOrEmpty ( sessionDetails . getDestinationRoot ( ) ) ) transferSpec . setDestination_root ( sessionDetails . getDestinationRoot ( ) ) ; if ( ! StringUtils . isNullOrEmpty ( String . valueOf ( sessionDetails . getMultiSession ( ) ) ) ) transferSpec . setMulti_session ( sessionDetails . getMultiSession ( ) ) ; if ( ! StringUtils . isNullOrEmpty ( String . valueOf ( sessionDetails . getMultiSessionThreshold ( ) ) ) ) transferSpec . setMulti_session_threshold ( sessionDetails . getMultiSessionThreshold ( ) ) ; } }
Modify the retrieved TransferSpec with the customised AsperaConfig object created by the user
3,881
public void excludeSubdirectories ( File directory , TransferSpecs transferSpecs ) { if ( directory == null || ! directory . exists ( ) || ! directory . isDirectory ( ) ) { throw new IllegalArgumentException ( "Must provide a directory to upload" ) ; } List < File > files = new LinkedList < File > ( ) ; listFiles ( directory , files ) ; for ( TransferSpec transferSpec : transferSpecs . transfer_specs ) { Vector < NodePath > paths = new Vector < NodePath > ( ) ; for ( File f : files ) { NodePath path = new NodePath ( ) ; path . setDestination ( f . getName ( ) ) ; path . setSource ( f . getAbsolutePath ( ) ) ; paths . add ( path ) ; } transferSpec . setPaths ( paths ) ; } }
List all files within the folder to exclude all subdirectories & modify the transfer spec to pass onto Aspera SDK
3,882
private void listFiles ( File dir , List < File > results ) { File [ ] found = dir . listFiles ( ) ; if ( found != null ) { for ( File f : found ) { if ( f . isDirectory ( ) ) { } else { results . add ( f ) ; } } } }
Lists files in the directory given and adds them to the result list passed in optionally adding subdirectories recursively .
3,883
private String updateRemoteHost ( String remoteHost ) { String [ ] splitStr = remoteHost . split ( "\\." ) ; remoteHost = new StringBuilder ( remoteHost ) . insert ( splitStr [ 0 ] . length ( ) , "-all" ) . toString ( ) ; return remoteHost ; }
Update the remoteHost parameter with the suffix - all within the subdomain name
3,884
protected void checkAscpThreshold ( ) { if ( TransferListener . getAscpCount ( ) >= asperaTransferManagerConfig . getAscpMaxConcurrent ( ) ) { log . error ( "ASCP process threshold has been reached, there are currently " + TransferListener . getAscpCount ( ) + " processes running" ) ; throw new AsperaTransferException ( "ASCP process threshold has been reached" ) ; } }
Check if ascp count has hit limit If it has throw an exception
3,885
public void setProgressListener ( com . ibm . cloud . objectstorage . services . s3 . model . ProgressListener progressListener ) { setGeneralProgressListener ( new LegacyS3ProgressListener ( progressListener ) ) ; }
Sets the optional progress listener for receiving updates about object download status .
3,886
public com . ibm . cloud . objectstorage . services . s3 . model . ProgressListener getProgressListener ( ) { ProgressListener generalProgressListener = getGeneralProgressListener ( ) ; if ( generalProgressListener instanceof LegacyS3ProgressListener ) { return ( ( LegacyS3ProgressListener ) generalProgressListener ) . unwrap ( ) ; } else { return null ; } }
Returns the optional progress listener for receiving updates about object download status .
3,887
public GetObjectRequest withProgressListener ( com . ibm . cloud . objectstorage . services . s3 . model . ProgressListener progressListener ) { setProgressListener ( progressListener ) ; return this ; }
Sets the optional progress listener for receiving updates about object download status and returns this updated object so that additional method calls can be chained together .
3,888
public static boolean isThrottlingException ( SdkBaseException exception ) { if ( ! isAse ( exception ) ) { return false ; } final AmazonServiceException ase = toAse ( exception ) ; return THROTTLING_ERROR_CODES . contains ( ase . getErrorCode ( ) ) || ase . getStatusCode ( ) == 429 ; }
Returns true if the specified exception is a throttling error .
3,889
public static boolean isRequestEntityTooLargeException ( SdkBaseException exception ) { return isAse ( exception ) && toAse ( exception ) . getStatusCode ( ) == HttpStatus . SC_REQUEST_TOO_LONG ; }
Returns true if the specified exception is a request entity too large error .
3,890
public static boolean isClockSkewError ( SdkBaseException exception ) { return isAse ( exception ) && CLOCK_SKEW_ERROR_CODES . contains ( toAse ( exception ) . getErrorCode ( ) ) ; }
Returns true if the specified exception is a clock skew error .
3,891
private static SecuredCEK secureCEK ( SecretKey cek , EncryptionMaterials materials , S3KeyWrapScheme kwScheme , SecureRandom srand , Provider p , AWSKMS kms , AmazonWebServiceRequest req ) { final Map < String , String > matdesc ; if ( materials . isKMSEnabled ( ) ) { matdesc = mergeMaterialDescriptions ( materials , req ) ; EncryptRequest encryptRequest = new EncryptRequest ( ) . withEncryptionContext ( matdesc ) . withKeyId ( materials . getCustomerMasterKeyId ( ) ) . withPlaintext ( ByteBuffer . wrap ( cek . getEncoded ( ) ) ) ; encryptRequest . withGeneralProgressListener ( req . getGeneralProgressListener ( ) ) . withRequestMetricCollector ( req . getRequestMetricCollector ( ) ) ; EncryptResult encryptResult = kms . encrypt ( encryptRequest ) ; byte [ ] keyBlob = copyAllBytesFrom ( encryptResult . getCiphertextBlob ( ) ) ; return new KMSSecuredCEK ( keyBlob , matdesc ) ; } else { matdesc = materials . getMaterialsDescription ( ) ; } Key kek ; if ( materials . getKeyPair ( ) != null ) { kek = materials . getKeyPair ( ) . getPublic ( ) ; } else { kek = materials . getSymmetricKey ( ) ; } String keyWrapAlgo = kwScheme . getKeyWrapAlgorithm ( kek ) ; try { if ( keyWrapAlgo != null ) { Cipher cipher = p == null ? Cipher . getInstance ( keyWrapAlgo ) : Cipher . getInstance ( keyWrapAlgo , p ) ; cipher . init ( Cipher . WRAP_MODE , kek , srand ) ; return new SecuredCEK ( cipher . wrap ( cek ) , keyWrapAlgo , matdesc ) ; } Cipher cipher ; byte [ ] toBeEncryptedBytes = cek . getEncoded ( ) ; String algo = kek . getAlgorithm ( ) ; if ( p != null ) { cipher = Cipher . getInstance ( algo , p ) ; } else { cipher = Cipher . getInstance ( algo ) ; } cipher . init ( Cipher . ENCRYPT_MODE , kek ) ; return new SecuredCEK ( cipher . doFinal ( toBeEncryptedBytes ) , null , matdesc ) ; } catch ( Exception e ) { throw failure ( e , "Unable to encrypt symmetric key" ) ; } }
Secure the given CEK . Note network calls are involved if the CEK is to be protected by KMS .
3,892
public void abort ( ) throws IOException { for ( Transfer fileDownload : subTransfers ) { ( ( DownloadImpl ) fileDownload ) . abortWithoutNotifyingStateChangeListener ( ) ; } for ( Transfer fileDownload : subTransfers ) { ( ( DownloadImpl ) fileDownload ) . notifyStateChangeListeners ( TransferState . Canceled ) ; } }
Aborts all outstanding downloads .
3,893
protected Request < CreateBucketRequest > addIAMHeaders ( Request < CreateBucketRequest > request , CreateBucketRequest createBucketRequest ) { if ( ( null != this . awsCredentialsProvider ) && ( this . awsCredentialsProvider . getCredentials ( ) instanceof IBMOAuthCredentials ) ) { if ( null != createBucketRequest . getServiceInstanceId ( ) ) { request . addHeader ( Headers . IBM_SERVICE_INSTANCE_ID , createBucketRequest . getServiceInstanceId ( ) ) ; if ( null != createBucketRequest . getEncryptionType ( ) ) { request . addHeader ( Headers . IBM_SSE_KP_ENCRYPTION_ALGORITHM , createBucketRequest . getEncryptionType ( ) . getKmsEncryptionAlgorithm ( ) ) ; request . addHeader ( Headers . IBM_SSE_KP_CUSTOMER_ROOT_KEY_CRN , createBucketRequest . getEncryptionType ( ) . getIBMSSEKMSCustomerRootKeyCrn ( ) ) ; } } else { IBMOAuthCredentials oAuthCreds = ( IBMOAuthCredentials ) this . awsCredentialsProvider . getCredentials ( ) ; if ( oAuthCreds . getServiceInstanceId ( ) != null ) { request . addHeader ( Headers . IBM_SERVICE_INSTANCE_ID , oAuthCreds . getServiceInstanceId ( ) ) ; if ( null != createBucketRequest . getEncryptionType ( ) ) { request . addHeader ( Headers . IBM_SSE_KP_ENCRYPTION_ALGORITHM , createBucketRequest . getEncryptionType ( ) . getKmsEncryptionAlgorithm ( ) ) ; request . addHeader ( Headers . IBM_SSE_KP_CUSTOMER_ROOT_KEY_CRN , createBucketRequest . getEncryptionType ( ) . getIBMSSEKMSCustomerRootKeyCrn ( ) ) ; } } } } return request ; }
Add IAM specific headers based on the credentials set & any optional parameters added to the CreateBucketRequest object
3,894
private ContentCryptoMaterial newContentCryptoMaterial ( EncryptionMaterialsProvider kekMaterialProvider , Map < String , String > materialsDescription , Provider provider , AmazonWebServiceRequest req ) { EncryptionMaterials kekMaterials = kekMaterialProvider . getEncryptionMaterials ( materialsDescription ) ; if ( kekMaterials == null ) { return null ; } return buildContentCryptoMaterial ( kekMaterials , provider , req ) ; }
Returns the content encryption material generated with the given kek material material description and security providers ; or null if the encryption material cannot be found for the specified description .
3,895
private ContentCryptoMaterial newContentCryptoMaterial ( EncryptionMaterialsProvider kekMaterialProvider , Provider provider , AmazonWebServiceRequest req ) { EncryptionMaterials kekMaterials = kekMaterialProvider . getEncryptionMaterials ( ) ; if ( kekMaterials == null ) throw new SdkClientException ( "No material available from the encryption material provider" ) ; return buildContentCryptoMaterial ( kekMaterials , provider , req ) ; }
Returns a non - null content encryption material generated with the given kek material and security providers .
3,896
public FASPConnectionInfoHandler parseFASPConnectionInfoResponse ( InputStream inputStream ) throws IOException { FASPConnectionInfoHandler handler = new FASPConnectionInfoHandler ( ) ; parseXmlInputStream ( handler , inputStream ) ; return handler ; }
Parses an FASPConnectionInfoHandler response XML document from an input stream .
3,897
public void setOutputSchemaVersion ( StorageClassAnalysisSchemaVersion outputSchemaVersion ) { if ( outputSchemaVersion == null ) { setOutputSchemaVersion ( ( String ) null ) ; } else { setOutputSchemaVersion ( outputSchemaVersion . toString ( ) ) ; } }
Sets the version of the output schema to use when exporting data .
3,898
public static S3Objects withPrefix ( AmazonS3 s3 , String bucketName , String prefix ) { S3Objects objects = new S3Objects ( s3 , bucketName ) ; objects . prefix = prefix ; return objects ; }
Constructs an iterable that covers the objects in an Amazon S3 bucket where the key begins with the given prefix .
3,899
private static synchronized ProfileCredentialsService getProfileCredentialService ( ) { if ( STS_CREDENTIALS_SERVICE == null ) { try { STS_CREDENTIALS_SERVICE = ( ProfileCredentialsService ) Class . forName ( CLASS_NAME ) . newInstance ( ) ; } catch ( ClassNotFoundException ex ) { throw new SdkClientException ( "To use assume role profiles the aws-java-sdk-sts module must be on the class path." , ex ) ; } catch ( InstantiationException ex ) { throw new SdkClientException ( "Failed to instantiate " + CLASS_NAME , ex ) ; } catch ( IllegalAccessException ex ) { throw new SdkClientException ( "Failed to instantiate " + CLASS_NAME , ex ) ; } } return STS_CREDENTIALS_SERVICE ; }
Only called once per creation of each profile credential provider so we don t bother with any double checked locking .