Project Wonder 5.0

er.extensions.foundation
Class ERXStringUtilities

java.lang.Object
  extended by er.extensions.foundation.ERXStringUtilities

public class ERXStringUtilities
extends java.lang.Object

Collection of String utilities. Contains the base localization support.


Field Summary
protected static double adjustement
          holds the base adjustment for fuzzy matching
static char[] HEX_CHARS
          Holds the chars for hex encoding
static com.webobjects.foundation.NSDictionary HTML_SAFE_UNESCAPES
          Safe HTML entities to unescape (SYMBOL+ISO).
static com.webobjects.foundation.NSDictionary HTML_UNESCAPES
          HTML entities to unescape (XML+SYMBOL+ISO).
static com.webobjects.foundation.NSDictionary ISO_UNESCAPES
          ISO entities to unescape.
static com.webobjects.foundation.NSArray SORT_ASCENDING
          Holds the ascending EOSortOrderings
static com.webobjects.foundation.NSArray SORT_DESCENDING
          Holds the ascending EOSortOrderings
static java.lang.String SpecialRegexCharacters
          Holds characters that have special meaning for regex
static com.webobjects.foundation.NSDictionary SYMBOL_UNESCAPES
          Symbol entities to unescape.
static com.webobjects.foundation.NSDictionary XML_UNESCAPES
          XML entities to unescape.
 
Constructor Summary
ERXStringUtilities()
           
 
Method Summary
static void appendSeparatorIfLastNot(char separator, char not, java.lang.StringBuffer sb)
          Utility method to append a character to a StringBuffer if the last character is not a certain character.
static java.lang.Object attributeCustomValueFromString(com.webobjects.eoaccess.EOAttribute attr, java.lang.String strVal, java.lang.String encoding)
          Attempts to convert string values for attributes into the appropriate value class for the attribute.
static java.lang.Number attributeNumberValueFromString(com.webobjects.eoaccess.EOAttribute attr, java.lang.String strVal)
          Attempts to convert string values for attributes into the appropriate value class for the attribute.
static java.lang.Object attributeValueFromString(com.webobjects.eoaccess.EOAttribute attr, java.lang.String strVal, java.lang.String encoding, java.text.Format formatter)
          Attempts to convert string values for attributes into the appropriate value class for the attribute.
static java.lang.String byteArrayToHexString(byte[] block)
          Converts a byte array to hex string.
static java.lang.String camelCaseToUnderscore(java.lang.String camelString, boolean lowercase)
          Converts ThisIsATest to this_is_a_test
static java.lang.String capitalize(java.lang.String value)
          Capitalizes a given string.
static java.lang.String capitalizeAllWords(java.lang.String value)
          Capitalizes all the strings in a given string.
static boolean caseInsensitiveStartsWith(java.lang.String stringToSearch, java.lang.String prefix)
          Tests if the string starts with the specified prefix ignoring case.
static boolean caseInsensitiveStartsWith(java.lang.String stringToSearch, java.lang.String prefix, int toffset)
          Tests if the string starts with the specified prefix starting at the specified index ignoring case.
static boolean containsAnyCharacter(java.lang.String source, java.lang.String characters)
          Checks if any of the characters specified in characters is contained in the string specified by source.
static java.lang.String displayNameForKey(java.lang.String key)
          Calculates a default display name for a given key path.
static double distance(java.lang.String a, java.lang.String b)
          Java port of the distance algorithm.
static java.lang.String dumpObject(java.lang.Object object)
          creates a readable debug string for some data types (dicts, arrays, adaptorOperations, databaseOperations)
static java.lang.String emptyStringForNull(java.lang.String s)
          Simple utility method that will return the string "" if the string passed in is null otherwise it will return the passed in string.
static java.lang.String escape(char[] _escapeChars, char _escapeWith, java.lang.String _sourceString)
          Escapes the given characters with the given escape character in _sourceString.
static java.lang.String escapeJavascriptApostrophes(java.lang.String sourceString)
          Escapes the apostrophes in a Javascript string with a backslash.
static java.lang.String escapeNonBasicLatinChars(char c)
           
static java.lang.String escapeNonBasicLatinChars(java.lang.String str)
           
static java.lang.String escapeNonXMLChars(java.lang.String str)
           
static java.lang.String escapePCData(java.lang.String pcdata)
          Escapes the given PCDATA string as CDATA.
static java.lang.String escapeSpace(java.lang.String aString)
          Removes the spaces in a given String
static java.lang.String excelSafeCsvString(java.lang.String s)
          Removes line breaks and quotes the string if neccessary
static java.lang.String firstPropertyKeyInKeyPath(java.lang.String keyPath)
           
static java.lang.String fromBytes(byte[] bytes, java.lang.String encoding)
          Utility to convert from bytes without the try/catch.
static java.lang.String fromUTF8Bytes(byte[] bytes)
          Utility to convert from UTF-8 bytes without the try/catch.
static com.webobjects.foundation.NSArray fuzzyMatch(java.lang.String name, java.lang.String entityName, java.lang.String propertyKey, java.lang.String synonymsKey, com.webobjects.eocontrol.EOEditingContext ec, ERXFuzzyMatchCleaner cleaner, com.webobjects.foundation.NSArray sortOrderings)
          Fuzzy matching is useful for catching user entered typos.
static com.webobjects.foundation.NSArray fuzzyMatch(java.lang.String name, java.lang.String entityName, java.lang.String propertyKey, java.lang.String synonymsKey, com.webobjects.eocontrol.EOEditingContext ec, ERXFuzzyMatchCleaner cleaner, java.lang.String comparisonString)
          Deprecated. use fuzzyMatch(String name, String entityName, String propertyKey, String synonymsKey, EOEditingContext ec, ERXFuzzyMatchCleaner cleaner, NSArray sortOrderings ) instead
static java.lang.String getSimpleClassName(java.lang.Class clazz)
          "Borrowed" from 1.5's Class.getSimpleClassName
static byte[] hexStringToByteArray(java.lang.String hexString)
          Converts a even-length, hex-encoded String to a byte array.
static void indent(java.io.PrintWriter writer, int level)
           
static void indent(java.lang.StringBuffer sb, int level)
           
static int indexOfNumericInString(java.lang.String str)
          Locate the the first numeric character in the given string.
static int indexOfNumericInString(java.lang.String str, int fromIndex)
          Locate the the first numeric character after fromIndex in the given string.
static java.lang.String insertString(java.lang.String destinationString, java.lang.String contentToInsert, int insertOffset)
          Inserts the a string into a nother string at a particular offset.
static java.lang.Integer integerWithString(java.lang.String s)
          Calculates an Integer for a given string.
static boolean isDigitsOnly(java.lang.String aString)
          checks if the specified String contains only digits.
static boolean isLettersOnly(java.lang.String aString)
          checks if the specified String contains only Letters.
static boolean isValueInRange(int value, java.lang.String rangeString)
          Returns whether the given value falls in a range defined by the given string, which is in the format "1-5,100,500,800-1000".
static java.lang.String keyPathWithoutFirstProperty(java.lang.String keyPath)
           
static java.lang.String keyPathWithoutLastProperty(java.lang.String keyPath)
           
static java.lang.String lastPropertyKeyInKeyPath(java.lang.String keyPath)
           
static java.lang.String leftPad(java.lang.String string, char padChar, int paddedLength)
          Pads a string to the specified number of chars by adding the the given pad char on the left side.
static java.lang.String localizedStringForKey(java.lang.String key)
          Gets a localized string for a given key in the application's Localizable strings file for the default language (English).
static java.lang.String localizedStringForKey(java.lang.String key, java.lang.String framework)
          Gets a localized string for a given key in a given framework's Localizable strings file for the default language (English).
static java.lang.String localizedStringForKey(java.lang.String key, java.lang.String framework, com.webobjects.foundation.NSArray languages)
          Gets a localized string for a given key in a given framework's Localizable strings file using the array of languages as the search order for the key.
static java.lang.String localizedTemplateStringWithObjectForKey(java.lang.Object o, java.lang.String key, java.lang.String framework, com.webobjects.foundation.NSArray languages)
          Uses the method localizedStringForKey to retreive a template that is then parsed using the passed in object to produce a resulting string.
static java.lang.String maskStringWithCharacter(java.lang.String arg, char mask, int beginIndex, int endIndex)
          Masks a given string with a single character in the substring specified by the begin and end indexes.
static java.lang.String matchCase(java.lang.String originalString, java.lang.String newString)
          Returns a string case-matched against the original string.
static byte[] md5(java.lang.String str, java.lang.String encoding)
          Generate an MD5 hash from a String.
static java.lang.String md5Hex(java.lang.String str, java.lang.String encoding)
          Generate an MD5 hash as hex from a String.
static java.lang.String nullForEmptyString(java.lang.String s)
          Simple utility method that will return null if the string passed in is equal to "" otherwise it will return the passed in string.
static int numberOfOccurrencesOfCharInString(char c, java.lang.String s)
          Counts the number of occurrences of a particular char in a given string.
static boolean quicksilverContains(java.lang.String _str, java.lang.String _searchString)
          Matches strings like Quicksilver (NullPointerException is matched by "NPE").
static java.lang.String quote(java.lang.String s, java.lang.String quoteSymbol)
          Quote the given string with the provided quote symbols
static boolean regionMatches(java.lang.StringBuffer str, int toffset, java.lang.String other, int ooffset, int len)
          It's ridiculous that StringBuffer doesn't have a .regionMatches like String.
static java.lang.String removeCharacters(java.lang.String source, java.lang.String characters)
          removes any character which is in characters from the source string
static java.lang.String removeExceptCharacters(java.lang.String source, java.lang.String characters)
          removes any character which is not in characters from the source string
static java.lang.String removeExtraDotsFromVersionString(java.lang.String version)
          Cleans up the given version string by removing extra dots(.), for example, 5.1.3 becomes 5.13, so that the string can be converted to a double or BigDecimal type easily.
static java.lang.String replaceStringByStringInString(java.lang.String old, java.lang.String newString, java.lang.String buffer)
          Replaces a given string by another string in a string.
static java.lang.String rightPad(java.lang.String string, char padChar, int paddedLength)
          Pads a string to the specified number of chars by adding the the given pad char on the right side.
static java.lang.String safeIdentifierName(java.lang.String source)
          Convenience method to call safeIdentifierName(source, "_", '_')
static java.lang.String safeIdentifierName(java.lang.String source, java.lang.String prefix)
          Convenience method to call safeIdentifierName(source, prefix, '_')
static java.lang.String safeIdentifierName(java.lang.String source, java.lang.String prefix, char replacement)
          Converts source to be suitable for use as an identifier in JavaScript.
static void setAdjustement(double newAdjustement)
          Sets the base adjustment used for fuzzy matching
static java.lang.String stringByAppendingCSSClass(java.lang.String originalString, java.lang.String cssClass)
          Appends a CSS class to an existing (possibly null) CSS class string.
static java.lang.String stringByReplacingFirstOccurrenceOfStringWithString(java.lang.String sourceString, java.lang.String stringToReplace, java.lang.String replacementString)
          Replaces the first occurrence of a string with another string in a string.
static java.lang.String stringByTruncatingStringToByteLengthInEncoding(java.lang.String inputString, int byteLength, java.lang.String encoding)
          This method takes a string and returns a string which is the first string such that the result byte length in the specified encoding does not exceed the byte limit.
static boolean stringContainsSpecialRegexCharacters(java.lang.String s)
          checks if the String contains a character that has a special meaning in regex.
static boolean stringEqualsString(java.lang.String s1, java.lang.String s2)
           
static java.lang.String stringFromDictionary(com.webobjects.foundation.NSDictionary dict)
          Same as NSPropertySerialization except it sorts on keys first.
static java.lang.String stringFromInputStream(java.io.InputStream in)
          Returns a string from the input stream using the default encoding.
static java.lang.String stringFromInputStream(java.io.InputStream in, java.lang.String encoding)
          Returns a string from the input stream using the default encoding.
static java.lang.String stringFromResource(java.lang.String name, java.lang.String extension, com.webobjects.foundation.NSBundle bundle)
          Retrives a given string for a given name, extension and bundle.
static java.lang.String stringFromURL(java.net.URL url)
          Returns a string from the contents of the given URL.
static java.lang.String stringFromURL(java.net.URL url, java.lang.String encoding)
          Returns a string from the contents of the given URL.
static boolean stringIsNullOrEmpty(java.lang.String s)
          Simple test if the string is either null or equal to "".
static java.lang.String stringWithContentsOfFile(java.io.File file)
          Reads the contents of a file given by a path into a string.
static java.lang.String stringWithContentsOfFile(java.lang.String path)
          Reads the contents of a file given by a path into a string.
static java.lang.String stringWithNtimesString(int n, java.lang.String s)
          String multiplication.
static java.lang.String stripHtml(java.lang.String str)
          Removes HTML characters from the given string.
static byte[] toBytes(java.lang.String string, java.lang.String encoding)
          Utility to convert to bytes without the try/catch.
static java.lang.String toHexString(char c)
           
static java.lang.String toHexString(java.lang.String str)
           
static java.lang.String toLowerCase(java.lang.String str)
          This method runs about 20 times faster than java.lang.String.toLowerCase (and doesn't waste any storage when the result is equal to the input).
static java.lang.String toString(java.lang.Object[] array, java.lang.String separator)
          Returns a String by invoking toString() on each object from the array.
static byte[] toUTF8Bytes(java.lang.String string)
          Utility to convert to UTF-8 bytes without the try/catch.
static java.lang.String trimString(java.lang.String s)
          Null-safe wrapper for java.lang.String.trim
static java.lang.String uncapitalize(java.lang.String value)
          Uncapitalizes a given string.
static java.lang.String underscoreToCamelCase(java.lang.String underscoreString, boolean capitalize)
          Converts this_is_a_test to ThisIsATest
static java.lang.String unescapeEntities(java.lang.String string, java.util.Map<java.lang.String,java.lang.String> map)
          Util to unescape entities.
static java.lang.String unquote(java.lang.String s, java.lang.String quoteSymbol)
          Remove the quote symbols from the given string
static java.lang.String urlDecode(java.lang.String string)
          Utility to decode an URL without the try/catch.
static java.lang.String urlEncode(java.lang.String string)
          Utility to encode an URL without the try/catch.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

HEX_CHARS

public static final char[] HEX_CHARS
Holds the chars for hex encoding


SORT_ASCENDING

public static final com.webobjects.foundation.NSArray SORT_ASCENDING
Holds the ascending EOSortOrderings


SORT_DESCENDING

public static final com.webobjects.foundation.NSArray SORT_DESCENDING
Holds the ascending EOSortOrderings


SpecialRegexCharacters

public static final java.lang.String SpecialRegexCharacters
Holds characters that have special meaning for regex

See Also:
Constant Field Values

adjustement

protected static double adjustement
holds the base adjustment for fuzzy matching


XML_UNESCAPES

public static final com.webobjects.foundation.NSDictionary XML_UNESCAPES
XML entities to unescape.


ISO_UNESCAPES

public static final com.webobjects.foundation.NSDictionary ISO_UNESCAPES
ISO entities to unescape.


SYMBOL_UNESCAPES

public static final com.webobjects.foundation.NSDictionary SYMBOL_UNESCAPES
Symbol entities to unescape.


HTML_SAFE_UNESCAPES

public static final com.webobjects.foundation.NSDictionary HTML_SAFE_UNESCAPES
Safe HTML entities to unescape (SYMBOL+ISO). This still prevents injection attacks.


HTML_UNESCAPES

public static final com.webobjects.foundation.NSDictionary HTML_UNESCAPES
HTML entities to unescape (XML+SYMBOL+ISO).

Constructor Detail

ERXStringUtilities

public ERXStringUtilities()
Method Detail

distance

public static double distance(java.lang.String a,
                              java.lang.String b)
Java port of the distance algorithm. The code below comes from the following post on http://mail.python.org Fuzzy string matching Magnus L. Hetland mlh@idt.ntnu.no 27 Aug 1999 15:51:03 +0200 Explanation of the distance algorithm... The algorithm: def distance(a,b): c = {} n = len(a); m = len(b) for i in range(0,n+1): c[i,0] = i for j in range(0,m+1): c[0,j] = j for i in range(1,n+1): for j in range(1,m+1): x = c[i-1,j]+1 y = c[i,j-1]+1 if a[i-1] == b[j-1]: z = c[i-1,j-1] else: z = c[i-1,j-1]+1 c[i,j] = min(x,y,z) return c[n,m] It calculates the following: Given two strings, a and b, and three operations, adding, subtracting and exchanging single characters, what is the minimal number of steps needed to translate a into b? The method is based on the following idea: We want to find the distance between a[:x] and b[:y]. To do this, we first calculate 1) the distance between a[:x-1] and b[:y], adding the cost of a subtract-operation, used to get from a[:x] to a[:z-1]; 2) the distance between a[:x] and b[:y-1], adding the cost of an addition-operation, used to get from b[:y-1] to b[:y]; 3) the distance between a[:x-1] and b[:y-1], adding the cost of a *possible* exchange of the letter b[y] (with a[x]). The cost of the subtraction and addition operations are 1, while the exchange operation has a cost of 1 if a[x] and b[y] are different, and 0 otherwise. After calculating these costs, we choose the least one of them (since we want to use the best solution.) Instead of doing this recursively, i.e. calculating ourselves "back" from the final value, we build a cost-matrix c containing the optimal costs, so we can reuse them when calculating the later values. The costs c[i,0] (from string of length n to empty string) are all i, and correspondingly all c[0,j] (from empty string to string of length j) are j. Finally, the cost of translating between the full strings a and b (c[n,m]) is returned. I guess that ought to cover it... --------------------------

Parameters:
a - first string
b - second string
Returns:
the distance between the two strings

setAdjustement

public static void setAdjustement(double newAdjustement)
Sets the base adjustment used for fuzzy matching

Parameters:
newAdjustement - factor to be used.

fuzzyMatch

public static com.webobjects.foundation.NSArray fuzzyMatch(java.lang.String name,
                                                           java.lang.String entityName,
                                                           java.lang.String propertyKey,
                                                           java.lang.String synonymsKey,
                                                           com.webobjects.eocontrol.EOEditingContext ec,
                                                           ERXFuzzyMatchCleaner cleaner,
                                                           com.webobjects.foundation.NSArray sortOrderings)
Fuzzy matching is useful for catching user entered typos. For example if a user is search for a company named 'Aple' within your application they aren't going to find it. Thus the idea of fuzzy matching, meaning you can define a threshold of 'how close can they be' type of thing.

Parameters:
name - to be matched against
entityName - name of the entity to perform the match against.
propertyKey - to be matched against
synonymsKey - allows objects to have additional values to be matched against in addition to just the value of the propertyKey
ec - context to fetch data in
cleaner - object used to clean a string, for example the cleaner might strip out the words 'The' and 'Inc.'
sortOrderings - can be either SORT_ASCENDING or SORT_DESCENDING to tell how the results should be sorted.
Returns:
an array of objects that match in a fuzzy manner the name passed in.

fuzzyMatch

public static com.webobjects.foundation.NSArray fuzzyMatch(java.lang.String name,
                                                           java.lang.String entityName,
                                                           java.lang.String propertyKey,
                                                           java.lang.String synonymsKey,
                                                           com.webobjects.eocontrol.EOEditingContext ec,
                                                           ERXFuzzyMatchCleaner cleaner,
                                                           java.lang.String comparisonString)
Deprecated. use fuzzyMatch(String name, String entityName, String propertyKey, String synonymsKey, EOEditingContext ec, ERXFuzzyMatchCleaner cleaner, NSArray sortOrderings ) instead


localizedStringForKey

public static java.lang.String localizedStringForKey(java.lang.String key)
Gets a localized string for a given key in the application's Localizable strings file for the default language (English).

Parameters:
key - to be lookup in the strings file
Returns:
string value of the looked up key

localizedStringForKey

public static java.lang.String localizedStringForKey(java.lang.String key,
                                                     java.lang.String framework)
Gets a localized string for a given key in a given framework's Localizable strings file for the default language (English).

Parameters:
key - to be lookup in the strings file
framework - name, specify app or null to perform the lookup in the application's resources.
Returns:
string value of the looked up key

localizedStringForKey

public static java.lang.String localizedStringForKey(java.lang.String key,
                                                     java.lang.String framework,
                                                     com.webobjects.foundation.NSArray languages)
Gets a localized string for a given key in a given framework's Localizable strings file using the array of languages as the search order for the key.

Parameters:
key - to be lookup in the strings file
framework - name, specify app or null to perform the lookup in the application's resources.
languages - array to search for the key in
Returns:
string value of the looked up key

localizedTemplateStringWithObjectForKey

public static java.lang.String localizedTemplateStringWithObjectForKey(java.lang.Object o,
                                                                       java.lang.String key,
                                                                       java.lang.String framework,
                                                                       com.webobjects.foundation.NSArray languages)
Uses the method localizedStringForKey to retreive a template that is then parsed using the passed in object to produce a resulting string. The template parser used is ERXSimpleTemplateParser.

Parameters:
o - object used to resolve keys in the localized template
key - to be lookup in the strings file
framework - name, specify app or null to perform the lookup in the application's resources.
languages - array to search for the key in
Returns:
localized template parsed and resolved with the given object.

stringWithContentsOfFile

public static java.lang.String stringWithContentsOfFile(java.io.File file)
Reads the contents of a file given by a path into a string.

Parameters:
file - path to the file in the file system
Returns:
the contents of the file in a string

stringWithContentsOfFile

public static java.lang.String stringWithContentsOfFile(java.lang.String path)
Reads the contents of a file given by a path into a string.

Parameters:
path - to the file in the file system
Returns:
the contents of the file in a string

integerWithString

public static java.lang.Integer integerWithString(java.lang.String s)
Calculates an Integer for a given string. The only advantage that this method has is to not throw a number format exception if the string is not correctly formatted. This method makes use of the ERXConstant.integerForString caching logic.

Parameters:
s - string to caclulate an Integer from
Returns:
parsed Integer from the string or null if the string is not correctly formed.
See Also:
ERXConstant#integerForString(String)

stringFromResource

public static java.lang.String stringFromResource(java.lang.String name,
                                                  java.lang.String extension,
                                                  com.webobjects.foundation.NSBundle bundle)
Retrives a given string for a given name, extension and bundle.

Parameters:
name - of the resource
extension - of the resource, example: txt or rtf
bundle - to look for the resource in
Returns:
string of the given file specified in the bundle

firstPropertyKeyInKeyPath

public static final java.lang.String firstPropertyKeyInKeyPath(java.lang.String keyPath)

lastPropertyKeyInKeyPath

public static final java.lang.String lastPropertyKeyInKeyPath(java.lang.String keyPath)

keyPathWithoutLastProperty

public static final java.lang.String keyPathWithoutLastProperty(java.lang.String keyPath)

keyPathWithoutFirstProperty

public static final java.lang.String keyPathWithoutFirstProperty(java.lang.String keyPath)

displayNameForKey

public static java.lang.String displayNameForKey(java.lang.String key)
Calculates a default display name for a given key path. For instance for the key path: "foo.bar" the display name would be "Bar".

Parameters:
key - to calculate the display name
Returns:
display name for the given key

indexOfNumericInString

public static int indexOfNumericInString(java.lang.String str)
Locate the the first numeric character in the given string.

Parameters:
str - string to scan
Returns:
position in int. -1 for not found.

indexOfNumericInString

public static int indexOfNumericInString(java.lang.String str,
                                         int fromIndex)
Locate the the first numeric character after fromIndex in the given string.

Parameters:
str - string to scan
Returns:
position in int. -1 for not found.

appendSeparatorIfLastNot

public static void appendSeparatorIfLastNot(char separator,
                                            char not,
                                            java.lang.StringBuffer sb)
Utility method to append a character to a StringBuffer if the last character is not a certain character. Useful for determining if you need to add an '&' to the end of a form value string.

Parameters:
separator - character to add to potentially add to the StringBuffer.
not - character to test if the given StringBuffer ends in it.
sb - StringBuffer to test and potentially append to.

replaceStringByStringInString

public static java.lang.String replaceStringByStringInString(java.lang.String old,
                                                             java.lang.String newString,
                                                             java.lang.String buffer)
Replaces a given string by another string in a string.

Parameters:
old - string to be replaced
newString - to be inserted
buffer - string to have the replacement done on it
Returns:
string after having all of the replacement done.

stringByReplacingFirstOccurrenceOfStringWithString

public static java.lang.String stringByReplacingFirstOccurrenceOfStringWithString(java.lang.String sourceString,
                                                                                  java.lang.String stringToReplace,
                                                                                  java.lang.String replacementString)
Replaces the first occurrence of a string with another string in a string.

Parameters:
sourceString - string to use on which to perform the replacement
stringToReplace - string to replace in sourceString if it exists.
replacementString - the string with which to replace stringToReplace.
Returns:
sourceString with stringToReplace replaced with replacementString if it existed in sourceString. otherwise, sourceString is returned.

escapeSpace

public static java.lang.String escapeSpace(java.lang.String aString)
Removes the spaces in a given String

Returns:
string removing all spaces in it.

toLowerCase

public static java.lang.String toLowerCase(java.lang.String str)
This method runs about 20 times faster than java.lang.String.toLowerCase (and doesn't waste any storage when the result is equal to the input). Warning: Don't use this method when your default locale is Turkey. java.lang.String.toLowerCase is slow because (a) it uses a StringBuffer (which has synchronized methods), (b) it initializes the StringBuffer to the default size, and (c) it gets the default locale every time to test for name equal to "tr".

See Also:
tolower
Author:
Peter Norvig

stringWithNtimesString

public static java.lang.String stringWithNtimesString(int n,
                                                      java.lang.String s)
String multiplication.

Parameters:
n - the number of times to concatinate a given string
s - string to be multipled
Returns:
multiplied string

numberOfOccurrencesOfCharInString

public static int numberOfOccurrencesOfCharInString(char c,
                                                    java.lang.String s)
Counts the number of occurrences of a particular char in a given string.

Parameters:
c - char to count in string
s - string to look for specified char in.
Returns:
number of occurences of a char in the string

stringIsNullOrEmpty

public static boolean stringIsNullOrEmpty(java.lang.String s)
Simple test if the string is either null or equal to "".

Parameters:
s - string to test
Returns:
result of the above test

nullForEmptyString

public static java.lang.String nullForEmptyString(java.lang.String s)
Simple utility method that will return null if the string passed in is equal to "" otherwise it will return the passed in string.

Parameters:
s - string to test
Returns:
null if the string is "" else the string.

emptyStringForNull

public static java.lang.String emptyStringForNull(java.lang.String s)
Simple utility method that will return the string "" if the string passed in is null otherwise it will return the passed in string.

Parameters:
s - string to test
Returns:
the empty string if the string is null, else the string

escapeNonXMLChars

public static java.lang.String escapeNonXMLChars(java.lang.String str)

unescapeEntities

public static java.lang.String unescapeEntities(java.lang.String string,
                                                java.util.Map<java.lang.String,java.lang.String> map)
Util to unescape entities. Entities not found in the set will be left intact.

Parameters:
string - string to unescape
map - map of entities
Returns:
unescaped string

escapePCData

public static java.lang.String escapePCData(java.lang.String pcdata)
Escapes the given PCDATA string as CDATA.

Parameters:
pcdata - The string to escape
Returns:
the escaped string

escapeNonBasicLatinChars

public static java.lang.String escapeNonBasicLatinChars(char c)

escapeNonBasicLatinChars

public static java.lang.String escapeNonBasicLatinChars(java.lang.String str)

escapeJavascriptApostrophes

public static java.lang.String escapeJavascriptApostrophes(java.lang.String sourceString)
Escapes the apostrophes in a Javascript string with a backslash.

Parameters:
sourceString - the source string to escape
Returns:
the escaped javascript string

escape

public static java.lang.String escape(char[] _escapeChars,
                                      char _escapeWith,
                                      java.lang.String _sourceString)
Escapes the given characters with the given escape character in _sourceString. This implementation is specifically designed for large strings. In the event that no characters are escaped, the original string will be returned with no new object creation. A null _sourceString will return null. Example: sourceString = Mike's, escape chars = ', escape with = \, returns Mike\'s

Parameters:
_escapeChars - the list of characters to escape
_escapeWith - the escape character to use
_sourceString - the string to escape the characters in.
Returns:
the escaped string

toHexString

public static java.lang.String toHexString(char c)

toHexString

public static java.lang.String toHexString(java.lang.String str)

byteArrayToHexString

public static java.lang.String byteArrayToHexString(byte[] block)
Converts a byte array to hex string.

Parameters:
block - byte array
Returns:
hex string

hexStringToByteArray

public static byte[] hexStringToByteArray(java.lang.String hexString)
Converts a even-length, hex-encoded String to a byte array.

Parameters:
hexString -

removeExtraDotsFromVersionString

public static java.lang.String removeExtraDotsFromVersionString(java.lang.String version)
Cleans up the given version string by removing extra dots(.), for example, 5.1.3 becomes 5.13, so that the string can be converted to a double or BigDecimal type easily.

Parameters:
version - string
Returns:
cleaned-up string that only contains the first dot(.) as the floating point indicator.

capitalize

public static java.lang.String capitalize(java.lang.String value)
Capitalizes a given string.

Parameters:
value - to be capitalized
Returns:
capitalized string

uncapitalize

public static java.lang.String uncapitalize(java.lang.String value)
Uncapitalizes a given string.

Parameters:
value - to be uncapitalized
Returns:
capitalized string

capitalizeAllWords

public static java.lang.String capitalizeAllWords(java.lang.String value)
Capitalizes all the strings in a given string.

Parameters:
value - to be capitalized
Returns:
capitalized string

underscoreToCamelCase

public static java.lang.String underscoreToCamelCase(java.lang.String underscoreString,
                                                     boolean capitalize)
Converts this_is_a_test to ThisIsATest

Parameters:
underscoreString - the string_with_underscores
capitalize - if true, the first letter is capitalized
Returns:
the StringWithoutUnderscores

camelCaseToUnderscore

public static java.lang.String camelCaseToUnderscore(java.lang.String camelString,
                                                     boolean lowercase)
Converts ThisIsATest to this_is_a_test

Parameters:
camelString - the StringWithCaps
Returns:
the string_with_underscores

stringEqualsString

public static boolean stringEqualsString(java.lang.String s1,
                                         java.lang.String s2)

caseInsensitiveStartsWith

public static boolean caseInsensitiveStartsWith(java.lang.String stringToSearch,
                                                java.lang.String prefix)
Tests if the string starts with the specified prefix ignoring case. This method is optimized so that it only converts the relevant substring of stringToSearch to lowercase before comparing it to the lowercase version of prefix.

Parameters:
stringToSearch - string to check
prefix - prefix to look for
Returns:
true if stringToSearch case-insensitively starts with prefix

caseInsensitiveStartsWith

public static boolean caseInsensitiveStartsWith(java.lang.String stringToSearch,
                                                java.lang.String prefix,
                                                int toffset)
Tests if the string starts with the specified prefix starting at the specified index ignoring case. This method is optimized so that it only converts the relevant substring of stringToSearch to lowercase before comparing it to the lowercase version of prefix.

Parameters:
stringToSearch - string to check
prefix - prefix to look for
toffset - starting offset to perform the search
Returns:
true if stringToSearch case-insensitively starts with prefix starting at toffset

stringByTruncatingStringToByteLengthInEncoding

public static java.lang.String stringByTruncatingStringToByteLengthInEncoding(java.lang.String inputString,
                                                                              int byteLength,
                                                                              java.lang.String encoding)
This method takes a string and returns a string which is the first string such that the result byte length in the specified encoding does not exceed the byte limit. This tends to be an issue with UTF-8 and Japanese characters because they're double- or triple-byte in UTF-8 and you need to be careful not to split in the middle of a multi-byte sequence.

This method is optimized for the UTF-8 case. If encoding is either "UTF-8" or "UTF8", the optimized case will kick in.

Parameters:
inputString - string to truncate
byteLength - maximum byte length
encoding - encoding to use
Returns:
string truncated appropriately.

isDigitsOnly

public static boolean isDigitsOnly(java.lang.String aString)
checks if the specified String contains only digits.

Parameters:
aString - the string to check
Returns:
true if the string contains only digits, false otherwise

isLettersOnly

public static boolean isLettersOnly(java.lang.String aString)
checks if the specified String contains only Letters.

Parameters:
aString - the string to check
Returns:
true if the string contains only Letters, false otherwise

stringContainsSpecialRegexCharacters

public static boolean stringContainsSpecialRegexCharacters(java.lang.String s)
checks if the String contains a character that has a special meaning in regex. This could used to ensure that username and passwords have no such characters.

Parameters:
s - the string to check
Returns:
true if s contains one or multiple characters that have special meanings in regex.

stringFromURL

public static java.lang.String stringFromURL(java.net.URL url)
                                      throws java.io.IOException
Returns a string from the contents of the given URL.

Parameters:
url - the URL to read from
Returns:
the string that was read
Throws:
java.io.IOException - if the connection fails

stringFromURL

public static java.lang.String stringFromURL(java.net.URL url,
                                             java.lang.String encoding)
                                      throws java.io.IOException
Returns a string from the contents of the given URL.

Parameters:
url - the URL to read from
encoding - the string encoding to read with
Returns:
the string that was read
Throws:
java.io.IOException - if the connection fails

stringFromInputStream

public static java.lang.String stringFromInputStream(java.io.InputStream in)
                                              throws java.io.IOException
Returns a string from the input stream using the default encoding.

Parameters:
in - stream to read
Returns:
string representation of the stream.
Throws:
java.io.IOException

stringFromInputStream

public static java.lang.String stringFromInputStream(java.io.InputStream in,
                                                     java.lang.String encoding)
                                              throws java.io.IOException
Returns a string from the input stream using the default encoding.

Parameters:
in - stream to read
encoding - to be used, null will use the default
Returns:
string representation of the stream.
Throws:
java.io.IOException

toString

public static java.lang.String toString(java.lang.Object[] array,
                                        java.lang.String separator)
Returns a String by invoking toString() on each object from the array. After each toString() call the separator is appended to the buffer

Parameters:
array - an object array from which to get a nice String representation
separator - a separator which is displayed between the objects toString() value
Returns:
a string representation from the array

dumpObject

public static java.lang.String dumpObject(java.lang.Object object)
creates a readable debug string for some data types (dicts, arrays, adaptorOperations, databaseOperations)


containsAnyCharacter

public static boolean containsAnyCharacter(java.lang.String source,
                                           java.lang.String characters)
Checks if any of the characters specified in characters is contained in the string specified by source.

Parameters:
source - the String which might contain characters
characters - the characters to check
Returns:
true if any character from characters is in source, false otherwise

removeExceptCharacters

public static java.lang.String removeExceptCharacters(java.lang.String source,
                                                      java.lang.String characters)
removes any character which is not in characters from the source string

Parameters:
source - the string which will be modified
characters - the characters that are allowed to be in source
Returns:
a new string only with characters from the characters argument

removeCharacters

public static java.lang.String removeCharacters(java.lang.String source,
                                                java.lang.String characters)
removes any character which is in characters from the source string

Parameters:
source - the string which will be modified
characters - the characters that are not allowed to be in source
Returns:
a new string without any characters from the characters argument

quicksilverContains

public static boolean quicksilverContains(java.lang.String _str,
                                          java.lang.String _searchString)
Matches strings like Quicksilver (NullPointerException is matched by "NPE"). The rule is basically just that all the letters of the search string must appear in the original string in the same order as the search string, but they are not required to be contiguous or case-matched.

Parameters:
_str - the string to search in
_searchString - the search string to look for
Returns:
whether or not _str contains _searchString

md5

public static byte[] md5(java.lang.String str,
                         java.lang.String encoding)
Generate an MD5 hash from a String.

Parameters:
str - the string to hash
encoding - MD5 operates on byte arrays, so we need to know the encoding to getBytes as
Returns:
the MD5 sum of the bytes
Throws:
java.io.IOException

md5Hex

public static java.lang.String md5Hex(java.lang.String str,
                                      java.lang.String encoding)
Generate an MD5 hash as hex from a String.

Parameters:
str - the string to hash
encoding - MD5 operates on byte arrays, so we need to know the encoding to getBytes as
Returns:
the MD5 sum of the bytes in a hex string
Throws:
java.io.IOException

matchCase

public static java.lang.String matchCase(java.lang.String originalString,
                                         java.lang.String newString)
Returns a string case-matched against the original string. For instance, if originalString is "Mike" and newString is "john", this returns "John". If originalString is "HTTP" and newString is "something", this returns "SOMETHING".

Parameters:
originalString - the original string to analyze the case of
newString - the new string
Returns:
the case-matched variant of newString

indent

public static void indent(java.io.PrintWriter writer,
                          int level)

indent

public static void indent(java.lang.StringBuffer sb,
                          int level)

getSimpleClassName

public static java.lang.String getSimpleClassName(java.lang.Class clazz)
"Borrowed" from 1.5's Class.getSimpleClassName


stringFromDictionary

public static java.lang.String stringFromDictionary(com.webobjects.foundation.NSDictionary dict)
Same as NSPropertySerialization except it sorts on keys first.

Parameters:
dict -

regionMatches

public static boolean regionMatches(java.lang.StringBuffer str,
                                    int toffset,
                                    java.lang.String other,
                                    int ooffset,
                                    int len)
It's ridiculous that StringBuffer doesn't have a .regionMatches like String. This is stolen from String and re-implemented on top of StringBuffer. It's slightly slower than String's because we have to call charAt instead of just accessing the underlying array, but so be it.

Parameters:
str - the StringBuffer to compare a region of
toffset - the starting offset of the sub-region in this string.
other - the string argument.
ooffset - the starting offset of the sub-region in the string argument.
len - the number of characters to compare.
Returns:
true if the specified sub-region of this string exactly matches the specified sub-region of the string argument; false otherwise.

safeIdentifierName

public static java.lang.String safeIdentifierName(java.lang.String source,
                                                  java.lang.String prefix,
                                                  char replacement)
Converts source to be suitable for use as an identifier in JavaScript. prefix is prefixed to source if the first character of source is not suitable to start an identifier (e.g. a number). Any characters in source that are not allowed in an identifier are replaced with replacement.

Parameters:
source - String to make into a identifier name
prefix - String to prefix source with to make it a valid identifier name
replacement - character to use to replace characters in source that are no allowed in an identifier name
Returns:
source converted to a name suitable for use as an identifier in JavaScript
See Also:
Character.isJavaIdentifierStart(char), Character.isJavaIdentifierPart(char)

safeIdentifierName

public static java.lang.String safeIdentifierName(java.lang.String source,
                                                  java.lang.String prefix)
Convenience method to call safeIdentifierName(source, prefix, '_')

Parameters:
source - String to make into a identifier name
prefix - String to prefix source with to make it a valid identifier name
Returns:
source converted to a name suitable for use as an identifier in JavaScript
See Also:
safeIdentifierName(String, String, char)

safeIdentifierName

public static java.lang.String safeIdentifierName(java.lang.String source)
Convenience method to call safeIdentifierName(source, "_", '_')

Parameters:
source - String to make into a identifier name
Returns:
source converted to a name suitable for use as an identifier in JavaScript
See Also:
safeIdentifierName(String, String, char)

urlEncode

public static java.lang.String urlEncode(java.lang.String string)
Utility to encode an URL without the try/catch. Throws an NSForwardException in the unlikely case that ERXMessageEncoding.defaultEncoding() can't be found.

Parameters:
string -

urlDecode

public static java.lang.String urlDecode(java.lang.String string)
Utility to decode an URL without the try/catch. Throws an NSForwardException in the unlikely case that ERXMessageEncoding.defaultEncoding() can't be found.

Parameters:
string -

toUTF8Bytes

public static byte[] toUTF8Bytes(java.lang.String string)
Utility to convert to UTF-8 bytes without the try/catch. Throws an NSForwardException in the unlikely case that your encoding can't be found.

Parameters:
string - string to convert

toBytes

public static byte[] toBytes(java.lang.String string,
                             java.lang.String encoding)
Utility to convert to bytes without the try/catch. Throws an NSForwardException in the unlikely case that your encoding can't be found.

Parameters:
string - string to convert
encoding -

fromUTF8Bytes

public static java.lang.String fromUTF8Bytes(byte[] bytes)
Utility to convert from UTF-8 bytes without the try/catch. Throws an NSForwardException in the unlikely case that your encoding can't be found.

Parameters:
bytes - string to convert

fromBytes

public static java.lang.String fromBytes(byte[] bytes,
                                         java.lang.String encoding)
Utility to convert from bytes without the try/catch. Throws an NSForwardException in the unlikely case that your encoding can't be found.

Parameters:
bytes - string to convert
encoding -

rightPad

public static java.lang.String rightPad(java.lang.String string,
                                        char padChar,
                                        int paddedLength)
Pads a string to the specified number of chars by adding the the given pad char on the right side. If the string is longer than paddedLength, it is returned unchanged.

Parameters:
string - the string to pad
padChar - the character to pad with
paddedLength - the length to pad to
Returns:
the padded string

leftPad

public static java.lang.String leftPad(java.lang.String string,
                                       char padChar,
                                       int paddedLength)
Pads a string to the specified number of chars by adding the the given pad char on the left side. If the string is longer than paddedLength, it is returned unchanged.

Parameters:
string - the string to pad
padChar - the character to pad with
paddedLength - the length to pad to
Returns:
the padded string

insertString

public static java.lang.String insertString(java.lang.String destinationString,
                                            java.lang.String contentToInsert,
                                            int insertOffset)
Inserts the a string into a nother string at a particular offset.

Parameters:
destinationString - the string to insert into
contentToInsert - the string to insert
insertOffset - the offset in destinationString to insert
Returns:
the resulting string

trimString

public static java.lang.String trimString(java.lang.String s)
Null-safe wrapper for java.lang.String.trim

Parameters:
s - string to trim
Returns:
trimmed string or null if s was null

excelSafeCsvString

public static java.lang.String excelSafeCsvString(java.lang.String s)
Removes line breaks and quotes the string if neccessary

Parameters:
s -
Returns:
the string in Excel save CSV format

unquote

public static java.lang.String unquote(java.lang.String s,
                                       java.lang.String quoteSymbol)
Remove the quote symbols from the given string

Parameters:
s -
quoteSymbol -
Returns:
the string unquoted

quote

public static java.lang.String quote(java.lang.String s,
                                     java.lang.String quoteSymbol)
Quote the given string with the provided quote symbols

Parameters:
s - the string to quote
quoteSymbol - - the quote symbol
Returns:
quoted string

stringByAppendingCSSClass

public static java.lang.String stringByAppendingCSSClass(java.lang.String originalString,
                                                         java.lang.String cssClass)
Appends a CSS class to an existing (possibly null) CSS class string.

Parameters:
originalString - the original string
cssClass - the new CSS class to append
Returns:
the CSS classes appended together (with a space between if originalString is non-empty)

stripHtml

public static java.lang.String stripHtml(java.lang.String str)
Removes HTML characters from the given string.

Parameters:
str - the string to remove HTML from
Returns:
the string without HTML characters in it

attributeValueFromString

public static java.lang.Object attributeValueFromString(com.webobjects.eoaccess.EOAttribute attr,
                                                        java.lang.String strVal,
                                                        java.lang.String encoding,
                                                        java.text.Format formatter)
Attempts to convert string values for attributes into the appropriate value class for the attribute. If the method is unable to convert the value, it returns null.

Parameters:
attr - The attribute for the value in question.
strVal - The string value to be coerced.
encoding - The encoding used if the attribute value class is custom and the factory method does not accept a string.
formatter - The formatter used if the value class is NSTimestamp.
Returns:
The coerced object value or null.

attributeNumberValueFromString

public static java.lang.Number attributeNumberValueFromString(com.webobjects.eoaccess.EOAttribute attr,
                                                              java.lang.String strVal)
Attempts to convert string values for attributes into the appropriate value class for the attribute. If the method is unable to convert the value, it returns null.

Parameters:
attr - The attribute for the value in question.
strVal - The string value to be coerced.
Returns:
The coerced object value or null.

attributeCustomValueFromString

public static java.lang.Object attributeCustomValueFromString(com.webobjects.eoaccess.EOAttribute attr,
                                                              java.lang.String strVal,
                                                              java.lang.String encoding)
Attempts to convert string values for attributes into the appropriate value class for the attribute. If the method is unable to convert the value, it returns null.

Parameters:
attr - The attribute for the value in question.
strVal - The string value to be coerced.
encoding - The encoding used if the attribute value class is custom and the factory method does not accept a string.
Returns:
The coerced object value or null.

isValueInRange

public static boolean isValueInRange(int value,
                                     java.lang.String rangeString)
Returns whether the given value falls in a range defined by the given string, which is in the format "1-5,100,500,800-1000".

Parameters:
value - the value to check for
rangeString - the range string to parse
Returns:
whether or not the value falls within the given ranges

maskStringWithCharacter

public static java.lang.String maskStringWithCharacter(java.lang.String arg,
                                                       char mask,
                                                       int beginIndex,
                                                       int endIndex)
Masks a given string with a single character in the substring specified by the begin and end indexes. Negative indexes count from the end of the string beginning with -1. For example, maskStringWithCharacter("Visa 4111111111111111", '*', 5, -4); will result in a string value of "Visa ************1111"

Parameters:
arg - The string value to mask
mask - The character mask
beginIndex - The string index where masking begins. Negative numbers count down from the end of the string.
endIndex - The index where masking ends. Negative numbers count down from the end of the string
Returns:
The masked string result

Last updated: Tue, Feb 21, 2017 • 05:45 PM CET

Copyright © 2002 – 2007 Project Wonder.