com.arsdigita.util
Class StringUtils

java.lang.Object
  extended bycom.arsdigita.util.StringUtils

public class StringUtils
extends Object

A (static) class of generally-useful string utilities.

Author:
Bill Schneider

Nested Class Summary
static interface StringUtils.PlaceholderValueGenerator
          An interface allowing the value for a placeholder to be dynamically generated.
 
Field Summary
static String NEW_LINE
           
 
Method Summary
static String addNewline(String s)
          Add a possible newline for proper wrapping.
static boolean emptyString(Object o)
          Tests if a string is empty.
static boolean emptyString(String s)
          Tests if a string is empty.
static String getParameter(String key, String plist, char sep)
          Extract a parameter value from a packed list of parameter values.
static List getStackList(Throwable throwable)
          Returns a list of lines where each line represents one level in the stack trace captured by throwable.
static String getStackTrace(Throwable throwable)
           
static String htmlToText(String s)
          Removes tags and substitutes P tags with newlines.
static String interpolate(String text, Map vars)
          This method performs interpolation on multiple variables.
static String interpolate(String text, String key, String value)
          THis method performs a single variable substitution on a string.
static boolean isAlphaNumeric(String value)
          Returns true if the String is AlphaNumeric.
static String join(List elements, String sep)
          "join" a List of Strings into a single string, with each string separated by a defined separator string.
static String join(String[] strings, char joinChar)
          Converts an array of Strings into a single String separated by a given character.
static String join(String[] strings, String joinStr)
          Converts an array of Strings into a single String separated by a given string.
static String nullToEmptyString(String s)
          If the String is null, returns an empty string.
static String quoteHtml(String s)
          Escapes some "special" characters in HTML text (ampersand, angle brackets, quote).
static String repeat(char pattern, int repeatCount)
          Returns a String containing the specified repeat count of a given pattern character.
static String repeat(String pattern, int repeatCount)
          Returns a String containing the specified repeat count of a given pattern String.
static String replace(String str, String find, String replace)
          Finds all occurrences of find in str and replaces them with them with replace.
static String smartTextToHtml(String s)
          Converts plain text with simple inline markup into HTML.
static String[] split(String s, char sep)
          Convert a string of items separated by a separator character to an array of the items.
static List splitUp(String s, String re)
           Given a string, split it into substrings matching a regular expression that you supply.
static String stripNewLines(String str)
          Strips all new-line characters from the input string.
static String stripWhiteSpace(String s)
          Strip extra white space from a string.
static String textToHtml(String s)
          Takes a plaintext string, and returns an HTML string that, when rendered by a web browser, will appear as the original input string
static String toString(Map m)
          create a String representation of a map.
static String toString(Object o)
          Get a String representation for an Object.
static String trimleft(String s)
          Removes whitespace from the beginning of a string.
static String truncateString(String s, int length)
          This takes the passed in string and truncates it.
static String truncateString(String s, int length, boolean removeHTML)
          This takes the passed in string and truncates it.
static String wrap(String input)
          Wrap a string to be no wider than 80 characters.
static String wrap(String input, int maxLength)
          Wrap a string to be no wider than a specified number of characters by inserting line breaks.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

NEW_LINE

public static final String NEW_LINE
Method Detail

emptyString

public static final boolean emptyString(String s)
Tests if a string is empty.

Parameters:
s - A string to test
Returns:
true if s is null or empty; otherwise false

emptyString

public static final boolean emptyString(Object o)
Tests if a string is empty.

Parameters:
o - A string to test
Returns:
true if o is null or empty; otherwise false

nullToEmptyString

public static final String nullToEmptyString(String s)
If the String is null, returns an empty string. Otherwise, returns the string unaltered


quoteHtml

public static final String quoteHtml(String s)
Escapes some "special" characters in HTML text (ampersand, angle brackets, quote).

Parameters:
s - The plain-text string to quote
Returns:
The string with special characters escpaed.

textToHtml

public static final String textToHtml(String s)
Takes a plaintext string, and returns an HTML string that, when rendered by a web browser, will appear as the original input string

Parameters:
s - The input plaintext string
Returns:
A HTML string with blank lines coverted to
<p>
and ampersands/angle brackets escaped.

htmlToText

public static final String htmlToText(String s)
Removes tags and substitutes P tags with newlines. For much more extensive conversion of HTML fragments to plain text equivalents, see HtmlToText.


smartTextToHtml

public static final String smartTextToHtml(String s)
Converts plain text with simple inline markup into HTML. The following constructs are recognised:


split

public static String[] split(String s,
                             char sep)
Convert a string of items separated by a separator character to an array of the items. sep is the separator character. Example: Input - s == "cat,house,dog" sep==',' Output - {"cat", "house", "dog"}

Parameters:
s - string contains items separated by a separator character.
sep - separator character.
Returns:
Array of items.

splitUp

public static List splitUp(String s,
                           String re)

Given a string, split it into substrings matching a regular expression that you supply. Parts of the original string which don't match the regular expression also appear as substrings. The upshot of this is that the final substrings can be concatenated to get the original string.

As an example, let's say the original string is:

 s = "/packages/foo/xsl/::vhost::/foo_::locale::.xsl";
 

We call the function like this:

 output = splitUp (s, "/::\\w+::/");
 

The result (output) will be the following list:

 ("/packages/foo/xsl/", "::vhost::", "/foo_", "::locale::", ".xsl")
 

Notice the important property that concatenating all these strings together will restore the original string.

Here is another useful example. To split up HTML into elements and content, do:

 output = splitUp (html, "/<.*?>/");
 

You will end up with something like this:

 ("The following text will be ", "", "bold", "", ".")
 

Parameters:
s - The original string to split.
re - The regular expression in the format required by Perl5Util.match(String, String).
Returns:
List of substrings.

join

public static String join(String[] strings,
                          char joinChar)
Converts an array of Strings into a single String separated by a given character. Example Input: {"cat", "house", "dog"}, ',' Output - "cat,house,dog"

Parameters:
strings - The string array too join.
joinChar - The character to join the array members together.
Returns:
Joined String

join

public static String join(String[] strings,
                          String joinStr)
Converts an array of Strings into a single String separated by a given string. Example Input: {"cat", "house", "dog"}, ", " Output - "cat, house, dog"

Parameters:
strings - The string array too join.
joinStr - The string to join the array members together.
Returns:
Joined String

getParameter

public static String getParameter(String key,
                                  String plist,
                                  char sep)
Extract a parameter value from a packed list of parameter values. Example: input: key="age", sep=',', plist="cost=23,age=27,name=Thom" output = "27". This is a simple implementation that is meant for controlled use in which the key and values are known to be safe. Specifically, the equals character must be used to indicate parameter assignments. There is no escape character. Thus the parameter names and values cannot contain the equals character or the separator character.

Parameters:
key - the key indicating which parameter value to extract.
plist - packed list of key=value assignments. The character '=' must be used to indicate the assignment.
sep - separator character.
Returns:
the value corresponding to the key, or null if the key is not present. If the key appears in the list more than once, the first value is returned.

stripWhiteSpace

public static String stripWhiteSpace(String s)
Strip extra white space from a string. This replaces any white space character or consecutive white space characters with a single space. It is useful when comparing strings that should be equal except for possible differences in white space. Example: input = "I \ndo\tsee". Output = "I do see".

Parameters:
s - string that may contain extra white space
Returns:
string the same as the input, but with extra white space removed and replaced by a single space.

toString

public static String toString(Object o)
Get a String representation for an Object. If it has an asString method, use that; otherwise fall back on toString


toString

public static String toString(Map m)
create a String representation of a map. This method is not too necessary, because Map.toString() does almost the same.


stripNewLines

public static String stripNewLines(String str)
Strips all new-line characters from the input string.

Parameters:
str - a string to strip
Returns:
the input string with all new-line characters removed.

addNewline

public static String addNewline(String s)

Add a possible newline for proper wrapping.

Checks the given String to see if it ends with whitspace. If so, it assumes this whitespace is intentional formatting and returns a reference to the original string. If not, a new String object is created containing the original plus a platform-dependent newline character obtained from System.getProperty("line.separator").


truncateString

public static String truncateString(String s,
                                    int length)
This takes the passed in string and truncates it. It cuts the string off at the length specified and then goes back to the most recent space and truncates any word that may have been cut off. It also takes the string and converts it to plain text so that no HTML will be shown.


truncateString

public static String truncateString(String s,
                                    int length,
                                    boolean removeHTML)
This takes the passed in string and truncates it. It cuts the string off at the length specified and then goes back to the most recent space and truncates any word that may have been cut off. The htmlToText dictates whehter or not the string should be converted from HTML to text before being truncated

Parameters:
s - The string to be truncated
length - The length which to truncate the string
removeHTML - Whether or not to convert the HTML to text

join

public static String join(List elements,
                          String sep)
"join" a List of Strings into a single string, with each string separated by a defined separator string.

Parameters:
elements - the strings to join together
sep - the separator string
Returns:
the strings joined together

trimleft

public static final String trimleft(String s)
Removes whitespace from the beginning of a string. If the string consists of nothing but whitespace characters, an empty string is returned.


repeat

public static final String repeat(String pattern,
                                  int repeatCount)
Returns a String containing the specified repeat count of a given pattern String.

Parameters:
pattern - the pattern String
repeatCount - the number of time to repeat it

repeat

public static final String repeat(char pattern,
                                  int repeatCount)
Returns a String containing the specified repeat count of a given pattern character.

Parameters:
pattern - the pattern character
repeatCount - the number of time to repeat it

wrap

public static final String wrap(String input)
Wrap a string to be no wider than 80 characters. This is just a convenience method for calling the more general method with a default string width.

Parameters:
input - the String to wrap
Since:
5.1.2

wrap

public static final String wrap(String input,
                                int maxLength)
Wrap a string to be no wider than a specified number of characters by inserting line breaks. If the input is null or the empty string, a string consisting of only the newline character will be returned. Otherwise the input string will be wrapped to the specified line length. In all cases the last character of the return value will be a single newline.

Notes:

  1. line breaks in the input string are preserved
  2. wrapping is "soft" in that lines in the output string may be longer than maxLength if they consist of contiguous non-whitespace characters.

Parameters:
input - the String to wrap
maxLength - the maximum number of characters between line breaks
Since:
5.1.2

isAlphaNumeric

public static boolean isAlphaNumeric(String value)
Returns true if the String is AlphaNumeric. Obviously, this is not at all globalized and should only be used with English text.

Parameters:
value - String to check
Returns:
true if value is alphanumeric, false otherwise.

interpolate

public static String interpolate(String text,
                                 Map vars)
This method performs interpolation on multiple variables. The keys in the hash table correspond directly to the placeholders in the string. The values in the hash table can either be plain strings, or an instance of the PlaceholderValueGenerator interface Variable placeholders are indicated in text by surrounding a key word with a pair of colons. The keys in the hash table correspond to the names eg. "::forename:: has the email address ::email::"

Parameters:
text - the text to interpolate
vars - a hash table containing key -> value mappings
See Also:
MessageFormat

interpolate

public static String interpolate(String text,
                                 String key,
                                 String value)
THis method performs a single variable substitution on a string. The placeholder takes the form of ::key:: within the sample text.

Parameters:
text - the text to process for substitutions
key - the name of the placeholder
value - the value to insert upon encountering a placeholder
See Also:
MessageFormat

replace

public static String replace(String str,
                             String find,
                             String replace)
Finds all occurrences of find in str and replaces them with them with replace.


getStackTrace

public static String getStackTrace(Throwable throwable)
Throws:
NullPointerException - if throwable is null

getStackList

public static List getStackList(Throwable throwable)
Returns a list of lines where each line represents one level in the stack trace captured by throwable.

For a stack trace like this:

 java.lang.Throwable
         at Main.level3(Main.java:19)
         at Main.level2(Main.java:15)
         at Main.level1(Main.java:11)
         at Main.main(Main.java:7)
 

the returned list looks like this:

 ["java.lang.Throwable",
  "Main.level3(Main.java:20)",
  "Main.level2(Main.java:15)",
  "Main.level1(Main.java:11)",
  "Main.main(Main.java:7)"]
 

Throws:
NullPointerException - if throwable is null
See Also:
getStackTrace(Throwable)


Copyright (c) 2004 Red Hat, Inc. Corporation. All Rights Reserved. Generated at July 21 2004:2337 UTC