Class StringUtil
java.lang.Object
com.ssgllc.fish.service.util.registered.StringUtil
-
Field Summary
Fields -
Method Summary
Modifier and TypeMethodDescriptionstatic StringcamelToWordPluralizeLast(String string) Converts a camel case string into a space-separated string and pluralizes the last word.
This method is particularly useful when transforming code identifiers into human-readable text that follows English grammar rules, making it ideal for dynamic UI labels or reports based on object properties.static StringcamelToWords(String string) Converts camel case strings into a space-separated string.
This method splits a camel case string (e.g., "CamelCaseString") into separate words ("Camel Case String"), improving readability for display or logging purposes.static booleancontainsStr(String str, String subStr) Checks if a substring exists within another string.
This method returnsfalseif the main string is null.static StringRemoves diacritical marks (accents) from a string and cleans up other non-ASCII characters to ensure a plain ASCII representation.static ObjectdeserializeString(String string, String className) Deserializes a JSON string into an object of the specified class.
This method dynamically loads the class based on the provided class name and then uses Jackson to deserialize the JSON string into an instance of that class.static booleandiffNonBlankStr(String e, String p) Determines if two strings are different and neither is blank.
This method checks that both strings are not blank and do not equal each other, ignoring case.static booleanChecks if two non-blank strings are different, considering case sensitivity.
This method ensures both strings are not blank and are not exactly the same, including case.static booleandiffNonEmptyStr(String e, String p) Determines if two strings are different, ignoring case, and neither is empty.
This method checks that both strings are not empty and do not equal each other, ignoring case.static booleanDetermines if two non-empty strings are different, considering case sensitivity.
This method ensures both strings are not empty and are not exactly the same, including case.static StringencodePassword(String password) Encodes a password using a secure encoding mechanism.
This method is typically used to encode passwords before storing them in a database.static StringfilterByEndsWith(String source, String[] patterns, String delimiter) Filters a string by retaining only those substrings that end with specified patterns.
This method splits the input string by a given delimiter and then filters the resulting tokens by checking if they end with any of the specified patterns.static StringgenerateRandomAlphanumeric(int length) Generates a random alphanumeric string of a specified length.
This method is useful for creating unique identifiers, temporary passwords, or any other random string needs.static StringgenerateRandomAlphaNumericFromString(int length, String allowedChars) Generates a random alphanumeric string of a specified length, using only characters provided in a custom set.
This method allows for precise control over the characters that appear in the resulting string, making it useful for cases where specific character requirements must be met, such as including only certain letters or numbers.static intgenerateRandomInt(int min, int max) Generates a random integer within a specified range.
This method is often used for random indexing, simulations, or whenever a random number is needed within a defined interval.static StringgenerateUnambiguousRandomAlphaNumeric(int length) Generates a random alphanumeric string of a specified length using an unambiguous character set.
This method avoids characters that are easily confused, such as 'O' and '0', 'I' and '1', making it suitable for user-visible codes or keys.static StringgenerateUnambiguousRandomAlphaNumericLowercase(int length) Generates a random alphanumeric string of a specified length using an unambiguous, lowercase-only character set.
This method excludes characters that can be easily confused, such as 'o' and '0', 'l' and '1', and ensures all characters are lowercase.static StringgetAfterLast(String string, String separator) Retrieves the substring after the last occurrence of a specified separator in a string.
If the separator is not found, the method returns the entire string.static StringgetChecksum(String string) Calculates the SHA-256 checksum of a string and returns it in uppercase.
This method is commonly used to verify data integrity through a cryptographic hash.static Longstatic LonggetLongFromString(String number) Converts a string representation of a number into aLong.
This method attempts to parse a string as a long value.static booleanChecks if a string is blank (null, empty, or whitespace only).
This method delegates toStringUtils.isBlankto evaluate the string.static booleanisEmptyStr(String cs) Checks if a string is empty (null or empty string).
This method delegates toStringUtils.isEmptyto evaluate the string.static booleanDetermines if the provided string can be parsed into aFloat.
This method checks if the string is a valid float by attempting to parse it usingtoFloat(String).static booleanDetermines if the provided string can be parsed into anInteger.
This method checks if the string is a valid integer by attempting to parse it usingtoInt(String).static booleanisNotBlank(String cs) Checks if a string is not blank (not null, not empty, and not whitespace only).
This method delegates toStringUtils.isNotBlankto evaluate the string.static booleanisNotEmpty(Object o) Checks if a string is not empty (neither null nor an empty string).
This method delegates toStringUtils.isNotEmptyto evaluate the string.static booleanisOnlySafeCharacters(String string) Determines if the provided string contains only "safe" characters.
"Safe" characters are defined as those that are safe from a SQL injection perspective.static booleanisValidEmail(String email) Validates an email address based on a predefined pattern.
This method checks if the provided email string conforms to a specific pattern that defines a valid email format.static booleanisValidJson(String string) Determines if a string counts as valid JSON and can be parsed as JSON without error.static booleanisValidUUIDString(String string) Checks if the provided string is a valid UUID, with or without dashes.
This method evaluates the string against standard UUID patterns to determine its validity.static StringjoinStr(Collection<String> strs, String separator) Joins a collection of strings into a single string, separated by the specified separator.static StringjoinStrings(String delimiter, Collection<String> strings) Joins a collection of strings into a single string with a specified delimiter.
This method concatenates elements of the provided collection, separating them with the specified delimiter.static StringjoinUniqStr(Collection<String> strs, String separator) Joins a collection of unique, non-blank strings into a single string, separated by the specified separator.
This method first filters out duplicate and blank strings from the input collection before joining.static StringlowerFirstPlural(String str) Converts the first letter of a string to lowercase and then makes the string plural.
This method uses theEnglish.pluralmethod from the Atlassian library to pluralize the string after the first character has been converted to lowercase.parseToList(String input, String delimiter) Splits a string formatted like an array or list, potentially enclosed in brackets, parentheses, or other characters, into a list of strings based on a specified delimiter.static booleanpasswordMatches(String password, String encoded) Checks if a plain password matches its encoded version using a password encoder.
This method is typically used to verify user passwords during authentication processes.static StringConverts a singular word to its plural form according to English language rules.
This method is useful for generating user interfaces or reports where grammatical correctness is required.static StringrandomElementFromList(String[] nameList) Selects a random element from a provided array of strings.
This method is useful for randomly selecting a name or any string from a fixed list.static StringSelects a random female first name from a predefined list of common female first names.
This method is suitable for generating sample data, mock-ups, or for use in situations where random female first names are required.static StringSelects a random last name from a predefined list of common last names.
This method can be used for generating sample data, mock-ups, or wherever random last names are required.static StringSelects a random male first name from a predefined list of common male first names.
This method is useful for generating sample data, mock-ups, or wherever random male first names are needed.static booleansameNonBlankStr(String e, String p) Checks if two strings are the same, ignoring case, and neither is blank.
This method ensures both strings are not blank and are equivalent when ignoring case differences.static booleanChecks if two non-blank strings are exactly the same, considering case sensitivity.
This method ensures both strings are not blank and are exactly the same, including case.static booleansameNonEmptyStr(String e, String p) Checks if two strings are the same, ignoring case, and neither is empty.
This method ensures both strings are not empty and are equivalent when ignoring case differences.static booleanChecks if two non-empty strings are exactly the same, considering case sensitivity.
This method ensures both strings are not empty and are exactly the same, including case.static StringserializeObject(Object object) Serializes an object to JSON using a minimal JSON printer.
This method converts Java objects into a JSON string format while minimizing whitespace and formatting.static StringserializeObjectPretty(Object object) Serializes an object to JSON with indentation for improved readability.
This method converts Java objects into a formatted JSON string, using indents and line breaks to make the output human-readable.static Collection<String> sortStr(Collection<String> strs) Sorts a collection of strings in ascending order.
This method takes a collection of strings and returns a new sorted list.static Collection<String> splitAndClean(String str, String delimiter) Splits a string by a specified delimiter and returns a collection of non-blank, trimmed substrings.
This method trims each substring resulting from the split and filters out any that are blank.Splits a given string into a list of substrings using the specified separator.static StringstringFromUUID(Object uuid) Converts a UUID object into its string representation.static StringRemoves all HTML tags from the input string, returning only the plain text content.static StringtoBase32Str(Object numberObj) Converts an object representing a number into a base-32 string.
This method delegates totoBaseNStr(Object, Integer)with a radix of 32, providing a string representation of the number in base-32.static StringtoBase36Str(Object numberObj) Converts an object representing a number into a base-36 string.
This method delegates totoBaseNStr(Object, Integer)with a radix of 36, providing a string representation of the number in base-36.static StringtoBaseNStr(Object numberObj, Integer radix) Converts an object representing a number into a string in the specified base (radix).
This method first converts the object to aLong, then returns its string representation in the specified radix.static StringtoBaseNStrFromCharList(Long i, Integer radix, char[] characterList) Converts a long integer to a string representation in a custom radix using a specified character list for digit mapping.
This method allows for conversion of numbers to any base betweenCharacter.MIN_RADIXand the length of the character list provided.static StringtoBaseNStrUnambiguous(Object numberObj, Integer radix) Converts an object representing a number into a string in a specified base using an unambiguous character set.
This method uses a predefined set of characters that excludes easily misread characters (like '0', '1', 'o', 'l') to minimize confusion.static StringtoBaseNStrUnambiguousLetters(Object numberObj, Integer radix) Converts an object representing a number into a string in a specified base using an unambiguous set of letters and digits.
This method uses a predefined set of characters that excludes easily misread characters (like 'O', 'I', 'L') to minimize confusion, and delegates the conversion totoBaseNStrFromCharList(Long, Integer, char[])using the 'unambiguousLetters' character set.static FloatAttempts to convert a string to aFloat.
This method uses theFloats.tryParsefunction from Google Guava to safely parse the string into a float.static StringConverts an object representing a number into a hexadecimal string.
This method delegates totoBaseNStr(Object, Integer)with a radix of 16.static IntegerAttempts to convert a string to anInteger.
This method uses theInts.tryParsefunction from Google Guava to safely parse the string into an integer.static StringtoProperCase(String str) Converts all words in a string to proper case, where each word starts with a capital letter and the rest are lowercase.
This method uses theWordUtils.capitalizeFullyfunction from Apache Commons Lang to capitalize each word in the string fully.static StringRetrieves the translation of a specified key for the default language, which is English.
This method is a convenience overload oftranslateTo(String, String)that defaults the language to English ('en').static StringtranslateFullString(String string) Translates a string containing tokens identified by %{key} into English.
This method searches the input string for placeholders in the format %{key} and replaces them with their translations based on the specified language code.static StringtranslateFullStringTo(String string, String language) Translates a string containing tokens identified by %{key} into the specified language.
This method searches the input string for placeholders in the format %{key} and replaces them with their translations based on the specified language code.static StringtranslateTo(String key, String language) Retrieves the translation of a specified key for a given language.
This method queries a cache or a configuration service to fetch the translation based on the key and the specified language.static StringTruncates a string to the specified maximum width.static Collection<String> uniqStr(Collection<String> strs) Returns a collection of unique, non-blank strings from the provided collection.static UUIDuuidFromString(String uuid) Converts a string representation of a UUID into aUUIDobject.static StringConverts a UUID to a database-friendly string format.
This method first converts the UUID to a standard string representation and then transforms it into a format suitable for database storage.
-
Field Details
-
uuidRegex
- See Also:
-
safeCharacterRegex
- See Also:
-
-
Method Details
-
uniqStr
Returns a collection of unique, non-blank strings from the provided collection.- Parameters:
strs- A collection of strings that may contain duplicates and/or blank entries.- Returns:
- A new collection containing only the unique, non-blank strings from the input collection.
Returns an empty collection if the input is null or empty.
Groovy example:
return stringUtil.uniqStr(['abc', 'def', 'def', 'hij'])
Returns:
["abc", "def", "hij"]
SpEL example:
#uniqStr({'abc', 'def', 'def', 'hij'})
Returns:
["abc","def","hij"]
-
splitStr
Splits a given string into a list of substrings using the specified separator.- Parameters:
str- The string to be split.separator- The delimiter used for splitting the string.- Returns:
- A list of substrings resulting from the split operation or null if the input string is null.
Groovy example:
return stringUtil.splitStr("one,two,three", ",")
Returns:
["one", "two", "three"]
SpEL example:
#splitStr("one,two,three", ",")
Returns:
["one","two","three"]Note: If the input string is null, the method returns null.
-
joinStr
Joins a collection of strings into a single string, separated by the specified separator.- Parameters:
strs- The collection of strings to be joined.separator- The delimiter to insert between each element of the collection.- Returns:
- A single string composed of all elements in the collection, separated by the specified delimiter,
or an empty string if the input collection is null or empty.
Groovy example:
return stringUtil.joinStr(['one', 'two', 'three'], ",")
Returns:
"one,two,three"
SpEL example:
#joinStr({'one', 'two', 'three'}, ",")
Returns:
"one,two,three"Note: If the collection of strings is null or empty, the method returns an empty string. If the collection contains null values, this will throw error, filter null values like
#joinStr({'one', null}.?[#this != null], ',')or use #joinStrings method.
-
joinUniqStr
Joins a collection of unique, non-blank strings into a single string, separated by the specified separator.
This method first filters out duplicate and blank strings from the input collection before joining.- Parameters:
strs- The collection of strings that may contain duplicates and/or blank entries.separator- The delimiter to insert between each unique, non-blank element of the collection.- Returns:
- A single string composed of the unique, non-blank elements in the collection, separated by the specified delimiter,
or an empty string if the input collection is null or empty.
Groovy example:
return stringUtil.joinUniqStr(['abc', 'def', 'def', '', 'hij'], ",")
Returns:
"abc,def,hij"
SpEL example:
#joinUniqStr({'abc', 'def', 'def', '', 'hij'}, ",")
Returns:
"abc,def,hij"Note: If the collection of strings is null or empty, the method returns an empty string.
-
truncate
Truncates a string to the specified maximum width.- Parameters:
str- The string to be truncated.maxWidth- The maximum width of the string after truncation.- Returns:
- The truncated string with "..." added if the original length exceeds `maxWidth`.
Groovy example:
return stringUtil.truncate("Hello, world!", 8)
Returns:
"Hello..."
SpEL example:
#truncate("Hello, world!", 8)
Returns:
"Hello..."Note: If the given string is shorter than or equal to `maxWidth`, the original string is returned.
-
deAccent
Removes diacritical marks (accents) from a string and cleans up other non-ASCII characters to ensure a plain ASCII representation.- Parameters:
str- The input string from which accents and non-ASCII characters are to be removed.- Returns:
- The cleaned string, normalized to plain ASCII.
Groovy example:
return stringUtil.deAccent("Café Été")
Returns:
"Cafe Ete"
SpEL example:
#deAccent("Café Été")
Returns:
"Cafe Ete"Note: This method also removes control characters, non-printable characters, and restricts the string to ASCII characters.
-
uuidFromString
Converts a string representation of a UUID into aUUIDobject. Returns null if the input string is empty.- Parameters:
uuid- The string representation of the UUID.- Returns:
- The
UUIDobject or null if the input string is empty.
Groovy example:
return stringUtil.uuidFromString("123e4567-e89b-12d3-a456-426614174000")
Returns:
123e4567-e89b-12d3-a456-426614174000
SpEL example:
#uuidFromString("123e4567-e89b-12d3-a456-426614174000")
Returns:
123e4567-e89b-12d3-a456-426614174000Note: If the input string is null or empty, the method returns null.
-
stringFromUUID
Converts a UUID object into its string representation.- Parameters:
uuid- The UUID object to be converted to a string. Can be null, in which case the method returns null.- Returns:
- The string representation of the UUID or null if the input is null.
Groovy example:
return stringUtil.stringFromUUID(UUID.randomUUID())
Returns:
"4ec6dca3-f68b-4f97-a5e7-537be7a1a5cf"
SpEL example:
#stringFromUUID(T(java.util.UUID).randomUUID())
Returns:
"4ec6dca3-f68b-4f97-a5e7-537be7a1a5cf"
-
uuidStr
Converts a UUID to a database-friendly string format.
This method first converts the UUID to a standard string representation and then transforms it into a format suitable for database storage.- Parameters:
uuid- The UUID to be converted. If null, the method returns null.- Returns:
- The database format of the UUID string, or null if the input is null.
Groovy example:
return stringUtil.uuidStr(UUID.randomUUID())
Returns:
"DB123E4567E89B12D3A456426614174000"
SpEL example:
#uuidStr(T(java.util.UUID).randomUUID())
Returns:
"DB123E4567E89B12D3A456426614174000"Note: The output format will be different based on the type of database being used for the application.
-
isValidUUIDString
Checks if the provided string is a valid UUID, with or without dashes.
This method evaluates the string against standard UUID patterns to determine its validity.- Parameters:
string- The string to be checked. If the string is empty, the method considers it valid.- Returns:
trueif the string is a valid UUID format (with or without dashes),falseotherwise.
Groovy example:
return stringUtil.isValidUUIDString("123e4567-e89b-12d3-a456-426614174000")
Returns:
true
SpEL example:
#isValidUUIDString("123e4567-e89b-12d3-a456-426614174000")
Returns:
true
-
isOnlySafeCharacters
Determines if the provided string contains only "safe" characters.
"Safe" characters are defined as those that are safe from a SQL injection perspective. This includes alphanumeric characters, spaces, and several common punctuation marks.- Parameters:
string- The string to be evaluated. If the string is empty, it is considered safe and the method returns true.- Returns:
trueif the string contains only safe characters as defined by thesafeCharacterRegex;falseotherwise.
Groovy example:
return stringUtil.isOnlySafeCharacters("Hello, World!")
Returns:
true
SpEL example:
#isOnlySafeCharacters("Hello; DROP TABLE Students")
Returns:
false
-
sortStr
Sorts a collection of strings in ascending order.
This method takes a collection of strings and returns a new sorted list. If the input collection is null or empty, an empty list is returned.- Parameters:
strs- The collection of strings to be sorted.- Returns:
- A new list containing the sorted strings, or an empty list if the input collection is null or empty.
Groovy example:
return stringUtil.sortStr(["banana", "apple", "cherry"])
Returns:
["apple", "banana", "cherry"]
SpEL example:
#sortStr({"banana", "apple", "cherry"})
Returns:
["apple", "banana", "cherry"]
-
getLongFromString
Converts a string representation of a number into aLong.
This method attempts to parse a string as a long value. If the string is null, the method returns null. If the string cannot be parsed as a long, this method will throw aNumberFormatException.- Parameters:
number- The string representing the number to be converted to a long.- Returns:
- The long value represented by the string, or null if the input string is null.
Groovy example:
return stringUtil.getLongFromString("12345")
Returns:
12345
SpEL example:
#getLongFromString("67890")
Returns:
67890
-
getLong
Converts an object to itsLongrepresentation if possible.
This method supports conversion from objects of typeLong,Integer, orString. If the object is of another type or cannot be converted to a long, the method returns null. If the object is null, it also returns null.- Parameters:
number- The object to be converted to a long. This can be an instance of Long, Integer, or String.- Returns:
- The Long representation of the object, or null if the conversion is not possible or the input is null.
Groovy example:
return stringUtil.getLong(12345) // Integer
return stringUtil.getLong("67890") // String
return stringUtil.getLong(123456789012345) // Long
Returns:
12345
67890
123456789012345
SpEL example:
#getLong(12345)
#getLong("67890")
#getLong(123456789012345)
Returns:
12345
67890
123456789012345
-
toHexStr
Converts an object representing a number into a hexadecimal string.
This method delegates totoBaseNStr(Object, Integer)with a radix of 16.- Parameters:
numberObj- The object representing the number to be converted to a hexadecimal string.- Returns:
- The hexadecimal string representation of the number, or null if the number cannot be converted.
Groovy example:
return stringUtil.toHexStr(255)
Returns:
"FF"
SpEL example:
#toHexStr(255)
Returns:
"FF"
-
toBase32Str
Converts an object representing a number into a base-32 string.
This method delegates totoBaseNStr(Object, Integer)with a radix of 32, providing a string representation of the number in base-32.- Parameters:
numberObj- The object representing the number to be converted to a base-32 string.- Returns:
- The base-32 string representation of the number, or null if the number cannot be converted.
Groovy example:
return stringUtil.toBase32Str(255)
Returns:
"7V"
SpEL example:
#toBase32Str(255)
Returns:
"7V"
-
toBase36Str
Converts an object representing a number into a base-36 string.
This method delegates totoBaseNStr(Object, Integer)with a radix of 36, providing a string representation of the number in base-36.- Parameters:
numberObj- The object representing the number to be converted to a base-36 string.- Returns:
- The base-36 string representation of the number, or null if the number cannot be converted.
Groovy example:
return stringUtil.toBase36Str(255)
Returns:
"73"
SpEL example:
#toBase36Str(255)
Returns:
"73"
-
toBaseNStr
Converts an object representing a number into a string in the specified base (radix).
This method first converts the object to aLong, then returns its string representation in the specified radix. If the object cannot be converted to a long, the method returns null.- Parameters:
numberObj- The object representing the number to be converted.radix- The base (radix) in which the number should be converted. Common radix values are 2 (binary), 8 (octal), 10 (decimal), and 16 (hexadecimal).- Returns:
- The string representation of the number in the specified radix, or null if the number cannot be converted.
Groovy example:
return stringUtil.toBaseNStr(255, 2)
Returns:
"11111111"
SpEL example:
#toBaseNStr(255, 2)
Returns:
"11111111"
-
toBaseNStrFromCharList
Converts a long integer to a string representation in a custom radix using a specified character list for digit mapping.
This method allows for conversion of numbers to any base betweenCharacter.MIN_RADIXand the length of the character list provided. If the radix is outside of this range, it defaults to decimal (base 10). The character list must be provided to represent each digit in the desired base; e.g., for hexadecimal, this would be ['0'-'9', 'A'-'F'].If the number is negative, the resultant string will be prefixed with a minus sign. It operates directly with the number by continuously dividing the number by the radix and mapping the remainder to characters from the given list.
- Parameters:
i- The number to convert.radix- The base of the numeral system to convert the number into.characterList- The array of characters used for representing digits in the target numeral system.- Returns:
- The string representation of the number in the specified base, using the provided character list for digits.
Groovy example:
char[] chars = ['0', '9', 'A', 'F'] return stringUtil.toBaseNStrFromCharList(100L, 3, chars)
Returns:
"90A09"
SpEL example:
#toBaseNStrFromCharList(100L, 3, {'0','9','A','F'})
Returns:
"90A09"
-
toBaseNStrUnambiguous
Converts an object representing a number into a string in a specified base using an unambiguous character set.
This method uses a predefined set of characters that excludes easily misread characters (like '0', '1', 'o', 'l') to minimize confusion. It delegates the conversion totoBaseNStrFromCharList(Long, Integer, char[])using the 'unambiguousDigits' character set.This method is useful when generating strings meant to be read and typed by humans, reducing the potential for errors in interpretation.
- Parameters:
numberObj- The object representing the number to be converted.radix- The base in which the number should be represented. The maximum valid radix is limited by the length of the 'unambiguousDigits' character set.- Returns:
- The string representation of the number using an unambiguous character set, or null if the conversion is not possible.
Groovy example:
return stringUtil.toBaseNStrUnambiguous(255, 16)
Returns:
"jj"
SpEL example:
#toBaseNStrUnambiguous(255, 16)
Returns:
"jj"
-
toBaseNStrUnambiguousLetters
Converts an object representing a number into a string in a specified base using an unambiguous set of letters and digits.
This method uses a predefined set of characters that excludes easily misread characters (like 'O', 'I', 'L') to minimize confusion, and delegates the conversion totoBaseNStrFromCharList(Long, Integer, char[])using the 'unambiguousLetters' character set.The method is particularly useful when generating strings meant to be read and typed by humans, thereby reducing the potential for errors in interpretation, especially in alphanumeric contexts such as serial keys and unique identifiers.
- Parameters:
numberObj- The object representing the number to be converted.radix- The base in which the number should be represented. The maximum valid radix is limited by the length of the 'unambiguousLetters' character set.- Returns:
- The string representation of the number using an unambiguous character set, or null if the conversion is not possible.
Groovy example:
return stringUtil.toBaseNStrUnambiguousLetters(245, 16)
Returns:
"f5"
SpEL example:
#toBaseNStrUnambiguousLetters(245, 16)
Returns:
"f5"
-
toInt
Attempts to convert a string to anInteger.
This method uses theInts.tryParsefunction from Google Guava to safely parse the string into an integer. If the string cannot be parsed, the method returns null instead of throwing an exception.- Parameters:
value- The string to be parsed into an integer.- Returns:
- The integer value of the string, or null if the string cannot be converted.
Groovy example:
return stringUtil.toInt("12345")
Returns:
12345
SpEL example:
#toInt("12345")
Returns:
12345
-
isInt
Determines if the provided string can be parsed into anInteger.
This method checks if the string is a valid integer by attempting to parse it usingtoInt(String).- Parameters:
value- The string to be checked.- Returns:
trueif the string can be parsed into an integer,falseotherwise.
Groovy example:
return stringUtil.isInt("12345")
Returns:
true
SpEL example:
#isInt("12345")
Returns:
true
-
toFloat
Attempts to convert a string to aFloat.
This method uses theFloats.tryParsefunction from Google Guava to safely parse the string into a float. If the string cannot be parsed, the method returns null instead of throwing an exception.- Parameters:
value- The string to be parsed into a float.- Returns:
- The float value of the string, or null if the string cannot be converted.
Groovy example:
return stringUtil.toFloat("3.14159")
Returns:
3.14159
SpEL example:
#toFloat("3.14159")
Returns:
3.14159
-
isFloat
Determines if the provided string can be parsed into aFloat.
This method checks if the string is a valid float by attempting to parse it usingtoFloat(String).- Parameters:
value- The string to be checked.- Returns:
trueif the string can be parsed into a float,falseotherwise.
Groovy example:
return stringUtil.isFloat("3.14159")
Returns:
true
SpEL example:
#isFloat("3.14159")
Returns:
true
-
containsStr
Checks if a substring exists within another string.
This method returnsfalseif the main string is null. It checks for the presence of the substring using thecontainsmethod of theStringclass.- Parameters:
str- The main string to search within.subStr- The substring to find within the main string.- Returns:
trueif the main string contains the substring,falseif it does not or if the main string is null.
Groovy example:
return stringUtil.containsStr("hello world", "world")
Returns:
true
SpEL example:
#containsStr("hello world", "world")
Returns:
true
-
lowerFirstPlural
Converts the first letter of a string to lowercase and then makes the string plural.
This method uses theEnglish.pluralmethod from the Atlassian library to pluralize the string after the first character has been converted to lowercase.- Parameters:
str- The string to be modified.- Returns:
- The modified string with the first character in lowercase and the rest of the string in plural form.
Groovy example:
return stringUtil.lowerFirstPlural("Category")
Returns:
"categories"
SpEL example:
#lowerFirstPlural("Category")
Returns:
"categories"
-
toProperCase
Converts all words in a string to proper case, where each word starts with a capital letter and the rest are lowercase.
This method uses theWordUtils.capitalizeFullyfunction from Apache Commons Lang to capitalize each word in the string fully.- Parameters:
str- The string to be converted to proper case.- Returns:
- The string converted to proper case.
Groovy example:
return stringUtil.toProperCase("hello world")
Returns:
"Hello World"
SpEL example:
#toProperCase("hello world")
Returns:
"Hello World"
-
getAfterLast
Retrieves the substring after the last occurrence of a specified separator in a string.
If the separator is not found, the method returns the entire string. Any leading whitespace in the result is trimmed.- Parameters:
string- The string from which to extract the substring.separator- The separator to look for.- Returns:
- The trimmed substring after the last occurrence of the separator. Returns the original string trimmed if the separator is not found.
Groovy example:
return stringUtil.getAfterLast("file.name. ext ", ".")
Returns:
"ext"
SpEL example:
#getAfterLast("file.name. ext ", ".")
Returns:
"ext"
-
isBlank
Checks if a string is blank (null, empty, or whitespace only).
This method delegates toStringUtils.isBlankto evaluate the string.- Parameters:
cs- The string to check.- Returns:
trueif the string is blank;falseotherwise.
Groovy example:
return stringUtil.isBlank(" ")
Returns:
true
SpEL example:
#isBlank(" ")
Returns:
true
-
isNotBlank
Checks if a string is not blank (not null, not empty, and not whitespace only).
This method delegates toStringUtils.isNotBlankto evaluate the string.- Parameters:
cs- The string to check.- Returns:
trueif the string is not blank;falseotherwise.
Groovy example:
return stringUtil.isNotBlank("hello")
Returns:
true
SpEL example:
#isNotBlank("hello")
Returns:
true
-
isEmptyStr
Checks if a string is empty (null or empty string).
This method delegates toStringUtils.isEmptyto evaluate the string.- Parameters:
cs- The string to check.- Returns:
trueif the string is empty;falseotherwise.
Groovy example:
return stringUtil.isEmptyStr("")
Returns:
true
SpEL example:
#isEmptyStr("")
Returns:
true
-
isNotEmpty
Checks if a string is not empty (neither null nor an empty string).
This method delegates toStringUtils.isNotEmptyto evaluate the string.- Parameters:
cs- The string to check.- Returns:
trueif the string is not empty;falseotherwise.
Groovy example:
return stringUtil.isNotEmpty("hello")
Returns:
true
SpEL example:
#isNotEmpty("hello")
Returns:
true
-
diffNonBlankStr
Determines if two strings are different and neither is blank.
This method checks that both strings are not blank and do not equal each other, ignoring case.- Parameters:
e- The first string to compare.p- The second string to compare.- Returns:
trueif both strings are non-blank and not equal ignoring case;falseotherwise.
Groovy example:
return stringUtil.diffNonBlankStr("hello", "Hello")
Returns:
false
SpEL example:
#diffNonBlankStr("hello", "world")
Returns:
true
-
sameNonBlankStr
Checks if two strings are the same, ignoring case, and neither is blank.
This method ensures both strings are not blank and are equivalent when ignoring case differences.- Parameters:
e- The first string to compare.p- The second string to compare.- Returns:
trueif both strings are non-blank and the same ignoring case;falseotherwise.
Groovy example:
return stringUtil.sameNonBlankStr("example", "Example")
Returns:
true
SpEL example:
#sameNonBlankStr("example", "Example")
Returns:
true
-
diffNonEmptyStr
Determines if two strings are different, ignoring case, and neither is empty.
This method checks that both strings are not empty and do not equal each other, ignoring case.- Parameters:
e- The first string to compare.p- The second string to compare.- Returns:
trueif both strings are non-empty and not equal ignoring case;falseotherwise.
Groovy example:
return stringUtil.diffNonEmptyStr("text", "Texts")
Returns:
true
SpEL example:
#diffNonEmptyStr("text", "Texts")
Returns:
true
-
sameNonEmptyStr
Checks if two strings are the same, ignoring case, and neither is empty.
This method ensures both strings are not empty and are equivalent when ignoring case differences.- Parameters:
e- The first string to compare.p- The second string to compare.- Returns:
trueif both strings are non-empty and the same ignoring case;falseotherwise.
Groovy example:
return stringUtil.sameNonEmptyStr("example", "Example")
Returns:
true
SpEL example:
#sameNonEmptyStr("example", "Example")
Returns:
true
-
diffNonBlankStrWithCase
Checks if two non-blank strings are different, considering case sensitivity.
This method ensures both strings are not blank and are not exactly the same, including case.- Parameters:
e- The first string to compare.p- The second string to compare.- Returns:
trueif both strings are non-blank and different with exact case matching;falseotherwise.
Groovy example:
return stringUtil.diffNonBlankStrWithCase("Hello", "hello")
Returns:
true
SpEL example:
#diffNonBlankStrWithCase("Hello", "hello")
Returns:
true
-
sameNonBlankStrWithCase
Checks if two non-blank strings are exactly the same, considering case sensitivity.
This method ensures both strings are not blank and are exactly the same, including case.- Parameters:
e- The first string to compare.p- The second string to compare.- Returns:
trueif both strings are non-blank and exactly the same with case sensitivity;falseotherwise.
Groovy example:
return stringUtil.sameNonBlankStrWithCase("Hello", "Hello")
Returns:
true
SpEL example:
#sameNonBlankStrWithCase("Hello", "Hello")
Returns:
true
-
diffNonEmptyStrWithCase
Determines if two non-empty strings are different, considering case sensitivity.
This method ensures both strings are not empty and are not exactly the same, including case.- Parameters:
e- The first string to compare.p- The second string to compare.- Returns:
trueif both strings are non-empty and different with exact case matching;falseotherwise.
Groovy example:
return stringUtil.diffNonEmptyStrWithCase("Example", "example")
Returns:
true
SpEL example:
#diffNonEmptyStrWithCase("Example", "example")
Returns:
true
-
sameNonEmptyStrWithCase
Checks if two non-empty strings are exactly the same, considering case sensitivity.
This method ensures both strings are not empty and are exactly the same, including case.- Parameters:
e- The first string to compare.p- The second string to compare.- Returns:
trueif both strings are non-empty and exactly the same with case sensitivity;falseotherwise.
Groovy example:
return stringUtil.sameNonEmptyStrWithCase("text", "text")
Returns:
true
SpEL example:
#sameNonEmptyStrWithCase("text", "text")
Returns:
true
-
splitAndClean
Splits a string by a specified delimiter and returns a collection of non-blank, trimmed substrings.
This method trims each substring resulting from the split and filters out any that are blank. If the original string or the delimiter is blank, specific handling ensures meaningful output.- Parameters:
str- The string to be split.delimiter- The delimiter to use for splitting the string.- Returns:
- A collection of non-blank, trimmed substrings. Returns an empty collection if the input string is blank.
Groovy example:
return stringUtil.splitAndClean(" apple, orange , , banana ", ",")
Returns:
["apple", "orange", "banana"]
SpEL example:
#splitAndClean(" apple, orange , , banana ", ",")
Returns:
["apple", "orange", "banana"]
-
parseToList
Splits a string formatted like an array or list, potentially enclosed in brackets, parentheses, or other characters, into a list of strings based on a specified delimiter. It intelligently handles and removes enclosing characters before splitting. This method detects and strips the first and last characters if they are common enclosure pairs such as brackets ('[', ']'), parentheses ('(', ')'), braces ('{', '}'), double quotes ('"'), or single quotes ('\'') before performing the split operation. This is useful for parsing strings that represent collections or arrays as it ensures only the internal elements are split.- Parameters:
input- The input string to be split. Enclosures, if present, are expected to match and be at the very start and end of the string.delimiter- The delimiter used to split the input string. If blank, the entire input string (minus enclosures) is returned as a single-element list.- Returns:
- A list of strings obtained by splitting the input string using the specified delimiter, with any
enclosing characters removed. Returns an empty list if the input string is blank.
Groovy example:
return stringUtil.parseToList("[apple, orange, banana]", ",")
Returns:
["apple", "orange", "banana"]
SpEL example:
#parseToList("[apple, orange, banana]", ",")
Returns:
["apple", "orange", "banana"]
-
filterByEndsWith
Filters a string by retaining only those substrings that end with specified patterns.
This method splits the input string by a given delimiter and then filters the resulting tokens by checking if they end with any of the specified patterns. If no patterns are provided, all tokens are retained.- Parameters:
source- The input string to be filtered.patterns- An array of suffix patterns used to filter the substrings.delimiter- The delimiter used to split the input string.- Returns:
- A string composed of the filtered substrings joined by commas, or the original string if it is blank or patterns are null.
Groovy example:
return stringUtil.filterByEndsWith("example.csv,test.txt,notes.doc", [".txt", ".csv"], ",")
Returns:
"example.csv,test.txt"
SpEL example:
#filterByEndsWith("example.csv,test.txt,notes.doc", {".txt", ".csv"}, ",")
Returns:
"example.csv,test.txt"
-
getChecksum
Calculates the SHA-256 checksum of a string and returns it in uppercase.
This method is commonly used to verify data integrity through a cryptographic hash.- Parameters:
string- The input string for which the checksum is calculated.- Returns:
- The SHA-256 checksum of the string, represented in uppercase.
Groovy example:
return stringUtil.getChecksum("hello world")
Returns:
"B94D27B9934D3E08A52E52D7DA7DABFAC484EFE37A5380EE9088F7ACE2EFCDE9"
SpEL example:
#getChecksum("hello world")
Returns:
"B94D27B9934D3E08A52E52D7DA7DABFAC484EFE37A5380EE9088F7ACE2EFCDE9"
-
encodePassword
Encodes a password using a secure encoding mechanism.
This method is typically used to encode passwords before storing them in a database.- Parameters:
password- The password to encode.- Returns:
- The encoded password.
Groovy example:
return stringUtil.encodePassword("myPassword123")
Returns:
"$2a$10$nzenJbG8Hee7hhI4IC0D4OU97LIW5hfTRlzPu2X7hQVkGkXR./bFe"
SpEL example:
#encodePassword("myPassword123")
Returns:
"$2a$10$nzenJbG8Hee7hhI4IC0D4OU97LIW5hfTRlzPu2X7hQVkGkXR./bFe"
-
passwordMatches
Checks if a plain password matches its encoded version using a password encoder.
This method is typically used to verify user passwords during authentication processes.- Parameters:
password- The plain password to verify.encoded- The encoded version of the password to check against.- Returns:
trueif the password matches the encoded version;falseotherwise.
Groovy example:
return stringUtil.passwordMatches("myPassword123", "$2a$10$nzenJbG8Hee7hhI4IC0D4OU97LIW5hfTRlzPu2X7hQVkGkXR./bFe")
Returns:
true
SpEL example:
#passwordMatches("myPassword123", "$2a$10$nzenJbG8Hee7hhI4IC0D4OU97LIW5hfTRlzPu2X7hQVkGkXR./bFe")
Returns:
true
-
generateRandomAlphanumeric
Generates a random alphanumeric string of a specified length.
This method is useful for creating unique identifiers, temporary passwords, or any other random string needs.- Parameters:
length- The length of the random alphanumeric string to generate.- Returns:
- A random alphanumeric string of the specified length.
Groovy example:
return stringUtil.generateRandomAlphanumeric(10)
Returns:
"sPZ4l1dgBT"
SpEL example:
#generateRandomAlphanumeric(10)
Returns:
"sPZ4l1dgBT"
-
generateUnambiguousRandomAlphaNumeric
Generates a random alphanumeric string of a specified length using an unambiguous character set.
This method avoids characters that are easily confused, such as 'O' and '0', 'I' and '1', making it suitable for user-visible codes or keys.- Parameters:
length- The length of the random unambiguous alphanumeric string to generate.- Returns:
- A random unambiguous alphanumeric string of the specified length.
Groovy example:
return stringUtil.generateUnambiguousRandomAlphaNumeric(10)
Returns:
"bvMdcejbjY"
SpEL example:
#generateUnambiguousRandomAlphaNumeric(10)
Returns:
"bvMdcejbjY"
-
generateUnambiguousRandomAlphaNumericLowercase
Generates a random alphanumeric string of a specified length using an unambiguous, lowercase-only character set.
This method excludes characters that can be easily confused, such as 'o' and '0', 'l' and '1', and ensures all characters are lowercase. It is ideal for generating user-friendly and readable verification codes or temporary passwords.- Parameters:
length- The length of the random unambiguous alphanumeric string to generate.- Returns:
- A random unambiguous alphanumeric string of the specified length, in lowercase.
Groovy example:
return stringUtil.generateUnambiguousRandomAlphaNumericLowercase(10)
Returns:
"dy369g387w"
SpEL example:
#generateUnambiguousRandomAlphaNumericLowercase(10)
Returns:
"dy369g387w"
-
generateRandomAlphaNumericFromString
Generates a random alphanumeric string of a specified length, using only characters provided in a custom set.
This method allows for precise control over the characters that appear in the resulting string, making it useful for cases where specific character requirements must be met, such as including only certain letters or numbers.- Parameters:
length- The length of the random alphanumeric string to generate.allowedChars- A string containing the set of characters that may be included in the random string.- Returns:
- A random alphanumeric string of the specified length, using only the characters from the allowed set.
Groovy example:
return stringUtil.generateRandomAlphaNumericFromString(10, "abcdef0123456789")
Returns:
"acde713a96"
SpEL example:
#generateRandomAlphaNumericFromString(10, "abcdef0123456789")
Returns:
"acde713a96"
-
randomLastName
Selects a random last name from a predefined list of common last names.
This method can be used for generating sample data, mock-ups, or wherever random last names are required.- Returns:
- A random last name from the list.
Groovy example:
return stringUtil.randomLastName()
Returns:
"Johnson"
SpEL example:
#randomLastName()
Returns:
"Johnson"
-
randomMaleFirstName
Selects a random male first name from a predefined list of common male first names.
This method is useful for generating sample data, mock-ups, or wherever random male first names are needed.- Returns:
- A random male first name from the list.
Groovy example:
return stringUtil.randomMaleFirstName()
Returns:
"Robert"
SpEL example:
#randomMaleFirstName()
Returns:
"Robert"
-
randomFemaleFirstName
Selects a random female first name from a predefined list of common female first names.
This method is suitable for generating sample data, mock-ups, or for use in situations where random female first names are required.- Returns:
- A random female first name from the list.
Groovy example:
return stringUtil.randomFemaleFirstName()
Returns:
"Mary"
SpEL example:
#randomFemaleFirstName()
Returns:
"Mary"
-
randomElementFromList
Selects a random element from a provided array of strings.
This method is useful for randomly selecting a name or any string from a fixed list.- Parameters:
nameList- The array of strings to select from.- Returns:
- A random element from the provided list.
Groovy example:
return stringUtil.randomElementFromList(["apple", "banana", "cherry"])
Returns:
"cherry"
SpEL example:
#randomElementFromList({"apple", "banana", "cherry"})
Returns:
"cherry"
-
generateRandomInt
public static int generateRandomInt(int min, int max) Generates a random integer within a specified range.
This method is often used for random indexing, simulations, or whenever a random number is needed within a defined interval.- Parameters:
min- The minimum value of the random integer (inclusive).max- The maximum value of the random integer (inclusive).- Returns:
- A random integer between the specified min and max values.
Groovy example:
return stringUtil.generateRandomInt(1, 100)
Returns:
57
SpEL example:
#generateRandomInt(1, 100)
Returns:
57
-
serializeObject
public static String serializeObject(Object object) throws com.fasterxml.jackson.core.JsonProcessingException Serializes an object to JSON using a minimal JSON printer.
This method converts Java objects into a JSON string format while minimizing whitespace and formatting. This is useful for logging, sending data over networks, or storing it in a format that is both human-readable and machine-parseable.- Parameters:
object- The object to serialize.- Returns:
- A JSON string representation of the object.
- Throws:
com.fasterxml.jackson.core.JsonProcessingException- If the object cannot be serialized to JSON.
Groovy example:
return stringUtil.serializeObject(new com.ssgllc.fish.service.dto.gen.AppConfigDTO().name('MyNewAppConfig').environment('dev'))
Returns:
{"@id":"1","entityType":"AppConfig","casetivityCanEdit":false,"casetivityCanDelete":false,"casetivityCanMerge":false,"name":"MyNewAppConfig","environment":"dev","casetivityExtraFields":{}}
SpEL example:
#serializeObject(new com.ssgllc.fish.service.dto.gen.AppConfigDTO().name('MyNewAppConfig').environment('dev'))
Returns:
{"@id":"1","entityType":"AppConfig","casetivityCanEdit":false,"casetivityCanDelete":false,"casetivityCanMerge":false,"name":"MyNewAppConfig","environment":"dev","casetivityExtraFields":{}}
-
serializeObjectPretty
public static String serializeObjectPretty(Object object) throws com.fasterxml.jackson.core.JsonProcessingException Serializes an object to JSON with indentation for improved readability.
This method converts Java objects into a formatted JSON string, using indents and line breaks to make the output human-readable. This is ideal for debugging, logging in development environments, or any scenario where readability of JSON data is prioritized.- Parameters:
object- The object to serialize.- Returns:
- A formatted JSON string representation of the object.
- Throws:
com.fasterxml.jackson.core.JsonProcessingException- If the object cannot be serialized to JSON.
Groovy example:
return stringUtil.serializeObjectPretty(new com.ssgllc.fish.service.dto.gen.AppConfigDTO().name('MyNewAppConfig').environment('dev'))
Returns:
{ "@id": "1", "entityType": "AppConfig", "casetivityCanEdit": false, "casetivityCanDelete": false, "casetivityCanMerge": false, "name": "MyNewAppConfig", "environment": "dev", "casetivityExtraFields": {} }
SpEL example:
#serializeObjectPretty(new com.ssgllc.fish.service.dto.gen.AppConfigDTO().name('MyNewAppConfig').environment('dev'))
Returns:
{ "@id": "1", "entityType": "AppConfig", "casetivityCanEdit": false, "casetivityCanDelete": false, "casetivityCanMerge": false, "name": "MyNewAppConfig", "environment": "dev", "casetivityExtraFields": {} }
-
deserializeString
public static Object deserializeString(String string, String className) throws ClassNotFoundException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException, IOException Deserializes a JSON string into an object of the specified class.
This method dynamically loads the class based on the provided class name and then uses Jackson to deserialize the JSON string into an instance of that class.- Parameters:
string- The JSON string to deserialize.className- The fully qualified name of the class to which the JSON should be deserialized.- Returns:
- An object of the specified class populated with data from the JSON string.
- Throws:
ClassNotFoundException- If the class cannot be found.com.fasterxml.jackson.core.JsonParseException- If the JSON is not in a valid format.com.fasterxml.jackson.databind.JsonMappingException- If the JSON cannot be mapped to the specified class.IOException- If an input or output exception occurred.
Groovy example:
return stringUtil.deserializeString('{ "name": "MyNewAppConfig", "environment": "dev" }', 'com.ssgllc.fish.service.dto.gen.AppConfigDTO')
Returns:
A new AppConfigDTO
SpEL example:
#deserializeString('{ "name": "MyNewAppConfig", "environment": "dev" }', 'com.ssgllc.fish.service.dto.gen.AppConfigDTO')
Returns:
A new AppConfigDTO
-
isValidJson
Determines if a string counts as valid JSON and can be parsed as JSON without error.- Parameters:
string- string to test- Returns:
- whether the string is valid JSON
SpEL example:
#isValidJson('{"name": "JsonEntity", "createdDate": "2025-01-02", "relatedEntity": {"id": "01234", "jurisdiction": {"code": "MA"} "entityVersion": 3}')
Returns:
false
-
translateTo
Retrieves the translation of a specified key for a given language.
This method queries a cache or a configuration service to fetch the translation based on the key and the specified language.- Parameters:
key- The key for the translation entry.language- The language code for which the translation is requested.- Returns:
- The translated string.
Groovy example:
return stringUtil.translateTo("reports.standard.description", "en")
Returns:
"Select a record above"
SpEL example:
#translateTo("reports.standard.description", "en")
Returns:
"Select a record above"
-
translate
Retrieves the translation of a specified key for the default language, which is English.
This method is a convenience overload oftranslateTo(String, String)that defaults the language to English ('en').- Parameters:
key- The key for the translation entry.- Returns:
- The translated string in English.
Groovy example:
return stringUtil.translate("reports.standard.description")
Returns:
"Select a record above"
Cannot be used in SpEL
-
translateFullStringTo
Translates a string containing tokens identified by %{key} into the specified language.
This method searches the input string for placeholders in the format %{key} and replaces them with their translations based on the specified language code. It is particularly useful for localizing messages that include dynamic content.- Parameters:
string- The string containing translation keys enclosed in %{key} to be translated.language- The language code to translate the keys into.- Returns:
- A string with all translation keys replaced by their translated values.
Groovy example:
return stringUtil.translateFullStringTo("Important notice: %{reports.standard.description} and %{reports.personalized.description}", "en")
Returns:
"Important notice: Snapshot Standard Description Test and Snapshot Personalized Description Test"
SpEL example:
#translateFullStringTo("Important notice: %{reports.standard.description} and %{reports.personalized.description}", "en")
Returns:
"Important notice: Snapshot Standard Description Test and Snapshot Personalized Description Test"
-
translateFullString
Translates a string containing tokens identified by %{key} into English.
This method searches the input string for placeholders in the format %{key} and replaces them with their translations based on the specified language code. It is particularly useful for localizing messages that include dynamic content.- Parameters:
string- The string containing translation keys enclosed in %{key} to be translated.- Returns:
- A string with all translation keys replaced by their English translated values.
Groovy example:
return stringUtil.translateFullString("Important notice: %{reports.standard.description} and %{reports.personalized.description}")
Returns:
"Important notice: Snapshot Standard Description Test and Snapshot Personalized Description Test"
Cannot be used in SpEL
-
isValidEmail
Validates an email address based on a predefined pattern.
This method checks if the provided email string conforms to a specific pattern that defines a valid email format. It's useful for validating user input in forms or before sending data to a server.- Parameters:
email- The email address to validate.- Returns:
trueif the email address is valid according to the pattern;falseotherwise.
Groovy example:
return stringUtil.isValidEmail("example@domain.com")
Returns:
true
SpEL example:
#isValidEmail("example@domain.com")
Returns:
true
-
joinStrings
Joins a collection of strings into a single string with a specified delimiter.
This method concatenates elements of the provided collection, separating them with the specified delimiter. It is ideal for compiling a list of strings into a readable format or preparing strings for display or logging.- Parameters:
delimiter- The delimiter to use for joining the strings.strings- The collection of strings to join.- Returns:
- A single string consisting of the collection's elements separated by the delimiter, or
nullif the input collection isnull.
Groovy example:
return stringUtil.joinStrings(", ", ["apple", "banana", "cherry"])
Returns:
"apple, banana, cherry"
SpEL example:
#joinStrings(", ", {"apple", "banana", "cherry"})
Returns:
"apple, banana, cherry"
-
camelToWords
Converts camel case strings into a space-separated string.
This method splits a camel case string (e.g., "CamelCaseString") into separate words ("Camel Case String"), improving readability for display or logging purposes.- Parameters:
string- The camel case string to convert.- Returns:
- The space-separated words of the camel case string.
Groovy example:
return stringUtil.camelToWords("CamelCaseInputString")
Returns:
"Camel Case Input String"
SpEL example:
#camelToWords("CamelCaseInputString")
Returns:
"Camel Case Input String"
-
pluralize
Converts a singular word to its plural form according to English language rules.
This method is useful for generating user interfaces or reports where grammatical correctness is required.- Parameters:
string- The singular form of the word to be pluralized.- Returns:
- The plural form of the word.
Groovy example:
return stringUtil.pluralize("diary")
Returns:
"diaries"
SpEL example:
#pluralize("diary")
Returns:
"diaries"
-
camelToWordPluralizeLast
Converts a camel case string into a space-separated string and pluralizes the last word.
This method is particularly useful when transforming code identifiers into human-readable text that follows English grammar rules, making it ideal for dynamic UI labels or reports based on object properties.- Parameters:
string- The camel case string to convert and pluralize the last word.- Returns:
- A space-separated string with the last word pluralized, or
nullif the input string is empty ornull.
Groovy example:
return stringUtil.camelToWordPluralizeLast("UserProfile")
Returns:
"User Profiles"
SpEL example:
#camelToWordPluralizeLast("UserProfile")
Returns:
"User Profiles"
-
stripTags
Removes all HTML tags from the input string, returning only the plain text content.- Parameters:
input- The string potentially containing HTML tags.- Returns:
- A plain text version of the input with all HTML tags removed, or the original input if it is empty or null.
Groovy example:
return stringUtil.stripTags("Hello World
")
Returns:
Hello World
SpEL example:
#stripTags("Hello World
")
Returns:
Hello World
-