Package org.apache.camel.util
Class StringHelper
- java.lang.Object
-
- org.apache.camel.util.StringHelper
-
public final class StringHelper extends Object
Helper methods for working with Strings.
-
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static String
after(String text, String after)
Returns the string after the given tokenstatic String
after(String text, String after, String defaultValue)
Returns the string after the given token, or the default valuestatic <T> Optional<T>
after(String text, String after, Function<String,T> mapper)
Returns an object after the given tokenstatic String
afterLast(String text, String after)
Returns the string after the the last occurrence of the given tokenstatic String
afterLast(String text, String after, String defaultValue)
Returns the string after the the last occurrence of the given token, or the default valuestatic String
asEnumConstantValue(String value)
Converts the value to an enum constant value that is in the form of upper cased with underscore.static String
before(String text, String before)
Returns the string before the given tokenstatic String
before(String text, String before, String defaultValue)
Returns the string before the given token, or the default valuestatic <T> Optional<T>
before(String text, String before, Function<String,T> mapper)
Returns an object before the given tokenstatic String
beforeLast(String text, String before)
Returns the string before the last occurrence of the given tokenstatic String
beforeLast(String text, String before, String defaultValue)
Returns the string before the last occurrence of the given token, or the default valuestatic String
between(String text, String after, String before)
Returns the string between the given tokensstatic <T> Optional<T>
between(String text, String after, String before, Function<String,T> mapper)
Returns an object between the given tokenstatic String
betweenOuterPair(String text, char before, char after)
Returns the string between the most outer pair of tokensstatic <T> Optional<T>
betweenOuterPair(String text, char before, char after, Function<String,T> mapper)
Returns an object between the most outer pair of tokensstatic String
camelCaseToDash(String text)
Converts the string from camel case into dash format (helloGreatWorld -> hello-great-world)static String
capitalize(String text)
Capitalize the string (upper case first character)static String
capitalize(String text, boolean dashToCamelCase)
Capitalize the string (upper case first character)static List<Integer>
changedLines(String oldText, String newText)
Compares old and new text content and report back which lines are changedstatic boolean
containsIgnoreCase(String src, String what)
Checks if the src string contains whatstatic int
countChar(String s, char ch)
Counts the number of times the given char is in the stringstatic int
countChar(String s, char ch, int end)
Counts the number of times the given char is in the stringstatic int
countOccurrence(String text, String search)
Returns the occurrence of a search string in to a string.static String
dashToCamelCase(String text)
Converts the string from dash format into camel case (hello-great-world -> helloGreatWorld)static boolean
hasStartToken(String expression, String language)
Does the expression have the language start token?static boolean
hasUpperCase(String text)
Determines if the string has at least one letter in upper casestatic String
humanReadableBytes(long bytes)
Outputs the bytes in human readable format in units of KB,MB,GB etc.static String
humanReadableBytes(Locale locale, long bytes)
Outputs the bytes in human readable format in units of KB,MB,GB etc.static boolean
isClassName(String text)
Determines if the string is a fully qualified class namestatic boolean
isJavaIdentifier(String name)
Returns true if the given name is a valid java identifierstatic boolean
isQuoted(String s)
Whether the string starts and ends with either single or double quotes.static String
limitLength(String s, int maxLength)
Limits the length of a stringstatic boolean
matches(String pattern, String target)
Check for string pattern matching with a number of strategies in the following order: - equals - null pattern always matches - * always matches - Ant style matching - Regexpstatic String
normalizeClassName(String name)
Cleans the string to a pure Java identifier so we can use it for loading class names.static String
notEmpty(String value, String name)
Asserts whether the string is not empty.static String
notEmpty(String value, String name, Object on)
Asserts whether the string is not empty.static String
removeCRLF(String s)
Remove carriage return and line feeds from a String, replacing them with an empty String.static String
removeLeadingAndEndingQuotes(String s)
Removes all leading and ending quotes (single and double) from the stringstatic String
removeQuotes(String s)
Removes all quotes (single and double) from the stringstatic String
removeStartingCharacters(String text, char ch)
Removes any starting characters on the given text which match the given characterstatic String
replaceFirst(String input, String from, String to)
Replaces the first from token in the given input string.static String
replaceFromSecondOccurrence(String text, String search, String replacement)
Replaces a string in to a text starting from his second occurrence.static String
sanitize(String s)
Ensures thats
is friendly for a URL or file system.static Stream<String>
splitAsStream(CharSequence text, String regex)
Creates a stream from the given input sequence around matches of the regexstatic String[]
splitOnCharacter(String value, String needle, int count)
static Iterator<String>
splitOnCharacterAsIterator(String value, char needle, int count)
static List<String>
splitOnCharacterAsList(String value, char needle, int count)
static String[]
splitWords(String text)
Split the text on words, eg hello/world => becomes array with hello in index 0, and world in index 1.static boolean
startsWithIgnoreCase(String text, String prefix)
Does the string starts with the given prefix (ignore case).static String
toJson(String name, String value, boolean isMap)
Creates a json tuple with the given name/value pair.static String
trimToNull(String given)
Removes the leading and trailing whitespace and if the resulting string is empty returnsnull
.static String
xmlEncode(String text)
Encodes the text into safe XML by replacing < > and & with XML tokens
-
-
-
Method Detail
-
sanitize
public static String sanitize(String s)
Ensures thats
is friendly for a URL or file system.- Parameters:
s
- String to be sanitized.- Returns:
- sanitized version of
s
. - Throws:
NullPointerException
- ifs
isnull
.
-
removeCRLF
public static String removeCRLF(String s)
Remove carriage return and line feeds from a String, replacing them with an empty String.- Parameters:
s
- String to be sanitized of carriage return / line feed characters- Returns:
- sanitized version of
s
. - Throws:
NullPointerException
- ifs
isnull
.
-
countChar
public static int countChar(String s, char ch)
Counts the number of times the given char is in the string- Parameters:
s
- the stringch
- the char- Returns:
- number of times char is located in the string
-
countChar
public static int countChar(String s, char ch, int end)
Counts the number of times the given char is in the string- Parameters:
s
- the stringch
- the charend
- end index- Returns:
- number of times char is located in the string
-
limitLength
public static String limitLength(String s, int maxLength)
Limits the length of a string- Parameters:
s
- the stringmaxLength
- the maximum length of the returned string- Returns:
- s if the length of s is less than maxLength or the first maxLength characters of s
-
removeQuotes
public static String removeQuotes(String s)
Removes all quotes (single and double) from the string- Parameters:
s
- the string- Returns:
- the string without quotes (single and double)
-
removeLeadingAndEndingQuotes
public static String removeLeadingAndEndingQuotes(String s)
Removes all leading and ending quotes (single and double) from the string- Parameters:
s
- the string- Returns:
- the string without leading and ending quotes (single and double)
-
isQuoted
public static boolean isQuoted(String s)
Whether the string starts and ends with either single or double quotes.- Parameters:
s
- the string- Returns:
- true if the string starts and ends with either single or double quotes.
-
xmlEncode
public static String xmlEncode(String text)
Encodes the text into safe XML by replacing < > and & with XML tokens- Parameters:
text
- the text- Returns:
- the encoded text
-
hasUpperCase
public static boolean hasUpperCase(String text)
Determines if the string has at least one letter in upper case- Parameters:
text
- the text- Returns:
- true if at least one letter is upper case, false otherwise
-
isClassName
public static boolean isClassName(String text)
Determines if the string is a fully qualified class name
-
hasStartToken
public static boolean hasStartToken(String expression, String language)
Does the expression have the language start token?- Parameters:
expression
- the expressionlanguage
- the name of the language, such as simple- Returns:
- true if the expression contains the start token, false otherwise
-
replaceFirst
public static String replaceFirst(String input, String from, String to)
Replaces the first from token in the given input string. This implementation is not recursive, not does it check for tokens in the replacement string.- Parameters:
input
- the input stringfrom
- the from string, must not be null or emptyto
- the replacement string, must not be empty- Returns:
- the replaced string, or the input string if no replacement was needed
- Throws:
IllegalArgumentException
- if the input arguments is invalid
-
toJson
public static String toJson(String name, String value, boolean isMap)
Creates a json tuple with the given name/value pair.- Parameters:
name
- the namevalue
- the valueisMap
- whether the tuple should be map- Returns:
- the json
-
notEmpty
public static String notEmpty(String value, String name)
Asserts whether the string is not empty.- Parameters:
value
- the string to testname
- the key that resolved the value- Returns:
- the passed
value
as is - Throws:
IllegalArgumentException
- is thrown if assertion fails
-
notEmpty
public static String notEmpty(String value, String name, Object on)
Asserts whether the string is not empty.- Parameters:
value
- the string to teston
- additional description to indicate where this problem occurred (appended as toString())name
- the key that resolved the value- Returns:
- the passed
value
as is - Throws:
IllegalArgumentException
- is thrown if assertion fails
-
splitOnCharacter
public static String[] splitOnCharacter(String value, String needle, int count)
-
splitOnCharacterAsIterator
public static Iterator<String> splitOnCharacterAsIterator(String value, char needle, int count)
-
splitOnCharacterAsList
public static List<String> splitOnCharacterAsList(String value, char needle, int count)
-
removeStartingCharacters
public static String removeStartingCharacters(String text, char ch)
Removes any starting characters on the given text which match the given character- Parameters:
text
- the stringch
- the initial characters to remove- Returns:
- either the original string or the new substring
-
capitalize
public static String capitalize(String text)
Capitalize the string (upper case first character)- Parameters:
text
- the string- Returns:
- the string capitalized (upper case first character)
-
capitalize
public static String capitalize(String text, boolean dashToCamelCase)
Capitalize the string (upper case first character)- Parameters:
text
- the stringdashToCamelCase
- whether to also convert dash format into camel case (hello-great-world -> helloGreatWorld)- Returns:
- the string capitalized (upper case first character)
-
dashToCamelCase
public static String dashToCamelCase(String text)
Converts the string from dash format into camel case (hello-great-world -> helloGreatWorld)- Parameters:
text
- the string- Returns:
- the string camel cased
-
after
public static String after(String text, String after)
Returns the string after the given token- Parameters:
text
- the textafter
- the token- Returns:
- the text after the token, or null if text does not contain the token
-
after
public static String after(String text, String after, String defaultValue)
Returns the string after the given token, or the default value- Parameters:
text
- the textafter
- the tokendefaultValue
- the value to return if text does not contain the token- Returns:
- the text after the token, or the supplied defaultValue if text does not contain the token
-
after
public static <T> Optional<T> after(String text, String after, Function<String,T> mapper)
Returns an object after the given token- Parameters:
text
- the textafter
- the tokenmapper
- a mapping function to convert the string after the token to type T- Returns:
- an Optional describing the result of applying a mapping function to the text after the token.
-
afterLast
public static String afterLast(String text, String after)
Returns the string after the the last occurrence of the given token- Parameters:
text
- the textafter
- the token- Returns:
- the text after the token, or null if text does not contain the token
-
afterLast
public static String afterLast(String text, String after, String defaultValue)
Returns the string after the the last occurrence of the given token, or the default value- Parameters:
text
- the textafter
- the tokendefaultValue
- the value to return if text does not contain the token- Returns:
- the text after the token, or the supplied defaultValue if text does not contain the token
-
before
public static String before(String text, String before)
Returns the string before the given token- Parameters:
text
- the textbefore
- the token- Returns:
- the text before the token, or null if text does not contain the token
-
before
public static String before(String text, String before, String defaultValue)
Returns the string before the given token, or the default value- Parameters:
text
- the textbefore
- the tokendefaultValue
- the value to return if text does not contain the token- Returns:
- the text before the token, or the supplied defaultValue if text does not contain the token
-
before
public static <T> Optional<T> before(String text, String before, Function<String,T> mapper)
Returns an object before the given token- Parameters:
text
- the textbefore
- the tokenmapper
- a mapping function to convert the string before the token to type T- Returns:
- an Optional describing the result of applying a mapping function to the text before the token.
-
beforeLast
public static String beforeLast(String text, String before)
Returns the string before the last occurrence of the given token- Parameters:
text
- the textbefore
- the token- Returns:
- the text before the token, or null if text does not contain the token
-
beforeLast
public static String beforeLast(String text, String before, String defaultValue)
Returns the string before the last occurrence of the given token, or the default value- Parameters:
text
- the textbefore
- the tokendefaultValue
- the value to return if text does not contain the token- Returns:
- the text before the token, or the supplied defaultValue if text does not contain the token
-
between
public static String between(String text, String after, String before)
Returns the string between the given tokens- Parameters:
text
- the textafter
- the before tokenbefore
- the after token- Returns:
- the text between the tokens, or null if text does not contain the tokens
-
between
public static <T> Optional<T> between(String text, String after, String before, Function<String,T> mapper)
Returns an object between the given token- Parameters:
text
- the textafter
- the before tokenbefore
- the after tokenmapper
- a mapping function to convert the string between the token to type T- Returns:
- an Optional describing the result of applying a mapping function to the text between the token.
-
betweenOuterPair
public static String betweenOuterPair(String text, char before, char after)
Returns the string between the most outer pair of tokens The number of token pairs must be evenly, eg there must be same number of before and after tokens, otherwise null is returned This implementation skips matching when the text is either single or double quoted. For example: ${body.matches("foo('bar')") Will not match the parenthesis from the quoted text.- Parameters:
text
- the textafter
- the before tokenbefore
- the after token- Returns:
- the text between the outer most tokens, or null if text does not contain the tokens
-
betweenOuterPair
public static <T> Optional<T> betweenOuterPair(String text, char before, char after, Function<String,T> mapper)
Returns an object between the most outer pair of tokens- Parameters:
text
- the textafter
- the before tokenbefore
- the after tokenmapper
- a mapping function to convert the string between the most outer pair of tokens to type T- Returns:
- an Optional describing the result of applying a mapping function to the text between the most outer pair of tokens.
-
isJavaIdentifier
public static boolean isJavaIdentifier(String name)
Returns true if the given name is a valid java identifier
-
normalizeClassName
public static String normalizeClassName(String name)
Cleans the string to a pure Java identifier so we can use it for loading class names. Especially from Spring DSL people can have \n \t or other characters that otherwise would result in ClassNotFoundException- Parameters:
name
- the class name- Returns:
- normalized classname that can be load by a class loader.
-
changedLines
public static List<Integer> changedLines(String oldText, String newText)
Compares old and new text content and report back which lines are changed- Parameters:
oldText
- the old textnewText
- the new text- Returns:
- a list of line numbers that are changed in the new text
-
trimToNull
public static String trimToNull(String given)
Removes the leading and trailing whitespace and if the resulting string is empty returnsnull
. Examples:Examples:
trimToNull("abc") -> "abc" trimToNull(" abc") -> "abc" trimToNull(" abc ") -> "abc" trimToNull(" ") -> null trimToNull("") -> null
-
containsIgnoreCase
public static boolean containsIgnoreCase(String src, String what)
Checks if the src string contains what- Parameters:
src
- is the source string to be checkedwhat
- is the string which will be looked up in the src argument- Returns:
- true/false
-
humanReadableBytes
public static String humanReadableBytes(Locale locale, long bytes)
Outputs the bytes in human readable format in units of KB,MB,GB etc.- Parameters:
locale
- The locale to apply during formatting. If l isnull
then no localization is applied.bytes
- number of bytes- Returns:
- human readable output
- See Also:
String.format(Locale, String, Object...)
-
humanReadableBytes
public static String humanReadableBytes(long bytes)
Outputs the bytes in human readable format in units of KB,MB,GB etc. The locale always used is the one returned byLocale.getDefault()
.- Parameters:
bytes
- number of bytes- Returns:
- human readable output
- See Also:
humanReadableBytes(Locale, long)
-
matches
public static boolean matches(String pattern, String target)
Check for string pattern matching with a number of strategies in the following order: - equals - null pattern always matches - * always matches - Ant style matching - Regexp- Parameters:
pattern
- the patterntarget
- the string to test- Returns:
- true if target matches the pattern
-
camelCaseToDash
public static String camelCaseToDash(String text)
Converts the string from camel case into dash format (helloGreatWorld -> hello-great-world)- Parameters:
text
- the string- Returns:
- the string camel cased
-
startsWithIgnoreCase
public static boolean startsWithIgnoreCase(String text, String prefix)
Does the string starts with the given prefix (ignore case).- Parameters:
text
- the stringprefix
- the prefix
-
asEnumConstantValue
public static String asEnumConstantValue(String value)
Converts the value to an enum constant value that is in the form of upper cased with underscore.
-
splitWords
public static String[] splitWords(String text)
Split the text on words, eg hello/world => becomes array with hello in index 0, and world in index 1.
-
splitAsStream
public static Stream<String> splitAsStream(CharSequence text, String regex)
Creates a stream from the given input sequence around matches of the regex- Parameters:
text
- the inputregex
- the expression used to split the input- Returns:
- the stream of strings computed by splitting the input with the given regex
-
countOccurrence
public static int countOccurrence(String text, String search)
Returns the occurrence of a search string in to a string.- Parameters:
text
- the textsearch
- the string to search- Returns:
- an integer reporting the number of occurrence of the searched string in to the text
-
replaceFromSecondOccurrence
public static String replaceFromSecondOccurrence(String text, String search, String replacement)
Replaces a string in to a text starting from his second occurrence.- Parameters:
text
- the textsearch
- the string to searchreplacement
- the replacement for the string- Returns:
- the string with the replacement
-
-