- java.lang.Object
-
- org.tentackle.common.StringHelper
-
public final class StringHelper extends Object
Some handy methods for strings.- Author:
- harald
-
-
Field Summary
Fields Modifier and Type Field Description static Function<String,String>stringNormalizerThe default normalizer used within the application.
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static voidblank(char[] buf)Null-safe char array filler.
Fills with blanks.static StringcamelCaseToDelimited(String str, String delimiter)Converts a camelCase string to strings with delimiters.static intcountOccurrences(String str, char c)Counts the number of occurrences of a given character in a string.static StringdigitToString(Character digit)Gets the word-string for a digit.
Example:static booleanequalsIgnoreCase(String a, String b)Null safeString.equalsIgnoreCase(String).static Stringevaluate(String str, Function<String,String> variableProvider)Evaluates a string replacing variables.
The semantics are very much the same as known from the maven resources plugin, but with the extension of optional default values and that@turns off nested variable processing.static voidfill(char[] buf, char val)Null-safe char array filler.static StringfillLeft(String str, int length, char filler)Fills up a string from the left with a filler character to match a given length.
If the string is already longer, nothing happens.static StringfillRight(String str, int length, char filler)Fills up a string to the right with a filler character to match a given length.
If the string is already longer, nothing happens.static StringfilterUpperCase(String str)Gets the uppercase letters only.
Useful to get the camel case letters of a string.static StringfirstBefore(String str, char delimiter)Gets the part of a string before a given delimiter.static StringfirstLine(String str)Gets the first line from a multi-line string.static StringfirstToLower(String str)Converts the first character of string to uppercase.static StringfirstToUpper(String str)Converts the first character of string to uppercase.static StringgetArchitecture()Gets the name of the architecture from the system properties.static StringgetContinuedLine(String line)Checks whether given string introduces a continuation line.static intgetMaxLogCollectionSize()Gets the size limit of collections to be logged.static StringgetPlainClassName(String className)Gets a classname without any optional generics.static StringgetPlatform()Gets the name of the operating system from the system properties.static Stringhash(String algorithm, char[] salt, char[] input)Builds a hash from an array of chars.
Note that this method converts the characters to bytes viatoBytes(char[])before applying the hash.static intindexAnyOf(String str, String anyOf)Returns the first index of any of the given characters.static booleanisAllDigits(String str)checks if a string contains only digits, i.e.static booleanisAllDigits(String str, boolean whitespaceAllowed)Checks if a string contains only digits or whitespaces, i.e.static booleanisAllWhitespace(String str)Checks if string contains only whitespaces.static booleanisFQCN(String className)Checks whether given string is a fully qualified classname (FQCN).
The class must belong to a package!static booleanisReservedWord(String word)Returns whether given string is a reserved java keyword.static booleanisValidJavaClassName(String className)Checks that given string is a valid Java classname.
Both classnames with a full classpath or without are validated.static booleanisValidJavaIdentifier(String str)Returns whether the given string is a valid java identifier.static booleanisValidJavaPackageName(String packageName)Checks that given string is a valid Java packagename.
This is very restrictive verification.static StringlastAfter(String str, char delimiter)Gets the part of a string after a given delimiter.static intlevenshteinDistance(String s1, String s2)Determines the Levenshtein distance of two strings.
Notice that for s1 and s2 null values are treated as empty strings.static Stringnormalize(String str)Normalizes a string (phonetically) for use as PDO.normText usingstringNormalizer.static Stringnormalize(String str, Function<String,String> normalizer)Normalizes a string (phonetically) for use as PDO.normText.static StringobjectArrayToString(Object[] objArray, String separator)Creates a string from an object array.static StringobjectToLoggableString(Object object)Converts a value to a loggable string.static StringparseString(String str)Parses a string.
The string may be enclosed in double- or single quotes which will be removed.static StringreadTextFromResource(Class<?> caller, String resourceName)Reads a textfile from a resource.static StringremoveTrailingText(String str, String... trail)Removes a trailing text from a string.
Stops when the first trailing string is found.static voidsetMaxLogCollectionSize(int maxLogCollectionSize)Sets the size limit of collections to be logged.
If an object is logged and it is a collection and the size exceedsmaxLogCollectionSize, only the number of items is logged inobjectToLoggableString(java.lang.Object)instead of each item.static List<String>split(String str, String delimiters)Splits a string keeping strings together.
The strings may be enclosed in double- or single quotes which will not be removed.static StringstripEnclosingDoubleQuotes(String str)Strips enclosing double quotes.static StringtoAsciiLetterOrDigit(String str)Converts to string containing only the letters A-z or digits.
All other characters will be converted to an underscore.static byte[]toBytes(char c)Converts a single (unicode) char to a byte-array.static byte[]toBytes(char[] chars)Converts a char-array to a byte-array.static StringtoCamelCase(String str)Converts a dotted path to camelCase.
Example:
"alpha.beta.gamma"is converted to"alphaBetaGamma".static char[]toCharArray(String str)Null-safe string to a char-array conversion.static StringtoDoubleQuotes(String str)Takes a string, surrounds it with double-quotes and escapes all double-quotes already in the string according to Unix rules.static StringtoDTA(String str)Filters illegal chars for DTA-Files (German "DATENAUSTAUSCH" banking format).static StringtoFixedLength(String str, int length)Takes a string and returns one with a given length, cutting or filling up with spaces, whatever appropriate.static StringtoFixedLength(String str, int length, char filler)Takes a string and returns one with a given length, cutting or filling up with fillchars, whatever appropriate.static StringtoFixedLengthLeftFill(String str, int length)Takes a string and returns one with a given length, cutting or filling up with spaces from the left, whatever appropriate.static StringtoFixedLengthLeftFill(String str, int length, char filler)Takes a string and returns one with a given length, cutting or filling up with fillchars from the left, whatever appropriate.static StringtoHexString(byte[] binaryData)Creates a human-readable hex-String out of a byte-array (e.g.static StringtoHTML(String text)Converts a multiline string to an HTML-string that can be displayed in a label.static StringtoLower(String str)Converts a string to lowercase allowing null values.static StringtoParsableString(String str)Converts a string to a string parsable byparseString(java.lang.String).static StringtoUpper(String str)Converts a string to uppercase allowing null values.static StringtoVarName(String str)Filters illegal chars for Java variable names.static Stringtrim(String s)Trims a string.static Stringtrim(String s, int max)Trims a string.static StringtrimLeft(String str, char filler)Cuts leading characters.static StringtrimRight(String str, char filler)Cuts trailing characters.static StringunDiacrit(String str, boolean keepLength)Converts special unicode characters (so-called diacrits) to standard ascii.
Supports also special german and northern european "umlauts".
-
-
-
Method Detail
-
setMaxLogCollectionSize
public static void setMaxLogCollectionSize(int maxLogCollectionSize)
Sets the size limit of collections to be logged.
If an object is logged and it is a collection and the size exceedsmaxLogCollectionSize, only the number of items is logged inobjectToLoggableString(java.lang.Object)instead of each item.- Parameters:
maxLogCollectionSize- the limit
-
getMaxLogCollectionSize
public static int getMaxLogCollectionSize()
Gets the size limit of collections to be logged.- Returns:
- the limit (default is 10)
-
equalsIgnoreCase
public static boolean equalsIgnoreCase(String a, String b)
Null safeString.equalsIgnoreCase(String).- Parameters:
a- first string, may be nullb- second string, may be null- Returns:
- true if equal ignoring the case or both are null
-
toUpper
public static String toUpper(String str)
Converts a string to uppercase allowing null values.- Parameters:
str- the string- Returns:
- the uppercase string or null
-
toLower
public static String toLower(String str)
Converts a string to lowercase allowing null values.- Parameters:
str- the string- Returns:
- the lowercase string or null
-
firstToUpper
public static String firstToUpper(String str)
Converts the first character of string to uppercase.- Parameters:
str- the string- Returns:
- the converted string
-
firstToLower
public static String firstToLower(String str)
Converts the first character of string to uppercase.- Parameters:
str- the string- Returns:
- the converted string
-
getPlainClassName
public static String getPlainClassName(String className)
Gets a classname without any optional generics.- Parameters:
className- the original classname- Returns:
- classname without generics
-
getContinuedLine
public static String getContinuedLine(String line)
Checks whether given string introduces a continuation line.This is the case if the last character is an unquoted backslash.
- Parameters:
line- the source line- Returns:
- null if line does not introduce a continuation line
-
indexAnyOf
public static int indexAnyOf(String str, String anyOf)
Returns the first index of any of the given characters.- Parameters:
str- the stringanyOf- the characters- Returns:
- the index to the first character found, -1 if no such character
-
toDoubleQuotes
public static String toDoubleQuotes(String str)
Takes a string, surrounds it with double-quotes and escapes all double-quotes already in the string according to Unix rules. Example:Length 5" --> "Length 5\""- Parameters:
str- the string- Returns:
- the string in double quotes
-
parseString
public static String parseString(String str)
Parses a string.
The string may be enclosed in double- or single quotes which will be removed. Those special characters may be escaped by a backslash. The backslash itself can be written as a double backslash. Special escapes are:\n = new line \r = carriage return \t = tab \f = form feed
- Parameters:
str- the source string- Returns:
- a string, never null
-
toParsableString
public static String toParsableString(String str)
Converts a string to a string parsable byparseString(java.lang.String).- Parameters:
str- the string- Returns:
- the parsable string
-
split
public static List<String> split(String str, String delimiters)
Splits a string keeping strings together.
The strings may be enclosed in double- or single quotes which will not be removed. Those special characters may be escaped by a backslash. The backslash itself can be written as a double backslash. Special escapes are:\n = new line \r = carriage return \t = tab \f = form feed
- Parameters:
str- the stringdelimiters- the delimiter characters- Returns:
- the strings, never null
-
isFQCN
public static boolean isFQCN(String className)
Checks whether given string is a fully qualified classname (FQCN).
The class must belong to a package!- Parameters:
className- the classname- Returns:
- true if FQCN
-
isValidJavaClassName
public static boolean isValidJavaClassName(String className)
Checks that given string is a valid Java classname.
Both classnames with a full classpath or without are validated.- Parameters:
className- the classname- Returns:
- true if valid
-
isValidJavaPackageName
public static boolean isValidJavaPackageName(String packageName)
Checks that given string is a valid Java packagename.
This is very restrictive verification. Packagenames must be all lowercase alphabetic or digits and must contain only dots and underscores.- Parameters:
packageName- the packagename- Returns:
- true if valid
-
isValidJavaIdentifier
public static boolean isValidJavaIdentifier(String str)
Returns whether the given string is a valid java identifier.- Parameters:
str- the string- Returns:
- true if valid, false if not
-
readTextFromResource
public static String readTextFromResource(Class<?> caller, String resourceName) throws IOException
Reads a textfile from a resource.Example:
String model = StringHelper.readTextFromResource("/org/tentackle/model/TestModel.txt");- Parameters:
caller- the caller class, null to determine via StackwalkerresourceName- the name of the resource- Returns:
- the loaded text
- Throws:
IOException- if loading failedFileNotFoundException- if no such resource found
-
isAllWhitespace
public static boolean isAllWhitespace(String str)
Checks if string contains only whitespaces.- Parameters:
str- the string to check- Returns:
- true if null, empty or all whitespace, false if at least one non-whitespace-character found
-
isReservedWord
public static boolean isReservedWord(String word)
Returns whether given string is a reserved java keyword.- Parameters:
word- the string to test- Returns:
- true if java reserved word
-
digitToString
public static String digitToString(Character digit)
Gets the word-string for a digit.
Example:'0' --> "zero"
- Parameters:
digit- the digit character- Returns:
- the word-string
-
unDiacrit
public static String unDiacrit(String str, boolean keepLength)
Converts special unicode characters (so-called diacrits) to standard ascii.
Supports also special german and northern european "umlauts".- Parameters:
str- the string to be convertedkeepLength- true if the length should be kept, i.e. no Ä to AE, but to A- Returns:
- the converted string
-
normalize
public static String normalize(String str, Function<String,String> normalizer)
Normalizes a string (phonetically) for use as PDO.normText.- Parameters:
str- the string to be normalizednormalizer- the normalizer to use, null = global default- Returns:
- the normalized string
-
normalize
public static String normalize(String str)
Normalizes a string (phonetically) for use as PDO.normText usingstringNormalizer.- Parameters:
str- the string to be normalized- Returns:
- the normalized string
-
stripEnclosingDoubleQuotes
public static String stripEnclosingDoubleQuotes(String str)
Strips enclosing double quotes.- Parameters:
str- the original string- Returns:
- the string with its double quotes removed
-
toFixedLength
public static String toFixedLength(String str, int length, char filler)
Takes a string and returns one with a given length, cutting or filling up with fillchars, whatever appropriate.- Parameters:
str- the stringlength- the length of the returned stringfiller- the character to fill up if str is too short- Returns:
- the string with the desired length
-
toFixedLength
public static String toFixedLength(String str, int length)
Takes a string and returns one with a given length, cutting or filling up with spaces, whatever appropriate.- Parameters:
str- the stringlength- the length of the returned string- Returns:
- the string with the desired length
-
toFixedLengthLeftFill
public static String toFixedLengthLeftFill(String str, int length, char filler)
Takes a string and returns one with a given length, cutting or filling up with fillchars from the left, whatever appropriate.- Parameters:
str- the stringlength- the length of the returned stringfiller- the character to fill up if str is too short- Returns:
- the string with the desired length
-
toFixedLengthLeftFill
public static String toFixedLengthLeftFill(String str, int length)
Takes a string and returns one with a given length, cutting or filling up with spaces from the left, whatever appropriate.- Parameters:
str- the stringlength- the length of the returned string- Returns:
- the string with the desired length
-
toDTA
public static String toDTA(String str)
Filters illegal chars for DTA-Files (German "DATENAUSTAUSCH" banking format).- Parameters:
str- the string- Returns:
- the DTA conform string
-
toVarName
public static String toVarName(String str)
Filters illegal chars for Java variable names.- Parameters:
str- the string- Returns:
- the java conform string
-
toCamelCase
public static String toCamelCase(String str)
Converts a dotted path to camelCase.
Example:
"alpha.beta.gamma"is converted to"alphaBetaGamma".- Parameters:
str- the dotted path- Returns:
- the camel case path
-
camelCaseToDelimited
public static String camelCaseToDelimited(String str, String delimiter)
Converts a camelCase string to strings with delimiters.Example:
"alphaBetaGamma"is converted to"alpha.beta.gamma", with delimiter".".- Parameters:
str- the camelcase stringdelimiter- the delimter to insert between parts, null or empty if none- Returns:
- the converted string
-
isAllDigits
public static boolean isAllDigits(String str, boolean whitespaceAllowed)
Checks if a string contains only digits or whitespaces, i.e. no illegal char in a number string.- Parameters:
str- the string to checkwhitespaceAllowed- true if whitespaces are allowed- Returns:
- true if no illegal char detected, false otherwise
-
isAllDigits
public static boolean isAllDigits(String str)
checks if a string contains only digits, i.e. no non-number char in string, even no whitespace.- Parameters:
str- the string to check- Returns:
- true if no illegal char detected, false otherwise
-
trim
public static String trim(String s, int max)
Trims a string. The method is nullpointer safe.- Parameters:
s- the string, may be nullmax- the maximum number of characters, 0 = minimum length- Returns:
- the trimmed string, null if s == null
-
trim
public static String trim(String s)
Trims a string. The method is nullpointer safe.- Parameters:
s- the string, may be null- Returns:
- the trimmed string, null if s == null
- See Also:
trim(java.lang.String, int)
-
trimRight
public static String trimRight(String str, char filler)
Cuts trailing characters.Removes all trailing characters of given value from the string. If the string consists of those characters only, the returned string will empty.
- Parameters:
str- the stringfiller- the filler to remove- Returns:
- the trimmed string, never null
-
trimLeft
public static String trimLeft(String str, char filler)
Cuts leading characters.Removes all leading characters of given value from the string. If the string consists of those characters only, the returned string will be empty.
- Parameters:
str- the stringfiller- the filler to remove- Returns:
- the trimmed string, never null
-
fillLeft
public static String fillLeft(String str, int length, char filler)
Fills up a string from the left with a filler character to match a given length.
If the string is already longer, nothing happens.- Parameters:
str- the stringlength- the desired lengthfiller- the filler character- Returns:
- the filled string, never null
-
fillRight
public static String fillRight(String str, int length, char filler)
Fills up a string to the right with a filler character to match a given length.
If the string is already longer, nothing happens.- Parameters:
str- the stringlength- the desired lengthfiller- the filler character- Returns:
- the filled string, never null
-
firstBefore
public static String firstBefore(String str, char delimiter)
Gets the part of a string before a given delimiter.- Parameters:
str- the stringdelimiter- the delimiter- Returns:
- the first part up to but excluding delimiter or the string if no delimiter at all
-
lastAfter
public static String lastAfter(String str, char delimiter)
Gets the part of a string after a given delimiter.- Parameters:
str- the stringdelimiter- the delimiter- Returns:
- the last part following delimiter or the string if no delimiter at all
-
firstLine
public static String firstLine(String str)
Gets the first line from a multi-line string. Nice in tables.- Parameters:
str- the multiline string- Returns:
- the first line, null if str == null
-
toHexString
public static String toHexString(byte[] binaryData)
Creates a human-readable hex-String out of a byte-array (e.g. from MessageDigest MD5sum).- Parameters:
binaryData- the data, may be null- Returns:
- the formatted hex string , null if data was null
-
toBytes
public static byte[] toBytes(char c)
Converts a single (unicode) char to a byte-array.- Parameters:
c- the character- Returns:
- the byte[2] array
-
toBytes
public static byte[] toBytes(char[] chars)
Converts a char-array to a byte-array.- Parameters:
chars- the character array- Returns:
- the byte array, empty if chars is null
-
hash
public static String hash(String algorithm, char[] salt, char[] input)
Builds a hash from an array of chars.
Note that this method converts the characters to bytes viatoBytes(char[])before applying the hash.- Parameters:
algorithm- the hashing algorithm (MD5, SHA-1, SHA-256 are supported by all java runtimes, at least)salt- the "salt", null if plain hashinput- is the input array of chars- Returns:
- the hash as a string, null if input == null
-
objectToLoggableString
public static String objectToLoggableString(Object object)
Converts a value to a loggable string.- Parameters:
object- the object- Returns:
- the string
-
countOccurrences
public static int countOccurrences(String str, char c)
Counts the number of occurrences of a given character in a string.- Parameters:
str- the string to testc- the character to check for- Returns:
- the number of times c is part of str
-
objectArrayToString
public static String objectArrayToString(Object[] objArray, String separator)
Creates a string from an object array.- Parameters:
objArray- the array of objectsseparator- the string between two objects- Returns:
- the string
-
toCharArray
public static char[] toCharArray(String str)
Null-safe string to a char-array conversion.- Parameters:
str- the string, may be null- Returns:
- the character array, null if str was null
- See Also:
String.toCharArray()
-
fill
public static void fill(char[] buf, char val)Null-safe char array filler.- Parameters:
buf- the char buffer, may be nullval- the value to fill- See Also:
Arrays.fill(char[], char)
-
blank
public static void blank(char[] buf)
Null-safe char array filler.
Fills with blanks.- Parameters:
buf- the char buff, may be null- See Also:
fill(char[], char)
-
toHTML
public static String toHTML(String text)
Converts a multiline string to an HTML-string that can be displayed in a label. Useful to print multiline labels.- Parameters:
text- the input string- Returns:
- the HTML string
-
removeTrailingText
public static String removeTrailingText(String str, String... trail)
Removes a trailing text from a string.
Stops when the first trailing string is found.- Parameters:
str- the original stringtrail- the trailing string(s) to remove- Returns:
- the shortened text, str if nothing removed
-
toAsciiLetterOrDigit
public static String toAsciiLetterOrDigit(String str)
Converts to string containing only the letters A-z or digits.
All other characters will be converted to an underscore. All diacrits will be converted first (seeunDiacrit(java.lang.String, boolean). The resulting string will not contain more than one underscore in a row.Nice to create filenames.
- Parameters:
str- the string- Returns:
- the filename
-
getPlatform
public static String getPlatform()
Gets the name of the operating system from the system properties.- Returns:
- the normalized platform name
-
getArchitecture
public static String getArchitecture()
Gets the name of the architecture from the system properties.- Returns:
- the normalized architecture name
-
filterUpperCase
public static String filterUpperCase(String str)
Gets the uppercase letters only.
Useful to get the camel case letters of a string.- Parameters:
str- the string- Returns:
- the upper case letters
-
evaluate
public static String evaluate(String str, Function<String,String> variableProvider)
Evaluates a string replacing variables.
The semantics are very much the same as known from the maven resources plugin, but with the extension of optional default values and that@turns off nested variable processing.Syntax:
$|@{name[?|!default]}, wherenameis the variable name anddefaultis the default value to be used if there is no such variable (!) or variable is empty (@{linkisAllWhitespace(String)}) or doesn't exist (?).Characters can be quoted with a backslash. A double backslash is treated as a single backslash.
Examples:
@{user.home}/somedir @{user.home?/tmp}/somedir @{user.home!/tmp}/somedirNotice that${...}may lead to unexpected results, if the variable's value contains backslashes, as with windows pathnames, for example.- Parameters:
str- the stringvariableProvider- the variables as properties- Returns:
- the processed string
-
-