com.opensymphony.util
Class TextUtils

java.lang.Object
  extended bycom.opensymphony.util.TextUtils

public class TextUtils
extends java.lang.Object

Utilities for common String manipulations. This is a class contains static methods only and is not meant to be instantiated.

Version:
$Revision: 1.9 $
Author:
Joe Walnes, Patrick Kan, Mike Cannon-Brookes, Hani Suleiman, Joseph B. Ottinger, Scott Farquhar

Field Summary
static java.lang.String[] SINGLE_TAGS
          An array of HTML tags that, in HTML, don't require closing tags.
 
Constructor Summary
TextUtils()
           
 
Method Summary
static java.lang.String br(java.lang.String s)
          Convert line breaks to html <br> tag.
static java.lang.String closeTags(java.lang.String str)
          Search through a String for any tags that have been opened and append closing tags for those that have not been closed.
static java.lang.String colorToHex(java.awt.Color c)
          Convert Color to html hex string.
static byte[] decodeBytes(java.lang.String str)
          Decode binary data from String using base64.
static java.lang.Object decodeObject(java.lang.String str)
          Decode Object from a String by decoding with base64 then deserializing.
static java.lang.String encodeBytes(byte[] data)
          Encode binary data into String using base64.
static java.lang.String encodeObject(java.lang.Object o)
          Encode an Object to String by serializing it and encoding using base64.
static java.lang.String extractNumber(java.lang.String in)
          Extract a number from a String.
static java.awt.Color hexToColor(java.lang.String color)
          Convert html hex string to Color.
static java.lang.String html(java.lang.String s)
          Deprecated. use htmlEncode(String) instead.
static java.lang.String htmlEncode(java.lang.String s)
          Escape html entity characters and high characters (eg "curvy" Word quotes).
static java.lang.String hyperlink(java.lang.String text)
          Convert all URLs and E-mail addresses in a string into hyperlinks.
static java.lang.String hyperlink(java.lang.String text, java.lang.String target)
          Convert all URLs and E-mail addresses in a string into hyperlinks.
static java.lang.String indent(java.lang.String string, int indentSize, boolean initialLine)
          Indent a String with line-breaks.
static java.lang.String innerTrim(java.lang.String s)
          Returns a string that has whitespace removed from both ends of the String, as well as duplicate whitespace removed from within the String.
static java.lang.String join(java.lang.String glue, java.util.Collection pieces)
          Join a Collection of Strings together.
static java.lang.String join(java.lang.String glue, java.util.Iterator pieces)
          Join an Iteration of Strings together.
static java.lang.String join(java.lang.String glue, java.lang.String[] pieces)
          Join an array of Strings together.
static java.lang.String leadingSpaces(java.lang.String s)
          Finds all leading spaces on each line and replaces it with an HTML space (&nbsp;)
static java.lang.String left(java.lang.String s, int n)
          Returns the leftmost n chars of the string.
static java.lang.String linkEmail(java.lang.String str)
          Wrap all email addresses in specified string with href tags.
static java.lang.String linkURL(java.lang.String str)
          Wrap all urls ('http://', 'www.', and 'ftp://') in specified string with href tags.
static java.lang.String linkURL(java.lang.String str, java.lang.String target)
          Wrap all urls ('abc://' and 'www.abc') in specified string with href tags.
static java.lang.String list(java.lang.String str)
          Create elements in a piece of plain text; Will convert lines starting with - or *.
static java.lang.String noNull(java.lang.String string)
          Return string, or "" if string is null.
static java.lang.String noNull(java.lang.String string, java.lang.String defaultString)
          Return string, or defaultString if string is null or "".
static boolean parseBoolean(java.lang.String in)
          Convert a String to an boolean.
static java.util.Date parseDate(java.lang.String year, java.lang.String month, java.lang.String day)
          Given 3 Strings representing the the year, month and day, return a Date object.
static double parseDouble(java.lang.String in)
          Convert a String to a double.
static float parseFloat(java.lang.String in)
          Convert a String to a float.
static int parseInt(java.lang.String in)
          Convert a String to an int.
static long parseLong(java.lang.String in)
          Convert a String to a long.
static java.lang.String plainTextToHtml(java.lang.String str)
          Converts plain text to html code.
static java.lang.String plainTextToHtml(java.lang.String str, java.lang.String target)
          Converts plain text to html code.
static java.lang.String removeAndInsert(java.lang.String str, int removeAndInsertStart, int removeEnd, java.lang.String insertStr)
          Removes part of the original string starting at removeAndInsertStart and ending at removeEnd.
static java.lang.String slashes(java.lang.String s)
          Escape chars that need slashes in front of them.
static boolean stringSet(java.lang.String string)
          Check whether string has been set to something other than "" or null.
static java.lang.String trimToEndingChar(java.lang.String str, int len)
          Trim a String to the specified length.
static boolean verifyEmail(java.lang.String email)
          Verify that the given string is a valid email address.
static boolean verifyUrl(java.lang.String url)
          Verify That the given String is in valid URL format.
static java.lang.String wrapParagraph(java.lang.String s)
          Wrap paragraphs in html <p> tags.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

SINGLE_TAGS

public static final java.lang.String[] SINGLE_TAGS
An array of HTML tags that, in HTML, don't require closing tags. Note that XHTML doesn't work this way.

Constructor Detail

TextUtils

public TextUtils()
Method Detail

br

public static final java.lang.String br(java.lang.String s)
Convert line breaks to html <br> tag.

Parameters:
s - the String to convert
Returns:
the converted string

closeTags

public static final java.lang.String closeTags(java.lang.String str)
Search through a String for any tags that have been opened and append closing tags for those that have not been closed.

Parameters:
str - A string possibly containing unclosed HTML tags
Returns:
the converted string #see #SINGLE_TAGS

colorToHex

public static final java.lang.String colorToHex(java.awt.Color c)
Convert Color to html hex string. (#012345)

Parameters:
c - the Color to convert
Returns:
A string with a hexadecimal RGB encoding

decodeBytes

public static final byte[] decodeBytes(java.lang.String str)
                                throws java.io.IOException
Decode binary data from String using base64.

Throws:
java.io.IOException
See Also:
encodeBytes(byte[])

decodeObject

public static final java.lang.Object decodeObject(java.lang.String str)
                                           throws java.io.IOException,
                                                  java.lang.ClassNotFoundException
Decode Object from a String by decoding with base64 then deserializing.

Throws:
java.io.IOException
java.lang.ClassNotFoundException
See Also:
encodeObject(java.lang.Object)

encodeBytes

public static final java.lang.String encodeBytes(byte[] data)
                                          throws java.io.IOException
Encode binary data into String using base64.

Throws:
java.io.IOException
See Also:
decodeBytes(java.lang.String)

encodeObject

public static final java.lang.String encodeObject(java.lang.Object o)
                                           throws java.io.IOException
Encode an Object to String by serializing it and encoding using base64.

Throws:
java.io.IOException
See Also:
decodeObject(java.lang.String)

extractNumber

public static final java.lang.String extractNumber(java.lang.String in)
Extract a number from a String.
Example
   " 12345"                 ->     "12345"
   "hello123bye"            ->     "123"
   "a2b4c6 8 "              ->     "2468"
   " -22"                   ->     "-22"
   "5.512"                  ->     "5.512"
   "1.2.3.4"                ->     "1.234"
   ".2"                     ->     "0.2"
   "-555.7"                 ->     "-555.7"
   "-..6"                   ->     "-0.6"
   "abc- dx.97 9"           ->     "-0.979"
   "?1,000,000.00 per year" ->     "1000000.00"
   ""                       ->     "0"
   "asdsf"                  ->     "0"
   "123."                   ->     "123"
   null                     ->     "0"
 

Parameters:
in - Original String containing number to be extracted.
Returns:
String stripped of all non-numeric chars.
See Also:
parseInt(String), parseLong(String)

hexToColor

public static final java.awt.Color hexToColor(java.lang.String color)
Convert html hex string to Color. If the hexadecimal string is not a valid character, Color.black is returned. Only the first six hexadecimal characters are considered; any extraneous values are discarded. Also, a leading "#", if any, is allowed (and ignored).

Parameters:
color - the String (in RGB hexadecimal format) to convert
Returns:
the java.awt.Color

html

public static final java.lang.String html(java.lang.String s)
Deprecated. use htmlEncode(String) instead.

Escape html entity characters and high characters (eg "curvy" Word quotes). Note this method can also be used to encode XML now


htmlEncode

public static final java.lang.String htmlEncode(java.lang.String s)
Escape html entity characters and high characters (eg "curvy" Word quotes). Note this method can also be used to encode XML.

Parameters:
s - the String to escape.
Returns:
the escaped string

hyperlink

public static final java.lang.String hyperlink(java.lang.String text)
Convert all URLs and E-mail addresses in a string into hyperlinks.

Parameters:
text - The block of text to hyperlink.
Returns:
the text with known uri formats hyperlinked
See Also:
hyperlink(String, String)

hyperlink

public static final java.lang.String hyperlink(java.lang.String text,
                                               java.lang.String target)
Convert all URLs and E-mail addresses in a string into hyperlinks.

Parameters:
text - The block of text to hyperlink.
target - The target attribute to use for href (optional).
Returns:
the text with known uri formats hyperlinked
See Also:
linkEmail(String), linkURL(String)

indent

public static final java.lang.String indent(java.lang.String string,
                                            int indentSize,
                                            boolean initialLine)
Indent a String with line-breaks.

Parameters:
string - String to indent.
indentSize - Number of spaces to indent by. 0 will indent using a tab.
initialLine - Whether to indent initial line.
Returns:
Indented string.

innerTrim

public static final java.lang.String innerTrim(java.lang.String s)
Returns a string that has whitespace removed from both ends of the String, as well as duplicate whitespace removed from within the String.


join

public static final java.lang.String join(java.lang.String glue,
                                          java.util.Iterator pieces)
Join an Iteration of Strings together.
Example
   // get Iterator of Strings ("abc","def","123");
   Iterator i = getIterator();
   out.print( TextUtils.join(", ",i) );
   // prints: "abc, def, 123"
 

Parameters:
glue - Token to place between Strings.
pieces - Iteration of Strings to join.
Returns:
String presentation of joined Strings.

join

public static final java.lang.String join(java.lang.String glue,
                                          java.lang.String[] pieces)
Join an array of Strings together.

Parameters:
glue - Token to place between Strings.
pieces - Array of Strings to join.
Returns:
String presentation of joined Strings.
See Also:
join(String, java.util.Iterator)

join

public static final java.lang.String join(java.lang.String glue,
                                          java.util.Collection pieces)
Join a Collection of Strings together.

Parameters:
glue - Token to place between Strings.
pieces - Collection of Strings to join.
Returns:
String presentation of joined Strings.
See Also:
join(String, java.util.Iterator)

leadingSpaces

public static final java.lang.String leadingSpaces(java.lang.String s)
Finds all leading spaces on each line and replaces it with an HTML space (&nbsp;)

Parameters:
s - string containing text to replaced with &nbsp;
Returns:
the new string

left

public static final java.lang.String left(java.lang.String s,
                                          int n)
Returns the leftmost n chars of the string. If n is larger than the length of the string, return the whole string unchanged.

Parameters:
s - - the string to operate on.
n - - the number of chars to return.

linkEmail

public static final java.lang.String linkEmail(java.lang.String str)
Wrap all email addresses in specified string with href tags.

Parameters:
str - The block of text to check.
Returns:
String The block of text with all email addresses placed in href tags.

linkURL

public static final java.lang.String linkURL(java.lang.String str)
Wrap all urls ('http://', 'www.', and 'ftp://') in specified string with href tags.

Parameters:
str - The block of text to check.
Returns:
String The block of text with all url's placed in href tags.

linkURL

public static final java.lang.String linkURL(java.lang.String str,
                                             java.lang.String target)
Wrap all urls ('abc://' and 'www.abc') in specified string with href tags.

Parameters:
str - The block of text to check.
target - The target to use for the href (optional).
Returns:
String The block of text with all url's placed in href tags.

list

public static final java.lang.String list(java.lang.String str)
Create
  • elements in a piece of plain text; Will convert lines starting with - or *. It might have been useful for the people writing earlier versions of this module's Javadocs. ;)

    Parameters:
    str - A string, possibly containing a plaintext "list"
    Returns:
    a converted string

  • noNull

    public static final java.lang.String noNull(java.lang.String string,
                                                java.lang.String defaultString)
    Return string, or defaultString if string is null or "". Never returns null.

    Examples:

     // prints "hello"
     String s=null;
     System.out.println(TextUtils.noNull(s,"hello");
    
     // prints "hello"
     s="";
     System.out.println(TextUtils.noNull(s,"hello");
    
     // prints "world"
     s="world";
     System.out.println(TextUtils.noNull(s, "hello");
     

    Parameters:
    string - the String to check.
    defaultString - The default string to return if string is null or ""
    Returns:
    string if string is non-empty, and defaultString otherwise
    See Also:
    stringSet(java.lang.String)

    noNull

    public static final java.lang.String noNull(java.lang.String string)
    Return string, or "" if string is null. Never returns null.

    Examples:

     // prints 0
     String s=null;
     System.out.println(TextUtils.noNull(s).length());
    
     // prints 1
     s="a";
     System.out.println(TextUtils.noNull(s).length());
     

    Parameters:
    string - the String to check
    Returns:
    a valid (non-null) string reference

    parseBoolean

    public static final boolean parseBoolean(java.lang.String in)
    Convert a String to an boolean. Accepts: 1/0, yes/no, true/false - case insensitive. If the value does not map to "true,", false is returned.

    Parameters:
    in - String to be parsed.
    Returns:
    boolean representation of String.

    parseDate

    public static final java.util.Date parseDate(java.lang.String year,
                                                 java.lang.String month,
                                                 java.lang.String day)
    Given 3 Strings representing the the year, month and day, return a Date object. This is only valid for Gregorian calendars.

    If the day cannot be determined, 1st will be used. If the month cannot be determined, Jan will be used.

    Parameters:
    year - Year : 4 digit
    month - Month : 1 or 2 digit (1=jan, 2=feb, ...) or name (jan, JAN, January, etc). If null, default is Jan.
    day - Day of month : 1 or 2 digit, prefix will be stripped (1, 30, 05, 3rd). If null, default is 1st.

    parseDouble

    public static final double parseDouble(java.lang.String in)
    Convert a String to a double.

    Parameters:
    in - String containing number to be parsed.
    Returns:
    Double value of number or 0 if error.
    See Also:
    extractNumber(String)

    parseFloat

    public static final float parseFloat(java.lang.String in)
    Convert a String to a float.

    Parameters:
    in - String containing number to be parsed.
    Returns:
    Float value of number or 0 if error.
    See Also:
    extractNumber(String)

    parseInt

    public static final int parseInt(java.lang.String in)
    Convert a String to an int. Truncates numbers if it's a float string; for example, 4.5 yields a value of 4.

    Parameters:
    in - String containing number to be parsed.
    Returns:
    Integer value of number or 0 if error.
    See Also:
    extractNumber(String)

    parseLong

    public static final long parseLong(java.lang.String in)
    Convert a String to a long. Truncates numbers if it's a float or double string; for example, 4.5 yields a value of 4.

    Parameters:
    in - String containing number to be parsed.
    Returns:
    Long value of number or 0 if error.
    See Also:
    extractNumber(String)

    plainTextToHtml

    public static final java.lang.String plainTextToHtml(java.lang.String str)
    Converts plain text to html code.

    Parameters:
    str - - String containing the plain text.
    Returns:
    the escaped string

    plainTextToHtml

    public static final java.lang.String plainTextToHtml(java.lang.String str,
                                                         java.lang.String target)
    Converts plain text to html code.

    Parameters:
    str - - String containing the plain text.
    target - - Target for href tags (optional).
    Returns:
    the escaped string

    removeAndInsert

    public static final java.lang.String removeAndInsert(java.lang.String str,
                                                         int removeAndInsertStart,
                                                         int removeEnd,
                                                         java.lang.String insertStr)
    Removes part of the original string starting at removeAndInsertStart and ending at removeEnd. Then insert another string at the same position where the part was removed (ie. at removeAndInsertStart).

    Parameters:
    str - - the original string.
    removeAndInsertStart - - the index within the original string at which removal is to start.
    removeEnd - - the index within the original string at which removal is to end (exclusive - ie. does not remove the character at that index).
    insertStr - - the string to be inserted.

    slashes

    public static final java.lang.String slashes(java.lang.String s)
    Escape chars that need slashes in front of them.

    Parameters:
    s - the String to add escape characters to
    Returns:
    the converted String

    stringSet

    public static final boolean stringSet(java.lang.String string)
    Check whether string has been set to something other than "" or null.

    Parameters:
    string - the String to check
    Returns:
    a boolean indicating whether the string was non-empty (and non-null)

    trimToEndingChar

    public static final java.lang.String trimToEndingChar(java.lang.String str,
                                                          int len)
    Trim a String to the specified length. However, if the cutoff point is in the middle of a sentence (remember that a String can contain many sentences), trim the string such that it ends with an ending char, which is defined in the isEndingChar() method.

    Parameters:
    str - - String to trim.
    len - - length to which string is to be trimmed.
    Returns:
    the trimmed string

    verifyEmail

    public static final boolean verifyEmail(java.lang.String email)
    Verify that the given string is a valid email address. "Validity" in this context only means that the address conforms to the correct syntax (not if the address actually exists).

    Parameters:
    email - The email address to verify.
    Returns:
    a boolean indicating whether the email address is correctly formatted.

    verifyUrl

    public static final boolean verifyUrl(java.lang.String url)
    Verify That the given String is in valid URL format.

    Parameters:
    url - The url string to verify.
    Returns:
    a boolean indicating whether the URL seems to be incorrect.

    wrapParagraph

    public static final java.lang.String wrapParagraph(java.lang.String s)
    Wrap paragraphs in html <p> tags. Paragraphs are seperated by blank lines.

    Parameters:
    s - the String to reformat
    Returns:
    the reformatted string

    See www.opensymphony.com for more information.