Modifier and Type | Class and Description |
---|---|
private static class |
Strings.PlainTextState
States enumeration for plain text parser automata.
|
private static class |
Strings.State
State machine for numeric value parser.
|
Modifier and Type | Field and Description |
---|---|
private static String |
ANY_REX
Regular expression for any character.
|
private static char |
DECIMAL_SEPARATOR
Current locale decimal separator.
|
private static char[] |
DEFAULT_SEPARATORS
Default separators used when
isSeparator(char, char...) separators list is empty. |
private static String |
DOT_REX
Regular expression for dot.
|
private static char |
GROUPING_SEPARATOR
Current locale grouping separator.
|
private static char[] |
HEXA
Hexadecimal characters, lower case.
|
private static DateFormat |
ISO_DATE_FORMAT
ISO8601 date format for
toISO(Date) . |
private static Log |
log
Class logger.
|
private static Pattern |
MEMBER_NAME_PATTERN
Pattern constant used for Java member name validation.
|
private static String[] |
PASSWORD_DICTIONARY
Password dictionary contains ASCII characters for lower case, upper case, numeric and punctuation.
|
private static Pattern |
QUALIFIED_CLASS_NAME
Pattern for qualified class name.
|
private static String |
REGEXP_PATTERN
Pattern for regular expression reserved characters.
|
private static String |
REPLACE_ARG_REX
First argument for regular expression string replacement.
|
private static String |
SEPARATORS
Standard word separator.
|
private static Pattern |
VARIABLE_PATTERN
String variable pattern used to inject system properties.
|
private static String |
WHITE_SPACES
Escaped white spaces.
|
Modifier | Constructor and Description |
---|---|
protected |
Strings()
Prevent default constructor synthesis but allow sub-classing.
|
Modifier and Type | Method and Description |
---|---|
static String |
concat(Object... objects)
Concatenates a variable number of objects, as strings.
|
static String |
escapeFilesPattern(String filesPattern)
Escape files pattern for usage with Java regular expressions.
|
static String |
escapeRegExp(String string)
Escape string for regular expression reserved characters.
|
static String |
escapeXML(String text)
Escape text for reserved XML characters.
|
static void |
escapeXML(String text,
Writer writer)
Escape text for reserved XML characters to a specified writer.
|
static String |
firstSentence(String text)
Return the first sentence of a string, where a sentence ends with a sentence separator followed be white space.
|
static String |
firstWord(String sentence)
Return first word from a sentence.
|
static String |
format(String format,
Object... args)
Process formatted string with arguments transform and no illegal format exception.
|
static String |
generatePassword(int length)
Generate random password of requested length.
|
static String |
getMethodAccessor(String prefix,
String memberName)
Get Java accessor for a given member name.
|
static String |
getProtocol(String url)
Get URL protocol or null if given URL does not contains one.
|
static int |
indexOneOf(CharSequence string,
char... chars)
Search string index of the first character from a series.
|
static String |
injectProperties(String string)
Inject system properties into text with variables.
|
static String |
injectVariables(String template,
Map<String,String> variables)
Inject string values into variables from a given template string.
|
static boolean |
isInteger(String string)
Test if string is an integer numeric value.
|
static boolean |
isMemberName(String name)
Test if given name is Java member like name.
|
static boolean |
isNumeric(String string)
Test if string is a numeric value.
|
private static boolean |
isNumericSuffix(char c)
Predicate to test if character is numeric value suffix.
|
static boolean |
isQualifiedClassName(String name)
Predicate to test if name is qualified name.
|
private static boolean |
isSeparator(char character,
char... separators)
Test if
character is a separator as defined by given separators list. |
static String |
join(Iterable<?> objects)
Join collection of objects, converted to string, using space as separator.
|
static String |
join(Iterable<?> objects,
char separator)
Join collection of objects, converted to string, using specified char separator.
|
static String |
join(Iterable<?> objects,
String separator)
Join collection of objects, converted to string, using specified string separator.Concatenates strings from
collection converted to string but take care to avoid null items.
|
static String |
join(Object[] objects)
Join array of objects, converted to string, using space as separator.
|
static String |
join(Object[] objects,
char separator)
Join array of objects, converted to string, using specified separator.
|
static String |
join(Object[] objects,
String separator)
Join array of objects, converted to string, using specified specified separator.
|
static String |
last(String string,
char separator)
Get last string sequence following given character.
|
static String |
load(File file,
Integer... maxCount)
Load string from UTF-8 file content.
|
static String |
load(InputStream inputStream,
Integer... maxCount)
Load string from UTF-8 bytes stream then closes it.
|
static String |
load(Reader reader,
Integer... maxCount)
Load string from character stream then closes it.
|
static String |
md5(String text)
Generate text MD5 hash into hexadecimal format.
|
private static Pair |
pair(String string,
char separator)
Split string value using given separator and return initialized pair instance.
|
static String |
removeFirstWord(String sentence)
Remove first word from a sentence.
|
static String |
removeTrailing(String string,
char c)
Remove trailing character, if exists.
|
static String |
replaceAll(String source,
Pattern pattern,
Handler<String,String> handler)
Replace all pattern occurrences using match transformer.
|
static void |
save(CharSequence chars,
File file)
Create target file and copy characters into.
|
static void |
save(CharSequence chars,
OutputStream outputStream)
Copy source characters to requested output bytes stream.
|
static void |
save(CharSequence chars,
Writer writer)
Copy source characters to requested output characters stream.
|
static String |
setPrefix(String text,
String prefix)
Ensure a given text start with requested prefix.
|
static List<String> |
split(String string,
char... separators)
Splits string into not empty, trimmed items, using specified separator(s) or space if no separator provided.
|
static List<String> |
split(String string,
String separator)
Splits string using specified string separator and returns trimmed values.
|
static List<Pair> |
splitPairs(String string,
char pairsSeparator,
char componentsSeparator)
Split string using given pairs separator and every pair using pair component separator.
|
static String |
toCamelCase(String word)
Convert word to camel case.
|
static String |
toDashCase(String memberName)
Convert Java member name to list of lower case words separated by dash, that is, HTML and CSS name convention.
|
static String |
toISO(Date date)
Format date to ISO8601.
|
static String |
toMemberName(String words)
Convert dash separated words to Java class member name.
|
static String |
toPlainText(String text)
Deprecated.
|
static String |
toPlainText(String text,
int offset,
int capacity)
Deprecated.
|
static String |
toString(Object... objects)
Concatenates variable number of objects converted to string, separated by colon.
|
private static String |
toString(Object object)
Convert object to string representation.
|
static String |
toTitleCase(String string)
Convert words separated by dash, underscore, space, slash and backslash to title case.
|
static String |
trim(String string)
Trim white spaces around given string.
|
static String |
trim(String string,
char garbage)
Trim given string.
|
static String |
UUID()
Get universal unique ID.
|
private static final Log log
private static DateFormat ISO_DATE_FORMAT
toISO(Date)
.private static final Pattern QUALIFIED_CLASS_NAME
qualifiedClassName := packageName ("." className)+ packageName := packageName "." packagePart packagePart := lowerChar+ className := upperChar char*
private static final Pattern MEMBER_NAME_PATTERN
private static final char[] DEFAULT_SEPARATORS
isSeparator(char, char...)
separators list is empty.private static final char DECIMAL_SEPARATOR
private static final char GROUPING_SEPARATOR
private static final String REGEXP_PATTERN
private static final String REPLACE_ARG_REX
private static final String DOT_REX
private static final String ANY_REX
private static final String WHITE_SPACES
private static final String SEPARATORS
private static final Pattern VARIABLE_PATTERN
private static String[] PASSWORD_DICTIONARY
private static final char[] HEXA
protected Strings()
public static String toCamelCase(String word)
toMemberName(String)
or toTitleCase(String)
if need to convert more words.
Returns null if word argument is null and empty if empty.
word
- word to convert.public static String toTitleCase(String string)
string
parameter is null, respective empty.string
- string containing words to convert.string
converted to title case, null or empty.public static String toMemberName(String words)
this-is-a-string
is converted to thisIsAString
.
Returns null if words argument is null and empty if empty.
words
- string to convert.public static String toDashCase(String memberName)
Returns null if member name argument is null and empty if empty.
memberName
- Java style, camel case member name.public static String toISO(Date date)
date
- date to format.public static String toString(Object... objects)
toString(Object)
to
actually convert every given object to string.objects
- variable number of objects.private static String toString(Object object)
object
is null returns "null",
String
returns it as it is,
Class
returns Class.getName()
,
Throwable
returns causes trace - limited to 8, from cause to cause; if no cause at
all returns Throwable.toString()
,
Object.toString()
.
object
- object to stringify.@Deprecated public static String toPlainText(String text)
toPlainText(String, int, int)
when using entire source text.text
- HTML formatted text.@Deprecated public static String toPlainText(String text, int offset, int capacity)
Implementation note: experimental implementation. This implementation is work in progress and is marked as deprecated to warn developer about logic evolution. Final parser should handle <br> to line break, <p> to double line breaks, <q> to simple quotation mark, <ul> to new lines beginning with tab and dash, <ol> to new lines beginning with tab and ordinal and all <h> tags to triple line breaks.
text
- HTML formatted source text,offset
- source text offset,capacity
- generated plain text maximum allowed length.public static String getMethodAccessor(String prefix, String memberName) throws IllegalArgumentException
memberName
prefixed by
prefix
. If memberName
is dashed case, that is, contains dash character convert it to
camel case. For example getter for email-addresses is getEmailAddresses and for picture
is getPicture.
Accessor prefix
is inserted before method name and for flexibility it can be anything. Anyway, ususal
values are get
, set
and is
. It is caller responsibility to supply the right
prefix.
prefix
- accessor prefix,memberName
- member name.IllegalArgumentException
- if any given parameter is null or empty.public static boolean isQualifiedClassName(String name)
name
- name to test.public static boolean isMemberName(String name)
name
is null return false.name
- name to test.public static String concat(Object... objects)
Object.toString()
overload and append to concatenated result. If a given argument happens to be null, skip
it. Return empty string if this method is invoked with no arguments at all.objects
- variable number of objects.public static String join(Object[] objects)
objects
parameter are ignored.objects
- array of objects to join.public static String join(Object[] objects, char separator)
objects
parameter are ignored.objects
- array of objects to join,separator
- character used as separator.public static String join(Object[] objects, String separator)
join(Iterable)
. Null objects or empty strings from given objects
parameter are
ignored.objects
- array of objects to join,separator
- string used as separator.public static String join(Iterable<?> objects)
objects
- collection of objects to join.public static String join(Iterable<?> objects, char separator)
objects
- collection of objects to join,separator
- character used as separator.public static String join(Iterable<?> objects, String separator)
join(Iterable)
. Null objects or empty strings from given objects
parameter
are ignored.objects
- collection of objects to join,separator
- string used as separator.public static List<String> split(String string, char... separators)
String.trim()
.
Returns null if string argument is null and empty list if is empty. This method supports a variable number of
separator characters - as accepted by isSeparator(char, char...)
predicate; if none given uses space.
string
- source string,separators
- variable number of characters used as separators.private static boolean isSeparator(char character, char... separators)
character
is a separator as defined by given separators
list. If separator list
is empty consider used DEFAULT_SEPARATORS
. This predicate is designed specifically for
split(String, char...)
operation.character
- character to test if usable as separator,separators
- variable number of separator characters.character
is a separator, as defined by this method.public static List<String> split(String string, String separator)
string
- source string,separator
- string used as separator.public static List<Pair> splitPairs(String string, char pairsSeparator, char componentsSeparator)
Returned pair components are trimmed for spaces. This means that spaces around separators are eliminated; this is true for both pairs and pair components separators. For example, " john : doe ; jane : doe ; " will return Pair("john", "doe"), Pair("jane", "doe").
Trailing pairs separator is optional.
string
- string value,pairsSeparator
- pairs separator,componentsSeparator
- pair components separator.BugError
- if a pair is not valid, that is, pair components separator is missing.private static Pair pair(String string, char separator)
string
- string value,separator
- pair components separator.BugError
- if separator not found.private static boolean isNumericSuffix(char c)
c
- character to test.public static boolean isNumeric(String string)
string
- string to test.public static boolean isInteger(String string)
string
- string to test.public static String escapeXML(String text)
text
- string to escape.public static void escapeXML(String text, Writer writer) throws IOException
escapeXML(String)
but result is serialized on the given writer. If text
parameters is null
this method does nothing.text
- string to escape,writer
- writer to serialize resulted escaped string.IOException
- if writer operation fails.public static String escapeRegExp(String string)
string
- regular expression to escape.public static String escapeFilesPattern(String filesPattern)
*.html
becomes .+\.html
. Return null if files pattern
argument is null and empty if empty.filesPattern
- files pattern to prepare.public static String last(String string, char separator)
string
- source string,separator
- character used as separator.public static String firstSentence(String text)
text
parameter is null. Current version recognizes next sentence separators: dot (.),
question mark (?), exclamation mark (!) and semicolon (;).text
- string to scan for first sentence.public static String firstWord(String sentence)
This method returns null if sentence
argument is null and empty if empty.
sentence
- sentence to be scanned for its first wordpublic static String removeFirstWord(String sentence)
firstWord(String)
.
White spaces after first word are also trimmed. For the purpose of this function white spaces are: space, tab,
carriage return, line feed, point, comma, colon and semicolon.
This method returns null if sentence
argument is null and empty if empty.
sentence
- sentence to remove first word from.public static String replaceAll(String source, Pattern pattern, Handler<String,String> handler)
Handler
interface. If Handler.handle(Object)
method returns given match
value replace all degrade to standard behavior, and of course there is no need to use it.
Pattern pattern = Pattern.compile("i"); String text = Strings.replaceAll("This is a text", pattern, new Handler<String, String>() { public String handle(String match) { return "<em>" + match + "</em>"; } });In above sample code, after replace all,
text
will be Th<em>i</em>s
<em>i</em>s a text.source
- source string,pattern
- pattern to look for,handler
- match transformer.public static String injectProperties(String string) throws BugError
${variable-name}
, as known from, for example, Ant or Log4j configuration. This method replace found
variable with system property using variable-name
as property key. It is a logic flaw if system
property is missing.
For example, injecting system properties into ${log}/app.log
will return /var/log/app.log
provided there is a system property named log
with value /var/log
. Note that there is no
limit on the number of system properties and/or variables to replace.
string
- text with variables.BugError
- if system property is missing.public static String injectVariables(String template, Map<String,String> variables)
${variable-name}
, where name is the key from given variables hash. It is legal for a
variable to be declared into template but be missing from variables hash, in which case variable from template is
left unchanged.template
- source string template,variables
- string variables hash.public static String trim(String string, char garbage)
This method returns null if given source string is null and returns empty string if source string is empty or contains only garbage.
string
- source string,garbage
- no longer needed characters at around the string.public static String trim(String string)
Character.isWhitespace(char)
.string
- string value to trim.public static String removeTrailing(String string, char c)
string
- source string,c
- trailing character to eliminate.public static String format(String format, Object... args)
IllegalFormatException
if given string is not well formatted. This method catches it and return
original, not formatted string if exception happened. Uses this method instead of Java String whenever source
string is not from safe source, that can guaranty its format correctness.
Return null if format string argument is null and empty if empty. If optional arguments is missing return original string.
This method takes care to pre-process arguments as follow:
All pre-processed arguments are replaced with string value and format specifier should be also string (%s).format
- string to format,args
- variable number of arguments related to format.public static int indexOneOf(CharSequence string, char... chars)
string
and compare with character
from chars
series one by one, in sequence. If found return string index; if reach the end of the
string return -1.string
- string builder to search on,chars
- characters series.public static String load(InputStream inputStream, Integer... maxCount) throws IOException
inputStream
- source input stream,maxCount
- optional maximum number of characters to read, default to MAX_VALUE.NullPointerException
- if input stream is null.IOException
- if input stream read operation fails.public static String load(File file, Integer... maxCount) throws IOException
file
- source file,maxCount
- optional maximum character count to load, default to entire file.IOException
- if file not found or file read operation fails.public static String load(Reader reader, Integer... maxCount) throws IOException
reader
- source character stream.maxCount
- optional maximum character count to load, default to entire file.IOException
- if read operation fails.public static void save(CharSequence chars, File file) throws IOException
chars
parameter is null or empty this
method does nothing.
Note that this method takes care to create file parent directories.
chars
- source characters sequence,file
- target file.FileNotFoundException
- if target
file does not exist and cannot be created.IOException
- if copy operation fails, including if target
is a directory.public static void save(CharSequence chars, Writer writer) throws IOException
chars
parameter is null or
empty this method does nothing.chars
- source characters stream,writer
- target writer.IOException
- if copy operation fails.public static void save(CharSequence chars, OutputStream outputStream) throws IOException
chars
parameter is null or empty
this method does nothing.chars
- source characters stream,outputStream
- target bytes stream.IOException
- if copy operation fails.public static String UUID()
UUID.randomUUID()
but with dashes removed.public static String setPrefix(String text, String prefix)
text
argument is empty returns given prefix;
returns null if text
argument is null.text
- text to add prefix to, null accepted,prefix
- prefix to force on text start.public static String generatePassword(int length)
PASSWORD_DICTIONARY
and has exactly requested length.length
- password length, strict positive.public static String md5(String text)
text
- source text.Copyright © 2018. All rights reserved.