Package org.cyclos.utils
Class StringHelper
- java.lang.Object
-
- org.cyclos.utils.StringHelper
-
public class StringHelper extends Object
Helper class for strings
-
-
Field Summary
Fields Modifier and Type Field Description static StringALPHANUMERICstatic Function<String,String>HTML_ENTITIES_REMOVERstatic StringLETTERSstatic StringLOWERCASE_LETTERSstatic StringMASKED_VALUEstatic StringNBSPstatic StringNUMBERSstatic Randomrandomstatic StringSPECIAL_CHARACTERSstatic List<String>THYMELEAF_MARKERSA text that must be present in the content in order to consider it to be a Thymeleaf templatestatic StringUPPERCASE_LETTERSstatic PatternVARIABLE_PATTERN
-
Constructor Summary
Constructors Constructor Description StringHelper()
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static booleananyLineMatches(String string, boolean supportsComments, Predicate<String> predicate)Returns whether at least one line matches the given predicate.static booleanareAllBlanks(Object... elements)Returns true if all elements are blanks, otherwise false.static booleanareAllNotBlanks(Object... elements)Returns true if all elements are not blanks, otherwise false.static booleanareNotAllBlanks(Object... elements)Equivalent to the negation ofareAllBlanks(Object...)Warning do not confuse withareAllNotBlanks(Object...)static StringasciiOnly(String string)Removes from the given string all non-ASCII characters, returning null if the input is nullstatic Stringcamelize(String string)Transforms the given string into camel case.static StringcamelizeAndCapitalizeFirst(String string)Same as invokecapitalizeFirst(String)to the result ofcamelize(String)static Stringcapitalize(String string)Returns a string where the first letter is uppercase and all others are lowercasestatic StringcapitalizeAndCamelize(String string)static StringcapitalizeFirst(String string)Transforms the first character of the given string to upper case, handling nulls / empty stringsstatic Stringcoalesce(String... values)Returns the first non-blank valuestatic booleancontainsIgnoreCase(String str, String searchStr)Copied from Apache Commons Lang 3static StringconvertNewLineToBr(String string)static Map<String,String>decodeQueryParameters(String query)Returns a set of parameters like application/x-www-form-urlencoded.static StringdecodeURIComponent(String component)Translates a string back fromapplication/x-www-form-urlencodedformat using UTF-8 as the encoding schemestatic StringdefaultValue(String string, String defaultValue)Returns the value of the second string if the first is blank.static StringdefaultValue(String string, Supplier<String> defaultValue)Lazy version ofdefaultValue(String, String)methodstatic Stringdelimit(String text, String delimiter, int delimitSize)Transforms the given text adding a delimiter every time delimit size is reached.static StringemptyIfNull(String s)Returns an empty string ("") when the parameter value is null.static StringencodeURIComponent(String component)Translates a string intoapplication/x-www-form-urlencodedformat using UTF-8 as the encoding schemestatic voidforEachLine(String string, boolean supportsComments, Consumer<String> consumer)Calls the given procedure for each non-empty untils the last line, trimmed line of the given string.static voidforEachLine(String string, boolean supportsComments, Predicate<String> predicate)Calls the given function for each non-empty while it return true, trimmed line of the given string.static StringformatNumber(String mask, String number, boolean padLeftWithZeros)Replaces the sharps in the mask by the digits found in the number.static StringgetNumberGenerationPattern(String prefix, Integer padLength, String suffix)Returns a pattern which may be used to filter user input based on a transaction number patternstatic booleanhasVariables(String template)static StringhtmlSpace()Returns the String representing an HTML spacestatic StringhtmlSpaces(int count)Returns the String representing n HTML spacesstatic intindexOf(String[] array, String stringToSearch)It returns the index of the first occurrence of the string in the array.static intindexOfAny(String str, String possibleChars)Returns the first index of any of the given charsstatic intindexOfAny(String str, String possibleChars, int fromIndex)Returns the first index of any of the given chars after the given indexstatic booleanisBlank(Object object)Use the object's toString() method and checks whether it is null, empty or blank string (spaces only)static booleanisNotBlank(Object object)Equivalent to the negation ofisBlank(Object)static booleanisNumeric(String text)Returns true if the given string is not null and composed of numbers onlystatic booleanisThymeleaf(String content)Indicates whether the given content contains Thymeleaf markupstatic Stringjoin(Object[] parts, String delimiter)Join the array of strings with the given delimiterstatic Stringjoin(Collection<?> parts, String delimiter)Join the array of strings with the given delimiterstatic StringjoinTrimming(Collection<?> parts, String delimiter)Likejoin(Collection, String), but each part is trimmed, and not used if emptystatic StringleftPad(String input, int size, char padChar)Left pad the specified input String until the specific pad size with the specified char.
If input is null then it returns null.static StringlowercaseFirst(String string)Sets the first character as lower case.static StringmaskDigits(String number, int plainLength)Returns a string with a all numbers replaced to *, except a few digits in the end.static StringmaskEmail(String email)Applies a mask to a given e-mail addressstatic StringmaskPhone(String number)Applies a mask to a given phone numberstatic StringnumbersOnly(String string)Returns only the numbers of the given string.static booleanphoneNumbersMatch(String number1, String number2)Returns whether 2 phone numbers match by suffixstatic Stringrandom(int size, String chars)Returns a random string with a given size, composed of any of the given charactersstatic StringrandomAlphabetic(int length)Returns a random string with the given size, comprised of lettersstatic StringrandomAlphanumeric(int length)Returns a random string with the given size, comprised of letters and numbersstatic StringrandomNumeric(int length)Returns a random string with the given size, comprised of numbersstatic StringremoveEnd(String string, String end)Removes the end of the given string, or returns the original string if end is null or not the final part of the string removeEnd(null, *) == null removeEnd(x, *) == x removeEnd("car", "ar") == "c" removeEnd("car", "r") == "ca" removeEnd("car", "x") == "car"static StringremoveMarkupTags(String string)Removes all html/xml tags, keeping br tags as line breaksstatic StringremoveMarkupTags(String string, boolean includeNL)Removes all html/xml tags and entities, keeping br tags as line breaksstatic StringremoveNonAlpha(String string)Removes any character from the given string which is neither a digit nor a letterstatic StringremoveScripts(String value)Removes all <script> tags from the given stringstatic StringremoveStart(String string, String start)Removes the start of the given string, or returns the original string if end is null or not the initial part of the string removeStart(null, *) == null removeStart(x, *) == x removeStart("car", "ca") == "r" removeStart("car", "c") == "ar" removeStart("car", "x") == "car"static Stringrepeat(String string, int times)Repeats the given string the given number of timesstatic Stringreplace(String text, String repl, String with)Replaces all occurrences of the source text with the destination text in the given stringstatic Stringreplace(String text, String repl, String with, int max)Replaces a specified number of occurrences (-1 means unlimited) of the source text with the destination text in the given stringstatic StringreplacePeriod(String value)Replaces the normal 'Full Stop' char (U+002E, i.e period in North American English) by a 'One Dot Leader' char (U+2024).
This utility method was created to prevent some email clients (e.g GMail) to auto-link the user's name (CYCLOS-10201).static StringreplaceVariables(String template, boolean keepUnusedVariables, Function<String,?> resolver)Replaces variables in the form {varname} or ${varname} with the ones produced by the given function.static StringreplaceVariables(String template, Function<String,?> resolver)Same asreplaceVariables(String, boolean, Function)but discarding unused variabledstatic StringreplaceVariables(String template, Map<String,?> variables)Replaces variables in the form {varname} with the ones in the map.static Stringright(String string, int size)Returns the suffix of the given string with the given size.static StringsafeFilename(String text)Makes the given text safe for being used on filenames.static floatscore(String filter, List<String> texts, Function<String,String> preprocess)Returns a score which indicates how well a set of texts match the given filter.static voidshuffle(StringBuilder sb, Random rnd)Shuffles the characters of the given string builderstatic List<String>split(String input, String separator)Splits a string into an array according to the char specified as separator.static String[]splitByLength(String str, int maxLength)Splits the given string into an array of strings where each element has the given maximum length.static String[]splitPreserveAllTokens(String str, String separatorChars)Splits the provided text into an array, separators specified, preserving all tokens, including empty tokens created by adjacent separators.static List<String>splitTrimming(String input, String separator)Likesplit(String, String), but each part is trimmed, and not returned if emptystatic booleansuffixesEqual(String s1, String s2, int size)Returns whether the suffix with a given size is the same on both stringsstatic SortedSet<Long>toLongSet(String commaSeparated)Splits the string by commas, trimming each element and converting to Long.static StringtransformCase(String string, boolean toUpperCase, char separator)Transforms the given string into upper or lower case, adding the given separator between words.static Stringtrim(Object value)Use the object's toString() method, trimming the result and returning the string.static StringtrimToNull(Object value)Same astrim(Object), but returning null instead of empty stringsstatic Stringtruncate(String string, int maxLength)Truncates the given string without cutting words in the middle, and appending ellipsis in the end.static StringtruncateLines(String string, int maxLines, int maxLengthPerLine)Truncates the given string to a maximum of lines, making each line have a maximum of characters.static Stringunaccent(String string)Replaces any accented characters by the nearest unaccented character, returning null if the input is null.static StringunaccentGwt(String string)A GWT version ofunaccent(String)static StringuncapitalizeFirst(String string)Transforms the first character of the given string to lower case, handling nulls / empty stringsstatic StringurlEncode(Map<String,?> params)Returns a set of parameters like application/x-www-form-urlencoded.static Stringwrap(String text, int wrapLength)Wraps a multi-line text to not break words.
Long word are not wrapped and a "\n" is inserted for each new line that must need to be created.
-
-
-
Field Detail
-
NUMBERS
public static final String NUMBERS
- See Also:
- Constant Field Values
-
UPPERCASE_LETTERS
public static final String UPPERCASE_LETTERS
- See Also:
- Constant Field Values
-
LOWERCASE_LETTERS
public static final String LOWERCASE_LETTERS
-
LETTERS
public static final String LETTERS
-
ALPHANUMERIC
public static final String ALPHANUMERIC
-
SPECIAL_CHARACTERS
public static final String SPECIAL_CHARACTERS
- See Also:
- Constant Field Values
-
NBSP
public static final String NBSP
- See Also:
- Constant Field Values
-
MASKED_VALUE
public static final String MASKED_VALUE
- See Also:
- Constant Field Values
-
VARIABLE_PATTERN
public static final Pattern VARIABLE_PATTERN
-
random
public static Random random
-
-
Method Detail
-
anyLineMatches
public static boolean anyLineMatches(String string, boolean supportsComments, Predicate<String> predicate)
Returns whether at least one line matches the given predicate. If supportsComments is true, lines starting with # are ignored
-
areAllBlanks
public static boolean areAllBlanks(Object... elements)
Returns true if all elements are blanks, otherwise false. AppliesisNotBlank(Object)to all elements to know if at least one element is not blank.
-
areAllNotBlanks
public static boolean areAllNotBlanks(Object... elements)
Returns true if all elements are not blanks, otherwise false. AppliesisBlank(Object)to all elements to know if at least one element is blank. Warning do not confuse withareNotAllBlanks(Object...)(this is not the negation)
-
areNotAllBlanks
public static boolean areNotAllBlanks(Object... elements)
Equivalent to the negation ofareAllBlanks(Object...)Warning do not confuse withareAllNotBlanks(Object...)
-
asciiOnly
public static String asciiOnly(String string)
Removes from the given string all non-ASCII characters, returning null if the input is null
-
camelize
public static String camelize(String string)
Transforms the given string into camel case. Examples:- camelize(null) == null
- camelize("") == ""
- camelize("MY_NAME") == "myName"
- camelize("MyName") == "myname"
-
camelizeAndCapitalizeFirst
public static String camelizeAndCapitalizeFirst(String string)
Same as invokecapitalizeFirst(String)to the result ofcamelize(String)
-
capitalize
public static String capitalize(String string)
Returns a string where the first letter is uppercase and all others are lowercase
-
capitalizeFirst
public static String capitalizeFirst(String string)
Transforms the first character of the given string to upper case, handling nulls / empty strings
-
coalesce
@SafeVarargs public static String coalesce(String... values)
Returns the first non-blank value
-
containsIgnoreCase
public static boolean containsIgnoreCase(String str, String searchStr)
Copied from Apache Commons Lang 3
-
decodeQueryParameters
public static Map<String,String> decodeQueryParameters(String query)
Returns a set of parameters like application/x-www-form-urlencoded. Returns an empty string for null / empty parameters. If the given string starts with either '?', ';' or '#', the first character is ignored. When the same parameter is specified multiple times, join the values with a comma.
-
decodeURIComponent
public static String decodeURIComponent(String component)
Translates a string back fromapplication/x-www-form-urlencodedformat using UTF-8 as the encoding scheme
-
defaultValue
public static String defaultValue(String string, String defaultValue)
Returns the value of the second string if the first is blank. Otherwise, returns the first- See Also:
isBlank(Object)
-
defaultValue
public static String defaultValue(String string, Supplier<String> defaultValue)
Lazy version ofdefaultValue(String, String)method
-
delimit
public static String delimit(String text, String delimiter, int delimitSize)
Transforms the given text adding a delimiter every time delimit size is reached.
Example:- delimit("helloworld", ";", 2) == "he;ll;ow;or;ld"
-
emptyIfNull
public static String emptyIfNull(String s)
Returns an empty string ("") when the parameter value is null. Otherwise, returns the parameter value.
-
encodeURIComponent
public static String encodeURIComponent(String component)
Translates a string intoapplication/x-www-form-urlencodedformat using UTF-8 as the encoding scheme
-
forEachLine
public static void forEachLine(String string, boolean supportsComments, Consumer<String> consumer)
Calls the given procedure for each non-empty untils the last line, trimmed line of the given string. If supportsComments is true, lines starting with # are ignored
-
forEachLine
public static void forEachLine(String string, boolean supportsComments, Predicate<String> predicate)
Calls the given function for each non-empty while it return true, trimmed line of the given string. If supportsComments is true, lines starting with # are ignored
-
formatNumber
public static String formatNumber(String mask, String number, boolean padLeftWithZeros)
Replaces the sharps in the mask by the digits found in the number. If padLeftWithZeros is true, replaces the extra front sharps with zeros.
-
getNumberGenerationPattern
public static String getNumberGenerationPattern(String prefix, Integer padLength, String suffix)
Returns a pattern which may be used to filter user input based on a transaction number pattern
-
hasVariables
public static boolean hasVariables(String template)
-
htmlSpace
public static String htmlSpace()
Returns the String representing an HTML space
-
htmlSpaces
public static String htmlSpaces(int count)
Returns the String representing n HTML spaces
-
indexOf
public static int indexOf(String[] array, String stringToSearch)
It returns the index of the first occurrence of the string in the array. Otherwise it returns -1. Null strings are supported and the index of the first null element in the array is returned (if any).
-
indexOfAny
public static int indexOfAny(String str, String possibleChars)
Returns the first index of any of the given chars
-
indexOfAny
public static int indexOfAny(String str, String possibleChars, int fromIndex)
Returns the first index of any of the given chars after the given index
-
isBlank
public static boolean isBlank(Object object)
Use the object's toString() method and checks whether it is null, empty or blank string (spaces only)
-
isNotBlank
public static boolean isNotBlank(Object object)
Equivalent to the negation ofisBlank(Object)
-
isNumeric
public static boolean isNumeric(String text)
Returns true if the given string is not null and composed of numbers only
-
isThymeleaf
public static boolean isThymeleaf(String content)
Indicates whether the given content contains Thymeleaf markup
-
join
public static String join(Collection<?> parts, String delimiter)
Join the array of strings with the given delimiter
-
join
public static String join(Object[] parts, String delimiter)
Join the array of strings with the given delimiter
-
joinTrimming
public static String joinTrimming(Collection<?> parts, String delimiter)
Likejoin(Collection, String), but each part is trimmed, and not used if empty
-
leftPad
public static String leftPad(String input, int size, char padChar)
Left pad the specified input String until the specific pad size with the specified char.
If input is null then it returns null.
-
lowercaseFirst
public static String lowercaseFirst(String string)
Sets the first character as lower case. Examples:- lowercaseFirst(null) == null
- lowercaseFirst("") == ""
- lowercaseFirst("MY_NAME") == "mY_NAME"
- lowercaseFirst("MyName") == "myName"
-
maskDigits
public static String maskDigits(String number, int plainLength)
Returns a string with a all numbers replaced to *, except a few digits in the end. Example: maskDigits("1234-5678-9876", 4) = "****-****-9876"
-
numbersOnly
public static String numbersOnly(String string)
Returns only the numbers of the given string. Never returns null.
-
phoneNumbersMatch
public static boolean phoneNumbersMatch(String number1, String number2)
Returns whether 2 phone numbers match by suffix
-
random
public static String random(int size, String chars)
Returns a random string with a given size, composed of any of the given characters
-
randomAlphabetic
public static String randomAlphabetic(int length)
Returns a random string with the given size, comprised of letters
-
randomAlphanumeric
public static String randomAlphanumeric(int length)
Returns a random string with the given size, comprised of letters and numbers
-
randomNumeric
public static String randomNumeric(int length)
Returns a random string with the given size, comprised of numbers
-
removeEnd
public static String removeEnd(String string, String end)
Removes the end of the given string, or returns the original string if end is null or not the final part of the string- removeEnd(null, *) == null
- removeEnd(x, *) == x
- removeEnd("car", "ar") == "c"
- removeEnd("car", "r") == "ca"
- removeEnd("car", "x") == "car"
-
removeMarkupTags
public static String removeMarkupTags(String string)
Removes all html/xml tags, keeping br tags as line breaks
-
removeMarkupTags
public static String removeMarkupTags(String string, boolean includeNL)
Removes all html/xml tags and entities, keeping br tags as line breaks
-
removeNonAlpha
public static String removeNonAlpha(String string)
Removes any character from the given string which is neither a digit nor a letter
-
removeScripts
public static String removeScripts(String value)
Removes all <script> tags from the given string
-
removeStart
public static String removeStart(String string, String start)
Removes the start of the given string, or returns the original string if end is null or not the initial part of the string- removeStart(null, *) == null
- removeStart(x, *) == x
- removeStart("car", "ca") == "r"
- removeStart("car", "c") == "ar"
- removeStart("car", "x") == "car"
-
repeat
public static String repeat(String string, int times)
Repeats the given string the given number of times
-
replace
public static String replace(String text, String repl, String with)
Replaces all occurrences of the source text with the destination text in the given string
-
replace
public static String replace(String text, String repl, String with, int max)
Replaces a specified number of occurrences (-1 means unlimited) of the source text with the destination text in the given string
-
replacePeriod
public static String replacePeriod(String value)
Replaces the normal 'Full Stop' char (U+002E, i.e period in North American English) by a 'One Dot Leader' char (U+2024).
This utility method was created to prevent some email clients (e.g GMail) to auto-link the user's name (CYCLOS-10201). Although we already have a validation to avoid URLs in the user's name, the library we use for such validation doesn't detect site.com as a URL allowing saving a user, but GMail does auto-link it anyway (it shouldn't, but what can we do... dad G is dad G ;) )
-
replaceVariables
public static String replaceVariables(String template, boolean keepUnusedVariables, Function<String,?> resolver)
Replaces variables in the form {varname} or ${varname} with the ones produced by the given function. The function receives the variable name and should return the corresponding value. If the function return value is null, an empty string is used instead.
-
replaceVariables
public static String replaceVariables(String template, Function<String,?> resolver)
Same asreplaceVariables(String, boolean, Function)but discarding unused variabled
-
replaceVariables
public static String replaceVariables(String template, Map<String,?> variables)
Replaces variables in the form {varname} with the ones in the map. If a variable is not present on the map, it is replaced with an empty string
-
right
public static String right(String string, int size)
Returns the suffix of the given string with the given size. If the string is shorter than that size, returns empty. Returns null for null input.
-
safeFilename
public static String safeFilename(String text)
Makes the given text safe for being used on filenames. Replaces any special characters by '_', but doesn't return multiple '_' in sequence. Example: "This.'is/a/\\text" results in "This_is_a_text".
-
score
public static float score(String filter, List<String> texts, Function<String,String> preprocess)
Returns a score which indicates how well a set of texts match the given filter. The order of the texts is important: It will have a higher score if it matches the first text. Note: This is currently a very simple algorithm: It just usescontainsIgnoreCase(String, String). Returning 0 means no match. Returning > 0 means some match. When the filter is blank, returns a non-zero result, indicating that all pass.
-
shuffle
public static void shuffle(StringBuilder sb, Random rnd)
Shuffles the characters of the given string builder
-
split
public static List<String> split(String input, String separator)
Splits a string into an array according to the char specified as separator.- Parameters:
input- the string to split. If it's null/empty then the return is an empty list.
-
splitByLength
public static String[] splitByLength(String str, int maxLength)
Splits the given string into an array of strings where each element has the given maximum length. If the string is null or empty, returns an empty array.- Parameters:
maxLength- the maximum length of each element. Must be greater than zero.
-
splitPreserveAllTokens
public static String[] splitPreserveAllTokens(String str, String separatorChars)
Splits the provided text into an array, separators specified, preserving all tokens, including empty tokens created by adjacent separators. This is an alternative to using StringTokenizer.
The separator is not included in the returned String array. Adjacent separators are treated as separators for empty tokens. For more control over the split use the StrTokenizer class.
A
nullinput String returnsnull. AnullseparatorChars splits on whitespace.
-
splitTrimming
public static List<String> splitTrimming(String input, String separator)
Likesplit(String, String), but each part is trimmed, and not returned if empty
-
suffixesEqual
public static boolean suffixesEqual(String s1, String s2, int size)
Returns whether the suffix with a given size is the same on both strings
-
toLongSet
public static SortedSet<Long> toLongSet(String commaSeparated)
Splits the string by commas, trimming each element and converting to Long. Returns an empty set for null / empty input.
-
transformCase
public static String transformCase(String string, boolean toUpperCase, char separator)
Transforms the given string into upper or lower case, adding the given separator between words. Examples:- transformCase(null, *, *) == null
- transformCase("", *, *) == ""
- transformCase("myName", true, '_') == "MY_NAME"
- transformCase("MyName", true, '_') == "MY_NAME"
- transformCase("MyNAME", true, '_') == "MY_N_A_M_E"
- transformCase("myName", false, '-') == "my-name"
- transformCase("MyName", false, '-') == "my-name"
- transformCase("MyNAME", false, '-') == "my-n-a-m-e"
-
trim
public static String trim(Object value)
Use the object's toString() method, trimming the result and returning the string. Never returns null values
-
trimToNull
public static String trimToNull(Object value)
Same astrim(Object), but returning null instead of empty strings
-
truncate
public static String truncate(String string, int maxLength)
Truncates the given string without cutting words in the middle, and appending ellipsis in the end. Line breaks are transformed in spaces.
-
truncateLines
public static String truncateLines(String string, int maxLines, int maxLengthPerLine)
Truncates the given string to a maximum of lines, making each line have a maximum of characters. Empty lines are ignored.
-
unaccent
public static String unaccent(String string)
Replaces any accented characters by the nearest unaccented character, returning null if the input is null. For example, áèïôçñ resuçts in aeiocn
-
unaccentGwt
public static String unaccentGwt(String string)
A GWT version ofunaccent(String)
-
uncapitalizeFirst
public static String uncapitalizeFirst(String string)
Transforms the first character of the given string to lower case, handling nulls / empty strings
-
urlEncode
public static String urlEncode(Map<String,?> params)
Returns a set of parameters like application/x-www-form-urlencoded. Returns an empty string for null / empty parameters.
-
-