idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
27,200
@ SuppressWarnings ( "unchecked" ) protected synchronized FileOutputFormat < K , V > getDelegate ( Configuration conf ) throws IOException { if ( delegate == null ) { delegate = BigQueryOutputConfiguration . getFileOutputFormat ( conf ) ; logger . atInfo ( ) . log ( "Delegating functionality to '%s'." , delegate . getClass ( ) . getSimpleName ( ) ) ; } return delegate ; }
Gets a reference to the underlying delegate used by this OutputFormat .
27,201
public static void validateConfiguration ( Configuration conf ) throws IOException { ConfigurationUtil . getMandatoryConfig ( conf , REQUIRED_KEYS ) ; getProjectId ( conf ) ; getTableSchema ( conf ) ; getFileFormat ( conf ) ; getFileOutputFormat ( conf ) ; getGcsOutputPath ( conf ) ; }
Helper function that validates the output configuration . Ensures the project id dataset id and table id exist in the configuration . This also ensures that if a schema is provided that it is properly formatted .
27,202
static Optional < BigQueryTableSchema > getTableSchema ( Configuration conf ) throws IOException { String fieldsJson = conf . get ( BigQueryConfiguration . OUTPUT_TABLE_SCHEMA_KEY ) ; if ( ! Strings . isNullOrEmpty ( fieldsJson ) ) { try { TableSchema tableSchema = BigQueryTableHelper . createTableSchemaFromFields ( fieldsJson ) ; return Optional . of ( BigQueryTableSchema . wrap ( tableSchema ) ) ; } catch ( IOException e ) { throw new IOException ( "Unable to parse key '" + BigQueryConfiguration . OUTPUT_TABLE_SCHEMA_KEY + "'." , e ) ; } } return Optional . empty ( ) ; }
Gets the output table schema based on the given configuration .
27,203
public static Path getGcsOutputPath ( Configuration conf ) throws IOException { Job tempJob = new JobConfigurationAdapter ( conf ) ; Path outputPath = FileOutputFormat . getOutputPath ( tempJob ) ; if ( outputPath == null ) { throw new IOException ( "FileOutputFormat output path not set." ) ; } FileSystem fs = outputPath . getFileSystem ( conf ) ; if ( ! ( fs instanceof GoogleHadoopFileSystemBase ) ) { throw new IOException ( "Output FileSystem must derive from GoogleHadoopFileSystemBase." ) ; } return outputPath ; }
Gets the stored GCS output path in the configuration .
27,204
public static String getWriteDisposition ( Configuration conf ) { return conf . get ( BigQueryConfiguration . OUTPUT_TABLE_WRITE_DISPOSITION_KEY , BigQueryConfiguration . OUTPUT_TABLE_WRITE_DISPOSITION_DEFAULT ) ; }
Gets the write disposition of the output table . This specifies the action that occurs if the destination table already exists . By default if the table already exists BigQuery appends data to the output table .
27,205
static void setFileOutputFormatOutputPath ( Configuration conf , String outputPath ) throws IOException { Job tempJob = new JobConfigurationAdapter ( conf ) ; FileOutputFormat . setOutputPath ( tempJob , new Path ( outputPath ) ) ; }
Sets the output path for FileOutputFormat .
27,206
public boolean accessDeniedNonRecoverable ( GoogleJsonError e ) { ErrorInfo errorInfo = getErrorInfo ( e ) ; if ( errorInfo != null ) { String reason = errorInfo . getReason ( ) ; return ACCOUNT_DISABLED_REASON_CODE . equals ( reason ) || ACCESS_NOT_CONFIGURED_REASON_CODE . equals ( reason ) ; } return false ; }
Determine if a given GoogleJsonError is caused by and only by account disabled error .
27,207
public boolean isClientError ( IOException e ) { GoogleJsonResponseException jsonException = getJsonResponseExceptionOrNull ( e ) ; if ( jsonException != null ) { return ( getHttpStatusCode ( jsonException ) ) / 100 == 4 ; } return false ; }
Determines if the exception is a client error .
27,208
public boolean fieldSizeTooLarge ( GoogleJsonError e ) { ErrorInfo errorInfo = getErrorInfo ( e ) ; if ( errorInfo != null ) { String reason = errorInfo . getReason ( ) ; return FIELD_SIZE_TOO_LARGE . equals ( reason ) ; } return false ; }
Determines if the given GoogleJsonError indicates field size too large .
27,209
public boolean resourceNotReady ( GoogleJsonError e ) { ErrorInfo errorInfo = getErrorInfo ( e ) ; if ( errorInfo != null ) { String reason = errorInfo . getReason ( ) ; return RESOURCE_NOT_READY_REASON_CODE . equals ( reason ) ; } return false ; }
Determines if the given GoogleJsonError indicates resource not ready .
27,210
public boolean rateLimited ( GoogleJsonError e ) { ErrorInfo errorInfo = getErrorInfo ( e ) ; if ( errorInfo != null ) { String domain = errorInfo . getDomain ( ) ; String reason = errorInfo . getReason ( ) ; boolean isRateLimitedOrGlobalDomain = USAGE_LIMITS_DOMAIN . equals ( domain ) || GLOBAL_DOMAIN . equals ( domain ) ; boolean isRateLimitedReason = RATE_LIMITED_REASON_CODE . equals ( reason ) || USER_RATE_LIMITED_REASON_CODE . equals ( reason ) ; return isRateLimitedOrGlobalDomain && isRateLimitedReason ; } return false ; }
Determine if a given GoogleJsonError is caused by and only by a rate limit being applied .
27,211
public boolean userProjectMissing ( GoogleJsonError e ) { ErrorInfo errorInfo = getErrorInfo ( e ) ; return errorInfo != null && e . getCode ( ) == STATUS_CODE_BAD_REQUEST && USER_PROJECT_MISSING . equals ( errorInfo . getMessage ( ) ) ; }
Determines if the given GoogleJsonError indicates that userProject is missing in request
27,212
public String getErrorMessage ( IOException e ) { GoogleJsonResponseException gjre = getJsonResponseExceptionOrNull ( e ) ; if ( gjre != null && gjre . getDetails ( ) != null ) { return gjre . getDetails ( ) . getMessage ( ) ; } return e . getMessage ( ) ; }
Extracts the error message .
27,213
protected ErrorInfo getErrorInfo ( IOException e ) { GoogleJsonError gjre = getDetails ( e ) ; if ( gjre != null ) { return getErrorInfo ( gjre ) ; } return null ; }
Get the first ErrorInfo from an IOException if it is an instance of GoogleJsonResponseException otherwise return null .
27,214
protected GoogleJsonError getDetails ( IOException e ) { if ( e instanceof GoogleJsonResponseException ) { return ( ( GoogleJsonResponseException ) e ) . getDetails ( ) ; } return null ; }
If the exception is a GoogleJsonResponseException get the error details else return null .
27,215
protected ErrorInfo getErrorInfo ( GoogleJsonError details ) { if ( details == null ) { return null ; } List < ErrorInfo > errors = details . getErrors ( ) ; return errors . isEmpty ( ) ? null : errors . get ( 0 ) ; }
Get the first ErrorInfo from a GoogleJsonError or null if there is not one .
27,216
public void getConfigurationInto ( Entries configuration ) { for ( String prefix : prefixes ) { configuration . setBoolean ( prefix + ENABLE_SERVICE_ACCOUNTS_SUFFIX , isServiceAccountEnabled ( ) ) ; if ( getServiceAccountEmail ( ) != null ) { configuration . set ( prefix + SERVICE_ACCOUNT_EMAIL_SUFFIX , getServiceAccountEmail ( ) ) ; } if ( getServiceAccountPrivateKeyId ( ) != null ) { configuration . set ( prefix + SERVICE_ACCOUNT_PRIVATE_KEY_ID_SUFFIX , getServiceAccountPrivateKeyId ( ) ) ; } if ( getServiceAccountPrivateKey ( ) != null ) { configuration . set ( prefix + SERVICE_ACCOUNT_PRIVATE_KEY_SUFFIX , getServiceAccountPrivateKey ( ) ) ; } if ( getServiceAccountKeyFile ( ) != null ) { configuration . set ( prefix + SERVICE_ACCOUNT_KEYFILE_SUFFIX , getServiceAccountKeyFile ( ) ) ; } if ( getServiceAccountJsonKeyFile ( ) != null ) { configuration . set ( prefix + JSON_KEYFILE_SUFFIX , getServiceAccountJsonKeyFile ( ) ) ; } if ( getClientId ( ) != null ) { configuration . set ( prefix + CLIENT_ID_SUFFIX , getClientId ( ) ) ; } if ( getClientSecret ( ) != null ) { configuration . set ( prefix + CLIENT_SECRET_SUFFIX , getClientSecret ( ) ) ; } if ( getOAuthCredentialFile ( ) != null ) { configuration . set ( prefix + OAUTH_CLIENT_FILE_SUFFIX , getOAuthCredentialFile ( ) ) ; } configuration . setBoolean ( prefix + ENABLE_NULL_CREDENTIAL_SUFFIX , isNullCredentialEnabled ( ) ) ; } if ( getProxyAddress ( ) != null ) { configuration . set ( PROXY_ADDRESS_KEY , getProxyAddress ( ) ) ; } if ( getProxyUsername ( ) != null ) { configuration . set ( PROXY_USERNAME_KEY , getProxyUsername ( ) ) ; } if ( getProxyPassword ( ) != null ) { configuration . set ( PROXY_PASSWORD_KEY , getProxyPassword ( ) ) ; } configuration . set ( HTTP_TRANSPORT_KEY , getTransportType ( ) . name ( ) ) ; }
Gets our parameters and fills it into the specified configuration . Typically the passed - in configuration is an empty instance of a configuration object that extends Entries .
27,217
public void setConfiguration ( Entries entries ) { for ( String prefix : prefixes ) { Optional < Boolean > enableServiceAccounts = maybeGetBoolean ( entries , prefix + ENABLE_SERVICE_ACCOUNTS_SUFFIX ) ; if ( enableServiceAccounts . isPresent ( ) ) { setEnableServiceAccounts ( enableServiceAccounts . get ( ) ) ; } String serviceEmailAccount = entries . getPassword ( prefix + SERVICE_ACCOUNT_EMAIL_SUFFIX ) ; if ( serviceEmailAccount != null ) { setServiceAccountEmail ( serviceEmailAccount ) ; } String serviceAccountPrivateKeyId = entries . getPassword ( prefix + SERVICE_ACCOUNT_PRIVATE_KEY_ID_SUFFIX ) ; if ( serviceAccountPrivateKeyId != null ) { setServiceAccountPrivateKeyId ( serviceAccountPrivateKeyId ) ; } String serviceAccountPrivateKey = entries . getPassword ( prefix + SERVICE_ACCOUNT_PRIVATE_KEY_SUFFIX ) ; if ( serviceAccountPrivateKey != null ) { setServiceAccountPrivateKey ( serviceAccountPrivateKey ) ; } String serviceAccountKeyFile = entries . get ( prefix + SERVICE_ACCOUNT_KEYFILE_SUFFIX ) ; if ( serviceAccountKeyFile != null ) { setServiceAccountKeyFile ( serviceAccountKeyFile ) ; } String serviceAccountJsonKeyFile = entries . get ( prefix + JSON_KEYFILE_SUFFIX ) ; if ( serviceAccountJsonKeyFile != null ) { setServiceAccountJsonKeyFile ( serviceAccountJsonKeyFile ) ; } String clientId = entries . get ( prefix + CLIENT_ID_SUFFIX ) ; if ( clientId != null ) { setClientId ( clientId ) ; } String clientSecret = entries . get ( prefix + CLIENT_SECRET_SUFFIX ) ; if ( clientSecret != null ) { setClientSecret ( clientSecret ) ; } String oAuthCredentialPath = entries . get ( prefix + OAUTH_CLIENT_FILE_SUFFIX ) ; if ( oAuthCredentialPath != null ) { setOAuthCredentialFile ( oAuthCredentialPath ) ; } Optional < Boolean > enableNullCredential = maybeGetBoolean ( entries , prefix + ENABLE_NULL_CREDENTIAL_SUFFIX ) ; if ( enableNullCredential . isPresent ( ) ) { setNullCredentialEnabled ( enableNullCredential . get ( ) ) ; } } String proxyAddress = entries . get ( PROXY_ADDRESS_KEY ) ; if ( proxyAddress != null ) { setProxyAddress ( proxyAddress ) ; } String proxyUsername = entries . getPassword ( PROXY_USERNAME_KEY ) ; if ( proxyUsername != null ) { setProxyUsername ( proxyUsername ) ; } String proxyPassword = entries . getPassword ( PROXY_PASSWORD_KEY ) ; if ( proxyPassword != null ) { setProxyPassword ( proxyPassword ) ; } String transportType = entries . get ( HTTP_TRANSPORT_KEY ) ; if ( transportType != null ) { setTransportType ( HttpTransportType . valueOf ( transportType ) ) ; } }
Load configuration values from the provided configuration source . For any key that does not have a corresponding value in the configuration no changes will be made to the state of this object .
27,218
public void apply ( Insert objectToInsert ) { if ( hasContentGenerationMatch ( ) ) { objectToInsert . setIfGenerationMatch ( getContentGenerationMatch ( ) ) ; } if ( hasMetaGenerationMatch ( ) ) { objectToInsert . setIfMetagenerationMatch ( getMetaGenerationMatch ( ) ) ; } }
Apply the conditions represented by this object to an Insert operation .
27,219
private URI getNextTemporaryPath ( ) { Path basePath = ghfs . getHadoopPath ( finalGcsPath ) ; Path baseDir = basePath . getParent ( ) ; Path tempPath = new Path ( baseDir , String . format ( "%s%s.%d.%s" , TEMPFILE_PREFIX , basePath . getName ( ) , curComponentIndex , UUID . randomUUID ( ) . toString ( ) ) ) ; return ghfs . getGcsPath ( tempPath ) ; }
Returns URI to be used for the next tail file in the series .
27,220
@ API ( status = EXPERIMENTAL ) public List < String > prepare ( final Precorrelation precorrelation , final HttpRequest request ) throws IOException { final String requestLine = String . format ( "%s %s %s" , request . getMethod ( ) , request . getRequestUri ( ) , request . getProtocolVersion ( ) ) ; return prepare ( request , "Request" , precorrelation . getId ( ) , requestLine ) ; }
Produces an HTTP - like request in individual lines .
27,221
@ API ( status = EXPERIMENTAL ) public String format ( final List < String > lines ) { return String . join ( "\n" , lines ) ; }
Renders an HTTP - like message into a printable string .
27,222
public static String appendArray ( final String value , final String [ ] appends ) { validate ( value , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; if ( appends == null || appends . length == 0 ) { return value ; } StringJoiner joiner = new StringJoiner ( "" ) ; for ( String append : appends ) { joiner . add ( append ) ; } return value + joiner . toString ( ) ; }
Append an array of String to value
27,223
public static String [ ] between ( final String value , final String start , final String end ) { validate ( value , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; validate ( start , NULL_STRING_PREDICATE , ( ) -> "'start' should be not null." ) ; validate ( end , NULL_STRING_PREDICATE , ( ) -> "'end' should be not null." ) ; String [ ] parts = value . split ( end ) ; return Arrays . stream ( parts ) . filter ( subPart -> subPart . contains ( start ) ) . map ( subPart -> subPart . substring ( subPart . indexOf ( start ) + start . length ( ) ) ) . toArray ( String [ ] :: new ) ; }
Returns an array with strings between start and end .
27,224
public static String [ ] chars ( final String value ) { validate ( value , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; return value . split ( "" ) ; }
Returns a String array consisting of the characters in the String .
27,225
public static String collapseWhitespace ( final String value ) { validate ( value , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; return value . trim ( ) . replaceAll ( "\\s\\s+" , " " ) ; }
Replace consecutive whitespace characters with a single space .
27,226
public static boolean contains ( final String value , final String needle , final boolean caseSensitive ) { validate ( value , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; if ( caseSensitive ) { return value . contains ( needle ) ; } return value . toLowerCase ( ) . contains ( needle . toLowerCase ( ) ) ; }
Verifies that the needle is contained in the value .
27,227
public static boolean containsAll ( final String value , final String [ ] needles ) { validate ( value , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; return Arrays . stream ( needles ) . allMatch ( needle -> contains ( value , needle , false ) ) ; }
Verifies that all needles are contained in value . The search is case insensitive
27,228
public static boolean containsAny ( final String value , final String [ ] needles , final boolean caseSensitive ) { validate ( value , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; return Arrays . stream ( needles ) . anyMatch ( needle -> contains ( value , needle , caseSensitive ) ) ; }
Verifies that one or more of needles are contained in value .
27,229
public static String ensureLeft ( final String value , final String prefix ) { return ensureLeft ( value , prefix , true ) ; }
Ensures that the value begins with prefix . If it doesn t exist it s prepended . It is case sensitive .
27,230
public static String ensureLeft ( final String value , final String prefix , final boolean caseSensitive ) { validate ( value , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; if ( caseSensitive ) { return value . startsWith ( prefix ) ? value : prefix + value ; } String _value = value . toLowerCase ( ) ; String _prefix = prefix . toLowerCase ( ) ; return _value . startsWith ( _prefix ) ? value : prefix + value ; }
Ensures that the value begins with prefix . If it doesn t exist it s prepended .
27,231
public static String base64Decode ( final String value ) { validate ( value , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; return new String ( Base64 . getDecoder ( ) . decode ( value ) , StandardCharsets . UTF_8 ) ; }
Decodes data encoded with MIME base64
27,232
public static String base64Encode ( final String value ) { validate ( value , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; return Base64 . getEncoder ( ) . encodeToString ( value . getBytes ( StandardCharsets . UTF_8 ) ) ; }
Encodes data with MIME base64 .
27,233
public static String ensureRight ( final String value , final String suffix ) { return ensureRight ( value , suffix , true ) ; }
Ensures that the value ends with suffix . If it doesn t it s appended . This operation is case sensitive .
27,234
public static String ensureRight ( final String value , final String suffix , boolean caseSensitive ) { validate ( value , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; return endsWith ( value , suffix , caseSensitive ) ? value : append ( value , suffix ) ; }
Ensures that the value ends with suffix . If it doesn t it s appended .
27,235
public static Optional < String > first ( final String value , final int n ) { return Optional . ofNullable ( value ) . filter ( v -> ! v . isEmpty ( ) ) . map ( v -> v . substring ( 0 , n ) ) ; }
Returns the first n chars of String
27,236
public static String format ( final String value , String ... params ) { validate ( value , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; Pattern p = Pattern . compile ( "\\{(\\w+)}" ) ; Matcher m = p . matcher ( value ) ; String result = value ; while ( m . find ( ) ) { int paramNumber = Integer . parseInt ( m . group ( 1 ) ) ; if ( params == null || paramNumber >= params . length ) { throw new IllegalArgumentException ( "params does not have value for " + m . group ( ) ) ; } result = result . replace ( m . group ( ) , params [ paramNumber ] ) ; } return result ; }
Formats a string using parameters
27,237
public static String insert ( final String value , final String substr , final int index ) { validate ( value , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; validate ( substr , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; if ( index > value . length ( ) ) { return value ; } return append ( value . substring ( 0 , index ) , substr , value . substring ( index ) ) ; }
Inserts substr into the value at the index provided .
27,238
public static boolean isUpperCase ( final String value ) { validate ( value , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; for ( int i = 0 ; i < value . length ( ) ; i ++ ) { if ( Character . isLowerCase ( value . charAt ( i ) ) ) { return false ; } } return true ; }
Verifies if String is uppercase
27,239
public static String last ( final String value , int n ) { validate ( value , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; if ( n > value . length ( ) ) { return value ; } return value . substring ( value . length ( ) - n ) ; }
Return the last n chars of String
27,240
public static String leftPad ( final String value , final String pad , final int length ) { validate ( value , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; validate ( pad , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; if ( value . length ( ) > length ) { return value ; } return append ( repeat ( pad , length - value . length ( ) ) , value ) ; }
Returns a new string of a given length such that the beginning of the string is padded .
27,241
public static int lastIndexOf ( final String value , final String needle ) { validate ( value , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; return lastIndexOf ( value , needle , value . length ( ) , true ) ; }
This method returns the index within the calling String object of the last occurrence of the specified value searching backwards from the offset . Returns - 1 if the value is not found . The search starts from the end and case sensitive .
27,242
public static int lastIndexOf ( final String value , final String needle , final int offset , final boolean caseSensitive ) { validate ( value , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; validate ( needle , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; if ( caseSensitive ) { return value . lastIndexOf ( needle , offset ) ; } return value . toLowerCase ( ) . lastIndexOf ( needle . toLowerCase ( ) , offset ) ; }
This method returns the index within the calling String object of the last occurrence of the specified value searching backwards from the offset . Returns - 1 if the value is not found .
27,243
public static String leftTrim ( final String value ) { validate ( value , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; return value . replaceAll ( "^\\s+" , "" ) ; }
Removes all spaces on left
27,244
public static String prependArray ( final String value , final String [ ] prepends ) { validate ( value , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; if ( prepends == null || prepends . length == 0 ) { return value ; } StringJoiner joiner = new StringJoiner ( "" ) ; for ( String prepend : prepends ) { joiner . add ( prepend ) ; } return joiner . toString ( ) + value ; }
Return a new String starting with prepends
27,245
public static String [ ] removeEmptyStrings ( String [ ] strings ) { if ( Objects . isNull ( strings ) ) { throw new IllegalArgumentException ( "Input array should not be null" ) ; } return Arrays . stream ( strings ) . filter ( str -> str != null && ! str . trim ( ) . isEmpty ( ) ) . toArray ( String [ ] :: new ) ; }
Remove empty Strings from string array
27,246
public static String removeLeft ( final String value , final String prefix ) { return removeLeft ( value , prefix , true ) ; }
Returns a new String with the prefix removed if present . This is case sensitive .
27,247
public static String removeLeft ( final String value , final String prefix , final boolean caseSensitive ) { validate ( value , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; validate ( prefix , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; if ( caseSensitive ) { return value . startsWith ( prefix ) ? value . substring ( prefix . length ( ) ) : value ; } return value . toLowerCase ( ) . startsWith ( prefix . toLowerCase ( ) ) ? value . substring ( prefix . length ( ) ) : value ; }
Returns a new String with the prefix removed if present .
27,248
public static String removeNonWords ( final String value ) { validate ( value , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; return value . replaceAll ( "[^\\w]+" , "" ) ; }
Remove all non word characters .
27,249
public static String removeRight ( final String value , final String suffix ) { return removeRight ( value , suffix , true ) ; }
Returns a new string with the suffix removed if present . Search is case sensitive .
27,250
public static String removeRight ( final String value , final String suffix , final boolean caseSensitive ) { validate ( value , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; validate ( suffix , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; return endsWith ( value , suffix , caseSensitive ) ? value . substring ( 0 , value . toLowerCase ( ) . lastIndexOf ( suffix . toLowerCase ( ) ) ) : value ; }
Returns a new string with the suffix removed if present .
27,251
public static String removeSpaces ( final String value ) { validate ( value , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; return value . replaceAll ( "\\s" , "" ) ; }
Remove all spaces and replace for value .
27,252
public static String repeat ( final String value , final int multiplier ) { validate ( value , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; return Stream . generate ( ( ) -> value ) . limit ( multiplier ) . collect ( joining ( ) ) ; }
Returns a repeated string given a multiplier .
27,253
public static String replace ( final String value , final String search , final String newValue , final boolean caseSensitive ) { validate ( value , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; validate ( search , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; if ( caseSensitive ) { return value . replace ( search , newValue ) ; } return Pattern . compile ( search , Pattern . CASE_INSENSITIVE ) . matcher ( value ) . replaceAll ( Matcher . quoteReplacement ( newValue ) ) ; }
Replace all occurrences of search value to newvalue . Uses String replace method .
27,254
public static String reverse ( final String value ) { validate ( value , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; return new StringBuilder ( value ) . reverse ( ) . toString ( ) ; }
Reverse the input String
27,255
public static String rightTrim ( final String value ) { validate ( value , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; return value . replaceAll ( "\\s+$" , "" ) ; }
Remove all spaces on right .
27,256
public static String safeTruncate ( final String value , final int length , final String filler ) { validate ( value , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; if ( length == 0 ) { return "" ; } if ( length >= value . length ( ) ) { return value ; } String [ ] words = words ( value ) ; StringJoiner result = new StringJoiner ( " " ) ; int spaceCount = 0 ; for ( String word : words ) { if ( result . length ( ) + word . length ( ) + filler . length ( ) + spaceCount > length ) { break ; } else { result . add ( word ) ; spaceCount ++ ; } } return append ( result . toString ( ) , filler ) ; }
Truncate the string securely not cutting a word in half . It always returns the last full word .
27,257
public static String [ ] split ( final String value , final String regex ) { validate ( value , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; return value . split ( regex ) ; }
Alias to String split function . Defined only for completeness .
27,258
public static String [ ] words ( final String value , final String delimiter ) { validate ( value , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; return value . split ( delimiter ) ; }
Splits a String to words by delimiter \ s + by default
27,259
public static String truncate ( final String value , final int length , final String filler ) { validate ( value , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; if ( length == 0 ) { return "" ; } if ( length >= value . length ( ) ) { return value ; } return append ( value . substring ( 0 , length - filler . length ( ) ) , filler ) ; }
Truncate the unsecured form string cutting the independent string of required position .
27,260
public static String htmlDecode ( final String encodedHtml ) { validate ( encodedHtml , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; String [ ] entities = encodedHtml . split ( "&\\W+;" ) ; return Arrays . stream ( entities ) . map ( e -> HtmlEntities . decodedEntities . get ( e ) ) . collect ( joining ( ) ) ; }
Converts all HTML entities to applicable characters .
27,261
public static String htmlEncode ( final String html ) { validate ( html , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; return html . chars ( ) . mapToObj ( c -> "\\u" + String . format ( "%04x" , c ) . toUpperCase ( ) ) . map ( HtmlEntities . encodedEntities :: get ) . collect ( joining ( ) ) ; }
Convert all applicable characters to HTML entities .
27,262
public static String shuffle ( final String value ) { validate ( value , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; String [ ] chars = chars ( value ) ; Random random = new Random ( ) ; for ( int i = 0 ; i < chars . length ; i ++ ) { int r = random . nextInt ( chars . length ) ; String tmp = chars [ i ] ; chars [ i ] = chars [ r ] ; chars [ r ] = tmp ; } return Arrays . stream ( chars ) . collect ( joining ( ) ) ; }
It returns a string with its characters in random order .
27,263
public static String slice ( final String value , int begin , int end ) { validate ( value , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; return value . substring ( begin , end ) ; }
Alias of substring method
27,264
public static String slugify ( final String value ) { validate ( value , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; String transliterated = transliterate ( collapseWhitespace ( value . trim ( ) . toLowerCase ( ) ) ) ; return Arrays . stream ( words ( transliterated . replace ( "&" , "-and-" ) , "\\W+" ) ) . collect ( joining ( "-" ) ) ; }
Convert a String to a slug
27,265
public static String transliterate ( final String value ) { validate ( value , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; String result = value ; Set < Map . Entry < String , List < String > > > entries = Ascii . ascii . entrySet ( ) ; for ( Map . Entry < String , List < String > > entry : entries ) { for ( String ch : entry . getValue ( ) ) { result = result . replace ( ch , entry . getKey ( ) ) ; } } return result ; }
Remove all non valid characters .
27,266
public static String surround ( final String value , final String prefix , final String suffix ) { validate ( value , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; String _prefix = Optional . ofNullable ( prefix ) . orElse ( "" ) ; return append ( _prefix , value , Optional . ofNullable ( suffix ) . orElse ( _prefix ) ) ; }
Surrounds a value with the given prefix and suffix .
27,267
public static String toCamelCase ( final String value ) { if ( value == null || value . length ( ) == 0 ) { return "" ; } String str = toStudlyCase ( value ) ; return str . substring ( 0 , 1 ) . toLowerCase ( ) + str . substring ( 1 ) ; }
Transform to camelCase
27,268
public static String toStudlyCase ( final String value ) { validate ( value , NULL_STRING_PREDICATE , NULL_STRING_MSG_SUPPLIER ) ; String [ ] words = collapseWhitespace ( value . trim ( ) ) . split ( "\\s*(_|-|\\s)\\s*" ) ; return Arrays . stream ( words ) . filter ( w -> ! w . trim ( ) . isEmpty ( ) ) . map ( Strman :: upperFirst ) . collect ( joining ( ) ) ; }
Transform to StudlyCaps .
27,269
public static Optional < String > tail ( final String value ) { return Optional . ofNullable ( value ) . filter ( v -> ! v . isEmpty ( ) ) . map ( v -> last ( v , v . length ( ) - 1 ) ) ; }
Return tail of the String
27,270
public static String join ( final String [ ] strings , final String separator ) throws IllegalArgumentException { if ( strings == null ) { throw new IllegalArgumentException ( "Input array 'strings' can't be null" ) ; } if ( separator == null ) { throw new IllegalArgumentException ( "separator can't be null" ) ; } StringJoiner joiner = new StringJoiner ( separator ) ; for ( String el : strings ) { joiner . add ( el ) ; } return joiner . toString ( ) ; }
Join concatenates all the elements of the strings array into a single String . The separator string is placed between elements in the resulting string .
27,271
public static String capitalize ( final String input ) throws IllegalArgumentException { if ( input == null ) { throw new IllegalArgumentException ( "input can't be null" ) ; } if ( input . length ( ) == 0 ) { return "" ; } return head ( input ) . map ( String :: toUpperCase ) . map ( h -> tail ( input ) . map ( t -> h + t . toLowerCase ( ) ) . orElse ( h ) ) . get ( ) ; }
Converts the first character of string to upper case and the remaining to lower case .
27,272
public static boolean isEnclosedBetween ( final String input , final String leftEncloser , String rightEncloser ) { if ( input == null ) { throw new IllegalArgumentException ( "input can't be null" ) ; } if ( leftEncloser == null ) { throw new IllegalArgumentException ( "leftEncloser can't be null" ) ; } if ( rightEncloser == null ) { throw new IllegalArgumentException ( "rightEncloser can't be null" ) ; } return input . startsWith ( leftEncloser ) && input . endsWith ( rightEncloser ) ; }
Verifies whether String is enclosed by encloser
27,273
public static String upperFirst ( String input ) { if ( input == null ) { throw new IllegalArgumentException ( "input can't be null" ) ; } return head ( input ) . map ( String :: toUpperCase ) . map ( h -> tail ( input ) . map ( t -> h + t ) . orElse ( h ) ) . get ( ) ; }
Converts the first character of string to upper case .
27,274
public static Optional < String > trimStart ( final String input ) { return Optional . ofNullable ( input ) . filter ( v -> ! v . isEmpty ( ) ) . map ( Strman :: leftTrim ) ; }
Removes leading whitespace from string .
27,275
public static Optional < String > trimStart ( final String input , String ... chars ) { return Optional . ofNullable ( input ) . filter ( v -> ! v . isEmpty ( ) ) . map ( v -> { String pattern = String . format ( "^[%s]+" , join ( chars , "\\" ) ) ; return v . replaceAll ( pattern , "" ) ; } ) ; }
Removes leading characters from string .
27,276
public static Optional < String > trimEnd ( final String input ) { return Optional . ofNullable ( input ) . filter ( v -> ! v . isEmpty ( ) ) . map ( Strman :: rightTrim ) ; }
Removes trailing whitespace from string .
27,277
public static Map < Character , Long > charsCount ( String input ) { if ( isNullOrEmpty ( input ) ) { return Collections . emptyMap ( ) ; } return input . chars ( ) . mapToObj ( c -> ( char ) c ) . collect ( groupingBy ( identity ( ) , counting ( ) ) ) ; }
Counts the number of occurrences of each character in the string
27,278
public static String underscored ( final String input ) { if ( input == null || input . length ( ) == 0 ) { return "" ; } return input . trim ( ) . replaceAll ( "([a-z\\d])([A-Z]+)" , "$1_$2" ) . replaceAll ( "[-\\s]+" , "_" ) . toLowerCase ( ) ; }
Changes passed in string to all lower case and adds underscore between words .
27,279
public static List < String > zip ( String ... inputs ) { if ( inputs . length == 0 ) { return Collections . emptyList ( ) ; } OptionalInt min = Arrays . stream ( inputs ) . mapToInt ( str -> str == null ? 0 : str . length ( ) ) . min ( ) ; if ( ! min . isPresent ( ) ) { return Collections . emptyList ( ) ; } return IntStream . range ( 0 , min . getAsInt ( ) ) . mapToObj ( elementIndex -> Arrays . stream ( inputs ) . map ( input -> String . valueOf ( input . charAt ( elementIndex ) ) ) . collect ( joining ( ) ) ) . collect ( toList ( ) ) ; }
Aggregates the contents of n strings into a single list of tuples .
27,280
public static String humanize ( final String input ) { if ( input == null || input . length ( ) == 0 ) { return "" ; } return upperFirst ( underscored ( input ) . replaceAll ( "_" , " " ) ) ; }
Converts an underscored camelized or dasherized string into a humanized one . Also removes beginning and ending whitespace .
27,281
public static String swapCase ( String input ) { if ( input == null || input . length ( ) == 0 ) { return "" ; } StringBuilder resultBuilder = new StringBuilder ( ) ; for ( char ch : input . toCharArray ( ) ) { if ( Character . isUpperCase ( ch ) ) { resultBuilder . append ( Character . toLowerCase ( ch ) ) ; } else { resultBuilder . append ( Character . toUpperCase ( ch ) ) ; } } return resultBuilder . toString ( ) ; }
Returns a copy of the string in which all the case - based characters have had their case swapped .
27,282
public static String formatNumber ( long number ) { String stringRepresentation = Long . toString ( number ) ; StringBuilder sb = new StringBuilder ( ) ; int bound = stringRepresentation . length ( ) - 1 ; String delimiter = "," ; int counter = 0 ; for ( int i = bound ; i >= 0 ; i -- ) { char c = stringRepresentation . charAt ( i ) ; if ( i != bound && counter % 3 == 0 ) { sb . append ( delimiter ) ; } sb . append ( c ) ; counter ++ ; } return sb . reverse ( ) . toString ( ) ; }
Returns a string representation of the number passed in where groups of three digits are delimited by comma
27,283
public void setPadding ( int left , int top , int right , int bottom ) { if ( ( left | top | right | bottom ) == 0 ) { mState . mPadding = null ; } else { if ( mState . mPadding == null ) { mState . mPadding = new Rect ( ) ; } mState . mPadding . set ( left , top , right , bottom ) ; } invalidateSelf ( ) ; }
Sets padding for the shape .
27,284
public void setThumbColor ( int startColor , int endColor ) { mSeekBarDrawable . setThumbColor ( ColorStateList . valueOf ( startColor ) ) ; if ( mIndicator != null ) mIndicator . setColors ( startColor , endColor ) ; }
Sets the color of the seek thumb as well as the color of the popup indicator .
27,285
public static void setHotspotBounds ( Drawable drawable , int left , int top , int right , int bottom ) { if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . LOLLIPOP ) { int size = ( right - left ) / 8 ; drawable . setHotspotBounds ( left + size , top + size , right - size , bottom - size ) ; } else { drawable . setBounds ( left , top , right , bottom ) ; } }
As our DiscreteSeekBar implementation uses a circular drawable on API < 21 we want to use the same method to set its bounds as the Ripple s hotspot bounds .
27,286
public static void setTextDirection ( TextView textView , int textDirection ) { if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . JELLY_BEAN_MR1 ) { UiCompatNotCrash . setTextDirection ( textView , textDirection ) ; } }
Sets the TextView text direction attribute when possible
27,287
private void checkShowTitle ( Editable s , boolean skipChange ) { if ( isShowTitle ( ) && getWidth ( ) > 0 ) { boolean have = s != null && s . length ( ) > 0 ; if ( have != isHaveText || ( have && skipChange ) ) { isHaveText = have ; animateShowTitle ( isHaveText ) ; } } }
Check show hint title
27,288
public void onDestroy ( ) { CommandServiceImpl impl = mImpl ; if ( impl != null ) { mImpl = null ; impl . destroy ( ) ; } super . onDestroy ( ) ; android . os . Process . killProcess ( android . os . Process . myPid ( ) ) ; }
Kill process when destroy
27,289
public void run ( ) { if ( ! mDone ) { synchronized ( this ) { if ( ! mDone ) { call ( ) ; mDone = true ; try { this . notifyAll ( ) ; } catch ( Exception ignored ) { } } } } }
Run to doing something
27,290
void waitRun ( long waitMillis , int waitNanos , boolean cancelOnTimeOut ) { if ( ! mDone ) { synchronized ( this ) { if ( ! mDone ) { try { this . wait ( waitMillis , waitNanos ) ; } catch ( InterruptedException ignored ) { } finally { if ( ! mDone && cancelOnTimeOut ) mDone = true ; } } } } }
Wait for a period of time to run end
27,291
private static Bitmap checkSource ( Bitmap original , int radius ) { if ( radius < 0 || radius > 256 ) { throw new RuntimeException ( "Blur bitmap radius must >= 1 and <=256." ) ; } if ( original == null ) { throw new NullPointerException ( "Blur bitmap original isn't null." ) ; } if ( original . isRecycled ( ) ) { throw new RuntimeException ( "Blur bitmap can't blur a recycled bitmap." ) ; } Bitmap . Config config = original . getConfig ( ) ; if ( config != Bitmap . Config . ARGB_8888 && config != Bitmap . Config . RGB_565 ) { throw new RuntimeException ( "Blur bitmap only supported Bitmap.Config.ARGB_8888 and Bitmap.Config.RGB_565." ) ; } return ( original ) ; }
Building the bitmap
27,292
public static Bitmap onStackBlur ( Bitmap original , int radius ) { Bitmap bitmap = checkSource ( original , radius ) ; if ( radius == 1 ) { return bitmap ; } nativeStackBlurBitmap ( bitmap , radius ) ; return ( bitmap ) ; }
StackBlur By Jni Bitmap
27,293
public static int [ ] onStackBlurPixels ( int [ ] pix , int w , int h , int radius ) { if ( radius < 0 || radius > 256 ) { throw new RuntimeException ( "Blur bitmap radius must >= 1 and <=256." ) ; } if ( pix == null ) { throw new RuntimeException ( "Blur bitmap pix isn't null." ) ; } if ( pix . length < w * h ) { throw new RuntimeException ( "Blur bitmap pix length must >= w * h." ) ; } nativeStackBlurPixels ( pix , w , h , radius ) ; return ( pix ) ; }
StackBlur By Jni Pixels
27,294
public static float dipToPx ( Resources resources , float dp ) { DisplayMetrics metrics = resources . getDisplayMetrics ( ) ; return TypedValue . applyDimension ( TypedValue . COMPLEX_UNIT_DIP , dp , metrics ) ; }
Change Dip to PX
27,295
public static int modulateColorAlpha ( int color , int alpha ) { int colorAlpha = color >>> 24 ; int scale = alpha + ( alpha >> 7 ) ; int newAlpha = colorAlpha * scale >> 8 ; int r = ( color >> 16 ) & 0xFF ; int g = ( color >> 8 ) & 0xFF ; int b = color & 0xFF ; return newAlpha << 24 | r << 16 | g << 8 | b ; }
Modulate the color to new alpha
27,296
public static int changeColorAlpha ( int color , int alpha ) { int r = ( color >> 16 ) & 0xFF ; int g = ( color >> 8 ) & 0xFF ; int b = color & 0xFF ; return alpha << 24 | r << 16 | g << 8 | b ; }
Change the color to new alpha
27,297
public static boolean isTrueFromAttribute ( AttributeSet attrs , String attribute , boolean defaultValue ) { return attrs . getAttributeBooleanValue ( Ui . androidStyleNameSpace , attribute , defaultValue ) ; }
Get the attribute have enabled value Form android styles namespace
27,298
public static int getBackgroundColor ( Context context , AttributeSet attrs ) { int color = Color . TRANSPARENT ; if ( isHaveAttribute ( attrs , "background" ) ) { int styleId = attrs . getStyleAttribute ( ) ; int [ ] attributesArray = new int [ ] { android . R . attr . background } ; try { TypedArray typedArray = context . obtainStyledAttributes ( styleId , attributesArray ) ; if ( typedArray . length ( ) > 0 ) color = typedArray . getColor ( 0 , color ) ; typedArray . recycle ( ) ; } catch ( Resources . NotFoundException e ) { e . printStackTrace ( ) ; } } return color ; }
Get Background color if the attr is color value
27,299
public static int [ ] getColorsFromArrayRes ( Resources resources , int resId ) { try { @ SuppressLint ( "Recycle" ) TypedArray array = resources . obtainTypedArray ( resId ) ; if ( array . length ( ) > 0 ) { final int len = array . length ( ) ; final int [ ] colors = new int [ len ] ; for ( int i = 0 ; i < len ; i ++ ) { colors [ i ] = array . getColor ( i , 0 ) ; } return colors ; } } catch ( Resources . NotFoundException ignored ) { } return null ; }
Get color array values form array resource