org.objectledge.utils
Class StringUtils

java.lang.Object
  extended by org.objectledge.utils.StringUtils

public class StringUtils
extends Object

This class contains various functions for manipulating Java Strings.

Version:
$Id: StringUtils.java,v 1.42 2006/06/30 12:07:29 zwierzem Exp $
Author:
Damian Gajda, Rafal Krzewski, Pawel Potempski

Nested Class Summary
private static class StringUtils.ByteSizeState
           
private static class StringUtils.CountOutputStream
          Helper class to count the string length.
 
Field Summary
static String UTF_8_ENCODING
           
 
Constructor Summary
private StringUtils()
          A private constructor to prevent instantiation of this static method only class.
 
Method Summary
static String backslashEscape(String in, String reserved)
          Backslash escape reserved characters in a string.
static String basePath(String path)
          Returns the base name of a file.
static String bytesSize(long value, int precision)
          Format size value in B, kB, MB, for example 15kB or 23.5MB.
static String capitalize(String str)
          Capitalize given string by transforming the first character to upper case.
static String cookieNameSafeString(String input)
          Prepares a given String to be used as a HTTP cookie name.
static String cookieNameSafeString(String input, char replaceChar)
          Prepares a given String to be used as a HTTP cookie name.
private static void cutDigits(int precision, StringBuilder b)
           
static String directoryPath(String path)
          Returns hte directory name of a file.
static String escapeNonASCIICharacters(String s)
          Escapes characters outside the US-ASCII range as Java unicode scapes (F;uxxxx where x is a hexadecimal digit).
static String escapeXMLCharacters(String string)
          Escapes xml characters.
static String expand(String s, Map t)
          Expand macros in a string.
static String expandUnicodeEscapes(String s)
          Expand unicode escapes.
static String fillString(String input, int total, char filling)
          Fill the string to the expected length with the specified filling character.
static String formatInterval(long interval)
          Returns human readable representation of interval value in days, hours etc.
static String formatMilliIntervalAsSeconds(long interval)
          Format a millisecond interval as number of seconds (with fracitonal part).
static String formatRate(double events, double time, String event)
          Renders a human readable event rate esitmation.
static String fromUTF8(byte[] bytes)
          Convert from UTF-8 bytes to a String.
static int getByteCount(String string, String encoding)
          Determines the number of bytes the string will ocuppy in a specifc character encoding.
static Locale getLocale(String name)
          Build a locale from string.
static String htmlLineBreaks(String s)
          Convert newlines in the string into <br/> tags.
static StringBuilder indent(StringBuilder buffer, int d)
          Appends the specified number of space charcter to a string buffer and returns it.
static boolean isEmpty(String str)
          Checks if a given string is null or empty.
static String join(Set<String> strings, String separator)
          Joins a set of strings comobinig them usign a given separator.
static String justify(List<String> strings, int w)
          Justifies a list of strings.
static String normalizedPath(String path)
          Normalizes a pathname.
static long parseBytesSize(String value)
          Parse a size value given as a number with B, kB, MB suffix, for example 15kB or 23.5MB.
static String[] pop(String[] values, int n)
          Remove strings from the end of a string array.
static String[] push(String[] values, String... additional)
          Append strings to the end of a string array.
static String relativePath(String path, String base)
          Returns the relative pathname of a file with respect to given base directory.
static String shortenString(String source, int minLength, int maxLength, String suffix)
          Shorten the string to the specifed lenght.
static Set<String> split(String in, String separator)
          Splits the string by the given separator and returns results as a set of strings.
static String substitute(String template, String[] values)
          Performs variable substitution on a template string.
static String toOctalUnicode(String input)
          Creates ascii based unicode representation of the string.
static byte[] toUTF8(String string)
          Convert from a String to UTF-8 bytes.
static String wrap(String in, int width)
          Wrap the text to the specified number of columns.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

UTF_8_ENCODING

public static final String UTF_8_ENCODING
See Also:
Constant Field Values
Constructor Detail

StringUtils

private StringUtils()
A private constructor to prevent instantiation of this static method only class.

Method Detail

cookieNameSafeString

public static String cookieNameSafeString(String input)
Prepares a given String to be used as a HTTP cookie name.

Parameters:
input - Cookie name unsafe string.
Returns:
a modified string.
See Also:
cookieNameSafeString(String, char)

cookieNameSafeString

public static String cookieNameSafeString(String input,
                                          char replaceChar)
Prepares a given String to be used as a HTTP cookie name.

It replaces characters used in cookies (exactly ; semicolon, , comma, = equals, $ and whitespace) with a given character. If this character is equal to any of the unsafe characters . dot is used.

Parameters:
input - Cookie name unsafe string.
replaceChar - Character to be used as a replacement for unsafe characters.
Returns:
a modified string.

backslashEscape

public static String backslashEscape(String in,
                                     String reserved)
Backslash escape reserved characters in a string.

Parameters:
in - the string to process.
reserved - the reserved characters.
Returns:
the string reserved characters escaped.

escapeNonASCIICharacters

public static String escapeNonASCIICharacters(String s)
Escapes characters outside the US-ASCII range as Java unicode scapes (F;uxxxx where x is a hexadecimal digit).

Parameters:
s - the string to process.
Returns:
processed string.

expandUnicodeEscapes

public static String expandUnicodeEscapes(String s)
                                   throws IllegalArgumentException
Expand unicode escapes.

Parameters:
s - the string to process.
Returns:
processed string.
Throws:
IllegalArgumentException - if the string contains invalid unicode escapes.

substitute

public static String substitute(String template,
                                String[] values)
Performs variable substitution on a template string.

The variables are formed of the dollar sign followed by a digit, ranging from 1 to 9. Special variable formed of the dollar singn followed by an asterisk is substitued with the remaining values separated by commas. Dollar sign followed by another dollar sign expands to single dollar sign. If there are not enough values provided, undefined variables will be substitutes with empty strings. Examples:

templatevaluesresult
$1 rules{"ziu"}ziu rules
$1 said "$2"{"Fred","Foo!"}Fred said "Foo!"
"$2" said $1{"Fred","Foo!"}"Foo!" said Fred
$1 likes the following colors: $*{"Mike","blue","grey","cyan"} Mike likes the following colors: blue, grey, cyan
$1 likes the following $2: $*{"Mike","food","pizza","french fries"}Mike likes the following food: pizza, french fries

Parameters:
template - the template string.
values - the values of the variables.
Returns:
the output string.

getLocale

public static Locale getLocale(String name)
Build a locale from string.

Parameters:
name - a string representation of a locale
Returns:
a Locale object

getByteCount

public static int getByteCount(String string,
                               String encoding)
                        throws IOException
Determines the number of bytes the string will ocuppy in a specifc character encoding.

Parameters:
string - the string.
encoding - the requested encoding.
Returns:
the size of the string.
Throws:
IOException - if happens.

indent

public static StringBuilder indent(StringBuilder buffer,
                                   int d)
Appends the specified number of space charcter to a string buffer and returns it.

Parameters:
buffer - the buffer.
d - number of spaces.
Returns:
the buffer.

fillString

public static String fillString(String input,
                                int total,
                                char filling)
Fill the string to the expected length with the specified filling character. Filling charaters will be added at the beginning of this input string.

Parameters:
input - the input string.
total - the expected length of result string.
filling - the filling character.
Returns:
the result string.

toOctalUnicode

public static String toOctalUnicode(String input)
Creates ascii based unicode representation of the string. Each unicode character of the input will be tranformed to 8 ascii characters in the following format: "\"<octal lower byte>"\"<octal higher byte> i.e. the output string looks as follows: "\124\000\102\001\165\000\155\000".

Parameters:
input - the input string.
Returns:
the output.

wrap

public static String wrap(String in,
                          int width)
Wrap the text to the specified number of columns.

The input string is expected to be a series of lines of text delimeted by \n characters. The output string contains the text reformatted in such way that each line is at most width characters wide. For each line of input text that is longer than the limit, last whitespace character before the limit is searched, and is replaced by a newline. Any whitespace characters immediately following that character are discarded. If the input text contains a sequence of non-whitespace characters longer than the specified limit, the sequence will be broken by newlines to fit in the limit.

Parameters:
in - the text to format.
width - the width of the output text.
Returns:
wrapped text.

justify

public static String justify(List<String> strings,
                             int w)
Justifies a list of strings.

Parameters:
strings - the strings.
w - the width of the text column.

shortenString

public static String shortenString(String source,
                                   int minLength,
                                   int maxLength,
                                   String suffix)
Shorten the string to the specifed lenght.

If the string is shorter than the maxLength limit it is returned intact. If the string is longer,it will be truncated and the suffix will be added. If truncation is necessary, the preferred truncation point is the last punctuation character before the limit, unless it occurs later than minLength in the string. In this case the prefferred truncation point is the last whitespace before the maxLength limit unless it occurs later than minLength. At last resort, the string is truncated at maxLenght limit.

Parameters:
source - the string to process.
minLength - minimum length of the shortened string.
maxLength - maximum length limit.
suffix - suffix to add if the string is actually shortened. Should be " ..." or " …" (using Unicode horizontal ellipsis glyph).
Returns:
shortened string.

normalizedPath

public static String normalizedPath(String path)
                             throws IllegalArgumentException
Normalizes a pathname.

This method removes redundant / characters, removes . and .. path elements, taking care that the paths dont reach outside filesystem root, removes trailing / from directories and adding leading / as neccessary.

Parameters:
path - the path.
Returns:
normalized path.
Throws:
IllegalArgumentException - if the path reaches outside the filesystem root.

basePath

public static String basePath(String path)
Returns the base name of a file.

This method returns the contents of the pathname after the last '/' character.

Parameters:
path - the pathname of the file.
Returns:
the basename of the file.

directoryPath

public static String directoryPath(String path)
Returns hte directory name of a file.

This method returns the normalized path before the last '/' character in the path.

Parameters:
path - the pathname of the file.
Returns:
the directory name of the file.

relativePath

public static String relativePath(String path,
                                  String base)
                           throws IllegalArgumentException
Returns the relative pathname of a file with respect to given base directory.

Parameters:
path - the pathname of a file.
base - the base pathname.
Returns:
the relative pathname.
Throws:
IllegalArgumentException - if the file is contained outside of base.

expand

public static String expand(String s,
                            Map t)
Expand macros in a string.

Parameters:
s - the String to process.
t - the macros (token -> value)
Returns:
an expanded String

escapeXMLCharacters

public static String escapeXMLCharacters(String string)
Escapes xml characters.

Parameters:
string - a string to escape
Returns:
the processed string.

htmlLineBreaks

public static String htmlLineBreaks(String s)
Convert newlines in the string into <br/> tags.

Parameters:
s - the string to process.
Returns:
processed string.

formatInterval

public static String formatInterval(long interval)
Returns human readable representation of interval value in days, hours etc.

Parameters:
interval - in seconds.
Returns:
human readable interval specification.

formatMilliIntervalAsSeconds

public static String formatMilliIntervalAsSeconds(long interval)
Format a millisecond interval as number of seconds (with fracitonal part).

Parameters:
interval - interval in milliseconds.
Returns:
interval as number of seconds (with fracitonal part).

formatRate

public static String formatRate(double events,
                                double time,
                                String event)
Renders a human readable event rate esitmation.

Parameters:
events - number of events.
time - timespan in seconds.
event - event name.
Returns:
a human readable event rate esitmation.

isEmpty

public static boolean isEmpty(String str)
Checks if a given string is null or empty.

Parameters:
str - string to be checked.
Returns:
true if the string is null or empty.

capitalize

public static String capitalize(String str)
Capitalize given string by transforming the first character to upper case.

Parameters:
str - the string.
Returns:
the capitalized string.

fromUTF8

public static String fromUTF8(byte[] bytes)
Convert from UTF-8 bytes to a String.

Parameters:
bytes - UTF-8 bytes.
Returns:
a String.

toUTF8

public static byte[] toUTF8(String string)
Convert from a String to UTF-8 bytes.

Parameters:
string - String.
Returns:
UTF-8 bytes.

push

public static String[] push(String[] values,
                            String... additional)
Append strings to the end of a string array.

Parameters:
values - original array.
additional - strings to be added.
Returns:
new array containg combined values.

pop

public static String[] pop(String[] values,
                           int n)
Remove strings from the end of a string array.

Parameters:
values - original array.
n - the number of strings to be removed.
Returns:
new array containt smallr number of values.

split

public static Set<String> split(String in,
                                String separator)
Splits the string by the given separator and returns results as a set of strings. The set is ordered (LinkedHashSet).

Parameters:
in - the input string
separator - the delimiter
Returns:
the set of strings.

join

public static String join(Set<String> strings,
                          String separator)
Joins a set of strings comobinig them usign a given separator.

Parameters:
strings - the input set of strings.
separator - the joining string.
Returns:
the resulting string.

bytesSize

public static String bytesSize(long value,
                               int precision)
Format size value in B, kB, MB, for example 15kB or 23.5MB.

Parameters:
value - the size in bytes.
precision - number of digits in decimal fraction.
Returns:
the size as string with a proper unit suffix.

cutDigits

private static void cutDigits(int precision,
                              StringBuilder b)

parseBytesSize

public static long parseBytesSize(String value)
Parse a size value given as a number with B, kB, MB suffix, for example 15kB or 23.5MB.

Parameters:
value - the size as string with a proper unit suffix.
Returns:
the size in bytes.


Copyright © 2003-2006 objectledge.org. All Rights Reserved.